text:
Q: Python: Counting while mouse Down, stop when mouse Up I'm trying to make a python script that starts counting from 0 when the mouse button is pressed. My idea is to use pyHook to go into a function when left mouse button is pressed and exit the function when left mouse is released. I'm pretty new to python so sorry for bad explanations.
Some pseudocode:
import pyHook
import pythoncom

def termin():
    return None
def counter(tell):
    a=0
    while True:
        print a
        a+=1
        hm = pyHook.HookManager()
        hm.SubscribeMouseLeftUp(termin)

hm = pyHook.HookManager()
hm.SubscribeMouseLeftDown(counter)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()

This code is my general idea, however I don't think it will work because SubscribeMouseLeftUp happens at a discrete time. What i'm looking for is maybe running the counter function and termin function in some kind of threading or multiprocessing module and use conditions in one function to terminate the other running function. But I'm not sure how to make this work.
Okay, so I tried this script after willpower's comment:
import pyHook,time,pythoncom

def counter(go):
    for a in range(5):
        time.sleep(1)
        print a
    return True

hm=pyHook.HookManager()
hm.SubscribeMouseLeftDown(counter)
hm.HookMouse()
pythoncom.PumpMessages()
hm.UnhookMouse()

The accepted answer from willpower2727 is the best solution I've seen so far. Before he posted his solution using threading I made the following code:
from multiprocessing import Process,Queue
import pyHook
import time
import pythoncom
import ctypes

def counter(tellerstate,q):
    while True:
        a=0
        tellerstate=q.get()
        if tellerstate==1:
            while True:
                a+=1
                print a
                tellerstate=q.get()
                if tellerstate==0:
                    break
        time.sleep(0.1)

def mousesignal(q):
    def OnDown(go):
        tellstate=1
        q.put(tellstate)
        return None

    def OnUp(go):
        tellstate=0
        q.put(tellstate)
        return None

    def terminate(go):
        if chr(go.Ascii)=='q' or chr(go.Ascii)=='Q':
            ctypes.windll.user32.PostQuitMessage(0)
            hm.UnhookKeyboard()
            hm.UnhookMouse()
            q.close()
            q.join_thread()
            process_counter.join()
            process_mousesignal.join()
        return None

    hm=pyHook.HookManager()
    hm.KeyDown = terminate
    hm.MouseLeftDown = OnDown
    hm.MouseLeftUp = OnUp
    hm.HookMouse()
    hm.HookKeyboard()
    pythoncom.PumpMessages()

if __name__ == '__main__':
    tellerstate=0
    q=Queue()
    process_counter = Process(target=counter,args=(tellerstate,q))
    process_mousesignal = Process(target=mousesignal,args=(q,))
    process_mousesignal.start()
    process_counter.start()

My expected behaviour of this code is that the counter and mousesignal functions should run as separate processes. In the mousesignal process I'm putting either a 0 or 1 to a Queue based on mouse input. The counter function runs continuously and reads the Queue and uses if statements to enter and quit the loop in this function. This code doesn't work at all, but I can't understand why.

A: Based on the example you provided it looks like you want to count the number of seconds the mouse button is down? You can do this without using multiple threads. The following example will print the amount of time the mouse button was pressed down for:
import pyHook
import time
import pythoncom

global starttime
starttime = time.time()
global endtime
endtime = time.time()

def OnDown(go):
    global starttime
    starttime = time.time()
    return True

def OnUp(go):
    global starttime
    global endtime
    endtime = time.time()
    etime = endtime-starttime
    print(etime)
    return True

hm = pyHook.HookManager()
hm.MouseLeftDown = OnDown
hm.MouseLeftUp = OnUp
hm.HookMouse()
pythoncom.PumpMessages()

A: Ok I have an example of using threading to do something while the mouse button is held down. This example breaks/gets stuck if the user double-clicks the mouse very quickly. It uses a lock and a thread that only executes certain code when the lock is released (triggered by mouse down).
import time
import threading
import pyHook
import pythoncom

def DoThis(Cond):
    while True:
        with Cond: #calling "with" automatically calls acquire() on the lock
            print(time.time())
    print('stopping...')

global Cond
Cond = threading.Lock()#create a threading lock
Cond.acquire() #give the lock to the main thread

global t1
t1 = threading.Thread(target=DoThis,args=(Cond, )) #initialize the thread that does stuff while mouse button is down
t1.start() #start the thread, it won't do anything until mouse button is down

def OnDown(go):
    global Cond
    Cond.release() #allow the thread to acquire the lock
    print('Lock released')
    return True

def OnUp(go):
    global Cond
    Cond.acquire() #take the lock away from the thread
    print('Lock acquired')
    return True

hm = pyHook.HookManager()
hm.MouseLeftDown = OnDown
hm.MouseLeftUp = OnUp
hm.HookMouse()
pythoncom.PumpMessages()

The challenge with using threads is that they can only be started once so you couldn't call thread.start() everytime the mouse is pressed, it would only work the first time. By allowing the thread to stay alive but not do anything (except constantly check if it should) enables the possibility to only execute some code when the mouse is down. There are some more sophisticated ways to do this that might improve the processing load on the computer (maybe using a thread condition instead of a regular lock) but this is the general idea I had.


text:
Q: How to change all spaces on span elements I have html:

Text1 Text2

        Text2

Text3

        Text4 Text5

I want to chage all spaces (only in text nodes) in all elements on .. The final html should looks like this:

Text1.Text2

        Text2

Text3

        Text4.Text5

How can i do it with jquery or without it?

A: Here is one possible jQuery solution:
$('div *').contents().filter(function() {
    // get only non-empty text nodes
    return this.nodeType === 3
        && $.trim(this.nodeValue).length;
}).replaceWith(function() {
    // replace all spaces with the corresponding markup
    return $.trim(this.nodeValue).replace(/\s+/g, '.');
});

DEMO: http://jsfiddle.net/9NL98/

A: try this..
$('div').contents().each(function() {
    console.log(this);
    this.data = this.data.replace(/ /g, '.');
});

redpajama_set_name: RedPajamaStackExchange


