text:
Q: postfix smtp connection timed out, why? A CentOS 7 web server has postfix, dovecot, and mailx installed.  I have been able to make an IMAP connection to the server in order to read inbox mail using a remote Thunderbird client, but I am not able to make an SMTP connection to send email from Thunderbird.  When I do forensics, I discover that the attempted SMTP connection times out.  How can I resolve this problem of the connection timing out, so that I can send email from Thunderbird through the server?
My forensics so far have resulted in:
Typing hostname in the terminal at the server returns mydomain.com.
nano /usr/lib/firewalld/services/smtp.xml indicates the smtp port is 25
The smtp service is activated in the public zone because firewall-cmd --list-all results in:
public (default, active)
  interfaces: enp3s0
  sources:
  services: dhcpv6-client imaps openvpn smtp
  ports:
  masquerade: yes
  forward-ports:
  icmp-blocks:
  rich rules:

But when I try to telnet from my devbox to the remote CentOS 7 server, I get the following results.  Typing telnet mydomain.com 25 resulted in:
Trying my.SERVER.ip.addr...
telnet: connect to address my.SERVER.ip.addr: Connection timed out

Then typing telnet smtp.mydomain.com 25 resulted in:
Trying my.SERVER.ip.addr...
telnet: connect to address my.SERVER.ip.addr: Connection timed out

Also, typing openssl s_client -CApath /etc/ssl/certs -starttls smtp -port 25 -host smtp.mydomain.com results in:
socket: Connection timed out
connect:errno=110

Similarly, typing openssl s_client -CApath /etc/ssl/certs -starttls smtp -port 25 -host mydomain.com also resulted in:
socket: Connection timed out
connect:errno=110

I typed nano /etc/postfix/main.cf to start to examine the config, but did not find anything related to ports.
EDIT:
As per FaheemMitha's advice, I tried telnet mydomain.com 587 from the client, and got No route to host in reply.  I think this is because only port 25 is open in firewalld for smtp.
I therefore thought to try telnet from within the remote server mydomain.com.  When I logged on to my remote server via ssh and typed telnet localhost 25, the result was:
Trying 127.0.0.1...
Connected to localhost.
Escape character is '^]'.
220 mydomain.com ESMTP Postfix

This causes me to suspect that postfix is running on port 25, but that somehow it is not able to accept outside connections.
EDIT#2
As per @RedCricket's suggestion, I ran iptables -L.  Since the results were verbose, I uploaded them to a file sharing site, which you can view by clicking on this link.
I also tried iptables --flush followed by firewall-cmd --reload, and then repeated the telnet and thunderbird tests from above, but I am still getting the connection timed out error.
What else can I try?
I uploaded the entire /etc/postfix/main.cf to a file sharing site.  You can read it by clicking on this link.
EDIT#3
A valid email address someone.else@some_other_domain.com sends email to me@mydomain.com without problems.  Therefore, as a test, I had my remote Thunderbird client try to send email to that someone.else@some_other_domain.com as part of the work documented above in this OP.  This morning, I received a return to sender message in my Thunderbird as a result of the test email.  I interpret this returned message to mean that at least one of my test messages from Thunderbird got into the SMTP on mydomain.com, but that mydomain.com was not able to look up or otherwise connect to some_other_domain.com.  Here is the message:
This is the mail system at host mydomain.com.

I'm sorry to have to someone.elserm you that your message could not
be delivered to one or more recipients. It's attached below.

For further assistance, please send mail to postmaster.

If you do so, please include this problem report. You can
delete your own text from the attached returned message.

The mail system

<someone.else@some_other_domain.com>: Host or domain name not found. Name service error for
    name=some_other_domain.com type=MX: Host not found, try again

Reporting-MTA: dns; mydomain.com
X-Postfix-Queue-ID: 2C915811BD1C
X-Postfix-Sender: rfc822; me@mydomain.com
Arrival-Date: Mon, 23 Feb 2015 16:46:34 -0500 (EST)

Final-Recipient: rfc822; someone.else@some_other_domain.com
Action: failed
Status: 4.4.3
Diagnostic-Code: X-Postfix; Host or domain name not found. Name service error
    for name=some_other_domain.com type=MX: Host not found, try again

ForwardedMessage.eml
Subject: key enclosed
From: me@mydomain.com
Date: 02/23/2015 01:46 PM
To:    someone.else@some_other_domain.com

this is the body of the email

Thus, it seems that sometimes the connection from my remote devbox to mydomain.com is closed, and at other times, the connection from mydomain.com to the rest of the internet is closed.
EDIT#4
Following @derobert's advice, I first tried the two telnet commands from the devbox to the server, then I tried to send an email from me@mydomain.com using the Thunderbird client on my devbox, and then I ran the tcpdump command on both the devbox and on the server.  Typing tcpdump port 25 in the devbox terminal resulted in the following:
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode

listening on tun0, link-type RAW (Raw IP), capture size 65535 bytes
    ^C
    0 packets captured
    0 packets received by filter
    0 packets dropped by kernel
Next, typing tcpdump on the server resulted in so much output that the results scrolled endlessly until I typed Ctrl-C.  So I then typed tcpdump port 25 and got the following results:
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on tun0, link-type RAW (Raw IP), capture size 65535 bytes
^C
0 packets captured
0 packets received by filter
0 packets dropped by kernel

As a curiosity, I then typed tcpdump port 25 again  on both the devbox and the server simultaneously and left it open without typing Ctrl-C, and I tried to manually send an email from me@mydomain.com using Thunderbird client on my devbox.  I still  got the same Connection timeout failure, but there was no activity reported by the open tcpdump port 25 commands.  And the totals also came up to zero when I typed Ctrl-C on both terminals afterwards.

A: After much troubleshooting, we determined that the ISP on the client side is blocking outgoing port 25 (SMTP). That was confirmed by using a random mail server test site on the Internet and finding that it could connect to the mail server fine. SMTP packets from the client machine did not arrive at all (confirmed via tcpdump).
Solution is to reconfigure SMTP listener on a different port. 465 (SMTP over SSL) and 587 (mail submission, RFC6409) are common options.


text:
Q: Hide element text but not child text Consider this element hierarchy

    A

B

Is it possible to hide text A but not B with CSS? The layout should also leave no empty space where A would be.
What I tried:

*

*Setting visibility to hidden and resetting it on child leaves blank space

*Setting font-size to 0 on parent and resetting on child works in FF but not WebKit on iOS

Here is a JSFiddle for the problem

A: You may try using visibility:collapse:
body > span{
    visibility:collapse;
}
span > span {
    visibility:visible;
}

Fiddle Demo
Also this works with visibility:hidden;
body > span{
    visibility:hidden;
}
span > span {
    visibility:visible;
}

Fiddle Demo

A: Try this:
Use your same concept like this
CSS:
     #a {
           visibility:hidden;
           font-size:0px
        }
        #b {
            visibility:visible;
            font-size:10px
        }

HTML:
 A
    B

DEMO1
DEMO2
FOR this HTML:

A

B

DEMO UPDATED

A: Yeah, I think you're on the right track with the visibility stuff: it's the only property where the display doesn't override the visibility of the child element (display: none cannot be overridden on a child element).
Note that visibility: collapse is only applicable for table-cells (and works poorly even there): visibility: hidden is what you're after.
To counter the non-collapsing nature of visibility toggling, your could try to fiddle with absolute positioning.
Check out this demo for the basic idea: http://jsbin.com/hetis/2/edit

redpajama_set_name: RedPajamaStackExchange


text:
Q: Don't understand why my function is not being called print ("Hello, User :)")
def search():
    answer = phrase.find(search)
    return answer

y = "Y"
while y == "Y":

    phrase = input("Please enter a phrase any phrase: ")
    print ("Thank you User - the phrase you entered reads as follows: ")
    print (phrase)

    search = input("Please enter one of the words of the phrase you just entered, or some consecutive characters from that phrase, and I will search for them: ")
    print ("Thank you, User")
    print ("Your word or characters are located at the following index location: ")
    search()
    #print (answer)

    y = input("Thanks for playing.  Would you like to play again(Y/N)?: ")
else:
    print ("Goodby, User")

Hoping someone can help why my function definition cannot be called.

A: The name of your function can't be the same as the variable name. Just change the search variable name like this:
search_ = input("Please enter one of the words of the phrase you just entered, or some consecutive characters from that phrase, and I will search for them: ")

search()

Also if you want the result to be printed out call the function like this:
print(search())


text:
Q: jQuery block moving I wanna move a div block to the top, so I coded like this:
CSS part:
.movingPart{
margin-top:80px;
}

jQuery part:
$(document).ready(function() {
$('#btn').click(function() {

    $('.movingPart').animate({
        "margin-top":'0px'

    });

});

});
it works perfectly in chrome, but doesn't move a little in firefox, why???
thanks in advance

A: The jQuery docs indicate that you should use camelCase for properties when using animate.

Note that properties should be
  specified using camel case, e.g.
  "marginLeft" instead of "margin-left."


text:
Q: How do I tell how close I'm getting to somaxconn? The sysctl option net.core.somaxconn defaults to 128 (on our systems) but can be raised.

*

*What exactly is this limit measuring and capping?

*How do I find out how close I am to the limit?
Context: I had a problem recently that appeared to be corrected by raising this limit. The problem was intermittent, so I don't trust that it is really fixed. I would like to find out if the current number of [whatever this setting caps] is greater than the previous maximum limit of 128.

A: somaxconn determines the maximum number of backlogged connections allowed for each TCP port on the system. Increasing it (recommended for servers) can prevent "connection refused" messages, but it can result in slow connections if the server can't handle the increased load.
You can check the current backlog with netstat -ant | grep -c SYN_REC according to this page. It will count how many connections are in the "SYN received" state, meaning the system has received a SYN packet (connection request) but hasn't acknowledged it yet.
If your system has ss installed, you can also use ss -s to display a summary of connections. Look for synrecv in the output, or ss -s | grep -Po '(?<=synrecv )\d+(?=,)' to just print the number.


text:
Q: Is Byte Really The Minimum Addressable Unit? Section 3.6 of C11 standard defines "byte" as "addressable unit of data storage ... to hold ... character".
Section 1.7 of C++11 standard defines "byte" as "the fundamental storage unit in the C++ memory model ... to contain ... character".
Both definitions does not say that "byte" is the minimum addressable unit. Is this because standards intentionally want to abstract from a specific machine ? Can you provide a real example of machine where C/C++ compiler were decided to have "byte" longer/shorter than the minimum addressable unit ?

A: A byte is the smallest addressable unit in strictly conforming C code. Whether the machine on which the C implementation executes a program supports addressing smaller units is irrelevant to this; the C implementation must present a view in which bytes are the smallest addressable unit in strictly conforming C code.
A C implementation may support addressing smaller units as an extension, such as simply by defining the results of certain pointer operations that are otherwise undefined by the C standard.

