text:
Q: Ubuntu Software redirecting to Snap Store I've been going through an interesting situation after upgrading to version 22.10 where Ubuntu Software, after opened by the dock, redirects to the Snap Store.

A: Yes. It seems that the old Ubuntu Software store has been discontinued and merged into the Snap Store. However, after selecting a specific software in the new Snap Store, you can go to the top right menu list and see if there is a ".deb" version provided by Ubuntu and install that. The "new" Snap Store is a bit buggy though.
If you really want to install the "old" GNOME Software tool, you can try:
$ sudo apt-get install gnome-software


text:
Q: Docker refuses to mount NFS share I'm trying to mount an NFS(version 3) share, which exists on the host, into a docker container, but it's not working.
Example:
docker run -v /mnt/test001/:/mnt/test001/ hello-world

This mount is an NFS share with squashed root, which I suspect is the reason for this problem. Docker seems to run as root(that's what ps -ef shows me anyway).
Error message states:

dockerd[...]: time="..." level=error msg="Handler for POST
  /.../containers/.../start returned error: error while creating mount
  source path '/mnt/.../': mkdir /mnt/.../: permission denied"

What is required here to allow for this mount to occur? Removing the root squash seems unsafe and overkill. Is it possible to allow my local root to have read rights, while still squashing root?
EDIT: The permissions were dwrxwrx---
The problem was that world/other didn't have read right.
As such the subdirectory I wanted to mount could not be read by my local root, as that root got squashed -> needed world/other rights and there were none.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unity's transform.RotateAround usage with lerp I am working on a 3D Camera controller, where player is able to rotate the camera around an object using mouse. transform.RotateAround() is perfect for this, except for one thing - I can't figure out a way to smoothly lerp it.
For reference - this is old code, which made camera rotate smoothly, but without a specific Target, just around an arbitrary point:
private void Rotate(){
        if(!EnableRotation || RotationTarget == null) return;
        if(Input.GetKeyDown(KeyCode.R)) _newRotation = Quaternion.identity;

        if(Input.GetKey(KeyCode.Mouse1)){
            float xInput = Input.GetAxis("Mouse X");

           _newRotation *= Quaternion.Euler(Vector3.up * RotationSpeed * xInput * RotationSensitivity);
        }
    }

    private void UpdateRotation(){
        transform.rotation = Quaternion.Lerp(transform.rotation,_newRotation,Time.deltaTime * RotationDampening);
    }

And this, is what I have currently:
private void Rotate(){
        if(!EnableRotation || RotationTarget == null) return;
        if(Input.GetKeyDown(KeyCode.R)) _newRotation = Quaternion.identity;

        if(Input.GetKey(KeyCode.Mouse1)){
            float xInput = Input.GetAxis("Mouse X");

            transform.RotateAround(RotationTarget.position,Vector3.up,RotationSpeed * xInput);
        }
    }

So my big question is - is there a way to lerp the rotation of transform.RotateAround()? Make it smooth. Or are there any other ways of doing this?
Thanks in advance.
I feel like I've tried everything, but no success so far.

A: Where is Rotate() called? Is the rotationSpeed * xInput meant to represent degrees as required?
I figure first the UpdateRotation() method was called frequently, while the Rotate() method was called to set the new rotation, in the new version you do the rotation on Rotate() are you calling it as often as you did with the UpdateRotation()?.
You could Lerp 360 degrees such as Vector3.Lerp(0, 360, t) where t should range from 0 to 1. Or simply adjust the rotation speed accordingly, making sure you call the method enough times to have a smooth rotation.


text:
Q: IP address rules for each octet This Wikipedia article on IPv4 addresses states the valid range for each octet is 0-255. However, when I enter a number that is deliberately out-of-range on my Windows 7 PC, the valid range is notified as 1-223 (not 0-255) for the 1st octet of my IP address:

This applies to the first octet of IP address, Default gateway, Preferred DNS sever and Alternate DNS server, but not Subnet mask.  All other octets allow 0-255. We have some Windows CE 6.0 machines on-site and these allow 0-255 for all octets.

*

*Why does my Windows 7 machine report a valid range of 1-223 for the 1st octet only and why different to Windows CE?

*What are the rules for IP address octets?

*In writing a technical blog on IP settings, is it safe to assume a valid range of 0-255 (and ignore obscure restrictions) or should I be more subtle and cover some of the exceptions?

NB! I am not interested in whether the entered IP address will actually work...only the low-level rules for entering them in the first place!
Note: I asked our IT department. They did not know the answers and just directed me to Wikipedia!

A: An IPv4 address is just a 32-bit number, e.g. 00001010000010110000110000001101. The decimal octet notation is just to make it easier for humans to read. Each octet is 8 bits, e.g. 00001010.00001011.00001100.00001101, which is then converted to decimal numbers (10.11.12.13). Since 8 bits can represent the numbers from 0 to 255, each octet can on have a number in that range.
The is nothing special or magical about the octet boundaries; they are artificial. Thinking of IPv4 addresses in terms of the textual representation (decimal octets) can really get you into some convoluted thinking and lead to errors. The computer and the network equipment only ever see and use the binary number. Many networking students want to manipulate IPv4 addresses without converting to binary first, and that is a path to failure.
The valid unicast IPv4 addresses go up to 223.255.255.255. Addresses larger than that are multicast addresses (begin with 1110 as the first four bits of the address = 224.0.0.0 to 239.255.255.255) or reserved (begin with 1111 as the first four bits of the address = 240.0.0.0 to 255.255.255.255). The address 255.255.255.255 is the limited broadcast address.
RFC 5735, Special Use IPv4 Addresses has a summary of the IPv4 special use addresses.

A: 1-223 covers Class A/B/C networks, which are what your PC will use.
224+ is for Class D (Multicasting) and Class E (not used) networks, neither of which are appropriate for a Windows PC.
Webopedia article on IP Addressing


text:
Q: How do I tell git that I only want to add the current file content of a child repo, not the repo as a submodule If you clone a git repo inside of another git repo (e.g. to install code for a library or plugin into the parent repo) it appears impossible to add the file content of that directory to the parent repo as a simple commit of files, unless you delete or move the child repo's .git directory first.
You might want to instead add the repo as a submodule, in which case git add submodule <child_repo_url> <child_folder> will add it as two files:
new file:   .gitmodules
new file:   child_folder

In which child_folder is not an actual folder, but a simple text file that contains a line like this:
Subproject commit 3ddea2d9a36dbdbf02f9f1897b713704300b0c34

And the .gitmodules file contains the info about the repo, allowing git to later check out the exact same commit from that repo and so reconstruct all the files without actually adding them to the parent repo.
But, if you don't want that because you do want to simply add the files and just do git add <child_folder> instead you will see this message:
warning: adding embedded git repository: child_folder
hint: You've added another git repository inside your current repository.
hint: Clones of the outer repository will not contain the contents of
hint: the embedded repository and will not know how to obtain it.
hint: If you meant to add a submodule, use:
hint:
hint:   git submodule add <url> child_folder
hint:
hint: If you added this path by mistake, you can remove it from the
hint: index with:
hint:
hint:   git rm --cached child_folder
hint:
hint: See "git help submodule" for more information.

This sounds like it has done what I want, and is warning you in case you didn't want that to happen. But in fact, it hasn't added the files.
Instead it has added the same child_folder file as the git submodule add, but not the .gitmodules entry which seems like a necessary partner for it, and neither of the two commands it suggests will actually work now, because of the action that the command has just taken.
The git submodule add command would have worked, if the previous command hadn't already added something to the git index called child_folder, so the command fails with 'child_folder' already exists in the index.
The second command I assume would work if the first command had done what I'd wanted, and allow you to undo that action, but instead it will say
error: the following file has staged content different from both the
file and the HEAD:
    child_folder

So it seems at some point, what I want to happen was the default, and this error message was added to help people who had done it by mistake. Now, it appears impossible to do this with a single command, and the old help message is out of date and unhelpful.
Previously, you could avoid this behaviour by being careful about using, or not using, a final / when using git add child_folder/ to get one behaviour or the other but at some point in git's history aronud version 1.6 this workaround appears to have stopped working and you now always get the behaviour I describe.
There seems to be no flags you can add to the command to specify that you know the subdirectory is a repo, and that you don't care. There is a flag        --no-warn-embedded-repo the help for which says:

By default, git add will warn when adding an embedded repository
to the index without using git submodule add to create an entry
in .gitmodules. This option will suppress the warning (e.g., if
you are manually performing operations on submodules).

If you ignore everything after the "e.g." then it sounds exactly what I want. But if you include the e.g. then I don't know why you would want to manually update submodules that don't exist in .gitmodules. Either way, it doesn't help. It does suppress the warning, but the action it takes remains the same.
My current workaround is to delete or move the .git folder from the child repo to a different location before performing the git add, but it seems like this should be a possible option to have as a preference setting or command line flag, or indeed be the default behaviour with the existing warning message as help for those who don't want that, and the existing flag for people who know that they're doing something that throws a warning, and don't care.
Am I missing a git command or option that would do what I want or is this just a bug in git?


text:
Q: How to analyze the time complexity $\Theta$ of this recurrence I am trying to understand how to show that
$$T(n) = T(n/2) + T(n/4) + n^2$$
is $\Theta(n^2)$ by using a recursion tree. I tried substitution at first but it got real messy real fast.
This is self-study. Problem is from this pdf, problem 1-12.

A: Suppose we start by solving the following recurrence:
$$T(n) = T(\lfloor n/2 \rfloor) + T(\lfloor n/4 \rfloor) + n^2$$
where $T(1) = 1$ and $T(0) = 0.$
Now let $$n = \sum_{k=0}^{\lfloor \log_2 n \rfloor} d_k 2^k$$
be the binary representation of $n.$
We unroll the recursion to obtain an exact formula for $n\ge 1$
$$T(n) = \sum_{j=0}^{\lfloor \log_2 n \rfloor}
[z^j] \frac{1}{1-z-z^2}
\left(\sum_{k=j}^{\lfloor \log_2 n \rfloor} d_k 2^{k-j}\right)^2.$$
We recognize the generating function  of the Fibonacci numbers, so the
formula becomes
$$T(n) = \sum_{j=0}^{\lfloor \log_2 n \rfloor} F_{j+1}
\left( \sum_{k=j}^{\lfloor \log_2 n \rfloor} d_k 2^{k-j}\right)^2.$$
We now compute lower and  upper bounds which are actually attained and
cannot  be improved upon.  For the  lower bound  consider a  one digit
followed by a string of zeroes, to give
$$T(n) \ge \sum_{j=0}^{\lfloor \log_2 n \rfloor}
F_{j+1} 4^{\lfloor \log_2 n \rfloor-j}
= 4^{\lfloor \log_2 n \rfloor}
\sum_{j=0}^{\lfloor \log_2 n \rfloor}
F_{j+1} 4^{-j}.$$
Now since $$\left|\frac{1+\sqrt{5}}{2}\right|<4$$
the sum term converges to a number, we have
$$1 \le
\sum_{j=0}^{\lfloor \log_2 n \rfloor-1} F_{j+1} 4^{-j}
\lt \sum_{j=0}^{\infty} F_{j+1} 4^{-j}
= \frac{16}{11}$$
and we thus get for the asymptotics
$$\frac{16}{11} 4^{\lfloor \log_2 n \rfloor}.$$
For an upper bound consider a string of one digits to get
$$T(n) \le \sum_{j=0}^{\lfloor \log_2 n \rfloor}
F_{j+1}
\left( \sum_{k=j}^{\lfloor \log_2 n \rfloor} 2^{k-j}\right)^2
= \sum_{j=0}^{\lfloor \log_2 n \rfloor}
F_{j+1} (2^{\lfloor \log_2 n \rfloor+1-j} - 1)^2
\\ = 4\times 4^{\lfloor \log_2 n \rfloor}
\sum_{j=0}^{\lfloor \log_2 n \rfloor}
F_{j+1} 4^{-j}
- 4\times 2^{\lfloor \log_2 n \rfloor}
\sum_{j=0}^{\lfloor \log_2 n \rfloor}
F_{j+1} 2^{-j}
+ \sum_{j=0}^{\lfloor \log_2 n \rfloor}
F_{j+1}
\\ = 4\times 4^{\lfloor \log_2 n \rfloor}
\sum_{j=0}^{\lfloor \log_2 n \rfloor}
F_{j+1} 4^{-j}
- 4\times 2^{\lfloor \log_2 n \rfloor}
\sum_{j=0}^{\lfloor \log_2 n \rfloor}
F_{j+1} 2^{-j}
+ F_{\lfloor \log_2 n \rfloor + 3} - 1.$$
The  same  constant appears  as  in  the lower  bound  as  well as  an
additional constant. Computing these we get
$$\frac{64}{11} \times 4^{\lfloor \log_2 n \rfloor}
- 16\times 2^{\lfloor \log_2 n \rfloor}
+ F_{\lfloor \log_2 n \rfloor + 3} - 1.$$
Doing the asymptotics of these three  terms we obtain a term in $n^2$,
a  term in  $n$ and  a  term in  $n^{\log_2 \varphi}  \in o(n)$  where
$\varphi$ is the golden ratio.

Joining the  upper and the lower  bound we get for  the asymptotics of
this recurrence that it is
$$T(n)\in\Theta\left(4^{\lfloor \log_2  n \rfloor}\right)
= \Theta\left(2^{2\log_2  n}\right) = \Theta(n^2),$$
which, let it be said, could also have been obtained by inspection.

Remark. The evaluation of the constant is done by noting that
the generating function of
$$F_{j+1} 4^{-j}\quad
\text{is}\quad\frac{1}{1-z/4-z^2/16}$$
which at $z=1$ evaluates to $\frac{1}{1-1/4-1/16} = \frac{16}{11}.$
Similarly we have the generating function of
$$F_{j+1} 2^{-j}\quad
\text{is}\quad\frac{1}{1-z/2-z^2/4}$$
which at $z=1$ evaluates to $\frac{1}{1-1/2-1/4} = 4.$
We have a certain  flexibility as to what power of four  to use in the
constant but this does not affect the asymptotics.

A closely related recurrence that  is somewhat simpler may be found at
this MSE link.

A: First consider the homogeneous equation
$$T(n)=T(\frac n2)+T(\frac n4).$$
Letting $n=2^k$,
$$T(2^k)=T(2^{k-1})+T(2^{k-2)}$$ or $$S(k)=S(k-1)+S(k-2).$$
You should recognize the Fibonacci recurrence, with the asymptotic solution
$$T(n)=S(k)=O(\phi^k)=O(e^{log(\phi)log(n)/log(2)})=O(n^{0.6942\cdots})$$
Then you try a particular solution of the non-homogenous equation, such as $T(n)=an^2$. Plugging in the given equation,
$$an^2=\frac{an^2}4+\frac{an^2}{16}+n^2$$ and
$$T(n)=\frac{16}{11}n^2$$ works.
As this solution dominates the other, you can conclude $\Theta(n^2)$.


text:
Q: USB folder hider/revealer My dad recently gave me this 7 GB key shaped USB. The USB is really cool, but as a user of a 2TB SSD, I don't really need it.
Seeing that it looks like a key, I was wondering how to conceal a folder on my computer that is only revealed when the key shaped USB is plugged into my computer. In other words folder doesn't exist until top secret USB key is plugged into computer. Is there a way to do this?
The folder I'm wanting to hide isn't that important, so encryption isn't what I'm looking for. Just kinda the cool factor (read gimmick) and being able to hide my folders
Edit: I was able to find sort of what I wanted. It is called the ROG keystone and it unlocks a secret drive when plugged into the laptop. Is there any way to replicate this with a normal USB?

A: It is really not possible to hide a folder on a computer that is not detectable at all unless external tools are required. You can encrypt a folder and have the decryption key be on the usb stick, but the folder itself will be visible.
You would need something like TrueCrypt to create a file storage container that requires a file to open, and store the file on the USB stick.
If the data you are trying to hide is not too large, you could make it much easier to just move the data to the USB stick itself. Then it is really gone from the harddisk.
This does mean that anyone that has the stick has the data too. You could use something like TrueCrypt and create the password protected chamber on the USB stick itself and require a passphrase or store its key on your computer. That way, you still keep the usbkey connected to the computer.

A: This command will make a folder "super-hidden":
attrib +r +a +s +h C:\MyHiddenFolder

Applying these attributes to a folder will hide it (assuming the user hasn't unticked "hide protected operating system files" in explorer view settings).
You could use the Task Scheduler to execute a batch file to add/remove these folder attributes triggered by the device specific add/remove event.
For the event to appear in Event Viewer you need to enable the event logging for that function first (See here).  The event can then be seen at this path:
Application and Services Logs > Microsoft > Windows > DriverFrameworks-UserMode > Operational

You will need to create a custom XML filter to capture the right event for your device.
Example of USB Device connected XML Filter:
(Note that you must escape the & with &)
<QueryList>
  <Query Id="0" Path="Microsoft-Windows-DriverFrameworks-UserMode/Operational">
    <Select Path="Microsoft-Windows-DriverFrameworks-UserMode/Operational">
*[System[EventID=2101]]
and
*[UserData[UMDFHostDeviceRequest[InstanceId='SWD\WPDBUSENUM\_??_USBSTOR#DISK&VEN_GENERIC&PROD_FLASH_DISK&REV_8.07#12F9600A&0#{53F56307-B6BF-11D0-94F2-00A0C91EFB8B}']]]
and
*[UserData[UMDFHostDeviceRequest[RequestMinorCode='20']]]
</Select>
  </Query>
</QueryList>

Lastly, if you have the folder in view it will initially just appear to "grey out" until the folder view is refreshed. You can force this with the following cmd line:
ie4uinit.exe -show


text:
Q: How to change text in the Alert in Flex I want to change the text in the Alert on timer tick, but nothing changes, see example below:
private var alert:Alert;
private var timer:Timer = new Timer(1000, 0);

private function init(){
   timer.addEventListener(TimerEvent.TIMER, onTimerTick);
   timer.start();
   alert = Alert.show("Logout in "+ 60 +" seconds","",3);
}

private function onTimerTick(event:TimerEvent):void{
   alert.text = "Logout in "+(60-timer.currentCount)+" seconds";
}

P.S. Title is overridden by this way.
Thanks in advance for any help

A: private var uiText:UITextField;

private function init():void{
    timer.addEventListener(TimerEvent.TIMER, onTimerTick);
    timer.start();
    alert = Alert.show("Logout in "+ 60 +" seconds","",3);
    var child:DisplayObjectContainer = alert.getChildAt(0) as DisplayObjectContainer;
    uiText = child.getChildAt(0) as UITextField;
    uiText.text;

}

private function onTimerTick(event:TimerEvent):void{
    (timer.currentCount > 60) ? [timer.stop(), alert.parent.removeChild(alert)] : void;
    uiText.text = "Logout in "+(60-timer.currentCount).toString()+" seconds";
}

Do some thing like this will help.

A: Alright, so this is rather ugly.
alert.mx_internal::alertForm.mx_internal::textField.text = "...";

Will let you update the text. It's not pretty, but it works.


text:
Q: How to lag number of days instead of number of rows - for every ID I am doing a classification problem in which I am trying to predict whether a car will be refuelled the following day.
The data consists of a date, an ID for every car, the distance to destination
What I want is a variable that is lagged 3 days, and not 3 rows per car_ID - since the case is that every car_ID is not present on every day. Therefore, the lag should be based on the date and not the rows.
If there are less than 3 days of history, the result should be -1.
Currently, I have this piece of code which lags every row 3 days
data['distance_to_destination'].groupby(data['car_ID']).shift(3).tolist()

But this is only lagging for the number of rows and not the number of days.
What I want to achieve is the column "lag_dtd_3":
date    car_ID  distance_to_destination lag_dtd_3

01/01/2019  1   100 -1

01/01/2019  2   200 -1

02/01/2019  1   80  -1

02/01/2019  2   170 -1

02/01/2019  3   500 -1

03/01/2019  2   120 -1

05/01/2019  1   25  80

05/01/2019  2   75  170

06/01/2019  1   20  -1

06/01/2019  2   30  120

06/01/2019  3   120 -1

A: One solution to lag information by 3 days is to move the index instead of shifting.
pivot = data.pivot(columns='car_ID')
shifted = pivot.copy()
shifted.index = shifted.index + pd.DateOffset(days=3) # Here I lag the index instead of shifting

shifted.columns = shifted.columns.set_levels(['lag_dtd_3'], 0)
output = pd.concat([pivot, shifted], axis = 1).stack('car_ID').reset_index('car_ID')
output['lag_dtd_3'] = output['lag_dtd_3'].fillna(-1)
output = output.dropna()

Output:
    car_ID  distance_to_destination lag_dtd_3
date
2019-01-01  1   100.0   -1.0
2019-01-01  2   200.0   -1.0
2019-01-02  1   80.0    -1.0
2019-01-02  2   170.0   -1.0
2019-01-02  3   500.0   -1.0
2019-01-03  2   120.0   -1.0
2019-01-05  1   25.0    80.0
2019-01-05  2   75.0    170.0
2019-01-06  1   20.0    -1.0
2019-01-06  2   30.0    120.0
2019-01-06  3   120.0   -1.0


text:
Q: In Swift, is it possible to convert a string to an enum? If I have an enum with the cases a,b,c,d is it possible for me to cast the string "a" as the enum?

A: Riffing on djruss70's answer to create highly generalized solution:
extension CaseIterable {
    static func from(string: String) -> Self? {
        return Self.allCases.first { string == "\($0)" }
    }
    func toString() -> String { "\(self)" }
}

Usage:
enum Chassis: CaseIterable {
    case pieridae, oovidae
}

let chassis: Chassis = Chassis.from(string: "oovidae")!
let string: String = chassis.toString()

Note: this will unfortunately not work if the enum is declared @objc.  As far as I know as of Swift 5.3 there is no way to get this to work with @objc enum's except brute force solutions (a switch statement).
If someone happens to know of a way to make this work for @objc enums, I'd be very interested in the answer.

A: All you need is:
enum Foo: String {
   case a, b, c, d
}

let a = Foo(rawValue: "a")
assert(a == Foo.a)

let  = Foo(rawValue: "")
assert( == nil)

A: In Swift 4.2, the CaseIterable protocol can be used for an enum with rawValues, but the string should match against the enum case labels:
enum MyCode : String, CaseIterable {

    case one   = "uno"
    case two   = "dos"
    case three = "tres"

    static func withLabel(_ label: String) -> MyCode? {
        return self.allCases.first{ "\($0)" == label }
    }
}

usage:
print(MyCode.withLabel("one")) // Optional(MyCode.one)
print(MyCode(rawValue: "uno"))  // Optional(MyCode.one)

A: Swift 4.2:
public enum PaymentPlatform: String, CaseIterable {
    case visa = "Visa card"
    case masterCard = "Master card"
    case cod = "Cod"

    var nameEnum: String {
        return Mirror(reflecting: self).children.first?.label ?? String(describing: self)
    }

    func byName(name: String) -> PaymentPlatform {
        return PaymentPlatform.allCases.first(where: {$0.nameEnum.elementsEqual(name)}) ?? .cod
    }
}

A: In case with an enum with Int type you can do it so:
enum MenuItem: Int {
    case One = 0, Two, Three, Four, Five //... as much as needs

    static func enumFromString(string:String) -> MenuItem? {
        var i = 0
        while let item = MenuItem(rawValue: i) {
            if String(item) == string { return item }
            i += 1
        }
        return nil
    }
}

And use:
let string = "Two"
if let item = MenuItem.enumFromString(string) {
    //in this case item = 1
    //your code
}

A: Extending Duncan C's answer
extension StringEnum: StringLiteralConvertible {

    init(stringLiteral value: String){
        self.init(rawValue: value)!
    }

    init(extendedGraphemeClusterLiteral value: String) {
        self.init(stringLiteral: value)
    }

    init(unicodeScalarLiteral value: String) {
        self.init(stringLiteral: value)
    }
}

A: For Int enum and their String representation, I declare enum as follows:
enum OrderState: Int16, CustomStringConvertible {

    case waiting = 1
    case inKitchen = 2
    case ready = 3

    var description: String {
        switch self {
        case .waiting:
            return "Waiting"
        case .inKitchen:
            return "InKitchen"
        case .ready:
            return "Ready"
        }
    }

    static func initialize(stringValue: String)-> OrderState? {
        switch stringValue {
        case OrderState.waiting.description:
            return OrderState.waiting
        case OrderState.inKitchen.description:
            return OrderState.inKitchen
        case OrderState.ready.description:
            return OrderState.ready

        default:
            return nil
        }
    }
}

Usage:
order.orderState = OrderState.waiting.rawValue

let orderState = OrderState.init(rawValue: order.orderState)
let orderStateStr = orderState?.description ?? ""
print("orderStateStr = \(orderStateStr)")

A: Sure. Enums can have a raw value. To quote the docs:

Raw values can be strings, characters, or any of the integer or
floating-point number types
— Excerpt From: Apple Inc. "The Swift Programming Language." iBooks. https://itun.es/us/jEUH0.l,

So you can use code like this:
enum StringEnum: String
{
    case one   = "value one"
    case two   = "value two"
    case three = "value three"
}

let anEnum = StringEnum(rawValue: "value one")!

print("anEnum = \"\(anEnum.rawValue)\"")

Note: You don't need to write = "one" etc. after each case. The default string values are the same as the case names so calling .rawValue will just return a string
EDIT
If you need the string value to contain things like spaces that are not valid as part of a case value then you need to explicitly set the string. So,
enum StringEnum: String
{
  case one
  case two
  case three
}

let anEnum = StringEnum.one
print("anEnum = \"\(anEnum)\"")

gives

anEnum = "one"

But if you want case one to display "value one" you will need to provide the string values:
enum StringEnum: String
{
  case one   = "value one"
  case two   = "value two"
  case three = "value three"
}

A: I used this:
public enum Currency: CaseIterable, Codable {
    case AFN = 971 // Afghani (minor=2)
    case DZD = 012 // Algerian Dinar (minor=2)

...

    private static var cachedLookup: [String: Currency] = [:]

    init?(string: String) {
        if Self.cachedLookup.isEmpty {
            Self.cachedLookup = Dictionary(uniqueKeysWithValues: Self.allCases.map { ("\($0)", $0) })
        }

        if let currency = Self.cachedLookup[string] {
            self = currency
            return
        } else {
            return nil
        }
    }
}

A: I found the other answers make this way more complicated then it needs to be. Here is a quick and concise example.
enum Gender: String {
    case male, female, unspecified
}

Simple enum, note that I added ": String" to the enum itself to declare the type as string.
Now all you have to do is:
let example: Gender = Gender(rawValue: "male")

And thats it, 'example' is now an enum of type Gender with the value of .male
There is literally nothing else you need to do in Swift 4+.


text:
Q: How to create a virtual machine from a .img disk image? I downloaded a disk image used for a wargame hosted by stripe, but I cant figure out how to create a virtual machine from this image.
I'm using virtualbox, but I could use another tool if it would be easier

A: Found the solution, VirtualBox has a tool to create the .vdi from .img:
VBoxManage convertfromraw image.img virtual_disk.vdi

A: For VMWare
I found a simple but complete freeware tool here
Use it to convert img to vmdk and create a new virtual machine manually within WMWare and set your vmdk file as virtual disk.

A: stripe-ctf-server-ubuntu-10.04-lucid-amd64-20120427-0108.img.tar

Burn the image to a dvd or mount the img, and then boot from it.

You can now install it into a VirtualBox VM.
Follow the steps in the link below.
The Beginner's Guide to Creating Virtual Machines with VirtualBox

Make sure "Mount CD/DVD Drive" is checked. If you're going to install
  your virtual system from a boot CD or DVD, put it in your computer's
  drive, then select "Host CD/DVD Drive." If you're using a downloaded
  or custom-made ISO file, select "ISO Image file," hit the folder icon
  to the right of the drop-down box, and then hit the "Add" button and
  browse for the ISO you're using. Once you've added an ISO file to this
  menu, you can mount it in any virtual machine you're running at any
  time

A: Ive used IMGtoISO and have been pleased with it.  Its free and easy to use.  Plus the ISO format is more compatible with more applications.


text:
Q: How would iOS reminder functionality be implemented? What is the recommended way to implement a reminder functionality, which would survive the app being in an inactive state, and would wake it up at a predetermined time?
Using NSTimer seems to be OK in the foreground, but the user should be able to set a reminder, close the app, and do something else.
How is this done?

A: Look into local notifications:
http://developer.apple.com/library/ios/#documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Introduction/Introduction.html
http://developer.apple.com/library/ios/#documentation/iPhone/Reference/UILocalNotification_Class/Reference/Reference.html#//apple_ref/occ/cl/UILocalNotification


text:
Q: sql query using LIKE or MATCH I have a table of 13 columns , out of those i have 5 columns that contains let say string data or VARCHAR data.
Now i have a string let say "abc".
I want to write a sql query to get all the rows that have this "abc" string in those 5 columns. "abc" can be the data of the column of part of the data of the column.
I used LIKE function
SELECT * FROM table WHERE col1 OR col2 OR col3 OR col4 OR col5 LIKE '%abc%';

but it didnt worked n got back all the rows.
I dont know how use MATCH function either, I m nt good in sql. so can anyone help.

A: You can specify condition multiple times:
SELECT *
FROM table
WHERE col1 LIKE '%abc%'
 OR col2 LIKE '%abc%'
 OR col3 LIKE '%abc%'
 OR col4 LIKE '%abc%'
 OR col5 LIKE '%abc%';

This will be really slow because you have multiple OR and non-SARGable condition.
Alternatively:
SELECT *
FROM table
WHERE CONCAT_WS('^', col1,col2,col3,col4,col5) LIKE '%abc%';

Using MATCH (preferred solution that utilizes full-text index):

SELECT *
FROM table
WHERE MATCH(col1, col2,col3,col4, col5) AGAINST ('abc');

SqlFiddleDemo
Keep in mind that to use MATCH you need to create index first:
ALTER TABLE tab ADD FULLTEXT ft_index_name (col1,col2,col3,col4,col5);


text:
Q: M.2. PCIe adapter with two M.2 SSDs only shows one I have just finished my (first ever) server build. Everything seems to work ok. Except I only see one of the two NVMe M.2 SSDs that I installed via a PCIe adapter. (At least, it shows as 500 GB, rather than 1 TB.)

*

*Are the NVMe SSDs faulty?

*Or is the adapter automatically generating some sort of RAID array?

*If so, how can I modify this?

*Or am I missing some setting somewhere?

The hardware (amongst others):

*

*Fujitsu D3417-B2 MB

*ASUS HYPER M.2 X16 Card (M.2 PCIe adapter for up to 4 M.2 drives)More hardware info

*2 500GB WD ST4000VN008-2DR166 NVMe SSDs in the adapter

*1 250GB WD WDS500G2X0c-00L350 NVMe SSD on the motherboard

*2 4TB SATA HDDs

The following image shows screenshot of BIOS - the highlighted drive is the one in the M.2 PCIe adapter

Additional info:

*

*The 250GB has EXSi installed - also there the SSD    shows as 500GB,
rather than 2x500GB

*The status leds on the ASUS adapter on both slots with SSD are lit

*The manual mentions "For Intel® motherboards, go to
Advanced > CPU Storage Configuration, then set the PCIE slot(s) that
you have installed the Hyper M.2 x16 card(s) to [Hyper M.2 X16]." But
I cannot find this option..

A: Check the manual for the PCIe card carefully - Some of the cheaper ones actually consist of 1x PCIe M2 slot and 1x SATA M2 slot but with the SATA slot needing to be connected in to the motherboard to work.
For example - this model: https://www.silverstonetek.com/product.php?pid=575&area=en
(I bought one of these and was disappointed to discover that limitation).
I'd check the link you've posted but the manual for the ASUS card you've linked deals exclusively with the RAID setup process (it doesn't discuss the hardware at all).

A: A review of the ASUS HYPER M.2 X16 PCIe RAID card manual shows it cannot be configured except as RAID. If you want to have 1,000 GB of storage using the two 500 GB M.2 drives, you must configure it for RAID 0, which is a more fragile system than having each M.2 drive assigned to its own drive letter; if either drive fails, the content of both drives is lost.
The Fujitsu motherboard uses an Intel CPU, so you would follow Chapter One of the Asus instructions. You cannot use RAID 1, RAID 5, or RAID 10; you must use RAID 0.
Furthermore, section 1.1.3 Paragraph 2 notes

Due to chipset limitation, when SATA ports are set to RAID mode, all
  SATA ports run at RAID mode together.

If so, this may require you configure your SATA HDDs for RAID, which you may not want.
I would suggest you consider returning this to the vendor if you don't want that.

A: After some back and forth with the retailer, they finally confirmed the MB and adapter are indeed not compatible.. Thanks!

A: The PCIE adapter in the original posters case requires a mainboard with Bifurbication support, while the adapter was confirmed incompatible, the reason why was never addressed.
Bifurbication splits a 16x or 8x electrical slot into a division of that slots max lane count, in some cases support can be modded in using bios and uefi editors.
Not all motherboards that can be modded support a full 4x4x4x4x bifurbication and can adapt to 3 out of a possible 4.
Since the original posters mainboard did not support this, only the nvme on the first 4 lanes was visible to the machine.


text:
Q: Possible to reformat multiline method parameters to single line? My IDE of choice is Netbeans and whenever I make a project with existing code that was formatted in Eclipse it is harder to read for me. For example Eclipse format looks like this:
As you can see it puts every parameter on a new line. There is an option for this in Netbeans aswell however it is set to "Never" by default as specified in the Options->Editor->Formatting->Java->Wrapping->Method Parameters setting. When I try to reformat the code in Netbeans it will not reformat this to become like this:
I have over 1000 classes and wish to let the Netbeans formatter do this. Is there any way or any alternative to reformat to this style?


text:
Q: Multiple Clients, same Firestore We have an app that uses Firestore, snapshots, and lots of connections.
We have multiple customers wanting to use it.
Scale question - do we need to have seperate apps for scale or is it really all about just not accessing a specific document too often and it doesn't matter if you just seperate them at a root collection?
We have 2 customers on it now, and are just making sure this scales like we think before adding the next 20.


text:
Q: 8Khz vs 48Khz audio sampling and noise expectations I'm messing around with this dac/dsp combo going into my picmx32.   Finally I have loopback stable and working cleanly at 48Khz sample rate.   This is a little too much data for me though so I want to bring the sample rate down to 8Khz.   When I do that audio still works but there are two things that bother me.
First the noise increases, or it seems to turn into a more of a hissing noise like background noise on an un-tuned radio or TV.   Maybe the noise is there but cleaner at 48Khz, I can't tell.
Second I get what sounds like a metallic tone that starts to show up when I record sound with the mic.
My question is, mainly about the noise, is this to be expected?   If this noise increase at lower sample rate is just a fundamental concept that I'm not familiar with then I'd like to learn about it.  If not I'll try to debug it more myself.   But no sense hunting it down if it's just a fact of lower sampling rates.

A: It sounds like there are two things going on here.
At the lower sample rate, high frequency noise that was previously picked up as such and subsequently filtered out now aliases into frequencies you can hear.  If you want 8 kHz sample rate, sample at a higher rate, then low pass filter before dessimation.  You want the filters to attenuate frequencies beyond 4 kHz, since that's the maximum a 8 kHz sample stream can reproduce anyway.  Anything above 4 kHz when you sample at 8 kHz is going to become noise that you can't really get rid of later.
The metallic sound is usually a consequence of low resolution, like 8 bits.  The quantization noise at 8 bits does sound sortof "metallic".  Try sampling with more bits, like 12 or 16 per sample.


text:
Q: Given a string that is a range of excel cells 'A1:F1' how would one go about interpolating this range in PHP? I would like to fill this 'A1:F1' out to either an array or a string such that it now equals array {A1, B1, C1, D1, E1, F1} or "A1:B1:C1:D1:E1:F1"
Does anyone have an efficient idea on how to do this?
Thanks.

A: This is one possible solution. It works in two dimensions. As can be seen in the output, it works column by row, to reverse that simply requires changing the order of the two for loops.
function split_range($range) {
    list($start_cell, $end_cell) = explode(':', $range);
    if (!preg_match('/^([A-Z]+)(\d+)$/', $start_cell, $start) || !preg_match('/^([A-Z]+)(\d+)$/', $end_cell, $end)) return array();
    $cells = array();
    for ($c = $start[1]; str_pad($c, strlen($end[1]), " ", STR_PAD_LEFT) <= $end[1]; $c++) {
        for ($r = $start[2]; $r <= $end[2]; $r++) {
            $cells[] = "$c$r";
        }

    }
    return $cells;
}

echo implode(':', split_range("A1:F1")) . "\n";
echo implode(':', split_range("A1:A6")) . "\n";
echo implode(':', split_range("B2:D4")) . "\n";
echo implode(':', split_range("Q3:AB4")) . "\n";

Output:
A1:B1:C1:D1:E1:F1
A1:A2:A3:A4:A5:A6
B2:B3:B4:C2:C3:C4:D2:D3:D4
Q3:Q4:R3:R4:S3:S4:T3:T4:U3:U4:V3:V4:W3:W4:X3:X4:Y3:Y4:Z3:Z4:AA3:AA4:AB3:AB4

A: If I don't misunderstood your question, then is one solution to achieve what you said on your question using php. But let me know if I am on wrong track :)
<?php
$str = 'A1:F1';
$arr = explode(":",$str);
$start = $arr[0];
$end = $arr[1];
$range = range($start[0],$end[0]);
$func = function($value) use ($start){
    return $value.$start[1];
};
$result  = array_map($func,$range);
echo "{".implode(',',$result)."}";
echo PHP_EOL;
echo implode(':',$result);
?>

Output:
{A1,B1,C1,D1,E1,F1}
A1:B1:C1:D1:E1:F1

DEMO: https://3v4l.org/iDsGe


text:
Q: 2checkout - Cannot generate token with sandbox mode I am using 2checkout payment gateway in my PHP project and facing issue in generating token with 'sandbox' mode. Here's the code:
 <form action="" method="post" id="frmSignup" name="frmSignup">

<input type="hidden" value="" name="token" id="token" />
<script type="text/javascript" src="https://www.2checkout.com/checkout/api/2co.min.js"></script>
<script>
  // Called when token created successfully.
  var successCallback = function(data) {
    console.log("success::"+data);
    var myForm = document.getElementById('frmSignup');

    // Set the token as the value for the token input
    myForm.token.value = data.response.token.token;

    // IMPORTANT: Here we call `submit()` on the form element directly instead of using jQuery to prevent and infinite token request loop.
    myForm.submit();
  };

  // Called when token creation fails.
  var errorCallback = function(data) {
    // Retry the token request if ajax call fails
    console.log("error::"+data.errorMsg);
    if (data.errorCode === 200) {
       // This error code indicates that the ajax call failed. We recommend that you retry the token request.
    } else {
      alert(data.errorMsg);
    }
  };

  var tokenRequest = function() {
    // Setup token request arguments
    var args = {
      sellerId: "<?php echo accountnumber_checkout; ?>",
      publishableKey: "<?php echo publickey_checkout; ?>",
      ccNo: $("#creditcardno").val(), //input field
      cvv: $("#billingcvv").val(), //input field
      expMonth: $("#expiryMonth").val(), //input field
      expYear: $("#expiryYear").val() //input field
    };

    // Make the token request
    TCO.requestToken(successCallback, errorCallback, args);
  };

  $(function() {
    // Pull in the public encryption key for our environment
    TCO.loadPubKey('sandbox');

    $("#frmSignup").submit(function(e) {
      // Call our token request function
      tokenRequest();

      // Prevent form from submitting
      return false;
    });
  });

</script>

</form>

Facing this error: ( in 2co.min.js 2:1628 )

Uncaught ReferenceError: tokenRequestUrl is not defined

If I use 'production' in TCO.loadPubKey('production') instead of 'sandbox', then the token is generated. But, in production mode, I am not able to use test cards:
Test Payment Methods


text:
Q: CSS max-width for an img makes IE use the 'original' div/table width I have a website where users can send their RICH text description.
I'm using max-width property for images inside the div (tried table too) that contains this description.
It's working perfectly of FF and Chrome but giving me some trouble (as always) on IE.
The thing is that, on IE, the images are resized (reduced) but the div still acts like it has one big image there.
Right on FF and Chrome:

Problem on IE:

So, can you people help me? Is there a way to solve this?

A: Had the same problem, I'm sure you're using the 'float' property (which is fine), bus still, for it to work under (the horrible) IE, you need to give every div the 'height' and 'width' properties, even if they get it from someone else, or by default.
Then just organize it properly, and you're done.


text:
Q: php call from variable method of variable object: how to indicate this First of all sorry for my english.
I try to explain with an exaple.
class Test{
    protected $functions = ['a'=>'function1', 'b'=>['ClassX', 'methodY']];

    public function exaple($value, $type){
        $k = call_user_func($this->functions[$type], $value);
    }
}

In this way the method can apply diffent functions to the value depending from type.
If i need to call a function put in the "functions" array only a string, otherwise i put an array with class name and method name.
In this way all works fine.

The problem comes when i need to put in the "functions" array a method of the "Test" class.
Bypassing the array i can write:
call_user_func([$this, 'localMethod'], $value);

and this work.
But when i try to put it in the "functions" array i don't know how to specify $this
Here the new exaple:
class Test{
    protected $functions = ['a'=>'function1', 'b'=>['ClassX', 'methodY'], 'c'=>['$this','localMethod']];

    public function exaple($value, $type){
        $k = call_user_func($this->functions[$type], $value);
    }

    public function localMethod($value){
        [...]
    }
}

In this way it doesn't work.
I've tryed in different ways:
'c'=>['$this','localMethod']
'c'=>['this','localMethod']
'c'=>[$this,'localMethod']

but with no luck.
Anyone can help me? Any help will be greatly appreciated.
Thanks

A: You cannot reference $this before the class is instantiated. You have to add those methods in the class's constructor:
public function __construct() {
    $this->functions['c'] = [$this, 'localMethod'];
}


text:
Q: Scrapy gets NoneType Error when using Privoxy Proxy for Tor I am using Ubuntu 14.04 LTS.
I tried Polipo, but it kept refusing Firefox's connections even if I added myself as allowedClient and hours of researching with no solution. So instead, I installed Privoxy and I verified it work with Firefox by going to the Tor website and it said Congrats this browser is configured to use Tor. This confirms that I should be able to scrape Tor websites.
However when I used Scrapy, I get an error that no one seems to have...?
2016-07-14 02:43:34 [scrapy] INFO: Enabled downloader middlewares:
['scrapy.downloadermiddlewares.httpauth.HttpAuthMiddleware',
 'scrapy.downloadermiddlewares.downloadtimeout.DownloadTimeoutMiddleware',
 'myProject.middlewares.RandomUserAgentMiddleware',
 'myProject.middlewares.ProxyMiddleware',
 'scrapy.downloadermiddlewares.retry.RetryMiddleware',
 'scrapy.downloadermiddlewares.defaultheaders.DefaultHeadersMiddleware',
 'scrapy.downloadermiddlewares.redirect.MetaRefreshMiddleware',
 'scrapy.downloadermiddlewares.httpcompression.HttpCompressionMiddleware',
 'scrapy.downloadermiddlewares.redirect.RedirectMiddleware',
 'scrapy.downloadermiddlewares.cookies.CookiesMiddleware',
 'scrapy.downloadermiddlewares.chunked.ChunkedTransferMiddleware',
 'scrapy.downloadermiddlewares.stats.DownloaderStats']
2016-07-14 02:43:34 [scrapy] INFO: Enabled spider middlewares:
['scrapy.spidermiddlewares.httperror.HttpErrorMiddleware',
 'scrapy.spidermiddlewares.offsite.OffsiteMiddleware',
 'scrapy.spidermiddlewares.referer.RefererMiddleware',
 'scrapy.spidermiddlewares.urllength.UrlLengthMiddleware',
 'scrapy.spidermiddlewares.depth.DepthMiddleware']
2016-07-14 02:43:34 [scrapy] INFO: Enabled item pipelines:
['myProject.pipelines.MysqlPipeline']
2016-07-14 02:43:34 [scrapy] INFO: Spider opened
2016-07-14 02:43:34 [scrapy] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2016-07-14 02:43:34 [scrapy] DEBUG: Telnet console listening on 127.0.0.1:6023
2016-07-14 02:43:34 [Tor] DEBUG: User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10 <GET http://thehiddenwiki.org>
2016-07-14 02:43:34 [scrapy] ERROR: Error downloading <GET http://thehiddenwiki.org>
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/twisted/internet/defer.py", line 1126, in _inlineCallbacks
    result = result.throwExceptionIntoGenerator(g)
  File "/usr/local/lib/python2.7/dist-packages/twisted/python/failure.py", line 389, in throwExceptionIntoGenerator
    return g.throw(self.type, self.value, self.tb)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/downloader/middleware.py", line 43, in process_request
    defer.returnValue((yield download_func(request=request,spider=spider)))
  File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/defer.py", line 45, in mustbe_deferred
    result = f(*args, **kw)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/downloader/handlers/__init__.py", line 65, in download_request
    return handler.download_request(request, spider)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/downloader/handlers/http11.py", line 60, in download_request
    return agent.download_request(request)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/downloader/handlers/http11.py", line 259, in download_request
    agent = self._get_agent(request, timeout)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/downloader/handlers/http11.py", line 239, in _get_agent
    _, _, proxyHost, proxyPort, proxyParams = _parse(proxy)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/downloader/webclient.py", line 37, in _parse
    return _parsed_url_args(parsed)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/downloader/webclient.py", line 20, in _parsed_url_args
    host = b(parsed.hostname)
  File "/usr/local/lib/python2.7/dist-packages/scrapy/core/downloader/webclient.py", line 17, in <lambda>
    b = lambda s: to_bytes(s, encoding='ascii')
  File "/usr/local/lib/python2.7/dist-packages/scrapy/utils/python.py", line 117, in to_bytes
    'object, got %s' % type(text).__name__)