text:
Q: Qt 4.8 Cross Compile for Embedded Linux using Linaro Toolchain from Windows I am trying to use the 2012.06 version of the Linaro Toolchain Windows Binary ( https://launchpad.net/linaro-toolchain-binaries/trunk/ ) to cross-compile the Qt 4.8 source to target an embedded Linux ARM Cortex-8 board. I was able to do this with the CodeSourcery toolchain mentioned in this post --> http://c2143.blogspot.com/?view=classic. But the target board software was built with the Linaro toolchain and so I am working towards that end.
I have patched the mkspec mentioned in the post above to look like this:
#
# qmake configuration for building with arm-none-linux-gnueabi-g++
#
include(../common/unix.conf)
include(../common/gcc-base-unix.conf)
include(../common/g++-unix.conf)
include(../common/qws.conf)

MAKEFILE_GENERATOR      = MINGW
CONFIG                 += no_import_libs no_generated_target_info
# modifications to g++.conf
QMAKE_CC                = arm-linux-gnueabihf-gcc
QMAKE_CXX               = arm-linux-gnueabihf-g++
QMAKE_LINK              = arm-linux-gnueabihf-g++
QMAKE_LINK_SHLIB        = arm-linux-gnueabihf-g++
QMAKE_LIB               = arm-linux-gnueabihf-ar
QMAKE_AR                = arm-linux-gnueabihf-ar cqs
QMAKE_OBJCOPY           = arm-linux-gnueabihf-objcopy
QMAKE_STRIP             = arm-linux-gnueabihf-strip
QMAKE_RUN_CC            = $(CC) -c $(CFLAGS) $(INCPATH) -o $obj $src
QMAKE_RUN_CC_IMP        = $(CC) -c $(CFLAGS) $(INCPATH) -o $@ $<
QMAKE_RUN_CXX           = $(CXX) -c $(CXXFLAGS) $(INCPATH) -o $obj $src
QMAKE_RUN_CXX_IMP       = $(CXX) -c $(CXXFLAGS) $(INCPATH) -o $@ $<
QMAKE_INCDIR            =
QMAKE_INCDIR_QT         = $$[QT_INSTALL_HEADERS]
QMAKE_LIBDIR_QT         = $$[QT_INSTALL_LIBS]
QMAKE_MOC               = $$[QT_INSTALL_BINS]\\moc.exe
QMAKE_UIC               = $$[QT_INSTALL_BINS]\\uic.exe
QMAKE_IDC               = $$[QT_INSTALL_BINS]\\idc.exe
QMAKE_COPY              = copy /y
QMAKE_COPY_DIR          = xcopy /s /q /y /i
QMAKE_MOVE              = move
QMAKE_DEL_FILE          = del
QMAKE_MKDIR             = mkdir
QMAKE_DEL_DIR           = rmdir
QMAKE_CHK_DIR_EXISTS    = if not exist
QMAKE_IDL               = midl
QMAKE_ZIP               = zip -r -9
CODESOURCERY_ARM_CFLAGS = -march=armv7-a -mtune=cortex-a8 -mthumb -mfpu=vfp -mfloat-abi=softfp -Wa,-mimplicit-it=thumb -marm -mthumb-interwork
#modifications to gcc-base.conf
QMAKE_CFLAGS           += $$CODESOURCERY_ARM_CFLAGS
QMAKE_CXXFLAGS         += $$CODESOURCERY_ARM_CFLAGS
QMAKE_LIBS             += -lrt -lpthread -ldl
QMAKE_LFLAGS           += $${QMAKE_LFLAGS_RPATH}$$[QT_INSTALL_LIBS]
!isEmpty(TARGET_QTDIR) {
    QMAKE_LFLAGS       += $${QMAKE_LFLAGS_RPATH}$${TARGET_QTDIR}/lib
}
!isEmpty(TARGET_SYSROOT) {
    QMAKE_LFLAGS       += $${QMAKE_LFLAGS_RPATH}$${TARGET_SYSROOT}/lib:$${TARGET_SYSROOT}/usr/lib
    QMAKE_LFLAGS       += -Wl,--dynamic-linker=$${TARGET_SYSROOT}/lib/ld-linux.so.3
}
load(qt_config)

When I run mingw32-make on the top level Makefile in order to produce the Qt libraries for the ARM board it compiles for a while but inevitably errors with:
collect2.exe: error: ld returned 1 exit status
mingw32-make[1]: *** [..\..\lib\libQtCore.so] Error 1
mingw32-make[1]: Leaving directory `C:/Users/user/Desktop/qt_creator_toolchain...
mingw32-make: *** [sub-corelib-make_default-ordered] Error 2

This error happens after many complaints like:
*.so uses VFP register arguments, *obj does not

I've researched that error and have tried to pass each of the following options to my mkespec and rebuild with the same error:
-mfloat-abi=softfp
-mfloat-abi=soft
-mfloat-abi=hard

I am clearly not understanding why the '-mfloat-abi=softfp' option works fine with the CodeSourcery Windows toolchain but not Linaro. The rest of the compiler flags are shown in the mkspec above.
Does anybody have any insight or thoughts on how to make this work? Thanks in advance.
UPDATE:
It turns out if I modify my C_FLAGS in the mkspec from this:
-march=armv7-a -mtune=cortex-a8 -mthumb -mfpu=vfp -mfloat-abi=softfp -Wa,-mimplicit-it=thumb -marm -mthumb-interwork

to this:
-march=armv7-a -mtune=cortex-a8 -mthumb -mfpu=neon -mfloat-abi=hard -Wa,-mimplicit-it=thumb -marm -mthumb-interwork

Then I can finally successfully compile Qt. How will this affect my performance / or ability to run a Qt App on the Board? Why can't I do softfp with Linaro but I can with CodeSourcery?

A: -
Hi, phil999,
Cortex-A Series Programmer's Guide Version: 2.0
at http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.den0013a/index.html
From the document, it is known that
-mfpu=vfp specifies that the target has VFP hardware. (As does specifying the option  -mfpu=neon.)
So, according to your C_FLAGS, option "-mfpu=vfp" equates with option"-mfpu=neon",
the difference in Linaro may lie between option "-mfloat-abi=softfp" and option "-mfloat-abi=hard".
From the errors provided,
This error happens after many complaints like:
*.so uses VFP register arguments, *obj does not

it seems that lib files are compiled with "-mfloat-abi=hard", which is recognized by "uses VFP register arguments".
'Cause if option "-mfloat-abi=softfp" is used for compiling lib files, floating-point arguments will be passed in R0-R3 and in stack space;
Option "-mfloat-abi=hard" must be spicified, once passing floating-point arguments in VFP or NEON floating-point registers.
So, in order to link with those lib files compiled with "-mfloat-abi=hard", you should also compile QT with "-mfloat-abi=hard", or, there will be some similar complaints as you encountered.
Besides, from the readme in gcc-linaro-arm-linux-gnueabihf-2012.06-20120625_win32\gcc-linaro-arm-linux-gnueabihf-2012.06-20120625_win32\share\doc\gcc-linaro-arm-linux-gnueabihf
Some points in readme are as follows
Target compatibility

The arm-linux-gnueabihf version targets the Linaro Evaluation Build
12.05 flavour of Ubuntu 12.04 "Precise Pangolin".  The default
configuration is:

*

*Runs on all Cortex-A profile devices

*Tuned for the Cortex-A9

*Thumb-2

*'hard float' calling convention

*Uses the VFPv3-D16 FPU

*Multiarch and multilib enabled

*EGLIBC 2.15

*A GCC 4.7 series libgcc and libstdc++

To use softfp or hard
Two points:
1. Using float-abi with "softfp", it is backward compatibility with older softfp ABI codes.
2. with "-mfloat-abi=hard", it is more efficient, but is not backward compatibility with softfp abi codes.
More details will be found in "18.2 VFP support in GCC" and "15.1.1 VFP and NEON register usage" in Cortex-A Series Programmer's Guide Version: 2.0 listed at the beginning.
Thanks.


text:
Q: Preserve user-specified-sorting during reactable refresh in shiny I am making a shiny app with a reactable where the user can choose how to sort the table. The trouble is when the table refreshes the sorting goes back to the default sorting specified when the table is created. I want to be able to have the table refresh to the sorting specifications the user has chosen.
I know this is possible by using a selectInput or pickerInput or some other input along those lines which can feed to the defaultSorted argument in the reactable but I am looking for something a little bit more organic without the need of an external input. Currently the getReactableState only provides page size/number and selection references.
Below is a toy example where if the user sorts by the first 2 columns and then clicks toggle, the table refreshes and goes back to its original sort state.
library(shiny)
library(reactable)

ui <- fluidPage(
  actionButton("toggle", "Toggle"),
  reactableOutput("table")
)

server <- function(input, output, session){

  df <- eventReactive(input$toggle, {
    mtcars[c(1:2,sample(3:ncol(mtcars), size = 3))]
  })

  output$table <- renderReactable({
    reactable(df(),
              filterable = FALSE,
              sortable = TRUE)
  })

}

shinyApp(ui, server)

A: You could use data argument of updateReactable:

data should have the same columns as the original table data. When updating data, the selected rows, expanded rows, and current page will reset unless explicitly specified. All other state will persist, including sorting, filtering, and grouping state

If you don't use rownames with your real data, this should be OK : sorting order is kept.
If you use rownames, there seems to be an issue with rownames disappearing : this is why I put rownames in the model column below and remove rownames.
library(shiny)
library(reactable)

ui <- fluidPage(
  actionButton("toggle", "Toggle"),
  reactableOutput("table")
)

server <- function(input, output, session){

  ref <- mtcars[c(1:2,sample(3:ncol(mtcars), size = 3))]
  ref$model <- rownames(ref)
  rownames(ref) <- NULL
  init <- ref[0,]

  output$table <- renderReactable({
    reactable(init,
              filterable = FALSE,
              sortable = TRUE)
  })

  df <- eventReactive(input$toggle, {
   ref[sample(1:nrow(ref),20),]
  })

  observeEvent(input$toggle, {
    updateReactable("table", data = df())
  })

}


text:
Q: How to get (all) Sharepoint List data to display in infopath SharePoint List Form I really hope you can help out! I'm so close to completing my project! I've learned so much just by trial and error, but I'm at a road block.
I've established a main data connection to connect my form to a SP List that displays employee ID, Title, Last Name, Department, and Workcenter.
I created a drop down and connected it to the workcenter data field.
At this point I would like to have all entries that are in that specific workcenter display. How do I do that?
Bonus question:
The entire point of this is to create a daily attendance report of all employees. Not a timecard, just a "Who is physically here and who is not." So, how would you go about creating fields that can mark someone as present or absent and then submit that list back to a SharePoint list?

A: Create a secondary data connection to your list...while creating data connection select get data from SharePoint list, then select all your required columns whichever you want to display in the form. Once data connection creation is done, go to the secondary data connection, and drag and drop the items nodes to form.
We can filter the list items data by applying the filter on the secondary data connection.
See my other answer here on how to filter the SharePoint list items and display them in the form.
How to save the data in SharePoint list?
If you are customizing the SharePoint list using InfoPath form... we don't need to create a secondary data connection to submit the form data back to SharePoint list, the inbuilt main data connection will take care... however, if you want to submit the data to a different list, you need to create another secondary data connection with Submit data (while creating the data connection you will get this option), then on the submit button rule as action select this data connection to submit the data.
How to create a secondary data connection to submit the data in the SharePoint list?

*

*Click on the Manage Data Connection from the right side Fields panel.

*Click on the "Add" button in the "Data Connections" wizard. In the next screen, you will get the below:

Create a new connection to:

*

*Submit data – This is used to submit the InfoPath form data to the
SharePoint list.

*Receive data – This is used to read the data from a SharePoint list (by default, this will be selected).

*Select the "Submit data" radio button

*In the next screen, you will see "Select the source of your data",
select as SharePoint library or list.

*Enter your SharePoint site URL in the "Enter the location of the
SharePoint site" box.

*From the available lists or libraries, select your list.

*Click on the Next button and continue...
For details refer to the below article:
How to auto populate field in InfoPath based on another field


text:
Q: Proof that $\exists U$ a neighborhood and a smooth function $h$ such that $h|_{U \cap S} = f|_U$ In this problem, we have a regular surface $S \subset \mathbb{R^3}$, and we wish to show that for any smooth function $f:S \to \mathbb{R}$ and any point $p \in S$, there exists an open neighborhood $U \subset \mathbb{R^3}$ around $p$ and a smooth function $h:U \to \mathbb{R}$ such that $h|_{U \cap S} = f|_U$.
Coud you give me a hint on how to solve this ? I don't really know how to proceed...


text:
Q: How to find "not a procedure" error (define (comp f g)
  (lambda (x)(f (g x))))

(define (complement f) (cond ((equal? (comp f (lambda (g) g)) #t) #f)
                             ((equal? (comp f (lambda (g) g)) #f) #t)))

((complement odd?)2)

It keeps saying that ((complement odd?)2) is not a procedure. I'm not sure how to fix it.

A: When you run this code you'll see that ((complement odd?) 2) is red in the definitions and you get the following error:
application: not a procedure;
 expected a procedure that can be applied to arguments
  given: #<void>

So that would mean (complement odd?) doesn't return a procedure but the value #<void>. Lets try that:
(complement odd?)
; ==> nothing (aka #<void>)

If you really want to see it use it somewhere:
(list (complement odd?))
; ==> (#<void>) now you see it

That means you are not handling all your possible checks in the cond in complement and I see why.. Have you tried comp?
(comp f (lambda (g) g)) ; ==> #<procedure>

Surely enough the use of comp becomes a procedure. Not strange since the  body has one lambda form that indicates the return would be a procedure. It will never be #t or #f When you don't have an else (default) term for when neither of your predicates became true cond returns an implementation specific defauls value. In Racket this is #<void> which is supressed by the REPL, but in other implementations it can be banana or whatever the implementers want it to be so you should always have a else clause. If you don't think you need it then do (else (error "should never happen")) and you're good to go. (try it)
The consequences in your cond are #t and #f. That means that if your code sould have worked you would have got this error message instead:
application: not a procedure;
 expected a procedure that can be applied to arguments
  given: #t

For each place your return smething that is not a procedure that would be an error since you are using the result as a procedure. You need to change your implementation such that it returns a procedure always.
So, this is the answer to how to find "not a procedure" error. It's not the answer to how to fix your procedure but since this is the simplest procedure in the world I'll add it. You have a procedure comp that takes two procedures and return the composition of the two. eg. if you want add2 you can (define add2 (comp add1 add1)). The complement must be that the false value #f turns #t while all the true values turn #f. not does this so the composition of not and odd? would become the procedure that works the same as even?:
(define (complement f)
  (comp not f)) ; comp returns a procedure always

(define my-even? (complement odd?))
(my-even? 2) ; ==> #t

Since we don't mutate anything you can use substitution method to check what this does:
(my-even? 2)                      ; ==>
((comp not odd?) 2)               ; ==>
(((lambda (x) (not (odd? x))) 2)  ; ==>
(not (odd? 2))                    ; ==>
(not #f)                          ; ==>
#t


text:
Q: backstretch slideshow is not working Can not understand about backstretch.
tried like 5 hours. I am beginner.Can you look at the code and tell
me what is wrong? And can you people tell me about
good simple plugin for slideshow of background img. I need slideshow
inside a division so that i can change it's size and put it anywhere
i like.Tried to find solution by searching google and this website but
failed.
$(".abcd").backstretch(["https://i.imgur.com/LquRrwI.jpg","https://i.imgur.com/zVk2HHq.jpg"] {duration: 10000, fade: 750});

https://codepen.io/roymahdi/pen/OxyWXy/

A: Add a comma , before {duration: 10000, fade: 750}


text:
Q: Set of keys from a map I have a map X and I'm trying to get a set of the keys satisfying a certain condition, something like this:
Map.Keys X
|> Set.filter (fun x -> ...)

...but I cannot find the way to get the keys from F#'s Map collection.

A: Convert your map to sequence of tuples (key,value) first and then map it to a sequence of just keys:
map |> Map.toSeq |> Seq.map fst

FSI sample:
>Map.ofList[(1,"a");(2,"b")] |> Map.toSeq |> Seq.map fst;;
val it : seq<int> = seq [1; 2]

Or alternatively, as ordering of keys likely does not matter you may use more eager method returning the list of all keys. It is also not hard to make it into extension method keys of Microsoft.FSharp.Collections.Map module:
module Map =
    let keys (m: Map<'Key, 'T>) =
        Map.fold (fun keys key _ -> key::keys) [] m

A: In F# 6.0, Map collection has now a Keys property.

OLD ANSWER:
Most readable (and probably most efficient, due to not needing previous conversions to Seq or mapping) answer:
let Keys(map: Map<'K,'V>) =
    seq {
        for KeyValue(key,value) in map do
            yield key
    } |> Set.ofSeq

A: For a set of keys you could just do:
let keys<'k, 'v when 'k : comparison> (map : Map<'k, 'v>) =
    Map.fold (fun s k _ -> Set.add k s) Set.empty map


text:
Q: Lagrangian and Friction How does lagrangian mechanics explain loss of momentum conservation in presence of friction?
My try is this:
The lagrange equation would then include a generalized force term $Q_i$:
$$\frac{d}{dt}\frac{\partial L}{\partial \dot{q_i}} - \frac{\partial L}{\partial q_i} = Q_{i}$$
$$\implies \frac{d}{dt}p_i = Q_i + \frac{\partial L}{\partial q_i}$$
Now how do I show that $Q_i + \frac{\partial L}{\partial q_i}$ is never $0$?
Since $Q_i$ is generalized force,
$$Q_i = \sum_{j}\vec{f_j}\cdot \frac{\partial \vec{r}_j}{\partial q_i}$$


text:
Q: Why is my slideshow above the menu when switching image? I've got a slideshow on my webpage. It switches from images using the following script:

setInterval(function() {
  $('#slideshow > div:first')
    .fadeOut(0)
    .next()
    .fadeIn(1000)
    .end()
    .appendTo('#slideshow');
}, 7000);

However, when the slides are changing, the slideshow is above the dropdown menu until it completely loaded. It then goes behind the menu again. The menu has a z-index of 100, the slideshow has a z-index of 10. If needed, I can give the css of the menu, but that's quite a long list.
Why is the slideshow above the menu when switching?

A: Using this code the slides work fine ...

var myIndex = 0;
carousel();

function carousel() {
    var i;
    var x = document.getElementsByClassName("mySlides");
    for (i = 0; i < x.length; i++) {
       x[i].style.display = "none";
    }
    myIndex++;
    if (myIndex > x.length) {myIndex = 1}
    x[myIndex-1].style.display = "block";
    setTimeout(carousel, 2000); // Change image every 2 seconds
}


text:
Q: Stacking Divs with CSS Im kinda new to CSS have been using tables for my html for years,  Im trying to figure out how I can nest divs or stack them inside the content section of a 3 column layout.  with tables I'd just do a new

but if I float another div into the content line line it will appear parallel or vertically, when I want to appear beneath.  is there another way to do this or am I missing the point of Divs here?
basic example code
        body {
        margin: 0px;
        padding: 0px;
        }
        #header {
        background: #438a48;
        width: 100%;
        }
        #leftcolumn {
        background: #2675a8;
        float: left;
        width: 25%;
        height: 700px;
        }
        #content {
        background: #000;
        float: left;
        width: 75%;
        height: 700px;
        }
        #footer {
        background: #df781c;
        clear: both;
        width: 100%;
        }

The HTML

Header

Left Column

Content

Footer

A: You can just add divs inside the #content div... the nesting will force them to stay inside their parent ... (do not float those inner divs, to make them go one beneath the other..)


text:
Q: How to detect where in a div the click event has occured? I want to detect where in the div with id clickdetectiondiv have i clicked. The code that I am using gives me the position with respect to the top left of the body of the HTML page. I have spent lot of time in figuring out how this could be done but am unable to find the answer.
    One solution i have is to subtract the position of this absolutely positioned div. But not always will I get the position of the div, as the screen sizes may vary. Please tell me an alternate method to do this.
Thanks in advance,

A: You want to use a javascript framework like jquery or mootools, they have functions to get relative position of an element to any other element you want already written in a cross-browser manner. Why reinvent the wheel?

A: If you can use jquery
$('#A').click(function(e) {   //Default mouse Position
              alert(e.pageX+ ' , ' + e.pageY);
       });

A: I suppose this can be solution:
function clicked(event){
    var x = event.x;
    var y = event.y;

    var divClicked = document.getElementById("clickdetectiondiv");

    x -= divClicked.offsetLeft;
    y -= divClicked.offsetTop;
    document.getElementById("outputdiv").innerHTML= "X coords: " + x + ", Y coords: " + y;
}


text:
Q: Bind CommandParameter to SelectedItem of GridView I work an a Windows 8 application which shows a GridView on one page. When ever the user selects an item of this grid and clicks on a button, the next page is loaded with detail information of the selected item.
I am using MVVM for this and have a DelegateCommand from Prims:
public DelegateCommand<Route> ShowRouteDetailsCommand { get; private set; }

This command is initialized inside the constructor:
this.ShowRouteDetailsCommand = new DelegateCommand<Route>(this.ShowRouteDetails);

The navigation is done by Prisms navigation service:
private void ShowRouteDetails(Route route)
{
    this.NavigationService.Navigate(PageNames.RouteDetails, route.Id);
}

The routes are shown inside a GridView:
                    <GridView x:Name="RouteGrid"
                              ItemsSource="{Binding Routes}"
                              SelectionMode="Single">
                        <GridView.ItemTemplate>
                            <DataTemplate> ...

The command is currently added inside the app bar (just for testing):
 <AppBarButton Command="{Binding ShowRouteDetailsCommand}"
                      CommandParameter="{Binding SelectedValue,
                                                 ElementName=RouteGrid, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                      Icon="Forward" />

My problem is, that the parameter of ShowRouteDetails is allways empty. It doesn't even matter if I try GridViews SelectedValue or SelectedItem property.
I know that I could easily add a SelectedRoute property, bind the SelectedItem to it and use it in ShowRouteDetails but this seems dirty to me.

A: Why don't you just create a var in your viewModel and bind it to the SelectedItem of the gridView? In this way, when you run the command, you have only to read the value of that var.
<GridView x:Name="RouteGrid" ItemsSource="{Binding Routes}"
               SelectionMode="Single" SelectedItem="{Binding myVar}">
    <GridView.ItemTemplate>
        <DataTemplate>


text:
Q: How Can I Order in an SQL Statement? I have these tables: Stock, Unit, Location, Category, StockBalance
At StockBalance: there is StockID from Stock, UnitId from Unit, LocationID from Location
I save at StockBalance Table like following
StockBalanceID | StockID | UnitID | LocationID | BalanceQuantity
1              | 1       | 1      | 1          | 20
2              | 1       | 2      | 1          | 30
3              | 1       | 3      | 1          | 40
4              | 2       | 1      | 2          | 20
5              | 2       | 2      | 2          | 30
6              | 2       | 3      | 2          | 40

I would like to show on Classic ASP as :
Group By : CategoryName
  Stock Name                    Quantity                             Location Name
                       Qty | Unit   | Qty | Unit | Qty | Unit
  Stock One |          20  |  One   |  30 | Two  | 40  | Three       | Location One
  Stock Two |          20  |  One   |  30 | Two  | 40  | Three       | Location Two

How can I Select From StockBalance to get like above? How about my edit one?
Please help me !

A: PIVOT is what you want.
First some sample data setup:
create table yourTable (
StockBalanceID int, StockID int, UnitID int, LocationID int, BalanceQuantity int);

insert yourTable
select  1              , 1       , 1      , 1          , 20
union all select  2              , 1       , 2      , 1          , 30
union all select  3              , 1       , 3      , 1          , 40
union all select  4              , 2       , 1      , 2          , 20
union all select  5              , 2       , 2      , 2          , 30
union all select  6              , 2       , 3      , 2          , 40
;

Now to do the work...
select StockID, LocationID,
    sum(case UnitID when 1 then BalanceQuantity end) as [Unit One],
    sum(case UnitID when 2 then BalanceQuantity end) as [Unit Two],
    sum(case UnitID when 3 then BalanceQuantity end) as [Unit Three]
from yourTable
group by StockID, LocationID;

A: Try the following
DECLARE @StockBalances TABLE(
        StockBalanceID INT,
        StockID INT,
        UnitID INT,
        LocationID INT,
        BalanceQuantity FLOAT
)

DECLARE @Stock TABLE(
        StockID INT,
        StockName VARCHAR(10)
)

DECLARE @Unit TABLE(
        UnitID INT,
        UnitName VARCHAR(10)
)

DECLARE @Location TABLE(
        LocationID INT,
        LocationName VARCHAR(10)
)

INSERT INTO @StockBalances SELECT 1,1,1,1,20
INSERT INTO @StockBalances SELECT 2,1,2,1,30
INSERT INTO @StockBalances SELECT 3,1,3,1,40
INSERT INTO @StockBalances SELECT 4,2,1,2,20
INSERT INTO @StockBalances SELECT 5,2,2,2 ,30
INSERT INTO @StockBalances SELECT 6,2,3,2,40

INSERT INTO @Stock SELECT 1, 'Stock 1'
INSERT INTO @Stock SELECT 2, 'Stock 2'

INSERT INTO @Unit SELECT 1, 'Unit 1'
INSERT INTO @Unit SELECT 2, 'Unit 2'
INSERT INTO @Unit SELECT 3, 'Unit 3'

INSERT INTO @Location SELECT 1, 'Location 1'
INSERT INTO @Location SELECT 2, 'Location 2'

SELECT  *
FROM    (
            SELECT  s.StockName,
                    sb.BalanceQuantity,
                    u.UnitName,
                    l.LocationName
            FROM    @StockBalances sb INNER JOIN
                    @Stock s ON sb.StockID = s.StockID INNER JOIN
                    @Unit u ON sb.UnitID = u.UnitID INNER JOIN
                    @Location l ON sb.LocationID = l.LocationID
        ) t
PIVOT   (SUM(BalanceQuantity) FOR UnitName IN ([Unit 1], [Unit 2], [Unit 3])) p


text:
Q: Automatically choose "Try Ubuntu without Installing" after booting from USB Startup Disk I have created a usb bootup stick for 10.10, and reduced the timeout to 0 sec... but after it boots up it shows two options either to install or try ubuntu... I want to avoid this screen and directly go to the tryout mode...
at the first screen at bootup if I press any key,there is an option to select "try Ubuntu without installing",in this case I go to tryout mode directly... I want this behaviour without pressing any key...
any suggestions???
Thanks.

A: I'm not really sure what you want, but if you want it to behave this way you should install Ubuntu on the usb disk rather than installing the Live-CD on it.

A: I don't know if it is a solution but I think it can get close to what you want.
Make a new Ubuntu install and then, without installing anything, put it back on the usb stick using Remastersys (http://en.wikipedia.org/wiki/Remastersys).
Done that you should be able to boot into your Ubuntu from the usb stick without choosing to try or install :)
If Remastersys doesn't do the trick as you want it just a plain install ON the usb stick could work too.

A: Solution!
use LiLi to create your USB key!

A: When you create the USB disk using Unetbootin, there won't be a "Try Ubuntu / Install Ubuntu" screen after booting.
I don't know why this difference exists between Unetbootin and Startup Disk creator, but I just tested this (see my question).
This makes bootup much faster in total.


text:
Q: Some StackExchange sites are differ from other SE sites Some of the Stack Exchange sites like Superuser,ServerFault  didn't have stackexchange.com in their urls, whereas someother sites like https://android.stackexchange.com/ , https://apple.stackexchange.com/ had unique themes of their own , but some other sites like https://sports.stackexchange.com/ didn't had it.
Recently, I saw another thing like

Stack Exchange was added to the names of site which were didn't having their unique themes.
I can understand that the SU and SF are the oldest and more busy SE sites, and sites like sports, christianity are with less users and low traffic. But I need to know, When can a SE site have its own theme and its own url like SU?


text:
Q: Does componentWillRecieveProps is always called before render or is it other way around I am trying to dispatch an action from componentWillRecieveProps and then the reducer is called. Reducers data is used in the component.
I am getting error of variable being undefined.
I think render is loaded before execution of componentWillRecieveProps.
So i want to ask if render is loaded first or componentWillRecieveProps.

A: componentWillReceiveProps is called before render.
Here's a diagram of which lifecycles are called when (up to React 16.3):

* Where 'initialization / setup props and state' is the constructor.
..
New lifecycles:
It's worth noticing that componentWillReceiveProps is considered legacy and should be avoided in 'new' code since React 16.3. The legacy lifecycles will be removed as of React 17.
Here's a dynamic diagram of which lifecycles are used at what moment per React version: http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/
You can read more about component lifecycles here.

A: The answer is Yes,
Note: componentWillReceiveProps with getDerivedStateFromProps in React 16.3
Please check: Replacing 'componentWillReceiveProps' with 'getDerivedStateFromProps'
Also, please have a look at Component Creation LifeCycle and Component Update Life Cycle
and also DO's and Dont's which is super important!
Creational Life Cycle hooks:

Update Life Cycle hooks:


text:
Q: How can I run Pyvmomi scripts based on vSphere alarms on the VCSA I need to trigger a script through vsphere for specific events, say if an ESXi host crashed. Wanted to do it using pyvmomi, prefer not to poll the vcenter and rather have an alarm trigger a script.
http://www.vcritical.com/2009/10/powershell-prevents-datastore-emergencies/
I looked at this as well https://pubs.vmware.com/vsphere-4-esx-vcenter/index.jsp#com.vmware.vsphere.dcadmin.doc_41/vc_client_help/working_with_alarms/c_running_commands_as_alarm_actions.html
But I wanted to know if we can achieve using pyvmomi?
Thanks

A: First a disclaimer:
It is not recommended that you add additional software to the VCSA, especially that which would increase the load on the machine. Doing so is not supported by VMWare to my knowledge and it could introduce stability issues into your VCSA so do so at your own risk and if you are worried check with your VMWare account team before making any changes.
That being said... This is possible to do. Since you would want to do this using the VCSA which runs on a SLES Linux box it will be very simple to do because it already has both Python and pyVmomi on it. This will also work on 6.5 once it comes out even though the underlying OS is changing from SLES to Photon. The process I describe below will work on 5.5, 6.0, and 6.5 in the same way.

*

*Write the script you want to run when the alarm you will be creating triggers, and place it on the VCSA in /root Be sure to set the the execution bit on the script using chmod a+x script.py

*Create the alarm in vCenter that matches the condition you are trying to monitor for. An existing Alarm Definition may exist but you will need to create your own because you can not modify the default alarms.

*In the Actions pane for the Alarm Definition select "Run a command".

*In the configuration box put the full path to the executable script that you want to run. /root/script.py and save the alarm.
Now when your alarm is triggered your script will run. If you have problems or think it is not working you can find a log file on the VCSA that can highlight what might be happening: /var/log/vmware/vpxd/vpxd.log
I have created a very crude example to show you how to get started with your script.
#!/usr/bin/python
#   Copyright 2016 Michael Rice <michael@michaelrice.org>
#
#   Licensed under the Apache License, Version 2.0 (the "License");
#   you may not use this file except in compliance with the License.
#   You may obtain a copy of the License at
#
#       http://www.apache.org/licenses/LICENSE-2.0
#
#   Unless required by applicable law or agreed to in writing, software
#   distributed under the License is distributed on an "AS IS" BASIS,
#   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#   See the License for the specific language governing permissions and
#   limitations under the License.

from __future__ import print_function
import os
import ssl
import sys
import requests

# This is where VMWare keeps the pyVmomi and other libraries
sys.path.extend(os.environ['VMWARE_PYTHON_PATH'].split(';'))

from pyVim import connect
from pyVmomi import vim
requests.packages.urllib3.disable_warnings()
# this is to ignore SSL verification which is helpful for self signed certs
try:
    _create_unverified_https_context = ssl._create_unverified_context
except AttributeError:
    # Legacy Python that doesn't verify HTTPS certificates by default
    pass
else:
    # Handle target environment that doesn't support HTTPS verification
    ssl._create_default_https_context = _create_unverified_https_context
USER_NAME = "YOUR USER"
PASSWORD = "YOUR PASS"
HOST = "YOUR HOST"
PORT = "443"
service_instance = connect.SmartConnect(host=HOST,
                                        user=USER_NAME,
                                        pwd=PASSWORD,
                                        port=int(PORT))

root_folder = service_instance.content.rootFolder
# again crude example here. use the logging module instead
with open("/var/log/my_script_log_file.txt", 'a') as f:
    print(root_folder.name, file=f)
    for var, val in os.environ.items():
        # When an alarm is triggered and run a lot of environment variables are set.
        # This will list them all with their values.
        if var.startswith("VMWARE_ALARM"):
            print("{} = {}".format(var, val), file=f)
    print("##########", file=f)
connect.Disconnect(service_instance)


text:
Q: Objective C - OpenGL ES | [EAGLView] unrecognized selector sent to instance I have an IOS app with two ViewController and both are working with Opengl ES.
I have a button which allows me to go from the first ViewController to the second one.
however, after touching the button, my app crash with this error message :
[EAGLView setDrawableDepthFormat:]: unrecognized selector sent to instance 0x15e5daa00

Here my code :
ViewControllerB.m
@interface ViewControllerB ()
{
    ....

    PointCloudRenderer *_renderer;

    ....

}

- (id)initWithNibName:(NSString *)nibNameOrNil
               bundle:(NSBundle *)nibBundleOrNil
{
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                   style:UIBarButtonItemStylePlain
                                                                  target:self
                                                                  action:@selector(dismissView)];
    self.navigationItem.leftBarButtonItem = backButton;

    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.title = @"Point Cloud viewer";
    }

    // GL setup
    _renderer = [[PointCloudRenderer alloc] initWithCols:DATA_COLS rows:DATA_ROWS];
    if (!_renderer) {
        NSLog(@"Failed to create renderer.");
        return;
    }

    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.context = _renderer.context;
    GLKView *view = (GLKView *)self.view;
    view.context = self.context;
    view.drawableDepthFormat = _renderer.drawableDepthFormat; //Crash here

    [self setupGestureRecognizer];
}

PointCloudRenderer.m
- (PointCloudRenderer *)initWithCols:(size_t)cols rows:(size_t)rows
{
   self.context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
   // self.context = [EAGLContext currentContext];
    assert (self.context != nil);
    if (!self.context) {
        NSLog(@"Failed to create ES context");
        return nil;
    }

    _cols = cols;
    _rows = rows;

    _fx = QVGA_F_X/QVGA_COLS*cols;
    _fy = QVGA_F_X/QVGA_ROWS*rows;
    _cx = QVGA_C_X/QVGA_COLS*cols;
    _cy = QVGA_C_Y/QVGA_ROWS*rows;

    _pointsData = [[NSMutableData alloc] initWithCapacity:cols * rows * 3 * sizeof(float)];
    _imageData = [[NSMutableData alloc] initWithCapacity:cols * rows * 4 * sizeof(char)];

    [self initGL];
    return self;
}

- (void)initGL
{
    [EAGLContext setCurrentContext:self.context];

    //Enable shader
    [self loadShaders];

    glEnable(GL_DEPTH_TEST);

    glGenVertexArraysOES(1, &_pointArray);
    glBindVertexArrayOES(_pointArray);

    glGenBuffers(1, &_pointBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, _pointBuffer);
    glBufferData(GL_ARRAY_BUFFER, _cols * _rows * 3 * sizeof(GLfloat) + sizeof(gTestPoints), NULL, GL_DYNAMIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(gTestPoints), gTestPoints);
    glEnableVertexAttribArray(GLKVertexAttribPosition);
    glVertexAttribPointer(GLKVertexAttribPosition, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), NULL);

    glGenBuffers(1, &_colorBuffer);
    glBindBuffer(GL_ARRAY_BUFFER, _colorBuffer);
    glBufferData(GL_ARRAY_BUFFER, _cols * _rows * 4 * sizeof(GLbyte) + sizeof(gTestPointColors), NULL, GL_DYNAMIC_DRAW);
    glBufferSubData(GL_ARRAY_BUFFER, 0, sizeof(gTestPointColors), gTestPointColors);
    glEnableVertexAttribArray(GLKVertexAttribColor);
    glVertexAttribPointer(GLKVertexAttribColor, 4, GL_UNSIGNED_BYTE, GL_TRUE, 4 * sizeof(GLubyte), NULL);

    glBindVertexArrayOES(0);

}

- (GLKViewDrawableDepthFormat)drawableDepthFormat
{
    return GLKViewDrawableDepthFormat24;
}

I really do not know why my app crashed. I was careful of initializing well OpenGl ES.
Could you please help me ?
Thank


text:
Q: (Java) Is there a type of object that can handle anything from primitives to arrays? I'm pretty new to Java, so I'm hoping one of you guys knows how to do this.  I'm having the user specify both the type and value of arguments, in any XML-like way, to be passed to methods that are external to my application.
Example: javac myAppsName externalJavaClass methodofExternalClass [parameters]
Of course, to find the proper method, we have to have the proper parameter types as the method may be overloaded and that's the only way to tell the difference between the different versions.  Parameters are currently formatted in this manner:
(type)value(/type), e.g. (int)71(/int) (string)This is my string that I'm passing as a parameter!(/string)
I parse them, getting the constructor for whatever type is indicated, then execute that constructor by running its method, newInstance(<String value>), loading the new instance into an Object.  This works fine and dandy, but as we all know, some methods take arrays, or even multi-dimensional arrays.
I could handle the argument formatting like so: (array)(array)(int)0(/int)(int)1(/int)(/array)(array)(int)2(/int)(int)3(/int)(/array)(/array)... or perhaps even better... {{(int)0(/int)(int)1(/int)}{(int)2(/int)(int)3(/int)}}.
The question is, how can this be implemented?  Do I have to start wrapping everything in an Object[] array so I can handle primitives, etc. as argObj[0], but load an array as I normally would?  (Unfortunately, I would have to make it an Object[][] array if I wanted to support two-dimensional arrays.  This implementation wouldn't be very pretty.)

A: Yes there is, and it's called java.lang.Object. You can even assign arrays like int[][] to an variable declared as java.lang.Object.
But I fear that's not what you wanted. It seems that you are writing a client-service framework -- the client (your user) pass some data to the service (your app). There're existing libraries that can do the same thing, e.g., Thrift, Protobuf. If you are looking for XML-based solution, there is SOAP.

A: What you're really looking for is JSON, and one of the Java kits for handling it.

A: I think what you are looking for here is a way to dynamically call Java methods based on attributes described inside an XML file.
If that's the case, you can explore the Java Reflection API.
Example class:
package foo;
public class Bar {

    public void doSomething(String x) {
        System.out.println("This is a method doSomething that takes in a String parameter");
    }

    public void doSomething(String [] arr, String str) {
        System.out.println("This is a method doSomething that takes in a String arr parameter and a String parameter");
    }
}

To dynamically use the methods in this class, do the following:
Class c = Class.forName("foo.Bar");
Object newInstance = c.newInstance();
Method method = c.getMethod("doSomething", String.class);
// This will locate the first method
method.invoke(newInstance, "Hello World");

Method method = c.getMethod("doSomething", String[].class, String.class);
// This will locate the second method

String [] arr = {"Hello", "World"};
method.invoke(newInstance, arr, "Hello World");

So you can specify in your XML file as follows:
<method>
    <name>doSomething</name>
    <params>
        <param>java.lang.String</param>
    </params>
</method>
<method>
    <name>doSomething</name>
    <params>
        <param>java.lang.String[]</param>   // or any other annotation to indicate that its an arr
        <param>java.lang.String</param>
    </params>
</method>

Then, read the XML file and use it to find the Java methods dynamically.
To dynamically create an array:
Class c = Class.forName("java.lang.String");
int length = 5;
Object o = Array.newInstance(c, length); // o is a String arr of length 5
String [] arr = (String []) o;


text:
Q: PL SQL bulk collect fetchall not completing I made this procedure to bulk delete data (35m records). Can you see why this pl/sql procedure runs without exiting and rows are not getting deleted ?
create or replace procedure clear_logs
as
 CURSOR c_logstodel IS SELECT * FROM test where id=23;
 TYPE typ_log is table of test%ROWTYPE;
 v_log_del typ_log;
BEGIN
OPEN c_logstodel;
LOOP
FETCH c_logstodel BULK COLLECT INTO v_log_del LIMIT 5000;
EXIT WHEN c_logstodel%NOTFOUND;
    FORALL i IN v_log_del.FIRST..v_log_del.LAST
    DELETE FROM test WHERE id =v_log_del(i).id;
    COMMIT;
END LOOP;
CLOSE c_logstodel;
END clear_logs;

A: Adding in rowid instead of column name,  exit when v_delete_data.count = 0; instead of EXIT WHEN c_logstodel%NOTFOUND; and changing chunk limit to 50,000 allowed the script clear 35 million rows in 15 mins
create or replace procedure clear_logs
as
 CURSOR c_logstodel IS SELECT  rowid FROM test where id=23;
 TYPE typ_log is table of rowid index by binary_integer;
 v_log_del typ_log;
BEGIN
OPEN c_logstodel;
LOOP
FETCH c_logstodel BULK COLLECT INTO v_log_del LIMIT 50000;
 exit when v_log_del.count = 0;
    FORALL i IN v_log_del.FIRST..v_log_del.LAST
    DELETE FROM test WHERE  rowid =v_log_del(i);
    exit when v_log_del.count = 0;
    COMMIT;
END LOOP;
COMMIT;
CLOSE c_logstodel;
END clear_logs;

A: First off when using BULK COLLECT LIMIT X the %NOTFOUND takes on a slightly unexpected meaning. In this case %NOTFOUND actually means Oracle could not retrieve X rows. (I guess technically it always does you fetch the next 1 and it says it could not fill the 1 row buffer.) Just move the EXIT WHEN %NOTFOUND to after the FORALL. But there is actually no reason to retrieve the data and then delete the retrieved rows. While one statement would be considerable faster 35M rows would require signifient rollback space. There is an interment solution.
Although not commonly used Delate statements generate rownum as do selects. This value can be user to limit the number or rows processed. So to break into a given commit size just limit rownum on the delete:
create or replace procedure clear_logs
as
    k_max_rows_per_interation constant integer := 50000;
begin
    loop
        delete
          from test
         where id=23
           and rownum <= k_max_rows_per_interation;
        exit when sql%rowcount < k_max_rows_per_interation;
        commit;
    end loop;
    commit;
end;

As @Stilgar points out deletes are expensive, meaning slow, so their solution may be better. But this has the advantage that it does not essentially take the table completely out-of-service during the operation. NOTE: I tend to use a much larger commit interval size, generally around 400,000 - 300,000 rows. I suggest you talk with your DBA see what they think this limit should be. Remember it is their job to properly size rollback space for typical operations. If this is normal in your operation they need to set it correctly.  If you can get rollback space for 35M deletes then that is the fastest you are going to get.


text:
Q: How to move a Character Sideways without causing any overflows in Unity? I have been working on a 3D endless runner game for some time when I faced this issue. During sideways movement, after switching each lane, my character just jumps back (-z axis) a couple of decimals which is very noticeable for someone who's playing the game; feeling like he's teleporting backward a few decimals. The issue came up after adding this simple code transform.position = locationAfterChangingLane; which stopped the overflowing of sideways movement. It did stop overflowing but made this annoying bug.
(code line situated in the isChangingLane if statement in update method.)
Here's my script (full, also I have commented where the above code line for easy reference.)
//Variables for Lane switching
    private bool isChangingLane = false;
    private Vector3 locationAfterChanginLane = Vector3.zero;
    private Vector3 sideWayMovementDistance = Vector3.right * 2f; // This might be the case that triggers abnormal movements
    private float sideWaySpeed = 6f;

    public enum Lane
    {
        Left,
        Right,
        Center
    }

    public enum MoveDirection
    {
        Left,
        Right,
        None
    }

    Lane currentLane = Lane.Center;

     void Update()
    {
        currentBaseState = anim.GetCurrentAnimatorStateInfo(0);

        if (controller.isGrounded)
        {
            verticalVelocity = -0.5f;
            if (currentBaseState.fullPathHash == locoState)
            {
                if (Input.GetButtonDown("Jump"))
                {
                    verticalVelocity = 18f;

                    anim.SetBool("Jump", true);
                }
                else if (Input.GetKeyDown(KeyCode.S))
                {
                    anim.SetBool("Slide", true);
                }

            }

            MoveLeftRight(); // This is the method to move right and left.

            if (isChangingLane)
            {
                if (Math.Abs(transform.position.x - locationAfterChanginLane.x) < 0.1f)
                {
                    isChangingLane = false;
                    moveVector.x = 0;
                    transform.position = locationAfterChangingLane; // This is the code which throws this issue.
                }
            }

        }
    }

    private void MoveLeftRight()
    {

        MoveDirection requestedMoveDirection = MoveDirection.None;
        if (Input.GetKeyDown(KeyCode.A) && !isChangingLane)
        {
            requestedMoveDirection = MoveDirection.Left;
            isChangingLane = true;
        }
        else if (Input.GetKeyDown(KeyCode.D) && !isChangingLane)
        {
            requestedMoveDirection = MoveDirection.Right;
            isChangingLane = true;
        }

        switch (requestedMoveDirection)
        {
            case MoveDirection.Right:
                if (currentLane == Lane.Right)
                {
                    Debug.Log("Right Lane");
                    break; //Do nothing when in right lane.

                }
                else if (currentLane == Lane.Center)
                {
                    locationAfterChanginLane = transform.position + sideWayMovementDistance;
                    moveVector.x = +sideWaySpeed;

                    currentLane = Lane.Right;
                    Debug.Log("Center --> Right");
                }
                else if (currentLane == Lane.Left)
                {
                    locationAfterChanginLane = transform.position + sideWayMovementDistance;
                    moveVector.x = +sideWaySpeed;

                    currentLane = Lane.Center;
                    Debug.Log("Left --> Center");
                }
                break;
            case MoveDirection.Left:
                if (currentLane == Lane.Left)
                {
                    Debug.Log("Left Lane");
                    break; //Do nothing when in left lane.
                }
                else if (currentLane == Lane.Center)
                {
                    locationAfterChanginLane = transform.position - sideWayMovementDistance;
                    moveVector.x = -sideWaySpeed;

                    currentLane = Lane.Left;

                    Debug.Log("Center --> Left");
                }
                else if (currentLane == Lane.Right)
                {
                    locationAfterChanginLane = transform.position - sideWayMovementDistance;
                    moveVector.x = -sideWaySpeed;

                    currentLane = Lane.Center;

                    Debug.Log("Right --> Center");
                }
                break;
        }
    }

Help would be greatly appreciated. How do I solve this? Also can you kindly explain why this happens? Many thanks!

A: It looks like you have a non-instantaneous movement animation as your character changes lane. That's good, but it also looks like you save the destination point at the moment that someone presses left or right. This position is stored in memory, and then about 0.5 sec later when they arrive at that lane fully, it reuses that position - which has stayed behind them.
A quick fix would be, once the lane movement animation has ended, just change locationAfterChangingLane's Z component to match the player's current Z component. Or, instead of saving and setting that vector, apply a Math.Max/Math.Min operation to the player's location so that they don't go past a certain maximum.
Another side note: I've seen some people run into math issues when playing their infinite runner for more than a few minutes because all their numbers are entering high ranges. It's possible that you'd want to consider simply having sections of the world simply "slide past" a still protagonist and be recycled behind him, so that even after 20 minutes of playing he's still at (0, 0, 0)


text:
Q: How do I find out where the Mercurial hook file is being called from? On the project I am working on there is a standard pre-commit hook for mercurial that looks something like this:
python:hookhgext.messagevalidation.checkCommitMessage

I would like to find out where the python script is located so I can create my own hook script that also calls this.
How would I either find the location of this file or also call this hook from a python script?

A: Accoring to docs

The value of the hook must start with the text "python:", and continue
  with the fully-qualified name of a callable object to use as the
  hook's value.
  …
  So long as you have the module name and PYTHONPATH right, it should
  "just work"

I.e. in your case Mercurial imports hookhgext.messagevalidation (from any possible for import location) and call checkCommitMessage from it.
I know nothing about Python, but for me hookhgext.messagevalidation is "messagevalidation" something inside "hookhgext.py", and "hookhgext" is the usual installed python-module in it's (installed modules) default location(s)


text:
Q: How to start tomcat server outside netbeans IDE I have created an application in Java EE, I have learned how to deploy it in the tomcat server using the manager app or by copying the war file to the webapps folder. Now I can start the tomcat server only  from the Netbeans IDE.
I want to know how to start the apache tomcat server without using the IDE and run my web application from the war file deployed. If I'm headed in the wrong direction please correct me. I'm asking this to gain knowledge of how to deploy the .war file in another server system without using the IDE only the tomcat server.

A: The shell scripts located in "CATALINA_HOME/bin" are the most bare-bones way of getting Tomcat up and running. The two scripts capable of starting Tomcat in this directory are named "catalina" and "startup", with extensions that vary by platform.

A: In your tomcat installation directory, there would be a startup.bat/sh file which will start the server for you. Moreover you can see the conf folder as well if you want to change any configurations. Whatever war you copy to the webapps folder will be automatically deployed


text:
Q: Worklight console is not opening I use Java 7 and when I try to start worklight console from Eclipse I get server errors.
In browser I get the message "Server error. Contact the server administrator." in IBM MobileFirst Platform Operations Console.
Application's preview is not accessible also.
This is my logs from console:

[WARNING ] CWNEN0070W: The javax.ws.rs.CookieParam annotation class will not be recognized because it was loaded from the null location rather than from a product class loader.
[WARNING ] CWNEN0070W: The javax.ws.rs.PathParam annotation class will not be recognized because it was loaded from the null location rather than from a product class loader.
[WARNING ] CWNEN0070W: The javax.ws.rs.HeaderParam annotation class will not be recognized because it was loaded from the null location rather than from a product class loader.
[WARNING ] CWNEN0070W: The javax.ws.rs.QueryParam annotation class will not be recognized because it was loaded from the null location rather than from a product class loader.
[WARNING ] CWNEN0070W: The javax.ws.rs.MatrixParam annotation class will not be recognized because it was loaded from the null location rather than from a product class loader.
[WARNING ] CWNEN0070W: The javax.ws.rs.core.Context annotation class will not be recognized because it was loaded from the null location rather than from a product class loader.
[AUDIT   ] CWWKZ0001I: Application WorklightConsole started in 9.391 seconds.
[AUDIT   ] CWWKZ0001I: Application WorklightAnalytics started in 9.917 seconds.
[ERROR   ] SRVE0283E: Exception caught while initializing context: java.lang.ExceptionInInitializerError
    at org.springframework.web.context.ContextLoaderListener.createContextLoader(ContextLoaderListener.java:53)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:44)
    at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated(WebApp.java:2227)
    at [internal classes]
Caused by: java.lang.IllegalStateException: Could not load 'ContextLoader.properties': class path resource [ContextLoader.properties] cannot be opened because it does not exist
    ... 6 more
[ERROR   ] SRVE0283E: Exception caught while initializing context: java.lang.NullPointerException
    at com.ibm.worklight.admin.common.util.Messages.getResourceString(Messages.java:208)
    at com.ibm.worklight.admin.common.util.Messages.get(Messages.java:230)
    at com.ibm.worklight.admin.common.util.Messages.getString(Messages.java:254)
    at com.ibm.worklight.admin.common.util.GeneralUtil.getProductBuildVersion(GeneralUtil.java:50)
    at com.ibm.worklight.admin.listeners.WorklightManagementServletContextListener.contextInitialized(WorklightManagementServletContextListener.java:41)
    at com.ibm.ws.webcontainer.webapp.WebApp.notifyServletContextCreated(WebApp.java:2227)
    at [internal classes]
[ERROR   ] M:\IBM\From_Sergey\Mobilefirst%20eclipse\MobileFirstServerConfig\servers\worklight\workarea\org.eclipse.osgi\bundles\73\data\cache\com.ibm.ws.app.manager_94.cache\WEB-INF\lib\ibm_web20_wink_no_abdera_no_jackson-1.1.0.0-20110422.jar (The system cannot find the path specified)
M:\IBM\From_Sergey\Mobilefirst%20eclipse\MobileFirstServerConfig\servers\worklight\workarea\org.eclipse.osgi\bundles\73\data\cache\com.ibm.ws.app.manager_94.cache\WEB-INF\lib\ibm_web20_wink_no_abdera_no_jackson-1.1.0.0-20110422.jar (The system cannot find the path specified)
[ERROR   ] M:\IBM\From_Sergey\Mobilefirst%20eclipse\MobileFirstServerConfig\servers\worklight\workarea\org.eclipse.osgi\bundles\73\data\cache\com.ibm.ws.app.manager_94.cache\WEB-INF\lib\ibm_web20_wink_no_abdera_no_jackson-1.1.0.0-20110422.jar (The system cannot find the path specified)
M:\IBM\From_Sergey\Mobilefirst%20eclipse\MobileFirstServerConfig\servers\worklight\workarea\org.eclipse.osgi\bundles\73\data\cache\com.ibm.ws.app.manager_94.cache\WEB-INF\lib\ibm_web20_wink_no_abdera_no_jackson-1.1.0.0-20110422.jar (The system cannot find the path specified)
[ERROR   ] Uncaught.init.exception.thrown.by.servlet                                                                                ManagementServlet                                                                                WorklightServices                                                                                java.lang.ExceptionInInitializerError
    at org.apache.wink.server.internal.DeploymentConfiguration.initAlternateShortcutMap(DeploymentConfiguration.java:386)
    at org.apache.wink.server.internal.DeploymentConfiguration.init(DeploymentConfiguration.java:167)
    at org.apache.wink.server.internal.servlet.RestServlet.getDeploymentConfiguration(RestServlet.java:202)
    at org.apache.wink.server.internal.servlet.RestServlet.createRequestProcessor(RestServlet.java:138)
    at org.apache.wink.server.internal.servlet.RestServlet.init(RestServlet.java:103)
    at javax.servlet.GenericServlet.init(GenericServlet.java:161)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:325)
    at [internal classes]
Caused by: java.util.MissingResourceException: Can't find bundle for base name org.apache.wink.common.internal.i18n.resource, locale en_US
    ... 14 more
[ERROR   ] SRVE0266E: Error occured while initializing servlets: javax.servlet.ServletException: SRVE0207E: Uncaught initialization exception created by servlet
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:395)
    at [internal classes]
Caused by: java.lang.ExceptionInInitializerError
    at org.apache.wink.server.internal.DeploymentConfiguration.initAlternateShortcutMap(DeploymentConfiguration.java:386)
    at org.apache.wink.server.internal.DeploymentConfiguration.init(DeploymentConfiguration.java:167)
    at org.apache.wink.server.internal.servlet.RestServlet.getDeploymentConfiguration(RestServlet.java:202)
    at org.apache.wink.server.internal.servlet.RestServlet.createRequestProcessor(RestServlet.java:138)
    at org.apache.wink.server.internal.servlet.RestServlet.init(RestServlet.java:103)
    at javax.servlet.GenericServlet.init(GenericServlet.java:161)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.init(ServletWrapper.java:325)
    ... 1 more
Caused by: java.util.MissingResourceException: Can't find bundle for base name org.apache.wink.common.internal.i18n.resource, locale en_US
    ... 14 more

A: I think you're using Java 8.
Worklight/MobileFirst Platform does not support Java 8 at this time.
Please downgrade to Java 6 or 7 and try again.


text:
Q: Insert large records quickly in mysql? I have a csv file more than one lakhs ( 100,000 ) records. when I'm using these file for inserting records into my database it will be take more than half an hour. Is there any other way increase the efficiency and speed for these process or any frameworks are available?

A: Use "mysqlimport" command. It works fast and is suited for large CSV files.
mysqlimport --ignore-lines=1 \
            --fields-terminated-by=, \
            --local -u root \
            -p Database \
             TableName.csv

A: Convert the CSV file into a file containing a SQL request in a text editor. Execute in console the request using:
mysql -u user -ppassword db_name < file_path.sql


text:
Q: Passing structs into function by address vs a pointer in C I was hoping someone could help me figure out why one version of the below code works, while the other doesn't. Below I've included the initArray method, stored in "worksheet.c". The function is accessed in main, both versions are given below.
void initArray(struct dynArray *a) {
    a->data = malloc(10 * TYPE_SIZE);
    assert(a->data != 0);
    a->size = 0;
    a->capacity = 10;
}

This works. I create a dynArray struct and pass it to initArray by reference.
#include "worksheet0.h"
#include <stdio.h>

int main(void)
{
    struct dynArray b;
    initArray(&b);
    return 0;
}

This fails with a seg fault. I thought that passing b here would be the same as passing the struct by reference.
int main(void)
{
    struct dynArray *b = NULL;
    initArray(b);
    return 0;
}

A: Because in the second case there is no memory allocated to which the struct pointer points to. It is simply a pointer having the value NULL. On your case by dereferencing the value NULL you have invoked undefined behavior.
It would work if you allocate memory, make changes to it and then return it's value. [But then you have to return the address of the allocated memory.] OR you can pass the address of the pointer variable and allocate memory to which dereferenced pointer (here the pointer has type struct dynAray**) would point to and make changes to it.
Let's be more clear now slowly:
Why the first case works? You have a struct dynArray variable whose address you have passed into the function and then you have accessed the content of that address - wait! that means you have accessed the struct dynArray variable itself and made changes to its member variables. Yes that is what exactly happened in the first case.
In the second case, you have a pointer to struct dynArray. And then you passed it - de-referenced it. Where was it pointing to? Is it some struct dynArray variable's address that it contained? No. It was NULL. So it is wrong if you expect it to work.
The second would work - but you have to change things a bit! Let's see how:
struct dynArray* initArray() {
    struct dynArray* a = malloc(sizeof *a);
    assert(a != NULL);
    a->data = malloc(10 * TYPE_SIZE);
    assert(a->data != 0);
    a->size = 0;
    a->capacity = 10;
    return a;
}

And in main()
struct dynArray* b;
b  = initArray();

You don't even need to pass the pointer variable. That would be meaningless if you want to do it like this.
And you know you can also pass the address of the pointer variable so that you can make changes to it -
void initArray(struct dynArray** a) {
    *a = malloc(sizeof **a);
    assert((*a) != NULL);
    (*a)->data = malloc(10 * TYPE_SIZE);
    assert((*a)->data != 0);
    (*a)->size = 0;
    (*a)->capacity = 10;
}

For this in main() you would call it like this
struct dynArray* b;
initArray(&b);

A: In the first example a pointer holding the address of an actual struct is passed to the function. But, in the second example the pointer b does not point to a struct. Instead, this pointer is initialized to NULL, and when this null pointer is dereferenced in the initArray() function, undefined behavior ensues.


text:
Q: If $a$ has order $p$ and $aPa^{-1}=P$ then $a\in P$
If $G$ is a finite group, $P$ a $p$-Sylow subgroup of $G$, $a\in G$ has order $p$ and $aPa^{-1}=P$ then $a\in P$.

This is proved in Rotman:
Proof: We have $a\in N_G(P)$. If $a\notin P$ then $aP\in N_G(P)/P$ has order $p$, which contradicts $N_G(P)/P$ is prime to $p$.
I don't see why $aP$ has order $p$ in the quotient. Of course $a^pP=P$. But why if $1<n<p$ can't we have $a^n\in P$?
Thank you.

A: If $f:G\rightarrow H$ is a groups morphism then $order(f(x))$
divides $order(x)=m$, because $f(x)^m=f(x^m)=f(e)=e$. So $aP$ has
order $1$ or $p$

A: Here is a proof without an appeal to modding out a normalizer by its Sylow subgroup: since $aPa^{-1}=P$, the subset $P\langle a \rangle$ is actually a subgroup containing $P$. Since $|P\langle a \rangle|=\frac{|P| \cdot |\langle a \rangle|}{|P \cap \langle a \rangle|}$ is a power of $p$, and $P$ is Sylow, whence a maximal $p$-subgroup, we must have $P\langle a \rangle=P$, that is, $a \in P$. This shows by the way that the order of $a$ can be any power of $p$ to make the statement true.


text:
Q: Snowflake caching not working with Snowpark Python 1.0 Snowflake is caching already executed queries, such that subsequent executions of the same query will finish much faster. As far as I know, this only works if the query is exactely the same.
In my app (a interactive dashboard which uses Snowpark-Python 1.0 to fire snowflake queries), this caching does not seem to work. Each time the (same snowpark) query is fired, snowflake does run the query again:

Depending on whether the warehouse cache is active are not (blue vs green bar), the execution time is several 100ms up to 2s. The result is not read from the cache.
I think the cause is that the generated SQL does contain random components (column and table names suffixes) which are different for each query:

How can I make use of the snowflake cache using Snowpark-generated queries?


text:
Q: image not showing the right image..? Basically, user uploads an image. The image is taken, checked for the right file type and uploaded to the server here:
$directory = 'uploads/';
$files = glob($directory . 'audit'.$id.'_image*.jpg');
$count = 0;
if ($files !== false) {
    $count = count($files) + 1;
}

if (!empty($_FILES)) {

    $tempFile = $_FILES['file']['tmp_name'];          //3

    $rename =  explode('.', $_FILES['file']['name']);

    $nameString = 'audit'.$id.'_image'.$count.'.'.strtolower($rename[1]);

    //only allow certain image files
    $allowed = array(   'jpg'
                        );

    if (in_array(strtolower($rename[1]), $allowed)) {

        $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;  //4

        $targetFile =  $targetPath. $nameString;  //5

        move_uploaded_file($tempFile,$targetFile); //6
    }

}

The name of the file is changed to suit the format for retrieval. That would be
audit(iD)_image*.jpg
or an example audit65_image1.jpg
Now, this works fine, and the image is uploaded.
HOWEVER, when it comes to retrieval for viewing the file.. This happens !
        $directory = 'uploads/';
        $files = glob($directory . 'audit'.$row['id'].'_image*.jpg');

        if (count($files) > 0) {
        ?>

Image Uploads

                        <?php

                        foreach ($files as $key => $value) {
                            ?>

                                <a href=<?php echo '"'.$value.'"'; ?>><img style="box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.65);" src=<?php echo '"'.$value.'"'; ?> class="superbox-img"/>

                            <?php
                        }
                        ?>

        <?php
        }
        ?>

Which again, I can't see a problem with! However, on the webpage.. It will load the incorrect image, so if I uploaded 3 files, it's asif they're saved to my system or part of a system somewhere and it's causing a big issue. But it's basically showing an image that doesn't exist. If I change the file name from say audit65_image1.jpg to audit65_image3.jpg then the image shown on the webpage changes. I'm so utterly confused. I tried loading the webpage on a different computer to account for caching and it loaded the wrong image on there too even though the file does not exist for the image it's loading!
Does anyone have any idea what's going wrong?

A: to give unique name to the image files try to add the timestamp to the name of the image before saving.


text:
Q: android soft keyboard capitalisation I am trying to set Android sample soft keyboard to make first letter in sentence  capital. It's the normal behavior of keyboard, but I don't know how to do this((

A: Must be a bit late to answer, but someone else might need this.
To capitalize the keyboard manually, you have to call your KeyboardView's setShifted (boolean shifted) method with desired shifted mode.
Here is an example:
private KeyboardView mInputView;
...
mInputView.setShifted(true);

But it is better if you let your SoftKeyboard to decide its capitalization mode by checking the attributes of the text editor. For example, emails usually are typed using lowercase letters.
If you look at this sample here, it has a method named updateShiftKeyState(EditorInfo attr) which is used to set the capitalization mode automatically based on the initial attributes of the text editor in which the text will be typed in:
/**
 * Helper to update the shift state of our keyboard based on the initial
 * editor state.
 */
private void updateShiftKeyState(EditorInfo attr) {
    if (attr != null
            && mInputView != null && mQwertyKeyboard == mInputView.getKeyboard()) {
        int caps = 0;
        EditorInfo ei = getCurrentInputEditorInfo();
        if (ei != null && ei.inputType != InputType.TYPE_NULL) {
            caps = getCurrentInputConnection().getCursorCapsMode(attr.inputType);
        }
        mInputView.setShifted(mCapsLock || caps != 0);
    }
}

A: Just set the android:capitalize xml attribute for the textview in your layout. Check the possible values for the attribute here


text:
Q: ReactJS dangerouslySetStyle? I am using ReactJS and am aware of dangerouslySetInnerHTML but I want to be able to set an element's style attribute to a raw string. I've searched and had a look through the React source but I can't find anything.
Is there a way to do this?

A: You have to manually set the attribute on the dom node to do this.  The simplest way would be with a wrapper component:
<CustomAttribute tag="div" dangerouslySetAttributes={{style: 'color:red'}}>
  red text
</CustomAttribute>

And the actual component
var DSA = 'dangerouslySetAttributes';
var CustomAttribute = React.createClass({
  setAttributes: function(oldAttrs, attrs){
    var el = this.getDOMNode();
    Object.keys(attrs).forEach(function(key){
      if (oldAttrs[key] !== attrs[key])
        el.setAttribute(key, attrs[key]);
    });
  },
  componentDidMount: function(){
    this.setAttributes({}, this.props[DSA]);
  },
  componentWillReceiveProps: function(nextProps){
    this.setAttributes(this.props[DSA], nextProps[DSA]);
  },
  render: function(){
    var Tag = this.props.tag || 'div';
    return <Tag>{this.props.children}</Tag>
  },
});

*not tested

A: Why don't you set the entire markup, including styles, in dangerouslySetInnerHTML, like such:
var markup = "
Content
"

That should get the job done

A: I looked more thoroughly through the React source and in /src/vendor/core/camelize.js I found this:
/**
 * Copyright 2013-2014, Facebook, Inc.
 * All rights reserved.
 *
 * This source code is licensed under the BSD-style license found in the
 * LICENSE file in the root directory of this source tree. An additional grant
 * of patent rights can be found in the PATENTS file in the same directory.
 *
 * @providesModule camelize
 * @typechecks
 */

var _hyphenPattern = /-(.)/g;

/**
 * Camelcases a hyphenated string, for example:
 *
 *   > camelize('background-color')
 *   < "backgroundColor"
 *
 * @param {string} string
 * @return {string}
 */
function camelize(string) {
  return string.replace(_hyphenPattern, function(_, character) {
    return character.toUpperCase();
  });
}

module.exports = camelize;

So it is a little inefficient in that it turns a hypenated style attribute into camel case and then React turns it back again but it does work.

A: Its simple to use dangerouslySetInnerHTML:

https://facebook.github.io/react/tips/dangerously-set-inner-html.html

It will work same as like normal html/JS:

A: Why not using classnames? When you receive new state from your resource then React will take care of rendering the correct style attributes.
Basically the code is:
classNames({
'random-string': condition ? true : false
});


text:
Q: Loading Keras model from google cloud ml bucket Using Keras on Google cloud ml:
Saving model from training:
model.save('model.h5')
if cfg.cloud:
    # Copy model.h5 over to Google Cloud Storage
    with file_io.FileIO('model.h5', mode='rb') as input_f:
        with file_io.FileIO(data_folder + 'model.h5', mode='wb+') as output_f:
            output_f.write(input_f.read())

Note: not saving to job_folder, I need to read this later, not wanting to keep track of the latest job (even if that's a good way to keep models apart).
Now I want to read from my next run:
f = file_io.FileIO(model_file, mode='rb')
model = load_model(f)
model.load_weights(f)

Where 'model_file' is given as input in my submission, pointing at
--model-file gs://$BUCKET_NAME/resources/model.h5

Complains from google cloud ml jobs:
TypeError: expected str, bytes or os.PathLike object, not FileIO

I tried a number of things, but my basic question is: what's the best practice writing and especially reading in models from gcp buckets?

A: Finally I got it working, using the solution here:
loading saved keras model from gs to pydatalab
Thanks Tíarnán McGrath (I don't have enough points to do a plus 1)


text:
Q: Javascript blackjack logic My logic to check if a card has already been used is wrong.
Can someone help me please. (Card comes from a hit function that just picks a new random one).
    function checkCard(card) {
    //if card = card in used array, select new card
    for (i = 0; i <= userCards.length; i++) {
        if (userCards[i] == card) {
            //selectCards(card)
            var newRank = Math.floor(Math.random() * 13);
            var newSuit = Math.floor(Math.random() * 4);
            var card = (rank[newRank] + suit[newSuit]);
            checkCard(card);
            //document.getElementById('userCards').innerHTML += "";
            //userCards[userCards.length] = card;
            //userTotal();
        } else {
            userCards[userIndex] = card;
            document.getElementById('userCards').innerHTML += "";
            userTotal();
        }
    }
}

A: In your for loop, if you do
i <= userCards.length

you are going past the index of the array. That should be:
i < userCards[i].length

Also, I don't understand what your base case is that allows you to stop the recursion. You're just creating some random card, recalling your function, then checking to see if it's in the used array?. If it is, you're making another random card and if it isn't you're adding it to the used array then calling userTotal() with no parameters. Every time you call your function recursively, it's starting at 0 and checking the whole array again.
Your logic to check to see if a card has already been used, other than going past the index, isn't wrong.. but certainly what you're trying to do with the information once you've found it seems wrong.
Try explaining exactly what you're trying to do in a little more detail.

A: You are missing a return statement. If you must use recursion try this logic:
function checkCard(card)
{    //if card = card in used array, select new card
    for (i = 0; i < userCards.length; i++)
    {
            if (userCards[i] == card)
            {   //selectCards(card)
                var newRank = Math.floor(Math.random() * 13);
                var newSuit = Math.floor(Math.random() * 4);
                var card = (rank[newRank] + suit[newSuit]);
                checkCard(card);
            return;  // new card was assigned in recursive call above
            }
   }
   // card is unused, assign now
   userCards[userCards.length] = card;
   document.getElementById('userCards').innerHTML += "";
   userTotal();
   return;      // new card was assigned here.
}


text:
Q: iOS SDK Realtime Text Removal on AVCatureSession Frame of Image in focus I am developing an iOS app similar to Word Lens . What I want is the functionality to add some blurred pieces as overlay on certain text part as shown in the attached images.
If it is possible to wipe out the text data completely from an Image, I would also appreciate that.
I searched a lot on internet and have found that it has something to do with OpenGL ES and OpenCV but do not exactly how to achieve this.
Any guidance would be highly appreciated !
Thanks
Please have a look at image here which has blurred rectangles over an Image under AVCaptureSession focus

A: There is a sdk called VUFORIA/QCAR. if you examine their Text Recognition Sample it will give you an idea.
For example;
firstly change open gl es shader program to render a square,
after that you need to detect what color behind the word. to do so. vuforia gives readonly access to image data.
like this;
QCAR::Frame vbFrame = state.getFrame();
const QCAR::Image *vbImage;
for (int i = 0; i<vbFrame.getNumImages(); i++) {
    if (state.getFrame().getImage(i)->getFormat() == QCAR::RGB888) {
        vbImage = state.getFrame().getImage(i);
    }
}

From that point you need vuforia experience and binary image knowledge.
for to give you and an idea, you can get a point RGBcolor values like this,
- (void) getColorFromVGImage:(int)xx andY:(int)yy
{
    const char* vbImageData = (const char*) vbImage->getPixels();

    int maxXx = vbImage->getWidth() - 1;
    int maxYy = vbImage->getHeight() - 1;

    int bytesPerPixel = 3;
    int bytesPerRow = vbImage->getStride();
    int byteIndex = ((bytesPerRow * yy) + (xx * bytesPerPixel));

    int maxByteIndex = (bytesPerRow * maxYy) + (maxXx * bytesPerPixel);

    if (maxByteIndex >= byteIndex && byteIndex > 0) {
        unsigned char rchar = vbImageData[byteIndex];
        unsigned char gchar = vbImageData[byteIndex + 1];
        unsigned char bchar = vbImageData[byteIndex + 2];

        int r = (int)rchar;
        int g = (int)gchar;
        int b = (int)bchar;
    }
}

AND PLEASE NOTE: This process for RGB888 binary image data.

hope this helped.

A: Yes it's possible, and yes OpenCV and OpenGL would be good technology to use.
OpenCV is a cross-platform hardware accelerated image recognition library. You could use it to develop routines that would find text in a video feed and place boxes around it. The more context you have about what you are viewing, the faster and more reliable you can make it. (e.g. if you know you will be scanning a paper form with a fixed layout and boxes for user information, it's much easier than if you are scanning some arbitrary image that might have text in different fonts/different sizes and the layout can vary.)
However, both of those are very advanced frameworks that take weeks or months to become proficient with, even for experienced developers.
If you are a newbie, you are in over your head.


text:
Q: How does a CSS rule override another CSS rule? So, this is what I'm doing:
#id-form td {
padding: 0 0 10px 0;
}

#particular-td {
border: 1px solid black;
text-align: center;
background-color: #DFDFDF;
height: 30px;
padding: 10px;
}

I have a table #id-form, on which I set all tds to have padding-bottom: 10px.
But on one special occasion, I want a particular td to have padding: 10px in all directions, which I set in the #particular-td.
Obviously, I put the CSS styling in sequence in an external file.
But the rendered CSS only has padding-bottom, and padding: 10px appears to be overridden!?
Please explain:
How and why is this happening?
How should I arrange these rules to solve my problem (other than inline styling)?
EDIT: I removed 'table' before #id-form in table. I was never using this, I just mentioned it here to be able to explain it better.

A: This has to do with specificity. table#id-form td is more specific than #particular-td. A rule with higher specificity has precedence over a rule with lower specificity.
Here are a few resources to get you started on understanding how it works:

*

*Smashing Magazine article

*W3C spec on specificity

*Specificity calculator
About using !important, as suggested by others:
One might be tempted to use the !important keyword to sort this out, but that is rarely a good idea:

*

*It becomes a pain to maintain/troubleshoot

*It breaks the normal flow of CSS

*The rule cannot be overridden by other rules later on

It might take a few minutes to read up on specificity, but it will be well worth the time spent when you've got a grasp of it.

A: Because of CSS Specificity. A selector's weighting is evaluated based on the components that make it up, with id's given a weighting of 100, classes with a weighting of 10, and element selectors with weighting of 1.
So in your example:
table#id-form td

Has a weighting of 102 (table#id is 101 and td is 1), whereas this:
#particular-td

Has a weighting of 100. If you change your second to this:
#id-form #particular-td

You will get a weighting of 200 which will override the previous selector. Only as a last resort should you ever use !important, as this pretty much prevents you from overriding it further down the line.

A: You have two ways, either add !important after your padding for the particular-td:
padding: 10px !important;

OR, your selector altered like so:
table#id-form td#particular-td {
border: 1px solid black;
text-align: center;
background-color: #DFDFDF;
height: 30px;
padding: 10px;
}

Both are fine. Personally I don't like the use of !important if I can avoid it.

A: Try this code, I have added !important to your css, in this mode can ovveride padding of table#id-form td
#particular-td {
border: 1px solid black;
text-align: center;
background-color: #DFDFDF;
height: 30px;
padding: 10px !important;
}


text:
Q: Batch to open a folder within a user's folder(c:\users\usernamehere\my documents)? But I am looking for a code that will allow whatever user that uses my batch file to get to their my documents. The idea is that they would type 3, press enter, and then the program would open up their "My Documents" folder.
Unfortunately every user has a different name, so the following command won't work unless it has a specific name after it.
%SystemRoot%\explorer.exe c:\users\James\My Documents

Is there some sort of replacement for the "James"? A universal command?

A: You can use the %UserProfile% environment variable, which points directly to the personal folder of the logged in user:
%SystemRoot%\explorer.exe %UserProfile%\My Documents

-If you're using windows 7 just do explorer %UserProfile%\Documents (should work with other Windows but I haven't tried...)
this is because any exe in system root can be used as a command and to my knowledge most versions of windows have a folder called "Documents" not "My Documents" it just appears that way to the user (same for Music etc.)


text:
Q: Strange error when converting from VB to C# TripleDESCryptoServiceProvider exception Specified key is not a valid size for this algorithm I built a password encryption program in visual basic and am porting it to c# all of the code is correctly converted as far as i can see ive debugged the program up to the point that the error is thrown all the key sizes are the same in the VB app and in the c# app yet the c# version throws the exception.
Unhandled Exception: System.Security.Cryptography.CryptographicException: Specified key is not a valid size for this algorithm.
the only difference between the two is the declaration of the statement in a class for use at runtime.
vb
Private Wrapper As New EncryptionWrapper(key:=0)

however :=0 does not work in c# so i used :"" instead i think this may be the issue but i hope its not because im not sure the workaround.
c#
private EncryptionWrapper Wrapper = new EncryptionWrapper(Key:"");

oh and security broker is just the declaration for the TripleDESCryptoServiceProvider like so
private TripleDESCryptoServiceProvider SecurityBroker = new TripleDESCryptoServiceProvider();

Visual Basic :
''' <summary>
''' Class initializer to initialize the encryption wrapper with a new encryption password.
''' </summary>
''' <param name="key">Encryption password string.</param>
Sub New(ByVal key As String)
    'Initialize the crypto provider.
    SecurityBroker.Key = TruncateHash(key, SecurityBroker.KeySize \ 8) ' 196 - 24 (runtime values)
    SecurityBroker.IV = TruncateHash("", SecurityBroker.BlockSize \ 8) ' 64 - 8 (runtime values)
End Sub

c# :
//Class constructor
public EncryptionWrapper(string Key)
{
    SecurityBroker.Key = TruncateHash(Key, SecurityBroker.KeySize / 8);  //196 - 24
    SecurityBroker.IV = TruncateHash("", SecurityBroker.BlockSize / 8);  //64 - 8
}

more useful information:
truncate hash function in c#
        public byte[] TruncateHash(string Key, int length)
        {
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(Key);
            byte[] hash = sha1.ComputeHash(keyBytes);

            return (byte[])RedimPreserve(hash, hash.Length - 1);
        }

        //c# custom function to take place of ReDim from VB
        public static Array RedimPreserve(Array originArray, Int32 desiredSize)
        {
            System.Type t = originArray.GetType().GetElementType();
            Array newArray = Array.CreateInstance(t, desiredSize);
            Array.Copy(originArray, 0, newArray, 0, Math.Min(originArray.Length, desiredSize));
            return newArray;
        }

in vb
    ''' <summary>
    ''' Truncates the hash to remove extra characters from the beginning and end
    ''' </summary>
    ''' <param name="key">Hash key</param>
    ''' <param name="length">Hash length</param>
    ''' <returns>A truncated hash byte array</returns>
    Private Function TruncateHash(ByVal key As String, ByVal length As Integer) As Byte()
        Dim sha1 As New SHA1CryptoServiceProvider

        'Hash the key.
        Dim keyBytes() As Byte = System.Text.Encoding.Unicode.GetBytes(key)
        Dim hash() As Byte = sha1.ComputeHash(keyBytes)

        'Truncate or pad the hash.
        ReDim Preserve hash(length - 1)
        Return hash
    End Function

A: A bit of funny VB stuff happening here:

*

*VB allows you to pass the integer literal 0 to a string parameter.  The equivalent is not an empty string in C#, but the string literal "0".

*This 'ReDim Preserve' converts trivially to Array.Resize.

*The conversion of VB integer division (operator '\') needs an accompanying cast to ensure a truncated integer result (like VB).
i.e.,
using System;

internal class Test
{
    private EncryptionWrapper Wrapper = new EncryptionWrapper(key: "0");
}

internal class EncryptionWrapper
{

    public EncryptionWrapper(string key) // 196 - 24 (runtime values)
    {
        //Initialize the crypto provider.
        SecurityBroker.Key = TruncateHash(key, Convert.ToInt32(SecurityBroker.KeySize) / 8);
        SecurityBroker.IV = TruncateHash("", Convert.ToInt32(SecurityBroker.BlockSize) / 8); // 64 - 8 (runtime values)
    }

    private byte[] TruncateHash(string key, int length)
    {
        SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

        //Hash the key.
        byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(key);
        byte[] hash = sha1.ComputeHash(keyBytes);

        //Truncate or pad the hash.
        Array.Resize(ref hash, length);
        return hash;
    }

}

A: Removing the -1 in the resized array of the truncate hash function fixed the pro
public byte[] TruncateHash(string Key, int length)
        {
            SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();

            byte[] keyBytes = System.Text.Encoding.Unicode.GetBytes(Key);
            byte[] hash = sha1.ComputeHash(keyBytes);

            Array.Resize(ref hash, length);

            return hash;
        }


text:
Q: How to draw a text in canvas in android I am writing an application that consists of a gauge view. I downloaded from here and i want to draw text inside the gauge view (that is at the center of the gauge view) how can i draw a text inside a gauge view please help me.
After my friends answers in stack overflow i did it like this but it did not works please make it work
 private void drawGauge()
    {
        if (null != mBackground)
        {
           mBackground.recycle();
        }

        /*--For Semi circle put getHeight()/2--*/
        mBackground = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        newBitmap = Bitmap.createBitmap(mBackground.getWidth(), mBackground.getHeight(), Config.ARGB_8888);
        Canvas newCanvas = new Canvas(newBitmap);
        final Canvas canvas = new Canvas(mBackground);
        final float scale = Math.min(getWidth(), getHeight());
        canvas.scale(scale, scale);
        canvas.translate((scale == getHeight()) ? ((getWidth() - scale) / 2) / scale : 0,(scale == getWidth()) ? ((getHeight() - scale) / 2) / scale : 0);

        Paint paintText = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintText.setColor(Color.WHITE);
        paintText.setTextSize(50);
        paintText.setTextAlign(Align.CENTER);
        paintText.setStyle(Style.FILL);
        Rect rectText = new Rect();
        paintText.getTextBounds(captionString, 0, captionString.length(), rectText);
        newCanvas.drawText(captionString, 0, rectText.height(), paintText);

        //canvas.drawText("MedeQuip", 200, 500, shadowpaint);
        //drawRim(canvas);
        //drawFace(canvas);

For vipluv:
 protected void onDraw(final Canvas canvas) {
        drawBackground(canvas);
        final float scale = Math.min(getWidth(), getHeight());
        canvas.scale(scale, scale);
        canvas.translate((scale == getHeight()) ? ((getWidth() - scale) / 2) / scale : 0, (scale == getWidth()) ? ((getHeight() - scale) / 2) / scale : 0);

        if (mShowNeedle) {
            drawNeedle(canvas);
        }

        if (mShowText) {
            drawText(canvas);
        }

        Paint paintText = new Paint(Paint.ANTI_ALIAS_FLAG);
        paintText.setColor(Color.WHITE);
        paintText.setTextSize(150);
        paintText.setTextAlign(Align.CENTER);
        paintText.setStyle(Style.FILL);
        Rect rectText = new Rect();
        paintText.getTextBounds(captionString, 0, captionString.length(), rectText);
        canvas.drawText(captionString, rectText.width(), rectText.height(), paintText);

        computeCurrentValue();
    }

A: In the onDraw() function in their GaugeView.java file, add a canvas.drawText() just before the call to computeCurrentValue().
Use your own Paint object, and make sure you have initialized its textsize and color properties.


text:
Q: Why swagger doesn't see files in public/bundles/hbswaggerui? I use OpenServer (Apache 2.4 + PHP 7.2).
Symfony 4 works correctly, routing works fine.
In /public folder I put .htaccess file.
RewriteEngine On
Options +FollowSymlinks
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule .* index.php [L]

It works.
I installed swagger like here:
https://github.com/harmbandstra/swagger-ui-bundle
I also used assetUrlPath parameter in hb_swagger_ui.yaml
hb_swagger_ui:
  directory: "%kernel.root_dir%/../docs/"
  assetUrlPath: '/public/bundles/hbswaggerui/'
  files:
    - "swagger.json"

url mysite/docs/?url=/docs/file/swagger.json shows white page
console shows:
Refused to apply style from 'http://mysite/docs/swagger-ui.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
?url=/docs/file/swagger.json:36 GET http://mysite/docs/swagger-ui-bundle.js net::ERR_ABORTED 404 (Not Found)
?url=/docs/file/swagger.json:37 GET http://mysite/docs/swagger-ui-standalone-preset.js net::ERR_ABORTED 404 (Not Found)
?url=/docs/file/swagger.json:41 Uncaught ReferenceError: SwaggerUIBundle is not defined
    at window.onload (?url=/docs/file/swagger.json:41)

If I make folder /public/doc/ and move there files from /public/bundles/hbswaggerui/ - it works.
But it should work in folder /public/bundles/hbswaggerui.
Why doesn't?
Should I do some additional Apache settings for rewrite /public/docs to /public/bundles/hbswaggerui ?
No info in manuals about it...

A: You should not set assetUrlPath, remove it from your configuration.