A: One example of a real machine and its compiler where the minimal addressable unit is smaller than a byte is the 8051 family. One compiler I was used to is Keil C51.
The minimal addressable unit is a bit. You can define a variable of this type, you can read and write it. However, the syntax to define the variable is non-standard. Of course, C51 needs several extensions to support all of this. BTW, pointers to bits are not allowed.
For example:
unsigned char bdata bitsAdressable;
sbit bitAddressed = bitsAdressable^5;

void f(void) {
    bitAddressed = 1;
}

bit singleBit;

void g(bit value) {
    singleBit = value;
}

A:
Both definitions does not say that "byte" is the minimum addressable unit.

That's because they don't need to. Byte-wise types (char, unsigned char, std::byte, etc) have sufficient restrictions that enforce this requirement.
The size of byte-wise types is explicitly defined to be precisely 1:

sizeof(char), sizeof(signed char) and sizeof(unsigned char) are 1.

The alignment of byte-wise types is the smallest alignment possible:

Furthermore, the narrow character types (6.9.1) shall have the weakest alignment requirement

This doesn't have to be an alignment of 1, of course. Except... it does.
See, if the alignment were higher than 1, that would mean that a simple byte array wouldn't work. Array indexing is based on pointer arithmetic, and pointer arithmetic determines the next address based on sizeof(T). But if alignof(T) is greater than sizeof(T), then the second element in any array of T would be misaligned. That's not allowed.
So even though the standard doesn't explicitly say that the alignment of bytewise types is 1, other requirements ensure that it must be.
Overall, this means that every pointer to an object has an alignment at least as restrictive as a byte-wise type. So no object pointer can be misaligned, relative to the alignment of byte-wise types. All valid, non-NULL pointers (pointers to a live object or to a past-the-end pointer) must therefore be at least aligned enough to point to a char.
Similarly, the difference between two pointers is defined in C++ as the difference between the array indices of the elements pointed to by those pointers (pointer arithmetic in C++ requires that the two pointers point into the same array). Additive pointer arithmetic is as previously stated based on the sizeof the type being pointed to.
Given all of these facts, even if an implementation has pointers whose addresses can address values smaller than char, it is functionally impossible for the C++ abstract model to generate a pointer and still have that pointer count as valid (pointing to an object/function, a past-the-end of an array, or be NULL). You could create such a pointer value with a cast from an integer. But you would be creating an invalid pointer value.
So while technically there could be smaller addresses on the machine, you could never actually use them in a valid, well-formed C++ program.
Obviously compiler extensions could do anything. But as far as conforming programs are concerned, it simply isn't possible to generate valid pointers that are misaligned for byte-wise types.

A: I programmed both the TMS34010 and its successor TMS34020 graphics chips back in the early 1990's and they had a flat address space and were bit addressable i.e. addresses indexed each bit. This was very useful for computer graphics of the time and back when memory was a lot more precious.
The embedded C-compiler didn't really have away to access individual bits directly, since from a (standard) C language point of view the byte was still the smallest unit as pointed out in a previous post.
Thus if you want to read/write a stream of bits in C, you need to read/write (at least) a byte at a time and buffer (for example when writing a Arithmetic or Huffman Coder).

A: (Thank you everyone who commented and answered, every word helps)
Memory model of a programming language and memory model of the target machine are different things.
Yes, byte is the minimum addressable unit in context of memory model of programming language.
No, byte is not the minimum addressable unit in context of memory model of machine. For example, there are machines where minimum addressable unit is longer or shorter than the "byte" of programming language:

*

*longer: HP Saturn   - 4-bit unit vs 8-bit byte gcc (thanks Nate).

*shorter: IBM 360    - 36-bit unit vs 6-bit byte (thanks Antti)

*longer: Intel 8051  - 1-bit unit vs 8-bit byte (thanks Busybee)

*longer: Ti TMS34010 - 1-bit unit vs 8-bit byte (thanks Wcochran)


text:
Q: Pushing data from one UIViewController to another I am pushing a string from one UIViewController to another so far I am doing this successfully however, when I add the pushed string to an NSMutableArray and NSLog the count of the array it always returns me 0 here is my code: I am using storyboards and do I need to reference the second view into the view did load?
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [_TableView setDelegate:self];
    //[_TableView setDataSource:self];
    _numberOfRows = [[NSMutableArray alloc]init];
}

-(void)pushName:(NSString*)contactName
{
    //NSLog(@"Pushed name is: %@ ", contactName);
    _contactName = contactName;
    NSLog(@"Pushed name is: %@ ", _contactName);//<-- Returns the pushed string fine

    [_numberOfRows addObject:contactName];
    //[self.TableView reloadData];
     NSLog(@"Number of names: %d ", [_numberOfRows count]);//<--Always returns a 0

}

Not really sure why this isn't working. If more code is required to clarify this question, then please do ask.

A: Your array seems to not be instantiated yet when you call pushName.
Can you provide us with the context of where you call it?
EDIT: Just to elaborate. Your problem isn't in passing the data between the two Controllers. Your problem seems to be that your Array isn't responding to the addObject and count messages.
Try using lazy instantiation on your array and it should work.
EDIT 2: Code snippet:
Try adding the method:
- (NSMutableArray *)numberOfRows:
{
  if( _numberOfRows == nil ) _numberOfRows = [[NSMutableArray alloc] init]
  return _numberOfRows
}

And where you use _numberOfRows try using self.numberOfRows, i.e.
[self.numberOfRows addObject:contactName];
//[self.TableView reloadData];
NSLog(@"Number of names: %d ", [self.numberOfRows count]);//<--Should return 1 or more now.

EDIT 3: Oh and if you do that you can remove the instantiation on viewDidLoad. But you knew that.
EDIT 4: Fixing up the code snippets. Sorry I edit so much. Just trying to make sure you get the right answer.


text:
Q: Grep lines that end with numbers I have a list of lines like:
Spend: 4,100
Spend2: 2,200
Spend3: 300
Spend4: 1,590
Spend5:

and I'm trying to grep just the lines that end with numbers
I tried
grep "[0-9]+$" filename.txt > filtered.txt
grep "\d$" filename.txt > filtered.txt

but none of these worked

A: The + operator is not supported by traditional grep, whose regular expression repertoire is very limited.
All you really care about is whether the last character is a digit, so
grep '[0-9]$' filename.txt

should do what you want. Other approaches include
grep -E '[0-9]+$' filename.txt   # use extended regex repertoire
grep '[0-9]\+$' filename.txt    # POSIX BRE extended
grep -P '\d+$' filename.txt    # PCRE extended; not portable

Notice how I use single quotes throughout. Double quotes introduce additional complications especially with backslashes which you probably want to avoid.

A: On Basic regular expressions mode you should specify the pattern in the following way:
grep '[0-9]\+$' filename.txt > filtered.txt

In basic regular expressions the meta-characters '?', '+', '{', '|',
  '(', and ')' lose their special meaning; instead use the backslashed
  versions '\?', '\+', '\{', '\|', '\(', and '\)'.

A: For extended regular expressions you should use egrep or grep -E.


text:
Q: printf wont print visible chars I have this function that reads from a tcp socket, but after I print the incoming message, no characters get printed in the printf() that follows, apart from the newline characters though for some reason.
void listenThread(void* context){ //context is a struct containing some userdata
  printf("started listener thread\n");
  struct clientdata *clientdata  = context;
  char* buff[128];
  for (;;){
    bzero(buff, sizeof(buff));
    read(clientdata->sockfd, buff, sizeof(buff));
    printf("\r%s", buff);
    printf("\n\n[%s]> ", clientdata->username); //the two \n's get printed but the rest after doesn't.
  }
}

I'm totally stumped and I'm convinced that the issue is glaringly obvious. Can anyone point me in the right direction?

A: By default output to stdout (which is where printf writes) is line-buffered. That means output is actually written to the terminal when

*

*The buffer is full

*The buffer is explicitly flushed with the fflush function

*Or when you print a newline

That's why it seems to work when you print a newline, the buffer is actually written to the terminal.
If you don't want to print the newline, you could explicitly flush the buffer using fflush(stdout).

And you should really fix that array issue.


text:
Q: INSERT: when should I not be using the APPEND hint? I'm trying to insert batches of data in an Oracle table, with an INSERT statement, namely:
INSERT INTO t1 SELECT * FROM all_objects;

I've come across the APPEND hint, which seems to increase performance in some cases.
Are there situations where it might decrease performance and it should not be used?
Thanks

A: The append hint does a direct path insert, which is the same direct path insert used by SQL*Loader, when specified.  For large datasets, you should see dramatic improvements.
One of the main caveats you need to be aware of is that one of the reasons it is so fast is that it inserts all new rows past the high water mark.  This means that if you are frequently deleting rows and re-inserting, a conventional insert could potentially be better than a direct path because it will reclaim the freed space from the deleted rows.
If, for example, you had a table with 5 million rows where you did a delete from followed by a direct path insert, after a few iterations you would notice things slow to a crawl.  The insert itself would continue to be nice and speedy, but your queries against the table will gradually get worse.
The only way I know of to reset the HWM is to truncate the table.  If you plan to use direct path on a table with minimal dead rows, or if you are going to somehow reset the HWM, then I think in most cases it will be fine -- preferable, in fact, if you are inserting large amounts of data.
Here's a nice article that explains the details of the differences:
https://sshailesh.wordpress.com/2009/05/03/conventional-path-load-and-direct-path-load-simple-to-use-in-complex-situations/
A final parting shot -- with all Oracle hints, know everything you can before you use them.  Using them haphazardly can be haphazard to your health.

A: I think performance will may be  decreased in the special case if  your select retrievs only one or a small number of rows.
So in this I would use not the append hint. The OracleBase article describes very well the impact of the APPEND hint. He also provides the link to the manual page
There are 3 different situations:

*

*The APPEND hint will not have any effect because it will be silently ignored. This will happen if a trigger is defined on the table or a reference constraint or under some other circumstances.

*The append hint will raise an error message or a statement following the statement with the APPEND hint will raise an error message. Her you have two possibilities: either you remove the APPEND hint or you split the transaction in two or more separate transactions.

*The append hint will work. Here you will get better performance if you use the APPEND hint (except if you have only a small number of rows to insert as stated at the beginning). But you will also need more space when using the append hint. The insert will use news extents for the data and not fill them in the free space of the existing extends. If you do a parallel insert each process uses its own extents. This may in a lot of unused space and be a drawback in some situations.

A: It might negatively affect performance if you are using it for inserting small sets of data.
That's because it will allocate new space every time instead of reusing free space, so using it with multiple small sets can fragment your table which may result on performance issues.
That hint is a good idea for large inserts scheduled for times where usage is low.


text:
Q: PHP: echo xml data I have HTTP(S) response data in xml format as displayed below, on making HTTP(S) post to a REST endpoint.
<?xml version="1.0" encoding="utf-8"?>
  <GetTransactionResponse xmlns="http://schemas.xxxxxxxxxxx">
  <Errors xmlns:a="http://schemas.xxxxxxxxxx" />
  <TransactionStatusCode>Completed</TransactionStatusCode>
    <Transaction xmlns:a="http://schemas.xxxxxxxxx">
      <a:AmountPaid>10.00</a:AmountPaid>
      <a:StartDate>2008-08-25</a:StartDate>
      <a:MerchantDefinedData>Testing</a:MerchantDefinedData>
    </Transaction>
  </GetTransactionResponse>