TypeError: to_bytes must receive a unicode, str or bytes object, got NoneType

I looked up this "to_byte" error but I go to the source code for Scrapy.
I know this code works without the proxy because it scraped my localhost website and other websites, but not Tor obviously since it's needs the proxy to access onion websites.
What is going on?
Middlewares.py
class RandomUserAgentMiddleware(object):
    def process_request(self, request, spider):
        ua  = random.choice(settings.get('USER_AGENT_LIST'))
        if ua:
            request.headers.setdefault('User-Agent', ua)
            #this is just to check which user agent is being used for request
            spider.log(
                u'User-Agent: {} {}'.format(request.headers.get('User-Agent'), request),
                level=log.DEBUG
            )

class ProxyMiddleware(object):
    def process_request(self, request, spider):
        request.meta['proxy'] = settings.get('HTTP_PROXY')

Settings.py
USER_AGENT_LIST = [
    'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.7 (KHTML, like Gecko) Chrome/16.0.912.36 Safari/535.7',
    'Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0) Gecko/16.0 Firefox/16.0',
    'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10'
]

DOWNLOADER_MIDDLEWARES = {
     'myProject.middlewares.RandomUserAgentMiddleware': 400,
     'myProject.middlewares.ProxyMiddleware': 410,
     #'scrapy.contrib.downloadermiddleware.useragent.UserAgentMiddleware': None
     'scrapy.downloadermiddlewares.useragent.UserAgentMiddleware': None
    # Disable compression middleware, so the actual HTML pages are cached
}

