text:
Q: open new tab on submitting html form from function called on anchor tag click event in angular-5 I have below requirement in angular-5, where i have navigation/anchor tag link and on anchor tag click event i am calling function "gotoApp1()", that function submitting HTML form programmatically to open application/website in new tab with same user session("keyField" in code is treated session here).
HTML code:

...
...
...
...

  <form id="app1" method="post" stype.display="none" target="_blank">
    <input id="key" name="key" type="hidden" [(ngModel)]="keyField">
    <input id="timeOut" name='timeOut' type="hidden" [(ngModel)]="timeOutField">
  </form>

      Container
      App-1
      App-2

Code behind file i.e. typescript(.ts) file:
export class MajorComponent implements OnInit {

private keyField:string;
private timeoutInterval = 2000; // seconds

ngOnInit() {
    // here making another service call to load some app data, this service calls is not related to our problem/requirement
}

gotoApp1() {
        this._service.getApp1Key().subscribe(key => {
          const myform = document.getElementById('app1') as HTMLFormElement;
          myform.action = key.app1Link;
          this.keyField = key.accessKey;
          this.timeOutField = this.timeoutInterval.toString(); // time out in seconds
          myform.submit();
        });
    }

gotoApp2() {
        ...
        ...
        ...
    }
}

Problems:

*

*When i do click on "App-1" anchor tag/link it just refreshes page
first time and if i clicked again or second time it is opening the new app
in new tab.

*I think angular takes time to load value of "input" tag or happens somethings wrong.

Any body have faced this situation and how to fix this?
Note: So requirement is here, new tab should be open when i click first time on link "App-1". Also no any logs found on console.

A: Switch your anchor tag to
<button class="nav-item" type="button" (click)="gotoApp1()">App-1</button>

