text:
Q: How to make headers glossy in IE7,8,9 using CSS I am using below code to get a glossy look for a header label. It works fine in FF, Chrome and IE10. But when loaded in lower versions of IE like IE7,8,9. Glossy finish is lost. Can any body help me to get glossy look on the header?? Please refer to the below images for glossy look and normal look.
Glossy Header

Normal Header

.docTitle
{
    font-weight: bold;
    width: 99.3%;

        font: bold 12px/100% Arial,Verdana,helvetica;
    padding: 8px 5px;
    text-decoration: none;
    color: rgb(255, 255, 255);
    text-shadow: 0 -1px 0 rgba(0,0,0,.9);
    background: #255182;
    background: -webkit-linear-gradient(top, #2f4f88, #385993 49%, #21427d 50%, #255182);
    background: -moz-linear-gradient(top, #2f4f88, #385993 49%, #21427d 50%, #255182);
    background: -ms-linear-gradient(top, #2f4f88, #385993 49%, #21427d 50%, #255182);
    background: -o-linear-gradient(top, #2f4f88, #385993 49%, #21427d 50%, #255182);
    background: linear-gradient(to bottom, #2f4f88, #385993 49%, #21427d 50%, #255182);
}

A: see the "notes" and "resources" on this page: http://caniuse.com/#feat=css-gradients. Older IE does not support the css3 gradients, but there are workarounds if its important enough to you. I personally would be fine with a "non-glossy" appearance in IE.
http://css3pie.com/ is one option for emulating support in IE.


text:
Q: Powershell get address list work in PS 5.1 but not in 7 I'm trying to retrieve info about Global Address List in Outlook.
It works in Powershell 5.1 but not in 7.0.3.
The Code is:
$Outlook = NEW-Object -comobject Outlook.Application
$Outlook.GetNamespace("MAPI").AddressLists("Global Address List")

Output in PS 5.1:
Application          : Microsoft.Office.Interop.Outlook.ApplicationClass
Class                : 7
Session              : Microsoft.Office.Interop.Outlook.NameSpaceClass
Parent               : System.__ComObject
AddressEntries       : System.__ComObject
ID                   : 00000000E3FDA12B9AF86342819F3DEFE5D82FE001000000000100002F00
Index                : 2
IsReadOnly           : True
Name                 : Global Address List
AddressListType      : 0
ResolutionOrder      : 1
IsInitialAddressList : True
PropertyAccessor     : System.__ComObject

Output in PS 7.0.3:
Method invocation failed because [System.__ComObject] does not contain a method named 'AddressLists'.

Do you havy any idea why this not working in new Powershell version?

A: I can replicate the issue. Does this work for you? It gives equal results $Outlook.GetNamespace("MAPI").AddressLists | Where {$_.name -eq 'Global Address List'}

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHPExcel - setTitle with variable not working When trying to use a variable to set worksheet name with PHPExcel it pulls up an error. Can anyone help?
Here is the code section I'm using:
for($i = 0;$i <= 9; $i++){
   $objPHPExcel->getActiveSheet()->setCellValue('A1', $i);

   $objWorksheet = $objPHPExcel->createSheet();
   $objWorksheet->setTitle($i);

   $objPHPExcel->setActiveSheetIndex($i);
}

Here is the error:
Fatal error: Uncaught exception 'Exception' with message
     'Invalid character found in sheet title' in ...Worksheet.php:401
Stack trace:
   #0 ...Worksheet.php(657): PHPExcel_Worksheet::_checkSheetTitle(1)
   #1 ...JH-auto-sheets.php(37): PHPExcel_Worksheet->setTitle(1)
   #2 {main} thrown in ...Worksheet.php on line 401`

A: There are some characters that PHPExcel won't allow you to use for tab titles, even if it's allowed within Excel itself.  I've experienced issues with the following characters, and make sure my tab titles don't contained these characters: []:?!/\*
I discovered this through experience and process of elimination.  There may be more characters out there that will throw this error.  I just haven't found them yet.

A: You cant use any of these characters *:/\?[] in the title.
Also the title has a maximum length of 31 characters, so you should check for that as well.

A:   array (size=7)

  0 => string '*' (length=1)

  1 => string ':' (length=1)

  2 => string '/' (length=1)

  3 => string '\' (length=1)

  4 => string '?' (length=1)

  5 => string '[' (length=1)

  6 => string ']' (length=1)

you can not use this in your parameter

A: I just had this same problem but was able to overcome it.
For some reason, setTitle will throw the exception "Invalid character found in sheet title" if your variable is not explicitly declared as a string.
So, in your example, change
`$objWorksheet->setTitle($i);`

to
`$objWorksheet->setTitle(strval($i));`


text:
Q: What is the difference between shadowsocks and openvpn? I currently configured openVPN and shadowsocks(based on socks5) on a server. I am confused what is the difference between two and when should I use one over other.

A: Although they can perform similar things, under the hood OpenVPN and Shadowsocks are entirely different beasts.
OpenVPN is a VPN server.
Shadowsocks is a Proxy.
A proxy can (optionally using encryption) ask another computer to get information for you.  Generally the intermediate system is actually doing some processing of the packets. This limits the programs which can run on top of it.
A VPN encrypts packets sent between points - in the case of a VPN, other then stripping encryption and forwarding the raw packet, the VPN server does modify the packets.  (*a VPN server may additionally deploy NAT which will rewrite the source or target address of the packets). VPN's are more flexible.  An application needs to be built to work with SOCKS.
VPN servers are generally (but not always) easier for governments to detect and block, as they generally speak their own protocol to make them more general purpose.  Applications do not need to modification to work with a VPN.    Also, the nature of a VPN is such that long sessions can be detected, even when web browsing - while a proxy server will open and close the connection like a web page.
Thus the answer to which to use depends on your purpose in using one.  If "flying under the radar" while using a limited set of protocols/programs is more valuable, use SOCKS.    If greater flexibility of protocols or more control of the underlying delivery mechanism is required, use OpenVPN.
Another way to think of it is that a VPN overlays a "virtual network" at (close to) an OS level on top of part of an actual actual network, while a proxy creates applications to talk to each other in an encrypted way without virtualising the underlying network.

A:
"Shadowsocks is based on a technique called proxying. Proxying grew
popular in China during the early days of the Great Firewall—before it
was truly "great." In this setup, before connecting to the wider
internet, you first connect to a computer other than your own. This
other computer is called a "proxy server." When you use a proxy, all
your traffic is routed first through the proxy server, which could be
located anywhere. So even if you're in China, your proxy server in
Australia can freely connect to Google, Facebook, and the like.
But the Great Firewall has since grown more powerful. Nowadays, even
if you have a proxy server in Australia, the Great Firewall can
identify and block traffic it doesn't like from that server. It still
knows you are requesting packets from Google—you're just using a bit
of an odd route for it. That's where Shadowsocks comes in. It creates
an encrypted connection between the Shadowsocks client on your local
computer and the one running on your proxy server, using an
open-source internet protocol called SOCKS5.
How is this different from a VPN? VPNs also work by rerouting and
encrypting data. But most people who use them in China use one of a
few large service providers. That makes it easy for the government to
identify those providers and then block traffic from them. And VPNs
usually rely on one of a few popular internet protocols, which tell
computers how to talk to each other over the web. Chinese censors have
been able to use machine learning to find "fingerprints" that identify
traffic from VPNs using these protocols. These tactics don't work so
well on Shadowsocks, since it is a less centralized system."

All information is from this site:
https://qz.com/1072701/meet-shadowsocks-the-underground-tool-that-chinas-coders-use-to-blast-through-the-great-firewall/


text:
Q: How to define a zero (runtime) cost abstract interface in C++ Context
I'm building a kernel in C++. I want to expose an interface to the kernel independent of the architecture implementation, so that the main kernel code can be architecture-agnostic. For example,
kernel.cpp
#include "Terminal.hpp"

void kernel_main()
{
    Terminal terminal;
    terminal.write("Hello, kernel!\n");
}

Terminal.hpp
class Terminal
{
public:
    void write(const char *str);

private:
    // members required for managing terminal output
};

where the implementation for Terminal is different for each architecture, and the compiler chooses the right object file to link based on the desired architecture target:
arch/x86/Terminal.cpp
Terminal::write(const char *str)
{
    // x86 specific way of writing to the terminal
}

Ideally, I want to have code that looks like kernel.cpp, where the implementation of Terminal changes depending on whether I decide to compile and link the project with arch/x86/Terminal.cpp, arch/mips/Terminal.cpp, or any other arch/<architecture>/Terminal.cpp.
Problem
The problem is that the private members of Terminal could differ depending on the architecture, depending on what is needed to manage terminal output for that specific architecture. I want a way to expose an abstract Terminal interface that does not define any implementation details (including differing private members).
Possible Solutions
Abstract Base Class
A solution might be to use an abstract base class. I want to avoid this because of the overhead of run-time polymorphism, and the fact that the desired Terminal type doesn't need to be determined at run-time since it's already known at compile-time (through knowledge of which architecture is being targeted).
PIMPL
Another solution could be to use the PIMPL idiom, but I also want to avoid this because of the overhead of allocating memory on the heap for the implementation and pointer indirection.
CRTF
The CRTF template pattern seems close to what I want, but I'm not sure how to use it without specifying the architecture I'm targeting in the form of a template parameter (which would make the kernel code not architecture-agnostic):
kernel.cpp
void kernel_main()
{
    Terminal<x86> terminal;
    terminal.write("Hello, kernel!\n");
}

What's the simplest and most idiomatic way to do this in C++?

A: As suggested in the comment, you could mix CRTP with macro preprocessor definitions. You could use a build system like CMake to conveniently set these definitions for you.
architecture.h.in
This is a header file to be prepared by CMake. CMake is to replace @ARCHITECTURE@ with the architecture of you choice and store the configured file in the binary/build directory:
#pragma once

#define ARCH_STR "@ARCHITECTURE@"
#define ARCH @ARCHITECTURE@

main.cpp
This represents your kernel code (which would surely be separated into several files)
#include "architecture.h"
#include <iostream>

template <typename Derived>
class Terminal {
    Derived& downcast(){
        return static_cast<Derived&>(*this);
    };

    Derived const& downcast() const {
        return static_cast<Derived const&>(*this);
    }

public:
    void write(const char* str) const {
        downcast().write(str);
    }
};

class x86_64: public Terminal<x86_64>
{
public:
    void write(const char* str) const {
        std::cout << std::string("Hello ") + std::string(str) + " from x86_64\n";
    }
};

class x86: public Terminal<x86>
{
public:
    void write(const char* str) const {
        std::cout << std::string("Hello ") + std::string(str) + " from x86\n";
    }
};

int main(){
    Terminal<ARCH> terminal;
    terminal.write("dav");
}

CMakeLists.txt
cmake_minimum_required(VERSION 3.1)
project(test)

configure_file(
    architecture.h.in
    architecture.h
)
include_directories(${CMAKE_CURRENT_BINARY_DIR})

add_executable(test main.cpp)

Building
mkdir build && cd build
cmake .. -DARCHITECTURE=x86_64
cmake --build .

See here for a demo. This is just a small example to get you started. You would probably want to automate setting the ARCHITECTURE definition through your cross compilation process. But this is where I leave my comfort zone.


text:
Q: Ubuntu Netbook Edition and automatic login I'm trying to set up the automatic login, but i can't choose the user which must be loged in. Here a screenshot (German is set as default language):

any suggestion, how to solve the problem?
I'm using UNE 10.10, upgraded from 10.04...

A: It seems, that i can't use the automatic login, because my home folder is encrypted.
* (gdmsetup:2834): WARNING: Unable to lookup user name data: Success *
* (gdmsetup:2834): DEBUG: XXXXXX XXXXX is using an encrypted home, not listing him for autologin *

A: Are you logging in as "root" by any chance (AFAIK "root" gets removed from that drop-down list)?
Anyways, you can add the information to the '[daemon]' section of the file '/etc/gdm/custom.conf':
...
[daemon]
AutomaticLoginEnable=true
AutomaticLogin=<USERNAME>
...

A: A "dirty" init script with a automated login, password and a decrypt should be coded?
I am not a programmer, so I don't know if it's possible. I think about something you can just turn on/off with a single reboot to go "holiday" mode or "inhome" mode. (put/delete the script to automatically run on boot, even a script to do this too, a button on dock)
The 1st script will do the autologin and the decrypt for you when in "inhome" mode.
Sure you gonna search a good way to store the password for the script.

A: Go to Applications, next go to Users and Groups click on the user and your going to have to put in the root password to unlock then click passwords and check the do not ask at log in.


text:
Q: Define 2 switchable implementations of the same functions in NodeJS / Express I have a bunch of field to calculate, and I have 3 cases.
Fields are mostly the same, but there is some differences.
Also, calculation to obtain each field may depend on differents variable, so function may have different signature.
In other languages, I would define an interface, use constructors using interface instead of concrete class and use dependency injection.
In nodeJS, I'm a newbie, and I saw there is no such thing that interfaces.
To take a concrete example, I must calculate
I have 2 case:

*

*case sup36 === true
fixedRouting = (CG + CC + CSF * subscribedPower) / 12

*case sup36 === false
fixedRouting = (CG + CC) / 12 + subscribedPower * billedCSFCoef * numDayInPeriod / 100

Right now, I add a parameter:
getFixedRouting(isSup36, CG, CC, subscribedPower, billedCSFCoef, numDayInPeriod) {
        if isSup{
            return (CG + CC + CSF * subscribedPower) / 12
        }else{
            return (CG + CC) / 12 + subscribedPower * billedCSFCoef * numDayInPeriod / 100
        }
    },

Problem is I will have more than 2 cases, and I will have to code more cases in the future. This way of coding will also increase the complexity of my code.
How should I do to be able to have 2 switchable implementations of getFixedRouting(...) ?

A: You can either have different functions for the different cases like this:
function getFixedRoutingSup36(CG, CC, subscribedPower) {
  return (CG + CC + CSF * subscribedPower) / 12;
}
function getFixedRoutingNonSup36(CG, CC, subscribedPower, billedCSFCoef, numDayInPeriod) {
  return (CG + CC) / 12 + subscribedPower * billedCSFCoef * numDayInPeriod / 100;
}

This can be helpful if the parameters sent to each differ greatly (for example above the sup36 case does not need or use billedCSFCoef or numDayInPeriod).
If you like having one entry point for all of this you can still have the functions split above like that but have this one entry point that you tell people to use:
function getFixedRouting(dataType, CG, CC, subscribedPower, billedCSFCoef, numDayInPeriod) {
  switch (dataType) {
    case 1:
      return getFixedRoutingSup36(CG, CC, subscribedPower);
    case 2:
      return getFixedRoutingNonSup36(CG, CC, subscribedPower, billedCSFCoef, numDayInPeriod);
    case 3:
      return someOtherFunction();
  }
}

The drawback here is that if your variety of cases take a different set of parameters it can get ugly.
Another variant is to pass the parameters as a Javascript Object so the contents can vary:
function getFixedRouting(data) {
  switch (data.type) {
    case 1:
      return getFixedRoutingSup36(data.CG, data.CC, data.subscribedPower);
    case 2:
      return getFixedRoutingNonSup36(data.CG, data.CC, data.subscribedPower, data.billedCSFCoef, data.numDayInPeriod);
    case 3:
      return someOtherFunction();
  }
}


text:
Q: Conditional probability question, joint probability for discrete random variables I have a homework question that I want to make sure I'm getting it right.
This is a joint probability table for the proportions of survey respondents who smoke and who have had heart attacks.
                          Smoker Non-Smoker
Heart Attack      0.03      0.03
No Heart Attack0.44      0.50
If a person is a smoker, are they more likely to have had a heart attack than someone who is not a smoker?
So I know that $P(A|B) = \dfrac{P(A \cap B)}{P(B)}$
So I could think of the question like: Find the conditional probability that a randomly selected person is a victim of a heart-attack, given that they're a smoker/ non-smoker.
$ P(X = Smoker \cap Y = Heart Attack) = 0.03  $
    $     P(X = NonSmoker \cap Y = Heart Attack) = 0.03  $
$P(Y) = 0.06$
That would mean that a smoker and a non-smoker would both have a $\dfrac{0.03}{0.06}$ chance of having a heart attack?
This defies my intuition because $\dfrac{3}{47}$ smokers get heart attacks, while only $\dfrac{3}{53}$ non-smokers get heart attacks.

A: You are given that they are a smoker/non-smoker. So your math is correct for what you have expressed, however you've done the conditional probabilities backwards. You are interested in $P(\text{ heart attack }| \text{ smoker })$ and $P(\text{ heart attack }| \text{ non-smoker })$. Calculating these will give you a more intuitive result for your question.
In the general case, consider $P(A|B)$ reading as "the probability of $A$ given $B$". Then your formula $P(A|B) = \frac{P(A \cap B)}{P(B)}$ should hopefully make some intuitive sense looking at your denominator.

A:
$ P(X = Smoker$ | $Y = Heart Attack) = 0.03  $
    $     P(X = NonSmoker$ | $Y = Heart Attack) = 0.03  $
    $P(Y) = 0.06$

No, from the table you have joint probabilities:
$ P(X = \textsf{Smoker} \cap Y = \textsf{Heart Attack}) = 0.03  $
$ P(X = \textsf{Non-Smoker}\cap Y = \textsf{Heart Attack}) = 0.03 $
$ \therefore P(Y=\textsf{Heart Attack}) = 0.06$
Then you calculate ${\large P}\big(X=\textsf{Smoker}\mid Y=\textsf{Heart Attack}\big) = 0.50$
This is the probability that someone is a smoker given that they have had a heart attack.
Now, according to the table it is slightly more likely for a smoker to have a heart attack than for a non-smoker.
$$P(Y=\textsf{Heart Attack}\mid X=\textsf{Smoker}) = \frac{0.03}{0.03+0.44} = \frac 3{47} \\ P(Y=\textsf{Heart Attack}\mid X=\textsf{Non-Smoker}) = \frac{0.03}{0.03+0.50} = \frac 3{53}$$
However there are only slightly more non-smokers than smokers over all.   This happens to balance out so that there are an equal number of smokers and non-smokers who have had heart-attacks.


text:
Q: Changing the default gateway, multiple NICs I have Ubuntu 13.10 (kernel 3.11.0-19-generic). On startup, the network configurations are as follows:
dor@ubuntu:~$ sudo ifconfig -a
em1       Link encap:Ethernet  HWaddr 44:37:e6:4c:ca:0a
          inet addr:10.1.0.102  Bcast:10.1.7.255  Mask:255.255.248.0
          inet6 addr: fe80::4637:e6ff:fe4c:ca0a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:732 errors:0 dropped:0 overruns:0 frame:0
          TX packets:79 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:68789 (68.7 KB)  TX bytes:12907 (12.9 KB)
          Interrupt:20 Memory:fe600000-fe620000

eth5      Link encap:Ethernet  HWaddr 00:0a:5e:50:cf:1e
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:20 Base address:0xa000

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:101 errors:0 dropped:0 overruns:0 frame:0
          TX packets:101 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:8485 (8.4 KB)  TX bytes:8485 (8.4 KB)

p4p1      Link encap:Ethernet  HWaddr 00:15:17:0b:6d:1c
          inet addr:192.168.1.2  Bcast:192.168.1.255  Mask:255.255.255.0
          inet6 addr: fe80::215:17ff:fe0b:6d1c/64 Scope:Link
          inet6 addr: fc00::215:17ff:fe0b:6d1c/64 Scope:Global
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:41 errors:0 dropped:0 overruns:0 frame:0
          TX packets:100 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:4062 (4.0 KB)  TX bytes:15981 (15.9 KB)
          Interrupt:16 Memory:fe540000-fe560000

dor@ubuntu:~$ sudo route -n
[sudo] password for dor:
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         192.168.1.1     0.0.0.0         UG    0      0        0 p4p1
10.1.0.0        0.0.0.0         255.255.248.0   U     0      0        0 em1
192.168.1.0     0.0.0.0         255.255.255.0   U     1      0        0 p4p1

The gateway to the internet is 10.1.0.1. So I manually execute the following:
dor@ubuntu:~$ sudo route del default
dor@ubuntu:~$ sudo route add default gw 10.1.0.1

This is how I manage to get to the internet.
But instead of doing this everytime manually, how do I make this permanent?
The content of /etc/network/interfaces (deleted some of the commented lines):
dor@ubuntu:~$ cat /etc/network/interfaces
# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto em1

iface eth5 inet static
     address 10.90.90.91
     netmask 255.255.255.0
     gateway 10.90.90.90

iface em1 inet static
     address 10.1.0.102
     netmask 255.255.248.0
     gateway 10.1.0.1

I've read the manual of interfaces and route for so many times and many google results but can't figure this out. Thank you.

Edit #1, 17 Apr 2014 12:11 UTC:
(response to the responder Sobrique)
I've edit the file /etc/network/interfaces to have the following content:
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
auto em1
#iface em1 inet dhcp

iface eth5 inet static
     address 10.90.90.91
     netmask 255.255.255.0
#     gateway 10.90.90.90

iface p4p1 inet static
     address 192.168.1.32
     netmask 255.255.255.0
#     gateway 192.168.1.22

iface em1 inet static
     address 10.1.0.102
     netmask 255.255.248.0
     gateway 10.1.0.1

Now there's an internet access immediately upon startup, without having to execute any command.
The problem is that I don't have access to the network 192.168.1.X.
Earlier there was an access. How can I fix this? Some data:
dor@ubuntu:~$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.1.0.1        0.0.0.0         UG    0      0        0 em1
10.1.0.0        0.0.0.0         255.255.248.0   U     0      0        0 em1
dor@ubuntu:~$ ifconfig -a
em1       Link encap:Ethernet  HWaddr 44:37:e6:4c:ca:0a
          inet addr:10.1.0.102  Bcast:10.1.7.255  Mask:255.255.248.0
          inet6 addr: fe80::4637:e6ff:fe4c:ca0a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:30356 errors:0 dropped:0 overruns:0 frame:0
          TX packets:329 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:2752089 (2.7 MB)  TX bytes:43904 (43.9 KB)
          Interrupt:20 Memory:fe600000-fe620000

eth5      Link encap:Ethernet  HWaddr 00:0a:5e:50:cf:1e
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:20

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:97 errors:0 dropped:0 overruns:0 frame:0
          TX packets:97 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:8463 (8.4 KB)  TX bytes:8463 (8.4 KB)

p4p1      Link encap:Ethernet  HWaddr 00:15:17:0b:6d:1c
          BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:16 Memory:fe540000-fe560000

Edit #2, 20 Apr 2014 08:05 UTC:
Eventually I've edit the file /etc/network/interfaces to have the following configurations:
auto em1
iface em1 inet dhcp

auto eth5
iface eth5 inet static
     address 10.90.90.91
     netmask 255.255.255.0
     up route add -net 10.90.90.0/24 dev eth5

auto p4p1
iface p4p1 inet static
     address 192.168.1.32
     netmask 255.255.255.0
     up route add -net 192.168.1.0/24 dev p4p1

And it worked! See:
dor@ubuntu:~$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         10.1.0.1        0.0.0.0         UG    0      0        0 em1
10.1.0.0        0.0.0.0         255.255.248.0   U     0      0        0 em1
10.90.90.0      0.0.0.0         255.255.255.0   U     0      0        0 eth5
10.90.90.0      0.0.0.0         255.255.255.0   U     0      0        0 eth5
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 p4p1
192.168.1.0     0.0.0.0         255.255.255.0   U     0      0        0 p4p1

The only problem is having those duplicates. But it doesn't interfere with anything, it still works.

Edit #3, 20 Apr 2014 09:57 UTC:
Indeed as I suspected, the duplicates were caused from the commands such as:
up route add -net 192.168.1.0/24 dev p4p1

So I removed them. Now everything's perfect.

A: I think the mistake here, is that you've got multiple default gateways configured in your config file. It doesn't work that way - it's a default, in that any traffic which doesn't have a known route gets sent there for passing on (in the expectation that it'll know, or have it's own default). But it's not tied to a particular interface explicitly - implicitly there will be interfaces that can reach the default gateway, but others that cannot.
So I would imagine what you need to do is remove your 'gateway' lines, and add in the single one you want - ideally in the right interface stanza, but I don't actually think it should matter.


text:
Q: AndroidMy 6.0 targetSdkVersion 23 open failed: EACCES (Permission denied) I got a error, W/System.err: java.io.FileNotFoundException: open failed: EACCES (Permission denied)
Code has :
Environment.getExternalStorageDirectory().getAbsolutePath()

AndroidManifest.xml has :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

build.gradle has:
targetSdkVersion is 23

A: You probably did not ask permission to do these actions, you have to ask the users to grant your app these permissions.
See this related post: Storage permission error in Marshmallow

A: The problem is security permission needed from Lollipop
public static boolean checkReadStoragePermission(final Context context){
        int currentAPIVersion = Build.VERSION.SDK_INT;

        if(currentAPIVersion>= 23)
        {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {

                if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context,
                        Manifest.permission.READ_EXTERNAL_STORAGE)) {

                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                    alertBuilder.setCancelable(true);
                    alertBuilder.setTitle("Storage Permission Necessary");
                    alertBuilder.setMessage("External storage permission is necessary");
                    alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions((Activity) context,
                                    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                                    MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                        }
                    });
                    AlertDialog alert = alertBuilder.create();
                    alert.show();

                } else {
                    ActivityCompat.requestPermissions((Activity) context,
                            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }

   public static boolean checkWriteStoragePermission(final Context context){
        int currentAPIVersion = Build.VERSION.SDK_INT;

        if(currentAPIVersion>= 23)
        {
            if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                    != PackageManager.PERMISSION_GRANTED) {

                if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)) {

                    AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
                    alertBuilder.setCancelable(true);
                    alertBuilder.setTitle("Storage Permission Necessary");
                    alertBuilder.setMessage("External storage permission is necessary");
                    alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            ActivityCompat.requestPermissions((Activity) context,
                                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
                        }
                    });
                    AlertDialog alert = alertBuilder.create();
                    alert.show();

                } else {
                    ActivityCompat.requestPermissions((Activity) context,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
                }
                return false;
            } else {
                return true;
            }
        } else {
            return true;
        }
    }


text:
Q: Adding multiple Dom Nodes in Content I am using a popup on my mapView from arcGIS API for Javascript 4.17. When the user opens the popup, I have set the following attributes:
    view.popup.open({
        // Set the popup's title to the coordinates of the clicked location
        title: "Location Coordinates: [" + lon + ", " + lat + "]",
        location: event.mapPoint, // Set the location of the popup to the clicked location
        content: setContentInfo(view.center, view.scale),
        actions: [risk_snapshot, ble_report, print_report, lidar_report]
    });

In the popup, I am adding some smaller maps using a function called setContentInfo that returns a "masterDiv" DOM node with the maps. However, I want to add an additional DOM Node outside of that div to the content. The function is essentially setup as below. How can you add multiple items -DOM Nodes to content?
function setContentInfo(center, scale) {
    var popupDiv1 = document.createElement("div");
    popupDiv1.classList.add("mapViewLeft");

    var popupView1 = new MapView({
        container: popupDiv1,
        map: map,
        actions: [],
        center: view.center,
        zoom: view.zoom,
        scale:
            view.scale *
            2 *
            Math.max(view.width / 250, view.height / 250),
        constraints: {
            rotationEnabled: false
        },
        ui: {
            components: []
        }
    });

    var popupDiv2 = document.createElement("div");
    ...

    var popupMasterDiv = document.createElement("div");
    popupMasterDiv.id = "masterDiv";
    popupMasterDiv.style.width = "650px";
    popupMasterDiv.style.height = "450px";
    var theDiv = document.getElementById("masterDiv");
    popupMasterDiv.appendChild(popupDiv1);
    popupMasterDiv.appendChild(popupDiv2);

    // Return a dom node
    //return popupView.container;
    return popupMasterDiv;
}

To test, I have tried adding var test = document.createElement("div"); test.textContent = "Hey"; and then adding
   popupMasterDiv.appendChild(popupDiv1);
   popupMasterDiv.appendChild(popupDiv2);
   popupMasterDiv.appendChild(test);

but it puts the "Hey" in the middle of the 2 maps. I also tried adding the above straight to the content like this:
  content: setContentInfo(view.center, view.scale) + test,

But that removes the map content and only displays "Hey"
What I want is to add a nice little table in its own div under the maps with something like this. What am I doing wrong here; how can I achieve this:
var table1 = "

                  Location

                  Coordinates
                  Parcel ID

                 123.345, -43.432
                 12345

"

A: I was able resolve this quite simple using the following:
 var table_1 = document.createElement("div");
    table_1.id = "table1";
    table_1.innerHTML = "
" +
        "
" +
        "
" +
        ...
        "
" +
        "
" +
        "
";

and then adding the new table1 div node to the master div using appendChild:
 var popupMasterDiv = document.createElement("div");
 popupMasterDiv.id = "masterDiv";
     ...
 popupMasterDiv.appendChild(table_1);

The trick is to create a DOM node for the table before appending it to the masterDiv.


text:
Q: python: scraping with button I faced the problem when I try to collect all the comments from https://ideas.lego.com/projects/6f1d4d6e-f47a-467a-8b10-d918d04e6d5c/comments_tab, there is two types of button for comments

*

*Load more comments, I solve it

*Show the reply, that one I couldn't solve it.

i tred to add it as button and click it but not work fine
    from bs4 import BeautifulSoup
    from selenium import webdriver
    import time

    driver = webdriver.PhantomJS()
    driver.get('https://ideas.lego.com/projects/6f1d4d6e-f47a-467a-8b10-d918d04e6d5c/comments_tab')

    sbtn = driver.find_element_by_class_name("load-more")
    sbtn.click()

    SCROLL_PAUSE_TIME = 1

    # Get scroll height
    last_height = driver.execute_script("return document.body.scrollHeight")

    while True:
        # Scroll down to bottom
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

        # Wait to load page
        time.sleep(SCROLL_PAUSE_TIME)

        # Calculate new scroll height and compare with last scroll height
        new_height = driver.execute_script("return document.body.scrollHeight")
        if new_height == last_height:
            break
        last_height = new_height

    html = driver.page_source
    soup = BeautifulSoup(html, "html.parser")
    z = soup.find_all('div', attrs={'class': 'comment-message cms'})
    #print(z)
    print(len(z))

Thanks
====== Edits ======
what i did :
Load all the page with scrolling all down the page and collect all the comments, except the under the reply, because I didn't find a way to click the button to complete load all of them


text:
Q: How do i bindkey the Right Control Key in zsh? I searched the internet and could not find anybody asking this question. I was annoyed of moving right and the autocomplete autosuggest-accept being the same keybind. My closes guesses were
bindkey -v '<C-Right>' autosuggest-accept

and
bindkey '\xffe4' autosuggest-accept

but they did not work. How should I go at finding how to do this?

A: short: you probably can't do that
longer: your mention of 0xffe4 refers to this chunk in <X11/keysymdef.h>:
/* Modifiers */

#define XK_Shift_L                       0xffe1  /* Left shift */
#define XK_Shift_R                       0xffe2  /* Right shift */
#define XK_Control_L                     0xffe3  /* Left control */
#define XK_Control_R                     0xffe4  /* Right control */
#define XK_Caps_Lock                     0xffe5  /* Caps lock */
#define XK_Shift_Lock                    0xffe6  /* Shift lock */

but take note of that Modifiers.  Normally those keys only modify other key bindings in X, and do not act alone.  For zsh, bash or any other shell, you need something that acts alone.  You can use xmodmap or tinker with xkb, by inventing some way to make that key send one or more characters, but without that, the shell will not see anything.

A: I don't think it can be done with any software/program running inside a terminal, including zsh.
Or at least, I have never seen in any software, either Right Ctrl (alone) binded to something, or a way to bind it explained in the manual, or an explicit distinction between Left Ctrl and Right Ctrl. If you know one software with this option (working with any terminal), please, let me know.
Software I configured includes : vim, zsh, lf, fzf, tmux, htop, less, most and visidata,
and none talks about what you want. So, if some software can do this in terminal, it's at least extremely rare.
The only times where I have seen something similar to C-Left, C-Right (quote from man tmux ) are about any Ctrl pressed with left or right arrow (It does means Left or Right Ctrl) : there are also C-Up, C-Down while there is not an up/down Ctrl key on regular keyboard.

You can't with zsh (assuming zsh's manual is correct) :
after searching man zshall (man zsh isn't complete), I see there is a Ctrl + v shortcut for :
quoted-insert (^V) (unbound) (unbound)
Insert the next character typed into the buffer literally.  An interrupt character will not be inserted.

So, now, I try any Ctrl + vLeft Ctrl + a, or any Ctrl + vRight Ctrl + a, both show me ^A, that means both put the same char (by checking this with vim too, and pressing ga, I see that it's the 2nd ascii char, with value 0x01). So zsh probably doesn't make any distinction between Left Ctrl and Right Ctrl.
If I press any Ctrl + vRight Ctrl (alone), it does nothing.
Both vim and zsh tells me the same thing : they don't know when a Ctrl key is pressed without a key,
while unusual keys like Ctrl + vF1 (at least unusual in a terminal) give me something :  ^[OP with zsh or <F1> with vim. Meaning F1 can be recognized with terminals.

A shell like zsh can run inside tmux, and tmux has a send-keys feature, that doesn't make any distinction between Left Ctrl and Right Ctrl. It means you will not be able to do what you want in the generic case.
To be sure, I also searched in tmux source code (I got it with git clone tmux), and tried rgrep -i "ctrl\|control" | grep -i "right\|ctrl.\?r\|r.\ctrl" to see every time it speaks about the Right Ctrl key, and what I found is :
tty-keys.c:134: { "\033Oc", KEYC_RIGHT|KEYC_CTRL },
tty-keys.c:405: { TTYC_KRIT5, KEYC_RIGHT|KEYC_CTRL },
tty-keys.c:406: { TTYC_KRIT6, KEYC_RIGHT|KEYC_SHIFT|KEYC_CTRL },
tty-keys.c:407: { TTYC_KRIT7, KEYC_RIGHT|KEYC_META|KEYC_IMPLIED_META|KEYC_CTRL },
CHANGES:2395:  control the maximum length of left and right components of the
status bar.
CHANGES:2550:  C- for ctrl keys (^ is still accepted as an alternative).
status.c:1168:  case KEYC_RIGHT|KEYC_CTRL:

so, most of them are talking about Ctrl + Right and the others aren't relevant.

On some terminals like st (where I can configure any key), on config.h, I see code like :
{ XK_KP_End,        ControlMask,    "\033[1;5F",    +1,    0},
{ XK_KP_End,        ShiftMask,      "\033[K",       -1,    0},

means some stuff is done when you press Ctrl + End or Shift + End, and I have seen nowhere any distinction between the left or right Ctrl. There is only one ControlMask, and also only one ShiftMask (so, my answer would be the same if it were about Shift keys).
I also tried my rgrep command on st source code, and again, it's talking only about Ctrl + Right.

I can do this for any other terminal emulator. I think it's enough to consider there is no way to do this in the generic case. Actually, there is a way to get this behavior and to get it only on zsh but it's very hard : edit the source code of zsh, and of your terminal emulator, and maybe of xorg.

If you want to change the Right Ctrl's behavior, you will need to bind the Right Ctrl for every software.
See man xmodmap, man setxkbmap and man xkeyboard-config for more informations about keyboard config.
Usually, Ctrl keys are modifiers. It means they are supposed to do something only when you press it with another key.
note : there are some rare cases where a key can either act as a modifier or as a key, like :

*

*some softwares (it includes libreoffice) where you will see some letters underlined while you press an Alt.

*xev is a tool made to test events, so, it recognizes everything, including pressing an arbitrary key.

*dual function key from QMK allows some keys to behave like "regular keys" when you type them fast, and like modifiers when you press another key.

*emacs has a key chord feature. It's not exactly about official modifiers (Shift or Control or Alt etc.), but it can make a regular key act like a modifier if pressed with some other key in some delay. emacs can run outside from the terminal, and you can run a shell inside emacs. So, maybe you can :

*

*remap the Right Ctrl key to something (let's call it foo) everywhere using setxkbmap or xmodmap.

*inside emacs, remap foo back to right control using key-chord for some parts but not for where you run zsh.

*note that I haven't tested this, and if possible, it's probably not
simple, but emacs is the only "terminal emulator" I know (actually, it's supposed to be a text editor, but it has many features, including running a shell) with a feature close to "something being both a modifier and a regular key".


text:
Q: Using scrollTo without the scrolling animation? Is there a way to 'jump' to the top of the page with a scrolling animation when a button is pressed?
This question's solution doesn't work for me (there is a scrolling animation).
I've tried the following:
window.scrollTo(0, 0 ,{duration:0});
window.location.hash = '#siteTop';
window.scrollTo(0, 0);
window.location.href ='#'

But they all have animations. Can anyone help (no jquery pls)?

A: use this code :

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">

<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>

Scroll Down

This example demonstrates how to create a "scroll to top" button that becomes visible
  when the user starts to scroll the page.


text:
Q: Prism view available after navigate from I am using prism in a wpf application using the latest stable release of 6.2.0
I have setup prism to use the IRegionMemberLifetime interface on a view model and have set the KeepAlive property to return false. In the view model, when it is create I register to an IEventAggregator event using the following code.
EventAggregator.GetEvent<NewLayerSetEnabledEvent>().Subscribe(NewLayersetEnabledAction);

The issue that I am having is that after I have navigated from the view, the view model still exists and when I publish the event this other view is also being called. Is there a way to force the view to be disposed of by GC after it is navigated from or do I need to unsubscribe from the events when the OnNavigatedFrom event is called.

A: The important thing you have to always keep in mind about the Garbage Collector in the .Net CLR, is the fact that you (normally) don't know when exactly it runs. (You could, of course, force the Garbage Collector to run using the GC.Collect() method etc, but this is rather an exception and shouldn't be overused - see this srticle).
So keeping that in mind, you can never be sure, when your view will be GC'ed. Generally speaking, it could still be alive for some time and even survive till the application shut down (see Generation 2).
If you want to make sure that your closed view's view-model doesn't actively react to the events raised by the EventAggregator anymore, you have to unsubscribe from all events just after the view removal.


text:
Q: Cannot connect PowerBI Desktop and PowerBI WebApp with Google Analytics I am trying to connect PowerBI Desktop with Google Analytics.
I am getting this error message, below is the screenshot.

Similarly, if I try to connect to Google Analytics with PowerBI WebApp, then as well, I am getting the same issues.
I have following configurations:

*

*Google Chrome v72

*Microsoft Internet explorer v11

*Windows 7 as OS. (haha.. that's true)

*As per the error message; I have deleted all of my credentials, cleared cache, deleted all password, and only have one Google Account where I use Google Analytics.

I've also asked my colleagues, but they get the same error message on PowerBI Desktop and PowerBI WebApp.
Please suggest the solution.

A: Solved it. I restarted my computer and then it worked like a charm. :)


text:
Q: Exclude namespace from FxCop code analysis
Possible Duplicate:
StyleCop/FxCop 10 - How do you properly suppress a message only on a namespace level?
How do I suppress FxCop rule 'DoNotCatchGeneralExceptionTypes' with SupressMessage?

I have a namespace ABC.Schema which has some classes. Name of classes are using underscore. I am checking FxCop analysis. I want to suppress this rule for namespace level.
namespace ABC.Schema
{
...
}
I want to suppress FxCop message CA1707:IdentifiersShouldNotContainUnderscores.
Does anyone have idea about this.
Please give your view on this.


text:
Q: How to increase productivity with slow startup time in frameworks like Spring Boot and Hibernate? I am trying out Hibernate and noticed that the startup time is roughly 4500ms on my laptop.
Spring boot for example also takes ~7000ms to startup, if you have the most basic spring-JPA and web-MVC set up.
How are developers supposed to do prototyping or TDD in Java, if after every code change I have to wait five seconds?
How much faster do dynamic language start up?
For example, how long does a single persist statement in Python's SQLAlchemy take?
I understand that in real-world applications startup takes way longer, and updates or tests are performed remotely with a CI/CD server. But I'm still in the learning phase and for now I like to be able to see my output after minor code changes.

A: I think there is a misconception on your end. The main focus of TDD are unit tests. Of course, TDD is a great concept, but the point is: you want those quick feedback loops.
Thus you use it to write unit tests. Tests that work on a small, isolated unit. Tests that have zero dependencies on anything else but your compiled classes and JUnit/TestNG/... other test related frameworks.
You write a test (5, 10 lines of code); you write production code (probably not much more than that). Run, write new test, or fix production code ...
And then; when you are convinced that all your units do what they are supposed to do; then you start looking into writing "functional" or "integration" tests that require your whole stack to be up and running.


text:
Q: How to fetch all products in the cart after place order button in my custom module Step 1: I want to fetch all products in the cart and Show them with a form individually
Currently, I am fetching data using this code
<?php
namespace Softadroit\Prescription\Block;

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$cart = $objectManager->get('\Magento\Checkout\Model\Cart');

// retrieve quote items collection
$itemsCollection = $cart->getQuote()->getItemsCollection();

// get array of all items what can be display directly
$itemsVisible = $cart->getQuote()->getAllVisibleItems();

// retrieve quote items array
$items = $cart->getQuote()->getAllItems();

foreach($items as $item) {
    echo 'ID: '.$item->getProductId().'
';
    echo 'Name: '.$item->getName().'
';
    echo 'Sku: '.$item->getSku().'
';
    echo 'Quantity: '.$item->getQty().'
';
    echo 'Price: '.$item->getPrice().'
';
    echo "
";
}

And this is my prescription.phtml code, it shows me empty page in the frontend

<?php echo $items = $cart->getQuote()->getAllItems(); ?>

Step 2: How to display that page after placing an order (Before onepage/success)?
Actually I am new to Magento
Any help is really appreciated!

A: You need to get Order in this way :
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$sessionObj = $objectManager->get('\Magento\Checkout\Model\Type\Onepage');
$session = $sessionObj->getCheckout();
$order = $session->getLastRealOrder();

Now from the $order you need to get there items.
$orderItems = $order->getAllItems();

foreach($orderItems as $item) {
    echo 'ID: '.$item->getProductId().'
';
    echo 'Name: '.$item->getName().'
';
    echo 'Sku: '.$item->getSku().'
';
    echo 'Quantity: '.$item->getQty().'
';
    echo 'Price: '.$item->getPrice().'
';
    echo "
";
}

NOTE: do not use $objectManager, instade of that one include proper class in constructor and then use there object in standard magento way.

A:
Try below

$obj = \Magento\Framework\App\ObjectManager::getInstance();
$order = $obj->create('\Magento\Checkout\Model\Session')->getLastRealOrder();

$itemsVisible = $order->getAllVisibleItems();
$items = $order->getAllItems();
//other order data
$orderId=$order->getEntityId();
$incrementId = $order->getIncrementId();

You should not use the ObjectManager directly!


text:
Q: Insert null value to date field in access using vba Am trying to insert date from a table to another table using vba in access, But one of the date values from the table is blank. So while inserting the date to new table it shows Invalid use of null exception Run-time  error 94.

A: If writing DAO code to clear a Date field, I found that I had to use "Empty".  Null and "" won't work. So for field dtmDelivery (type Date), I had to use the following. strDelivery is just a string with the date in it.
Set rst = dbs.OpenRecordset("tblSomething", dbOpenDynaset)
If (strDelivery = "") Then
    rst!dtmDelivery = Empty
Else
    rst!dtmDelivery = strDelivery
End If

rst.Update

A: you can use the NZ() function to define a value that should be used instead of NULL. Internally a date is a float value where the number represents the days between 01.01.1900 and the date that should be stored. The part behind the decimal point represents hours/minutes (.25 for example is 6 AM). So you can use the NZ() funtion to replace NULL bei 0 (what would be interpreted as 01.01.1900).
Another solution would be to configure the target table in a way that it allows NULL values. You can do this easily in the design view of the table.

A: I think i figure it out , declare the variable to string. Then check whether value from the table is empty, then assign null to it.Other wise assign the value from the table.
for example
   Dim newdate As String

Check whether the fetched values is null or not
   If IsNull(rst![value]) Then
            newdate = "null"
   Else
           newdate = rst![value]
   End If

A: I encountered this problem and solved it this way.
SQL = "update mytable set mydatefield = '" & txtdate & "'"

On the txtdate on your form, put a date format to ensure date is either a real date or just blank.


text:
Q: Two 12v batteries in parallel 7ah and 20ah I have two 12v batteries, 7ah and 20ah. Can they be connected in parallel without damaging the 7ah battery? They will be charged separately.

A: If you simply parallel connect the two batteries for discharging, then the combined Ah capacities do not add. As current is drawn from the paralleled batteries, the voltage of the 7Ah battery will typically drop more quickly than the 20 Ah battery. This will typically cause the higher voltage 20 Ah battery to begin charging the 7 Ah battery. Whichever way the current draw occurs, the action of one battery charging another battery wastes energy in the form of heat.
Since part of the energy of one battery is being used to charge the other battery, the combined capacity will likely be more than 7 Ah but less than 27 Ah. The exact answer is not known without an extensive analysis of the load characteristics and the specifications of the batteries.
By adding some electronics to the system, it may be possible to realize an overall higher Ah capacity compared to simply paralleling the batteries.

A: Yes they can be connected in parallel.
Different Ah of batteries means they have different ampere hours, thus when used alone a 7Ah battery will discharge sooner than a 20Ah battery when connected to the same load.
When both are connected in parallel they become one 27Ah battery of 12V.
They can be charged from the same source of ~14V simultaneously.
If voltages were different then the higher voltage battery would act as a source while the lower voltage battery would act as a load which is not recommended.

A: As a general rule I never put batteries (of same nominal voltage of course) in parallel: they might have different State of Charge (SoC), different internal resistance, etc. and the situation will turn out into a battery charging the other, rather than having the current all going where it is required to be (... your load).
To replace batteries on the spot and to protect against reverse polarity, I always use a diode in series, possibly Schottky to reduce voltage drop and heating.

simulate this circuit – Schematic created using CircuitLab
D1 and D2 may be different components, or the two legs of a common-cathode 2-diode component (see below).

*

*With a normal PN diode and 10A flowing, forward voltage drop of 0.9-1.0 V is common, with 10W dissipated across the diode (!), and 1V less on your load.

*Schottky diodes have a much lower voltage drop (about 50%): 1 leg of a common-cathode 2-diode MBR2045 at 10 A has a 0.58V voltage drop; with the 2 legs in parallel (5A each) and some self-heating that brings temperature around 50-60°C, 0.45V can be achieved => 4.5W. Vishay VS-48CTQ060S-M3 can reach 0.37-0.38V, thus 3.8W!

A connector suitable for current rating is always a good idea


text:
Q: Error while applying custom type in puppet I am facing below error while applying custom type.
Error: /Stage[main]/Main/login[new]: Could not evaluate: No ability to determine if login exist`s

Login is the custom type.
The path where file is placed is
/etc/puppet/modules/demo/lib/puppet/type

Can anyone help with the solution?

A: puppet can't find your file.  Maybe it isn't in the module path, or the permissions are wrong


text:
Q: Lisp: Elegant way to strip trailing nil's from a list? (Review) I want to write a function that removes trailing nil's from a list. I first tried to write it elegantly with recursion, but ended up like this:
(defun strip-tail (lst)
  (let ((last-item-pos (position-if-not #'null lst :from-end t)))
    (if last-item-pos
      (subseq lst 0 (1+ last-item-pos)))))

; Test cases.
(assert (eq nil (strip-tail nil)))
(assert (eq nil (strip-tail '(nil))))
(assert (equal '(a b) (strip-tail '(a b nil nil))))
(assert (equal '(a nil b) (strip-tail '(a nil b nil))))
(assert (equal '(a b) (strip-tail '(a b))))

It's arguably clear, but I'm not convinced. Is there a more lispy way to do it?

A: Well, a version would be:

*

*reverse the list

*remove leading nils

*reverse the list

The code:
(defun list-right-trim (list &optional item)
  (setf list (reverse list))
  (loop for e in list while (eq item e) do (pop list))
  (reverse list))

Here is another variant:

*

*iterate over the list and note the position of the first nil which is only followed by nils

*return the sub-sequence

the code:
(defun list-right-trim (list &aux (p nil))
  (loop for i from 0 and e in list
    when (and (null p) (null e))
    do (setf p i)
    else when (and p e) do (setf p nil))
  (if p (subseq list 0 p) list))

A: (defun strip-tail (ls)
    (labels ((strip-car (l)
                  (cond ((null l)       nil)
                        ((null (car l)) (strip-car (cdr l)))
                        (t              l))))
        (reverse (strip-car (reverse ls)))))

Sample run (against your test cases):
[1]> (assert (eq nil (strip-tail nil)))
NIL
[2]> (assert (eq nil (strip-tail '(nil)))) ;'
NIL
[3]> (assert (equal '(a b) (strip-tail '(a b nil nil))))
NIL
[4]> (assert (equal '(a nil b) (strip-tail '(a nil b nil))))
NIL
[5]> (assert (equal '(a b) (strip-tail '(a b))))
NIL
[6]>

A: How about this?
(defun strip-tail (lst)
  (if lst
    (let ((lst (cons (car lst) (strip-tail (cdr lst)))))
      (if (not (equal '(nil) lst)) lst))))

...wonder how to make it tail-recursive though, this version would exhaust the stack for large lists.

A: Here's what I came up with, assuming you don't mind this being destructive:
(defvar foo (list 'a 'b 'c nil 'd 'e 'nil 'nil 'f nil nil))

(defun get-last-non-nil (list &optional last-seen)
  (if list
      (if (car list)
          (get-last-non-nil (cdr list) list)
          (get-last-non-nil (cdr list) last-seen))
      last-seen))

(defun strip-tail (list)
  (let ((end (get-last-non-nil list)))
    (if (consp end)
        (when (car end) (setf (cdr end) nil) list))))

(strip-tail foo) -> (A B C NIL D E NIL NIL F)

A: I tried using recursion but it doesn't work on GNU CL:
(defun strip(lst)
    (if (null (last lst))
        (strip (butlast lst))
     lst))

the idea is:

*

*test if the last list element is nil, if so make a recursive call with
 the last element removed (butlast)

*then return the list itself

A: Well, this is not really an answer, but I thought I'd put this here as well so it has better visibility.
In your original implementation, do you think non-list items should be handled?
* (strip-tail "abcde")

"abcde"
* (strip-tail 42)

debugger invoked on a TYPE-ERROR in thread #<THREAD "initial thread" {A69E781}>:
  The value 42 is not of type SEQUENCE.


text:
Q: Member function with multi-level list in Common Lisp I'm trying to understand how it works member function with list and list of lists.
Here an example.
(member '(A 6) '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'second)

I want to check with the member function if the second argument of the list '(A 6) is member of the second list in input.
The answer should be
true

but I'm doing something wrong, because Common Lisp reply:
 Error: Cannot coerce (A 6) to type STRING.

So how can I take the second argument from the first list?
Thank you for the help.

A: What you are missing is that the :key argument is not applied to the first argument of member.
Another thing is that second will return the number, not the symbol.
Thus:
(member 'A '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'first)
==> ((A 7) (B 6) (E 6) (D 5))
(member 'C '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'first)
==> NIL
(member 'E '((A 7) (B 6) (E 6) (D 5)) :test #'string-equal :key #'first)
==> ((E 6) (D 5))

Note that the return value is the tail, not the matched list element.
This is to allow the use of member as a predicate, i.e., to distinguish between finding nil and finding nothing:
(member nil '(1 2 nil 3))
==> (NIL 3)
(find nil '(1 2 nil 3))
==> NIL
(find t '(1 2 nil 3))
==> NIL


text:
Q: Using a While for loop for a simulated coin flip in R I want to toss a coin and want it to stop when I get two consecutive heads in a row.
Here is my code
coin<-0:1
sample(coin, size = 1, replace = TRUE)

flip<-function(){
  coin<-0:1
  toss<-sample(coin, size = 1, replace = TRUE)
}
flip()

heads=1
tosses<-c()
while (heads=="?") {
  tosses=c(tosses, flip())
}

I have my flip function made. I am not sure if I need use a if else statement or count the flips to check for back to back 1's after each coin flip? I am using a while for loop

A: With minimum modification of your current code:
flip<-function(){
  coin<-0:1
  sample(coin, size = 1, replace = TRUE)
}

tosses<-c()
while (length(tosses) < 2 | !all(tail(tosses, 2) == 1)) {
  tosses=c(tosses, flip())
}

A: Similar to sindri's answer, but removing the need to check length at each iteration
while(sum(tail(tosses, 2)) != 2){
  tosses <- c(tosses, flip())
}

A: Perhaps you can try repeat
repeat {
  tosses <- c(tosses, flip())
  if (mean(tail(tosses, 2)) == 1 & length(tosses) > 1) break
}


text:
Q: How to set child's contenteditable property without affecting the parent element? I came across this weird issue with contenteditable DIVs, I have a parent div whose contenteditable property is set to true, And in a button click event I'm trying to append a div with contenteditable='false' to this parent div. The problem is that when i just do that, the parent element become uneditable. (There is no problem with the child - which is of course, uneditable). I searched the web and tried to figure this problem out, but still have no clue what the problem actually is.
This is my code:
Html:

jQuery (on button click):
$("#parent").append
(
    "
" +
        "" +
    "
"
);

When the above jQuery code is executed, the #parent div became uneditable, like (contenteditable = false). Why is that? Is there something wrong with this code? Is there any other way to prevent the child from affecting the parent?
I read many many articles that says that this is the correct way of making a child of contenteditable div uneditable, and i know this even without reading them. I have a lot of experience dealing with contenteditable elements, and it is the first time I'm facing this problem.
(This code is currently tested only on Firefox, Since it is the main browser I'm targeting, But there is no reason that this code will behave differently on other browsers).
Thanks a lot for reading this question, Any helpful ideas will be appreciated and upvoted. Thank you.

A: $("#parent > div").prop("contenteditable", "false");

Use this for select child div


text:
Q: how to increment the hour of Date().toLocaleTimeString().slice, every second im trying to figure out how to increment Date().toLocaleTimeString().slice by 1 for each second. in order for my question to make more sense, i need to show you my code:
heres the time in state:
class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            currentTime: new Date().toLocaleTimeString()
        };
    }
    componentDidMount() {
      setInterval(() => {
        this.setState({
          currentTime: new Date().toLocaleTimeString()
        });
      }, 1000);
    }

the method newOrder(timeAsProp) converts the time from '12:00:00', into '12'.
newOrder(timeAsProp) {
    const hour = timeAsProp.slice(0, 2);

the method newOrder(timeAsProp) then assigns a new image order for each hour like this:
(basically, i would like to have the 'hour' increment by 1, each second, so that i can see a new image order every second, instead of every hour (for testing purposes))
 newOrder(timeAsProp) {
    const hour = timeAsProp.slice(0, 2);
    let returnValue = [];
    const yud = <Image key="yud" source={require('./img/yud.png')} style={Style.image} />;
    const hey1 = <Image key="hey1" source={require('./img/hey1.png')} style={Style.image} />;
    const vav = <Image key="vav" source={require('./img/vav.png')} style={Style.image} />;
    const hey2 = <Image key="hey2" source={require('./img/hey2.png')} style={Style.image} />;

    if (hour === '00' || hour === '12') {
       returnValue = [
        yud, hey1, vav, hey2
        ];
    }
    if (hour === '01' || hour === '13') {
        returnValue = [
        yud, hey1, hey2, vav
        ];
    }

for testing purposes, i would like to increment
 "hour", each second by 1, so that i can see the images change every second, instead of every hour, to see everything works properly.
im new to coding, and tried seeing if any other questions adressed this issue first, but could not find, so please forgive me if this has already been answered.
 i already tried this: (but its not helping)
currentTime: new Date().toLocaleTimeString() + 1

im sure it must be a simple solution but i cant figure it out. im guessing if i can save: "const hour" in state, and then have that update every second that might work... but again as i said, im new to all this and can use all the help i can get.   thnks!
sb


text:
Q: PowerBI - Convert text to time I am working with a set of data called Response time and it is currently in the format of hh:mm:ss but the field is a text field in Power BI Power Query Editor.  I am trying to convert it to straight time so I can get an average from it but I keep getting errors due to many of the times being higher than 24 hours. I have results of like 37:50:00 and 40:00:00 and those error out while times like 22:24:00 work fine but it is converted to the actual time on a clock.
How do I keep the design of the data but get it into a Time data type so that I can pull an average?


text:
Q: Create RStudio connection that uses environment variables as defaults I am trying to add connection snippet to the bigrquery package based on this documentation:
https://db.rstudio.com/advanced/snippets/
I would like to default project name to a env var like this:
library(bigrquery)
con <-  dbConnect(
  bigquery(),
  project = "${1:Project=Sys.getenv('BIGQUERY_PROJECT')}"
)

Unfortunately this does not work, as Sys.getenv('BIGQUERY_PROJECT') is not evaluated.
UPDATE
e.g. for @Jozef's example I get the following code generated:
library(bigrquery)
con <-  dbConnect(
  bigquery(),
  project = "`r eval({Sys.getenv('BIGQUERY_PROJECT'))`"
)

UPDDATE 2
This sort of works, but does not look good:
library(bigrquery)
con <-  dbConnect(
  bigquery(),
  project = paste0("${1:Project=", Sys.getenv("BIGQUERY_PROJECT"), "}")
)

A: Not sure if this is exactly what you want, but you can use r eval({ }) in back-ticks if I understand your purpose correctly.
Example with the 'USER' environment variable:
snippet envvar
    library(bigrquery)
    con <-  dbConnect(
        bigquery(),
        project = "${1:Project=`r eval({Sys.getenv('USER')})`}"
    )

Will do this for my user (jozef) when triggered:

Also, I wrote a post with more examples of advanced snippet use.


text:
Q: To reach out: on Monica, the Lavender community, and the future of the Stack Exchange network Over the past weeks, the uproar has been vast, spanning the new Code of Conduct, Stack Exchange's conduct over the years, and more. Gallons of internet ink have been spilled by everyone involved, including myself.
If you don't know me, I'm heather. I am a moderator on Quantum Computing Stack Exchange, and I'm a member of the LGBTQ+ community, or the Lavender community. On October 6th, I posted a letter I had co-written addressing Stack Exchange about the current situation and how it was affecting the Lavender community.
In the Lavender letter, I wrote

We are human, we are hurt, we are tired

I am not the only one who is hurt and tired. I am spilling ink today to talk about something different, to extend an olive branch, and to reach out under the belief that we are all human here.
Monica Cellio is a highly respected member of this network. I talked with her last night for a long time (with the help of Journeyman Geek as mediator), and we came to some resolution about our situation. I speak as a member of the LGBTQ+ community when I say the following:

*

*It is clear to me personally that Monica meant no harm by her avoidance of nonbinary pronouns (I say as someone who uses they/them among other pronouns). I believe that while there were problems with what she said, she meant all the best, and that is a starting point for a conversation, not an ending point for a long and productive relationship with Stack Exchange.

*It is clear to me that Monica was in the wrong place at the wrong time, and that Stack Exchange took these unfortunate circumstances and used Monica as a scapegoat for something that had been festering across the network for a while, and did so in a way that is, quite frankly, unacceptable to me and to many others.

*It is clear to me that while there are problems in how this site handles LGBTQ+ issues (and, to be honest, issues surrounding tolerance and kindness in general), these issues do not stem from Monica, and it is beyond time that Monica gets a sincere apology and closure. Then we can all move forward with the understanding that we are humans talking across our screens in an attempt to make this site a better and more comfortable place to learn and help others.

I say that Monica and I have come to a resolution, and I say this because we talked. We talked understanding that we come from different backgrounds, with different perspectives. We talked understanding that we each carry different baggage with us. We talked knowing that we were there to understand each other, and that there would be more talking after this conversation, and the next and the next.
I post this today in an attempt to reach out a hand, and to ask all of you to do so as well, to ask Stack Exchange to do so as well. Talk to those around you remembering the faces behind the screens. I believe many things about the current situation, but this post isn't about that. We need to start healing. There will be much more to say, of course: about the Code of Conduct, about how Stack Exchange can regain our trust, about how the LGBT+ community has been marginalized on Stack Exchange. But this seems to me like a pretty good place to start.
Monica, I am sorry for the hurt you have experienced these past few weeks. I cannot claim to understand what you have been going through, but I hope that you can find peace with Stack Exchange. I hope that they can remember that behind the screens and the web of legal concerns lies a person affected deeply by their words, and reach out.

A: I think this is great that a trusted user from the lavender community was able to reach out to Monica and that they were able to connect and have a productive conversation. I think it is great that they both put themselves out there to allow this to happen. I want to thank them and JourneymanGeek for helping with this process and sharing the results. I think it shows that there is a chance for Monica and the lavender community to resolve their issues.
I am not a member of the lavender community, but I saw how Monica's actions hurt some users. Monica in the past has admitted her actions have hurt users (or more accurately caused them to feel hurt). There is no question in my mind that she did not intended to hurt anyone, but none the less, injury was caused. I hope that this conversation between a member of the lavender community and Monica will be the first step to Monica reaching out with an apology to the lavender community and the users she has hurt. If I saw such an olive branch, I could fully support efforts to reinstate Monica.
Just because I cannot fully support the reinstatement of Monica until I see an apology, does not mean that I don't support her in other aspects. I have seen how some users actions have hurt Monica. Monica deserves apologies from those users and from those of us that did not stand up and defend her. I am fully supportive of any actions that would help resolve those issues, regardless of if Monica apologizes first. I am also aware that the atrocious behavior of SE has hurt Monica (as well as the lavender community, moderators and users). These also need to be corrected and I support efforts to correct them regardless of if Monica apologizes.
Given the hurt that SE has caused Monica, maybe it is unfair to hope that she can rise above it and apologize to the users she has hurt. I  believe Monica is one of the best among us and hope that she can step back and see how she can move this process forward. This conversation  between her and Heather makes me confident that we can resolve the issues between Monica and the users she hurt and turn our full attention and support on how SE has hurt Monica and how SE's actions have empowered some users to act in ways designed to hurt lavender users.
I wish SE was leading the way in helping resolves these rifts, but instead they seem to be actively fanning the flames. As a user lead community, it encourages me to see users stepping forward and trying to fix the problems.

A: I'm just a random onlooker, but I'm really happy to see this development, and I'd like to thank @heather for approaching Monica and having this discussion, Monica for being open to it, and Journeyman Geek for mediating and (if I'm not mistaken) actually suggesting this approach. This is one of those awesome things where everyone who participates (in good faith) is a winner. Notably, the Corporation has declined to participate.
I only have one question (stemming from my ignorance): was there a direct conflict or rift between heather and Monica in the Teachers' Lounge that was related to the start of the whole debacle? If that's the case, it makes this reconciliation even more meaningful!

A: Thank you for this heartfelt, encouraging message, and for being willing to have the conversation that preceded it instead of just walking away.
We need more of that at Stack Exchange.
It's too easy to forget that, behind the gravatar and user name, there is an actual human being.  We have text-only interactions, sometimes limited to messages of a few hundred characters at a time, and we draw conclusions, think we know the other, when we don't.  And then we filter all further interactions through the filter of what we "know", regardless of accuracy, and spirals happen.
That happens everywhere online (as we've known for decades).  Now throw into the mix an environment where we discuss important issues that are deeply personal to those involved.  What could go wrong with that, right?  Currently it's pronouns, but it's also been religion (there's a lot of hostility to religion on the network), politics, national identity... topics that are challenging to discuss regardless of how respectful everyone involved is being.  The current situation arose from a conversation in Teachers' Lounge that was by and large very respectful -- but involved deeply-held feelings that were in conflict.
If we can't even manage respectful private conversations without over-reactions, then how are we to deal with disrespectful public actions on the network?  We've seen far too much trolling, far too many attacks, far too much pain.  Our collective inability to recognize the humanity in our fellow moderators has emboldened those who cannot see the humanity in fellow users.  It has added hurt, in particular, to the hurt already being felt by members of the Lavender community.
Heather, I regret that we had these failures of communication in Teachers' Lounge.  It wasn't my intention to offend, and yet some were offended.  I assume that those who offended me with their words also didn't intend to offend, and perhaps they will address that just as you and I did.  I believe we both are now doing better at listening and weighing the impact of our words, and I hope others will join us in trying to rise above the quick reaction, will try harder to see the human being behind the screen.
The network writ large, and the 600 or so moderators who care for it, are global, diverse communities.  Diversity means sometimes encountering perspectives we disagree with, that we might even find deeply wrong or heretical.  I experience this on our religion sites, and yet we manage to work together there -- by being respectful in how we present our perspectives, by being ready to listen, and by knowing that we're still all here for the same reason.  If any of us were to be able to shut down the perspectives we disagree with, our communities would be poorer for it.
But some conversations are too painful, too personal, and we need to be able to say "let's not do this".  We need to be able to step out instead of escalating, and we need to be able to communicate clearly that we're feeling hurt without it being seen as an attack.  We need more "I feel" language and less "you did" language.  This requires effort and will on both sides of the interaction.  Communities of people with good intentions can solve these problems.  We might need help, like mediators.  We definitely need to presume good intent.  But we can do it if we want to.
And we should want to.  The alternative, where more and more people get hurt more and more badly, is too awful to contemplate.

A:
I post this today in an attempt to reach out a hand, and to ask all of you to do so as well, to ask Stack Exchange to do so as well.

Just picking this sentence to stress how important it is for the party being reached out to to play its part. The community seems to have been discussing the situation for quite some time now, but it is very much a one-sided discussion in which the company seems rather silent. Most have been a bit more blunt about it, possibly because they think SE should be reaching out to the community, we shouldn't have to beg for it.
That said, I think most if not all in the community stand behind your message, and
let's hope the company will dignify it with a response.

A: A wonderful piece of work!
I think, in the end, it all boils down to "assume good faith/intent".
Which we basically don't have any more in the relationship between the community and the company. On both sides. Years of frustration, surprising actions leading to a loss of trust.
Your input here, and the answers coming back show us the way.
I hope the other side is listening, while keeping in mind that German proverb" to wait and to hope makes many a fool" unfortunately...

A: I go by 'they', and I speak for myself, not on behalf of all queer folks.
What I understand of Monica's position—based previously on public TL leaks and now on what heather has relayed—is a little baffling to me.
Nevertheless, it seems that SE.inc have foolishly chosen Monica as a scapegoat for much larger issues—and now, having put their corporate foot in their corporate mouth by suddenly bypassing established procedures and applying a potential future rule ex post facto, SE.inc do not appear to appreciate the law of holes.
In large part because of SE.inc's obstinacy about Monica, the queer members of the community whom SE.inc claimed to be trying to support are now being framed as an authoritarian minority abusing illegitimate power to ram a new CoC down everyone else's throats and put compelled speech in their mouths.  Obviously SE.inc are not doing the harassment themselves, but it is not cool that by stonewalling Monica, SE.inc have exacerbated the harassment in the name of supporting us.
I think the first step for SE.inc to restore legitimacy—and to seriously address larger cultural issues in good faith—is to reinstate Monica.
(We also have some other issues of legitimacy in SE.inc's governance too.)

A: Thanks for this. It's awesome that people can put down the vitriol once in a while and talk.
Do you have a stance on restoration of her diamond? It's not clear in your post what action you feel is best in that regard.

*

*Do you feel that her diamond should be restored promptly?

*Do you feel that this needs more discussion to determine under what conditions her diamond could be restored?

*Are you opposed to restoring her diamond, but in favor of an amicable (not accusatory, not condemnatory, etc.) social parting from moderatorship?


text:
Q: Bibliography using biber not appearing I'm trying to create a bibliography using TeXworks and biber on Windows 10. I keep getting errors and I just do not understand. I can work with latex but have no experience with bibliographies so the problem can absolutely be a stupid error on my part.
This is everything in my tex file:
\documentclass{scrreprt}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[british]{babel}
\usepackage[autostyle]{csquotes}
\usepackage[natbib,hyperref,sorting=none]{biblatex}
\addbibresource{quellen.bib}
\usepackage{hyperref}
\begin{document}
nothing
\nocite{*}

\printbibliography
\end{document}

This is everything in quellen.bib:
@book{Horn1985,
   author = {Roger A. Horn and Charles R. Johnson},
   doi = {10.1017/CBO9780511810817},
   isbn = {9780521386326},
   month = {12},
   note = {Schur decomp},
   pages = {79-80},
   publisher = {Cambridge University Press},
   title = {Matrix Analysis},
   year = {1985},
}

Running with biber I have seen:
ERROR - main.bcf is malformed, last biblatex run probably failed. Deleted main.bbl
But currently I don't get any errors but there simply is no bibliography.
What can I do? What information have I forgotten to provide?


text:
Q: hexlify and unhexlify functions in C Please help... I'm trying to learn C types conversion.
This code works well only converting some hex chars as 1, 2, 3. For others, also changing string or reduce string length, the conversion fails...
I'll put the code below... Anyone can explain me where the code is wrong?
Thanks in advance!
#include <stdio.h>

int a2v(char c)
{
    if ((c >= '0') && (c <= '9'))
    {
        return c - '0';
    }
    if ((c >= 'a') && (c <= 'f'))
    {
        return c - 'a' + 10;
    }
    else return 0;
}

char v2a(int c)
{
    const char hex[] = "0123456789abcdef";
    return hex[c];
}

char *unhexlify(char *hstr)
{
    char *bstr = malloc((strlen(hstr) / 2) + 1);
    char *pbstr = bstr;
    for (int i = 0; i < strlen(hstr); i += 2)
    {
        *pbstr++ = (a2v(hstr[i]) << 4) + a2v(hstr[i + 1]);
    }
    *pbstr++ = '\0';
    return bstr;
}

char *hexlify(char *bstr)
{
    char *hstr = malloc((strlen(bstr) * 2) + 1);
    char *phstr = hstr;
    for (int i = 0; i < strlen(bstr); i++)
    {
        *phstr++ = v2a((bstr[i] >> 4) & 0xFF);
        *phstr++ = v2a((bstr[i]) & 0xFF);
    }
    *phstr++ = '\0';
    return hstr;
}

int main()
{
    char *title = "... Trying to convert hex into binary string and back again ?! ...";
    printf("%s\n\n", title);

    char *input = "0123456789abcdef\0";
    printf("Original: %s (%d)\n\n", input, (int)strlen(input));

    char *input_bin = unhexlify(input);
    printf("Bin: %s (%d)\n\n", input_bin, (int)strlen(input_bin));

    char *input_hex = hexlify(input_bin);
    printf("Hex: %s (%d)\n\n", input_hex, (int)strlen(input_hex));

    system("pause");
    return 0;
}

A: Updated Version of @Kevin's answer:
int a2v(char c) {
    if ((c >= '0') && (c <= '9')) return c - '0';
    if ((c >= 'a') && (c <= 'f')) return c - 'a' + 10;
    if ((c >= 'A') && (c <= 'F')) return c - 'A' + 10;
    else return 0;
}

char v2a(int c) {
    const char hex[] = "0123456789abcdef";
    return hex[c];
}

char *hexlify(char *bstr) {
    char *hstr=malloc((strlen(bstr)*2)+1);
    bzero(hstr,(strlen(bstr)*2)+1);
    char *phstr=hstr;
    for(int i=0; i<strlen(bstr);i++) {
        *phstr++ =v2a((bstr[i]>>4)&0x0F);
        *phstr++ =v2a((bstr[i])&0x0F);
    }
    *phstr++ ='\0';
    return hstr;
}
char *hexlifyn(char *bstr, uint str_len) {
    char *hstr=malloc((str_len*2)+1);
    bzero(hstr,(str_len*2)+1);
    char *phstr=hstr;
    for(int i=0; i<str_len;i++) {
        *phstr++ =v2a((bstr[i]>>4)&0x0F);
        *phstr++ =v2a((bstr[i])&0x0F);
    }
    *phstr++ ='\0';
    return hstr;
}

char *unhexlify(char *hstr) {
    char *bstr=malloc((strlen(hstr)/2)+1);
    bzero(bstr,(strlen(hstr)/2)+1);
    char *pbstr=bstr;
    for(int i=0;i<strlen(hstr); i += 2)
        *pbstr++ =(a2v(hstr[i])<<4)+a2v(hstr[i+1]);
    *pbstr++ ='\0';
    return bstr;
}
char *unhexlifyn(char *hstr, uint str_len) {
    char *bstr=malloc((str_len/2)+1);
    bzero(bstr,(str_len/2)+1);
    char *pbstr=bstr;
    for(int i=0;i<str_len; i += 2)
        *pbstr++ =(a2v(hstr[i])<<4)+a2v(hstr[i+1]);
    *pbstr++ ='\0';
    return bstr;
}

A: Thank you!
Based on chux's answer, the mistake was into hexlify function:
*phstr++ = v2a((bstr[i] >> 4) & 0x0F);
*phstr++ = v2a((bstr[i]) & 0x0F);

Masks was wrong! I will study much more!
PS = I added some code in order to handle NULL binary character (0), that truncates string.
#include <stdio.h>

int a2v(char c)
{
    if ((c >= '0') && (c <= '9'))
    {
        return c - '0';
    }
    if ((c >= 'a') && (c <= 'f'))
    {
        return c - 'a' + 10;
    }
    else return 0;
}

char v2a(int c)
{
    const char hex[] = "0123456789abcdef";
    return hex[c];
}

char *unhexlify(char *hstr)
{
    char *bstr = malloc((strlen(hstr) / 2) + 1);
    char *pbstr = bstr;
    for (int i = 0; i < strlen(hstr); i += 2)
    {
        char c = (a2v(hstr[i]) << 4) + a2v(hstr[i + 1]);
        if (c == 0) {
            *pbstr++ = -128;
        } else {
            *pbstr++ = c;
        }
    }
    *pbstr++ = '\0';
    return bstr;
}

char *hexlify(char *bstr)
{
    char *hstr = malloc((strlen(bstr) * 2) + 1);
    char *phstr = hstr;
    for (int i = 0; i < strlen(bstr); i++)
    {
        if (bstr[i] == -128)
        {
            *phstr++ = '0';
            *phstr++ = '0';
        } else {
            *phstr++ = v2a((bstr[i] >> 4) & 0x0F);
            *phstr++ = v2a((bstr[i]) & 0x0F);
        }
    }
    *phstr++ = '\0';
    return hstr;
}

int main()
{
    printf("... Trying to convert hex into binary string and back again ?! ...\n\n");

    char *input = "070790ca8fd8058b455f13dd698a4eed028cb0efc13907f681604676d69e57affe299aae7c91fd000000005271266004e4cd7f52548153f8f78b76840aeca16e91bac0ebeb4d74ff3ce3c901\0";

    char *input_bin = unhexlify(input);
    char *input_hex = hexlify(input_bin);

    printf("Input: %s (%d)\n\n", input, strlen(input));
    printf("Output: %s (%d)\n\n", input_hex, strlen(input_hex));

    if (strcmp(input, input_hex) == 0)
    {
        printf("Input and output are EQUALS !\n\n");
    } else {
        printf("Input and output are NOT EQUALS !\n\n");
    }

    system("pause");
    return 0;
}

Regards, Kevin


text:
Q: Gerrit sens timestamp via REST API with timezone I tried to query our changes by Gerrit querybox. I need to add the timezone information and can get my result like this:
after:"2020-05-08 22:30:55 +0400" before:"2020-05-08 22:40:33 +0400"
The timezone setting +0400 is required and the " is also required since the timezone information. Now I need use REST API to get the json result by following URL:
http://GERRIT:8888/a/changes/?q=after:"2020-05-08 22:30:55 +0400" before:"2020-05-08 22:40:33 +0400"
but I get an http ERR_INVALID_RESPONSE
Could someone help me check this?

A: You need to escape the quotes and to change the following characters:
space => +
+     => %2B

So, you need to change:
after:"2020-05-08 22:30:55 +0400" before:"2020-05-08 22:40:33 +0400"

To:
after:\"2020-05-08+22:30:55+%2B0400\"+before:\"2020-05-08+22:40:33+%2B0400\"

I was able to get the info executing:
curl -s --user USER:PASS --request GET "https://$GERRIT-SERVER/a/changes/?q=after:\"2020-05-08+22:30:55+%2B0400\"+before:\"2020-05-08+22:40:33+%2B0400\""


text:
Q: Revenue Forecast Database Design I am currently trying to design an Access database that will house financial data containing forecasting, actuals and prior forecast data.
The current format of the Excel "database" is
Customer Name | Contract Number | Region | Product | Fee Type | Commit Type
| Jan 19 Plan - Dec 2023 Plan | Jan 19 Prior Forecast to Dec 2023 Prior
Forecast | Jan 19 Forecast - Dec 2023 Forecast

Where Jan 19 Plan - Dec 2023 Plan is a set of 59 columns, each month with it's own column, and no column in the entire "database" is unique. And contract numbers will have N/A's or blanks etc. This is my initial design
I'd love any feedback or modifications anyone can provide


text:
Q: How can I convert a class name into the equivalent in JNI in Java Given an object obj from a Java class called MyExample (in package a.b.c) and then doing the following:
System.out.println(obj.getClass().getName());

It will print the string:
a.b.c.MyExample

Now, I would like to convert this into the equivalent in JNI:
La/b/c/MyExample;

What is the method that I should call to get to this result?

A: I think that you won't have a simple, straight forward way of doing so :( At least I am not aware of one.
You can follow instruction on how native signatures are created and follow the path (the other way round):
https://docs.oracle.com/javase/8/docs/technotes/guides/jni/spec/design.html#resolving_native_method_names
You can also take a look at how javap tool does that (note that javap can provide you with signatures).
For class:
package a.b.c;

public class Simple {
  public static void main(String [] arg) {
    Simple s = new Simple();
    System.out.println(s.getClass().toString());
  }

  public void callOnMe(Simple s) {

  }
}

you will get
> javap -s -cp . a.b.c.Simple
Compiled from "Simple.java"
public class a.b.c.Simple {
  public a.b.c.Simple();
    descriptor: ()V

  public static void main(java.lang.String[]);
    descriptor: ([Ljava/lang/String;)V

  public void callOnMe(a.b.c.Simple);
    descriptor: (La/b/c/Simple;)V
}

However, if you take a closer look at javap itself:
https://github.com/openjdk/jdk
and then inside
./jdk.jdeps/share/classes/com/sun/tools/javap/ClassWriter.java

you will note that there is no magic there, just bare bone parsing.
Note
In case somebody has a solution in a form SomeClass.getMangledName() I'd love to learn it as well :)


text:
Q: Set Vue JS select option from two values I have a Nuxt JS / Vue JS application with an address finder that I'm building using getaddress.io
I have a <select> element with a load of counties, fetched from the data object. When a user types in a postcode, it should set the county <select> with a matching county from the API.
However, not all counties are listed or match within my code, so I need to check if what's fetched from the API matches a particular field, and if not, utilise the district key.
Here's my JS method that runs when selecting an address after addresses have been found:
/**
 * Pick address
 */
addressPickerSelection: function addressPickerSelection(addressKey) {
  const cleanedPostcode = this.formData.AppPostCode.toUpperCase()

  var addressRaw = this.address.addressList[addressKey]
  var cleanAddress = {
    house: (addressRaw['building_number'] != '') ? addressRaw['building_number'] : (addressRaw['building_number'] === '' && addressRaw['line_1']) ? addressRaw['line_1'] : '',
    street: (addressRaw['thoroughfare'] != '') ? addressRaw['thoroughfare'] : (addressRaw['thoroughfare'] === '' && addressRaw['line_1']) ? addressRaw['line_1'] : '',
    town: (addressRaw['town_or_city'] != '') ? addressRaw['town_or_city'] : '',
    county: addressRaw['county']
  }

  this.formData.AppPreviousPostCode = (cleanedPostcode != '') ? cleanedPostcode.replace(/ /g,'') : ''
  this.formData.EmpPostCode = (cleanedPostcode != '') ? cleanedPostcode.replace(/ /g,'') : ''

  this.formData.AppHouseNumber = cleanAddress['house']
  this.formData.AppStreet = cleanAddress['street']
  this.formData.AppTown = cleanAddress['town']
  this.formData.AppCounty = cleanAddress['county']

  this.formData.EmpAddress = cleanAddress['house']
  this.formData.EmpAddress2 = cleanAddress['street']
  this.formData.EmpTown = cleanAddress['town']
  this.formData.EmpCounty = cleanAddress['county']

  if (addressRaw['district'] != '') {
    var countySelectValue = this.formData.AppCounty
    this.formData.AppCounty = addressRaw['district']
    if (this.formData.AppCounty == '') {
      this.formData.AppCounty = countySelectValue
    }
    countySelectValue = ''
  }

  this.address.addressSelected = true
}

cleanAddress['county'] may not always match an item from my array of counties, whereas addressRaw['district'] might, so in the case of cleanAddress['county'] not being found, or matching, it should utilise the district.
For example:

*

*I type a UK postcode in

*I select an address, and "Mid Glamorgan" doesn't exist in my array of counties, it should utilise the district.

This is the part of the code that I'd like to work, but it doesn't seem to be working:
if (addressRaw['district'] != '') {
    var countySelectValue = this.formData.AppCounty
    this.formData.AppCounty = addressRaw['district']
    if (this.formData.AppCounty == '') {
      this.formData.AppCounty = countySelectValue
    }
    countySelectValue = ''
  }

This is a common issue, where someone needs to set a select item to be one of two possible values if one doesn't exist.
Where am I going wrong?


text:
Q: Are closures allocated memory when they are defined or first called? Are closures allocated memory when they are defined or first called?  For example, is the closure for the name asHTML allocated memory when the HTMLElement named headerTitle is instantiated, or on the next line when asHTML() is called. Furthermore, with classes a deinit implementation is provided.  Is there a similar feature for closures?
class HTMLElement {
    let name: String
    let text: String?
    lazy var asHTML: () -> String = {
        return "<\(self.name)>\(self.text ?? "")</\(self.name)>"
    }

    init(name: String, text: String? = nil) {
        self.name = name
        self.text = text
    }
    deinit {print("\(name) is being deinitialized")}
}

var headerTitle: HTMLElement? = HTMLElement(name: "h1", text: "Welcome")
print(headerTitle!.asHTML())
headerTitle = nil

A: In general, a closure will need to be allocated at its definition site in order to capture variables used within the closure that are outside of the closure. However, the lazy keyword makes it so that the closure is not declared until its first use. From Apple's documentation

A lazy stored property is a property whose initial value is not calculated until the first time it is used. You indicate a lazy stored property by writing the lazy modifier before its declaration.

I'm assuming what you mean by deinit for closures mean to release any strong references to reference-semantic variables in your closure. Your example comes from Apple's own The Swift Programming Guide (Swift 4). They explain that this example has a strong reference cycle, meaning the class instance holds a strong reference to the closure, and the closure has a strong reference to the instance. And nether are willing to release one another causing the instance to never be de-initialized. Here is Apple's visual:

If you read look further ahead in the chapter, they speak about defining a capture list to break the strong reference cycle.
lazy var asHTML: () -> String = {
    [unowned self] in /*<-- Add self in the capture list, so the closure does not have a strong reference to the instance. */
    if let text = self.text {
        return "<\(self.name)>\(text)</\(self.name)>"
    } else {
        return "<\(self.name) />"
    }
}

Now when headerTitle is set to nil, the deinit print message will show.