HTTP_PROXY = 'localhost:8118'

A: Internally, Scrapy uses urllib(2)'s _parse_proxy to detect proxy settings. From urllib docs:

The urlopen() function works transparently with proxies which do not require authentication. In a Unix or Windows environment, set the http_proxy, or ftp_proxy environment variables to a URL that identifies the proxy server before starting the Python interpreter.

% http_proxy="http://www.someproxy.com:3128"
% export http_proxy
% python
...

And when using proxy key in meta, Scrapy expects the same syntax, that is it must contain the scheme, for example 'http://localhost:8118'.
This is in the docs, albeit a bit burried:

You can also set the meta key proxy per-request, to a value like http://some_proxy_server:port.


text:
Q: Angular - Do We Need A Constructor If It Doesn't Have Any Logic I'm working with angular.
I'm wondering about whether constructors are needed, and would appreciate some insight.
In several classes, I have constructor that are empty most of the time my service classes have empty constructors. Can these empty constructors be removed? Are there any negative impact to a class have no constructor vs having an empty one?

A: If you don't use DI service for angular in your class you can remove it .

If the class won't be used by third parties and you don't need an overloaded constructor, don't write an empty constructor.


text: Q: Google cloud bucket through Storage account New to GCP and looking for some help on how to access the project storage bucket using a Service Account. Can Storage accounts not be accessed via google console like how Azure blob storages are accessed?


