text:
Q: Instrumentation Agent not hooking up to the app My Agent Class
package com.mytransformers;

import java.lang.instrument.Instrumentation;

public class MyTransformerAgent {

    public static void premain(String args, Instrumentation inst) {
        MyTransformer transformer = new MyTransformer();
        inst.addTransformer(transformer);
    }

}

My Transformer:
public class MyTransformer implements ClassFileTransformer{

    public byte[] transform(ClassLoader arg0, String arg1, Class<?> arg2, ProtectionDomain arg3, byte[] arg4)
            throws IllegalClassFormatException {

        // processing to return some bytes/null;
    }

I built my manifest using maven POM and I can confirm that my jar has the following manifest inside META-INF
Manifest-Version: 1.0
Premain-Class: com.mytransformers.MyTransformerAgent
Archiver-Version: Plexus Archiver
Built-By: ha9u63@r
Can-Redefine-Classes: true
Can-Retransform-Classes: true
Class-Path: C:/apache-tomcat-8.5.16/bin/tomcat-juli.jar
Can-Set-Native-Method-Prefix: true
Created-By: Apache Maven 3.0.5
Build-Jdk: 1.8.0_141
Boot-Class-Path: C:/apache-tomcat-8.5.16/lib/tomcat-coyote.jar

I copy both my application jar (simple Hello World 1 line statement) and the agent jar into the same folder and run the following:
java -javaagent:myagent.jar -jar myapp.jar
And I am constantly getting the following error:
Exception in thread "main" java.lang.ClassNotFoundException: com.mytransformers.MyTransformerAgent
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.instrument.InstrumentationImpl.loadClassAndStartAgent(Unknown Source)
        at sun.instrument.InstrumentationImpl.loadClassAndCallPremain(Unknown Source)
FATAL ERROR in native method: processing of -javaagent failed

What else is missing here? I am a bit confused. Is there some classloading delegation which I have broken?
Regards,

A: Hmm... looks like java says that it cannot find class com.mytransformers.MyTransformerAgent in C:/apache-tomcat-8.5.16/lib/tomcat-coyote.jar according your manifest =)
Maybe to add your jar to Boot-Class-Path list like:
Boot-Class-Path: C:/apache-tomcat-8.5.16/lib/tomcat-coyote.jar myagent.jar


text:
Q: Haskell Snap: Session example I've been googling around for an example on how to use Snap session. Nothing so far.
Can someon please point me to an article or something with a simple example of a cookie based session?
A code snippet would be very appriciated.
Something like putting a username in the session and checking for its existence and validity before every request. I looked at Snap.extension.session but I am still too noob to figure out how to use it just from the library code.
I understand that setInSession is the function to put the session value in the cookie but I cant quite figure out how to use it from the signature:
setInSession k v = Map.insert k v `liftM` getSession >>= setSession

or how to glu the whole thing together.
I dont know if it is against the rules to ask for a bit of example code but I would not do it if I could find anything on the net.
Thank you in advance.
--- UPDATE ---
I followed the example below and the links but things are still not comming out right.
I just want a simple test that reads a key and a value and puts it in session cookie then I want to read the session value back and display.
So I initialized my session and put it in the main application state.
s <- nestSnaplet "" sess $ initCookieSessionManager "config/site_key.txt" "sess" (Just 3600)

The first confusion is the key that session initialization fanction needs.
The key is not created during the initial project setup.
So how do I create it?
Where is the key supposed to go in the project file structure so the function can find it?
Then the handlers:
putCookie :: Handler App App ()
putCookie = do
  par <- getPostParams
  let k = T.decodeUtf8 $ head (par ! (B.pack "key"))
  let v = T.decodeUtf8 $ head (par ! (B.pack "value"))
  with sess $ setInSession k v
  heistLocal (bindString "message" "Cookie inserted!") $ render "reply"

This one just reads the key and the value from a web form and it is supposed to put the key value pair in the cookie. Well, apparently it does not.
shCookie :: Handler App App ()
shCookie = do
  v <- with sess $ getFromSession "key"
  heistLocal (bindString "message" (fromMaybe "" v)) $ render "reply"

This one just reads it back and displays. I always get an empty string which means there is no such thing.
Does any of the above look incorrect? Where do I make a mistake?
It all compiles correct but the session cookie is just not there.

A: Does Snap.extension.session means this module? AFAIK the snap-auth package is deprecated.
You can use new session api implemented as snaplet.
Check out an example how to setup your application to use session and auth snaplets. Then you will be able to store data in session:
data App = App
{ _heist :: Snaplet (Heist App)
, _sess :: Snaplet SessionManager
, _auth :: Snaplet (AuthManager App)
}
makeLens ''App

myHandler :: Handler App App ()
myHandler = do
  with sess $ setInSession "key" "value"

ADDED:
File with site key will be created automatically. The function initCookieSessionManager (defined here) uses getKey function from clientsession package (see here). From the docs: If the file does not exist or is corrupted a random key will be generated and stored in that file.
I think your handler doesn't works cos you didn't commit session (see commitSession here) You can commit it in every handler that updates session, or use wrapHandlers and/or withSession to do it automatically.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create a enum field with default value?   types = { # add your custom types here
          'attendance': ('Notconfirmed','Coming', 'Notcoming', 'Maycome',),
          }

  CREATE TYPE attendance AS ENUM types;

The above query creates enum type attendance with enumlabels mentioned in types. How to create a type with default label? In this case the I want to create attendance type with default value Notconfirmed.

A: I was trying the same as you, and I got answer in stackoverflow only, It is possible to create ENUM with default value. Here is what I got for you.
CREATE TYPE status AS ENUM ('Notconfirmed','Coming', 'Notcoming', 'Maycome');

CREATE TABLE t (
    id serial,
    s status default 'Notconfirmed' -- <==== default value
);

INSERT INTO t(id) VALUES (default) RETURNING *;

This worked for me like a charm.

A: In addition to Sudarshan's words...
In case someone needs an example in different schema:
CREATE TABLE schema_name.table_name ( --
    id serial,
    s schema_name.type_name default 'Notconfirmed'::schema_name.type_name
);

A: I am not sure why we need to have below query in our table. I have tried without this line still works.
INSERT INTO t(id) VALUES (default) RETURNING *;


text:
Q: Is it possible to access struct fields from within a trait? Traits are used to group some functions to be implemented from a struct, but is it possible to access struct fields from within the trait?
I could imagine declaring fields inside the trait so that the fields are abstracted as well. I haven't found such a syntax; is there any other solution? Otherwise, it wouldn't be possible to have non-static methods using a trait, would it?
I know object oriented programming from C# and I'm playing around with Rust, trying to adapt the OOP functionality I already know from C#.

A: You can make accessor function in default trait implementation, that must return field value/ref in child implementations, returning default value. Use it in other fn's in default implementation, and redefine accessor's in child implementation. Default implementation fn's will use redefined accessors as it's virtual fn's.

A: This sounds like you're misunderstanding how traits work.  Traits can't have fields.  If you want to provide access to a field from a trait, you need to define a method in that trait (like, say, get_blah).
If you're asking whether you can access fields of a struct from within that struct's implementation of a trait, then yes.  The struct knows it's own type, so there's no problem.
trait Pet {
    fn is_smelly(&self) -> bool;
}

struct Dog {
    washed_recently: bool,
}

impl Pet for Dog {
    fn is_smelly(&self) -> bool {
        !self.washed_recently
    }
}

If you're writing a default implementation of a trait (i.e. defining a method body within the trait), then no, you can't access fields.  A default implementation can only use methods that are defined on the trait or in a super trait.

A: It would be useful to define fields in a trait's default implementation, so a struct implementing the trait would always have the same fields.
Apparently, the Rust team thinks the same but it is still a work in progress according to this RFC. It's a big change and it has been postponed, so I think the short answer is: you can't do it yet, but you might be able to do it in the future.
For now, you'll have to make do with less powerful traits.


text:
Q: Dumping subprcess output in a file in append mode I have to dump the output of a subprocess to a file opened in appended mode
from subprocess import Popen

fh1 = open("abc.txt", "a+") # this should have worked as per my understanding

# fh1.readlines() # Adding this solves the problem

p = Popen(["dir", "/b"], stdout = fh1, shell=True)

print p.communicate()[0]
fh1.close()

The above code however overwrites my file abc.txt which i don't want,  un-commenting fh1.readlines() will move the cursor to appropriate position, which is a temporary solution
Is there anything basic i m missing.
In [18]: fh1 = open("abc.txt",'a')

In [19]: fh1.tell() # This should be at the end of the file
Out[19]: 0L

In [20]: fh1 = open("abc.txt",'r')

In [21]: print fh1.readlines()
['1\n', '2\n', '3\n', '4\n', '5\n']

A: A simple, easy way of puting the cursor at the end of the file, without reading it is using:
fh1.seek(2)
# .seek(offset, [whence]) >> if offset = 2 it will put the cursor in the given position relatively
# to the end of the file. default 'whence' position is 0, so at the very end

A: In my OS X, both python 2.7 and 3.3 work fine.
adylab:Downloads adyliu$ cat ./a.txt
a
b
c
d
e
f
adylab:Downloads adyliu$ python -V
Python 2.7.2
adylab:Downloads adyliu$ python3 -V
Python 3.3.0
adylab:Downloads adyliu$ python -c "print(open('./a.txt','a').tell())"
12
adylab:Downloads adyliu$ python3 -c "print(open('./a.txt','a').tell())"
12

In python doc:

stdin, stdout and stderr specify the executed program's standard
  input, standard output and standard error file handles, respectively.
  Valid values are PIPE, DEVNULL, an existing file descriptor (a
  positive integer), an existing file object, and None. PIPE indicates
  that a new pipe to the child should be created. DEVNULL indicates that
  the special file os.devnull will be used. With the default settings of
  None, no redirection will occur; the child's file handles will be
  inherited from the parent. Additionally, stderr can be STDOUT, which
  indicates that the stderr data from the applications should be
  captured into the same file handle as for stdout.

So the 'Popen' process will not reset the current stream position of the file object.


text:
Q: Meaning: deconstruct (cooking)? In cooking what exactly does it mean to deconstruct something?
Haven't seen this covered much in dictionaries, etc.
edit: as per @Frank's request
this is everywhere in cooking recently:

deconstructed shortcake
deconstructed tiramisu
deconstructed sauce

A: To deconstruct a dish is something of a current fad here in the UK; I put it down to the influence of the popular BBC amateur chef program 'Masterchef'.  A deconstructed tiramisu will comprise a quenelle of mascarpone, a sponge finger, a sprinkling of sugar, some grated dark bitter chocolate and, who the heck knows, a double espresso on the side.  All of this will be artfully arranged on a large plate with lots of white space.  You get all the ingredients of a tiramisu, but without putting the kitchen staff to the terrible effort of combining them into a tiramisu.
So, that's what deconstruction of a dish is all about.
You are entitled to conclude that I am not a fan of deconstructed dishes ...