Now, I want to echo some of the above columns as like:

TransactionStatusCode: Completed AmountPaid: 10.00 StartDate:
  2008-08-25


text:
Q: Split parent's remaining width space between child elements with CSS I have a parent div with relative a width (100%), with 2 child div in it. The child elements width are based on the content in them. Let's say child1 has a content which makes child1 width to the 20% of the parent's width. The child2's content makes it 40%. So basically the parent has 40% remaining space.
What I would like to achieve is to split the remaining space between the child elements evenly (by increasing their width). So child1 should be 20% + 40/2 = 40% and child2 should be 40% + 40/2 = 60%.
The whole thing should based on the content of the child elements, so only relative units are ok. Is this something possible to achieve with pure CSS?


text:
Q: How to escape the regex when splitting an String array I'm looking for a simpler solution. I'm new to Java and I need a little help. I'm trying to split String to String[] by this '],['. The problem is that Java tries to get these like a Regex and I don't want to use it because I'm not good enough in it. I want just to split the string by these 3 characters "],[";
Here is my code:
String usefulData = ...;
String[] list = null;
String token = "],[";
list = usefulData.split(token);

And here is the error ouput: Exception in thread "AWT-EventQueue-0" java.util.regex.PatternSyntaxException: Unclosed character class near index 2
],[... Please, any suggestions how to make this think works?
PS. Is there any other way to split the String? I don't like this Regex very much. I have been used Qt and C# and in both places there is a way to escape from this Regular Expresions. Thanks a lot People!

A: You want "\]\,\[".
String usefulData = ...;
String[] list = usefulData.split("\\],\\[");

This is because [ and ] are special characters in a RegEx. You have to escape them with \\ to use them as regular characters.

A: You can build your String using Pattern#quote method.
That way you won't have to escape your special characters with a backslash. Pattern.quote makes all your special characters in string behave like String literal: -
String usefulData = "[a],[b],[c,d]";
String token = Pattern.quote("],[");
String[] list = usefulData.split(token);

for (String val: list) {
    System.out.println(val.replaceAll("\\[|\\]", ""));
}

OUTPUT: -
a
b
c,d

A: String usefulData = ...;
String[] list = null;
String token = "],[";
list = usefulData.split(java.util.regex.Pattern.quote(token));


text:
Q: Angular - window.screen.height doesn't work on template I have a problem when I want to optimize part of my template for mobiles in horizontal mode.
TS:
window = window;

Template:
<div [ngStyle]="{'height': window.innerHeight < window.innerWidth ?
 window.screen.height : (widget == 'playlist' ? '334px' : '275px')}">
</div>

I'm getting nothing from window.screen.height but when I log it, it's returning good values. I was trying to use it like value but the result was the same.

A: I think you are not telling your style height what size unit it should get. Pixels px, Percentage %, etc. I added the pixel unit as an example this:
 <div [ngStyle]="{'height': window.innerHeight < window.innerWidth ?
    window.screen.height + 'px' : (widget == 'playlist' ? '334px' : '275px')}">
 </div>


text:
Q: NASM assembly swap string value of two variables in a function Im trying to swap the values of two similarly long strings with each other. However, the solution I have been trying to use is not working. It involves the use of a local variable to store the address of the other string and a loop to copy the contents of the other string to another through its memory address and by using the length of the string to iterate through it
global _start
global get_strlen
global get_vowel

section .data
NULL equ 0
SYS_EXIT equ 60
string1 db 'hello everyone', NULL
strlen dq 0

section .bss
string2 resb 20

section .text
_start:
mov rdi, string1
mov rsi, strlen
call get_strlen

mov rsi, string1
mov rdi, string2
mov rdx, qword[strlen]
mov rcx, qword[strlen]
call get_vowel

exit_here:
mov rax, SYS_EXIT
xor rdi, rdi
syscall

get_strlen:
len_loop:
    mov al, byte[rdi]
    cmp al, NULL
    je return

    inc rdi
    inc byte[rsi]
    jmp len_loop
return:
    ret

get_vowel:
push rbp
mov rbp, rsp
sub rsp, 8

mov rcx, rcx
mov rsi, rsi
mov rdi, rdi
cld
str_loop:

lodsb
stosb

cmp al, 'a'
je vowel_a
cmp al, 'e'
je vowel_e
cmp al, 'i'
je vowel_i
cmp al, 'o'
je vowel_o
cmp al, 'u'
je vowel_u
loop str_loop

mov byte[rdi], NULL
mov al, 0
jmp str_swap

vowel_a:
    dec rdi
    mov byte[rdi], '@'
    inc rdi
    jmp str_loop

vowel_e:
    dec rdi
    mov byte[rdi], '3'
    inc rdi
    jmp str_loop

vowel_i:
    dec rdi
    mov byte[rdi], '1'
    inc rdi
    jmp str_loop

vowel_o:
    dec rdi
    mov byte[rdi], '0'
    inc rdi
    jmp str_loop

vowel_u:
    dec rdi
    mov byte[rdi], 'U'
    inc rdi
    jmp str_loop

str_swap:                 ;swaps address of string1 and string2
    mov r10, rdi
    mov qword[rbp-8], r10
    mov r10, rsi
    mov rdi, r10
    mov r10, qword[rbp-8]
    mov rsi, r10
    jmp str_copy

str_copy:                  ;swap string1 and string2 values
mov rcx, rdx
mov rsi, rsi
mov rdi, rdi
cld

loop1:
    movsb
    loop loop1
    mov byte[rdi], NULL

add rsp, 8
pop rbp
ret

the ending always results in the value of string2 to be the manipulated string value and the value of string1 remains the same throughout


text:
Q: Trying to use Managed Identity with Azure Service Bus I've tried following this tutorial in order to authenticate my service bus against DefaultAzureCredentials, however, I get a 401.
I'm using the following code in the set-up:
services.AddAzureClients(x =>
{
    x.AddServiceBusClientWithNamespace("myns.servicebus.windows.net")
        .WithCredential(new Azure.Identity.DefaultAzureCredential());
});

I then call the SB client like this:
var sender = client.CreateSender("myqueue");
var message = new ServiceBusMessage(Encoding.UTF8.GetBytes("test"));

await sender.SendMessageAsync(message);

When I call SendMessageAsync I get a 401 error:

fail: Azure-Messaging-ServiceBus[82]
An exception occurred while creating send link for Identifier: myqueue-578624f3-f732-4a9b-2ab0-9adc01949a5a. Error Message:
'System.UnauthorizedAccessException: Put token failed. status-code:
401, status-description: InvalidIssuer: Token issuer is invalid.
TrackingId:cde3a89c-8108-48d1-8b8f-dacde18e176f,
SystemTracker:NoSystemTracker, Timestamp:2021-05-19T07:18:44.