text:
Q: Разделение проекта под SVN Например есть основной проект (ОП). Дня него создан репозиторий, и все с ним прекрасно. Но с этого проекта нужно сделать 2 дочерних проекта.
В основном проекте файлы - уникальны. То есть файлы основного проекта в дочерних не изменяться, а в дочерних будут свои.
Вопрос. Можно как-нибудь настроить проект дочернего! проекта, чтоб можно было обновлять его с двоих репозиториев. Основные файлы с основного репозитория, и свой репозиторий.
Спасибо!

A: Вам необходимо использовать внешние зависимости, то есть по сути несколько связанных репозиториев.
Данная статья должна Вам помочь:
http://elis.dvo.ru/~lab_11/svn-book-html-chunk/svn.advanced.externals.html

A: Если все лежит на одном сервере, то использовать hook post-commit.
В проекте XXX, который использует проект YYY, сделать checkout проекта YYY, а в post-commit'e автоматизировать update.

A: Для этого существуют ветки в SVN http://habrahabr.ru/post/120063/


text:
Q: Kernel of a morphism from a locally free sheaf is locally free Let $C$ be a projective curve (not necessarily reduced or irreducible). Let $\mathcal{F}, \mathcal{G}$ be $\mathcal{O}_C$-modules and $\phi:\mathcal{F} \to \mathcal{G}$ be a morphism of $\mathcal{O}_C$-modules. Suppose further that $\mathcal{F}$ is locally free. Is it true that the kernel of $\phi$ is also locally free?