A: Deconstruction in cooking is a method for taking traditional dishes and reconfiguring them to create new interpretations for modern times. This method was popularized by some of the worlds most famous chefs, most notably Thomas Keller of The French Laundry.
The interpretations can come in many forms.
http://mindofachef.tumblr.com/post/44158113422/behind-the-scenes-spain-david-chang-makes-fideos
If you look at the last picture in this series you will see strawberry shortcake deconstructed. Fresh strawberries, mint cream, and cake that was made with a CO2 can and a microwave. This is a great example of deconstruction in cooking.


text:
Q: debug local asp.net is very slow with Visual Studio 2008 I am trying to run and debug my application using local Web server with VS 2008, it is very slow to load the web page. It's taking about 5 minutes to load the initial page. What could be wrong? I tried on IE and FireFox.

A: First time compilation of your code does take some time - how big is the application? Subsequent loads should take less time. Have you tried setting breakpoints at the entry of your web app to see if it is your code that is slow?


text:
Q: Python3 method not callable due to UnboundLocalError Take into account the following code:
def main():
    print('Calling methodA()')
    methodA()

    print('Calling methodB(True)')
    methodB(True)

    print('Calling methodB(False)')
    try:
        methodB(False)
    except UnboundLocalError as error:
        print(f'--> "UnboundLocalError" raised: {error}')

def methodA():
    print('Running methodA()')
    print('"method_original" in globals(): ' + str('method_original' in globals()))
    method_original()

def methodB(patch_function):
    print(f'Running methodB({patch_function})')
    print('"method_original" in globals(): ' + str('method_original' in globals()))
    if patch_function:
        method_original=method_patched
    method_original()

def method_original():
    print('Running method_original()')

def method_patched():
    print('Running method_patched()')

if __name__ == '__main__':
    main()

It produces the following output:
Calling methodA()
Running methodA()
"method_original" in globals(): True
Running method_original()
Calling methodB(True)
Running methodB(True)
"method_original" in globals(): True
Running method_patched()
Calling methodA(False)
Running methodB(False)
"method_original" in globals(): True
--> "UnboundLocalError" raised: local variable 'method_original' referenced before assignment

Which makes no sense because "method_original" is in globals(). This error can be fixed simply adding global method_original at the beginning of the methodB() but in some cases we have a lot of functions and it could be a pain in the ass to put all of them at the beginning of every method.
Are there any rules to avoid this behavior?
//BR!

A: Let me explain it in a simpler example :
def fn(a):
    if a % 2 == 0:
        x = a
    return x

print(fn(10))  # Fine
print(fn(9))   # UnboundLocalError: local variable 'x' referenced before assignment

In compile time, when interpreter reaches the function, it sees that there is an assignment to x, so it marks x as a "local" variable. Then in "runtime" interpreter tries to find it only in local namespace ! On the other hand, x is only defined, if a is even.
It doesn't matter if it presents in global namespace, now I want to add a global variable named x, to my example:
def fn(a):
    if a % 2 == 0:
        x = a
    return x

x = 50

print(fn(10))  # Fine
print(fn(9))   # UnboundLocalError: local variable 'x' referenced before assignment

Nothing changed. Interpreter still tries to find x inside the function in local namespace.
Same thing happened in your example.
This is to show which variables are "local":
def fn(a):
    if a % 2 == 0:
        x = a
    return x

print(fn.__code__.co_varnames)

co_varnames is a tuple containing the names of the local variables
(starting with the argument names)