Before I run this, I call az login. I have access to the the namespace to both send and receive. My guess is that I need to allocate some kind of permission between the service bus and ... something - but since I'm running this as a console app, I'm running with my own credentials. Clearly there's something about managed identity that I don't understand.
EDIT:
Following advice from @juunas, I tried the following:
services.AddHostedService<ConsoleHostedService>();
services.AddAzureClients(x =>
{
    //var creds = new Azure.Identity.EnvironmentCredential(); // 1st - EnvironmentCredential authentication unavailable. Environment variables are not fully configured.'
    //var creds = new Azure.Identity.ManagedIdentityCredential(); // 2nd - No Managed Identity endpoint found
    //var creds = new Azure.Identity.SharedTokenCacheCredential(); // 3rd - 'SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.'
    //var creds = new Azure.Identity.VisualStudioCodeCredential(); // 4th - 'Stored credentials not found. Need to authenticate user in VSCode Azure Account.'
    //var creds = new Azure.Identity.AzureCliCredential(); // 5th
    var creds = new Azure.Identity.DefaultAzureCredential();

    x.AddServiceBusClientWithNamespace("myns.servicebus.windows.net")
        .WithCredential(creds);

A: It says the "token issuer is invalid".
That means it got an access token, but it was issued by the wrong Azure AD tenant.
The Az CLI allows you to specify the Azure AD tenant id with the -t tenant-id-here argument on az login.
DefaultAzureCredential could also be using some other credential (it attempts multiple credentials like VisualStudioCredential before the AzureCliCredential).
You could instead try to use AzureCliCredential directly and see if it works.
That of course won't use Managed Identity so you'd need to use ChainedTokenCredential with the AZ CLI credential + ManagedIdentityCredential to support both.


text:
Q: Cloud Datastore Insert and Upsert Problems I am facing a strange problem while inserting an additional property under an entity key.

I am trying to add one more property without modifying the existing, however, my below code creates the new property and it deletes the existing Data(Display blank)
As per GCP Doc, I have tried with Insert and upsert not issue not got fixed

server.post('/submit', (req, res,) => {

    const OutTime  = new Date();

 const key = datastore.key([VData, 5717023518621696])
 const entity = {
   key:key,
   method: 'insert',
   data: { content: OutTime },
 }

 datastore.insert(entity).then(() => {
  // Task inserted successfully.
});
// [END datastore_upsert]

});

https://cloud.google.com/datastore/docs/concepts/entities

A: This is expected, you can't add/modify just a property of an existing entity - the entire entity needs to be re-written. So you need to get the entity, add the new property to it then update/upsert it back to the datastore.
From Updating an entity in the doc you referenced (emphasis mine):

The provided data overwrites the existing entity. The entire object must be sent to Cloud Datastore. If the entity does not exist, the
  update will fail. If you want to update-or-create an entity, use
  upsert as described previously. Using a transaction allows you
  to perform the get and update operations in a single atomical
  transaction.

And from Creating an entity (emphasis mine):

You can save the entity to Cloud Datastore using upsert (which
  will overwrite an entity if it already exists in Cloud Datastore)


text:
Q: RXJS do operator not getting hit in stream when subscribe is called without a callback parameter I am experimenting with a Redux-like pattern to maintain state in a service for a particular feature. My intent is that a consumer can subscribe to separate streams of data by calling getItem1() or getItem2(), then call action methods such as initializeItem1() or initializeItem2() on the service as desired to dispatch actions that will change the state of the store. In the service, data may be obtained either from an http call or something else as is simulated in the provided plnkr.
https://plnkr.co/edit/f3HLp5C8ckIpjNsM8dTm?p=preview
Specifically, what I do not understand is why, in my sample code, the observable returned by getItem1() does not emit a value unless I change this.service.initializeItem1().subscribe(); to this.service.initializeItem1().subscribe(() => {});. Can someone please explain if this seems like a bug in rxjs, if there is a good / known explanation as to why this behaves this way, or if I am just missing something? I appreciate any insight the community can provide me with. Thanks.
Component
//our root app component
import {Component, OnInit} from '@angular/core'
import {Observable} from 'rxjs/Rx'
import {SampleService} from './sample.service'

@Component({
  selector: 'my-app',
  template: `

Item 1 Value

{{ item1 }}

Item 2 Value

{{ item2 }}

  `,
})
export class App implements OnInit {
  name:string;
  item1: string;
  item2: string;
  constructor(private service: SampleService) { }

  ngOnInit() {
    this.item1 = this.service.getItem1().subscribe(item1 => this.item1 = item1);
    this.item2 = this.service.getItem2().subscribe(item2 => this.item2 = item2);

    /* broken */
    //Item 1 does not display
    //Item 2 displays as expected
    this.scenario1();

    /* works */
    //Item 1 displays as expected
    //Item 2 displays as expected
    // this.scenario2();
  }

  private scenario1() {
    this.service.initializeItem1().subscribe();
    this.service.initializeItem2().subscribe();
  }

  private scenario2() {
    this.service.initializeItem1().subscribe(() => {});
    this.service.initializeItem2().subscribe();
  }
}

Service
import {Injectable} from '@angular/core'
import {Observable, Subject} from 'rxjs/Rx'
import { Http, Headers } from '@angular/http';

@Injectable()
export class SampleService {
  constructor(private http: Http) { }
  private headers: Headers = new Headers({ 'Content-Type': 'application/json' });
  private _store: Subject<any> = new Subject<any>();
  private store = this._store.asObservable()
      .startWith({})
      .scan(reducer);

  public initializeItem1(): Observable<string> {
    return this.http.get('api/foobar')
      .map(response => response.json().item).do(data => {
        console.log('not hit in scenario 1, but hit in scenario 2:', data);

        this._store.next({
          type: 'INITIALIZE_1',
          payload: data
        });
      });
  }

  public initializeItem2(): Observable<string> {
    return Observable.of('foobar-2').do(data => {
      console.log('hit in scenario 1 and scenario 2:', data);

      this._store.next({
        type: 'INITIALIZE_2',
        payload: data
      });
    });
  }

  getItem1(): Observable<string> {
        return this.store.map(store => store.settings1);
    }

  getItem2(): Observable<string> {
      return this.store.map(store => store.settings2);
  }
}

function reducer(store, action) {
    switch(action.type) {
        case 'INITIALIZE_1':
            return Object.assign({ }, store, {
                initialSettings: action.payload,
                settings1: action.payload
            });
        case 'INITIALIZE_2':
            return Object.assign({ }, store, { settings2:action.payload });
        default:
            return store;
    }
}

A: This is a bug in RxJS 5 up to the RxJS 5.2.0 version. It's fixed already but it hasn't been released yet.
The only workaround is to use any subscriber for example () => {} (I think using just {} should work as well).
Merged PR on RxJS GitHub fixing this issue:

*

*https://github.com/ReactiveX/rxjs/pull/2238
Related Issues:

*

*https://github.com/ReactiveX/rxjs/issues/2283

*https://github.com/ReactiveX/rxjs/issues/2237


text:
Q: How do i access an inner widget's animation controller (or state) from outer widget? So I've been experimenting with Flutter & Dart for the past few days.
I'm stuck on this one for over a day now, so I'm here.
So I have the AlarmScreen, and we have 2 objects inside it. One is the DraggableMoonWidget, and the other is the RisingSunWidget.
Currently, the RisingSunWidget animates onto the screen from the bottom, while the DraggableMoonWidget is draggable by touch.
What I want to achieve, is that when the RisingSunWidget's animation would stop and change when the DraggableMoonWidget is being dragged. So I have the MoonDragListener in place and working, but I still can't figure it out. (currently calls the listener back to the AlarmScreen, but then what?)
I have tried a whole bunch of methods to do that, all deleted since then, as not a single one worked.
TLDR
How do I control the RisingSunWidget's animation controller when the user touches the DraggableMoonWidget, for example, I want to stop the controller and animate it to a different point.
What is the best approach in dart/flutter?
AlarmScreen
import 'package:flutter/widgets.dart';
import 'package:moonworshiper_app/backgrounds.dart';
import 'package:moonworshiper_app/ui/alarm/moon_draggable.dart';
import 'package:moonworshiper_app/ui/alarm/rising_sun.dart';

class AlarmScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return new _AlarmScreenState();
  }
}

class _AlarmScreenState extends State<AlarmScreen> {
  bool _moonWasTouched = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return new Stack(
      children: <Widget>[
        new DraggableMoonWidget(new MoonDragListener(this)),
        new LayoutBuilder(
            builder: (BuildContext context, BoxConstraints constraints) {
          return new RisingSunWidget(constraints.heightConstraints().maxHeight, _moonWasTouched);
        })
      ],
    );
  }

  void _refreshSun() {
    setState(() {
      _moonWasTouched = true;
    });
  }
}

class MoonDragListener {
  _AlarmScreenState state;

  MoonDragListener(this.state);

  void onMoonDragStarted() {
    state._refreshSun();
  }
}

DraggableMoonWidget
import 'package:flutter/widgets.dart';
import 'package:moonworshiper_app/ui/alarm/alarm_screen.dart';

class DraggableMoonWidget extends StatefulWidget {

  final MoonDragListener moonStartListener;

  DraggableMoonWidget(this.moonStartListener);

  State<StatefulWidget> createState() => new _DraggableMoonState();
}