A: You ask if every submodule of a locally free module $F$ is again locally free. Of course this fails. First of all, this submodule doesn't have to be quasi-coherent. But even when it is quasi-coherent, and we therefore may pass to affine covers, it fails even for $F=\mathcal{O}$, i.e. not every quasi-coherent ideal is locally free. For this it would have to be zero or invertible.

A: If you assume the curve smooth, then yes. This is because for a smooth curve, the local rings $\mathcal O_{X,x}$ are DVRs or fields, e.g. PIDs. In particular, a submodule of a free module over a PID is again free. Therefore, the exact sequence
$$
0 \to \ker \varphi \to \mathcal F \to \mathcal G
$$
can be seen at the stalks as the sequence
$$
0 \to \ker \varphi_x \to \mathcal O_{X,x}^{\oplus I} \to \mathcal G_x.
$$
where $I$ is some index set. Therefore $\ker \varphi_x$ is free for each $x \in X$, which means $\ker \varphi$ is locally free.
Of course not all curves are smooth, so with non-smooth curves you get counter-examples.
Another situation where the answer is "yes" is when $\varphi : \mathcal F \to \mathcal G$ is surjective and $\mathcal G$ is locally free. This is because looking at the exact sequence at the stalks, since $\mathcal G_x$ is free, it is projective, thus the exact sequence splits ; in particular, $\ker \varphi_x$ is projective. But a projective module over a local ring is free, so that $\ker \varphi_x$ is free for all $x \in X$.
Hope that helps,


text:
Q: Is it possible to deploy a Node.js application to Heroku without a web dyno? For some backstory and reference, here are some quotes from a few Heroku documentation pages.
From the Heroku Node.js Support > Activation:

The Heroku Node.js buildpack is employed when the application has a package.json file in the root directory.

From Heroku Node.js Support > Default web process type:

First, Heroku looks for a Procfile specifying your process types.
If no Procfile is present in the root directory of your app during the build process, your web process will be started by running npm start, [...]

From Process Types and the Procfile > Process types as templates:

A Procfile contains a number of process type declarations, each on a new line. Each process type is a declaration of a command that is executed when a dyno of that process type is started.
For example, if a web process type is declared, then when a dyno of this type is started, the command associated with the web process type, will be executed. This could mean starting a web server, for example.

I have a package.json file in the root (which will activate the Node.js buildpack), and I've also included a Procfile in the root with the following contents:
service: npm start

I would assume that not defining a web dyno would cause it to not be created; only the service dyno should be created, following the configuration declared in the Procfile.
Instead, what happened is that an active web dyno was automatically created using npm start and an inactive service dyno was created using the definition in Procfile. I then had to:

*

*heroku ps:scale web=0

*heroku ps:scale service=1
I can definitely imagine wanting to run a Node.js "service" application on Heroku that does not accept any incoming connections, only making outgoing ones. Is there a way to configure the Node.js buildpack to not automatically create a web dyno when one is not defined? I've looked through lots of documentation looking for a way to either: (1) define it as such or (2) remove the automatically generated web dyno; but, I haven't found anything.
Thanks for the help!

A: I just ran into the same problem and worked it around doing this in my Procfile after reading Shibumi's answer:
web: echo "useless"
service: node index.js

A: I ended up opening a helpdesk ticket with Heroku on this one. Got a response from them, so I'll post it here. Thanks Heroku support!

The short answer is that, no, currently you'll need to heroku scale web=0 service=1 in order to run a service without a public web process. For a longer explanation:
Early on, the Node.js Buildpack checked for the presence of a Procfile and, if missing, created a default one with web: npm start. This made it easy to create apps without a web process, since you could just provide a Procfile that defined some processes, omitting web from the list.
However, as more and more users needed arrays of buildpacks instead of a single one, that solution created issues. Node is the most popular first buildpack, since it's frequently used by Java, Python, PHP, and Ruby apps to build front-end assets. Whenever an app without a Procfile ran Node first, and another buildpack second, Node would inject its own default Procfile (web: npm start), and the second buildpack would then not create its default Procfile as one already existed in the filesystem. So injecting a default Procfile when one is missing from the app creates problems downstream for multilingual apps.
So, we stopped creating a default Procfile and instead used default_process_types in bin/release. This fixes the issue of subsequent buildpacks inheriting incorrect default Procfiles, but since default_process_types is extended rather than replaced by the Procfile process list, apps without a web process defined in their Procfile will get the default web process merged in. This is why web appears even without a web entry in Procfile.
We also don't want to surprise any customers with unexpected bills. Some apps have many process types, some of which are only to be run occasionally, some limited to a single instance, some which need to be scaled up and down, etc, so defaulting everything to 1 rather than 0 could cause extra billing as well as app malfunctions. This is why non-web processes are scaled to zero by default.


text:
Q: A data race and safe publication @State
@JCStressTest
public class M {
    class A {
        int f;
        A() {
            f = 42;
        }
    }
    private A a;

    @Actor
    void actor1(){
        a = new A();
    }
    @Actor
    void actor2(IntResult1 r){
        r.r1 = 1;
        if(a != null){
            r.r1 = a.f;
        }
    }
}

I tested it with a jcstress and I cannot get the output 0. I know that is is not obvious that I should see that output, but it's possible and I would like to see it. Is there any JVM option (like XX:....) to enforce it?

A:
I know that is is not obvious that I should see that output, but it's possible and I would like to see it.

You are correct that your code does have a data race.
(There is no happens-before chain between f = 42 and ... = a.f deducible under the rules set out in the JMM.  Therefore, it is not guaranteed that a.f will always see the value 42.)
However, the nature of this race is such that it will only occur in extremely rare scenarios.  It would most likely require a system with multiple cores, and either high memory load or an involuntary thread context switch at just the wrong instant.  And it would be dependent on the native code emitted by the JIT compiler1.

Is there any JVM option (like XX:....) to enforce it?

Unfortunately, no there isn't.

1 - Note you cannot draw sound inferences from the bytecodes.  The JIT compiler is allowed (by the JLS / JVMS) to reorder instructions including memory reads and writes provided that they don't violate the JMM rules.  This is important for performance of multi-threaded  code.


text:
Q: Insert text file to JAR using php I made a j2me code and extracted the jar file ..... jar file will be downloaded online and I need to insert data generated automatically for every download which I can deal with it from J2me code .
Thanks in advance.

A: You just have to create the new jar file the same way you would create a zip file (ex. Here )
If your jar archive is signed, beware that code signing verification fails if content is modified.