Most probably you see sharp (#) at the end of your url.
It is not proper to use anchor if you do not use href attribute. You are waiting a button behaviour from an anchor. But there are hacky ways.
href="javascript:void(0);"

or (click)="gotoApp1($event)" and inside the function
    gotoApp1(event) {
      event.preventdefault();
      ...
    }

A: After some effort i found solution to open new tab on submitting html form from function which is called on anchor tag click event,
HTML code:

    ...
    ...
    ...
    ...

      <form #app1 id="app1" method="post" stype.display="none" target="_blank" [action]="appLink">
        <input #key id="key" name="key" type="hidden">
        <input #timeOut id="timeOut" name='timeOut' type="hidden">
      </form>

          Container
          App-1
          App-2

.ts code:
export class MajorComponent implements OnInit {

private appLink:string;
private timeoutInterval = 2000; // seconds
@ViewChild('app1') app1: ElementRef;
@ViewChild('key') key: ElementRef;
@ViewChild('timeOut') timeOut: ElementRef;

ngOnInit() {
    // here making another service call to load some app data, this service calls is not related to our problem/requirement
}

gotoApp1() {

        this._service.getApp1Key().subscribe(key => {
          const myform = this.app1.nativeElement;
          const keyField = this.key.nativeElement;
          keyField.value = key.accessKey;
          const timeOutField = this.timeOut.nativeElement;
          timeOutField.value = this.timeoutInterval.toString(); // time out in seconds
          myform.submit();
        });
    }

gotoApp2() {
        ...
        ...
        ...
    }
}

i think problem is with href attribute, here i am opening new tab on form submission through a function, so removed the href attribute and in typescript code use ElementRef from angular/core instead using document.getElementById() method of DOM, to set the values which is required on form submission, so not required to bind it on HTML.


text:
Q: How to use SimplePie laravel package to display rss feed? I want to display news from the given rss feed url. But I am not getting anything in data section. Below is the code I tried from https://github.com/willvincent/feeds and replaced the url.
public function demo() {
    $feed = Feeds::make('https://timesofindia.indiatimes.com/rssfeeds/296589292.cms);
    $data = array(
      'title'     => $feed->get_title(),
      'permalink' => $feed->get_permalink(),
      'items'     => $feed->get_items(),
    );

    return View::make('feed', $data);
  }

When I print the $feed I am getting the below information.
SimplePie {#1572 ▼
  +data: array:3 [▼
    "type" => 0
    "links" => []
    "items" => []
  ]
  +error: "cURL error 60: SSL certificate problem: unable to get local issuer certificate"
  +sanitize: SimplePie_Sanitize {#1573 ▶}
  +useragent: "SimplePie/1.5.3 (Feed Parser; http://simplepie.org; Allow like Gecko) Build/20200302054845"
  +feed_url: "https://timesofindia.indiatimes.com/rssfeeds/296589292.cms"
  +permanent_url: "https://timesofindia.indiatimes.com/rssfeeds/296589292.cms"
  +file: null
  +raw_data: null
  +timeout: 10
  +curl_options: []
  +force_fsockopen: false
  +force_feed: false
  +cache: true
  +force_cache_fallback: false
  +cache_duration: 3600
  +autodiscovery_cache_duration: 604800
  +cache_location: "D:\Laraveltest\laravelinit_latest_2020_02_17\storage\framework/cache"
  +cache_name_function: "md5"
  +order_by_date: true
  +input_encoding: false
  +autodiscovery: 31
  +registry: SimplePie_Registry {#1574 ▶}
  +max_checked_feeds: 10
  +all_discovered_feeds: []
  +image_handler: ""
  +multifeed_url: []
  +multifeed_objects: []
  +config_settings: null
  +item_limit: 0
  +check_modified: false
  +strip_attributes: array:14 [▶]
  +add_attributes: array:3 [▶]
  +strip_htmltags: array:19 [▶]
  +enable_exceptions: false
}

Please help me out to solve this.

A: As you see in your output you are getting cURL error 60: SSL certificate problem in your curl

cURL error 60: SSL certificate problem: unable to get local issuer certificate

To resolve this if you are using XAMPP server. You can download cacert.pem file from the below link and put it in your under C:\xampp\php\extras\ssl\cacert.pem  and add it's path php.ini file
https://curl.haxx.se/docs/caextract.html
Put it here
C:\xampp\php\extras\ssl\cacert.pem

In your php.ini put this line in this section ("c:\xampp\php\php.ini"):
curl.cainfo = "C:\xampp\php\extras\ssl\cacert.pem"

restart your webserver/apache
Laracast -> cURL error 60: SSL certificate problem: unable to get local issuer certificate

redpajama_set_name: RedPajamaStackExchange


text:
Q: Service/Product to enable users on my Web App to invite friends (e.g. Hotmail, Yahoo Messenger, Gmail, AIM, etc) I'm building a consumer web application and want to enable my users to invite their friends/contacts from popular email (e.g gmail, yahoo, hotmail) and social networking services to join my service.  Can you suggests some products/services you've used in the past that enable this sort of functionality.  Can you tell me what you like/don't like about the product/service.  Thx in advance for the help!

A: A simple widget can be "ShareThis"


text:
Q: Typescript: Null check doesn't work inside array.map function Why my nullable type that was previously checked before the map function doesn't work inside the map?
function x() {
  let y: number | null;
  y = null;

  if (!y) {
    return [];
  }

  return [1, 2, 3, 4].map((z) => {
    // error: y cannot be null
    return z + y;
  })
}

The code on TypeScript Playground.

A: As you are using let instead of const your type guard cannot guarantee that you will not modify the value, that said TS is taking the original assumption about the type (number | null), and you need to check it again. Changing y into const helps.
Examples of re-assigning y
Consider that you could be after the check, again set y into null.
function x(defValue: number | null) {
  let y = defValue;
  if (!y) {
    return [];
  }
  // and below the change even though we checked that before the check is not safe
  y = null;
  return [1, 2, 3, 4].map((z) => {
    // no error
    return z + y;
  })

}

Another example how I can change the value is - in map itself, consider:
return [1, 2, 3, 4].map(z => {
    y = null // changed to null!!
    return z;
  }).map((z) => {
    // error as it can be null
    return z + y;
  })

The main reason why its not safe check is that we cannot say when callback will be called, fact that we declare it in this scope, does not mean it will be executed in the same time, for example if it would be Promise.then, time of execution is unknown. Consider such code:
function x(defValue: number | null) {
  let y = defValue;
  if (!y) {
    return [];
  }
  httpClient.get('http://something').then((z: number) => {
    // error correctly because y is null
    return z + y;
  });

  y = null; // this code is executed before then
}

Another example would be exposing possible change of y outside. Consider:
function x(defValue: number | null) {
  let y = defValue;
  if (!y) {
    return null
  }
  return {
    f: (z: number) => z + y, // error as y can be null because yToNull can change it
    yToNull: () => { y = null } // modify the y to null
  }
}
const fg = x(1);

if (fg) {
  fg.yToNull();
  fg.f(2); // y is null inside the scope of f
}

Use const to have persistent guard
As you can see it is very unsafe to treat let variables as narrowed by guards in the whole closure.
With const such re-assign is not possible, and TS is able to infer the narrow type of the value in scope of closure.
function x(defValue: number | null) {
  const y = defValue;
  if (!y) {
    return [];
  }
  // any change of y type is not possible with const
  return [1, 2, 3, 4].map((z) => {
    // no error as y cannot be re-assigned
    return z + y;
  })

}

A: As per documentation- https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-0.html#non-null-and-non-undefined-type-guards.

A property access or a function call produces a compile-time error if
  the object or function is of a type that includes null or undefined.
TypeScript 2.0 implements a control flow-based type analysis for local
  variables and parameters. Previously, the type analysis performed for
  type guards was limited to if statements and ?: conditional
  expressions and didn't include effects of assignments and control flow
  constructs such as return and break statements. With TypeScript 2.0,
  the type checker analyses all possible flows of control in statements
  and expressions to produce the most specific type possible (the
  narrowed type) at any given location for a local variable or parameter

If you try to access y after if condition, it will not show compiler error Object possibly null, because it has already been check for null in the if condition and is present in same scope.
  if (!y) {
    return [];
  }

  console.log(y); // No error.

Whereas, when you are accessing the y within the callback function of map, the scope is different. Instead you can use non-null assertion operator i:e !.
function x() {
  let y: number | null;
  y = null;

  if (!y) {
    return [];
  }

  return [1, 2, 3, 4].map((z) => {
    // error: y cannot be null
    return z + y!;
  })
}


text:
Q: Disassamble ELF file - debugging area where specific string of binary is loaded I would like to disassamble / debug an elf file. Is it somehow possible to track the function where a specific string in the elf file is called?
So I mean, I have a string where I know it is used to search for that string in a file. Is it somehow possible with e.g. gdb to debug exactly that position in the executable?
Or is the position of the string in the elf file, somehow visible in the objdump -d output?

A: In order to do that you need a disassembler - objdump just dumps the info - it might not give you enough information as some analysis is needed before you can tell where it is being used. What you need is to get the XREFs for the string you have in mind.
If you open your binary in the disassembler it will probably have the ability to show you strings that are present in the binary with the ability to jump to the place where the string is being used (it might be multiple places).
I'll showcase this using radare2.
Open the binary (I'll use ls here)

r2 -A /bin/ls

and then

iz

to display all the strings. There's a lot of them so here's an extract
000 0x00004af1 0x100004af1   7   8 (4.__TEXT.__cstring) ascii COLUMNS
001 0x00004af9 0x100004af9  39  40 (4.__TEXT.__cstring) ascii 1@ABCFGHLOPRSTUWabcdefghiklmnopqrstuvwx
002 0x00004b21 0x100004b21   6   7 (4.__TEXT.__cstring) ascii bin/ls
003 0x00004b28 0x100004b28   8   9 (4.__TEXT.__cstring) ascii Unix2003
004 0x00004b31 0x100004b31   8   9 (4.__TEXT.__cstring) ascii CLICOLOR
005 0x00004b3a 0x100004b3a  14  15 (4.__TEXT.__cstring) ascii CLICOLOR_FORCE
006 0x00004b49 0x100004b49   4   5 (4.__TEXT.__cstring) ascii TERM
007 0x00004b60 0x100004b60   8   9 (4.__TEXT.__cstring) ascii LSCOLORS
008 0x00004b69 0x100004b69   8   9 (4.__TEXT.__cstring) ascii fts_open
009 0x00004b72 0x100004b72  28  29 (4.__TEXT.__cstring) ascii %s: directory causes a cycle

let's see where this last one is being used. If we move to the location where it's defined 0x100004b72. We can see this:
;-- str.s:_directory_causes_a_cycle:
; DATA XREF from 0x100001cbe (sub.fts_open_INODE64_b44 + 378)

And here we see where it's being referenced -> DATA XREF. We can move there (s 0x100001cbe) and there we see how it's being used.
⁝   0x100001cbe      488d3dad2e00.  lea rdi, str.s:_directory_causes_a_cycle    ; 0x100004b72 ; "%s: directory causes a cycle"
⁝   0x100001cc5      4c89ee         mov rsi, r13
⁝   0x100001cc8      e817290000     call sym.imp.warnx         ;[1]

Having the location you can put a breakpoint there (r2 is also a debugger) or use it in gdb.


text:
Q: How do I make a boolean attribute go back to a default value in a Python class? I'm trying to make a class to handle logic Literals and I want to account for negated literals by overloading the __neg__() operator:
class Literal():

def __init__(self,n):
    self.name = n
    self.sign = True

def __neg__(self):
    self.sign = False
    return self

def __repr__(self):
    return self.name

Nothing too complicated; what I have now successfully changes the sign attribute to False when I define an instance A=Literal('A') and run the command (-A).sign. However, if I later run A.sign the attribute is still set to False, which I don't want. I want the value of A.sign to always return True and the value of (-A).sign to always return False.
Note: I can't just make a secondary instance other and set other.sign = False because regardless of its sign value, any call to A should reference to A and not a copy.
I've been playing around with different ideas such as setting a @property but can't seem to figure it out so I turn to the internet for help. Thanks in advance and let me know if you would like any more info!
EDIT:
I made it return a new instance as I had previously done since it seems everyone agrees that's the best option. I added an example case of the problem this generates so it's more clear:
class Literal():

def __init__(self,n,s=True):
    self.name = n
    self.sign = s

def __neg__(self):
    result = Literal(self.name, not self.sign)
    return result

def __repr__(self):
    return self.name

A = Literal('A')
B = Literal('B')
C = Literal('C')

print((-A).sign)
>>> False
print(B.sign)
>>> True
print((-B).sign)
>>> False
print(A.sign)
>>> True
print(B.sign)
>>> False

That works. However, I need to gather a list of the literals in a list of sets (this is representing CNF) later, and having the separate instances causes a problem because I end up with duplicate literals:
test = [{A,-B},{B,C},{-A,C}]
lits = []

for x in test:
    for i in x:
        print(x,i,i.sign)
        if i not in lits:
            lits.append(i)

print(f'\n{test}')
print(lits)

>>> {B, A} B False
>>> {B, A} A True
>>> {B, C} B True
>>> {B, C} C True
>>> {C, A} C True
>>> {C, A} A False

>>> test: [{B, A}, {B, C}, {C, A}]
>>> lits: [B, A, B, C, A]

Literals B and A, which were negated, are duplicated because of this implementation of the sign.
Hope this clarified my previous note.

A: If you don't want to change the original you have to create a new instance.
class Literal():
    def __init__(self, n):
        self.name = n
        self.sign = True

    def __neg__(self):
        result = Literal(self.name)
        result.sign = False
        return result

    def __repr__(self):
        return self.name

a = Literal('A')
print((-a).sign)
print(a.sign)

But there's a problem with your code. You always return False for the sign. This means that (-a).sign and (--a).sign are the same. You should change __neg__ to the following code.
    def __neg__(self):
        result = Literal(self.name)
        result.sign = not result.sign
        return result

If you add the sign as an optional parameter to __init__ the code could look like this.
class Literal():
    def __init__(self, n, sign=True):
        self.name = n
        self.sign = sign

    def __neg__(self):
        return Literal(self.name, not self.sign)

    def __repr__(self):
        return self.name

For maximum flexibility you can replace return Literal(self.name, not self.sign) by return self.__class__(self.name, not self.sign).

A: @jonrsharpe is correct: __neg__ should return a new instance:
class Literal():

    def __init__(self,n, sign=True):
        self.name = n
        self.sign = sign

    def __neg__(self):
        return Literal(self.name, sign=False)

    def __repr__(self):
        return self.name

a = Literal('a')
print((-a).sign)
>>> False
print((a).sign)
>>> True
a = -a
print((a).sign)
>>> False


text:
Q: Is that the right way to check if an existing password is stored? I'm creating an application with 2 ATMega16 micro controller.
The second micro should check if a password is stored in the external EEPROM then send this information to the first one. So, if there were a stored password user will be ask to log-in, else the user should set a new password and send it to the second micro to save it in the external EEPROM.
The code doesn't run in a right way; can you help me to understand what happens?
Note: all driver used are tested and all of them works correctly.
First Micro Code
#define PASSWORD_LENGTH 5
#define PASSWORD_ADDRESS 0x0311
#define HMI_READY 0
#define CONTROL_READY 1
#define IS_PASSWORD_EXIST 6
#define PASSWORD_EXISTS 7
#define PASSWORD_NOT_EXISTS 8

#include "lcd.h"
#include "keypad.h"
#include "uart.h"

void HMI_init(void) ;
void HMI_set_new_password(uint8 *a_ptrPassword) ;
void HMI_send_password(uint8 *a_ptrPass) ;

uint8 g_password[PASSWORD_LENGTH] = {0} ;

int main(void)
{
    HMI_init() ;
    UART_sendByte(HMI_READY) ;
    LCD_clearDisplay() ;
    LCD_displayString("Stuck Here : ( ") ; /*<<<<<<<<<<<<<<<<<<<<<*/
    if(UART_receiveByte() == PASSWORD_NOT_EXISTS)
    {
        LCD_sendCommand(CLEAR_DISPLAY) ;
        LCD_displayString("N O ") ;

    }
    else if(UART_receiveByte() == PASSWORD_EXISTS) ;
    {
        LCD_sendCommand(CLEAR_DISPLAY) ;
        LCD_displayString("Y E S ") ;
        while(1)
        {

        }
    }

}

/* Functions Definitions */
void HMI_init(void)
{
    LCD_init() ;
    LCD_sendCommand(CLEAR_DISPLAY) ;
    LCD_sendCommand(CURSOR_OFF) ;
    LCD_displayStringRowCol(0,4,"WELCOME") ;
    LCD_displayStringRowCol(1,1,"TO DOOR LOCKER") ;
    UART_init();
    SREG |=(1<<7) ;
}

void HMI_set_new_password(uint8 *a_ptrPassword)
{
    uint8 i = 0 ;
    uint8 key = 0 ;
    uint8 temp_pass[PASSWORD_LENGTH] = {0} ;
    uint8 confirm_flag = 0 ;

    while(confirm_flag == 0)
    {
        i = 0 ;
        LCD_sendCommand(CLEAR_DISPLAY) ;
        LCD_sendCommand(CURSOR_ON) ;
        LCD_displayString("SET A PASSWORD : ") ;
        LCD_goToRowCol(1,0) ;
        while(i<PASSWORD_LENGTH)
        {
            key = KeyPad_getPresssedKey() ;
            if(key>=0 && key<=9)
            {
                a_ptrPassword[i] = key ;
                LCD_displayCharacter('*') ;
                i++ ;

            }else
            {

            }
            _delay_ms(2000) ;
        }
        LCD_sendCommand(CLEAR_DISPLAY) ;
        LCD_sendCommand(CURSOR_ON) ;
        LCD_displayString("REPEAT PASSWORD : ") ;
        LCD_goToRowCol(1,0) ;
        i = 0 ;
        while(i<PASSWORD_LENGTH)
        {
            key = KeyPad_getPresssedKey() ;
            if(key>=0 && key <=9)
            {
                temp_pass[i] = key ;
                i++ ;
                LCD_displayCharacter('*') ;
            }else
            {

            }
            _delay_ms(2000) ;
        }
        /* compare */
        for(i = 0 ; i<PASSWORD_LENGTH ; i++)
        {
            if(a_ptrPassword[i] != temp_pass[i])
            {
                confirm_flag = 0 ;
                break ;
            }else{
                confirm_flag = 1 ;
            }
        }

        if(confirm_flag == 1)
        {
            LCD_sendCommand(CLEAR_DISPLAY) ;
            LCD_displayString("CONFIRMED") ;
            _delay_ms(2000) ;
        }else if(confirm_flag == 0 )
        {
            LCD_sendCommand(CLEAR_DISPLAY) ;
            LCD_displayString("NOT CONFIRMED") ;
            _delay_ms(2000) ;
        }
    }
}

void HMI_send_password(uint8 *a_ptrPass)
{
    uint8 i = 0 ;
    for(i = 0 ; i<PASSWORD_LENGTH ; i++)
    {
        UART_sendByte(a_ptrPass[i]) ;
    }
}

Second micro code
#define PASSWORD_LENGTH 5
#define PASSWORD_ADDRESS 0x0311
#define HMI_READY 0
#define CONTROL_READY 1
#define IS_PASSWORD_EXIST 6
#define PASSWORD_EXISTS 7
#define PASSWORD_NOT_EXISTS 8

#include "lcd.h"
#include "uart.h"
#include "eeprom.h"

void CONTROL_init(void) ;
uint8 CONTROL_password_exist(void) ;
void CONTROL_receive_password(uint8 *a_ptrPass) ;
void CONTROL_save_password(uint8 *a_ptrPass) ;

uint8 g_received_password[PASSWORD_LENGTH] = {0}  ;
int main(void)
{
    CONTROL_init() ;
    if(CONTROL_password_exist() == 0)
    {
        while(UART_receiveByte() != HMI_READY) ;
        UART_sendByte(PASSWORD_NOT_EXISTS) ;
    }
    else
    {
        while(UART_receiveByte() != HMI_READY) ;
        UART_sendByte(PASSWORD_EXISTS) ;
        while(1)
        {

        }
    }
}

void CONTROL_init(void)
{
    LCD_init() ;
    LCD_sendCommand(CLEAR_DISPLAY) ;
    LCD_sendCommand(CURSOR_OFF) ;
    EEPROM_init() ;
    UART_init() ;
    SREG |=(1<<7) ;
}

uint8 CONTROL_password_exist(void)
{
    uint8 i = 0 ;
    uint8 temp = 0 ;
    for(i=0 ; i<PASSWORD_LENGTH ; i++)
    {
        EEPROM_readByte((PASSWORD_ADDRESS+i) , &temp) ;
        _delay_ms(150) ;
        if(temp != 0xFF)
        {
            return 1 ;
        }
    }
    return 0 ;
}

void CONTROL_receive_password(uint8 *a_ptrPass)
{
    uint8 i = 0 ;
    for(i = 0 ; i<PASSWORD_LENGTH ; i++)
    {
        a_ptrPass[i] = UART_receiveByte() ;
    }
}

void CONTROL_save_password(uint8 *a_ptrPass)
{
    uint8 i = 0 ;
    for(i = 0 ; i<PASSWORD_LENGTH ; i++)
    {
        EEPROM_writeByte((PASSWORD_ADDRESS+i) , a_ptrPass[i]);
        _delay_ms(150) ;
    }
}

A: The synchronisation is poorly implemented - you have a start-up race condition.  You have no guarantee that CONTROL is ready when HMI sends its single HMI_READY byte.
The HMI should wait for a response, and if none is received in a reasonable time (a matter of milliseconds), resend the HMI_READY:
Pseudo-code - this is just to illustrate a possible structure and logic:
 // Wait for response
 response = false ;
 while( !response )
 {
     // Send or resend synchronisation byte
     send( HMI_READY )

     // Wait for response or timeout
     start_time = now() ;
     while( !response && (now() - start_time) < TIMEOUT )
     {
         ch = receive() ;
         response = ( ch == PASSWORD_NOT_EXISTS || ch == PASSWORD_EXISTS )
     }
}

if( ch == PASSWORD_NOT_EXISTS)
{
    ...
}
else // password exists
{
    ...
}

Your CONTROL may be fine, since it does wait indefinitely for HMI_READY, but might better be structured thus:
// Wait for synch byte
while( receive() == HMI_READY )
{
    // wait
}

if( CONTROL_password_exist() )
{
    send( PASSWORD_EXISTS )
}
else
{
    send( PASSWORD_NOT_EXISTS )
}

...

In this way, it does not matter when or in what order each micro is started, each will wait for the other - synchronisation.


text:
Q: Occasional SSL error serving GitHub Pages site over custom domain Using GitHub pages built-in SSL, I have been serving a github pages site over https since it was announced. I set this up by following the tutorial GitHub provides. However, perhaps 25% of the time when I try to access the site, I get an SSL error that says the browser cannot find the certificate. Reloading the page one or more times resolves the issue for a while. The site use enforced HTTPS. Due to the intermittent nature of the issue, I have failed to determine the cause. I am unsure of what information I could provide to help diagnose the error.
Edit: the error is NET::ERR_CERT_COMMON_NAME_INVALID on chrome


text:
Q: F-Spot fails to load into Ubuntu 16.04. I have tried to download F-Spot into my PC that runs Ubuntu 16.04 and have failed. Have tried F-Spot from several sources without success. Any Ideas?

A: *

*Download the .deb package suitable for your system architecture: i386 or amd64 (choose a mirror in your vicinity – your system architecture is shown by uname -m, where x86_64 corresponds to amd64)

*Open the file to install the package.

Alternatively you can download the tar.gz archive and install it as explained here: How do I install a .tar.gz (or .tar.bz2) file?


text:
Q: How to develop a new pkg version while using the old one I am developing my own pkg with console_scripts in python.
I installed a stable version:
python setup.py install

I already use this version. I want to implement and test some improvements.
How can i do something like the following without "loosing" my installed version:
python setup.py develop

A: The best practice is to use different virtualenvs: one for your current release, one for your development.
For the current release:
cd /path/to/virtualenv/dir/
virtualenv my_app
source my_app/bin/activate
pip install my_app  # or a path to my last wheel

Instead of using pip, you can run python setup.py install, that way:
cd /path/to/workspace/my_app/  # <- directory containing the setup.py
python setup.py install

Then, you can use your application's entry point (say "my_entry"):
/path/to/virtualenv/dir/bin/my_entry <args>

To develop, you create a different virtualenv:
cd /path/to/virtualenv/dir/
virtualenv my_app_dev
source my_app_dev/bin/activate

cd /path/to/workspace/my_app/  # <- directory containing the setup.py
pip install -e .

You have linked your my_app_dev virtualenv to your source code. To check that:
pip list

EDIT More about virtualenvs
You can read the online book Hitchhiker's Guide to Python to know more about virtualenvs.


text:
Q: Any way to programatically get key of google script? I understand how to get sheet key of a google spreadsheet using script, is there a way to get the key to the script file associated with the sheet through script? For example:
https://script.google.com/macros/d/I_Want_This_String/edit

A: No there is no way to do that.


text:
Q: Uploading file doesn't work on second time I am trying to upload an excel file and send to api with reactjs, so far I can successfully send file to api. In my submit function, I also want to reset saved excel file from state when submitted, so I am doing as following
  const [urlImg, setURLImg] = useState("");
  const [excelFile, setExcelFile] = useState();

  function handleOnSubmit(e) {
    e.preventDefault();

    setExcelFile();
    setURLImg("");
  }

But it is not working when I upload for the second time with the same excel file as previous one. I console.log the state but not showing anything, it seems like the whole component is not being rendered when submit with the same excel file. You can see my codesandbox sample here
google drive link to download sample excel

A: You can use the form's onSubmit event object to reset the file input field using the input's id property.
function handleOnSubmit(e) {
  e.preventDefault();

  e.target["icon-button-file"].value = "";

  setExcelFile();
  setURLImg("");
}


text:
Q: How to convert SOAP methods to restful API? I am new to this world of Rest services, I have simple SOAP service with names
withDrawCashFromAccount(int id, int amountToWithDraw)
depositCashToAccount(int id, int amountToDeposit)

which are self explanatory, this was a simple service as the management team has decided to move to restful architecture, i face the following problems on how to convert about two methods in restful API

*

*In order to change a single column in a resource, do we need send the
complete JSON structure of the resource ?.

resource name "Account"
e.g Json structure:

        id : 1,
        name : "awesome customer",
        Amount : 500

*

*In order to have above two type of simple use cases where user can
withdraw cash or user can deposit, I am puzzled on how can i design the
end points for rest service. Can I name them
/account/depositCash/id,
/account/withdrawCash/id

*

*Anything else I need to think like Idempotent nature of above calls?

Currently using spring boot as from this example

A: You do not necessarily need to send the entire Account object, and you should be able to name your endpoints whatever you like, as long as they stem from the same base URL; it all depends on how you have your services and POJOS configured.
For instance, using JAX-RS, you can annotate a service class with @Path("path/you/want/here") to specify a base path for all methods accessible in that service, followed by more specific @Path annotations for each method to give them unique paths (the method level @Path annotation gets added to the end of the class level one). You can annotate your public methods with HTTP verb annotations like @GET or @POST to specify which verb that method will take.
In your REST endpoint methods, you can deserialize the incoming JSON into POJOs using Jackson, going as far as to specify which attributes are required, how they should be deserialized/serialized, and so on. As long as you don't need the attributes or you are expecting them to not always be there, you can simply allow missing POJO fields to deserialize to null.


text:
Q: Parsing DateTime to Universal Time C# I have a xml which can return a time in the format (7/23/2013 4:00pm) my question is: How can I explain to DateTime.ParseExact that I'm in the "am" or in the "pm"? I have this piece of code, but it returns me an exception (String can not be parsed)
I alredy placed an example string (7/23/2013 4:00pm) in which I replace "pm" by the empty chain "".
string pattern = "MM/dd/yyyy H:mm 'UTC' zzz";
DateTime time = DateTime.ParseExact(sb.ToString(), pattern, CultureInfo.InvariantCulture,
                                                      DateTimeStyles.AssumeUniversal |
                                                      DateTimeStyles.AdjustToUniversal);

Thank you very much :)

A: You can pass an array to cover various formats.  I use the following for various time inputs.
var formats = new[]
    {
        "M/dd/yyyy hh:mm tt",
        "M/dd/yyyy hh:mmtt",
        "M/dd/yyyy h:mm tt",
        "M/dd/yyyy h:mmtt",
        "M/dd/yyyy hhtt",
        "M/dd/yyyy htt",
        "M/dd/yyyy h tt",
        "M/dd/yyyy hh tt"
    };

    var date = "7/23/2013 4:00pm";

    DateTime time = DateTime.ParseExact(date, formats, CultureInfo.InvariantCulture,
                                                  DateTimeStyles.AssumeUniversal |
                                                  DateTimeStyles.AdjustToUniversal);

A: You need the tt format:
string pattern = "MM/dd/yyyy h:mm 'UTC' tt";
DateTime time = DateTime.ParseExact(sb.ToString(), pattern, CultureInfo.InvariantCulture,
                                                      DateTimeStyles.AssumeUniversal |
                                                      DateTimeStyles.AdjustToUniversal);

A: H in your pattern expects the time in a 24 style. You need tt (as outlined in the previous answer) AND you must a small h in your pattern:
string pattern = "MM/dd/yyyy h:mm 'UTC' tt";


text:
Q: Expressions with slashes are highlighted incorrectly First off: I'm not talking about multi line commenting, I don't think. The problem is occurring when there is a space between the / and the * such as
draw.arc(x, y, radius, Math.PI/2, Math.PI/2, true);

In dreamweaver, the text
/2,Math.PI/

Goes green.
I've googled but to no avail. I'm sure it's something dumb but I'm stumped.
Also note: still occurs when the Math.PI formula is defined as a variable

A: As stated below, it's a parsing issue with Dreamweaver - interpreting your syntax as a regular expression.
A solution to this problem would be to create a variable for that value. Additionally, it's more efficient than doing the same operation more than once.
var piOver2 = Math.PI / 2;

draw.arc(x, y, radius, piOver2, piOver2, true);

A: Dreamweaver is interpreting that as a regex for syntax highlighting.
The regex notation /regex/ is the most notoriously difficult part to parse in all of Javascript.
Your code is fine. You could try adding spaces around the /. I've often seen that work.

A: It is something dumb: Dreamweaver has a bug in it. Your code must still execute. That is a perfectly valid sequence of characters, that does not result in a comment.


text:
Q: How can I put variable into session name? I want to put variable value to session name, like
session[:this_is_@profile_of] = "Smth"

How can I do this?

A: You will have to use to_sym method:
session_key = "this_is_#{@profile}_of".to_sym

session[session_key] = "Smth"


text:
Q: Is there a convenient way to set default values for ApplicationData.Current.LocalSettings using a settings file? I'm using the built in settings infrastructure in my Windows Phone 8.1 application to store my settings key-value pairs. For instance:
ApplicationDataContainer settings = ApplicationData.Current.LocalSettings;
object value = settings.Values["DailyReminderOnOff"];

I'm trying to find a way to supply default values that come canned with the app at installation. Is there some recommended and convenient way of doing that?
I could implement my own system by placing a dirty bit and reading from a file if it's unset or provide defaults through if-null checks within the getter; but I'd rather avoid the hassle of writing and maintaining that code if the system provides something I've missed.
Thanks!

A: There is no default way to get the value. Why don't you use simple fallback like this:
const string DefaultValue1 = "value123";
object value = settings.Values["DailyReminderOnOff"] ?? DefaultValue1;


text:
Q: Cannot get HTMLUnitDriver Warnings Off I cannot get the HTML Unit Driver warnings to turn off. The code below reduced the original amount of warnings. Cannot get the last bit to turn off.
I cannot get the HTML Unit Driver warnings to turn off. The code below reduced the original amount of warnings. Cannot get the last bit to turn off.
My code:
  LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");

  java.util.logging.Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.OFF);
  java.util.logging.Logger.getLogger("com.gargoylesoftware.htmlunit").setLevel(java.util.logging.Level.OFF);
  java.util.logging.Logger.getLogger("org.apache.http").setLevel(java.util.logging.Level.OFF);
  java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);

  htmlDriver = new HtmlUnitDriver(browserVersion, isJavaScriptEnabled) {
    @Override
    protected WebClient modifyWebClient(WebClient client) {
      WebClient modifiedClient = super.modifyWebClient(client);

      modifiedClient.getOptions().setThrowExceptionOnScriptError(false); // see here
      modifiedClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
      modifiedClient.getOptions().setJavaScriptEnabled(isJavaScriptEnabled);
      modifiedClient.setCssErrorHandler(new SilentCssErrorHandler());
      modifiedClient.getOptions().setCssEnabled(false);
      modifiedClient.getOptions().setPrintContentOnFailingStatusCode(false);

      modifiedClient.getOptions().setTimeout(10000);

      modifiedClient.setIncorrectnessListener(new IncorrectnessListener() {

        @Override
        public void notify(String arg0, Object arg1) {
          // TODO Auto-generated method stub
        }
      });

      modifiedClient.setJavaScriptErrorListener(new JavaScriptErrorListener() {
        @Override
        public void timeoutError(HtmlPage arg0, long arg1, long arg2) {
          // TODO Auto-generated method stub
        }

        @Override
        public void scriptException(HtmlPage arg0, ScriptException arg1) {
          // TODO Auto-generated method stub
        }

        @Override
        public void malformedScriptURL(HtmlPage arg0, String arg1, MalformedURLException arg2) {
          // TODO Auto-generated method stub
        }

        @Override
        public void loadScriptError(HtmlPage page, java.net.URL scriptUrl,
                                    Exception exception) {
          // TODO Auto-generated method stub
        }
      });
      modifiedClient.setHTMLParserListener(new HTMLParserListener() {

        @Override
        public void error(String message, java.net.URL url, String html, int line, int column,
                          String key) {
          // TODO Auto-generated method stub
        }

        @Override
        public void warning(String message, java.net.URL url, String html, int line, int column,
                            String key) {
          // TODO Auto-generated method stub
        }
      });

      modifiedClient.setHTMLParserListener(new HTMLParserListener() {
        @Override
        public void error(String message, URL url, String html, int line, int column,
                          String key) {
          // TODO Auto-generated method stub
        }

        @Override
        public void warning(String message, URL url, String html, int line, int column,
                            String key) {
          // TODO Auto-generated method stub
        }
      });
      modifiedClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
      modifiedClient.getOptions().setThrowExceptionOnScriptError(false);

      return modifiedClient;
    }
  };

But I still get:
01:12:36.667 [Thread-10] ERROR c.g.h.javascript.StrictErrorReporter - runtimeError: message=[An invalid or illegal selector was specified (selector:
01:12:37.264 [Thread-10] ERROR c.g.h.javascript.StrictErrorReporter - runtimeError: message=[An invalid or illegal selector was specified (selector: '*,:x' error: Invalid selector: :x).] sourceName=[http://code.jquery.com/jquery-1.9.1.js] line=[4224] lineSource=[null] lineOffset=[0]
01:12:38.393 [JS executor for com.gargoylesoftware.htmlunit.WebClient@4c085759] ERROR c.g.h.javascript.StrictErrorReporter - runtimeError: message=[An invalid or illegal selector was specified (selector: '*,:x' error: Invalid selector: :x).] sourceName=[http://code.jquery.com/jquery-1.9.1.js] line=[4224] lineSource=[null] lineOffset=[0]
01:12:41.251 [JS executor for com.gargoylesoftware.htmlunit.WebClient@4c085759] ERROR c.g.h.javascript.StrictErrorReporter - runtimeError: message=[An invalid or illegal selector was specified (selector: ':text' error: Invalid selector: :text).] sourceName=[http://code.jquery.com/jquery-1.9.1.js] line=[3983] lineSource=[null] lineOffset=[0]
01:12:41.256 [JS executor for com.gargoylesoftware.htmlunit.WebClient@4c085759] ERROR c.g.h.javascript.StrictErrorReporter - runtimeError: message=[An invalid or illegal selector was specified (selector: ':text' error: Invalid selector: :text).] sourceName=[http://code.jquery.com/jquery-1.9.1.js] line=[3983] lineSource=[null] lineOffset=[0]

How do you turn off these messages completely?

A: you need to Disable logging from logback XML
this kind of deactivation
java.util.logging.Logger.getLogger("com.gargoylesoftware").setLevel(Level.OFF);

not working, I think they using locgback and it can't be disabled from the log4j config too
com.gargoylesoftware.htmlunit.level = WARNING
com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter.level = OFF

you need something like that in your logback.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>
    <root level="INFO">
        <appender-ref ref="STDOUT" />
    </root>
    <logger name="com.gargoylesoftware.htmlunit.javascript.StrictErrorReporter" level="OFF" />
</configuration>


text:
Q: Using generics restricts me to using a specific type while I want to use all possible subclasses of that type I have the following code, which ended up this way due to other constraints:
public interface Action { }

public interface Result { }

public interface Player<A extends Action, R extends Result, P extends Player<A, R, P>> { }

public interface Game<A extends Action, R extends Result, P extends Player<A, R, P>> { }

abstract public class AbstractGame<A extends Action, R extends Result, P extends Player<A, R, P>> implements Game<A, R, P> { }

public class RPSGame<P extends RPSPlayer<P>> extends AbstractGame<RPSGesture, RPSResult, P> { }

Other relevant classes/interfaces:
abstract public class GesturePlayer<A extends Action, R extends Result, P extends GesturePlayer<A, R, P>> implements Player<A, R, P> { }

abstract public class RPSPlayer<P extends RPSPlayer<P>> extends GesturePlayer<RPSGesture, RPSResult, P> { }

public class RPSHumanPlayer extends RPSPlayer<RPSHumanPlayer> { }

public class RPSSimpleAIPlayer extends RPSPlayer<RPSSimpleAIPlayer> { }

public enum RPSGesture implements Gesture, Action, GestureFPSRules { }

public enum RPSResult implements Result { }

Then I noticed that, due to all changes, I am using raw types in my program, which I do not want at all:
private void init() {
    RPSGame rpsGame = new RPSGame();
    rpsGame.addPlayer(new RPSHumanPlayer());
    rpsGame.addPlayer(new RPSSimpleAIPlayer());
    rpsGame.playGame();
}

Here RPSGame is a raw type, while I initially intended it to be raw, it got generics added to it to keep the code working.
The problem is that I cannot make it non-generic as then the code does not compile anymore with everything that I have tried, therefore is it possible to:

*

*Either remove the generics from the RPSGame class?

*Or define RPSGame rpsGame in such a way (with typed parameters), that it compiles?


text:
Q: How to make a timer and a loop in a batch file? I need some help completing my .bat file.
So what I wanna do is that after the program has started I wanna leave it running for like 1min then I want it to close the program and then run it agian for 1min. So it will be loop. I'm a complete novice on this so all help is appreciated.
This is what i currently have:
    @echo off
    color a
    echo ProHaxor1337 Initialised
    color b
    :start
    start (Program Name Here)
    GOTO start

A: Try this, assuming that there is only one instance of programname.exe allowed on the system:
@echo off
color a
echo ProHaxor1337 Initialised
color b
:start
start programname.exe
REM Delay using ping to localhost (1 ping per second)
ping 127.0.0.1 -n 60 > nul
REM Kill the process forcefully.
taskkill /im programname.exe /f
GOTO start


text:
Q: R: How to transform dataframe into .hyper? I am an R & tableau user. My object is to extract a dataframe in R and transform it into .hyper format, so that my tableau can read the dataframe directly.
Why I am not considering extract a csv format which can also be read by tableau? Because the .csv file is too large (about 1.7 GB) and there is no way to shrank my dataframe anymore. I hope there is way to extract .hyper and that's not a super large file. Thanks!

A: pantabR should support your use case
To cite from their README:
devtools::install_github("btibert3/pantabR")
library(pantabR)
dat = data.frame(x=1:10, y=letters[1:10])
frame_to_hyper(dat, f="dataset.hyper", tbl="dataset")


text:
Q: How can i optimize subsequent related queries by using rowid i am using ExecuteOracleNonQuery and getting rowid as output parameter.How can i optimize subsequent related queries by using rowid?

A: Perhaps if you posted the query you're using it would be more clear what it is you're trying to achieve?
The Oracle ROWID identifes a row in a table (but is not unique within the Database). By using ExecuteOracleNonQuery you are only affecting one row if it returns the ROWID, I'm not sure however what it is you plan to do with your 'subsequent related queries'.

A: A rowid can be used in SELECT, INSERT, UPDATE and DELETE.
SELECT *
FROM mytable
WHERE rowid = :rowid

ROWID is a oracle keyword to directly access a datarow. To access a datarow through rowid there is no index lookup necessary.
Use OracleDbType.RowID to define the type of the parameter :rowid.


text:
Q: Fix for Xcode's indiscernible highlighting of inline errors? I can't be the only one that finds Xcode's method of "pointing out" where your mistakes are - ridiculous.  As helpful and essential as the feature is.. it does not help to make the line I need to fix virtually impossible to read or edit... let alone see...

And don't get me started on the constant struggle to find a "selection" color that is visible, yet retains one's sanity/ability to see what the selected text actually IS!

What am I missing here?  I know how to futz with the colors in xCode, I know how to mess with the Appearance "Control Panel", but it all just results in different configurations  - of varying aesthetic quality - that are all hard to read...  I don't have this issue in TextMate...  Is that my answer?
UPDATE: Thanks to the brilliant work, and answer by @amadillu, here is what the remarkably more usable Xcode looks like after installing his Xcode 4 "Fix-Ins"

A: I've made an Xcode Plugin by using davekeck's "fixins" that allows you to customize the colors of the inline error and warning messages. This really helps if you use a dark scheme / background . See here.


text:
Q: What is the likely definition of a women's "'health' west" from 1891? In an 1891 newspaper advertisement (published in Manitoba, Canada) there is a reference to "wool 'health' wests in girls and ladies" which on first glance looks like a spelling error but is repeated in other ads in the same year. Unfortunately, this is a very difficult combination of simple words to search for, does anyone have a reference for a definition of this garment term?

A: It's almost sure to be a misspelling of vest. In the nineteenth century, at least in London, /v/ and /w/ were either interchangeable, or they were replaced by a sound in between. Witness Sam Weller.

A: Oxford English Dictionary, under "vest" does list the spelling "west" from the  17th century as dialect.  From 1712:

Payd for mackin a west and briches for gouddins child, [£]0. 1. 6.

A: While west might be an alternative spelling for vest, it might also be a local or regional term for weskit or waistcoat (which at the time was typically pronounced "weskit"), formed as a sort of contraction of weskit, or a blending of vest and weskit.

A: On the "Health" part of the name:
In this era there was a theory that sweating was good for the health.  Ballplayers used to train in wool uniforms to get in some sweating.  This might be the reason for the 'health', as a wool vest would be considerably warmer than lighter fabrics.
It could also just be warmer to avoid colds and chills.


text:
Q: How to form array of arrays in typescript? I have two arrays,
arr1 = [1589135400000, 1589221800000, 1589308200000, 1589394600000, 1589481000000, 1589567400000, 1589653800000, 1589740200000, 1589826600000, 1591122600000]'
arr2 = [90.05, 98.0225, 99.8231, 99.3969, 73.45, 68.356, 55.123, 100, 68.75, 98.02430  ]

i need  to form array of arrays which should look like this.
[
      [1589135400000, 90.05],
      [1589221800000, 98.0225],
      [1589308200000, 99.8231],
      [1589394600000, 99.3969],
      [1589481000000, 73.45],
      [1589567400000, 68.356],
      [1589653800000, 55.123],
      [1589740200000, 100],
      [1589826600000, 68.75],
      [1591122600000, 98.02430]

]

I am using typescript.
please some one help me to solve this.please please
Thanks in advance

A: You can use array.map to combine the array values at the same index.

const arr1 = [
  1589135400000,
  1589221800000,
  1589308200000,
  1589394600000,
  1589481000000,
  1589567400000,
  1589653800000,
  1589740200000,
  1589826600000,
  1591122600000,
];

const arr2 = [
  90.05,
  98.0225,
  99.8231,
  99.3969,
  73.45,
  68.356,
  55.123,
  100,
  68.75,
  98.02430,
];

const combined = arr1.map((n, i) => [n, arr2[i]]);

console.log(combined);

A: Just loop over the first and find the same index in the second

arr1 = [1589135400000, 1589221800000, 1589308200000, 1589394600000, 1589481000000, 1589567400000, 1589653800000, 1589740200000, 1589826600000, 1591122600000]
arr2 = [90.05, 98.0225, 99.8231, 99.3969, 73.45, 68.356, 55.123, 100, 68.75, 98.02430 ]

console.log(arr1.map((el, i) => [ el, arr2[i] ]))


text:
Q: Using javascript, how can I have my function use different reference functions within it? For the function which is as follows,
At the line with pixel.addEventListener("mouseover", classic);, I'd like to be able to swap the classic function reference with other function references as I have buttons that use this same function but only swap through the function reference in this line. For now I have just copied and pasted this whole function 3 different times for the 3 buttons with the different reference functions in this line, but I know there must be a more elegant solution. I have tried creating an argument for the function but it doesn't seem to work.
resolutionChange function is called like so:
window.onload = resolutionChange;
...
slider.addEventListener("click", resolutionChange);

function resolutionChange(e) {
  const otherbuttons = document.querySelectorAll("button");
  otherbuttons.forEach((button) => {
    button.classList.remove("buttonclicked");
  });

  const button = document.querySelector("#classic");
  button.classList.add("buttonclicked");

  let pixel = document.querySelectorAll(".pixel");
  pixel.forEach((pixel) => {
    pixel.remove();
  });

  let slider = document.querySelector(`#slider`);
  let res = slider.value;

  for (let i = 0; i < res * res; i++) {
    let pixel = document.createElement("div");
    pixel.classList.add("pixel");
    pixel.setAttribute(
      "style",
      `width: ${512 / res}px; height: ${512 / res}px;`
    );
    pixel.addEventListener("mouseover", classic);
    mainholder.appendChild(pixel);
  }
}

I was hoping that I could do something like this:
function resolutionChange(func) {
  const otherbuttons = document.querySelectorAll("button");
  otherbuttons.forEach((button) => {
    button.classList.remove("buttonclicked");
  });

  const button = document.querySelector("#classic");
  button.classList.add("buttonclicked");

  let pixel = document.querySelectorAll(".pixel");
  pixel.forEach((pixel) => {
    pixel.remove();
  });

  let slider = document.querySelector(`#slider`);
  let res = slider.value;

  for (let i = 0; i < res * res; i++) {
    let pixel = document.createElement("div");
    pixel.classList.add("pixel");
    pixel.setAttribute(
      "style",
      `width: ${512 / res}px; height: ${512 / res}px;`
    );
    pixel.addEventListener("mouseover", func);
    mainholder.appendChild(pixel);
  }
}

I can't seem to figure out the solution to be able to use the resolutionChange function block of code so that I could use it like this, for example
let darkenbutton = document.querySelector("#darken");
darkenbutton.addEventListener("click", resolutionChange(darken));
let classicbutton = document.querySelector("#classic");
classicbutton.addEventListener("click", resolutionChange(classic));
let colorsbutton = document.querySelector("#colors");
colorsbutton.addEventListener("click", resolutionChange(colors));

instead of like this
let darkenbutton = document.querySelector("#darken");
darkenbutton.addEventListener("click", buttonchange.darkenmethod);
let classicbutton = document.querySelector("#classic");
classicbutton.addEventListener("click", buttonchange.classicmethod);
let colorsbutton = document.querySelector("#colors");
colorsbutton.addEventListener("click", buttonchange.colorsmethod);

Where buttonchange object holds the resolutionChange function repeated 3 times, with only that line previously mentioned changed for the 3 different functions

A: You can do that, you just need to call the function differently:
function resolutionChange(e, func) {
  const otherbuttons = document.querySelectorAll("button");
  otherbuttons.forEach((button) => {
    button.classList.remove("buttonclicked");
  });

  const button = e.target;
  button.classList.add("buttonclicked");

  let pixel = document.querySelectorAll(".pixel");
  pixel.forEach((pixel) => {
    pixel.remove();
  });

  let slider = document.querySelector(`#slider`);
  let res = slider.value;

  for (let i = 0; i < res * res; i++) {
    let pixel = document.createElement("div");
    pixel.classList.add("pixel");
    pixel.setAttribute(
      "style",
      `width: ${512 / res}px; height: ${512 / res}px;`
    );
    pixel.addEventListener("mouseover", func);
    mainholder.appendChild(pixel);
  }
}
const darkenbutton = document.querySelector("#darken");
darkenbutton.addEventListener("click", e => resolutionChange(e, darken));
const classicbutton = document.querySelector("#classic");
classicbutton.addEventListener("click", e => resolutionChange(e, classic));
const colorsbutton = document.querySelector("#colors");
colorsbutton.addEventListener("click", e => resolutionChange(e, colors));

Alternatively, you can make the function return an event handler closure:
function makeResolutionChanger(func) {
  return function clickHandler(e) {
    const otherbuttons = document.querySelectorAll("button");
    otherbuttons.forEach((button) => {
      button.classList.remove("buttonclicked");
    });

    const button = e.target;
    button.classList.add("buttonclicked");

    let pixel = document.querySelectorAll(".pixel");
    pixel.forEach((pixel) => {
      pixel.remove();
    });

    let slider = document.querySelector(`#slider`);
    let res = slider.value;

    for (let i = 0; i < res * res; i++) {
      let pixel = document.createElement("div");
      pixel.classList.add("pixel");
      pixel.setAttribute(
        "style",
        `width: ${512 / res}px; height: ${512 / res}px;`
      );
      pixel.addEventListener("mouseover", func);
      mainholder.appendChild(pixel);
    }
  }
}
const darkenbutton = document.querySelector("#darken");
darkenbutton.addEventListener("click", makeResolutionChanger(darken));
const classicbutton = document.querySelector("#classic");
classicbutton.addEventListener("click", makeResolutionChanger(classic));
const colorsbutton = document.querySelector("#colors");
colorsbutton.addEventListener("click", makeResolutionChanger(colors));


text:
Q: Join over three tables I have the following tables:
items id, principaluri, title
principals id, uri, name
members principal_id, member_id

The items principaluri is a reference to the principals uri field. The members table defines relationships between principals, means a member of a principal has access to the items of the principal in principal_id. How does the select look like to get all items of a principal?
To get the principals for a membership I do
SELECT p.*
FROM principals p
LEFT JOIN members m ON m.principal_id = p.id
WHERE p.id = m.principal_id and p.uri = 'myuri'

But now I need to get all items from the list.
--- UPDATE ---
In the principals table I have also records like
20, 'principals/admin', 'main account'
21, 'principals/admin/read', 'read access'
22, 'principals/admin/write', 'write access'
30, 'principals/test', 'main account'
31, 'principals/test/read', 'read access'
32, 'principals/test/write', 'write access'

The member table looks like:
21,30
22,30

which means the user test has read and write access to the items of the admin user.
But in the items table I have entries like:
100, 'principals/admin', 'Foo'
101, 'principals/admin', 'Bar'

A: This uses a nested query, but it seems to do the job:
SELECT i.*, mainp.uri mainuri, mp.memberuri, mp.linkuri access
FROM items i
LEFT OUTER JOIN principals mainp
   ON mainp.uri = i.principaluri
LEFT OUTER JOIN
  (SELECT memberp.uri memberuri, linkp.uri linkuri
     FROM principals memberp
      INNER JOIN members m on memberp.id = m.member_id
      INNER JOIN principals linkp on m.principal_id = linkp.id) as mp
  ON mp.linkuri LIKE CONCAT(i.principaluri, '%')
WHERE mainp.uri = 'principals/test' OR mp.memberuri = 'principals/test'

Fiddle: http://www.sqlfiddle.com/#!2/7acc8/4


text:
Q: Regular expression adjustment not working as expected I have the following regex https://regex101.com/r/arBFtI/2.
It is a regex for searching and replacing on a webpage. It searches and replaces the results by appending a highlight div so the words show up accordingly for the user.
In order to make sure the HTML itself is not changed (page can not break..) it recognizes HTML tags/attributes so it doesn't show a result in that.
But I have one more issue, now the regexp is strict and only shows a results if it is preceded with a space.
When searching for "export" it will show a result in the sentence above but not in the query below on db0383_bpost.export_201506.
In order to match on all "export" occurrences I can adjust the regex to be (?<![&((])export(?![^<>]*(([\/\"']|]]|\b)>)) but then the following problem arises.. HTML entities!
If you search on "b" for example using (?<![&((])b(?![^<>]*(([\/\"']|]]|\b)>)) it will also match the b in   ..
So I like the "strict" regexp (?<![&((\S+])export(?![^<>]*(([\/\"']|]]|\b)>)) or (?<![&((\S+])b(?![^<>]*(([\/\"']|]]|\b)>)) when searching for b but the only thing I need is for it to ignore HTML entities as well. So if I search for "b" it should match all the b's except in HTML entities and b's not between HTML tags.
It looks like a slight adjustment to the original regex in the (\S+]) part but I can't figure it out. Can you? Please help me I greatly appreciate it.


text:
Q: How to make a Convert To PDF button in HTML I tried making a button convert my HTML page into a PDF and downloads it, but I can't get it to work. For example, if this is the page:

function download() {
      print()
}

Page Content

The page content will go here...

    <button onclick="download()">Download Page</button>

     ^ The above button uses the print() function. However, this prompts the user with a print page, instead of asking to download.

The closest I got was adding a button that ran the print() function, however that asks the user to print the page, not download it.
Does anyone know how I can convert the HTML page to a pdf for download?

A: First, you make a php file (or whatever technique you want to use) to turn the html to pdf (for those who don't have this step completed, wkHtmlToPdf is nice for this).
The next step is optional, but recommended:
You create a download.php which reads the file, and echo's it to the screen, with the proper headers. This file can be secured (now, or later) eg maybe you want the user to be logged in for specific files. This can now easily be added.
And now you link in your html template to it: download. Because the download.php send headers to the browser (saying "hi there, I am a PDF, download me") the browser knows what to do with it.
If you want to skip the download.php, which again I dont recommend, just link directly to the convertToPdf.php and let thet output its result rather than storing it.

A: Option 1: The print() method prints the contents of the current window.
    <button onclick="window.print()">Download page</button>

Option 2: Use some server side technique to convert html to dpf like Martijn answer.
Option 3: Use jsPDF library to handle on client side. Check out https://rawgit.com/MrRio/jsPDF/master/, they have many examples there.
    function download() {
      var doc = new jsPDF();

      // All units are in the set measurement for the document
      // This can be changed to "pt" (points), "mm" (Default), "cm", "in"
      doc.fromHTML($('body').get(0), 15, 15, {
        'width': 170,
      });
      doc.save();
    }

<button onclick="download()">Download page</button>


text:
Q: What is the relationship between pi and Feigenbaum's constant? I am student who is new to bifurcation theory, and am interested in better understanding how Feigenbaum's constant relates to other constants.
This morning I divided pi (using math.pi in Python) by Feigenbaum's constant (to 30 decimal places; δ = 4.669201609102990671853203821578), which yielded 0.6728329416029073.
I found this number (rounded up to 6 decimal places) in a chart of elliptic integrals, but do not have enough understanding of bifurcation to draw a meaningful connection to the Heuman lambda function.
Is there any literature exploring period doubling and pi?

A:
What is the relationship between π and Feigenbaum's constant ? My inquiry was born  out of looking at this graphic.

$\quad$ They are both related to shapes determined by quadratic equations. Thus, the value of  the former is given by $~\dfrac\pi8=\displaystyle\int_0^1\sqrt{x(1-x)}~dx,~$ and that of the latter by the logistic map $x_{n+1}=r~x_n(1-x_n).~$ Notice any similarities there ? ;-$)$ Also, looking at the graphic, one  cannot help but notice that the periods in question resemble a parabola, which is hardly  surprising, since the recursive expression of $\{x\}_{n\in\mathbb N}$ is parabolic, and, as we all know, circles  and ellipses, as well as parabolas, are ultimately conic sections. But this should not by any  means be misconstrued by thinking that their numerical values are supposedly connected.  Thus, Euler's famous constant e is also related to the other conic section, the hyperbola,  since $~\displaystyle\int_1^e\dfrac1x~dx=1,~$ but no one actually expects them to be numerically related. $($Hope  this helps$).$


text:
Q: PHP - I want the user to have no possibility to upvote more than one time I am working on a small social network with PHP and MySQL
I want the users to have the possibility to upvote a post, and I already did this but the problem is that I want the user to be able to upvote only one time.
Here is my PHP code:
if (isset($_POST['heart']))
{
  $identificateur = $_POST['hide'];
  $Q = "UPDATE posts  SET avis = avis + 1 where id=$identificateur ";
  $bdd->query($Q);
}

This is the form of the upvote button :
<form action="p.php" method="POST">
        <label><?php
        if ($avis != 0)
                    {
                        echo $avis;
                    }
        ?></label>
        <input type="hidden" value="<?php echo "$id" ?>" name="hide">
        <input type="submit" value=" " id="heart" name="heart">
</form>

Every user should have the right to click on the up vote icon only once.
Thank you very much in  advance.

A: You need to have a second table, that has two fields, post_id and voter_id. (post_voter).post_id has a foreign key containing the id of the post table and voter_id has foreign key to the user table. This table specifies voters of a post and posts that users have voted for. When a user tries to upvote a post, you must check post_voter table and get count of rows which have the post_id equal to the post's id and voter_id equal to the user's id. If count = 0, this means the user has not upvoted the post, yet, and he can vote for it now. Otherwise, the user upvoted the post already and he can't upvote it again.


text:
Q: How can I get dates that wrap around new year from non-datetime columns? I have a table in my MySQL database that stores daily data (an entry for each day of the year), but does not use a DATETIME column for this. This is because the data is the same for every year (it's climatology data, so the "normal" high temperature for Jan 7, 2015 is the same as for Jan 7, 2016 and so on). I have three fields that represent the day this data is valid for, so my table looks like:
month, day_of_month, day_of_year, value
1      1             1            23
1      2             2            22.95
...
12     31            365          23.12

Say I then want to get the values from this table from a certain date, like 01 Dec 2015 to 60 days from then, which would be 30 Jan 2016. Is there a way to get back the date and value for all of those days, working okay across the new year? Ideally I'd love results that flow like:
valid_date, value
...
2015-12-31  23.12
2016-01-01  23
2016-01-02  22.95
...

(hopefully you get the idea).
If you can think of a better way to store this static daily data so that I can achieve the above goal, I'm open to that as well! Thanks for your help!

A: You can use MAKEDATE(), it makes the day_of_year to a date.
Test:
mysql> SELECT * FROM cli_table;
+-------+--------------+-------------+-------+
| month | day_of_month | day_of_year | value |
+-------+--------------+-------------+-------+
|     1 |            1 |           1 | 23.00 |
|     1 |            2 |           2 | 22.95 |
|    12 |           31 |         365 | 23.12 |
+-------+--------------+-------------+-------+
3 rows in set (0.00 sec)

mysql> SELECT
    -> MAKEDATE(YEAR(CURDATE()),day_of_year) AS Date,
    ->     value AS DayValue
    -> FROM test.cli_table;
+------------+----------+
| Date       | DayValue |
+------------+----------+
| 2015-01-01 |    23.00 |
| 2015-01-02 |    22.95 |
| 2015-12-31 |    23.12 |
+------------+----------+
3 rows in set (0.00 sec)

mysql>

You can try it in this Fiddle.
EDIT:
According of what you want, you can make it with pure SQL:
mysql> SELECT * FROM test.cli_table;
+-------+--------------+-------------+-------+
| month | day_of_month | day_of_year | value |
+-------+--------------+-------------+-------+
|     1 |            1 |           1 |  5.00 |
|     1 |            2 |           2 |  6.00 |
|     1 |            3 |           3 |  7.00 |
|    12 |           25 |         359 | 23.00 |
|    12 |           26 |         360 | 22.95 |
|    12 |           27 |         361 |  1.00 |
|    12 |           28 |         362 |  2.00 |
|    12 |           29 |         363 |  3.00 |
|    12 |           30 |         364 |  4.00 |
|    12 |           31 |         365 | 23.12 |
+-------+--------------+-------------+-------+
10 rows in set (0.00 sec)

mysql> SELECT
    -> v.selected_date,
    -> v.dayyear,
    -> c.value AS DayValue,
    -> c.day_of_year
    -> FROM test.cli_table AS c
    -> JOIN (SELECT
    -> adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) AS selected_date,
    -> DAYOFYEAR(adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i)) AS dayyear
    -> FROM
    -> (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
    -> (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
    -> (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
    -> (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
    -> (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) AS v
    -> ON (v.selected_date between '2015-12-25' AND '2016-01-03'
    -> AND v.dayyear=c.day_of_year);
+---------------+---------+----------+-------------+
| selected_date | dayyear | DayValue | day_of_year |
+---------------+---------+----------+-------------+
| 2015-12-25    |     359 |    23.00 |         359 |
| 2015-12-26    |     360 |    22.95 |         360 |
| 2015-12-27    |     361 |     1.00 |         361 |
| 2015-12-28    |     362 |     2.00 |         362 |
| 2015-12-29    |     363 |     3.00 |         363 |
| 2015-12-30    |     364 |     4.00 |         364 |
| 2015-12-31    |     365 |    23.12 |         365 |
| 2016-01-01    |       1 |     5.00 |           1 |
| 2016-01-02    |       2 |     6.00 |           2 |
| 2016-01-03    |       3 |     7.00 |           3 |
+---------------+---------+----------+-------------+
10 rows in set (0.00 sec)

mysql>

Query Meaning:
SELECT
    v.selected_date,
    v.dayyear,
    c.value AS DayValue,
    c.day_of_year
FROM test.cli_table AS c
--- > This JOIN is generating all the dates between the selected_dates ('2015-12-25' AND '2016-01-03')
JOIN (SELECT
        adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) AS selected_date,
        DAYOFYEAR(adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i)) AS dayyear
      FROM
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
     (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) AS v
--- > Here I'm matching every dayyear of the generated dates with the cli_table.day_of_year.
ON (v.selected_date between '2015-12-25' AND '2016-01-03'
    AND v.dayyear=c.day_of_year);

A: I'd suggest you use a proven BI date dimension design. Each reading is a Fact - stored in something like
CREATE TABLE FactDailyTemp
DateSK INT
Temp Numeric(10,5)

DateSK is an FK to DIM.Date. If you need time, simply add another column to the fact TimeSK and a time dimension table. There are plenty of free scripts to load these tables on the net. Here's an example to get you started.
Dim.Date looks like this and allows for all kinds of filtering such as DayOfYear while retaining the actual date. Additional flag columns can help with typical queries... in this example the three bit fields I've tacked onto the end of my dimension.
CREATE TABLE [DIM].[Date]
(
 [DateSK] INT NOT NULL
,[FullDate] DATETIME NULL
,[DateAbbreviation] VARCHAR(11) NULL   --US Date FORMAT, MM/DD/YYYY
,[DayOfWeek] TINYINT NULL
,[DayNameOfWeek] CHAR(10) NULL
,[DayOfMonth] TINYINT NULL
,[DayOfYear] SMALLINT NULL
,[WeekOfYear] TINYINT NULL
,[MonthName] CHAR(10) NULL
,[MonthOfYear] TINYINT NULL
,[CalendarQuarter] TINYINT NULL
,[CalendarYear] SMALLINT NULL
,[CalendarYearMonth] CHAR(7) NULL
,[CalendarYearQtr] CHAR(7) NULL
,[Weekday] bit NULL
,[IsLastDayOfMonth] bit NULL
,[IsCurrentYear] bit NULL
,CONSTRAINT [PK_DimDate] PRIMARY KEY CLUSTERED ( [DateSK] )
)

This approach is called Dimensional Modeling and is suited to long term storage and analysis of large sets of data. If this works for you, I'd suggest investigating in more detail.
Specifically to the query you asked for, you can easily use the FullDate column with a DATE_ADD query.


text:
Q: What is the most efficient way to pass numpy array to c++ function and return numpy array as output? I've created a shared library. And I'm using it like that
class CAudioRecoveryStrategy(AbstractAudioRecoveryStrategy):
    def __init__(self):
        array_1d_double = npct.ndpointer(dtype=numpy.double, ndim=1, flags='CONTIGUOUS')
        self.lib = npct.load_library("libhello", ".")

        self.lib.demodulate.argtypes = [array_1d_double, array_1d_double, ctypes.c_int]

    def demodulate(self, input):
        output = numpy.empty_like(input)
        self.lib.demodulate(input, output, input.size)
        return output

Right now I have a problem, which is in c++ code I only have pointer to array of output data, not the array. So I can't return the array, unless I manually copy it.
What is the right way to do it? It must be efficient (like aligned memory etc.)

A: Numpy arrays implement the buffer protocol, see
https://docs.python.org/2/c-api/buffer.html.  In particular,
parse the input object to a PyObject* (conversion O if you're
using PyArg_ParseTuple or PyArg_ParseTupleAndKeywords), then
do PyObject_CheckBuffer, to ensure that the type supports the
protocol (numpy arrays do), then PyObject_GetBuffer to fill in
a Py_buffer struct with the physical addresses, dimensions,
etc. of the underlying memory block.  To return a numpy buffer
is more complicated; in general, I've found it sufficient to
create objects of my own type which also support the buffer
protocol (set tp_as_buffer to non null in the PyTypeObject).
Otherwise (but I've not actually tried this), you'll have to
import the numpy module, get its array attribute, call it with
the correct arguments, and then use the buffer protocol above on
the object you thus construct.


text:
Q: Getting Text from external URL via AngularJS I'm trying to get the JSON-Text-Stream from an URL (e.g. SOMEURL/ean.php?id=4001513007704). The result looks like this:

{
    "product": {
        "ean_id": "4001513007704",
        "title": "Gerolsteiner Mineralwasser",
...
     },
    "success": true
}

As you can see these are some informations for scanned items.
I searched for implementations using URLs (--> http://www.w3schools.com/angular/tryit.asp?filename=try_ng_http_get ) and this example only works for the internal URL. Google and other sources leave the variable blank.
This does work. It returns the HTML-Code of the entered website:

<!DOCTYPE html>

Today's welcome message is:

{{myWelcome}}

The $http service requests a page on the server, and the response is set as the value of the "myWelcome" variable.

And this doesn't (variable is left blank). In this case i use Google but usually we would use another source!

I assume that it's because of the security settings from the website..
How can i get the data from the URL? Is there any workaround?
Thanks for any kind of help!

A: response.data will only return something if there is a data object within response.
The response thatyou get when you send a request to google.com is this:
<TITLE>302 Moved</TITLE>

302 Moved

The document has moved
here.

This is because that URL serves up an HTML, and not some JSON response.
If you do a response.data on this, it will be undefined because there is no data there. If you hit a proper end point that has JSON data, you will get your response.
For example if you change the url to https://api.github.com/users/mralexgray/repos, you'll see data.

A: You are getting this error because you are not defining the angular module to be included in the html.
Try running the above code in w3 schools with the link http://google.com/ in the site as shown

<!DOCTYPE html>

Today's welcome message is:

{{myWelcome}}

The $http service requests a page on the server, and the response is set as the value of the "myWelcome" variable.


text:
Q: Threejs Shadows not rendering So I have looked over all the other shadow issues on here, and none of them seemed relevant to mine, or I just overlooked it about 10 times.
https://gist.github.com/Sinistralis/58249d2f9aefa8f08a7d
I would make a fiddle for this, but the version they host seems incompatible with either my code or the current version of chrome. I could not get it to work even after changing .merge and BoxGeometry back to GeometryUtils and CudeGeometry respectively.
Basically, I am getting 0 shadows using threejs v .71
I have all the cast booleans set, the scene is within my shadowmap, and I am using a correct light type. Why am I not getting shadows?

A: This is not going to be very helpful to other users, unfortunately...
The proper spelling is receive.
floor.receiveShadow = true;
city.receiveShadow = true;

Also, have a look at this post about self-shadowing artifacts.
three.js r.71


text:
Q: How to avoid Switch case on input values I asked myself a question to optimize my code in JavaScript.
I am currently doing something like this :
Data.json :
{
  "House" :
    { "bedroom"  : "4" }
    { "kitchen"  : "1" }
    { "bathroom" : "2" }
}

Choose.js :
var Data = require('./Data.json');

printData = function(id) {
  console.log(getData(id));
}

getData = function(id) {
  switch (id) {
    case "bedroom":
      return Data.House.bedroom;
    case "kitchen":
      return Data.House.kitchen;
    case "bathroom":
      return Data.House.bathroom;
    default:
      break;
  }
}

And I would like to know if we could optimize this with a special syntax, for example if we simply have :
var Data = require('./Data.json');

printData = function(id) {
  console.log(Data.House.{ id });
}

I know this might be a stupid question for you but it would be helpful if you tell me if it's possible or not. I wish I could avoid very long Switch Cases in my project.
Thanks.

A: Use [] notation
printData=function(id){
    return Data.House[id];
}

A: You can do it:

var Data = {
  "House" : {
    "bedroom"  : "4",
    "kitchen"  : "1",
    "bathroom" : "2"
  }
};

getData = function(id) {
  return Data.House[id];
}

console.log(getData('bedroom'));
console.log(getData('kitchen'));
console.log(getData('xxx'));

A: getData=function(id){
   if(Data.House.hasOwnProperty(id)) return Data.House[id];
    return '';
}


text:
Q: Sending data to nodejs server I'm learning nodejs at the moment and I'm stuck with a few things.
I'm creating a server that's serving a html file. That html file has a js that does an xmlHttpRequest to get data. The data I'm retrieving I want to send back to my server to process it. And that last step is where I'm stuck. every time the server stops, while I would like to receive the urls in the server to process them.
Server.js
var http = require('http'),
    url = require('url'),
    path = require('path'),
    fs = require('fs');

var mimeTypes = {
    "html": "text/html",
    "js": "text/javascript",
    "css": "text/css"};

    http.createServer(function(request, response){

        var uri = url.parse(request.url).pathname;
        var filename = path.join(process.cwd(), uri);

        fs.exists(filename, function(exists){
            if(!exists){
                console.log(filename + " does not exist");
                response.writeHead(200, {'Content-Type' : 'text/plain'});
                response.write('404 Not found\n');
                response.end();
                return;
            }

            var mimeType = mimeTypes[path.extname().split(".")[1]];
            response.writeHead(200, {'Content-Type' : mimeType});

            var fileStream = fs.createReadStream(filename);
            fileStream.pipe(response);
        });

    response.on('end', function(){
        console.log("Request: " + request);
        console.log("Response: " + response);
    });

    }).listen(1337);

Client.js
function getURLs(){
    var moduleURL = document.getElementById("url").value;
    var urls = [];
    console.log(moduleURL);

    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange=function(){
      if (xmlhttp.readyState==4 && xmlhttp.status==200){
            var xml = xmlhttp.responseXML;
            var items = xml.children[0].children[0].children;

            for(var i = 13; i<items.length; i++){
                urls.push(items[i].children[1].getAttribute("url")+"&hd=yes");
            }

            //console.log(urls);
            sendDataToServer(urls);
        }
      }
    xmlhttp.open("GET", moduleURL, true);
    xmlhttp.send();

}

function sendDataToServer(urls){
    //console.log(urls);

    var http = new XMLHttpRequest();
    http.open("POST", "http://127.0.0.1:1337/", true);
    http.send(urls);
}

I'm getting this in the console of the browser

POST http://127.0.0.1:1337/ net::ERR_CONNECTION_REFUSED

And this in cmd of node

events.js:72
          throw er; // Unhandled 'error' event
                ^ Error: EISDIR, read

And while it's processing the data I would like to send back the progress to the client to show it on the html page for the end user. I already have the function of the progress it's only the sending/receiving of data where I am stuck. Can someone point me in the correct direction please?
I also know that there is express and other modules that I can use, but to learn node I'm trying it to do it this way. So I hope someone can push me in the correct direction.

A:
events.js:72 throw er; // Unhandled 'error' event ^ Error: EISDIR, read

This error means that the file you're trying to read is actually a directory.
What you need to do is make sure that the file is really a file as the function fs.exists() is only for files.
In this example fs.lstat() is used to get a fs.stat object which has the methods you need to make sure that a file is of the right type.
var http = require('http'),
url = require('url'),
path = require('path'),
fs = require('fs');

var mimeTypes = {
    "html": "text/html",
    "js": "text/javascript",
    "css": "text/css"
};

http.createServer(function(request, response){

    var uri = url.parse(request.url).pathname;
    var filename = path.resolve(path.join(process.cwd(), uri));
    console.log(filename);

    // Get some information about the file
    fs.lstat(filename, function(err, stats) {

      // Handle errors
      if(err) {
        response.writeHead(500, {'Content-Type' : 'text/plain'});
        response.write('Error while trying to get information about file\n');
        response.end();
        return false;
      }

      // Check if the file is a file.
      if (stats.isFile()) {

        fs.exists(filename, function(exists){
            if(!exists){
                console.log(filename + " does not exist");
                response.writeHead(200, {'Content-Type' : 'text/plain'});
                response.write('404 Not found\n');
                response.end();
                return;
            }

            var mimeType = mimeTypes[path.extname().split(".")[1]];
            response.writeHead(200, {'Content-Type' : mimeType});

            var fileStream = fs.createReadStream(filename);
            fileStream.pipe(response);
        });

      } else {
        // Tell the user what is going on.
        response.writeHead(404, {'Content-Type' : 'text/plain'});
        response.write('Request url doesn\'t correspond to a file. \n');
        response.end();
      }

    });

response.on('end', function(){
    console.log("Request: " + request);
    console.log("Response: " + response);
});

}).listen(1337);


text:
Q: ODI12C: Unable to Load Control Characters from XML File My XML File contains invalid Characters. Can some one help me how to load those from XML in ODI12C?
Error: ODI is throwing an error saying Invalid characters.
The value from the XML file looks like this : LA CASUBADA FLINTRIDGE.
But the original value is LA CAÑADA FLINTRIDGE
When I have searched I found that it is an control character and supported by oracle. But, I'm unable to load the value from the file.
Thanks for the help in advance.


text:
Q: ruby language - merge an array into another by finding same element A = [
  { :id => 1, :name => 'good', :link => nil },
  { :id => 2, :name => 'bad', :link => nil }
]

B = [
  { :id => 3, :name => 'good' },
  { :id => 4, :name => 'good' },
  { :id => 5, :name => 'bad' }
]

I need to merge array B into A so that :link in array A includes the entry in array B if :name is the same value in each array.
For example, after processing array A should be:
A = [
  { :id => 1, :name => 'good', :link => [{ :id => 3, :name => 'good' }, { :id => 4, :name => 'good' }] },
  { :id => 2, :name => 'bad', :link => [{ :id => 5, :name => 'bad' }] }
]

thanks.

A: The short version;
a.each { | item | item[:link] = b.find_all { | x | x[:name] == item[:name] } }

Demo here.

A: In ruby the constants begin with an uppercase letter, so you should use lowercase letter:
A => a, B => b
a.each do |ha|
  b.each do |hb|
    if ha[:name] == hb[:name]
      ha[:link] |= []
      ha[:link] << hb
    end
  end
end

A: Functional approach:
B_grouped = B.group_by { |h| h[:name]  }
A2 = A.map { |h| h.merge(:link => B_grouped[h[:name]]) }
#=> [{:link=>[{:name=>"good", :id=>3}, {:name=>"good", :id=>4}], :name=>"good", :id=>1},
#    {:link=>[{:name=>"bad", :id=>5}], :name=>"bad", :id=>2}]


text:
Q: Integral of Motion in the 1D Calogero Model In section 4 of this article, suppose we have $N$ particles of the same mass $m$ moving in one dimension and interacting with each other via the potential $V_{ij}\equiv V(x_i - x_j)$, where $x_i$ denotes the position of the $i$-th particle. Because the total momentum
$$
I_1 = m\sum_i \dot{x}_i
$$
and energy
$$
E = \frac{m}{2}\sum_i \dot{x}_i^2 + \sum_{1\leqslant i < j\leqslant N}V_{ij}
$$
are conserved, we have that
$$
I_2:= \frac{1}{2}I_1^2 - E = \left(m^2\sum_{1\leqslant i < j\leqslant N}\dot{x}_i\dot{x}_j\right) - \left(\sum_{1\leqslant i < j\leqslant N}V_{ij}\right).
$$
is also conserved.
I am stuck when trying to derive $I_3$ in the article, with the same constraints (that is, $\sum_{1\leqslant i < j < k\leqslant N}V_{ij}'V_{jk} = 0$). I do not have any clue for deriving the expression of $I_3$ (which is also a constant) as proposed in the article:
$$
I_3 = \left(m^3\sum_{1\leqslant i<j<k\leqslant N}\dot{x_i}\dot{x_j}\dot{x_k}\right) - \left(m\sum_{1\leqslant i<j<k\leqslant N}\dot{x}_i V_{jk}\right).
$$
Could anyone please provide some hints? Any of your help will be greatly appreciated! :)

Please Note:  I am also a little bewildered about the derivation of $I_2$. I am not sure whether it is a typo in the document, but it seems that
$$
I_2 = \frac{1}{2m}I_1^2 - E = \left(m\sum_{1\leqslant i < j\leqslant N} \dot{x}_i\dot{x}_j\right) - \left(\sum_{1\leqslant i < j\leqslant N}V_{ij}\right)
$$
makes more sense than that in the article, in which I am not sure how the terms $\frac{m^2}{2} \sum_i \dot{x}_i^2$ and $\frac{m}{2}\sum_i \dot{x}_i^2$ cancelled out.

A: for 2 particles
$$T=\frac m2\,(\dot{x}_1^2+\dot{x}_2^2)$$
$$V=\frac 12 \,(x_1^2+(x_2-x_1)^2)=-x_2\,x_1$$
$$E=T+V$$
$$p=m\,(\dot{x}_1+\dot{x}_2)$$
thus :
$$I_2=\frac 12\,p^2-E=m^2\,\dot{x}_1\,\dot{x}_2-V(x_1\,x_2)$$
with : $$\dot{x}_1^2=0~,\dot{x}_2^2=0~,x_1^2=0~,x_2^2=0$$
for 3 particles
$$T=\frac m2\,(\dot{x}_1^2+\dot{x}_2^2+\dot{x}_2^3)$$
$$V=\frac 12\,(x_1^2+(x_2-x_1)^2+(x_3-x_2)^2))=-x_1\,x_2-x_2\,x_3$$
$$E=T+V$$
$$p=m\,(\dot{x}_1+\dot{x}_2+\dot{x}_3)$$
thus:
$$I_3=\frac 12\,p^3-p\,E=3\,m^3\,\dot{x}_1\,\dot{x}_2\,\dot{x}_3-p\,V$$
Edit
all square  and cubic products are zero
$$\frac 12\,p^3=\frac 12\,m^3\,(\dot{x}_1+\dot{x}_2+\dot{x}_3)^3:=3\,m^3\dot{x}_1\dot{x}_2\dot{x}_3$$
$$-p\,E=-p\,(T+V)=-p\,(\frac m2\,(\dot{x}_1^2+\dot{x}_2^2+\dot{x}_2^3))-p\,V:=-p\,0-p\,V$$


text:
Q: My subscriber has the "edit comment" capability but can't edit comment When i use the wp_get_current_user function to display all informations about my user (subscriber), it shows that i can edit comment :

I tried to display an edit comment button next to each comment that belongs to my user. However, in the edit_comment_link func there is this condition that checks if the user can edit comment :

And it turns out that this condition doesn't pass. I don't get how this could be true on one side and false on the other side...
I disable all my plugins and the problem is still here so i don't think it comes from this... i can't find any answer helpful, nothing works so far...
Does anyone have any idea? :(


text:
Q: Copy executing files from a UNC path I am writing an application that needs to copy files from a network directory, where the files are currently executing.
I have tried opening the file with
using (var source = new FileStream(fileData.FileName,
                                   FileMode.Open,
                                   FileAccess.Read,
                                   FileShare.ReadWrite))

After I open the file stream I create another stream to copy into.
However, this throws an exception saying that the file is in use by another process. I am not sure how to get around this problem. If I just use file explorer it will copy the files fine. So I know that it is possible, just not sure on how.
EDIT:
I have also tried the simple File.Copy(source, destination) and I get the same exception saying the file is in use by another process.

A: To copy a file that is being used by another process, we have to make use of two services in Windows, and you'll need to verify that these services are not disabled:

*

*Volume Shadow Copy

*Microsoft Software Shadow Copy Provider

They can be left as Manual startup, so they don't need to be running all the time.
For this, we can use any 3rd party tool. Hobocopy is one of them. It will start the two services automatically when needed, and the Volume Shadow Copy service will be turned back off after it's done.
Download Link: https://github.com/candera/hobocopy/downloads
Unzip the file and place them into Lib directory of your project. Then call the process using System.Diagnostics.Process. In your case, just use the following switch as argument: /y (Don't prompt, just copy everything)
Command-Line Syntax:
hobocopy [/statefile=FILE] [/verbosity=LEVEL] [ /full | /incremental ]
     [ /clear ] [ /skipdenied ] [ /y ] [ /simulate ] [/recursive]
     src dest [file [file [ ... ] ]

C# code:
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = @"Lib\hobocopy.exe";
process.StartInfo.Arguments = @" /y <network-directory> <local-directory> <filename>";
process.Start();

This'll copy any files (hobocopy focuses mainly on copying directories efficiently) that is being used or unused to your destination.


text:
Q: Bot Framework serviceUrl I am developing a Notification Only bot to enable proactive Teams notifications.
As far as I am aware it is necessary to store the ServiceUrl from an incoming message to the bot endpoint. I have read that it is also possible that service Url can change in the future (although unlikely) and that if this happens the serviceUrl should be updated and used for future messages.
Using a test O365 instance in UK region I see the following behaviour:
When I add member to team or install the app to a team, the service Url comes through as:
https://smba.trafficmanager.net/uk/
When I remove a member from team or remove the app from team, the service Url comes through as:
https://smba.trafficmanager.net/emea/
If our service tries to send a notification via the rest api, using the /emea ServiceUrl it returns a 403 Forbidden
Doing the same using an O365 instance in US region the service Url is allways:
https://smba.trafficmanager.net/amer/
Is this expected behaviour or a bug?
Are there any rules on when the Service Url should be updated and when it should not?
Many Thanks.


text:
Q: Under what conditions does ABC=AB'C imply B=B'? I am doing some linear algebra HW, and I am trying to prove the statement:
Let $\langle \textbf{x},\textbf{y}\rangle_B=\textbf{x}^TB\textbf{y}$, where $\textbf{x},\textbf{y}\in \mathbb{R}^n$. Then $B=B^T\iff\langle \textbf{x},\textbf{y}\rangle_B=\langle \textbf{y},\textbf{x}\rangle_B$.
In proving the reverse, I managed to show that $\textbf{x}^TB\textbf{y}=\textbf{x}^TB^T\textbf{y}$. However, I am unsure how to justify that $B=B^T$. Under what conditions does $ABC=AB'C$ imply $B=B'$? Thanks!


text:
Q: Using Jackson with Map I want to know if there is some way to get the following deserializing properly:
public class MyClass {
     Map<String, Serializable> map;
     OtherObject object;
     [...]
}

ObjectMapper mapper = new ObjectMapper();
MyClass instance = mapper.readValue(someJson, MyClass);

Currently, I'm trying and I get an exception
com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of java.io.Serializable: abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information

A: As of v2.10.0, Jackson supports naive deserialization of 'Serializable' values, i.e., it will consider 'Serializable' the same as 'Object'.
See this Github issue for more details.
So update Jackson to 2.10.0+ and try.

A: You can change your data class's Map property declaration to not reference Serializable:
public class MyClass {
     Map<String, ?> map;
     OtherObject object;
     [...]
}

This will affect the signature of the Map's getter and setter as well. This does loosen type-checking, however, and the the map's values could be any subclass of Object instead of implementations of Serializable. If that's an important detail, you could do post-serialization validation of the map values.
Or you can configure a custom Deserializer, as those in your question's comments have suggested. It's just a matter of where you want to add the code, and that depends on how widespread this case is in your application.


text:
Q: How to change XHTML closing tags automatically in Notepad++ I apologize if this has been asked before, but I don't believe it's been clearly asked, causing a lot of confusion on stackoverflow....I'm using Notepad v6.6.9 and I am looking for way to automaticlaly change my closing element tags when I want to "later" change my opening element tags. For example if I have an XHTML page with the following content....

hello world

...and I save this page, and re-open it, and then click to change
 to
, I want notepad++ to automatically change my closing
 element to

Another way to put it:
"As I am typing and changing the currently selected opening tag, I want the closing tag to automatically change during the same time."
Is this possible in Notepad++? If so, how?
Thanks

A: I'm not sure I fully understood your question but I'll try to answer it.
you can replace all your inside tags with notepad++ using this way:

*

*click on CTRL+F to open the find pop up.

*navigate to replace tab

*for your example, Replace only the P inside the tags to make it h3.

*Click Replace All.

This will replace all the P into h3 and keep your starting / ending tags unharmed.
Hope that was helpful.
EDIT: Based on my comment, below is my trick:

*

*go to settings menu

*click on preferences

*select Auto-completion

*check the html/ xml close tags

As I said, this will auto close the tags but I did not test it for auto changing closed tags.


text:
Q: Update the url using javascript / jQuery I want to update my page URL on click of something.
Then when I share the updated URL I want it to open in that same updated state so that I can share the updated view. How do I achieve this??


text:
Q: How to use pandas Styler to escape percentage for LaTeX I would like to export a dataframe containing percentage values like
df = pd.DataFrame([0.2323, 0.5254, 1], columns=['c'])

to LaTeX which can be done by
df.style.format('{:.2%}').to_latex()

This returns
\begin{tabular}{lr}
 & c \\
0 & 23.23% \\
1 & 52.54% \\
2 & 100.00% \\
\end{tabular}

which is obviously no valid TeX code since % is not properly escaped. How do I do that?
df.to_latex(float_format='{:0.2%}'.format)

would work but I get a deprecation warning:

FutureWarning: In future versions `DataFrame.to_latex` is expected to utilise the base implementation of `Styler.to_latex` for formatting and rendering. The arguments signature may therefore change. It is recommended instead to use `DataFrame.style.to_latex` which also contains additional functionality.

A: My approach:
df = pd.DataFrame([0.2323, 0.5254, 1], columns=['c'])
df.style.format(lambda s: '{:.2f}\%'.format(s*100)).to_latex()

which gives
\begin{tabular}{lr}
 & c \\
0 & 23.23\% \\
1 & 52.54\% \\
2 & 100.00\% \\
\end{tabular}

A: I found a wonderful tool that does what I need wonderfully: tabulate
df = pd.DataFrame([0.2323, 0.5254, 1], columns=['c'])
print(tabulate(df, intfmt=",", floatfmt='.2%', tablefmt='latex', headers=df.columns))

prints

\begin{tabular}{rr}
\hline
    &       c \\
\hline
  0 &  23.23\% \\
  1 &  52.54\% \\
  2 & 100.00\% \\
\hline
\end{tabular}

Yet another option could be texttable (or its latex-focused extensions latextable), but I haven't checked them yet.


text:
Q: Executing SQL query joins on Cosmos DB using Azure Mobile Apps for Node I'm currently developing a back end for a mobile system using Azure Mobile Apps with Node.js and Azure Cosmos DB (Document DB).
I'm using the example that was given here:
https://github.com/Azure/azure-mobile-apps-node/blob/master/samples/custom-api-sql-stmt/api/completeall.js
So far so good - however, whenever I run this SQL, I get:
TypeError: provider.read is not a function
    at Function.module.exports.api.execute (x:\x\node_modules\azure-mobile-apps\src\data\index.js:32:18
The SQL I need to run looks like this:
SELECT c.id, c.Email FROM Profile c JOIN d in c.DeviceIDs WHERE d.DeviceID = @deviceId
This is because my data is nested, like this (the Profile collection in Cosmos) - I need to get the records where the DeviceID matches:
[
    {
        "id": "2ca572d0-858d-4376-8537-c228a8379638",
        "Email": "test@user.com",
        "Name": "Test User 1",
        "OrgRoles": null,
        "DeviceIDs": [
            {
                "DeviceID": "123445555555",
                "DeviceCode": "1234"
            }
        ],
        "UpdatedDate": "2017-11-10T13:18:32.0110724Z",
        "CreatedDate": "2017-11-10T13:18:27.220764Z",
        "IsDeleted": true
}]
I would love to be able to do this the other way, using something like this:
context.tables('Profile').where({ DeviceID: id })
but I cannot figure out how on earth to accomplish joins using this method, let alone joins on the same table.
Can anyone help with either method? I get the feeling the Azure Mobile Apps Document DB driver hasn't been finished properly by MS, but I can't seem to get a hold of anyone to see if there's any way I can help.
UPDATE: We have managed to do this via the document db driver directly, but it means that we will need to have some of our api methods connecting to the database one way and some others connecting a different way. Seems a shame, Microsoft should fully invest in Cosmos - it's quite good imho.

A: As the Azure Mobile Apps Node.js SDK doesn't support Cosmos DB driver, you would need to integrate the SDK azure-documentdb-node into your mobile app.
var documentClient = require("documentdb").DocumentClient;

var endpoint = 'https://<account_name>.documents.azure.com:443/';
var primaryKey = '<primary_key>';
var client = new documentClient(endpoint, { "masterKey": primaryKey });

var databaseUrl = `dbs/<database_name>`;
var collectionUrl = `${databaseUrl}/colls/Profile`;

var querySpec = {
    'query': 'SELECT c.id, c.Email FROM Profile c JOIN d in c.DeviceIDs WHERE d.DeviceID = @deviceId',

    "parameters": [
        { "name": "@deviceId", "value": '123445555555' }
    ]
}

client.queryDocuments(collectionUrl, querySpec).toArray(function(err, results) {
    if(err) return console.log(err);

    console.log(results);
});