class _DraggableMoonState extends State<DraggableMoonWidget>
    with TickerProviderStateMixin {

  final moonDragTween = new Tween<Offset>(
    begin: new Offset(0.0, -0.5),
    end: new Offset(0.0, 0.5),
  );

  var moonAnimListener;
  AnimationController _animationController;
  Animation<Offset> _dragAnimation;
  AnimationController _dragAnimationController;
  bool isFirstDraw = true;

  @override
  initState() {
    super.initState();
    _animationController = new AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 3000),
    );
    _dragAnimationController = new AnimationController(vsync: this);

    moonAnimListener = (AnimationStatus status) {
      if (status == AnimationStatus.dismissed) {
        _animationController.forward();
      } else if (status == AnimationStatus.completed) {
        _animationController.reverse();
      } else if (status == AnimationStatus.forward) {}
    };

    _dragAnimation = moonDragTween.animate(new CurvedAnimation(
        parent: _dragAnimationController,
        curve: Curves.easeInOut,
        reverseCurve: Curves.easeInOut));

    _dragAnimationController.animateTo(0.5, duration: new Duration());

    _animationController.addStatusListener(moonAnimListener);

    _animationController.forward();
  }

  @override
  Widget build(BuildContext context) {
    return new Container(
      child: new Center(
        child: new SlideTransition(
          position: _dragAnimation,
          child: new GestureDetector(
            child: new Image.asset(
              "assets/moon.png",
              width: 280.0,
              height: 280.0,
            ),
            onVerticalDragStart: (DragStartDetails details) {
              print("start:" + details.globalPosition.toString());
              _animationController.removeStatusListener(moonAnimListener);
              _animationController.stop();
              _dragStartDetails = details;

              _dragAnimationController.animateTo(0.5,
                  duration: new Duration(milliseconds: 50));

              if (isFirstDraw) {
                isFirstDraw = false;
                widget.moonStartListener.onMoonDragStarted();
              }
            },
          ),
        ),
      ),
//      margin: new EdgeInsets.only(top: 48.0),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }
}

RisingSunWidget
import 'package:flutter/widgets.dart';

class RisingSunWidget extends StatefulWidget {
  // needed to calculate the offset map
  final double screenHeight;

  // that's how we know if the use touched the moon
  final bool moonWasTouched;

  RisingSunWidget(this.screenHeight, this.moonWasTouched);

  @override
  State<StatefulWidget> createState() {
    return new RisingSunState();
  }
}

class RisingSunState extends State<RisingSunWidget> with TickerProviderStateMixin {
  AnimationController _animationController;
  Animation<Offset> _sunAnimation;

  final double sunSize = 320.0;

  @override
  initState() {
    super.initState();

    _animationController = new AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 6000),
    );

    // how many suns fit in the height of our screen

    assert(widget.screenHeight > sunSize);

    double sunsInHeight = widget.screenHeight / sunSize;

    print(sunsInHeight.toString() + " suns could fit on the user's screen");

    var sunsPlusMargins = sunsInHeight + 1; // required margins

    final moonTween = new Tween<Offset>(
      begin: new Offset(0.0, -0.5 * sunsPlusMargins),
      end: new Offset(0.0, 0.5 * sunsPlusMargins), //move by 8% of height max
    );

    _sunAnimation = moonTween.animate(new CurvedAnimation(
      parent: _animationController,
      curve: Curves.easeInOut,
      reverseCurve: Curves.easeInOut,
    ));

    if (widget.moonWasTouched) {
      _animationController.stop();
      _animationController.animateTo(0.68,
          duration: new Duration(milliseconds: 2000));
    } else {
      _animationController.animateTo(0.88,
          duration: new Duration(milliseconds: 0));
      _animationController.animateTo(0.75,
          duration: new Duration(milliseconds: 15000));
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Center(
      child: new SlideTransition(
        position: _sunAnimation,
        child: new Image.asset(
          "assets/sun.png",
          width: sunSize,
          height: sunSize,
        ),
      ),
    );
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

}

A: 2 possibilities :

*

*Use the BuildContext context that is provided in your build method. BuildContext has a few methods get the closest parent of a specific type.

*Pass a key attribute to the desired widget.
GlobalKey to be exact.
GlobalKey allows you directly access to a Widget or it's state.


text:
Q: zypper refresh not working: "Refreshing service 'cloud_update'." I'm on Google Cloud and I'm trying to update from the SUSE repositories, but I am unable. For example when I run this:
 # zypper refresh

I get:
Refreshing service 'cloud_update'.

For a long time, then I get:
Timeout exceeded when accessing `'http://download.opensuse.org/repositories/server:/database:/postgresql/SLE_12_SP3/repodata/repomd.xml'.`

The VPN Gateway logs indicate:
D  sending DPD request
D  generating INFORMATIONAL request 878 [ ]
D  sending packet: from [Google IP address here][500] to [my IP address here][500] (80 bytes)
D  received packet: from [my IP address here][500] to [Google IP address here][500] (80 bytes)
D  parsed INFORMATIONAL response 878 [ ]

What is going on? Is the SUSE repo down?
If I put the link above in my browser I get:
This XML file does not appear to have any style information associated with it. The document tree is shown below.
<repomd xmlns="http://linux.duke.edu/metadata/repo" xmlns:rpm="http://linux.duke.edu/metadata/rpm">
<revision>1516763417</revision>
<tags>
<repo>
obsrepository://build.opensuse.org/server:database:postgresql/SLE_12_SP3
</repo>
</tags>
<data type="primary">
<checksum type="sha256">
b728c544d7f29705060e8c13e9f3e65fc4b4ae688abfaf950fce2a69ae6bce4a
</checksum>
<open-checksum type="sha256">
0806dae0c956c56000c214d7027f47c180fefe0d3b751bb7b0bfff23df8e2aef
</open-checksum>
<location href="repodata/b728c544d7f29705060e8c13e9f3e65fc4b4ae688abfaf950fce2a69ae6bce4a-primary.xml.gz"/>
<timestamp>1516763417</timestamp>
<size>240325</size>
<open-size>2523553</open-size>
</data>
<data type="filelists">
<checksum type="sha256">
2a21f81192105b74d873f49136e1490fc390dfaf7f1f6b76bfe27b8dbb970e15
</checksum>
<open-checksum type="sha256">
3e86d4e3323cd401d766dd4837a5f3ab701ed5c3840b4d5fc340b5ec8a7ff678
</open-checksum>
<location href="repodata/2a21f81192105b74d873f49136e1490fc390dfaf7f1f6b76bfe27b8dbb970e15-filelists.xml.gz"/>
<timestamp>1516763417</timestamp>
<size>510797</size>
<open-size>6503598</open-size>
</data>
<data type="other">
<checksum type="sha256">
ebf8fa6a503f73d046ce3ceac4d5549ba82d635f2284aabba740156a40c223ec
</checksum>
<open-checksum type="sha256">
ae1032a71dfd8089e96ecb9f149bb947d244e0482696700b8edcf1d4c19c2293
</open-checksum>
<location href="repodata/ebf8fa6a503f73d046ce3ceac4d5549ba82d635f2284aabba740156a40c223ec-other.xml.gz"/>
<timestamp>1516763417</timestamp>
<size>3494469</size>
<open-size>15687434</open-size>
</data>
</repomd>

I didn't come up with much doing online searches.
# cat /etc/os-release
NAME="SLES"
VERSION="12-SP3"
VERSION_ID="12.3"
PRETTY_NAME="SUSE Linux Enterprise Server 12 SP3"
ID="sles"
ANSI_COLOR="0;32"
CPE_NAME="cpe:/o:suse:sles:12:sp3"


text:
Q: Can We use Java EE Servlets for the backend with Angular as the frontend? I was wondering if it is possible to use Angular(2+) as the frontend, and use specifically Java EE Servlets as the Backend? If so, can the project be stored as a WAR file?
Thank you in advance.

A: Yes it's possible wiht JEE servlets with angular2+ as a front end.
You can create the angular project using angular cli. Go through the following link,
[Connecting your Angular 2 App to your Java EE Backend][1]
For creating angular project you can
From the Eclipse menu, choose File>New>Dynamic Web Project; or right click in Project/Package Explorer and choose New>Dynamic Web Project.
Initialize using angular cli
Right-click the newly created project and select Show in>Terminal. and type ng init , after that you can run npm start and see running your application.


text:
Q: How to add a condition to existing lambda expression? Consider the following class:
public class Customer
{
    public int Id {get; set;}
    public int GroupId {get; set;}
    public int Number {get; set;}
    public string Name {get; set;}
}

I have a method in the service layer that does:
public Customer Get(Expression<Func<Customer, bool>> where)
{
    return customerRepository.Get(where);
}

The calling code is:
var customer = customerService.Get(x => x.Number == number);

In the above method, the user searches a customer based on a property (excluding GroupId because this is hidden in the ViewModel). However, a user is always assigned to a group, and therefore, he is only allowed to search for customers within his group. So the GroupId must be added dynamically.
How can I add the GroupId to the where expression in the method above. The GroupId may or may not be already available in the expression.

A: Using PredicateBuilder you can help build expressions that you can add onto your calls. This would allow you to do something like below.
public void DoSearch(MyViewModel vm)
{
    Expression<Func<Customer, bool>> myFilter = x => yourCurrentFilterLogic;
    var combined = myFilter.And(x => x.GroupId == vm.GroupId);   //PredicateBuilder extension method
    var customers = Get(combined);
}

public Customer Get(Expression<Func<Customer, bool>> where)
{
    return customerRepository.Get(where);
}


text:
Q: Use interceptor for components in shared modules I am using Angular's new interceptor feature within "app.module" and all components in my app are successfully using it:
import { ProgressInterceptor } from "./progress.interceptor";
providers: [
      { provide: HTTP_INTERCEPTORS, useClass: ProgressInterceptor, multi: true }
  ]

However I also have a "shared.module" and all components in there are not using the interceptor even though it's been declared in "app.module". How can I get the components in "shared.module" to use the same interceptor?
For reference here is my "shared.module":
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { RouterModule } from "@angular/router";
import { MyDatePickerModule } from 'mydatepicker';
import { EditorModule, SharedModule } from 'primeng/primeng';
import { FileUploadModule } from 'primeng/primeng';
import { DialogModule } from 'primeng/primeng';
import { ChartModule } from 'primeng/primeng';
import { ColorPickerModule } from 'ngx-color-picker';
import { AccordionModule } from 'primeng/primeng';

import { NotifyModalComponent } from '../shared/notify-modal.component';
import { ErrorModalComponent } from '../shared/error-modal.component';
import { UploadDownloadComponent } from '../shared/upload-download.component';
import { HeaderComponent } from '../shared/header.component';
import { BarChartComponent } from '../shared/bar-chart.component';
import { PieChartComponent } from '../shared/pie-chart.component';
import { EventNavigationComponent } from '../shared/event-navigation.component';
import { EventTitleBannerComponent } from '../shared/event-title-banner.component';
import { StandardFooterComponent } from '../shared/standard-footer.component';
import { StandardNavigationComponent } from '../shared/standard-navigation.component';
import { StandardReportDataComponent } from '../shared/standard-report-data.component';
import { MisReportsFormComponent } from '../shared/mis-reports-form.component';
import { StandardReportTotalsDataComponent } from '../shared/standard-report-totals-data.component';
import { AuditLogFormComponent } from '../shared/audit-log-form.component';
import { CreateEventBannerComponent } from '../shared/create-event-banner.component';
import { LanguageSelectorComponent } from '../shared/language-selector.component';
import { DisableButtonDuringAjax } from '../shared/disable-button-during-ajax.directive';

import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
import { TranslateHttpLoader } from "@ngx-translate/http-loader";
import { TranslateService } from '@ngx-translate/core';

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        ReactiveFormsModule,
        RouterModule,
        MyDatePickerModule,
        EditorModule,
        SharedModule,
        FileUploadModule,
        DialogModule,
        ChartModule,
        ColorPickerModule,
        AccordionModule,
        TranslateModule
    ],
    declarations: [
        NotifyModalComponent,
        ErrorModalComponent,
        UploadDownloadComponent,
        HeaderComponent,
        BarChartComponent,
        PieChartComponent,
        EventNavigationComponent,
        EventTitleBannerComponent,
        StandardFooterComponent,
        StandardNavigationComponent,
        StandardReportDataComponent,
        MisReportsFormComponent,
        StandardReportTotalsDataComponent,
        AuditLogFormComponent,
        CreateEventBannerComponent,
        LanguageSelectorComponent,
        DisableButtonDuringAjax
    ],
    exports: [
        NotifyModalComponent,
        ErrorModalComponent,
        UploadDownloadComponent,
        HeaderComponent,
        BarChartComponent,
        PieChartComponent,
        EventNavigationComponent,
        EventTitleBannerComponent,
        StandardFooterComponent,
        StandardNavigationComponent,
        StandardReportDataComponent,
        MisReportsFormComponent,
        StandardReportTotalsDataComponent,
        AuditLogFormComponent,
        CreateEventBannerComponent,
        LanguageSelectorComponent,
        DisableButtonDuringAjax,
        TranslateModule
    ]
})
export class SharedModuleForSite{

    constructor(private translate: TranslateService) {

    }

}

and here is my "app.module":
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { routing } from "./app.routing";
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { MomentModule } from 'angular2-moment';
import { MyDatePickerModule } from 'mydatepicker';
import { EditorModule, SharedModule } from 'primeng/primeng';
import { FileUploadModule } from 'primeng/primeng';
import { DialogModule } from 'primeng/primeng';
import { ChartModule } from 'primeng/primeng';
import { ColorPickerModule } from 'ngx-color-picker';

import { SharedModuleForSite } from './shared/shared.module';

import { AppComponent } from './app.component';

import { LoginComponent } from './login.component';
import { NoEventsComponent } from './no-events.component';
import { ReportsComponent } from './reports/reports.component';
import { AddressReportsComponent } from './address-reports/address-reports.component';
import { ForgottenPasswordComponent } from './forgotten-password.component';

import { HttpService } from "./http.service";
import { AuthGuard } from "./auth.guard";
import { NotifyService } from "./notify.service";
import { ErrorService } from "./error.service";
import { BusyService } from "./busy.service";
import { ReloadComponentService } from "./reload-component.service";
import { DateFormatPipe } from 'angular2-moment';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
import { ProgressInterceptor } from "./progress.interceptor";

import { HttpClient, HttpClientModule } from "@angular/common/http";
import { TranslateModule, TranslateLoader } from "@ngx-translate/core";
import { TranslateHttpLoader } from "@ngx-translate/http-loader";

export function HttpLoaderFactory(httpClient: HttpClient) {
    return new TranslateHttpLoader(httpClient, "./assets/i18n/", ".json");
}