text:
Q: How to find and replace a character and apply on a large file I am trying to replace a certain character found in convert.txt. Now, every characters found in convert.txt will replace into a linefeed in a file.
I have this code:
for /f "delims=" %%s in (convert.txt) do (
    Type c:\PETER\%%a  | repl.bat "\%%s" "%%s\n" X > c:\PETER\%%a
  )

I tried to use the replace.bat suggestion on this page see here. Now, when I am trying to replace a large file's character into a line feed, the output is not complete. Do we have a limit on this case?

A: As MC ND said in his comment, you cannot simultaneously read and write to the same file. You must write to a new file, and then replace the original with the new using MOVE.
for /f "delims=" %%s in (convert.txt) do (
  type "c:\PETER\%%a"  | repl.bat "\%%s" "%%s\n" X > "c:\PETER\%%a.new"
  move /y "c:\PETER\%%a.new" "c:\PETER\%%a" >nul
)

The MOVE operation is nearly instantaneous, no matter what the file size.


text:
Q: Visual C# 2010 Express Edition Build Application Not Correct OK, so I am making a sample Tic-Tac-Toe game.  I then go to build my application, and everything works correctly.  I then go to make some changes, and the changes don't register.  For example, I delete a button in the Form1.Designer file, but when I build it, it still shows the button I deleted.  Or when I change the value of a int variable, it still shows the previous value upon building the application.  This has happened multiple times, and I am really getting frustrated.  Any help is appreciated.

A: Nvm, I figured it out.  The problem was with the debug build, so I deleted it and rebuilt my program- and voila!  It worked.  If anyone else has this problem, navigate to your project folder and head over to the debug folder.  Then delete the contents, and rebuild!  It should work, as it did for me.