Solution:
Either use global (which I see you don't like) , or do not do assignment inside the function, for example change your methodB to :
def methodB(patch_function):
    print(f'Running methodB({patch_function})')
    print('"method_original" in globals(): ' + str('method_original' in globals()))
    if patch_function:
        method_patched()
    else:
        method_original()


text:
Q: redux-form Multiple forms with the same name; how to not override syncErrors I'm using redux-form to manage a wizard-like form. All the forms of the wizard steps have the same name, which was never really a problem, because they were never mounted at the same time.
Now, in one of those steps I have a modal, which opens another form with this name.
This leads to redux-form overriding the syncErrors property, when initializing the second from, so all the errors that were there before opening the modal are now lost.
A quick example:
I have a form with Field1 and Field2, both having errors. Now I open a modal with another form, which renders Field2 and Field3. The error of Field1 has now been removed from the state, even though it's still mounted in the background.
I'd think that the keepDirtyOnReinitialize & enableReinitialize props would circumvent this, but it doesn't seem to work.
Is this the way redux-form is supposed to work? I know it's kinda weird, to have multiple forms with the same name, especially on the same page, but it made a lot of sense until now. Using a different name for the second form solves the problem obviously, but introduces a whole lot of other issues.
Any ideas? Do you think this is a bug?
Thanks alot!

A: Try setting destroyOnUnmount to false to keep the form fields and errors in your redux state.


text:
Q: Create code first poco classes from database I know that I can create the POCO files from .edmx, but this only give's you a part of the code, because if you are going to use code first approach you need to provide more info to the POCO clases for example the key and foreign key by annotations or mapping, Now I was wondering , if exit's some way about how can I created this POCO classes with the annotations from a existing database.

A: what you are describing is not code first, is database first!
here is the answer you need to check: Entity Framework 4.1 - Code First with existing Database, how to define classes, using Attributes or EntityTypeConfiguration? What is the difference?

A: the EF power tools can generate pocos fro your db
link


text:
Q: Embedded c - how to free allocated memory when a program crashes I'm writing a simple bare-metal application on an embedded processor. As part of this application it must allocate some memory on the heap of approx 256kB, using malloc. Note: Originally this was statically allocated in main but at a certain size limit we had to move to dynamic allocation (gcc sliently failed).
The issue is - when the program runs the first time everything works. However if the processor gets reset during execution the pc returns to the start but the program memory still has the heap as it was at the previous execution. So the next time the program runs malloc fails (as malloc's allocation table from the previous run still exists and it thinks the available heap space is already allocated).
So the question is - how do I ensure malloc's table is cleared at the start of main every time I run? Is there a way I can use the location of the heap to zero out some memory (to blank the table) or alternatively get access to the list of pointers malloc has previously returned so I could free them?

A: The heap should be setup in the pre main init code. In a bare metal system there is no system call to allocate heap memory to your program. You might try getting the debugger to start at the first loaded instruction instead of main and see where it sets up the heap. It sounds like your system requires the program be reloaded on a reset to initialize the heap. What system are you using?

A: There is a topic here for exactly this issue:
Microblaze (no OS) - heap not clean after reset
Unfortunately no answer but you are not the first to hit this. I think you have to step through from load in the debugger and see where the init code sets the heap pointer.

A: What on earth are you doing?

*

*At CPU reset you can't rely on anything, you need to initialize everything in the MCU, including stack and RAM setup. This is true for every microcontroller program ever written, bare metal ones in particular. In case you for some reason is using a heap, you need to zero-out the memory before use.

*Using malloc on a bare metal embedded system simply does not make sense. Where you had static .data/.bss variables before, you have a static heap segment instead. The heap solves no problem, it just hides the problem under the carpet.
The main thing here is: either you have enough memory to cover the worst case, or you don't. Period. See this. Or if you are writing a program which is allowed to fail and bug out unexpectedly, you can ignore this.


text:
Q: Assembler GNU: Lowercase to uppercase and vice versa I need to transform any input characters from lowercase to uppercase and vice versa. This currently only reads the input and prints it out. I'm using HEW with GNU for H8S/2600 Series. I'm new to this language so I'm sorry if I'm missing something.
    .h8300s

    .equ    PUTS,0x114
    .equ    GETS,0x113
    .equ    syscall,0x1FF00

    .data
input:  .space  100
prompt: .asciz "Zadejte vstupni data: "

    .align  2
par_input:  .long  input
par_prompt: .long  prompt

    .align  1
    .space  100
stck:

    .text
    .global _start

transform the string here:
transform:

lab1:   rts

_start: mov.l   #stck,ER7
    mov.l   #input,ER2

    mov.w   #PUTS,R0
    mov.l   #par_prompt,ER1
    jsr     @syscall

    mov.w   #GETS,R0
    mov.l   #par_input,ER1
    jsr     @syscall

    xor.l   ER1,ER1

lab2:   mov.b   @ER2,R0L
    cmp.b   #0x0A,R0L
    beq     print
    jsr     @transform
    shll.l  #2,ER1
    shll.l  #2,ER1
    or.b    R0L,R1L
    inc.l   #1,ER2
    bra     lab2

print:
        mov.w   #PUTS,R0
        mov.l   #par_input,ER1
        jsr     @syscall
        jmp @lab3

lab3:   jmp @lab3


text:
Q: Error handling in Swift AWSPolly Every example of AWSPolly I can find says:
// Again, we ignore the errors in the example.
For example:
https://github.com/awslabs/aws-sdk-ios-samples/blob/master/Polly-Sample/Swift/PollySample/ViewController.swift
I cannot figure out how to handle the errors. What if internet service drops out and Polly can't be accessed. I'd like to use the internal voice. But I can't figure out.
I checked:
 awsTask.isCanceled || awsTask.isFaulted
But neither of them are true if Internet service is not available.


text:
Q: History pushstate and fallback for IE9 problems I use history.pushstate to load content and have a fallback for IE9 and prior, but im having issues that i cant find working solutions for by googling. Ive read a lot of posts on the topic, but most of them seems to be missing important information -  I should say that I'm not JavaScript/jQuery-expert at all.
I know that its possible to use routers like Backbone.js, History.js, Path.js etc - this is not what im looking for - id would like to fully understand how to set up the code in my own script.
Im posting ALL of the code except styling - this might be of help to others trying to acchieve a working solution for AJAX loading with pushstate + fallback.
Issues with the history.pushstate (the .."if" in script):

*

*How do i rewrite the URL making it possible to bookmark and do a page refresh?

Issues with the fallback method (.."else" in script):

*

*URL changes in IE9 when pressing back-/forward-buttons, but content
doesnt reload - how can i reload the content using the existing
code?

*How do i rewrite the URL making it possible to bookmark and
do a page refresh?

On top of that, im having trouble adressing pages placed in a subfolder (and sub-sub-folder) - where do i put the ("/") in my existing code?
I know especially the URL rewriting may not have a simple answer - i have tested with some .htaccess mod_rewrite on WAMP, but i cant make it work - im missing something in the process..
Heres the working script i have so far:
$(document).ready(function(){

if (typeof(window.history.pushState) == 'function') {

// AJAX-LOADING
$('a').click(function() {
    var page = $(this).attr('href');

    history.pushState({ path: (page + ".html")}, '', page);     // ("/") - url for absolute links in subfolders where?
    $("#content").load(page + ".html");
    return false;
});

// BACKBUTTON
$(window).bind('popstate', function(event) {
    var state = event.originalEvent.state;
    if (state) {
        $("#content").load(state.path);
    }
});

//  FALLBACK IE9
} else {
$('a').click(function() {
    var page = $(this).attr('href');

    window.location.hash = page + ".html";
    $("#content").load(page + ".html");
    return false;
});

} // END of if.. and else..

}); // END DOC READY

This is the index.html:

this is index.html

Load page 1

Load page 2

Load here.....

page1.html is:

 page 1 - this is

page2.html is:

 this is the 2. page


text:
Q: How to determine applications whose application master ran on current node in YARN? Suppose I have a program running on given node in cluster, in that program is it possible to get list of applications whose application master ran on current node?
One way I could figure out till now is by querying RM REST API from the program and getting applications list and comparing 'amHostAddress' with the current node address but I want to avoid polling RM API. I am looking for a way in which I can get this information locally without contacting master node.
Can anyone help me please?


text:
Q: Access profile images of the people from their twitter account in Android I have Android application, which have directory module and it list out some of the contacts. Now I want to fetch profile image of each contact person from their Twitter account and for that I have their twitter username too. How I can fetch it in Android?
I have already tried with this but getting no success.
imageView.setImageDrawable(readDrawableFromNetwork("https://api.twitter.com/1/users/profile_image?screen_name=twitterapi&size=bigger"));

A: this is the relavent API for twitter Twitter API  we can get json from this , by using json string we can do what ever you want. for profile image use this json object : profile_image_url you can get iamge url. by using url get image drawable.

A: I tried below code and it is working now
String twitterURL = "https://api.twitter.com/1/users/profile_image?screen_name=#screen_name#&size=normal";
twitterURL = twitterURL.replace("#screen_name#", twitterScreenName);
imageView.setImageDrawable(readDrawableFromNetwork(twitterURL));

I also tried with below code and it is also working but I am not sure which one is best for the performance and recommended too.
URL urlImg = new URL(twitterURL);
InputStream in = new BufferedInputStream(urlImg.openStream());
Bitmap bm = BitmapFactory.decodeStream(in);
imageView.setImageBitmap(bm);

Thanks RajaReddy P :)


text:
Q: MySQL workbench: multiple windows MySQL workbench is a fantastic tool. However, I'm having a hard time figuring out how to create multiple windows. For example, in Sequel Pro (or TablePlus or really any other SQL client) I can have multiple windows:

Yes I know there are 'tabs' but those aren't quite the same thing. Is there a way to have multiple windows using MySQL Workbench?

It seems like from a few other threads this would need to be done manually via:
$ open -n -a MySQLWorkbench.app

A: MySQL Workbench is originally designed to be a single instance app only. On Windows this has been extended to allow multiple instances (there's a setting in the preferences) and you found a way to do this on macOS. However this bears some risks, because all instances share the same config and cache files and can write simultaneously to them, which is prone to file corruption. Also, any changes done to the configuration or connections end up in the same file, so the last change may override previously made changes in another instance.


text: Q: How do i call a function everytime my entry is updated I am trying to make a program, where i need to update something everytime, the user types in the entry. However I cant seem to find out how. Is it possible?


text:
Q: Decomposing the homology of a connected sum of surfaces in a way which highlights the combinatorics of gluing For each $i = 1,2$ and $j = 1,\ldots,n$, let $C_{i,j}$ be a connected compact oriented surface with $k$ boundary components. For $i = 1,2$, let $C_i = \sqcup_{j=1}^n C_{i,j}$, and let $C$ be the closed orientable surface obtained by attaching cylinders connecting boundary components of $C_1$ to those of $C_2$.
I would like to decompose $H_1(C)$ as a direct sum of $A_1,A_2,B$, where $A_1,A_2$ are related to $H_1(C_1),H_1(C_2)$, and $B$ is related to the combinatorics of how the various components of $C_1,C_2$ are glued together. If $\Gamma$ denotes the component graph of $C$ (it has $2n$ vertices corresponding to the components $C_{i,j}$ and $nk$ edges corresponding to the cylinders), then $h_1(\Gamma) = nk-2n+1$. Mayer-Vietoris shows that
$$h_1(C) = h_1(C_1) + h_1(C_2) - 2n + 2$$
Thus if $\overline{C_1},\overline{C_2}$ denote the closed surfaces obtained by "capping" the boundary holes, then $h_1(C_i) = h_1(\overline{C_i}) + nk - n$. Thus we have
$$h_1(C) = h_1(\overline{C_1}) + h_1(\overline{C_2}) + 2(nk-2n+1) = h_1(\overline{C_1}) + h_1(\overline{C_2}) + 2h_1(\Gamma)$$
This "decomposition" of Betti numbers is helpful because it indicates that the homology of the glued surface $C$ comes from cycles in $\overline{C_1}$ and $\overline{C_2}$, together with the $h_1(\Gamma)$-many cycles coming from loops in the component graph, together with another $h_1(\Gamma)$-many cycles which come from "loops around the cylinders". In fact I want to think of the contribution of $2h_1(\Gamma)$ as somehow identifying the associated homology classes in $H_1(C)$ with the homology of the boundary of a tubular neighborhood of $\Gamma$ embedded in 3-space. Let $\partial N_\Gamma$ denote this boundary. This space records the combinatorics of the gluing data.
I'd like some way of making this precise. While Mayer-Vietoris gives a decomposition of the number $h_1(C)$ into a sum of things that are of the desired form "$A_1$", "$A_2$", "$B$", I would like to construct natural maps between the homology groups that realize this. In other words, I'd like to define in a natural way an isomorphism
$$H_1(\overline{C_1})\oplus H_1(\overline{C_2})\oplus H_1(\partial N_\Gamma)\stackrel{\cong}{\longrightarrow} H_1(C)$$
I'm sure this must be discussed somewhere in the literature, so references would also be appreciated!


text:
Q: surefire HeapDumpOnOutOfMemoryError When running my unit tests in Maven on windows i'm getting an OutOfMemory exception. I tried to add -XX:-HeapDumpOnOutOfMemoryError option to the surefire argLine, but no dump file is generated.
I also tried to add the same thing to MAVEN_OPTS, but still nothing, I simply get an OutOfMemory exception and the process hangs until I manually kill it.
My pom is as follows:
<plugin>
    <artifactId>maven-surefire-plugin</artifactId>
    <configuration>
        <testFailureIgnore>false</testFailureIgnore>
        <argLine>-Xms512m -Xmx512m -XX:PermSize=256m -XX:-HeapDumpOnOutOfMemoryError</argLine>
        <forkMode>once</forkMode>
    </configuration>
</plugin>

MAVEN_OPTS:
set MAVEN_OPTS=-XX:-HeapDumpOnOutOfMemoryError

Do you have any idea why no dump file is generated?

A: You're using "-" to disable the option. Use "+" to enable it:
<argLine>... -XX:+HeapDumpOnOutOfMemoryError</argLine>
                 ^

A: Try this:
set MAVEN_OPTS="-Dmaven.surefire.debug=\"-XX:-HeapDumpOnOutOfMemoryError\""

A: Your memory leak might just be fixed, see http://jira.codehaus.org/browse/SUREFIRE-495. You may want to try surefire 2.7.1 or newer.

A: I think you forget the path :
    <argLine>-Xms512m -Xmx512m -XX:PermSize=256m -XX:-HeapDumpOnOutOfMemoryError  -XX:HeapDumpPath=/tmp</argLine>

with this argument :
     -XX:HeapDumpPath=/tmp


text:
Q: How to get sushi coins faster? I just started this game and as in almost every 2nd Kairosoft game you first have to find out how this and that works. Now I learned that the sushi coins (the special currency as in every kairosoft game) is again really important and you should take care of getting them really quickly and in particular get a lot of them!
So I noticed customers generate them at for example vending machines or by paying the bill. But I get the coins really randomly and it seems to me that they are very rare.
Is there a way to get the coins faster for example by making the customers more saitisfied with the food or is there a special time when every customer generates a coin or anything like that?

A: In order to generate Sushi Coins (SC), you need to use interior objects as you said. I found out that the best way to get a lot of sushis coins is to do all the PR missions and make two L shaped belts with the facilities inside the square formed by the two L-shaped belts. This allows to have most of the customers have a facility nearby and you can also put decorations that boost many facilities at once. I also use quality boosters on the facilities after upgrading the belt, which seems to help a lot.
SCs allow you to develop better sushis and are essential for projects such as training staff. A list of facilities that can generate SC are:

*

*Capsule machine

*Fish library

*Flower arrangement corner

*Commercial parlor

*Toy counter

*Petting zoo

*Print Machine

Contests are also a way to earn sushi coins. According to the guide below:

If you do not win a contest, you will be awarded a consolation prize of Sushi Coins, equivalent to 10 x the difficulty of the contest. Upon winning a contest, you will be awarded a bonus prize of Sushi Coins, in addition to the regular prize, which is equivalent to 50 x the difficulty of the contest.

This is taken from the website: http://adeptgamer.com/forum/pages/the-sushi-spinnery-guide/


text:
Q: Prove the following limit (only use the limit epsilon delta definition) I would like to prove the following statement,
$$\lim_{n\to\infty} \frac{20\sqrt{n-1}}{3n^2} = 0$$
And I am aware that I want to get to $\,\frac{20\sqrt{n-1}}{3n^2}<\epsilon\,$ (epsilon) and then solve for n. However, I don't know how to simplify the expression to solve for n.....

A: Hint:
$$\frac{20\sqrt{n-1}}{3n^2}<\frac{20\sqrt n}{2n}=\frac{10}{\sqrt n}$$

A: Hint: Multiply the fraction by $$\frac{1/\sqrt{n}}{1/\sqrt{n}}=1$$and recall that $\sqrt{1-1/\sqrt{n}}<1$. This leaves you with your limit as $$0<\frac{20\sqrt{n-1}}{3n^2}<\frac{20}{3n^{3/2}}.$$ The first inequality follows from the fact that all terms are positive, and the second inequality from the observation above. Now, if you can show the limit on the right is zero, the limit in the middle must be zero by the squeeze theorem.


text:
Q: photo gallery for CKEditor I need to integrate a photo gallery to the CKEditor.
I have a list of albums to be shown on the page. I need to have an custom icon in the CKEditor, which shows the list of albums on click of that. I need to have an option to select the album and show the album inside the page as  like Galleria.
I need to be able to show the gallery between the actual content something like Sample.
Any Ideas on this?

A: I'm afraid you have to program your own plugin. I don't know any plugin that do what you want. An alternative idea is to use a file browser like PWE to allow users to choose images in a server folder.


text:
Q: Different results on different machines - casting decimal to double static void Main(string[] args)
{
    double a = 222.65;
    double b = 0.056124761669643426;
    double c = (double) ((decimal) a*(decimal) b);
}

Why these calculations give different results on different operating systems?
This part gives always the same result:
((decimal) a*(decimal) b)

After casting to double I get either:
12.496178185746102

or
12.496178185746105

My problem is that this minor change has big impact on the result and tests fail.
Now important information:

*

*Project is built with .NET 4.0 on the same machine.

*Both machines have got .NET 4.0 and .NET 4.5.2 installed.

*Projects are run as x86 application.

*The first result I get on machines with Windows 7, Windows Server 2003, Windows Server 2008 installed.

*The second result I get on machines with Windows Server 2012, Windows 10 installed.

*I am not sure about CLR version but I suppose it comes with .NET so should be the same.

It seems that something changed after Windows 8, Windows Server 2012 (both were released together). I've always thought that results may be impacted only by .NET version. Any ideas?
Edit: Due to misinformation from my side there is an example:
 double a = 222.65;
 double b = 0.056124761669643426;
 double c = (double) ((decimal) a*(decimal) b);

  double result = Process(c) <- doing something very complicated

Assert.That(result,expectedResult,tolerance=1E-8) <- here is an impact


text:
Q: How to fix "DistributionNotFound: The 'jsonschema' distribution ..." in ipython When in a virtual environment (venv) with jsonschema 3.0.1 installed, trying to import jsonschema from ipython results in the following error.
(venv) COMPUTER:prj user.name$ ipython
/usr/local/Cellar/ipython/7.5.0/libexec/lib/python3.7/site-packages/IPython/core/interactiveshell.py:925: UserWarning: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
  warn("Attempting to work in a virtualenv. If you encounter problems, please "
Python 3.7.3 (default, Mar 27 2019, 09:23:15)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help.

[ins] In [1]: import jsonschema
---------------------------------------------------------------------------
DistributionNotFound                      Traceback (most recent call last)
<ipython-input-1-a1a01cfa025e> in <module>
----> 1 import jsonschema

~/prj/venv/lib/python3.7/site-packages/jsonschema/__init__.py in <module>
     31
     32 from pkg_resources import get_distribution
---> 33 __version__ = get_distribution(__name__).version

/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py in get_distribution(dist)
    479         dist = Requirement.parse(dist)
    480     if isinstance(dist, Requirement):
--> 481         dist = get_provider(dist)
    482     if not isinstance(dist, Distribution):
    483         raise TypeError("Expected string, Requirement, or Distribution", dist)

/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py in get_provider(moduleOrReq)
    355     """Return an IResourceProvider for the named module or requirement"""
    356     if isinstance(moduleOrReq, Requirement):
--> 357         return working_set.find(moduleOrReq) or require(str(moduleOrReq))[0]
    358     try:
    359         module = sys.modules[moduleOrReq]

/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py in require(self, *requirements)
    898         included, even if they were already activated in this working set.
    899         """
--> 900         needed = self.resolve(parse_requirements(requirements))
    901
    902         for dist in needed:

/usr/local/lib/python3.7/site-packages/pkg_resources/__init__.py in resolve(self, requirements, env, installer, replace_conflicting, extras)
    784                     if dist is None:
    785                         requirers = required_by.get(req, None)
--> 786                         raise DistributionNotFound(req, requirers)
    787                 to_activate.append(dist)
    788             if dist not in req:

DistributionNotFound: The 'jsonschema' distribution was not found and is required by the application

python -c 'import jsonschema' works.

A: As the warning suggests, running the following commands fixes the issue:
(venv) COMPUTER:prj user.name$ pip install ipython
(venv) COMPUTER:prj user.name$ venv/bin/ipython
Python 3.7.3 (default, Mar 27 2019, 09:23:15)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.5.0 -- An enhanced Interactive Python. Type '?' for help.

[ins] In [1]: import jsonschema

[ins] In [2]:


text:
Q: ggcorrplot, multiple columns, grouped by factor My data looks the following way
data = data.frame(
Group = sapply(1:5, function(x) paste0("G", x)),
Y = runif(100, min=1, max=3),
X1 = rnorm(100, 100, 10),
X2 = rnorm(100, 20, 8)
)

What I want is to plot the correlations with ggcorrplot between (X1, Y), (X2, Y) for the groups 1:5
i.e the correlation plot should look like this
        (X1,Y)   (X2, Y)
     G1
     G2
     G3
     G4
     G5

what I have tried:
correlate <- data %>%
group_by(Group) %>%
summarise(r = cor(cbind(X1,X2), Y))

 #Groups:   Group [5]
  Group   r[,1]
  <chr>   <dbl>
  1 G1    -0.472
  2 G1    -0.0375
  3 G2     0.0385
  4 G2     0.0248
  5 G3     0.0232
  6 G3     0.507
  7 G4    -0.180
  8 G4    -0.452
  9 G5    -0.264
 10 G5     0.297

I get the values, but I have to know myself that the first is for (X1, Y) and the second (X2, Y) isn't there some nice way to do it automatically? and how could I plot those values with ggcorrplot?

A: Provided I understood you correctly, how about the following (making use of patchwork::wrap_plots)
library(ggcorrplot)
library(patchwork)
library(tidyverse)

df <- data %>%
    group_by(Group) %>%
    nest() %>%
    mutate(plot = map2(data, Group, ~ggcorrplot(.x) + ggtitle(.y)))

df$plot %>%
    wrap_plots(ncol = 1)

Sample data
set.seed(2020)
data = data.frame(
    Group = sapply(1:5, function(x) paste0("G", x)),
    Y = runif(100, min=1, max=3),
    X1 = rnorm(100, 100, 10),
    X2 = rnorm(100, 20, 8)
)


text:
Q: A word for when you are almost crying, but not quite yet? You know how sometimes you want to cry, but do not cry.  Maybe a few tears are shed, but you mostly just choke up.  The urge to cry is there, perhaps overwhelmingly, but you suppress it somehow and don't actually cry.
Is there a word for this state?  I've always used "crying" but it really isn't quite crying yet.

A: The "Coffee Talk" sketches from (US) Saturday Night Live popularized the Yiddish word verklempt, which describes this pretty well. Dictionary.com defines it as:

overcome with emotion; clenched

A: Good single-word suggestions by John and others.
In case you're open to phrases, you're

fighting back tears

or choking back/blinking back/swallowing tears

A: The ones that immediately come to mind:
You could be: Teary,  Tearful,  Weepy,  Misty-Eyed.  Perhaps you are about to 'tear up', or are 'tearing up'.  Perhaps tears are about to 'well up' or are 'welling up'.

A: You could have

"On the verge of tears"

Which implies that you are very close to tears, but not quite; perhaps displaying some emotion

A: As you mentioned, "choked up" is a perfectly good phrase for this.
Feeling choked up means feeling "a lump in your throat" and the sensation of being about to start crying.
Similarly, to "choke back" tears or sobs means to fight against the urge to cry.

A: You are misty-eyed.

crying a little, or feeling that you might cry [MacMillan]

A: The phrase: 'to feel tears welling up,'
is commonly abbreviated to 'welling up.'
an informal usage, discussed in this informal conversation
http://www.usingenglish.com/forum/threads/127389-I-m-welling-up

A: Really the most common way to describe when you're experiencing this feeling is to simply say "I'm going to cry", or "I'm about to cry", or even "I could cry". The single word solutions in other answers are technically correct, but I've never heard any of them used in conversation, just in literary narrative.

A: I believe "lacrimose" is usable in this context. Readily available definitions seem to contain "inclined to weep," "given to shedding tears," etc.

A: How about upset?

very sad, worried, or angry about something

It might be a little too generic, but it's a good fallback that covers a lot of situations.

She was so upset when she didn't pass the audition that she almost started to cry.

A: "Wussy"
Note this term is more commonly used to describe a 'full cry state' especially when the cry-er is male and even more particularly when the onlooker point-of-view is also that of a man.  However, surveys of majority male populations are likely to indicate the point at which the word "Wussy" may be applied is of significantly less magnitude than 'full crying' with some going as far as to approve any contexts in which thoughts of crying persist in the mind for times exceeding a second or two.

A: Although I'm aware that you specifically asked for a "word" answer, I don't think there is a specific single word that really nails it. My advice is to use a sentence as a description. Words in concert have the power to make a more vivid picture in the mind of the reader than a single word would do. If I was telling a story, I might say:
"I felt my throat tighten and a tear came to my eye, but I kept myself from crying."
A listener/reader gets a vivid impression of how I felt. This makes the impression all the stronger and more relate-able.


text:
Q: ¿Cómo optimizar el llamado a Directions API (Google) en una aplicación de taxi? Buen día a todos,
Estamos desarrollando una aplicación de taxi de la cual tenemos la mayor parte desarrollada, sin embargo, quisiéramos optimizar los costos de Google Maps Platform.
Antes de comentar mi duda, resumo la lógica de la aplicación luego de haber revisado videotutoriales y cursos que te orientan para el desarrollo de apps de taxi:

*

*Luego de que la aplicación tiene el LatLng del punto de partida y de destino. Se hace un llamado a la webservice de Directions API para obtener los puntos de la ruta que formarán el polyline en la aplicación.

*Cuando el conductor se dirige a recoger al cliente o cuando inicia el viaje desde el punto de partida al destino, a medida que cambia la posición del conductor, la aplicación tiene que ir haciendo llamados a Directions API para obtener este nuevo polyline y dibujar en el mapa (Ver imagen).

*Según los precios de Google Platform (Ver aquí), con el caso supuesto de que un viaje promedio tenga 10km de distancia daría y la aplicación use 5 metros de precisión, tendría como resultado aproximadamente 2000 solicitudes y sin considerar que lo mismo lo tiene que ver el cliente. Esto no resulta rentable puesto que lo que cobraría Google sería más de lo que se le cobraría al cliente.
Entonces mi pregunta es:
¿Cuál sería la mejor manera para evitar tantas llamadas a Directions API?
¿Se podría reducir a solo una llamada por viaje?
PD:
Pensamos que se podría ir quitando los points de un polyline e ir refrescando el mapa, pero no sabemos como se podría identificar que el vehículo está pasando por ese polyline, ya que los GPS tienen un margen de error que no es muy exacto.


text:
Q: What is the difference between "man" and "info" documentation? Regarding man-pages and info help documentation:
Why do two such similar sources of documentation exist?
Sometimes a man-page is available and the info is not; or vice-versa.
I haven't yet latched on to the rhyme and reason behind it.
Maybe there is a significant difference between them, but even if there is, why do they both exist?  It seems like unnecessary doubling up.

A: Info is the default format for documentation inside the GNU project, man is the much older traditional format for UNIX.
Info uses Texinfo as its source format, which is a bunch of macros for TeX, and that makes it much easier to also create "good-looking" printed versions or PDFs.
Generally, manpages are more about 1 specific topic (a command, a config file, a system function, ...) while info normally has more the structure of a combined manual, more like a book.

A: man uses less to display the manual page which in turn uses vim keybindings while info uses emacs keybindings and standard emacs commands for search, quitting etc.

A: Man pages are the UNIX traditional way of distributing documentation about programs.  The term "man page" itself is short for "manual page", as they correspond to the pages of the printed manual; the man pages "sections" (1 for commands, 2 for system calls, etc.) correspond to sections in the full UNIX manual.  Support is still there if you want to print a man page to paper, although this is rarely done these days, and the sheer number of man pages make it just impossible to bind them all into a single book.
In the early '90s, the GNU project decided that "man" documentation system was outdated, and wrote the info command to replace it: info has basic hyperlinking features and a simpler markup language to use (compared to the "troff" system used for man pages).  In addition, GNU advocates against the use of man pages at all and contends that complex software systems should have complete and comprehensive documentation rather than just a set of short man pages.
There are actually other documentation systems in use, besides man and info: GNOME and KDE have their own, HTML-based system, etc.
In the end, the form in which you get documentation depends on the internal policies of the project that provided the software in the first place -- there is no globally accepted standard.


text:
Q: Jsoup wrap text with HTMLTag I have the following sample text

This is (within brackets jsoup a text).

This is a text (hint: plz note) with a sample

This is a text (hint: plz note with a sample

This is a text (hint: plz note) with a sample (nothing)

I need to wrap the brackets into a new HTML Tag, e.g. . I need to wrap ONLY the brackets which

*

*has matching pairs

*has a Tag with data-attribute-id inside the brackets

The resulting HTML text should look like

This is (within brackets jsoup a text).

This is a text (hint: plz note) with a sample

This is a text (hint: plz note with a sample

This is a text (hint: plz note) with a sample(nothing)

I know that I can select the required element with some kind of regexp for the brackets \(\) and than the containing attribute. So I can select with the following selector the proper element:
Elements elements = doc.select(":matchesWholeOwnText(\((.?)*\)):has([data-attribute-id])");

The problem I'm facing now is that e.g. the first element is a
. I can wrap it easily with el.before("<span...") but that's way to much. I just need to wrap the brackets.
Is there a way to replace the HTML-text within an Element (easily)?


text:
Q: #2002 - The server is not responding (or the local MySQL server's socket is not correctly configured) I am trying to study how stuff works in mysql.
This is under localhost using wamp. So I renamed ibdata1 in the mysql data folder, and restarted. Mysql will automatically create a new ibdata1 file.I start phpmyadmin and I saw this error. So i delete the new ibdata1 and paste the old ibdata1(the one I renamed, i rename it back to ibdata1 and paste it on mysql data folder), and I still see this error. How can I solve this?

A: I had that problem, i searched the web and found out that mysqld is not running, what i did is i opened the mysql and mysqld from the mysql directory, and checked if the mysqld and mysql processes are running, then i tried to connect..


text:
Q: Pymongo - Get a Nested Collection and Updating it I want to find a nested collection in my MongoDB database and update it from Pymongo. Here is how my document tree is structured:
{
    "name_list" : [
        {
            "_id" : ...,
            "name" : "Joe Edwards",
            "aliases" : [
                "Allen Dingus",
                "Edward McPickles"
            ]
        },

        ...
    ]
}

The collection I wish to access is aliases. Currently, my code uses the find() function to locate the element in the name_list with the name key of "Joe Edwards". What I'm getting in return is a cursor object; that is expected. However, I cannot find a way to access the aliases collection and update it (I'm looking for something like db.name_list.find(...)[0].aliases.update(...) so that I can just manipulate aliases directly).
I've looked over the PyMongo documentation and a lot of posts on Stack Exchange as well but I found nothing similar. My temporary fix is just to access the name_list and update the whole document belonging to "Joe Edwards", but it isn't really elegant. Can someone please help?
Thanks.

A: MongoDB tries to align the operators of the drivers (Pymongo included) with the operators for the mongo shell. In the best case, the mongo shell operation looks exactly like the Pymongo version of the command. So if you can't find an operator that you need, chances are you may be able to find it in the Operator documentation page
Regarding your question, depending on what you want to do, there are a couple of options available to you:
Updating an existing array element
This can be done using the $ update positional operator:
db.name_list.update_one({'aliases':'Allen Dingus'}, {'$set': {'aliases.$': 'Alias 1'}})

Note the aliases.$ operation, which will update an alias of "Allen Dingus" and replace it with "Alias 1". With your example document, this will result in:
{
  "_id": ...,
  "name": "Joe Edwards",
  "aliases": [
    "Alias 1",
    "Edward McPickles"
  ]
}

Adding a new array element
This can be done using the $push operator or the $addToSet operator:
db.test.update_one({'aliases':'Allen Dingus'}, {'$push': {'aliases': 'Alias 2'}})

This will search for an alias "Allen Dingus" and add the new entry into the array. With your example document, this will result in:
{
  "_id": ...,
  "name": "Joe Edwards",
  "aliases": [
    "Allen Dingus",
    "Edward McPickles",
    "Alias 2"
  ]
}


text:
Q: What happened to swing labs or swingx-ws? JXMapKit for Java I am new to java and have been looking at few tutorials around GIS or geogrpahical GUI java applications.
Many of them mention and seem to require swingx-ws or swing labs componet and classes.
I have managed to track down some old versions, but they dont seem to have the desired affect in my Jform application.
Basically when I try and drag and drop after adding the .jar to my libraries folder I get the stop smoking sign (joke) or rejected symbol.
I have also added the components to the palette through palette manager and they appear once selected, but when I attempt to add I am shown a javja no class error.
Alot of the links in the tutorials seem to send me to dead sites and are pretty old.
Basically my question is. Is swingx-ws still an active option for adding mapping functionality to java gui apps? And if not, are there any other alternatives?
Thanks in advance
This is the tutorial I am trying to follow.

A: I don't know what features you are looking for, but take a look at JMapViewer and see if it will do the trick.

A: Outdated answer, there are much newer options out there:
I have used JOSM as a library of map components, but as it is not its intended use, it may not be quite straight forward.
You can also use gvSIG2 as a library of map components. They rearranged the code on this version(2) to make it simpler to use gvSIG as a library, but this version is still on a beta phase.

A: A couple years late, but here is the answer you were looking for:
Internal link to Stack Overflow Q&A


text:
Q: Pulsing an LED with no series resistor I have a basic circuit using a BJT common emitter which I have constructed to pulse a red LED on to use as a strobe with 1us ON time (@12V) and plenty of time to cool down (<< 1% duty cycle). The pulse is coming from an Arduino MEGA 2560.
Initially I was running it with a series resistor as it that is the way I have been taught is 100% necessary when using LED's, however I have been testing without one, and it is pulsing brighter (measuring using a photodetector) and not burning out.
Just wondering what kind of lifetime I could expect from operating a LED in a manner like this, or any other effects that I should be aware of. And also if I am correct in assuming that the internal resistance of a LED is on the order of 10 ohms?
I am  90% sure this is the datasheet for the LED.
http://www.jaycar.com.au/products_uploaded/ZD1790%20-%20TLCR5800.pdf
Thanks

A: Unqualified - nothing is ever "100% necessary".
Driving LEDs directly from energy sources without any great knowledge of what controls the current and how much current flows, will sometimes work well enough in many cases*, but in many cases at other times it may work inadequately, and may lead to destruction or early death of LED or energy source (the Arduino in this case). ie the likelihood is that results will not be guaranteed repeatable or predictable. If you don't know whether it will work in a predictable manner then it's predictable that it may work in an unknown manner.
It may be acceptable to do what you are doing and possibly even designable, but if you do not know if it is or isn't then it isn't.
The "saving grace" in many cases is the combination of "facts" that

*

*most microcontrollers do not have enough drive capability to destroy an LED in a very short time span, and

*most microcontrollers will often not be damaged by the overload presented by a directly connected LED and

*most microcontrollers will often not malfunction or not malfunction especially badly when abused beyond their designers recommendations in this manner.
As the above "grace statements" contain qualifiers such as "in a very short time", most, often not, not malfunction especially badly etc , one is on shaky ground at best if you rely on such things.
The qualified statement goes something like

*

*If you want the LED to live long and prosper, and

*the Arduino to live long and prosper, and

*the circuit to be "designable" so it works ~= the same every time you build it
THEN

*

*you MUST control the current in some manner

AND

*

*a series resistor is an approximate but often good enough way of doing this.

A: Something is limiting the current in your diode, no single LED would survive 12V across its terminals for 1us.
I suspect that you drive the collector current into its limit. Are you able to measure the residual voltage across CE? Is it really close to 0V?
WRT "internal resistance of a LED", there is no such thing. Check figure 4 of the datasheet, it shows I/V (inverse resistance) which isn't linear. You can calculate a "differential resistance" at a given point on the curve (the tangent at this point), but this is only valid for small variations of V.

A: This paper has some interesting details on overdriving LEDs at very high multiples (20x) of their rated current for short periods on the order of 1 microsecond. It's oriented around power LEDs rather than indicators as you're using, but the conclusions should be generally sound.
In short, the mechanism by which LEDs are typically destroyed is overheating. At 20 times rated current over one microsecond, not nearly enough power is dissipated to destroy an LED via overheating, so as long as the duty cycle is very low, the LED will survive just fine. They didn't find any indications of gradual failure through repeated spikes of high amplitude.
At extremely high (>20x rated) current spikes, the failure mechanism was the bond wires melting due to high inrush currents from the device's parasitic capacitance.
So, the short answer is that if this works a few times, it'll likely continue to work. How much current you're actually conducting depends on the LED's IV curve, and the range you're operating in is likely far outside that provided for in the datasheet, so you'd need to determine it experimentally.
Note, though, that you're operating the LED well outside the "absolute max" limits of the datasheet, so there's absolutely no warranty on how it will actually behave - only what experimental evidence you can gather. If this is a useful part of your design, fine, but if it's just to avoid having to add one series resistor, I'd suggest that this is a poor place to be trying to skimp on components.

A: Directly driving an LED from a microcontroller's IO pin with no resistor is not usually a good idea.  However, there are caveats:

*

*The IO pin has a maximum current it can source. That limits what the LED can get

*Draw too much current from the IO pin and it overheats and burns out

*Allow too much current through the LED and it overheats and burns out

The ATMega chips usually have a maximum of 40mA per pin, with a recommended maximum of no more than 25mA.  A typical LED has a steady-state current of around 20mA.  But, LEDs also often have a rated pulse current limit.
For instance, a cheap 3mm red LED has a maximum forward current of 30mA and a pulse current of 100mA at a 10% duty cycle limit, and an on-time of less than 100µs.
So by pulsing the LED at a higher current (say 40mA), as long as you are within a 10% duty cycle, and the pulses are less than 0.1ms long (which means a PWM frequency [50% duty] of no less than 1000Hz) would be well within the specifications of the LED.
What effect would it have on the IO pin?  Well, over time the current draw would be around a tenth of the peak, since it's only on for a tenth of the time.  However, that doesn't mean that it dissipates a tenth of the power.  Most power is dissipated during switching, and with all that extra switching going on it's going to be dissipating much more power.  That may, or may not, depending on how the pin is constructed, negate the benefits of the pulsing.
Either way, it is still good practice to include a small resistance. Not to protect the LED, but to protect the IO pin.  Just enough to keep the current below the absolute maximum for the IO pin.

Edit:
I didn't notice you are using a BJT.  The above still applies though, but with slight differences:

*

*You should use a resistor to limit the current to the pulse current limit for the LED, or

*You should use the BJT to set the current by controlling the current in from the IO pin that controls it.

A: I did something similar, but for much shorter pulses in the range of 5-10ns.
The LEDs I had were rated to 20mA@3.7V or similar. I used a capacitor of 150pF which was charged up to 12V and then discharged via the LED and a fast transistor. The measured currents were up to 1A. The duty cycle was... well, too small to call it duty cycle. (a few pulses per second)
As I was also concerned about life time of the LED, I measured the light output while pulsing the LED with 90kHz over 40 days. I could not notice any degradation of the LED performance.
But OK, you want to drive the LED for a much longer time.
One point you should care about is if the driving circuit is fail safe. It is fine if your LED survives your 1us pulses, but if your Arduino switches the LED on for a long time by accident, the LED will be destroyed.


text:
Q: Geb session keeping example I am searching for a simplest working example of implementing geb that will keep session.
I read Mantain session between tests using Geb still it is not ready to use example.
Session keeping of logging cookies is practical in most of tests so it should be easy to follow example. If easy solution exist with other webdriver releated technology it could also be interesting to know.
import org.openqa.selenium.firefox.FirefoxDriver
import geb.Configuration
import geb.Browser
import org.openqa.selenium.WebElement
import org.openqa.selenium.remote.RemoteWebDriver
import org.openqa.selenium.By

Browser browser = new Browser(driver: new FirefoxDriver())
browser.getConfig().autoClearCookies=false;
browser.getDriver().get("http://mypage.com/login")

browser.getDriver().findElement(By.id("user_login")).sendKeys("admin")
browser.getDriver().findElement(By.name("user_pass")).sendKeys("admin");
browser.getDriver().findElement(By.name("user_pass")).submit();

Still I can not connect to browser with autenticated cookie, I has to provide password every time(site use cookies veryfication and in normal browser it is keeped).


text:
Q: 1px gap between divs on HiDPI display http://jsfiddle.net/p959zse4/3/
I've got a progress bar with a "fill" area and an image that caps the end of it. On Chrome 38, win8 with a hiDPI/retina screen, there's a 1px gap between the progress bar and the arrow image that caps the bar. It depends on where the bar is positioned, sometimes there's no gap. Is there any standard way to remove this gap?
Also, I'm using the css transition property to animate changes in width, and the gap seems to flicker during the transition.

.progress {
    width: 100%;
    background-color: lightgray;
    height: 20px;
}

.fill {
    display: inline-block;
    height: 20px;

    transition: width 1s;
    background: linear-gradient(to right, #d0d9d8 0%, rgb(237, 28, 36) 100%)
}

.arrow {
    display: inline-block;
    width: 10px;
    height: 20px;
    background-image: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAAUCAIAAADUTlA/AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAFiUAABYlAUlSJPAAAAAaSURBVChTY3gro4IfjapARaMqUBE9VMioAABP/AK8RcGPowAAAABJRU5ErkJggg==")
}

A: My coworker's theory is that the issue is I'm using a percentage width which ends up being a fraction of a pixel, and if we could somehow round up/down the width to an exact pixel the gap wouldn't appear.
Anyways, my solution ended up being adding an extra line of pixels on the left edge of the image, and adding margin-left: -1px; to the arrow image so it covers the gap when it appears.


text:
Q: Prevent C preprocessor to do a specific macro subsitution How can I tell the preprocessor not to replace a specific macro?
The specific problem is the following: Windows header files define the GetMessage macro.
My C++ header files with my API have a GetMessage method. I do not want to rename my method. But when using the API on Windows, including windows.h replaces my GetMessage method call with GetMessageA.

A: have you tried just doing an
#undef GetMessage
or even
#ifdef GetMessage
#undef GetMessage
#endif
and then calling the windows GetMessageA or GetMessageW directly, whichever is appropriate.
you should know if you are using char* for wchar_t8..
(thanks don.neufeld)
Brian also says that
Jus some useful info, you can also use the #pragma push_macro/pop_macro to push and pop macro definitions. This is great if you want to override a macro definition in a block of code:
#pragma push_macro("GetMessage")
#undef GetMessage

// Your GetMessage usage/definition here

#pragma pop_macro("GetMessage")

I suspect this is an MS specific feature though, so keep that in mind.

A: (GetMessage)(...)
GetMessage on MSDN

A: Jus some useful info, you can also use the #pragma push_macro/pop_macro to push and pop macro definitions. This is great if you want to override a macro definition in a block of code:
#pragma push_macro("GetMessage")
#undef GetMessage

// Your GetMessage usage/definition here

#pragma pop_macro("GetMessage")

I suspect this is an MS specific feature though, so keep that in mind.

A: Is there code that calls both your GetMessage and Window's GetMessage?
Such code won't be able differentiate between the two of them.  You won't be able to call both in the same file.
If you use one function in one file and the other in another file, just do the suggested #undef in one file.

A: Given your constraints as outlined in your comment, the only way you can do this is to do a:
#undef GetMessage

right before the call to your API's GetMessage. (And this assumes noone after this point in the source file is calling the Win32 GetMessage.)


text:
Q: How can I have a aws iot rule-engine type of scenario in Azure IoT hub? I actually wanted a conditional statement varying an output. For example, if temperature<0 do something, likewise if temperature>50 do something. I wanted to know how is it possible to have this conditional case in Azure Iot? What should i follow? What term should I be looking for? Please help.

A: You can query the IoT Hub messages flow in real time using Stream Analytics.  You'll write a SQL like query with your condition (temperature<0) that will then send a message to an output like an Event Hub message queue or write to a database.


text:
Q: Receiver () has no segue with identifier I have no idea and have tried renaming the story board, cleaning the project, changing simulators. I cannot get my by segue to work.
I have a manual modeling segue from ViewController (A) to ViewController (B), called "MoveToLogin".
What happens is when you click the login button, I create a new instance of a custom object I made that contains a log in method like so:
#ViewController.m
//If the username and password fields are not blank, attempt to log in.
        [_custom object loginUser:_usernameTxt.text password:_passwordTxt.text]

#custom object's login method (CustomObject.m)
-(void)loginUser:(NSString *)username password:(NSString *)password
{
    ViewController *viewcontroller = [[ViewController alloc]init];

    //Attempts to log in the user
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    NSDictionary *params = @ {@"username" : username, @"password": password};
    [manager POST:_login_url parameters:params
    success:^(AFHTTPRequestOperation *operation, id responseObject)
    {
        if([responseObject objectForKey:@"login_okay"])
        {
            _valid_login = YES;
            [viewcontroller onSuccessfulLogin];
        }
        else
        {
            _valid_login = NO;
            [viewcontroller onInvalidLogin];
        }
    }
          failure:
     ^(AFHTTPRequestOperation *operation, NSError *error) {
         [viewcontroller onRequestFail];
     }];
}

As you can see the custom object's method, which is in another class obviously, upon receiving a json response from the server calls ViewController (a) method onSuccessfulLogin.
That method looks like so:
-(void)onSuccessfulLogin
{
    //if we get a successful login
    [self performSegueWithIdentifier:@"MoveToLogin" sender:nil];
}

But whenever I successfully log in, I am presented with this pleasant message:

terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: 'Receiver () has no segue with identifier 'MoveToLogin''

A: You cannot create an instance of viewcontroller like you are doing..  In general it is good to have your async methods use blocks/delegates..
How about doing something like this using a completion block..
    #ViewController.m
    //If the username and password fields are not blank, attempt to log in.
     [_customobject  loginUser:@"" password:@"" completionBlock:^(BOOL validLogin, NSError *error) {
        if(error){
            [self onRequestFail];
        }else{
            if(validLogin){
                    //if we get a successful login
                 [self performSegueWithIdentifier:@"MoveToLogin" sender:nil];
            }else{
                //if we get a invalid login
            }
        }
    }];

    #custom object's login method (CustomObject.m)
    -(void)loginUser:(NSString *)username password:(NSString *)password completionBlock:(void (^)(BOOL validLogin, NSError *error))completionblock{

        //Attempts to log in the user
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        manager.requestSerializer = [AFHTTPRequestSerializer serializer];
        manager.responseSerializer = [AFJSONResponseSerializer serializer];
        NSDictionary *params = @ {@"username" : username, @"password": password};
        [manager POST:_login_url parameters:params
        success:^(AFHTTPRequestOperation *operation, id responseObject)
        {
            if([responseObject objectForKey:@"login_okay"])
            {
                _valid_login = YES;
                if (completionblock) completionblock(YES, nil);
            }
            else
            {
                _valid_login = NO;
                if (completionblock) completionblock(NO, nil);
            }
        }
              failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             if (completionblock) completionblock(NO, error);
         }];
    }


text:
Q: How to post a form to self? I have a page which is accessible via a url - something like this http://websitename/index.php?q=pagename. On this page, I have a form that I would like to submit to the same page so that I could do some post processing. I have tried the following things but couldn't get it to work -
<form name="formname" action="pagename.php" method="post">
<form name="formname" action="" method="post">
<form name="formname" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post">

In other words, I would like to submit the form to pagename.php file (where the form resides). The page (pagename.php) is not directly accessible. How do I get this done? I will greatly appreciate any help on this one. Thanks.

A: Try this:
In HTML5 you can just do <form> and its set to self.
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">

OR
<form name="formname" id="mainForm" method="post" enctype="multipart/form-data" action="<?php echo $_SERVER['REQUEST_URI'];?>">

OR
<form method="POST" action="<?=($_SERVER['PHP_SELF'])?>">

The point is your $_SERVER variable contains all the information you would require to generate that specific page's URL. If you have decided not to go with the HTML5 way, then one of these options should work. Otherwise you're missing something else not mentioned in your question.

A: i think this will solve your problem
<form name="formname" action="#" method="post">

A: Try
 <form method="post">/*your stuff here*/</form>

and you should add a submit button with attribute "name=submit" so the form could be submitted also track if its have been posted with php then do your actions like below
 if(isset($_POST["submit"])){ /* your code */}


text:
Q: Unity3d android plugin capabilities I have little experience with Unity3d and checking my possibilities:
Say i write android plugin for unity
My requirements:

*

*Display different android layouts with WebView which run html-5.

*Run android activities while using png assets

*Intercept android device UI touches

Is this something that can be implemented in unity as an android plugin?
Thanks for the help

A: Basing on your requirements, I suppose that you'd like to create native Ads or something like that which is perfectly doable.

*

*It is possible to pause Unity Game and display another activity. It's also possible to show WebView as this activity.

*I don't understand this fully but I guess you wanted to use PNG assets and display them. If I'm correct then yes, it's possible, you can bundle PNG assets as resources and them bundle into JAR.

*UI Touches are collected by activity that is currently being displayed.


text:
Q: How to remove a parenthesis from a cellvalue in sql? I have a cell value (-4.00), where i want to replace the parenthesis '(', ')' with space or nothing at all, but it gives me error.
I tried Replace(Replace(cellvalue, ')', ' '),'(', ' ') but the error that I get is

Number value '' is not recognised.

A: You could use TRANSLATE:
SELECT cellvalue,
       TRANSLATE(cellvalue::STRING, '()', '  ') AS paranthesis_removed,
       TRY_CAST(paranthesis_removed AS NUMBER) -- if cast needed
FROM Tab


text:
Q: Disabling characters other than numbers in scanf in C The problem I have is that I want to disable the user the possibility of putting character instead of number inside my program and optionally printing the message "it is disabled". It should ask for the value of the same variable. I tried to do this using this:
scanf(" %[0-9]d",&x);

and this:
else
       result = scanf("%*s");

but it still does not work. What should I look for? I've searched internet, but I've only found solutions for C++ in which cin was used and unfortunately it does not work in C at all.

A: You can try something like this:
char c[SIZE];
int i;

// While the string is not a number
while(fgets(c, SIZE , stdin) && !isAllDigit(c));

where isAllDigit is:
int isAllDigit(char *c){
    int i;
    for(i = 0; c[i] != '\0' && c[i] != '\n'; i++) // Verify if each char is a digit
       if(!isdigit(c[i]))         // if it this char is not a digit
           return 0;              // return "false"

    return 1; // This means that the string is a number
}

A: scanf isn't used much anymore as it is completely unsuitable for keyboard input. The basic scheme these days is to do fgets() + validate + sscanf() in a loop.


text:
Q: Within Delphi XE6 FTP GET() statement does not return after download finished I have a problem with the idFTP Indy component trying to download a file from our server.  It downloads 99% of the file, and then just hangs.  The GET statement doesn't return.  All that has changed recently is that we've moved from Desktops running win 8.1 to laptops running win10.  If I write the progress and the full file size to the screen it downloads rather quickly until right at the end, and the last bytes just doesn't finish.  The file I'm trying to download is 15,573,350 Bytes.  It gets to about 14MB (rather quick) and stops.  I've tried downloading another file, and it's the same thing.
Any ideas?
Here is the code, there is nothing fancy about it.  I've copied it from our working app to try and test it, to see if it was something within the main project.
  with IdFTP1 do
  begin
    Host :=  'xxx';
    Username := 'xxx';
    Password := 'xxx';
    passive := True;
    Connect;
    ChangeDir('Service_Update');
    ChangeDir('QA');
    Self.Caption := Size('jam.zipper').tostring;
    TransferType := ftBinary; //tried with and without
    Get('jam.zipper','jam.zipper',true);
    Button1.Caption := 'Done'; //never gets here
  end;

A: There are many ways Get() could freeze as you have described. Some ways include:

*

*the server does not close the transfer connection gracefully at the end, or the server is not sending a final FTP response message on the command connection after the transfer is finished. Use a packet sniffer to verify.  To handle this, try assigning a non-infinite ReadTimeout on both command and transfer connections.

*If the FTP session passes through a router/firewall that is not FTP-aware, the command connection may timeout and be dropped during a lengthy transfer. To handle this, TIdFTP has a NATKeepAlive property to configure TCP keep-alives on the command connection during transfers.

*If you are using TIdFTP in a worker thread with event handlers that make unsynchronized calls to UI controls, this can cause all kinds of problems, including deadlocks. Always sync access to the UI.


text:
Q: ggplot2: Replace legend keys and sort alphabetically I'm producing a set of graphs in two languages with ggplot2 (Hadley Wikham). I could produce them in two separate workflows by renaming variables inside the original dataset. Instead, I wish to modify a ggplot object: I wish to first produce the graphs in English and then translate the labels into French. How could/should I change the legend keys inside the ggplot object? And how can I then sort the legend keys?
The reason I am exploring this approach is that I would like my plot colours and symbols to be the same in English and French, while at the same time having the legend keys ordered alphabetically. The problem is that French and English legend keys do not have the same alphabetical order (Spain versus Espagne). Compare the legend keys obtained from the MWE: the legend keys are ordered alphabetically in the English legend, but incorrectly in the French legend.

Replacing the xlab, ylab, ggtitle, and modifying the styles of the axes labels (e.g. number formatting) is rather straightforward, so my focus really is on the legend keys and their order of listing inside the legend.
A MWE  with lots of names to illustrate the tediousness of having to copy names several times in the approach below (once to group, another time for colour, and again for shape, etc.):
    df <- structure(list(year = c("2006", "2007", "2006", "2007", "2006",
    "2007", "2006", "2007", "2006", "2007", "2006", "2007", "2006",
    "2007", "2006", "2007", "2006", "2007", "2006", "2007", "2006",
    "2007", "2006", "2007", "2006", "2007", "2006", "2007", "2006",
    "2007", "2006", "2007", "2006", "2007", "2006", "2007", "2006",
    "2007", "2006", "2007"), country = c("Australia", "Australia",
    "Austria", "Austria", "Belgium", "Belgium", "Canada", "Canada",
    "Denmark", "Denmark", "Finland", "Finland", "France", "France",
    "Germany", "Germany", "Greece", "Greece", "Italy", "Italy", "Japan",
    "Japan", "Netherlands", "Netherlands", "New Zealand", "New Zealand",
    "Norway", "Norway", "Portugal", "Portugal", "Spain", "Spain",
    "Sweden", "Sweden", "Switzerland", "Switzerland", "United Kingdom",
    "United Kingdom", "United States", "United States"), value = c(33,
    33, 33, 33, 30, 30, 34, 34, 30, 30, 33, 33, 28, 29, 27, 27, 40,
    39, 35, 35, 35, 35, 27, 27, 33, 33, 27, 27, 37, 37, 32, 32, 31,
    31, 32, 31, 32, 32, 33, 33)), .Names = c("year", "country", "value"
    ), row.names = c(NA, -40L), class = "data.frame")

    library("ggplot2")
    ggplot(data = df, aes(x = year, y = value, group = country, colour = country)) +
        geom_line(size = 0.5) + geom_point(size = 1)
    ggsave(last_plot(), file = "stackoverflow-1.png")

    ggplot(data = df, aes(x = year, y = value, group = factor(country, labels = c("Australie", "Autriche", "Belgique", "Canada", "Danemark", "Finlande", "France", "Allemagne", "Grèce", "Italie", "Japon", "Pays-Bas", "Nouvelle-Zélande", "Norvège", "Portugal", "Espagne", "Suède", "Suisse", "Royaume-Uni", "États-Unis")), colour = factor(country, labels = c("Australie", "Autriche", "Belgique", "Canada", "Danemark", "Finlande", "France", "Allemagne", "Grèce", "Italie", "Japon", "Pays-Bas", "Nouvelle-Zélande", "Norvège", "Portugal", "Espagne", "Suède", "Suisse", "Royaume-Uni", "États-Unis")))) + geom_line(size = 0.5) + geom_point(size = 1) + theme(legend.title = element_blank())
    ggsave(last_plot(), file = "stackoverflow-2.png")

I would like to have a method that would not break if I use only a subset of the variables (countries in the example). The most convenient and less error-prone would be to define a mapping like this:
list("A Cuckoo Land" = "Un Pays Idyllique", # This mapping is not used
 "Australia" = "Australie",
 "Austria" = "Autriche",
 "Belgium" = "Belgique",
 "Canada" = "Canada",
 "Denmark" = "Danemark",
 "Finland" = "Finlande",
 "France" = "France",
 "Germany" = "Allemagne",
 "Greece" = "Grèce",
 "Italy" = "Italie",
 "Japan" = "Japon",
 "Netherlands" = "Pays-Bas",
 "New Zealand" = "Nouvelle-Zélande",
 "Norway" = "Norvège",
 "Portugal" = "Portugal",
 "Spain" = "Espagne",
 "Sweden" = "Suède",
 "Switzerland" = "Suisse",
 "United Kingdom" = "Royaume-Uni",
 "United States" = "États-Unis")

and substitute, within the legend keys, every occurrence of the left-hand side by the right-hand side. (even better if the method can handle a trilingual approach, e.g. a mapping like "Belgium" = c("Belgique", "Bélgica").

A: I might actually approach this by creating a list of data frames with the same column names, but with the country names in different languages. Creating the list of data frames might be a bit of work if there are a lot of them, but I'm fairly certain it will be less cumbersome than mucking about in with grobs and gtables. An example:
key <- unlist(list("A Cuckoo Land" = "Un Pays Idyllique", # This mapping is not used
                   "Australia" = "Australie",
                   "Austria" = "Autriche",
                   "Belgium" = "Belgique",
                   "Canada" = "Canada",
                   "Denmark" = "Danemark",
                   "Finland" = "Finlande",
                   "France" = "France",
                   "Germany" = "Allemagne",
                   "Greece" = "Grèce",
                   "Italy" = "Italie",
                   "Japan" = "Japon",
                   "Netherlands" = "Pays-Bas",
                   "New Zealand" = "Nouvelle-Zélande",
                   "Norway" = "Norvège",
                   "Portugal" = "Portugal",
                   "Spain" = "Espagne",
                   "Sweden" = "Suède",
                   "Switzerland" = "Suisse",
                   "United Kingdom" = "Royaume-Uni",
                   "United States" = "États-Unis"))
df_eng <- df
df_fra <- df
df_fra$country <- unlist(key[df_eng$country])

dfs <- list('english' = df_eng,'french' = df_fra)

library("ggplot2")
#Now you can create one "default" plot...
p <- ggplot(data = dfs[['english']],
            aes(x = year, y = value,
                group = country, colour = country)) +
  geom_line(size = 0.5) +
  geom_point(size = 1)
print(p)

#And simply swap out the data frame...
p %+% dfs[['french']]

A: In this answer to my own question, I would like to detail further tweaking based on joran's answer, for the record and/or further discussions.
To summarize, the purpose is: to generate sets of graphs in 2 languages with consistent colors, shapes, linetypes, and so on, across the 2 sets of graphs. The difficulty is that ggplot orders by the levels, but the labels of the levels have a different alphabetical order in the 2 languages, e.g.: one expects "Spain" to be listed towards the end of the list in English, as it starts with the letter S, but near the beginning in French, as "Espagne" starts with the letter E.
In the following, I create a country factor with labels written in English and ordered according to the English alphabetical order, and a country.fr factor with labels written in French and ordered according to the French alphabetical order. The same logic would apply to shapes, line types, fill, etc.. My code is a little and various shortcuts are no doubt possible.
    ### Create a fixed assignment for colors, shapes, linetypes, etc.
    ### The same for both the English and French versions
    ### Data
    df <- structure(list(year = c("2006", "2007", "2006", "2007", "2006",
    "2007", "2006", "2007", "2006", "2007", "2006", "2007", "2006",
    "2007", "2006", "2007", "2006", "2007", "2006", "2007", "2006",
    "2007", "2006", "2007", "2006", "2007", "2006", "2007", "2006",
    "2007", "2006", "2007", "2006", "2007", "2006", "2007", "2006",
    "2007", "2006", "2007"), country = c("Australia", "Australia",
    "Austria", "Austria", "Belgium", "Belgium", "Canada", "Canada",
    "Denmark", "Denmark", "Finland", "Finland", "France", "France",
    "Germany", "Germany", "Greece", "Greece", "Italy", "Italy", "Japan",
    "Japan", "Netherlands", "Netherlands", "New Zealand", "New Zealand",
    "Norway", "Norway", "Portugal", "Portugal", "Spain", "Spain",
    "Sweden", "Sweden", "Switzerland", "Switzerland", "United Kingdom",
    "United Kingdom", "United States", "United States"), value = c(33,
    33, 33, 33, 30, 30, 34, 34, 30, 30, 33, 33, 28, 29, 27, 27, 40,
    39, 35, 35, 35, 35, 27, 27, 33, 33, 27, 27, 37, 37, 32, 32, 31,
    31, 32, 31, 32, 32, 33, 33)), .Names = c("year", "country", "value"
    ), row.names = c(NA, -40L), class = "data.frame")

    ## Create a unique country ID and a language map
    key <- read.table(textConnection("
    AUS,Australia,Australie
    AUT,Austria,Autriche
    BEL,Belgium,Belgique
    CAN,Canada,Canada
    CHE,Switzerland,Suisse
    DEU,Germany,Allemagne
    DNK,Denmark,Danemark
    ESP,Spain,Espagne
    FIN,Finland,Finlande
    FRA,France,France
    GBR,United Kingdom,Royaume-Uni
    GRC,Greece,Grèce
    ITA,Italy,Italie
    JPN,Japan,Japon
    NLD,Netherlands,Pays-Bas
    NZL,New Zealand,Nouvelle-Zélande
    NOR,Norway,Norvège
    PRT,Portugal,Portugal
    SWE,Sweden,Suède
    USA,United States,États-Unis"),
    sep = ',', stringsAsFactors = FALSE)
    names(key) <- c('country.code', 'country.name', 'country.name.fr')
    ##  Check the types of data
    ##  ! Make sure country is a 'string' not a 'factor' !
    ##  ! otherwise, the 'translation' will be incorrect !
    str(key)
    ##'data.frame': 20 obs. of  3 variables:
    ## $ country.code   : chr  "         AUS" "         AUT" "         BEL" "         CAN" ...
    ## $ country.name   : chr  " Australia" " Austria" " Belgium" " Canada" ...
    ## $ country.name.fr: chr  " Australie" " Autriche" " Belgique" " Canada" ...

    ## Create a unique code variable for each country
    df$country.code <- NA
    matched <- match(df$country, key$country.name)
    df$country.code <- ifelse(is.na(matched), df$country, key$country.code[matched])

    ## translate country name with translation key
    df$country.fr <- NA
    matched <- match(df$country, key$country.name)
    df$country.fr <- ifelse(is.na(matched), NA, key$country.name.fr[matched])

    ## Set the country names to be factors (they are currently strings)
    ## function as.factor orders alphabetically
    # English
    df$country <- as.factor(df$country)
    View(df)
    # French
    df$country.fr <- as.factor(df$country.fr)
    View(df)

    ## Define some colors (here manually combining Set1 and Set3 of RColorBrewer)
    ## The Palette could also have been embedded in the key dataframe earlier...
    colorPalette <- c("#E41A1C", "#377EB8", "#4DAF4A", "#984EA3", "#FF7F00", "#FFFF33", "#A65628", "#F781BF", "#999999","#8DD3C7", "#FFFFB3", "#BEBADA", "#FB8072", "#80B1D3", "#FDB462", "#B3DE69", "#FCCDE5", "#D9D9D9", "#BC80BD", "#CCEBC5", "#FFED6F")
    length(colorPalette)  # Make sure we have enough colors
    ## [1] 21

    ## Set the colors to each country within the dataframe
    ## There is no need for that, but I felt it was idiot-proof
    names(colorPalette) <- levels(df$country)
    df$colors <- NA
    matched <- match(df$country, names(colorPalette))
    df$colors <- ifelse(is.na(matched), NA, colorPalette[matched])
    ##'data.frame': 40 obs. of  6 variables:
    ## $ year        : chr  "2006" "2007" "2006" "2007" ...
    ## $ country     : Factor w/ 20 levels "Australia","Austria",..: 1 1 2 2 3 3 4 4 5 5 ...
    ## $ value       : num  33 33 33 33 30 30 34 34 30 30 ...
    ## $ country.code: chr  "AUS" "AUS" "AUT" "AUT" ...
    ## $ country.fr  : Factor w/ 20 levels "Allemagne","Australie",..: 2 2 3 3 4 4 5 5 6 6 ...
    ## $ colors      : chr  "#E41A1C" "#E41A1C" "#377EB8" "#377EB8" ...

    ### Make the English plot
    ##  use the country factor to order variables
    library("ggplot2")
    p <- ggplot(data = df, aes(x = year, y = value,
                    group = country, colour = country)) +
      geom_line(size = 0.5) +
      geom_point(size = 1) +
      guides(colour = guide_legend(ncol = 2))
    p

    ### Swap out the colors with custom scheme using scale_colour_manual
    ## To ensure correct mapping, use named vectors in scale_colour_manual
    colors <- df$colors
    names(colors) <- df$country
    str(colors)
    ## Named chr [1:40] "#E41A1C" "#E41A1C" "#377EB8" ...
    ## - attr(*, "names")= chr [1:40] "Australia" "Australia" "Austria" "Austria" ...

    p + scale_colour_manual(name = "country", values = colors)

    ### Make the French plot
    ##  use the country.fr factor to order variables
    colors.fr <- df$colors
    names(colors.fr) <- df$country.fr
    str(colors.fr)
    ##Named chr [1:40] "#E41A1C" "#E41A1C" "#377EB8" ...
    ## - attr(*, "names")= chr [1:40] "Australie" "Australie" "Autriche" "Autriche" ...
    p <- ggplot(data = df, aes(x = year, y = value,
                    group = country.fr, colour = country.fr)) +
      geom_line(size = 0.5) +
      geom_point(size = 1) +
      guides(colour = guide_legend(ncol = 2))
    p

    p + scale_colour_manual(name = "pays", values = colors.fr)

Here the corresponding legends side by side:


text:
Q: Different results for same mathematical operations I encountered a strange behaviour in simple Python operations. It happens with power operation with two specific numbers:
print(-0.5660330877786267 ** 0.5515471713326932)
a = -0.5660330877786267
b = 0.5515471713326932
print(a ** b)

The outputs are unexpectingly not the same:
-0.7306015753489663
(-0.117797331106763+0.7210426136411876j)

Dose someone have an idea why this happens?
This happens with Python 3.8.1 on Windows. I tried both ** operator and pow function.

A: This is because
print(-0.5660330877786267 ** 0.5515471713326932)

is actually
print(-(0.5660330877786267 ** 0.5515471713326932))

You can learn about operator precedence in the documentation

A: -0.5660330877786267 ** 0.5515471713326932 is not equivalent to (-0.5660330877786267) ** (0.5515471713326932). Because of the relevant precedence rules, it is equivalent to -(0.5660330877786267 ** 0.5515471713326932), which of course has a different result.
With the pow function call, of course, the arguments are necessarily evaluated before the function is called, so it doesn't matter whether the values come from variables or literals.


text:
Q: what to do with page fault from copy_from_user()? I have the following system call:
long do_print(int n, char *p){
  char tmp[n]; //allocate array of n bytes
  int ret = copy_from_user(tmp,p,n);
  if (!ret){
    //do something with tmp
  }
  return ret;
}

which return non-zero value for n>5000 (I reckon because of page fault).
How do I force the copy to be successful. In other words, what do I do if the system call return non-zero value?

A: Allocating a big array on the stack is not something you should, or really can do. The linux kernel operates with a small stack, usually 2 memory pages. Equally more dangerous is this if your char tmp[n]; relies on an n that comes from user space, letting user space potentially crash the kernel. In a situation such as this, you'll have to dynamically allocate memory instead of using a buffer on the stack.
As to what you'll do if copy_from_user() fails, the user has lied to the kernel, and passed something wrong down to the kernel.
The normal way to handle that is to bail out of whatever you're performing, and pass -EFAULT back up to user space.


text:
Q: Using SUMIFS Function or Alternative Across Multiple Columns Let's say that I have the following in an Excel spreadsheet, in the same row:
joe hs  12  joe college 234 joe hs  12

My objective was to use a SUMIFS function that parses through each column, identifies whether or not "hs" appears, and, if that condition is met, adds the number following it. In this case, the sum would appear as 24.
I tried doing this using SUMIFS, but hit a wall. I then tried implementing the following array formula:
{=SUM(IF((B1:B1="hs")+(E1:E1="hs")+(H1:H1="hs")),A1:I1,0)}
This returned #VALUE!, and I don't understand why.
Any help would be deeply appreciated. I checked around, but have not been able to find an example that matches my dilemma.

A: Assuming that the data you have is in A1:I1, you can use
=SUMPRODUCT((A1:I1="hs")*1,B1:J1)


text:
Q: How to enable / disable Bluetooth in all android versions via ADB looking for a way to enable / disable BT through ADB in all versions of android (or just to know from which version it was changed and to do accordingly).
What I did is :
(get android version is function I wrote to get the android version).
private final String disableBT = " shell am broadcast -a io.appium.settings.bluetooth --es setstatus disable";
if(Integer.parseInt(getAndroidVersion(udid)) > 9){
            sendCommands(udid, disableBTFromV10);
            sendCommands(udid, keyEvent22);
            sendCommands(udid, keyEvent22);
            sendCommands(udid, keyEvent66);
        }
        else {
            sendCommands(udid, disableBT);
        }

sendCommands is actually through ADB and terminal.
still not something that it is 100%.
Thanks


text:
Q: Establishing synchronized music streaming across devices I am attempting to stream audio files from a server to iOS devices and play them completely synchronized. For example on my phone I might be 20 secs into a song and then my friend next to me should also be 20 secs into the song as well. I know this is not an easy problem to solve, but I am attempting to do so.
I can currently get them within one second of each other by calculating the difference in time between the devices and then have them sync up, however that is not good enough because the human ear can detect a major difference in a second and this is over WIFI.
My next approach is going to be to unicast the one file from the server and then have the all devices pick it up directly from the server and then implement some type of buffer system similar to netflix so that network connectivity would be a limiting factor. http://www.wowza.com/ is what I would use to help with that.
I know this can be done, because http://lysn.in/ is does it with their app and I want to be able to do something similar.
Any other recommendations after I try my unicast option?
Would implementing firebase help solve a lot of the heavy lifting problems?

A: (1) In answer to ONE of your questions (the final one):
Firebase is not "realtime" in "that sense" -- PubNub is probably (almost certainly) the fastest "realtime" messaging for and between apps/browser/etc.
But they don't mean real-time in the sense of real-time, say, as race game engineers mean it or indeed in your use-case.
So firebase is not relevant to you here and won't help.
(2) Regarding your second general question: "how to synchronise time on two or more devices, given that we have communications delays."
Now, this is a really well-travelled problem in computer science.
It would be pointless outlining it here, because it is fully explained here http://www.ntp.org/ntpfaq/NTP-s-algo.htm if you click on "How is time synchronised"?
So in fact, to get a good time base on both machines, you should use that!  Have both machines really accurately set a time to NTP using the existing (perfected for decades) NTP synchronisation.
(So for example https://stackoverflow.com/a/6744978/294884 )
In fact are you doing this?
It's possible that doing that will solve all your problems; then just agree to start at a certain exact time.
Hope it helps!

A: I would recommend against using the data movement to synchronize the playback. This should be straightforward to do with a buffer and a periodic "sync" signal that is sent at a period of < 1/2 the buffer size. Worst case this should generate a small blip on devices that get ahead or behind relative to the sync signal.