@NgModule({
  declarations: [
    AppComponent,
    LoginComponent,
    NoEventsComponent,
    ReportsComponent,
    AddressReportsComponent,
    ForgottenPasswordComponent
  ],
  imports: [
      BrowserModule,
      HttpClientModule,
      TranslateModule.forRoot({
          loader: {
              provide: TranslateLoader,
              useFactory: HttpLoaderFactory,
              deps: [HttpClient]
          }
      }),
      routing,
      BrowserAnimationsModule,
      FormsModule,
      ReactiveFormsModule,
      MomentModule,
      MyDatePickerModule,
      EditorModule,
      SharedModule,
      FileUploadModule,
      DialogModule,
      ChartModule,
      ColorPickerModule,
      SharedModuleForSite
  ],
  providers: [
      HttpService,
      AuthGuard,
      NotifyService,
      ErrorService,
      BusyService,
      ReloadComponentService,
      DateFormatPipe,
      { provide: HTTP_INTERCEPTORS, useClass: ProgressInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
Q: Identity throws "Invalid object name 'dbo.AspNetUserClaims'" after removing that table I have removed the "AspNetUserClaims" table from my DB because I am not saving any claims information.
After creating a user I am trying to fetch user info by its user name and it returns an error:

"Invalid object name 'dbo.AspNetUserClaims'.".

IdentityResult result = await manager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
    var userInfo = manager.FindByName(user.UserName);
    foreach (var myRole in myRoles)
    {
        manager.AddToRole(userInfo.Id, myRole.Name);
    }
    await AddToPreviousPasswordsAsync(user, user.PasswordHash);
}

A: In the UserManager class of Identity 2, the Entity Framework-backed UserStore will ensure the claims are loaded for the requested user.
This accesses the AspNetUserClaims table, which will throw an exception when your database doesn't contain that table.
Simply don't remove tables that are required by a library, or rebuild the library without the claims part. And you don't want to do the latter, because then you won't receive any updates from the official channel anymore, and have to manually patch it. This is no way to handle a security-related library, or generally any library for that matter.


text:
Q: How to fix UTF8 inside laravel Seed? I'm trying to import an old DB inside my new laravel project. To make things simple, some of the entries were made through the French version of MS Office and the old website was dealing with those encoding really poorly.
There are apostrophes, accents, strange characters word has to make the texts prettier...

*

*On the original files, enca tells me "Unknown encoding"

*I tried python-chardet and it tells me ISO-8859-7 (.88)

*I tried iconv with ISO-8859-{1-15}, no good came out of it.

*I resolved myself on booting up my windows and using Notepad ++ to
convert the file to UTF8-no-bom. Which ended up having enca
recognizing UTF-8 but literally destroyed half the caracters.

*I've tried adding the 3 UTF8 following lines in /etc/mysql/my.cnf
and  every test were done with and without them (commenting /
un-commenting), so far it hasn't changed anything.
collation-server = utf8_unicode_ci
init-connect='SET NAMES utf8'
character-set-server = utf8

*I made sure that those 2 lines were in the mysql array of /app/config/database.php
'charset'   => 'utf8',
'collation' => 'utf8_unicode_ci',
Currently the seed file (simplified) looks like this :
<?php
// app/database/seeds/ArticlesTableSeeder.php

class ArticlesTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('articles')->delete();
            Articles::create(array(
                     // ' != ', I could do a str_replace but
                     // there are many similar characters spread everywhere
                    'test1'       => utf8_decode("l'année"),
                    'test2'       => "l'année",
                    'test3'       => "l'année"
                    ));

    }

}

Once seeded, this is what I get in my database :
test1 > l?ann
test2 > lâannée
test3 > lâannée // Same as test2

I made this test output :
print_r(utf8_encode($test1));
// l?ann
print_r(utf8_decode($test2));
// l?année
print_r($test3);
// l'année

I'm at this point where I've spent more time on this problem than I should have but I'm not the kind of person who simply gives up. I'm not sure of what to do so I figured it was time to ask.

A: Try run htmlentities over the given string, with UTF-8 support.
htmlentities($str, ENT_QUOTES, "UTF-8");

http://laravel.com/docs/4.2/helpers#strings

A: Laravel also has a built in method called "e" for returning an htmlentity. So all you need to do is run:
'test1' => e("l'année"),

See http://laravel.com/docs/5.1/helpers#method-e for more info.


text:
Q: Thread.Sleep and Task.Delay randomly hanging and never ends Not a duplicate. The code directly below also hangs and causes the console to wait for input 'randomly' - Bigger underlying issue somewhere.
int i = 0;
while (true)
{
    Console.WriteLine(++i);
    System.Threading.Thread.Sleep(3000);
}

So i have the strangest bug and nothing online seems to ever have this. I recently moved my task scheduler to a different server (Windows server 2016 standard) and since the move the app seems to randomly hang on the Task.Delay line and never execute past it.
It will simply say 'Check completed next run at 09:31' for example, then never execute again.
Interestingly pressing enter into the console window seems to trigger it to execute, however then every time it hangs on the sleep until the application is closed and re-opened.
It can go many days without experiencing this issue, then it will seemingly randomly crop up.
I've tried with Thread.Sleep instead of Task.Delay and both experience the same issue. I also added a check to see if possibly the Directory.Exists command was causing it to hang, so stored the directories in memory instead.
I have no idea what could be causing this - I've never experienced anything like it before. Any ideas?
Code is below - however will be impossible to replicate id imagine due to the weird nature of the bug
TLDR:
Windows server 2016 console application hangs on Task.Delay (and Thread.Sleep) until key push on console window
        // This is the main execution loop
            while (true)
        {
            Task run = checkDirectoriesForAppsToRun();
            run.Wait();
        }

       static async Task checkDirectoriesForAppsToRun()
    {
        Console.WriteLine("Starting apps...");
        foreach (string subFolder in listOfSubfolders)
        {
            if (directoryExists.ContainsKey(currentDirectory + @"\" + subFolder) || System.IO.Directory.Exists(currentDirectory + @"\" + subFolder)) // Only if the sub directory exists!
            {
                if (directoryExists.ContainsKey(currentDirectory + @"\" + subFolder) == false)
                    directoryExists.Add(currentDirectory + @"\" + subFolder, true);
                foreach (string directory in System.IO.Directory.GetDirectories(currentDirectory + @"\" + subFolder))
                {
                    CheckDirectoryForApp(directory); // Load the apps xml file, and check if we need to run it.
                }
            }
            else
            {
                Console.WriteLine(subFolder + " Doesn't exist in the root directory - Please check");
            }
        }
        Console.WriteLine("Check completed next run at " + DateTime.Now.Add(timeToPause).ToShortTimeString());
        await Task.Delay(timeToPause);
    }

A: Why not use System.Threading.Timer instead of creating your own version that is a loop? That is what they were created for. See the already excellent comments on the question as to why the posted code would/could be deadlocking, this is easy to do if you mix synchronous calls with async/await and it is also not necessary to use async/await as you are only using it for Task.Delay
private static System.Threading.Timer _timer;

static void Main(string[] args)
{
  // start the timer
  _timer = new System.Threading.Timer(checkDirectoriesForAppsToRun, null, 0, timeToPause);
}

static void StopTimer()
{
  // call this method when you want to stop the timer
  _timer?.Dispose();
}

static void checkDirectoriesForAppsToRun(object state)
{
  Console.WriteLine("Starting apps...");
  /* exising code not considered in this answer... */
  Console.WriteLine("Check completed next run at " + DateTime.Now.Add(timeToPause).ToShortTimeString());

  // await Task.Delay(timeToPause); // removed
}

A: So it seems this is an issue with RDP connectivity freezing .NET applications at runtime.
Was not an issue on Windows server 2008 - is an issue on later windows server versions. See link below. Currently been unable to resolve - Got rid of RDP in favour of VNC to sidestep the issue
https://social.msdn.microsoft.com/Forums/vstudio/en-US/f1d6d2e3-417f-4bc4-be83-1e659852d6cb/application-hang-when-using-remote-desktop?forum=vcgeneral


text:
Q: Turning a Google apps script library into ... an extension? I've got a GA script library, which contains some Google Docs operations that I use a lot (such as specific formatting, heading numbers or specific searches). When I want to use these functions, I currently add a script to the document, that loads the menu builder (in the library), and then add the library to that script. That seems to be the shortest way of using the library across multiple files. I have these questions:
(1) Is there a way in which these library functions can be available to all my Google Docs, without having to load them per document? My understanding is that this is not possible.
(2) Is this correct: The best way to make these library functions available would be to build an extension, and publish this on the Chrome store. (Possibly as 'beta extension'?)
If this is correct, then could somebody point me to a simple step-by-step guide for turning scripts into docs extensions? I've looked around, but what I saw wasn't all that clear. Ideally I'd like to be able to update the extension frequently, as it's still under development.
Thanks!


text:
Q: Customize Jackson serialization when using value objects as entity id I want to use a Value Object as the database id in my entity. I also want to have clean JSON. Suppose I have this entity:
private static class TestEntity {
    private TestEntityId id;
    private String mutableProperty;

    public TestEntity(TestEntityId id) {
        this.id = id;
    }

    public TestEntityId getId() {
        return id;
    }

    public String getMutableProperty() {
        return mutableProperty;
    }

    public void setMutableProperty(String mutableProperty) {
        this.mutableProperty = mutableProperty;
    }
}

Which has this id class:
private static class TestEntityId extends ImmutableEntityId<Long> {
    public TestEntityId(Long id) {
        super(id);
    }
}

If I use default settings of Jackson, I get this:
{"id":{"id":1},"mutableProperty":"blabla"}

But I would like to get this:
{"id":1,"mutableProperty":"blabla"}

I managed to get the serialization ok by adding a custom serializer:
        addSerializer(ImmutableEntityId.class, new JsonSerializer<ImmutableEntityId>() {
            @Override
            public void serialize(ImmutableEntityId immutableEntityId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
                jsonGenerator.writeNumber( (Long)immutableEntityId.getId() );
            }
        });

(I know that the cast is not really good, but please ignore that for the purpose of the question).
The question is how can I write a deserializer for it? Somehow Jackson should keep track that when deserializing a TestEntity, he needs to create a TestEntityId instance (and not the ImmutableEntityId superclass). I could write serializers and deserializers for each Entity, but I was hoping on a more generic solution.

A: Use @JsonUnwrapped. It works perfectly with objects with a single property, too, IIRC.


text:
Q: How to extract the values of interest in a string In one column of my dataframe there are several namings for the same object.
Say, for example, that I'm working with types of cancer. There are several sub-specifications for each type of cancer.
type <- c("Breast (ER- / PR- / EGFR - / AR - / PD-L1 - / HER2-)", "Breast (ER- / PR- / HER2- / AR - / EGFR -)", "Breast (ER- / PR- / HER2- / BRCA- / PDL1 1% / FGFR -)", "Breast (ER- / PR- / HER2- / BRCA- / PDL1 2%)", "Breast (ER- / PR- / HER2- / PDL1 - / AR -)", "Breast (ER- / PR- / HER2- / PD-L1 50% (Breast and IC 5% liver))", "Breast (ER- / PR- / HER2-)", "Breast (ER- / PR- / HER2- / PD-L1 -)", "Breast (ER- / PR+ / HER2 -)")

dat <- as.data.frame(type)
dat

So we have:
Breast (ER- / PR- / EGFR - / AR - / PD-L1 - / HER2-)
Breast (ER- / PR- / HER2- / AR - / EGFR -)
Breast (ER- / PR- / HER2- / BRCA- / PDL1 1% / FGFR -)
Breast (ER- / PR- / HER2- / BRCA- / PDL1 2%)
Breast (ER- / PR- / HER2- / PDL1 - / AR -)
Breast (ER- / PR- / HER2- / PD-L1 50% (Breast and IC 5% liver))
Breast (ER- / PR- / HER2-)
Breast (ER- / PR- / HER2- / PD-L1 -)
Breast (ER- / PR+ / HER2 -)

It may not look like it, but we have only two different types of cancer here, which are Breast (ER- / PR- / HER2-) and Breast (ER- / PR+ / HER2-).
Of course I have many more rows, this is just a substract, so I would like to develop a function that allows me to count how many of each type I have, that is, paying attention to ER, PR and HER2 values.
For this, I though of creating a function that captures the string composed of Breast (ER\s+ PR\s+HER2\s, where \s is any possible value (the reason to separate them is that as you may see these three values not always follow each other).
But I didn't find a way of doing this with gsub.
Edit:
At the end I would like to get another column that would look like:
Breast (ER- / PR- / HER2-)
Breast (ER- / PR- / HER2-)
Breast (ER- / PR- / HER2-)
Breast (ER- / PR- / HER2-)
Breast (ER- / PR- / HER2-)
Breast (ER- / PR- / HER2-)
Breast (ER- / PR- / HER2-)
Breast (ER- / PR- / HER2-)
Breast (ER- / PR+ / HER2-)

This would allow me to count with a unique() function

A: The stringr package is your friend
Stringr is a package that's part of the tidyverse and provides a lot of helpful wrappers to make handling strings more intuitive.
There are a few steps needed here, so I'll show you the output after each step
type <- c("Breast (ER- / PR- / EGFR - / AR - / PD-L1 - / HER2-)", "Breast (ER- / PR- / HER2- / AR - / EGFR -)", "Breast (ER- / PR- / HER2- / BRCA- / PDL1 1% / FGFR -)", "Breast (ER- / PR- / HER2- / BRCA- / PDL1 2%)", "Breast (ER- / PR- / HER2- / PDL1 - / AR -)", "Breast (ER- / PR- / HER2- / PD-L1 50% (Breast and IC 5% liver))", "Breast (ER- / PR- / HER2-)", "Breast (ER- / PR- / HER2- / PD-L1 -)", "Breast (ER- / PR+ / HER2 -)")

dat <- as.data.frame(type)
intersect, setdiff, setequal, union

## Get rid of all spaces
mutate(dat, simple_type = str_remove_all(type, "[:space:]")) |>
  pull(simple_type) # just using pull to show you where we're up to with the process
#> [1] "Breast(ER-/PR-/EGFR-/AR-/PD-L1-/HER2-)"
#> [2] "Breast(ER-/PR-/HER2-/AR-/EGFR-)"
#> [3] "Breast(ER-/PR-/HER2-/BRCA-/PDL11%/FGFR-)"
#> [4] "Breast(ER-/PR-/HER2-/BRCA-/PDL12%)"
#> [5] "Breast(ER-/PR-/HER2-/PDL1-/AR-)"
#> [6] "Breast(ER-/PR-/HER2-/PD-L150%(BreastandIC5%liver))"
#> [7] "Breast(ER-/PR-/HER2-)"
#> [8] "Breast(ER-/PR-/HER2-/PD-L1-)"
#> [9] "Breast(ER-/PR+/HER2-)"

## Extract a list of the codes we're interested it
mutate(dat,
       simple_type = str_remove_all(type, "[:space:]") |>
         str_extract_all("(ER[+-])|(PR[+-])|(HER2[+-])")) |>  ## extract all instances of 'ER' and one of +/-, OR PR and one of +/-, etc.
  pull(simple_type)
#> [[1]]
#> [1] "ER-"   "PR-"   "HER2-"
#>
#> [[2]]
#> [1] "ER-"   "PR-"   "HER2-"
#>
#> [[3]]
#> [1] "ER-"   "PR-"   "HER2-"
#>
#> [[4]]
#> [1] "ER-"   "PR-"   "HER2-"
#>
#> [[5]]
#> [1] "ER-"   "PR-"   "HER2-"
#>
#> [[6]]
#> [1] "ER-"   "PR-"   "HER2-"
#>
#> [[7]]
#> [1] "ER-"   "PR-"   "HER2-"
#>
#> [[8]]
#> [1] "ER-"   "PR-"   "HER2-"
#>
#> [[9]]
#> [1] "ER-"   "PR+"   "HER2-"

## Collapse each list element into a single string, then turn the list into a character vector
### (saving this new df as 'dat' because it makes the next step much easier to write)
dat <-
  mutate(dat,
       simple_type = str_remove_all(type, "[:space:]") |>
         str_extract_all("(ER[+-])|(PR[+-])|(HER2[+-])") |>
         lapply(str_c, collapse = " / ") |> # stringr::str_c() is pretty much identical to base::paste()
         as.character())
dat[["simple_type"]]
#> [1] "ER- / PR- / HER2-" "ER- / PR- / HER2-" "ER- / PR- / HER2-"
#> [4] "ER- / PR- / HER2-" "ER- / PR- / HER2-" "ER- / PR- / HER2-"
#> [7] "ER- / PR- / HER2-" "ER- / PR- / HER2-" "ER- / PR+ / HER2-"

## Paste back in the other stuff
dat <- mutate(dat, simple_type = str_c("Breast (", simple_type, ")"))
dat[["simple_type"]]
#> [1] "Breast (ER- / PR- / HER2-)" "Breast (ER- / PR- / HER2-)"
#> [3] "Breast (ER- / PR- / HER2-)" "Breast (ER- / PR- / HER2-)"
#> [5] "Breast (ER- / PR- / HER2-)" "Breast (ER- / PR- / HER2-)"
#> [7] "Breast (ER- / PR- / HER2-)" "Breast (ER- / PR- / HER2-)"
#> [9] "Breast (ER- / PR+ / HER2-)"

Created on 2022-05-27 by the reprex package (v2.0.1)

A: If I do not missunderstand something, the cancer types can be distinguished unambiguously by +/- after "PR". Then, would this be an option for you?
Note. Probably, the way you deal with the pattern (accounting for whitespaces/typos) needs to be more advanced. I am bad in regular expressions.
library(stringr)
df$type <- as.factor(str_sub(df$cancer, 14, 17))
table(df$type)
#>
#>  PR-  PR+
#>    8    1

Created on 2022-05-27 by the reprex package (v2.0.1)
Data
df <- data.frame(cancer = c("Breast (ER- / PR- / EGFR - / AR - / PD-L1 - / HER2-)",
                            "Breast (ER- / PR- / HER2- / AR - / EGFR -)",
                            "Breast (ER- / PR- / HER2- / BRCA- / PDL1 1% / FGFR -)",
                            "Breast (ER- / PR- / HER2- / BRCA- / PDL1 2%)",
                            "Breast (ER- / PR- / HER2- / PDL1 - / AR -)",
                            "Breast (ER- / PR- / HER2- / PD-L1 50% (Breast and IC 5% liver))",
                            "Breast (ER- / PR- / HER2-)",
                            "Breast (ER- / PR- / HER2- / PD-L1 -)",
                            "Breast (ER- / PR+ / HER2 -)")
)

A: Here is a variant of stringr approach. First, extract the ER, PR, and HER2 components, including the sign (+/-). The line starting with across() removes the spaces between the spaces between the texts and the sign. Then put the three components together in a column.
dat <- read.delim(text = text)

library(tidyverse)

dat |>
  mutate(er = str_extract(type, "ER\\s*[+-]"),
         pr = str_extract(type, "PR\\s*[+-]"),
         her2 = str_extract(type, "HER2\\s*[+-]"),
         across(c(er, pr, her2), ~ str_remove(., "\\s")),
         type1 = paste0("Breast (", er, " / ", pr, " / ", her2, ")")) |>
  select(-c(er, pr, her2))

#                                                             type                      type1
#           Breast (ER- / PR- / EGFR - / AR - / PD-L1 - / HER2-) Breast (ER- / PR- / HER2-)
#                     Breast (ER- / PR- / HER2- / AR - / EGFR -) Breast (ER- / PR- / HER2-)
#          Breast (ER- / PR- / HER2- / BRCA- / PDL1 1% / FGFR -) Breast (ER- / PR- / HER2-)
#                   Breast (ER- / PR- / HER2- / BRCA- / PDL1 2%) Breast (ER- / PR- / HER2-)
#                     Breast (ER- / PR- / HER2- / PDL1 - / AR -) Breast (ER- / PR- / HER2-)
#Breast (ER- / PR- / HER2- / PD-L1 50% (Breast and IC 5% liver)) Breast (ER- / PR- / HER2-)
#                                     Breast (ER- / PR- / HER2-) Breast (ER- / PR- / HER2-)
#                           Breast (ER- / PR- / HER2- / PD-L1 -) Breast (ER- / PR- / HER2-)
#                                    Breast (ER- / PR+ / HER2 -) Breast (ER- / PR+ / HER2-)

Data:
text <- "type
Breast (ER- / PR- / EGFR - / AR - / PD-L1 - / HER2-)
Breast (ER- / PR- / HER2- / AR - / EGFR -)
Breast (ER- / PR- / HER2- / BRCA- / PDL1 1% / FGFR -)
Breast (ER- / PR- / HER2- / BRCA- / PDL1 2%)
Breast (ER- / PR- / HER2- / PDL1 - / AR -)
Breast (ER- / PR- / HER2- / PD-L1 50% (Breast and IC 5% liver))
Breast (ER- / PR- / HER2-)
Breast (ER- / PR- / HER2- / PD-L1 -)
Breast (ER- / PR+ / HER2 -)"


text:
Q: How does one have the Jupyter variable pane in VS Code to load the variables in session? I was trying out VS Code with Jupyter but the variables never finish loading in the variable pane:

this is some info by my env:
Environment data
VS Code version: Version: 1.41.1
Extension version (available under the Extensions sidebar):2020.2.59126-dev
OS and version: macOS Catalina 10.15.2 (19C57)
Python version (& distribution if applicable, e.g. Anaconda): python 3.7.6 64-bit ('base':conda)
Type of virtual environment used (N/A | venv | virtualenv | conda | ...): conda
Relevant/affected Python packages and their versions: Jupyter

Did anyone else have this issue? Anyone know how to fix it? Is this really a bug or maybe just a problem with my set up?

Related sources:

*

*gitissue: https://github.com/microsoft/vscode-python/issues/9773

*reddit: https://www.reddit.com/r/vscode/comments/eub7n2/how_does_one_have_the_jupyter_variable_pane_in_vs/

*quora: https://qr.ae/TDT92y

A: From the gitissue suggestion from the developers:

Can you try updating your build?

I couldn't find an easy way to do this except by right clicking on the gear icon for the python extension.

Then clicked install another version and clicked the most current one.

That made things work.

Enable Auto updating extensions:
With the command palette, one can also turn on automatic updates for extensions. Simply do:
Command + shift + p
then type:
updating extensions
and select
enable auto updating extensions
not sure if it will avoid this issue in the future but its worth a try.


text:
Q: Bulk update of one column with other column in same table I'm using postgresql 13.1. I'm trying to update one column of a table with another column of same table. It's not fast enough. It's taking forever to update as I've millions of records in the table and I've index on the column which I'm trying to update. Here is the query.
UPDATE tbl t1 SET col_1 = to_tsvector(t2.col_2) FROM tbl t2;
index on col_1. Can someone give a better solution which is fast?
Thanks in Advance.

A: No need for a FROM clause:
UPDATE tbl
  SET col_1 = to_tsvector(col_2);


text:
Q: Is it a grammar error to connect two verbs? I found the following example sentence in my dictionary.

She renewed her promise to come see me.

Is it an error to connect come and see? My friend says it's come and see but the and got omitted. Is it true? Thanks.


text:
Q: Accessing the Row of a UISwitch in a UITableView I Used Code Similar to This to add switches to the rows of my TableView.
Once the switch is changed it calls switchChanged. But How do I access what row (which switch) was actually changed?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
switch( [indexPath row] ) {
    case MY_SWITCH_CELL: {
        UITableViewCell* aCell = [tableView dequeueReusableCellWithIdentifier:@"SwitchCell"];
        if( aCell == nil ) {
            aCell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:@"SwitchCell"] autorelease];
            aCell.textLabel.text = @"I Have A Switch";
            aCell.selectionStyle = UITableViewCellSelectionStyleNone;
            UISwitch *switchView = [[UISwitch alloc] initWithFrame:CGRectZero];
            aCell.accessoryView = switchView;
            [switchView setOn:NO animated:NO];
            [switchView addTarget:self action:@selector(switchChanged:) forControlEvents:UIControlEventValueChanged];
            [switchView release];
        }
        return aCell;
    }
    break;
}
return nil;

}
- (void) switchChanged:(id)sender {
UISwitch* switchControl = sender;
NSLog( @"The switch is %@" switchControl.on ? @"ON" : @"OFF );

}

A: The UITableViewCell object that you are adding the switch to will be switchControl.superview so
UITableViewCell * cell = (UITableViewCell *)switchControl.superview;
NSIndexPath * indexPath = [self.tableView indexPathForCell:cell];


text:
Q: Cancel a keypressed event throught handler function (addEventListener function) I would like to create a test function which change the '.' charachter into ',' character in a text box.  I cannot change the server side since it is google doc.  '56.3' is considered as a number but '56,3' is (!).
Let's say that I have used the code below :
function changeValue(e) {
    e = window.event || e;
    var keyCode = e.charCode || e.keyCode;
    if (String.fromCharCode(keyCode)==='.') {
          event.target.value+=",";
          return false;
    }
    return true;
}

function start_up () {
    console.log('Start');
    var tmp = document.getElementById('ss-form');
    tmp = tmp.getElementsByTagName('input');
    console.log(tmp);
    for(var i=0; i<tmp.length; i++) {
            tmp[i].addEventListener('keypress',changeValue, false);
            console.log(i, tmp[i]);
    }
};

window.addEventListener("load",start_up, false);

Then the problem is that both ',' and '.' are added to the field.  How can I cancel the '.' pressed event?  How can I replace the '.' pressed event by ',' pressed event?
I have searched the Internet and see no solution with the 'addEventListener' function.

A: Using e.preventDefault() should do it.
I got a jsFiddle demo put together:  http://jsfiddle.net/yrYH4/

A: It may be because you are returning true from the event handler.
You can use event.preventDefault or return false to prevent default actions from being taken - you are returning false from the inner if statement of your handler, then returning true from the main function.


text:
Q: How to find a hidden code in a wordpress theme I have developed and published a wordpress website and I used a nulled theme (Business Lounge). After publish it into google suddenly I noticed there are pop up advertisements and push notifications are showing. I can Inspect the advertisement element. But I can't locate the source code from wp files. please help me to locate and delete the advertisement pop ups. also really appreciate if anyone can tell me how to figure out the push notifications code to modify/disable.
enter image description here

A: It's very bad idea to use nulled thems and plugins, and this issue you have is one of the reasons why.
But if you insist, you can use  php malware scanner :
https://github.com/scr34m/php-malware-scanner
NB : this tool may report some false positives, so you gonna have to be sure that the code is really a malware before you remove it


text:
Q: Visual Studio 2013 deploy without installer I'm developing a Windows app in Visual Studio 2013. When I use the publish feature, it creates a setup to install the app.
I don't want it to create a setup. I want it to build and deploy into a test environment, ready to be executed, without overwriting that environment's app.config. It would be great if I could configure multiple environments and choose which to be deployed.
I found https://msdn.microsoft.com/en-us/library/hh191495%28v=vs.120%29.aspx but it requires TFS. I wanna do it directly in VS.
To make it more clear, the best solution would me to type F6 - or any other shortcut - and have Visual Studio do the following:

*

*build solution

*copy exe and dlls to a specified folder

*don't change destination's app.config

*if possible, copy also source code so that debugger when opened is able to run thru it

It should be able to configure multiple profiles, so that it can send files to multiple test environments.


text:
Q: Accessing member type with `if constexpr` inside generic lambda requires both branches to be well-formed - gcc vs clang Consider two structs with different member type aliases:
struct foo { using x = int;   };
struct bar { using y = float; };

Given a T in a template context, I want to get either T::x or T::y depending on what T is:
template <typename T>
auto s()
{
    auto l = [](auto p)
    {
        if constexpr(p) { return typename T::x{}; }
        else            { return typename T::y{}; }
    };

    return l(std::is_same<T, foo>{});
}

int main()
{
    s<foo>();
}

g++ compiles the code above, while clang++ produces this error:
error: no type named 'y' in 'foo'
        else            { return typename T::y{}; }
                                 ~~~~~~~~~~~~^
note: in instantiation of function template specialization 's<foo>' requested here
    s<foo>();
    ^

on godbolt.org, with conformance viewer

Is clang++ incorrectly rejecting this code?
Note that clang++ accepts the code when removing the indirection through the generic lambda l:
template <typename T>
auto s()
{
    if constexpr(std::is_same<T, foo>{}) { return typename T::x{}; }
    else                                 { return typename T::y{}; }
}

A: See Richard Smith's post on std-discussion:

In the implementation I'm familiar with [i.e. Clang], a key problem is that the lexical scopes used while processing a function definition are fundamentally transient, which means that delaying instantiation of some portion of a function template definition is hard to support. Generic lambdas don't suffer from a problem here, because the body of the generic lambda is instantiated with the enclosing function template, [..]

That is, generic lambdas' bodies are partially instantiated using the local context (including template arguments) when the template is instantiated; thus under Clang's implementation, T::x and T::y are substituted directly, since the closure type could be passed outside. This leads to the failure. As pointed out by @T.C., the code can be considered ill-formed, no diagnostic required, as the instantiation of s<foo> yields a template definition (that of the closure) whose second if constexpr branch has no well-formed instantiations. This explains the behaviour of both Clang and GCC.
This boils down to an architectural issue in a major implementation (see also this answer; GCC apparently doesn't suffer from this limitation), so I'd be surprised if Core would deem your code well-formed (after all, they accounted for this in the design of generic lambda captures--see the linked answer). GCC supporting your code is, at best, a feature (but probably harmful, since it enables you to write implementation-dependent code).


text:
Q: How to remove duplicate unordered elements from list of lists? I have a list of lists:
[[1, 2, 5], [1, 7], [1, 6, 1], [2, 6], [2, 1, 5], [7, 1]]

I'm trying to remove elements [2,1,5] & [7,1] from it since elements [1,2,5] & [1,7] have the same elements and the order doesn't matter.
What is the fastest way to remove such elements?

A: You can keep track of the already seen elements in a set. You can sort them before, in order to "normalize" them and thus ignore the order of the elements.
>>> lst = [[1, 2, 5], [1, 7], [1, 6, 1], [2, 6], [2, 1, 5], [7, 1]]
>>> seen = set()
>>> unique = []
>>> for x in lst:
...     srtd = tuple(sorted(x))
...     if srtd not in seen:
...         unique.append(x)
...         seen.add(srtd)
...
>>> unique
[[1, 2, 5], [1, 7], [1, 6, 1], [2, 6]]

You have to convert the sorted elements to tuples before putting them into the set, as lists are not hashable, though. You might also consider using frozenset instead, but that will not work well with entries that have duplicate elements, such as [1, 6, 1]

A: You can create a list of sets as follows:
my_list = [[1, 2, 5], [1, 7], [1, 6, 1], [2, 6], [2, 1, 5], [7, 1]]
new_list = [frozenset(element) for element in my_list]

In order to remove the duplicates, do:
cleaned_set = set(new_list)

cleaned_set is a collection of sets, therefore contains no duplicates.

A: You can do something like this:
a = [[1, 2, 5], [1, 7], [1, 6, 1], [2, 6], [2, 1, 5], [7, 1]]
b = []
for k in a:
    if not sorted(k) in b:
        b.append(k)

>>> b
[[1, 2, 5], [1, 7], [1, 6, 1], [2, 6]]

Ps: if you have duplicates in your input list, think of using set() to remove them before using the loop.
Edit:
If the order doesn't matter:
a = [[1, 2, 5], [1, 7], [1, 6, 1], [2, 6], [2, 1, 5], [7, 1]]
b = [[1, 2, 5], [7, 1], [1, 6, 1], [2, 6], [2, 1, 5], [1, 7]]

>>> list(map(list, set(tuple(sorted(k)) for k in a)))
[[2, 6], [1, 1, 6], [1, 2, 5], [1, 7]]

>>> list(map(list, set(tuple(sorted(k)) for k in b)))
[[2, 6], [1, 1, 6], [1, 2, 5], [1, 7]]


text:
Q: How to add button and a processing layout on android studio I'm a student in 2 year electrical and computer science : i am not familiar with android studio (most of the time i work on C++).
I made a joystick on processing for an android project, and then I exported my processing sketch to android studio, now I have to find a way to recover data (vector position) from my processing sketch to my main activity.
BUT here is the problem:

*

*I want to add a TextView to my main activity but the processing sketch takes all the window, and I can't reduce it.

so what did i try :

*

*I tried to place the fragment in a relative layout, and then place the TextView but it didn't work, even if i make the fragment very little it still taking the whole screen.

My thought are that there is a problem with this line ->
setContentView(frame, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                     ViewGroup.LayoutParams.MATCH_PARENT));

I made some screenshots:
Here the Main Activity :
 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    FrameLayout frame = new FrameLayout(this);
    frame.setId(CompatUtils.getUniqueViewId());
    setContentView(frame, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                     ViewGroup.LayoutParams.MATCH_PARENT));
   // setContentView(R.layout.main); // attach the view for this activity

    sketch = new Joystick();

    PFragment fragment = new PFragment(sketch);
    fragment.setView(frame, this);
  }

Here the view of the main activity

A: In order to have a fragment in your Main Activity you can do the following:
 public class MainActivity extends AppCompatActivity {

        @Override
        protected void onCreate (Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            SectionsPagerAdapter mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

            // Set up the ViewPager with the sections adapter.*/
            ViewPager mViewPager = (ViewPager) findViewById(R.id.container);
            mViewPager.setAdapter(mSectionsPagerAdapter);

            TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
            tabLayout.setupWithViewPager(mViewPager);
        }

        /**
         * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
         * one of the sections/tabs/pages.
         */
         private class YourFragmentAdapter extends FragmentPagerAdapter {

              SectionsPagerAdapter(FragmentManager fm) {
              super(fm);
         }

         @Override
         public Fragment getItem(int position) {
             switch (position) {
                 case 0:
                     return new YourFragment()
                 default:
                     return null;
            }
        }

        @Override
        public int getCount() {
            return 1;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
                case 0:
                    return "Your fragment name";
            }
            return null;
        }
    }

    }

main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <android.support.v4.view.ViewPager
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>

Your fragment class:
public class YourFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_main, container, false);
        return rootView;
    }
}

In this way you could have an activity with as many views as you want, and as many fragments as you wish. Note that if you have more than one fragment your activity will be more like a tabbed activity.