text:
Q: Double-slit experiment: electrons 'everywhen'? Non-scientist here trying to get my head around the double slit experiment.
If whilst exhibiting wave-like behaviour electrons are potentially in more than one place at once, and if time is a dimension just as the spatial dimensions are dimensions (correct me if I'm wrong), then why whilst exhibiting wave-like behaviour would electrons not also be potentially in more than one time at once? And if they can be, wouldn't that explain the irrelevance of intervals when it comes to the appearance of the interference pattern? They're not only everywhere but everywhen, so to speak. The act of observation would then not only force the electron to be in a particular place but in a particular time. Or am I so far off that I need to go back to school? (Only did science up to GCSE level many years ago.) ;)
Perhaps a clearer way to ask this is: why is uncertainty limited to spatial dimensions, and generally not considered in the time dimension?

A: Electrons are not everywhere at once. All information about the electron is encoded in a function $\psi (x, y, z, t) $. And there is no hidden information about the electron other than this (at least not in the standard interpretation).
$|\psi (x, y, z, t) |^2$ is the probability density of observing the electron at the point $(x, y, z) $ at time $t$. Note that:
$$\int |\psi (x, y, z, t) |^2 dxdydz=1$$
for a fixed time $t$. So if you simultaneously conducted position measurements at all space locations, the probability of you finding the particle would be 1. The information about a particle is uncertain in space, but not uncertain in time.
It is not true that:
$$\int |\psi (x, y, z, t) |^2 dxdydzdt=1$$
If your hypothesis was right, the above equation would have been true. Position is a probabilistic observable in Quantum Mechanics. Time is only a parameter.

if time is a dimension just as the spatial dimensions are dimensions

Time and space should be treated equally in a relativistic theory. The theory I described above is a non-relativistic theory.
In the Relativistic theory, called Quantum Field Theory, both space and time become parameters instead of observables. They appear as parameters of Operator Fields which are mathematical objects defined at every point of spacetime.

A: In quantum mechanics, time is not a dimension, it's a universal parameter (involved in the evolution of states/operators depending upon your so-called picture). Also in quantum mechanics, the electron is a particle described by a wave function. The wave function can go through both slits but what does that mean for a particle? That question is the point of the experiment.
Of course, time is not a parameter. Quantum mechanics is a (mostly) non-relativistic approximation. Incorporating relativity leads to quantum field theory, where there are no particles. Quantum fields permeate space-time, and an electron is quanta of that field.
Since computations are so difficult, we usually think in approximations. There is an initial state: incoming free particle electron, a final state: outgoing free particle electron detected at the screen. The electron takes all possible paths between the two (Feynman's path integral formulation), and we can calculate the scattering matrix describing it.
In that picture, there really is no mystery: beam impinges on target and scatters to a detector.


text:
Q: Order By RegExp Without Function in MySQL? I need to order a varchar column in the following way: 100, 110, 120, [...] 1490, 1495, 1495.1, 1495.2, 1495.3, etc.
With help from another question, I created this function:
    CREATE FUNCTION isNumeric(value VARCHAR(1024))
    RETURNS TINYINT(1) DETERMINISTIC
    RETURN value REGEXP '^(-|\\+)?([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';

And then added this to my query:
    ORDER BY isNumeric(ItemCode) DESC, CASE WHEN isNumeric(ItemCode) = 1 THEN CAST(ItemCode as UNSIGNED) ELSE NULL END, ItemCode

It worked great. Unfortunately, when I tried this on the live server, I wasn't able to create the function. "Column count of mysql.proc is wrong. Expected 20, found 16. Created with MySQL 50067, now running 50147. Please use mysql_upgrade to fix this error." My boss says we can't run an update in case it breaks something, so I was hoping someone could help me achieve the same thing without a function. Thanks!

A:     ORDER BY ABS(ItemCode)

That worked for me. Thanks M Khalid.


text:
Q: Пространство имен в XML (xmlns:mvc) Изучаю новый фреймоврк(SAPUI5), в нем используется представление в виде XML, прочитал немного про XML:
xmlns:mvc - это же пространоство имен mvc, которые используется в корне проекта, но чуть выше используется xmlns - просто без префикса. Обьясните пожалуйста какое пространство имен будет у дочерних элементов?

A: Немного не понял вопрос.
С помощью XMLNS задаем пространство имен.
xmlns="sap.m" //будет NS по умелчанию
xmlns:mvc="sap.ui.core.mvc"

Т.е. Это будет развернуто в:
lable -> sap.m.lable
button -> sap.m.button
mvc:view -> sap.ui.core.mvc.view
xmlns:html в рамках XMLView смысла не имеет.


text:
Q: Http Session expiration When accessing a specific website I observe a "jsessionid" on the client side.
This identifier is used to identify the session with the server.
When does this session expire? Only when the client is inactive for a timeout-period? Or also after a fixed time (,which might be longer, say 30min.)?
Is there anyway to find out the timeout-period from the client side?
Also, is there a way to check whether the session is active?
Unfortunately, I don't know much about server side development and I could not find a clear answer in the web.


text:
Q: How to auto fill date after selecting current date and number of years I have 2 text fields and 1 drop down box, if I have selected date in first text box after that I have to select number of year from drop down.
So how can I auto fill the next date in second text box of that selected no of year from drop down.
this is text box code

    <input type="text" name="purchese_date" id="tbDate" class="pwaf form-control" value="<?php echo isset($_POST['purchese_date']) ? $_POST['purchese_date'] : '' ?>" placeholder="Enter Purchese Date eg:dd/mm/yyyy"/>

    <select class="form-control pwafs" name="year">
        <option value="#">- Select Year-</option>
        <option value="1"> 1</option>
        <option value="2"> 2</option>
        <option value="3"> 3</option>
        <option value="4"> 4</option>
        <option value="5"> 5</option>
        <option value="6"> 6</option>
        <option value="7"> 7</option>
        <option value="8"> 8</option>
        <option value="9"> 9</option>
        <option value="10"> 10</option>
    </select>

    <input type="text" name="renual_date" id="tbDate" class="form-control pwafr" value="<?php echo isset($_POST['renual_date']) ? $_POST['renual_date'] : '' ?>" placeholder="Enter Renual Date eg:dd/mm/yyyy"/>

    <input type="text" name="customer_id" id="tbDate" class="form-control" value="<?php echo isset($_POST['customer_id']) ? $_POST['customer_id'] : '' ?>" placeholder="Enter Customer Id"/>

this is php code
 <?php
    $domains = new domains;
    if (isset($_POST['add-domain'])) {

        //print_r($_POST['email']);
        //exit;
        $errors = $domains->validate_domains_members();
        if (count($errors)) {
            $emsg = $errors;
            $eclass = "alert-danger";
        } else {

            if ($domains->save($domains->table, $_POST)) {
                unset($_POST);
                $emsg = "User Added Successfully";
                $eclass = "alert-success";
            }
        }
    }
?>
<?php if (isset($emsg)) { ?>
    <div class="alert <?php echo $eclass; ?>"><?php echo $emsg; ?>

<?php } ?>

A: try this
$(".pwafs").change(function(){
        //alert("ok");
        //alert($(".pwaf").val());
        var date = $(".pwaf").val();
        var year = date.replace("/", "");
        var year2 = year.replace("/", "");
        var year3 = year2.substring(4, year2);
        var add = +year3 + +$(this).val();
        var final = date.slice(0,-4);
        //alert(final+add);
        $(".pwafr").val(final+add);
    })


text:
Q: Probability of reception from n users Say I have 4 boxes on the ground. At every time interval the nth user(n = 1,2,3...) has some probability of throwing 0, 1, 2, 3, or 4 balls into the boxes. Each box can only hold one ball, and the probability of throwing each ball is p0 for 0, p1 for 1, p2 for 2, p3 for 3, and p4 for 4. p0+p1+p2+p3+p4 = 100% and p0, p1, p2, p3, p4 are constant. If the boxes each have a ball in them, any subsequent balls will bounce off and be lost. Closer throwers' balls always land in the boxes before subsequent users. So my question is what is the probability that the nth user will be able to land at least 1 ball in a box after m tries. My first instinct is to use a Poisson distribution, but I have a feeling it's not quite appropriate.
Thanks in advance.


text:
Q: Algorithm not supported - OAuth in Gentics Mesh I'm using the new OAuth support in Gentics Mesh, but getting an exception -
ecms-mesh-server     | 23:57:42.312 [] INFO  [vert.x-eventloop-thread-4] [i.v.e.w.h.i.LoggerHandlerImpl] - 192.168.16.4 - GET /api/v2/auth/me HTTP/1.1 200 587 - 7 ms
ecms-mesh-server     | 23:58:09.374 [] DEBUG [vert.x-eventloop-thread-4] [c.g.m.a.p.MeshJWTAuthProvider] - Could not authenticate token.
ecms-mesh-server     | java.lang.RuntimeException: Algorithm not supported
ecms-mesh-server     |  at io.vertx.ext.jwt.JWT.decode(JWT.java:280)
ecms-mesh-server     |  at io.vertx.ext.auth.jwt.impl.JWTAuthProviderImpl.authenticate(JWTAuthProviderImpl.java:122)
ecms-mesh-server     |  at com.gentics.mesh.auth.provider.MeshJWTAuthProvider.authenticateJWT(MeshJWTAuthProvider.java:90)
ecms-mesh-server     |  at com.gentics.mesh.auth.handler.MeshJWTAuthHandler.handleJWTAuth(MeshJWTAuthHandler.java:152)
ecms-mesh-server     |  at com.gentics.mesh.auth.handler.MeshJWTAuthHandler.handle(MeshJWTAuthHandler.java:89)
ecms-mesh-server     |  at com.gentics.mesh.auth.MeshAuthChain.lambda$secure$0(MeshAuthChain.java:40)
ecms-mesh-server     |  at io.vertx.ext.web.impl.RouteImpl.handleContext(RouteImpl.java:231)

I'm running the server in docker, with a Spring Boot Gateway in front, using the Token Relay Filter.
I can access Mesh through the gateway fine, if I'm anonymous or authenticated by Mesh.
But if I authenticate with Okta, and the gateway passes my token to Mesh, I get the exception...
I've added a file /config/public-keys.json with the contents of my Okta public keys.

Update:
I can confirm in the logs that my public keys are being picked up, because the debug output matches my /config/public-keys.json contents.
ecms-mesh-server     | 00:19:55.101 [] DEBUG [vert.x-eventloop-thread-0] [c.g.m.a.MeshOAuth2ServiceImpl] - {
ecms-mesh-server     |   "kty" : "RSA",
ecms-mesh-server     |   "alg" : "RS256",
ecms-mesh-server     |   "kid" : "u13712iLhUmkpeREecKaQhPvZvuImdNVWGJwAmgU-SM",
ecms-mesh-server     |   "use" : "sig",
ecms-mesh-server     |   "e" : "AQAB",
ecms-mesh-server     |   "n" : "vw5G7FUjegmT_BybIfgDWr..."
ecms-mesh-server     | }
ecms-mesh-server     | 00:19:55.101 [] DEBUG [vert.x-eventloop-thread-0] [c.g.m.a.MeshOAuth2ServiceImpl] - {
ecms-mesh-server     |   "kty" : "RSA",
ecms-mesh-server     |   "alg" : "RS256",
ecms-mesh-server     |   "kid" : "DzmghgcUAcXhxL-LeF3qJqefqeQpHR4BSHUoSY7m3FU",
ecms-mesh-server     |   "use" : "sig",
ecms-mesh-server     |   "e" : "AQAB",
ecms-mesh-server     |   "n" : "4yosHHYoEW6wqqOso5qfDONqLw2MK..."
ecms-mesh-server     | }
ecms-mesh-server     | 00:19:55.102 [] DEBUG [vert.x-eventloop-thread-0] [c.g.m.a.AuthHandlerContainer] - Keys changed. Creating a new auth handler to be used.

A: I noticed the token's "kid" parameter in the header, did not have a matching "kid" in the public key list.
I was using the wrong authorization servers JWKs... wow. Heh.
I had this -
https://dev-xxxxxx.okta.com/oauth2/v1/keys
When it should have been this -
https://dev-xxxxxx.okta.com/oauth2/default/v1/keys
Hope this helps someone else.


text:
Q: How to calculate audio metrics through parselmouth on a subsequence of audio I am using parselmouth (wrapper around praat) to extract intensity and pitch features by doing so:
snd = parselmouth.Sound(path)

intensity = snd.to_intensity()
pitch = snd.to_pitch()

However, the audio file contains long sequences of silences, which I would like to remove before I calculate these audio metrics. I am able to remove the silences by processing the numpy array returned by reading the audio through the wave package (and applying some logic), but am not able to pass the new array to parselmouth.
I am even open to providing startTime and endTime parameters to parselmouth, but cannot find documentation that supports that either.

A: There are two options that might be useful for this situation:

*

*You can create a parselmouth.Sound from samples rather than reading from file. There's a constructor taking a NumPy array (or a list/iterable convertible to NumpyArray) and sampling frequency

*A Parselmouth Sound also has a method Sound.extract_part (equivalent to Praat's "Extract part..." button in the UI) that allows you to extract fragments (optionally even windowed with a different window shape than a rectangular window).

Do note that you will likely want to leave a bit or margin when removing silences, because 1) both the intensity and pitch analyses use a sliding window of a certain size (so if you don't leave a margin, some of the windows will be over 'discontinous speech'), and 2) the pitch analysis uses a heuristic to keep a +- continuous pitch contour (so if you don't leave a margin where silence/the absence of voicing is detected, neighboring fragments' pitch estimates will influence each other).


text:
Q: Python- Why does it say password denied even when I enter a password that should work?
userpass= input('Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter=0
lowercounter=0
numbercounter=0
for i in range(len(userpass)):

    if userpass[i].isupper():
        uppercounter=uppercounter+1
        print(uppercounter)
        if uppercounter > 0:
            print("working")
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].islower():
        lowercounter=lowercounter+1
        print(lowercounter)
        if lowercounter > 0:
            print('working')
    else:
        print('Password Denied')
        raise SystemExit(0)

    if userpass[i].isnumeric():
        numbercounter=numbercounter+1
        print(numbercounter)
        if numbercounter > 0:
            print("working")
            print("Password Accepted")
    else:
        print('Password Denied')
        raise SystemExit(0)

I'm trying to make a program for a password that must contain one uppercase letter, one lowercase letter, and one number. But the if statements don't seem to be working properly and whenever I enter a password like "Py11", it says password denied.

A: For every char of the password you are checking againt all three conditions:
lets say you typed in: "hi"
for the first loop you'll be in letter "h"
if it is upper (which is not) your else you be executed running the password denied part (thats the problem)
In order to acomplish what you want I suggest checking like this:
if condition1:
    pass #add here the counting you are making
elif condition2:
    pass #add here the counting you are making
elif condition3:
    pass #add here the counting you are making
# [...]
else:
    print("password denied")

and for the conditions you check for upper, lower, numeric and if you want to allow special chars you need to check for them also
Other way you could do it:
userpass= input('Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter=0
lowercounter=0
numbercounter=0
for i in range(len(userpass)):
    if userpass[i].isupper():
        uppercounter=uppercounter+1
    if userpass[i].islower():
        lowercounter=lowercounter+1
    if userpass[i].isnumeric():
        numbercounter=numbercounter+1
if uppercounter == 0 or lowercounter == 0 or numbercounter == 0:
    print("Password denied")
    raise SystemExit(0)

this way you don't have to check against other special chars

A: Because your logic is wrong.
So first, you're entering the Py11 password and it enters the first if statement.
Your loop takes first value is P from Py11. When it goes to second if statement, it immediately goes to else statement of second if statement because the value is still P.
I tried not to modify your code so much but you could try this way:
userpass = input(
    'Enter a password with at least one uppercase letter, one lowercase letter, and one number: ')
uppercounter = 0
lowercounter = 0
numbercounter = 0
for i in range(len(userpass)):
    print(userpass[i])
    if userpass[i].isupper():
        uppercounter = uppercounter+1
        print(uppercounter)
        if uppercounter > 0:
            print("working")
    elif userpass[i].islower():
        lowercounter = lowercounter+1
        print(lowercounter)
        if lowercounter > 0:
            print('working')
    elif userpass[i].isnumeric():
        numbercounter = numbercounter+1
        print(numbercounter)
        if numbercounter > 0:
            print("working")

if uppercounter <= 0 or lowercounter <= 0 or numbercounter <= 0:
    print('Password Denied')
    raise SystemExit(0)
else:
    print("Password Accepted")


text:
Q: Java how to continue current loop when condition is false I am having an issue whereby whenever input validation is incorrect it breaks out of my current loop and continues with the next method can anyone help me so that when condition is false it re-asks for the same input until it meets the condition. Here's my source code for my method class
public class Student {
    public int gradePt;
    public int i;
    public int credSum = 0;
    public double gradeCredSum = 0;
    public double gpa;
    String [] moduleName;
    String [] moduleGrade;
    int [] moduleCred ;
    Module[] modules;

    public void createModules(){

        getModuleNo();

         modules = new Module[i];
         moduleName = new String[i];
         moduleGrade = new String[i];
         moduleCred = new int[i];

         getModule();
         getGrade();
         getCred();

    for (int j = 0; j < modules.length; j++) {

       modules[j] = new Module(moduleName[j],moduleCred[j],moduleGrade[j]);
       }
    }

    public void getModuleNo(){
        do{
     String input  = JOptionPane.showInputDialog(null,
             "How many modules did you take?","Input");
           int a  = Integer.parseInt(input);
           if (a<1 || a>8){
               JOptionPane.showMessageDialog(null,
                       "Invalid input please enter a number greater than 0",
                       "Error",JOptionPane.ERROR_MESSAGE);
               break;
    }      i = a;
        }while(i<1 || i>8);

}
    public void getModule(){
        for (int i=0;i<moduleName.length;i++){
             String input = JOptionPane.showInputDialog(null,
                    "Enter the name of module #"+(i+1));
             moduleName[i] = input;
             if (input == ""){
                 JOptionPane.showMessageDialog(null,
                         "Invalid input, module name cannot be blank","Error",JOptionPane.ERROR_MESSAGE);
                 break;
       }
    }

    }
    public void getGrade(){
        for (int i=0;i<moduleGrade.length;i++){
            String input = JOptionPane.showInputDialog(null,
                    "Enter grade (A,B,C,D,F) for module #"+(i+1));
             moduleGrade[i] = input;
             if (!"A".equals(input) && !"B".equals(input) && !"C".equals(input) && !"D".equals(input) &&
                     !"F".equals(input) && !"a".equals(input) && !"b".equals(input) && input!="c" &&
                     !"d".equals(input) && !"f".equals(input)){
                 JOptionPane.showMessageDialog(null,
                         "Invalid input!"+"\n"+"Please enter A,B,C,D or F","Error",JOptionPane.ERROR_MESSAGE);
                 break;
             }
             moduleGrade[i] = input;
      }
    }
    public void getCred(){

        for (int i=0;i<moduleCred.length;i++){
            String input = JOptionPane.showInputDialog(null,
                    "Enter credit units for module #"+(i+1));
             moduleCred[i] = Integer.parseInt(input);
             if (moduleCred[i]<1 || moduleCred[i]>8){
                 JOptionPane.showMessageDialog(null,
                         "Invalid input!"+"\n"+"Please enter a number form 1 to 8","Error",JOptionPane.ERROR_MESSAGE);
                 break;
             }

        }
    }

A: This is a common process.  You keep asking for input, checking it each time until the input is valid.
Pseudocode:
repeat
  display("Please enter your input: ")
  input <- getInput()
until (isValid(input))

A: I count four getter methods where you use a JOptionPane to gather user input.  In the code snippet below, I have refactored getGrade() such that it continues to prompt the user for input, for a given module grade, until valid input is received.
While the fix for your three other methods is not given here, you can try following a similar pattern.
public void getGrade() {
    String invalidInputMsg = "Invalid input!" + "\n" + "Please enter A,B,C,D or F";
    for (int i=0; i < moduleGrade.length; i++) {
        do {
            String enterGradeMsg = "Enter grade (A,B,C,D,F) for module #" + (i+1)";
            String input = JOptionPane.showInputDialog(null, enterGradeMsg);
            if (input.length() == 1 &&
                "ABCDF".indexOf(input.toUpperCase().charAt(0)) != -1) {
                moduleGrade[i] = input;
                break;
            }
            else {
                JOptionPane.showMessageDialog(null, invalidInputMsg, "Error",
                                              JOptionPane.ERROR_MESSAGE);
            }
        } while(true);
    }
}

If the input be valid, then break will end the do loop, and the next value of i will be used in the for loop, should it be available.  If the input be invalid, then the do loop will continue and prompt the user again for input.

A: There are many loops in your program asking for input. so here is some code for your problem
boolean inputOk=false;
    BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

    do{
        // ask for input
        System.out.println("Enter the value");

        // capture input
        String input = reader.readLine();

        // evaluate input
        if(input.equals("ok"))
            inputOk = true;         // set flag if input is ok

    }while(!inputOk);               // if flag is ok then exit loop


text:
Q: How to code a method to return 2 different arrays to another class? i have a code with 4 class, Deck, Card, Player and Test.
My idea is create a blackjack game where a Player have your "hands" with cards provided by deck.
My code is working, but i want only 1 method to return 2 different arrays.
Resume of my code:
Card: a card(value,suit)
Deck: create a array of cards with 52 cards. a class with method provideCards() to get cards for players.
Player: a class with array of cards "hands"
Where is the problem?
Look the class "Deck" i'm using 2 methods, provideCards() and provideNewCards(), both methods are equals however returning different arrays for each player.
I can't use in my method provideCards() " ArrayList player = new ArrayList<>();
" because i need save my old array to add a new card before. How can I code only 1 method to return 1 array of "hands" for each player?
My code:
Deck Class:
    package jamilzin.cassino;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Random;

 // /*
   public class Deck {
    private ArrayList<Card> deck = new ArrayList<>();
    public  ArrayList<Card> playerA = new ArrayList<>();
    public  ArrayList<Card> playerB = new ArrayList<>();

    private ArrayList<String> suits = new ArrayList(Arrays.asList(" Diamonds", " Clubs", " Spades", " Hearts"));
    Random gerador = new Random();

    public Deck(){
  for(int j=0; j<suits.size(); j++){ // Idea: create a 13 cards for each suits
      for(int i=0; i<13; i++){
 deck.add(new Card((i + 1), suits.get(j)));
    } // for i
  } // for j
   Collections.shuffle(deck); // randomize the deck
} // deck()

public ArrayList<Card> provideCards(){
   int  number = gerador.nextInt(52);
   while(deck.get(number)==null){
        number = gerador.nextInt(52);}
   Card card = (deck.get(number));
  playerA.add(card);
   deck.set(number, null);
        return  playerA ;}

public ArrayList<Card> provideNewCards(){
   int  number = gerador.nextInt(52);
   while(deck.get(number)==null){
        number = gerador.nextInt(52);}
   Card card = (deck.get(number));
  playerB.add(card);
   deck.set(number, null);
        return  playerB ;}

@Override
public String toString(){
    return deck.toString();
    }
   }

Card Class:
package jamilzin.cassino;

public class Card {

    private String suit;
    private int value;

    Card(int value, String suit){
    this.value = value;
    this.suit = suit;
    }

    public String getSuit() {
        return suit;
    }

    public int getValue() {
        return value;
    }

    @Override
    public String toString() {
     return getValue() + getSuit();
    //return Integer.toString(getValue());
}
}

Player Class:
package jamilzin.cassino;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.*;
public class Player {
 ArrayList<Card>  hands = new ArrayList<>();

   public Player(){
this.hands = new ArrayList<>();
    }

    public ArrayList<Card> getHands() {
    return hands;
    }

    public void setHands(ArrayList<Card> hands) {
        this.hands = hands;
    }
}

Test Class:
package jamilzin.cassino;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Cassino {

    public static void main(String[] args) {
 Deck deckMaster = new Deck();
Player PlayerA = new Player();
Player PlayerB = new Player();
for(int i=1;i<=5;i++){
 PlayerA.setHands(deckMaster.provideCards());}
for(int i=1;i<=5;i++){
PlayerB.setHands(deckMaster.provideNewCards());}

        System.out.println(PlayerA.getHands());
        System.out.println(PlayerB.getHands());

        System.out.println(deckMaster);
    }
 }

class Test results: Run Project result

A: Enum Suit
public enum Suit {
    DIAMONDS, CLUBS, SPADES, HEARTS
}

Cassino
public class Cassino {
    public static void main(String[] args) {
        Blackjack game = new Blackjack(2);

        System.out.println(game);
    }
}

Blackjack
public class Blackjack {
    private final Player[] players;
    private final Deck deck;

    public Blackjack(int player) {
        this.players = createPlayer(player);
        this.deck = new Deck();
    }

    public Player[] createPlayer(int player){
        Player[] players = new Player[player];
        for (int i = 0; i < player; i++) {
            List<Card> cards = new ArrayList<>();
            for (int j = 0; j < 5; j++) {
                cards.add(deck.provideCard());
            }
            players[i] = new Player(cards);
        }
        return players;
    }

    public Player[] getPlayers() {
        return players.clone();
    }

    public Deck getDeck() {
        return deck;
    }

    @Override
    public String toString() {
        return "Blackjack{" +
                "players=" + Arrays.toString(players) +
                ", deck=" + deck +
                '}';
    }
}

Deck
public class Deck {
    private final LinkedList<Card> deck;

    public Deck() {
        Suit[] suits = Suit.values();
        List<Card> cards = new ArrayList<>();
        for (Suit suit : suits) { // Idea: create a 13 cards for each suits
            for (int j = 0; j < 13; j++) {
                cards.add(new Card((j + 1), suit));
            }
        }
        Collections.shuffle(cards); // randomize the deck
        deck = new LinkedList<>(cards) {
        };
    } // deck()

    public Card provideCard() {
        return deck.pollFirst();
    }

    @Override
    public String toString() {
        return "Deck{" +
                "deck=" + deck +
                '}';
    }
}

Card
    public class Card {
    private final Suit suit;
    private final int value;

    Card(int value, Suit suit) {
        this.value = value;
        this.suit = suit;
    }

    public Suit getSuit() {
        return suit;
    }

    public int getValue() {
        return value;
    }

    @Override
    public String toString() {
        return getValue() + getSuit().toString();
        //return Integer.toString(getValue());
    }
}

Player
    public class Player {
    List<Card> hand;

    public Player(List<Card> cards) {
        this.hand = cards;
    }

    public List<Card> getHand() {
        return hand;
    }

    public void setHand(List<Card> hand) {
        this.hand = hand;
    }

    public void addToHand(Card card){
        this.hand.add(card);
    }

    @Override
    public String toString() {
        return "Player{" +
                "hand=" + hand +
                '}';
    }
}

Some Recommendations

*

*Use the more general type for your variables and methods as you can, because it doesn't change the logic if you would use an LinkedList instaed

*You don't need Random because your deck is already shuffeld so you don't need to get a random one of the shuffeld list.  Instead you should use a explicit LinkedList this will offer you the methode pollFirst which polls out the first/head of the list and reduce the list aka you deck.

*Suits should be an Enum and not a List of strings because it is a not changing enumeration. So new Enum Suits.

*Is there a reason why the hand of the players should not be in the player class?

*And you need more classes to give the game a structure for the logic and things like that


text:
Q: How to perform JSF setPropertyActionListener before javascript onclick event Here is the deal: I have a dataTable populated by a list in my managed bean. What I want is to open a simple primefaces dialog with the selected object's infos and I am trying to do so by using a setPropertyActionListener and a onclick event.
                <p:commandButton id="basic" value="Resumo" onclick="dlg1.show();"
                                 type="button"

                                 >
                    <f:setPropertyActionListener target="#{consultaArtigoBean.artigoSelecionado}"
                                                 value="#{artigo}" />

                </p:commandButton>

And the dialog
        <p:dialog id="basicDialog" header="Resumo - #{consultaArtigoBean.artigoSelecionado.titulo}"
                  widgetVar="dlg1"
                  dynamic="true">
            #{consultaArtigoBean.artigoSelecionado.resumo}
        </p:dialog>

The thing is that the action performs before the setPropertyActionListener takes effect. So the dialog pops up with no object at all.
What should I do to make sure the setProperty performs before the action thus setting my object.
Update
An other topic here helped answer this.
Pass a value from h:outputLink to JSF after onclick event
and the result is that:
<p:commandLink id="basic" value="Resumo"
                               oncomplete="dlg1.show();"
                               update="@form">
                    <f:setPropertyActionListener target="#{consultaArtigoBean.artigoSelecionado}"
                                                 value="#{artigo}" />

                </p:commandLink>

and the dialog
<p:dialog id="basicDialog" header="Resumo - #{consultaArtigoBean.artigoSelecionado.titulo}"
                  widgetVar="dlg1"
                  dynamic="true">
            #{consultaArtigoBean.artigoSelecionado.resumo}
        </p:dialog>

A: Use the oncomplete attribute which will get fired after the ajax postback.
Further update the dialog via the update attribute.
Execute p:commandLink action before onclick event?


text:
Q: How can I pick a random border color in react? I would love some help with this problem. I'm playing around with react trying to pick a random border-color with each character I print.
This is the code:
const style = {
    padding: '16px',
    margin: '12px',
    border: '*** I want to insert a random color in here***'
    textAlign: 'center',
    display: 'inline-block',
    transition: '0.2s ease-in',
}

Any suggestion on what is the best clean way to do it?

A: Just use Math.random to pick three numbers (and then probably would wanna round down). I feel like generating three numbers under 255 is gonna be eaiser than generating one hex string, since that'd be a pretty big number to generate with a number generator. Just my intuition though, dunno if it would make a perfomance difference.
// just for brevity, I would do this inline in practice.
const random = () => Math.floor(Math.random() * 255));

const style = {
    padding: '16px',
    margin: '12px',
    border: `rgb(${random()}, ${random()}, ${random()})`, // <--
    textAlign: 'center',
    display: 'inline-block',
    transition: '0.2s ease-in',
}

A: From MDN you can get the border styles
Then create a function that gets a random number between 0 and the number of border styles in your array, this number will be the index that you pass to the array of border types using string templates in style object

const borderStyles = ["none", "dotted", "dashed", "solid", "double", "groove"];

function getIndex() {
  return Math.floor(Math.random() * borderStyles.length);
}

const style = {
  padding: "16px",
  margin: "12px",
  border: `${borderStyles[getIndex()]}`,
  textAlign: "center",
  display: "inline-block",
  transition: "0.2s ease-in",
};

console.log(style.border);

See

*

*https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

A: If you just want to change the color then follow this. I have kept the border width 1px and solid.
var randomColor = '#' + Math.floor(Math.random()*16777215).toString(16);

const style = {
  padding: '16px',
  margin: '12px',
  border: `1px solid ${randomColor}`,
  textAlign: 'center',
  display: 'inline-block',
  transition: '0.2s ease-in',
}

A: there! Well, I think a way you can do it is by first creating three variables with a random number between 0 and 255, and the  assign each value to your style variable. The use interpolation to combine the variables with the strings:
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);

const style = {
//your code
border: `rgb(${r}, ${g}, ${b})`,
//more code
}

I really hope this works!

A: Try the following:-
const style = {
    padding: '16px',
    margin: '12px',
    border: '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16),
    textAlign: 'center',
    display: 'inline-block',
    transition: '0.2s ease-in',
}

A:     const generateColor = () => {
        const CHHAPOLA = Math.floor(Math.random() * 98373737)
          .toString(15)
          .padStart(5,'1','3','5','9','6');
        return `#${CHHAPOLA}`;
      };

<View Style={{bordercolor:generateColor(),borderwidth:1}}>
<Text>HELLO</Text>
</View>


text:
Q: Is there a way to (programatically) tell the difference between an arrow function and regular one? Pretty self explanatory, is there a way to check, in code, the difference between an arrow function an a regular one?
Explaining myself:
I have an array of functions coming in, most are simple arrow functions that return an object, but the rest are regular functions, used as constructors. Is there a way to check whether a function is an arrow or not without being horribly inefficient with pak.map(el => {try {el.unpak = new el.fn} catch(e) {el.unpak = el.fn()}})? The try/catch is an idea I came up with that works, but is horridly slow (since only a handful of functions are actually constructors in this array) and really refuse to use that in any production scenario. Does anyone have any ideas to this?