Scala Implicit class (using implicits inside implicit class) - Not a member of Int error

Question: I want to write a totient-function with scala (recursive).

Euler's totient function counts the positive integers up to a given integer n that are relatively prime to n

I came up with:
object Totient {
  implicit class Improvements(val number: Int) {
    def totient: Int = {
      @tailrec
      def helper(currentN: Int, accumulator: Int): Int =
        if (currentN == 1) accumulator
        else {
          if (number.isDividable(currentN)) helper(currentN - 1, accumulator)
          else helper(currentN - 1, accumulator + 1)
        }
      helper(number, 0)
    }

    private def isDividable(divisor: Int) = number % divisor == 0
  }
}

For readability I created a small function isDividable.
This function I want to use in my recursive helper-method.
Unfortunately I get the following error:
Error:(12, 22) value isDividable is not a member of Int
      if (number.isDividable(currentN)) helper(currentN - 1, accumulator)

Question: Can someone explain to me, what I did wrong and how I can fix it?
Edit:
for completeness I will add the valid implementation of the totient function:
object Totient {
  implicit class Improvements(val number: Int) {
    def totient: Int = {
      @tailrec
      def helper(currentN: Int, accumulator: Int): Int =
        if (currentN == 0) accumulator
        else {
          if (number.isCoprimeTo(currentN)) helper(currentN - 1, accumulator + 1)
          else helper(currentN - 1, accumulator)
        }
      helper(number, 0)
    }

    private[Totient] def isCoprimeTo(otherNumber: Int): Boolean = {
      gcd(number, otherNumber) == 1
    }

    private def gcd(firstNumber: Int, secondNumber: Int): Int =
      if (secondNumber == 0) firstNumber else gcd(secondNumber, firstNumber % secondNumber)
  }
}

Comment: Unfortunately, the implementation of the totient-function here is wrong. `10.totient` should be 4 not 6. But the problem with the `isDividable`-method is solved in the answer below.
Comment: see below `edit` in the question for working/valid implementation
Answer: private without extra information mean here "accessible only by other methods of Improvements but for the same instance of Improvements".
That means you can call isDividable to get the result for the same number for which you call totient/helper, but it doesn't becomes an extension method (because it is not visible outside of Improvements).
To fix that you can change the scope of the method, e.g. to make it visible to all methods defined within Totient:
object Totient {
  implicit class Improvements(val number: Int) {
    def totient: Int = {
      @tailrec
      def helper(currentN: Int, accumulator: Int): Int =
        if (currentN == 1) accumulator
        else {
          if (number.isDividable(currentN)) helper(currentN - 1, accumulator)
          else helper(currentN - 1, accumulator + 1)
        }
      helper(number, 0)
    }

    // notice [Totient] after private
    private[Totient] def isDividable(divisor: Int) = number % divisor == 0
  }
}

This compiles in my ammonite and works:
@ import Totient._
import Totient._

@ 12.totient
res2: Int = 6

Answer: Another option is to call isDividable/isCoprimeTo from this instead of number. This way, the compiler doesn't have to perform an implicit resolution at all to get the method. With your original code:
    def totient: Int = {
      @tailrec
      def helper(currentN: Int, accumulator: Int): Int =
        if (currentN == 1) accumulator
        else {
          if (this.isDividable(currentN)) helper(currentN - 1, accumulator)
          else helper(currentN - 1, accumulator + 1)
        }
      helper(number, 0)
    }

(You can even leave out the call to this entirely and simply have isDividable(currentN), but that makes the code less clear.)


CoreData -> Multiple data stores based on some value

Question: I have an odd need, and I suspect the answer is going to be "it's not meant to work that way", but here goes (and no, I haven't tried this yet) - I need to be able to hit various data stores in CoreData based on the app user's login. Think of an on-call phone that gets handed around to multiple people, each having their own login. So, if Bob has the phone and logs in, it creates/uses a CoreData data store unique to Bob, then when Bob logs out and hands the phone off to Sandy, she logs in and same deal.
I know you provide the name of the CoreData data store in the CoreData initialization code, but I've read a number of articles where people say CoreData gets squirrely if that name isn't the name of the app. Not sure I believe that is true (or STILL true...?), but am I just barking up the wrong tree here?
Thoughts?
Comment: Still true but you can change the url, not ideal but possible
Comment: You can have multiple core data persistent stores and specify a different url but use a single managed object model. You will just need to set up your coordinator [manually](https://developer.apple.com/documentation/coredata/setting_up_a_core_data_stack/setting_up_a_core_data_stack_manually) rather than relying on the coordinator. It might be simpler to have a `userid` field in your entities and just use that in your queries.
Comment: Understood, and that's the way it currently works. There are concerns from management about data isolation, etc., per user, but frankly with the stuff existing under a common user in the phone, I'm not sure I agree with management's worry. Thanks so much.
Answer: It is not required for the Core Data store's name to match the name of the app. In fact, it is possible to have multiple data stores with different names for a single app.
To achieve this, you need to create the NSPersistentContainter providing the data store name and the managed object model.
That is, instead of NSPersistentContainer(name: storeName) initialiser you need the NSPersistentContainer(name: storeName, managedObjectModel: managedObjectModel).
The challenging part is to obtain the NSManagedObjectModel for the current version of the data model, but the snippet below will show you how to do that:
Struct PersistenceController {

    let container: NSPersistentContainer

    init(userName: String,
         inMemory: Bool = false) {

        // Both the store and data model can be any string, for the sake of simplicity lets
        // consider your app's name
        let yourAppName = "YourAppName"

        // Append the userName to your data store name
        let storeName = "\(yourAppName)-\(userName)"

        // This must be the same name as the data model file in your project.
        // Typically is the same as the app's name
        let dataModelName = yourAppName

        // Here you get the managedObjectModel to create the persistent container
        guard let managedObjectModel = NSManagedObjectModel(name: dataModelName) else {
            fatalError("Cannot instantiate NSManagedObjectModel")
        }

        // When you create the persistent container specifying the name and the managed object model,
        // you "decouple" the name of the store from the name of the data model:
        container = NSPersistentContainer(name: storeName, managedObjectModel: managedObjectModel)

        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let error = error as NSError? {
                fatalError("Unresolved error \(error), \(error.userInfo)")
            }
        })

        // Other code required for creating the persistent container goes here,
        // including the creation of the mainContex and any background context you need.
    }
}

extension NSManagedObjectModel {

    convenience init?(name: String) {

        let bundle = Bundle.main
        let dataModelFolder = "\(name).momd"  //Assuming your CoreData model is located in your project's roor directory

        // You need to read the current model version from the VersionInfo.plist file, located in the datamodel folder
        guard let versionPlistUrl = bundle.url(forResource: "VersionInfo",
                                               withExtension: "plist",
                                               subdirectory: dataModelFolder) else { fatalError("VersionInfo.plist doesn't exist") }

        // Here you parse the VersionInfo.plist file to a Dictionary and get the current version name:
        let versionPlist = NSDictionary(contentsOf: versionPlistUrl)
        let currentVersion = versionPlist?.object(forKey: "NSManagedObjectModel_CurrentVersionName") as? String

        // You need the current version model URL to instantiate the managed object model:
        guard let currentModelVersionURL = bundle.url(forResource: currentVersion,
                                                      withExtension: "mom",
                                                      subdirectory: dataModelFolder) else { fatalError("Model not found") }

        // Initialise the model with the url defined above
        self.init(contentsOf: currentModelVersionURL)
    }
}

Comment: Cool, I follow you. Thanks much! As mentioned, this is a discussion at the moment. I see why and how this works, and it seems perfectly solid. I'll mark this as accepted. Thanks!


How to add a directory to the PATH?

Question: How do I add a directory to the $PATH in Ubuntu and make the changes permanent?
Comment: https://help.ubuntu.com/community/EnvironmentVariables There is all you need to know. I found out that a lot of the input here was incorrect or at least the method was not suggested. This is a great piece of information that will let you figure out where to modify your environment variable based on the reason you are doing it and exactly how to do it without screwing everything up (like I did following some of the aforementioned bad advice). So long, and thanks for all the fish!
Answer: Using ~/.profile to set $PATH
A path set in .bash_profile will only be set in a bash login shell (bash -l).
If you put your path in .profile it will be available to your complete desktop session. That means even metacity will use it.
For example ~/.profile:
if [ -d "$HOME/bin" ] ; then
  PATH="$PATH:$HOME/bin"
fi

Btw, you can check the PATH variable of a process by looking at its environment in /proc/[pid]/environ (replace [pid] with the number from ps axf). E.g. use grep -z "^PATH" /proc/[pid]/environ
Note:
bash as a login shell doesn't parse .profile if either .bash_profile or .bash_login exists. From man bash :

it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that
  order, and reads and executes commands from the first one that exists
  and is  readable.

See the answers below for information about .pam_environment, or .bashrc for interactive non-login shells, or set the value globally for all users by putting a script into /etc/profile.d/ or use /etc/X11/Xsession.d/ to affect the display managers session.
Comment: This piece of documentation is very well done: [Official documentation about environment variable](http://help.ubuntu.com/community/EnvironmentVariables#Persistent_environment_variables). Consider reading it (not to say that is updated to the last version of the rules to add values to environment variable).
Comment: On Xbunutu .profile isn't be executed so I put it in .bashrc and it works.
Comment: Cool, that worked. I saw where it will auto add the bin dir if I make it so I just used that instead of scripts. TY.
Comment: I've still got no idea where to add my extra path part to.  I need to add the android SDK to my path... `PATH="$HOME/bin:$PATH"` So I add it to it?
Comment: Keep in mind .profile is used on login and thus you have to logout-login again for it to be used (closing and reopening the terminal is not enough). @JamieHutber the path is `$WHERE_YOU_INSTALLED_THE_SDK/platform-tools` and `$WHERE_YOU_INSTALLED_THE_SDK/tools`
Comment: Where in  .profile do we add the path ??
Comment: Sorry for non-constructive comment but... has anyone an explanation why they had to make it so complicated?
Comment: If you were thinking of using spaces in the PATH statement like: PATH = "... you're in for a treat: Bash will fail to parse it and just respond that PATH isn't a command.
Comment: @LiveWireBT: Could you drop into the [AU general chat](http://chat.stackexchange.com/rooms/201/ask-ubuntu-general-room) and discuss where you got the info from your edit March 7???
Comment: What is this if used for? Can't I just use the inner part?
Comment: ~/.profile still works for Ubuntu 18.04
Comment: When someone sudos as you, .profile doesn't get used.
Comment: On Elementary OS (based on Ubuntu 18.04), `.profile` wasn't being executed. So, I had to put this in `.bashrc`.
Comment: @Display Name  I can relate to that sentiment. I get having system-wide PATH entries as distinct to those available to a given user account., e.g /etc files like profile, bashrc, etc. It's good to be able to add a new PATH entry for the duration of a terminal session: otherwise entries made for packages later discarded will clog it up. But having to set a new entry each time you use a package is also a nuisance. Hence the need for permanent additons to PATH. For a fuller explanation, read https://www.baeldung.com/linux/bashrc-vs-bash-profile-vs-profile  This says nothing about other shells !
Answer: Edit .bashrc in your home directory and add the following line:
export PATH="/path/to/dir:$PATH"

You will need to source your .bashrc or logout/login (or restart the terminal) for the changes to take effect. To source your .bashrc, simply type
$ source ~/.bashrc

Comment: `.bashrc` is not the right place for setting environment variables. They should go in `.profile` or `.pam_environment`. See http://mywiki.wooledge.org/DotFiles
Comment: In bash it is simply '. .bashrc'
Comment: How do you "source your `.bashrc`"? How do you "restart the terminal"?
Comment: @LaoTzu `. .bashrc` not `.bashrc` :) or `source .bashrc` for that matter
Comment: I was making the assumption that you were in your home directory. since that's where the .bashrc you want to edit is.
Comment: True here @Ophidian
Comment: What if $PATH is used before path: `export PATH="$PATH:/path/to/dir"`?
Comment: Before or after is fine, but if you add it to the end then it will have no effect for any executables with naming collisions.  Your copy of an executable will get ignored in favour of one found earlier in the list of directories that make up the PATH.
Comment: Don't forget that ":$PATH" at the end, or you'll have to log into a tty (by using ctrl+alt+F2) and edit it in using /usr/bin/nano .profile Happened to me!
Comment: Tried this but messed all commands from terminal. Whenever trying cd or ls or whatever, it said this was not available and that they could either be invoked with /bin/ls OR added to the PATH. Maybe I misunderstood this solution but to fix this I just undid changed to .bashrc file and restarted pc
Answer: The recommended place to define permanent, system-wide environment variables applying to all users is in:
/etc/environment

(which is where the default PATH is defined)
This will work in desktop or console, gnome-terminal or TTY, rain or shine ;)

To edit, open the terminal and type:
sudoedit /etc/environment

(or open the file using sudo in your favorite text editor)

To make it work without rebooting, run . /etc/environment or source /etc/environment. Since this file is just a simple script it will run and assign the new path to the PATH environment variable. To check run env and see the PATH value in the listing.
Related:

EnvironmentVariables - Community Help Wiki
Comment: and then you need to reboot for changes to take effect...
Comment: To take changes in effect run . /etc/environement (yes, dot, a space and /etc/environment). Since this file is just a simple script it will run and assign the new path to the PATH environment variable. To check run env and see the PATH value in the listing.
Comment: This is exactly what I needed. Provisioning a throw-away vm image via vagrant and needed to add node and npm to the path.
Comment: I needed to run `source /etc/environment` to reload the changes
Comment: @JohnnyAW: source is equivalent to the initial dot, see for example https://en.wikipedia.org/wiki/Source_(command).
Comment: Now that `gksudo` is deprecated, you can just use `sudo`.
Comment: From the linked documentation _"It is not a script file, but rather consists of assignment expressions, one per line. ... Note: Variable expansion does not work in /etc/environment. "_, so it isn't a script and you can't use the variable itself as in `PATH=$PATH:/path`.
Comment: should be the accepted answer, as far as I can tell other ways to set the path, through dot files like `/home/you/.profile` have down-sides.
Comment: Given a /path/to/directory I want to add, is there then a command I can execute to add that, instead of manually editing the file?
Comment: source /etc/environment is needed to patchup with the updates
Answer: I think the canonical way in Ubuntu is:

create a new file under /etc/profile.d/
 sudo vi /etc/profile.d/SCRIPT_NAME.sh

add there:
 export PATH="$PATH:YOUR_PATH_WITHOUT_TRAILING_SLASH"

and give it execute permission
 sudo chmod a+x /etc/profile.d/SCRIPT_NAME.sh

Comment: It is usually safer to add your custom path to the end of PATH instead of the beginning.  This avoids accidentally replacing system commands with your programs (or someone else's malicious programs). This also avoids a lot of confusion when someone else works on your system (or gives you advice) and they get unexpected results from commands you have "replaced".
Comment: It works in my case! I `pip install cmake` but I get "WARNING: The scripts cmake, cpack and ctest are installed in '/home/q/.local/bin' which is not on PATH." So I do your script with `export PATH="$PATH:/home/q/.local/bin"` After reboot it works ok.
Answer: For complete newbies (like I am) who are more comfortable with GUI:

Open your $HOME folder.
Go to View → Show Hidden Files or press Ctrl + H.
Right click on .profile and click on Open With Text Editor.
Scroll to the bottom and add PATH="$PATH:/my/path/foo".
Save.
Log out and log back in to apply changes (let Ubuntu actually load .profile).
Comment: Editing the .profile file is not recommended anymore.You can still use this method to edit the file .pam_environment see: https://help.ubuntu.com/community/EnvironmentVariables
Comment: @Frisbetarian you have to make sure to add the `$PATH:` bit which includes the existing PATH definition
Comment: This answer caused my system to stop logging in due to all paths being overridden. Using Ubuntu 16.04.
Comment: home folder means not the one named home, but the one you go into when you type "cd ~" in terminal
Comment: Thank @PulsarBlow! I'm not really sure what's exactly the difference and the benefit though... This is the direct URL to the relevant section: https://help.ubuntu.com/community/EnvironmentVariables#Session-wide_environment_variables
Comment: @dain : your comment saved my life!
Answer: For persistent environment variables available to particular users only. I highly recommend Ubuntu official documentation.
https://help.ubuntu.com/community/EnvironmentVariables
Referring to documentation above, I have setup my Android SDK path-tools by:

creating ~/.pam_environment file in home directory.
the content of which is PATH DEFAULT=${PATH}:~/android-sdk-linux/tools.
additional custom user path can be added by separating paths with colon (:).
this requires re-login, which means you need to log-out and log-in back to desktop environment.
Answer: Put that line in your ~/.bashrc file.
It gets sourced whenever you open a terminal
EDIT: Based on the comments below, for a more general setting that will apply to all shells (including when you hit Alt-F2 in Unity), add the line to your ~/.profile file. Probably shouldn't do both however, as the path will be added twice to your PATH environment if you open a terminal.
Comment: I haven't really looked into this for a while, so I did a search, and it seems that there are at least 95 different ways to set the path, most of which are discussed [here](http://askubuntu.com/q/60218/39753). I never figured out which one is best. I think `~/.profile` is correct for personal paths, though; that's where Ubuntu adds the `~/bin` directory.  And I confess that I exaggerated a slight bit on the number of ways - just a little.
Comment: @geirha - I agree that most guides on the internet in general are probably crap, especially anything linux since different distros, or even different versions of the same one, do things differently. It usually boils down to what works, but most people don't realize that what works is simply what works, not necessarily what's right or even what will always work.  I try to figure out which of the many ways is actually correct, because I hate doing things more than once - but it's not always easy. :)
Comment: Actually, I thought you set the path in either `$HOME/.profile` for personal settings, or `/etc/profile` for all users.  But if it's only needed for bash, I suppose either will work.
Comment: If you set it in `~/.bashrc`, it'll only be available in the terminals you open. E.g. if you hit Alt+F2 and try to run a command from that dir, it won't find it. If you set it in `~/.profile` or `~/.pam_environment`, the gnome session (or whichever DE you use) will inherit it. Appending PATH in `~/.bashrc` also has the drawback that if you open/exec bash interactively from another interactive bash shell, it'll be appended multiple times.
Comment: @MartyFried, yes, to quote the bot in #bash on freenode: «The overwhelming majority of bash scripts, code, tutorials, and guides on the Internet are crap. Sturgeon was an optimist.» Using google for bash problem, you'll often find a lot of half-working solutions before you find a good one. Oh and I'd go with `~/.profile` in this case too.
Comment: That's only for login shells. EDIT:Doh... I guess the system will source it when you login in to the computer.  I always thought of it like a remote login thing.
Answer: Adding it to .bashrc will work but I think the more traditional way of setting up your path variables is in .bash_profile by adding the following lines.
PATH=$PATH:/my/path/foo
export PATH

According to this thread it appears as though Ubuntu's behavior is slightly different than RedHat and clones.
Comment: If you have `.bashrc`, stick it in `.bashrc` instead. GUI terminals in Ubuntu are not login shells, so `.bash_profile` will not be run.
Comment: @justingrif No, you don't need `.bash_profile`. If bash doesn't find a `.bash_profile` (when you log in interactively), it will look for `.profile` and use that instead. By default, you'll have a `.profile` and `.bashrc` in Ubuntu. And `.profile` is the correct place to set environment variables if we disregard pam_env.
Comment: Both will work if your shell is a login shell.  But I just tried the .bash_profile approach on one of my Ubuntu machines and even after restarting my gnome session it didn't source my .bash_profile.  So I would say that putting this in .bashrc is probably the way to go with Ubuntu.
Comment: I don't have a .bash_profile, Should I create it?
Comment: I am not running a gui shell. But from the thread above it looks like the .bashrc will work just fine.
Answer: To set it system wide, append the line export PATH=/path/you're/adding:$PATH to the end of /etc/profile.
To add the directory for only the logged-in user, append the same line to ~/.bash_profile.
Answer: In terminal, cd to the_directory_you_want_to_add_in_the_path
echo "export PATH=$(pwd):\${PATH}" >> ~/.bashrc

This wasn't my idea. I found this way to export path at this blog here.
Answer: sudo vi /etc/profile.d/SCRIPT_NAME.sh

add there
export PATH=YOUR_PATH_WITHOUT_TRAILING_SLASH:$PATH

Comment: `sudo nano /etc/profile.d/SCRIPT_NAME.sh` is easier for beginners.
Comment: For beginners, `gksu gedit /etc/profile.d/SCRIPT_NAME.sh` is even easier.
Answer: The recommended way to edit your PATH is from /etc/environment file
Example output of /etc/environment:
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games"

For example, to add the new path of /home/username/mydir
PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/home/username/mydir"

Then, reboot your PC.

System-wide environment variables
A suitable file for environment variable settings that affect the system as a whole (rather than just a particular user) is /etc/environment. An alternative is to create a file for the purpose in the /etc/profile.d directory.
/etc/environment
This file is specifically meant for system-wide environment variable settings. It is not a script file, but rather consists of assignment expressions, one per line.
Note: Variable expansion does not work in /etc/environment.

More info can be found here: EnvironmentVariables
Comment: The lowest answer yet the most correct. This file is usually auto-populated bin Ubuntu with the path.
Comment: Indeed this is THE correct answer, not the others
Answer: Whenever I "install" my folder of BASH scripts, I follow the pattern of the test for a $HOME/bin folder that's in most .profile files in recent versions of Ubuntu. I set a test that looks like
if [ -d "/usr/scripts" ]; then
   PATH="/usr/scripts:$PATH"
fi

It works just about 100% of the time, and leaves me free to change it in a GUI text editor with a quick "Replace all" should I ever decide to move /scripts somewhere closer to my $HOME folder. I haven't done so in 6 Ubuntu installs, but there's "always tomorrow." S
BZT
Answer: Open your terminal, type gedit .profile and insert the following:
# set PATH so it includes user's private bin if it exists
if [ -d "$HOME/bin" ] ; then
    PATH="$PATH:$HOME/bin"
fi

 #the following line add Bin where you dont have a Bin folder on your $HOME
    PATH="$PATH:/home/mongo/Documents/mongodb-linux-i686-2.2.2/bin"

Close and open terminal, it should be working.
Answer: Even if system scripts do not use this,
in any of the cases that one wants to add a path (e.g., $HOME/bin) to the PATH environment variable, one should use
PATH="${PATH:+${PATH}:}$HOME/bin"

for appending (instead of PATH="$PATH:$HOME/bin"),
and
PATH="$HOME/bin${PATH:+:${PATH}}"

for prepending (instead of PATH="$HOME/bin:$PATH").
This avoids the spurious leading/trailing colon when $PATH is initially empty, which can have undesired effects.
See e.g. https://unix.stackexchange.com/questions/162891/append-to-path-like-variable-without-creating-leading-colon-if-unset
Answer: Put it to your ~/.bashrc or whatevershell you use rc (or to beforementioned ~/.profile) AND ~/.xsessionrc so it will also work in X (outside shell).
Answer: For Ubuntu edit the ~/.bashrc and add the following line.
. ~/.bash_profile
Then edit your .bash_profile as you need.....
Comment: This is the wrong way. `.profile` or `.bash_profile` should source `.bashrc`. Not the other way around.
Comment: Downvoted because you didn't explain how to "edit your `.bash_profile` as you need". What exactly do I need to do to the `.bash_profile`?

How to add a directory to the PATH?


Unique visitor hit count with PHP for multiple pages

Question: I have a "blog" type website and I want to know how many visits each post gets (unique visitors).
I want to store this "visit" count in the "posts" table as a single integer value.
What's the best way to do this? Do I need to create another table for storing IPs and checking for duplicates or is there a simpler way to do this?
Comment: If it was me, i would use goggle analytics, much better than any diy php hit counter.
Comment: I know, I would too, but the client actually wants to be able to see the hit count on the administrator panel (which is a DIY by itself lol) sooo, I'm not looking for any robust solution, just some simple stuff
Comment: There's no best way especially not without any specification on the condition to be counted as 1 visit. How much traffic does the site gets matters too but yes, you need a table or at least modify your existing post table.
Comment: you can still use google analytics for that, they have an API, you can get any stats you like in any format you like to display elsewhere
Comment: You could write out a text file (shudder...).  No, I think a quick little table would be the way to go.  You could even track per page that way.
Comment: Using the IP address is in the right direction. Your table column could be ip_address, page_name, today_date, visits. Check if today, IP address and page name exist. Insert only if it doesn't. This https://stackoverflow.com/questions/14104304/mysql-select-where-datetime-matches-day-and-not-necessarily-time can also help you.
Comment: i wouldent bother with IP, its not what you think it is. 1 IP could be thousands of people, one person could use thousands of IP's
Comment: It's not really useful to save IP addresses with the goal of counting unique visits. One IP have hundreds or thousands of users (like schools), and one device can get a new ip address (cellphones probably go through more than ten ip addresses a day).  Much easier to just do `session_start(); $id = session_id()` and use that.
Comment: @dave but I'd need a session for each post, right?
Comment: you'd just need to keep track of whether that session has visited that post, so a table  like `CREATE TABLE post_session_visits(post_id INT, session_id VARCHAR)` and then you can just count how many rows exist for a given post to know how many unique visitors you had for that post.
Answer: I would use Google Analytics API, but to answer the question you asked.
First create a table for "visits". You can do it in your existing table but creating a new one would be ideal.  For your rows have "blogID", "IP", "hits". You can name your rows accordingly.
I would create a function in PHP for trackViews() and pass the IP address and the current blog post identifier.
Example:
function trackViews($IPAddr, $id) {...}

Inside that function first, check to see if the IP has already been stored under that blog post
SELECT * FROM `visits` WHERE `IP` = $IPAddr & `blodgID` = $id

If the database returns no results, then add the IP to the database which will track unique views.
Now if it returns data, update the database hits row to increment +1 to track hits from the same IP address. The reason is not only to track all views but public wifi may also get multiple hits which would all be from the same IP address.
You can still display data easily either in a cross join or just two separate SQL queries.


My texturepack folder in minecraft doesn't exist. (Mac computer)

Question: I've tried restarting Finder, showing hidden folder codes, and the "Open resource pack folder" ingame button doesn't work; I have a sneaking suspicion my computer doesn't have the folder at all. It's a MacBook Pro, if that helps at all. If anyone has any methods, I would love to try them out.

This is what my labelled texture pack folder looks like:
Comment: Have you tried creating a folder called `resourcepacks`?
Comment: What Minecraft version are you using?
Comment: That would be 1.8.
Answer: In minecraft 1.5 and before, the folder was for texturepacks was texturepacks. Now, in 1.6 and above, it is called resourcepacks. Therefore the folder is now resourcepacks. See the minecraft wiki page on texturepacks here and the page for resourcepacks here.
Comment: I'll check it out. I was mostly trying to add a mod, but it'd be nice to know how to download a texture as well.
Comment: @Accaila What does unregistered mean? It says that on your profile page
Comment: I haven't verified my email yet. I have now. @TheCodingMonster
Comment: Ok. I hope you stay on at Arqade and not leave once you get your answer. Mabye go edit some questions to get reputation.
Comment: I was wondering how that works... I'll do that.
Answer: Alright, so I've found the folder, my problem is now that texture packs placed in the correct folder don't appear ingame to be selected.

Thanks to RavenM for suggesting to simply make a folder. That worked beautifully.


How to collect data from more than two localhost to one main server in Wordpress

Question: I want to know that is it possible to crate a web site on different local servers and after that collect all data to another local server for final version control
Answer: it is possible dude, please follow steps.
Step 1:- download whole data base in local server
step 2:- open that file in notepad and find current local site url and
 Replace to all new site url.
Step 3:- import that database file to new server
Step4:- go to word press admin site and change permalink.
Ex:- old site utl is www.oldsite.com
     new site is   www.newsite.com
     1:- download to old site database
     2:- open on notepad Replace all site url  www.oldsite.com to www.newsite.com and site that file
     3:- import that file to new local database
     4) go to wordpress admin and change permalink setting
enjoy i hope it's working for you. :)
Comment: Hello Mithun, We are creating same website on three different machines,  and now I want to collect work of each person to one machine and then upload to server
Comment: ohh.. so only one option. you have to crate github a/c and create user.

it's same work SVN. more info visit https://github.com/
Comment: ohh.. so only one option. you have to crate github a/c and create user.


Invoke a service from a multi container pod with a Istio sidecar

Question: I have two pods with two containers. In each pod, one container is the Istio sidecar-proxy (Envoy)
$ kubectl get pods
NAME                                     READY   STATUS    RESTARTS   AGE
helloserver-744bf7487-m426t              2/2     Running   0          14h
helloworld-deployment-7dfc7db54d-d4ddf   2/2     Running   0          15h

I have a helloworld service in the pod helloworld-deployment-7dfc7db54d-d4ddf. I want to invoke that service from the helloserver-744bf7487-m426t pod.
$kubectl get services
NAME                 TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
helloserver          NodePort    10.100.244.253   <none>        9095:30161/TCP   13h
helloworld-service   NodePort    10.111.142.95    <none>        9095:32685/TCP   14h

I used the command,
$ kubectl exec -it helloserver-744bf7487-m426t -c helloserver -- \bin\sh\
> curl http://helloworld-service:9095/helloworld/

But it gives an error as,
OCI runtime exec failed: exec failed: container_linux.go:348: starting container process caused "exec: \"binshcurl\": executable file not found in $PATH": unknown
command terminated with exit code 126

How to invoke this service?
Answer: Just use the following command:
kubectl exec -it helloserver-744bf7487-m426t -c helloserver -- curl http://helloworld-service:9095/helloworld/


What's the geometric meaning of a negative determinant?

Question: Geometrically, the determinant of a matrix is the signed volume of a unit cube after the transformation defined by the matrix is applied. However, I'm have trouble understanding what the "signed" mean here. Since effectively volumes are only positive (or zero but for now let's not worry about it). So what's the geometric meaning of a negative determinant? How should I understand the negative volume produced by applying such transformation?
Comment: It means orientation has been reversed. Start by using examples to see what happens in two and three dimensions.
Comment: @TedShifrin What does "orientation" mean here?
Comment: Here is an analogy: Given two points on the real line $a,b$ we could define a signed length between them as $b-a$. It carries a little more information (the orientation, which can be positive or negative) than just the length.
Comment: Think about the right-hand rule, and see [this](https://en.m.wikipedia.org/wiki/Orientation_(vector_space)).
Comment: I beg to disagree with other commenters here. I think the sign of a determinant has no geometric significance. It is an algebraic property, not a geometric one. It's a -- somewhat useful -- artifact of the definition of determinant: we want the determinant to be multilinear in the matrix columns and we want it to be zero when the column vectors are linearly dependent. Consequently, determinants are signed and if we swap two columns, the sign flips. While we can interpret the sign as some sort of orientation in two or three dimensions, this analogue breaks down in higher dimensional cases.
Comment: It's funny that when one calls a generic orthogonal matrix of size > 3 a "rotation matrix", people will rush to ask (probably in a sarcastic tone) "Huh? Rotation about what?" However, when one asks why the sign of the determinant is (mistakenly, IMHO) called an "orientation", no one will try to explain what that term means in four or higher dimensions.
Comment: @user1551 The definition I prefer for the determinant of an endomorphism $T$ is $\underline T(I) = \det(T)I$ where $\underline T$ is the outermorphism of $T$ and $I$ is a pseudoscalar.  This formula has a **highly** geometric meaning.
Answer: The idea has to do with orientation, that is, which direction is right and which is left.  Ultimately this has to do with which order is given for the basis elements. For example consider $\Bbb R^2$ with basis elements $(1,0)$ and $(0,1)$. We can consider $(1,0)$ to be pointing "to the right", and $(0,1)$ pointing " forward".
Putting $(1,0)$ and $(0,1)$ in a matrix gives the identity matrix whose determinant is $1$ of course.
Now switch the two basis elements. Imagine rotating the plane around the line $y=x$.  Now $(1,0)$ is pointing forward but $(0,1)$ is pointing to the left.
Of course if we switch rows in the identity matrix the resulting matrix has determinant $-1$.
Comment: Of course is not an explanation in my opinion. In particular if of course comes exactly, where you should find a preciser explanation.
Answer:
I'm have trouble understanding what the "signed" mean here.

By signed volume they mean scalar triple product of the edge vectors of the cube.

So what's the geometric meaning of a negative determinant?

The matrix has a mirroring component. It transforms left hands into right hands. When such matrix transforms a triangular mesh, it flips winding order of triangles.


All of a sudden, my text editor in Visual Studio is all sorts of crazy colors

Question: This happened all of a sudden - I have no idea what triggered it.  But, when I opened up a Visual Studio solution, here's what I get:

The text in blue and red aren't usually those colors, and the weird white border on the selected row isn't usually a border like this.  As you can see, it's kind of hard to read.  I can't recall exactly what colors they were, but they weren't these.  I went to the following and chose "Use Defaults", but that didn't do anything:

Any ideas on how to fix this?
Comment: Have you installed any extensions lately?
Comment: @jsve Well, guess that was it.  I installed Bing Code Search for C# (and I went in to disable it just now), and that resolved it.  Weird.  If you want to convert your comment to an answer, I'll mark it as the answer.
Answer: An extension that you have recently installed might have caused this unexpected behaviour. Even seemingly unrelated extensions can sometimes do weird things.
If you've installed multiple extensions and don't know which one is the problem, try disabling them one by one and see if you can deduce which one is being problematic.
Comment: The problem was Bing Code Search Tool for C#.  I disabled it and problem went away.  Thanks.
Comment: Glad to hear you found a solution.


NetBeans getting resource inside JAR file?

Question: I have been trying to include some images and sounds in my Netbeans Java project and I have searched all over google looking for answers all of which I have tried and implemented but some play the audio file correctly when running it inside Netbeans but not when its actually built as a JAR file.
I am struggling to play a sound when executing the JAR File. As i understand it, the packages/folders inside the project are compiled and built into the JAR file.
Can anyone point me in the right direction as to how I correctly get a resource?
My code is as below:
public void SND_REQUEST() {
    AudioInputStream clipNameAIS;
    Clip clipNameClip = null;
    try {
        clipNameAIS = AudioSystem.getAudioInputStream(getClass().getResourceAsStream("/Sounds/Cat.wav"));
        clipNameClip = AudioSystem.getClip();
        clipNameClip.open(clipNameAIS);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null,"Request Button Sound Not Working");
    }
    clipNameClip.setFramePosition(0);
    clipNameClip.start();
}

Resource Stucture:

UPDATE - 22:45:
It seems to work when running inside Netbeans, but not in the executable Jar file.
I have tried both ways, ill post images:
The file is certainly in ther, thanks for the help on that 1 Nik.

Updated code:
   public void SND_REQUEST() {
        AudioInputStream clipNameAIS;
        Clip clipNameClip = null;
        try {
            clipNameAIS = AudioSystem.getAudioInputStream(getClass().getResourceAsStream("/overtimesystem/Sounds/Cat.wav"));
            clipNameClip = AudioSystem.getClip();
            clipNameClip.open(clipNameAIS);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,"Request Button Sound Not Working");
        }
        clipNameClip.setFramePosition(0);
        clipNameClip.start();
    }

Result:

Print Stack Trace:
java.lang.NullPointerException
    at com.sun.media.sound.SoftMidiAudioFileReader.getAudioInputStream(SoftMidiAudioFileReader.java:134)
    at javax.sound.sampled.AudioSystem.getAudioInputStream(AudioSystem.java:1113)
    at overtimesystem.OvertimeSystem.SND_REQUEST(OvertimeSystem.java:293)
    at overtimesystem.OvertimeSystem$ADD.actionPerformed(OvertimeSystem.java:148)
    at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
    at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2346)
    at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
    at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
    at java.awt.Component.processMouseEvent(Component.java:6525)
    at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
    at java.awt.Component.processEvent(Component.java:6290)
    at java.awt.Container.processEvent(Container.java:2234)
    at java.awt.Component.dispatchEventImpl(Component.java:4881)
    at java.awt.Container.dispatchEventImpl(Container.java:2292)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4898)
    at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4533)
    at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4462)
    at java.awt.Container.dispatchEventImpl(Container.java:2278)
    at java.awt.Window.dispatchEventImpl(Window.java:2750)
    at java.awt.Component.dispatchEvent(Component.java:4703)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:751)
    at java.awt.EventQueue.access$500(EventQueue.java:97)
    at java.awt.EventQueue$3.run(EventQueue.java:702)
    at java.awt.EventQueue$3.run(EventQueue.java:696)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:86)
    at java.awt.EventQueue$4.run(EventQueue.java:724)
    at java.awt.EventQueue$4.run(EventQueue.java:722)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java:721)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
    at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
    at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

UPDATE - WORKS::
AHH, FOUND THE ISSUE, Thanks for your help. Didnt think of passing the E.printstack trace in a JOptionPane msgbox lol :) It seems i needed the BufferReader for it to stream correctly. Also the path is correct. Please see my updated code which works for the project :)  THANKS AGAIN!!!
public void SND_REQUEST() {
    AudioInputStream clipNameAIS;
    Clip clipNameClip = null;
    try {
        InputStream audioSrc = getClass().getResourceAsStream("/overtimesystem/Sounds/Cat.wav");
        InputStream bufferedIn = new BufferedInputStream(audioSrc);
        AudioInputStream audioStream = AudioSystem.getAudioInputStream(bufferedIn);

        clipNameClip = AudioSystem.getClip();
        clipNameClip.open(audioStream);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, e);
        return;
    }
    clipNameClip.setFramePosition(0);
    clipNameClip.start();
}

Comment: I think the path should be `"overtimesystem/Sounds/Cat.wav"`.
Comment: If you open the JAR file as a zip, can you see the .wav files?  Use the path to them as found in the jar.
Answer:
Can anyone point me in the right direction as to how i correctly get a resource?

Presuming the resources are within the created jar file, you can define the path as absolute relative to the package root:
clipNameAIS = AudioSystem.getAudioInputStream(getClass().getResourceAsStream("/overtimesystem/Sounds/Cat.wav"));

Note the / at the beginning, defining the path as absolute (relative to the package root). You can also define a relative path (relative to the calling class). For instance, if the calling class is within the /overtimesystem/Images/ package, you can access the resource with ../Sounds/Cat.wav
Comment: @AlpaxJ1 Print out the stack trace (eg `e.printStackTrace();`) to verify exactly what the exception is
Comment: Plesae see my Print Stack trace update, Says nullpointer exception? path is incorrect, it cant be...
Comment: Ahh, running it in the JAR file gives this error: http://stackoverflow.com/questions/5529754/java-io-ioexception-mark-reset-not-supported
Comment: @AlpaxJ1, that link suggests (if that problem is the case) you should get an `IOException` rather than a `NullPointerException`. But if it works, congrats.


SQL server query joins

Question: Goal -  List average salary for men and average salary for women for each department. Show department name and number.
 select AVG(salary) as 'Avg salary for men'
   From [Enterprise].[dbo].[Employee]JOIN [Enterprise].[dbo].[Department]
   ON Employee.EMPNO = Department.deptNo
   where SEX = 'm'

Still learning joins not exactly sure if i need an outer join here?  And how do i get it to list avg by department?
Comment: `Employee.EMPNO = Department.deptNo`?, this doesn't seem right, can you list the columns of the `Employee` table?
Answer: I'm going to assume you meant to join by deptNo.
SELECT Department.Name, AVG(salary) as 'Avg salary for men'
FROM [Enterprise].[dbo].[Employee]
JOIN [Enterprise].[dbo].[Department]
ON Employee.deptNo= Department.deptNo
WHERE SEX = 'm'
GROUP BY Department.Name

This will show the average for each department for males.  You can do the same for females, and include them in the query with UNION.  Or add to your GROUP BY sex, and remove the WHERE clause entirely.
The list for GROUP BY usually will match your non aggregated columns in the SELECT list.  In this case it is just Department.Name.
Comment: If you use the UNION approach, use UNION ALL as these two sets of records shoudl be mutually exclusive unless your system allows you to select more than one sex per person. UNOIN ALL is significantly faster.
Answer: Well, first of all, it seems that you are using the wrong column from Employee on the JOIN. That said, your query should be like this:
SELECT  D.deptNo,
        D.deptName,
        AVG(CASE WHEN E.SEX = 'm' THEN salary END) [Avg salary for men],
        AVG(CASE WHEN E.SEX = 'f' THEN salary END) [Avg salary for women]
FROM [Enterprise].[dbo].[Employee] E
INNER JOIN [Enterprise].[dbo].[Department] D
    ON E.deptNO = D.deptNo     -- use the right column from Employee here
GROUP BY D.deptNo,
         D.deptName

Answer: SELECT Employee.EMPNO, Department.Name, SEX, AVG(salary) as [Avg salary]
FROM [Enterprise].[dbo].[Employee]JOIN [Enterprise].[dbo].[Department]
   ON Employee.EMPNO = Department.deptNo
GROUP BY Employee.EMPNO, Department.Name, SEX

This will get you the data, from here you can format it as you please.
Answer: The SQL OUTER JOIN clause is a variation of the SQL JOIN clause enables a SELECT statement to access more than one table. The JOIN clause controls how tables are linked. It is a qualifier of the SQL FROM clause. As result you need the OUTER JOIN in your case. You can visit the link for further information if you want.
To get an output as a list avg by Department, just add this to the end of your query:
ORDER BY Department.deptNo
Answer: No one has accounted for the fact that some departments might contain no men or no women.
SELECT  D.deptNo,
        D.deptName,
        Coalesce(AVG(CASE WHEN E.SEX = 'm' THEN salary END), 0) [Avg salary for men],
        Coalesce(AVG(CASE WHEN E.SEX = 'f' THEN salary END, 0)) [Avg salary for women]
FROM [Enterprise].[dbo].[Department] D
LEFT JOIN [Enterprise].[dbo].[Employee] E
    ON E.deptNO = D.deptNo     -- use the right column from Employee here
GROUP BY D.deptNo,
         D.deptName

Answer: As pointed out, your join condition doesn't make sense, you are joining an employee number to a department number, which wouldn't match (or would, but wouldn't achieve the logic you desire).
SELECT
  d.name
, AVG(e_man.salary) avg_man
, AVG(e_woman.salary) avg_woman
FROM department d
LEFT OUTER JOIN employee e_man ON e_man.deptNo = d.deptNo AND e_man.sex = 'm'
LEFT OUTER JOIN employee e_woman ON e_woman.deptNo = d.deptNo AND e_woman.sex = 'f'
GROUP BY d.name

Here you join twice, once to male rows and once to female and calculate the averages based on them. OUTER joins are used in case there aren't any men/women.

Note: my queries will return you a single row per department with male and female averages as 2 columns. Alternate solutions are to return you 0-2 rows per department, with separate rows per sex and listing the relevant salary per row/sex.

EDIT: Alternative sub-query solution which people seem very unhappy with. In my experience sometimes sub-queries are the right answer and sometimes a join is the right answer, and you would often use whichever fits your logical aim/representation best as long as it doesn't sacrifice performance. The optimiser for the RDBMS you are using will often rewrite it anyway. As always, best to check the Plan and see what is going on.
SELECT
  d.name
, (
    SELECT AVG(e1.salary)
    FROM employee e1
    WHERE e1.sex = 'm'
    AND e1.deptNo = d.deptNo
  ) avg_man
, (
    SELECT AVG(e2.salary)
    FROM employee e2
    WHERE e2.sex = 'f'
    AND e2.deptNo = d.deptNo
  ) avg_woman
FROM department d

Comment: -1 - Sub-query in the `SELECT` shouldn't be the first option.
Comment: That is correct and there is an option to do it via OUTER JOINs
Comment: SUbselect is the last option I would ever use. For anything. Subselects are like cursors in how they operate. The join query is fine, but don't suggest subselects.
Answer: Query1 :

SELECT Table1.*, Table2.[Roll no],Table2.Address,Table2.City
FROM (Table1 right JOIN Table2 ON Table1.[roll no] = Table2.[roll no] and Table1.[status] = Table2.[status])
where Table1.Status="New" or Table2.status="New"
UNION SELECT Table1.*,Table2.[roll no], table2.Address,table2.City
FROM (Table1 left JOIN Table2 ON Table1.[roll no] = Table2.[roll no] and Table1.[status] = Table2.[status])
where Table1.Status="New" or Table2.status="New";

Qury2:

SELECT Table3.*,table4.[roll no],Table4.Sports_id,Table4.Name
FROM (Table3 right JOIN Table4 ON Table3.[roll no] = Table4.[roll no] and Table3.[status] = Table4.[status])
where Table3.Status="New" or Table4.status="New"
UNION SELECT Table3.*,table4.[roll no],Table4.Sports_id,Table4.Name
FROM (Table3 left JOIN Table4 ON Table3.[roll no] = Table4.[roll no] and Table3.[status] = Table4.[status])
where Table3.Status="New" or Table4.status="New";

Query3:

SELECT *
FROM (Query2 right JOIN Query3  ON Query2.[Table1.roll no] = Query3.[table3.roll no])
UNION SELECT *
FROM (Query2 left JOIN Query3  ON Query2.[Table1.roll no] = Query3.[table3.roll no]);

Query4:

SELECT Query4.* INTO Final_table
FROM Query4;

Query5:

UPDATE Final_Table SET Query2_Status = "New"
WHERE Query2_Status is null or Query2_status="";

SQL server query joins


Replace elements of a list with Prolog

Question: how to replace any of the element in the list with prolog?
example:
replace(2,[1,2,3,2,1],5,X)

should have both the solutions:

X = [1,5,3,2,1]
X = [1,2,3,5,1]
Comment: This question appears to be off-topic because it is asking for a complete code solution rather than asking for help on any specific attempts.
Answer: You can do it by iterating over the input list:
%replace(_, [], _, []).
replace(Element, [Element|Tail], NElement, [NElement|Tail]).
replace(Element, [CurElement|Tail], NElement, [CurElement|NTail]):-
  replace(Element, Tail, NElement, NTail).

Sample input:
?- replace(2,[1,2,3,2,1],5,X).
X = [1, 5, 3, 2, 1] ;
X = [1, 2, 3, 5, 1] ;

If you uncomment the first clause it would also output the solution where the output list remains unchanged.
The first clause (commented) is a base case for iterating over a list. It states that the replaced list of an empty list is the empty itself.
The second clause states that if the head of the list unifies with the Element then the replace list would contain the replaced element and the rest of the list (Tail).
The third clause is the recursive step, it takes the first element and calls recursively with the tail of the list, and the output is the element taken concatenated with the result of the recursive call.
Comment: @fanrenwu: It's the Prolog comment marker. That clause is commented out; if you remove the % then that clause would be part of the procedure so it would add a base case for the recursion.

Replace elements of a list with Prolog


how do I find a value within a string in php

Question: My value is stored within a string inside (). I need to return this value to check if it's empty.
$variable = "My Link (55)";
$value = "55"; // how do I get the value?

if($value < 1) {
    // no link
} else {
    // show link
}

This code would be used to show links with no posts in them in Wordpress.
Answer: $variable = "My Link (55) plus more text";
preg_match('/\((.*?)\)/',$variable,$matches);

$value = $matches[1];
echo $value;

Answer: Your question doesn't quite make sense - although you should look at using instr
Answer: You can use preg_match to extract the value from your string. But if you just need to know whether the value is empty, checking whether your string contains () should work just as well.
Answer: Are you looking for a string's value, or just check to see if it is empty?
If your checking if the string is empty try
return empty($mystring);

Answer: if(strpos($string,')')-strpos($string,'(')==1)){
  #empty
}

to return the string
$newstring = substr($string,strpos($string,'('),strpos($string,')')-strpos($string,'('));

Answer: This:
<?php
$str = "blah blah blah blah blah blah blah (testing)blah blah blah blah blah ";

echo preg_filter("/.*(\(.*?\)).*/","\\1",$str);
?>

Would output (testing). Hopefully that is what you were looking for :o)
Answer: Putting all of this together, it is clear from the example that InnateDev intends to test against positive numeric values inside the parentheses. In my opinion, the safest way to do this would be:
$testString = "My Link (55)";
$matches = array();

/* Assuming here that they never contain negative values e.g. (-55) */
preg_match('/\((\d*?)\)/s', $testString, $matches);

$hasComments = false;

if (count($matches) >= 1) // * Note A
{
    $hasComments = $matches[1] > 0;
}

if ($hasComments)
{
    // link
}
else
{
    // no link
}

Note A: Maybe this is redundant, in which case you're free to ignore it - this can also go as a comment to Mark Baker's answer (sorry, don't have those 50 rep yet :( ) - if you're working in an environment where error_reporting includes E_NOTICE and if the tested string comes from an untrusted source then $matches[1] will raise a notice when no parantheses are present. Just wanted to point this one out.


how to write a script which will displays only regulars files

Question: Someone can say me how to Writing a script,which will displays the number of regular files in the current folder and each of its subfolders ?
Thanks.
Comment: Are you asking for a **count** of regular files or a **list**?
Comment: This sounds like a homework assignment - what have you tried?
Comment: @steeldriver
#!/bin/bash
ls /B-CPE-100-COT-1-1-cpoolday02-sidney.yeto | wc -l
But I have the irregular files too in results
Comment: @DaveWhite I ask indeed a count of regular files
Answer: To get a count of all the regular files in the current directory and its subfolders, you can use
find . -type f -printf x | wc -c

Note that "regular files" include hidden files (aka "dotfiles") which you will not see with plain ls (it would need ls -A or ls -a)
Comment: I just want to get a count for regular files in directory and its subfolders
Answer: find . -type f -name "[^.]*" | wc -l
Find (find) all files in current directory (.) (includes subdirectories) of type "file" (-type f), match all filenames that do not start with a dot (-name "[^.]*", that is a regular expression), pipe | output to wc and count the lines (-l)
Comment: Piping to filenames to `wc -l` has the disadvantage that it will miscount files whose names include a newline (rare but legal in *nix filesystems). Also `[^.]*` in this context is a glob (shell metacharacter) expression, rather than a regular expression (in any case, hidden files **are** regular files in the usual definition of "regular").
Comment: I see, thank you for pointing that out. I guess newlines in filenames really are edge cases, but your point is legit. So, combining my solution with yours, I'd go with a `find . -type f -name "[^.]*" -printf x | wc -c` - due to the `-name` it will skip all files starting with a dot, which I think is what the op wants.
Comment: Yes that may well be the case - I guess we need the OP to confirm


What happens in the faction war when an owned territory is detached from your home base?

Question: I've seen that it's possible for a team to own a territory but not have any path of owned territories from their home base to that territory. At that point, it has a slashed pattern instead of a solid one, and the team that owns that territory can't use it as the origination point for any attacks, but it also can't be attacked by other teams.
What exactly is going on here? How do those territories come back into play? Will another team be able to gain control of that territory? Is it strategically good or bad to have territories like this for your team?
Comment: Correct me if I am wrong, but aren't the territories only decided by you placing war assets in them, not "attacking"? So are you saying you cannot add war assets to those slashed territories?
Comment: You can add war assets to your own territories or territories adjacent to territories you own, except for these slashed territories. You can't defend them and you can't attack territories adjacent to them unless you have another adjacent territory allowing the attack.
Comment: So by attack you mean adding war assets basically? And I tried to find more information about how it works but no where seems to talk about these contested territories :/
Answer: These zones are completely out of action, you can't attack from or to them. Factions are also given one turn to join the zone back to their main land, or the zone is awarded to the faction with the most borders surrounding it*.
You can use this mechanic so you can focus war assets on less zones, and get a positive outcome.

A longer explanation
Ubisoft has an online view for the faction map, which has a history of the seasons.
All the following turns are based on season 1 turn 1, as it's yet to be completed as of writing this. Following are some occurrences of this happening:
Turns 1 - 3.
On Turn 1 the Knights and Vikings swapped a tile.
On Turn 2 both these zones were gray zebra striped out.
The Knights attacked, and took, the Viking zone next to it.
On Turn 3 both the zone they'd attacked, and the separated Viking zone were given to the Knights.
Turns 3 - 4.
On Turn 3 the Knights and Vikings swapped zones, the Vikings was not connected to the main land, but the Knights was.
This meant the Vikings was fully surrounded by Knights main land.
On Turn 4 the Vikings took an adjacent zone and connected it to their main land.
Turns 5 - 7.
On Turn 5 the Knights took a Viking zone, but the Samurai cut the zone off.
On Turn 6 the Samurai took a Viking zone, to control three of the four adjacent tiles.
On Turn 7 the Samurai's were awarded the zone.
And so we can guess at the basic functionality of this.
But there may be a couple of edge cases that we've not seen, and I've not guessed.

How do those territories come back into play? Will another team be able to gain control of that territory?

Either a faction rejoins it to their main land, or
they are awarded to the faction with the most zones around it*, after being out of play for one turn.

Is it strategically good or bad to have territories like this for your team?

I'd say it's good, if the faction knows what it's doing, take Turn 9, and ignoring Turn 10:

The Knights surrounded three of the Samurai's zones.
On this turn they could have taken all three of the Samurai's zones by focusing on just four zones, the two the Vikings took, the only non-taken zone and the one above it.
If the Samurai took more zones, then they'd be cut off and awarded to the knights, due to this mechanic, and it's easier to bulk up four zones rather than focus on nine.
The Samurai on the other hand only needed to focus on three zones to gain one zone in the long run.
Of the three zones that were surrounded by Knights if they'd had given up on the one closet the Knights base,
protected the other two of the three and taken the single zone below the closest to the Knights base.
Then they could have taken the two zones below their line, and lost the one that was cut off. Ending in +1 territory.
Only focusing on three of the nine zones.

Both these examples are ignoring Turn 10. But I think the faction would have to protect the core zones for another turn. And so the Samurai probably should have won. This didn't happen however, the Samurai took some of the Knights zones, and auto lost everything the round after.

* We don't know how this works if there are even territories around the zone.
Comment: Should be "Viking", not "Barbarian".  If you wanted to put "Filthy Viking", I'd be okay with that too.


Can Teflon thread tape be reused?

Question: I need to take off my shower head for cleaning and possible replacement.
I can see there is Teflon tape on the fitting where the head connects to the arm. When I reconnect the head, can I reuse the existing tape? Do I wrap an extra layer around the existing tape? Or do I need to go ahead and completely remove and replace the existing tape?
Comment: Note that many modern shower heads have rubber washers and don't really even need thread tape.
Comment: I have about 5 or 10 rolls of Teflon tape in my shed; whenever I buy a plumbing fixture I always pick one up; invariably I come across one of the other rolls a few days/weeks/months later. $1 per roll < time / gas for extra trip!
Comment: Good to know! Thanks!
Comment: if the shower head fitting is plastic be careful with too much teflon tape u can split the plastic of the shower head screwing it on to the metal pipe.
Comment: @MonkeyZeus If this was an answer instead of a comment, I would upvote it.
Answer: You should remove the tape and replace it, a small roll at a big box store is less than a dollar.
Comment: I agree, though a few times i reused it when  I got stuck doing some plumbing  I hadn't planned on and left my tape at home... success  rate about 50% so a second trip to the job site.
Answer: I agree with Ed Beal that you should replace it, but if you're in a pinch you certainly can reuse PTFE tape, assuming you recover enough of it and it's not totally shredded.
Carefully unwrap it and evaluate which end is in better shape. Re-wrap with that portion to the outside, respecting thread direction (you want the tape to tighten as you thread the parts together, not loosen or fold back). Usually that's clockwise looking from the pipe end.
Check carefully for leaks as the seal will not be as reliable.
Comment: It really depends on the job... don't re-use teflon tape where you cannot easily access. Expect it to leak basically.
Comment: I've had about a 50% success rate when reusing tape.... back to the job site again.
Comment: Sure, but it's different if you're a homeowner and can monitor and respond to the results.
Answer: As an additional answer alluded to by Nelson, it also somewhat depends on the use case.  If it's a shower head (as in this example) where a drip really won't make any difference, if you don't have new, go ahead and reuse.  However, if it's hidden or difficult to get to, you'll want to do it right the first time.  Also, if your jurisdiction permits the use of Teflon tape on natural gas or other flammable gas/fluid connections, always use new, as a leak there could be catastrophic.
Answer: For an application like this where a slow leak would not be a disaster you can omit the tape or substitute something similar like cling-wrap.
That's if the tape is even needed, usually shower-heads use a washer.
Comment: Jason, I almost put this kind of advice in my answer, no shower head I have installed needed or used a washer , or I would up vote. I have used a bread bag a little thicker than cling wrap where I had a leak , I did come back and replace with fresh PFTE tape a couple of days later. I find many leaks where folks don't understand tapered threads, like on hose bibs where I have seen 1/2 a roll of tape used when a simple washer was needed or on pipe threads where a washer was used when when it should have been tape or dope.
Answer: Teflon tape is a one-time use item. It's sole purpose is to deform and tear itself into the threading of the pipe to prevent water from getting through the threads.
Clean the old tape off as much as possible. Use a metal wire brush to really get off the crusty stuff as well but don't scratch up the chrome/nickel/whatever finish and apply about 2-3 layers of new tape clockwise; assuming that righty-tighty applies here. This should take no more than 5 minutes.
Do note that if the shower head has a rubber gasket then that gasket is what produces the water tight seal and teflon tape may not do anything if the gasket fails. It all depends on how that joint was designed. In this scenario you can still apply the teflon tape as long as you don't put any tape where the rubber gasket meets the pipe.

Can Teflon thread tape be reused?


ReactJs style table row from props

Question: I am trying to style the background of my tr if a prop is present:
I am passing the prop here in one of my columns:
<Column highlightRow="yes" />

Here is my table row render:
 render: function () {

   var columns = this.props.columns;
   var data = this.props.data;
   //loop through columns looking for prop
   var styleCheck =  columns.map(function (column) {
        if (column.props.highlightRow) {

            var styles = {
                backgroundColor: 'pink'
            };
        }
    });

    return (

            {this.getCellNodes()}

    );

}

I keep getting the error styles is not defined
Can anyone please help?
Comment: instead of `highlightRow="yes"` better to use `highlightRow={ true }`. Because when you (or somebody else) do `highlightRow="no"` the result will be the same as with 'yes'
Answer: You simply need to scope the styles variable so it can be seen:
render: function () {

   var columns = this.props.columns;
   var data = this.props.data;
   var styles = {};
   //loop through columns looking for prop
   var styleCheck =  columns.map(function (column) {
        if (column.props.highlightRow) {

            styles = {
                backgroundColor: 'pink'
            };
        }
    });

    return (

            {this.getCellNodes()}

    );

}

Besides that, currently, if highlightRow is set to any string, it will be truthy.

ReactJs style table row from props


Non-Silverlight application build: Unable to start debugging. The Silverlight Developer Runtime is not installed

Question: I am trying to run my team's website in Visual Studio 2015. When I try to debug it I get the following message:

Unable to start debugging. The Silverlight Developer Runtime is not installed.

Clicking OK (only option) on that shows another error:

Unable to Attach to application 'chrome.exe' using 'pc-name'. Operation Aborted. Do you want to continue anyway?

Clicking yes repeats both error boxes, clicking no stops debugging.
The annoying part is that Silverlight is not used anywhere in this project or in the whole solution.
Why is this happening, and how can I get it to stop so I can debug this website?
Answer: You can try see in the website / properties / web / debuggers section if "Silverlight" is checked
Comment: That was it, wow. I must have clicked it accidentally once. I didn't see this option when I was trying to fix it. Thanks!
Comment: You may also have to uninstall "Microsoft Silverlight" form Add/Remove Programs (only uninstall that exact one). Then install the developer runtime (Silverlight_Developer.exe or Silverlight_Developer_x64.exe) from  http://www.microsoft.com/downloads/details.aspx?FamilyID=72eeedda-fd89-4ccb-85b2-7001ac5c6c47.


How to use freebase api to get all the tourist spots of a city? I can only get 10 from the returned JSON

Question: I'm trying to use freebase to get all the tourist spots's name of a city, and I used request like below:
<code>    https://www.googleapis.com/freebase/v1/topic/m/030qb3tprops=&lang=en&filter=%2Ftravel%2Ftravel_destination%2Ftourist_attractions
</code>
this should return 27 values, but in the returned JSON I can only get at most 10 values, how can I get all the tourist spots's name?
Answer: It looks like the default limit is 10 (which is probably reasonable since you're unlikely to want to show the user a list of dozens in the first overview).
Try this to get more:
<code>https://www.googleapis.com/freebase/v1/topic/m/030qb3t?props=&lang=en&filter=%2Ftravel%2Ftravel_destination%2Ftourist_attractions&limit=30
</code>


regex needed to match anything within p tags

Question: I need a regular expression to match anything that is within
 tags so for example if I had some text:

Hello world

The regex would match the Hello world part
Comment: Have you seen http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags ?
Comment: What if `` tags are not properly balanced, as they usually (or at least very often) are?
Comment: Which programming language? Maybe there's still a hope for you.
Answer: in javascript:
var str = "
Hello world
";
str.search(/<\s*p[^>]*>([^<]*)<\s*\/\s*p\s*>/)

in php:
$str = "
Hello world
";
preg_match_all("/<\s*p[^>]*>([^<]*)<\s*\/\s*p\s*>/", $str);

These will match something as complex as this

Hello world

Comment: Fails if there is a tag inside, as in `I would like all the text!`.
Answer: EDIT: Don't do it. Just don't.
See this question
If you insist, use
(.+?)
 and the result will be in the first group. It is not perfect, but no regexp solution to HTML parsing problem will ever be.
E.g (in python)
>>> import re
>>> r = re.compile('
(.+?)
')
>>> r.findall("
fo o

ba adr
")
['fo o', 'ba adr']

Comment: Fails to match `Spaces are valid in tags`
Comment: MSalters is talking about spaces *in* the tags, not between them. ie: there's a space between the `p` and the `>`.
Comment: Oh, nevermind. yet another reason why you really should __NEVER__ try parse __ANY__ html with regexp. "#¤()%#=!"¤(=!"#¤! _Hmpf, I Should know this by now_
Comment: That matches the p tags aswell though I don't want the tags to be returned
Answer: It seems that the above proposed solutions will fail either:

to return text within
...
 tags whenever it contains other tags like , , etc.
or
to distinguish between
 and <path> or
to include tags with attributes like

Consider using this regex:

]*)>(.*?)<\/p\s*>
Resulting text will be captured in group 2.

Obviously, this solution won't work properly whenever closing tag
 will be for some reason enclosed in comment tags
 ...
Comment: This really is the most complete answer to the OP.  Should be the accepted answer!
Comment: Nice solution! I think just about every other proposed solution will fail if there is a  tag.
Answer: You can use this in Python as a comprehensive solution:
import re
import bs4
import requests

page = requests.get(link)
page_content = bs4.BeautifulSoup(page.content,'html.parser')
result = page_content.find_all('p')

Answer: Regex:
<([a-z][a-z0-9]*)\b[^>]*>(.*?)</\1>

This will work for any pair of tags.
e.g
hello

The \1 makes sure that the opening tag matches the closing tag.
The content between the tags is captured in \2.
Answer: For anybody looking into this Regex or any other regex to match specific HTML tags, this Regex below will work as needed:
<\s*p[^>]*>(.*?)<\s*\/\s*p\s*>

This will match strings like the below strings as mentioned in xzyfer's answer:

I would like all the text!

Hello world

Link to the Regex on Regex101 here: https://regex101.com/r/kjpLII

If you would like to use the Regex for other HTML tags instead of just p tags you can change the p's  in the Regex to whichever HTML tag you wish to match:
<\s*div[^>]*>(.*?)<\s*\/\s*div\s*>

Comment: You'll have problem with nested ``.


Blank xcode app generating unexpected errors

Question: What I did was:

create new project via master detail template
select 'use core data'
build -> run using ios sim

I got the following error code:

the model used to open the store is incompatible with the one used to create the store

I googled around and read a lot about data migration and what not. I even following the directions and tried to migrate.
The model used to open the store is incompatible with the one used to create the store, apple store release version
But then it gave me another error message:

can't find model for source code

But since the app is not edited whatsoever, and there is only one version, why is there an issue with data migrating anyways? Shouldn't it just run with no error and just do nothing meaningful?
Comment: Yes, it should. Which app template did you use?
Comment: Sry , forgot to mention, I used master detail
Comment: Thanks. Okay, well, I just created a new Master-Detail iPhone app with Core Data checked and it works fine.
Comment: I think you need to drop back ten yards and punt, as suggested in the answer you've already gotten. See my instructions here: http://stackoverflow.com/a/6247073/341994
Answer: After the error is thrown, push the stop button on Xcode.
Then, go to the simulator (it should now be on the home screen) and delete the app.
You delete apps from the simulator the same way you do on an actual iPhone (hold down on the icon until it shakes and the 'x' appears in the corner).
Then, run the app again.
You probably, at some point, made another project with the same bundle-id. That project probably had a data-model which is different than the blank (or whatever the default data model is) in the template app, which causes your app to crash somewhere in your AppDelegate.m when it tries to load up the store.
Comment: Glad to hear it! Would you mind accepting my answer?


Electrical - 50A to 20A Adapter for heater?

Question: I am currently in the process of remodeling my detached garage and have run into a snag with the electrical. The previous owner ran 6-2 wiring out to the garage into a 50A outlet but then pigtailed a 20A outlet off of that (see attached pictures).

I have a Cadet Garage Heater that needs the 6-20R outlet. The heater would only be used in the winter and when I am making something out in the garage which is not that frequent. I am assuming the pigtail connection the previous owner ran is not safe.
Ideally, I would run 6-3 wire out to the garage for a subpanel and come off of that but I am hoping for an easier solution in the form of an adapter. As mentioned before, the usage of the heater would be limited to the winter, running maybe 2-3 hours max a couple times a month. I would like to keep the 50A outlet in case I ever decide to flirt with a welder.
The 6-2 wiring is on a 50A breaker and is run underground to to the garage. Also ran out to the garage are two 14-2 lines as well as a 14-3 line. The two 14-2's are on a 15A breaker and the 14-3 is on another 15A breaker tied into a few things inside the house. I have already replaced the fluorescent lights with LED lights and added a couple more plugs off of the 14-2's. The 14-3 controls the lights on the garage (other switch is at the back door).
All help is appreciated. Let me know if I need to provide more details. Thank you!
Answer: I believe you could have a safe, code compliant install now if you used the 6/2 to feed a small subpanel with no neutral.  The 240V receptacles don't have a neutral.
There may be a tap rule that would allow you to tap the 50A circuit with #12 if you keep the tap very short, but only if you hardwired the heater, not with a receptacle.
Answer: If the heater has a built-in breaker or fuse, then I would just make a cheater cord. Totally not legit, but it should be safe, provided the heater has its own breaker or fuse.
Comment: No, an adapter cord for plugging a 6-20 device into a 6-50 receptacle is *fine*
Comment: @ThreePhaseEel Because it's not part of the building wiring, and thus out of the bailiwick of the electrical code?
Comment: @Harper -- partially, at least.
Comment: It's only fine if the heater has built-in protection to prevent overload of its wiring and cord. Otherwise, swapping in a 20 amp breaker like @EdBeal suggests is a better idea.
Comment: This is the heater that I have
https://cadetheat.com/products/garage-heaters/RCP402S

I would like to keep the 50A outlet in case I get a welder so really do not want to run new line although it may sound like I have to? Two winters ago, I used the heater for about 2 hours without incident with the current setup. Last year, I did not even use the heater.
Comment: Running a new line is not what Ed suggested. He is suggesting that you replace the 50 amp breaker with a 20 amp one, and replace the 50 amp receptacle with a 20 amp one. When you get a welder, you can put the 50 amp breaker and receptacle back.
Answer: You can pull the 50 amp breaker or add another 20 and remove the 50 amp outlet since this is not code . you can run the 20 amp circuit on the number 6 wire but may need to pigtail for the breaker. If you want to use for a welder at a later time you still have the breaker and outlet that can be reinstalled


How to rescue exception in model?

Question: In Rails.
Exception can rescue in controller class but in model class can not.
How to rescue exception in model?
Answer: You can do exception handling anywhere in a rails application, as it's part of Ruby, not part of Rails.  Wherever you want to catch errors, just wrap it as so:
begin
  SomethingElse.doSomething(x, y)
rescue Exception
  ErrorLogger.log(Time.now, "Something went wrong!")
end

Please note that you should always "rescue Exception" instead of just "rescue".  Just using "rescue" will only catch StandardError, which is a subclass of Exception (meaning something might get through that you don't want to get through).
Also as usual, you can raise an exception by doing:
raise ArgumentError, "Illegal arguments!"

anywhere in your code, be it a model or controller.
Comment: Generally I agree, but I disagree with your first code block.

You should not use "rescue Exception" directly since it will rescue even signals that try to kill the process. Unless you're REALLY sure you want to make that portion of code immune to being cleanly killed, stick to the default behavior that Ruby has for a good reason.

Thus, it's generally better practice to use a vanilla "rescue" and have your custom error classes derive from StandardError.
Comment: Small correction: You've got a double `raise` in your second code snippet. Good answer though.
Comment: That's not a syntax error or double raise.  See here: http://web.njit.edu/all_topics/Prog_Lang_Docs/html/ruby/syntax.html#raise
Answer: Unless I'm mistaken you can use error handling anywhere in Ruby. What are you trying to do?

How to rescue exception in model?


How do I update mySQL with PHP, but only if the last update was more than 24hrs ago?

Question: I have a table of different users, but I want to be able to limit how frequently the user can update their own information. In the table, the timestamp is automatically updated when the user makes a change.
The page automatically updates their information with UPDATE edits SET EDITS=EDITS+1 WHERE ID='$sID' when it loads, but I would like for that to be ignored if the last update was less than 24hrs ago.
I'm not sure if that can be solved in UPDATE, or if there is a better alternative.
Thanks!
Answer: Assuming your column for last update is last_updated
UPDATE edits SET EDITS=EDITS+1 WHERE ID='$sID' AND DATE_SUB(NOW(), INTERVAL 24 HOUR)>last_updated

Answer: You will need to add a column to the database containing the last update. Let's assume it's called last_update and DATETIME format.
$one_day_ago = strtotime('24 hours ago');
Then run this query:
UPDATE edits SET EDITS=EDITS+1 WHERE ID='$sID' AND last_update <= FROM_UNIXTIME('$one_day_ago')


A Navigation bar with hover effect

Question: I want to make a Navigation bar with a hover effect.
The goal is that when you hover over it there is more content.
However, when you hover over the navigation bar and there is content displayed, I desire more content to be displayed when you hover over that content.
Something like this.
I hope you understand what I mean.
Thanks
Answer: Do you mean with a drop down when you hover?
I've created a codesandbox with what i think you mean
https://codesandbox.io/s/awesome-shockley-qosw6
html:

  Home
  News

    <button class="dropbtn">Dropdown

    </button>

      Link 1
      Link 2
      Link 3

CSS:
/* Navbar container */
.navbar {
  overflow: hidden;
  background-color: #333;
  font-family: Arial;
}

/* Links inside the navbar */
.navbar a {
  float: left;
  font-size: 16px;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

/* The dropdown container */
.dropdown {
  float: left;
  overflow: hidden;
}

/* Dropdown button */
.dropdown .dropbtn {
  font-size: 16px;
  border: none;
  outline: none;
  color: white;
  padding: 14px 16px;
  background-color: inherit;
  font-family: inherit; /* Important for vertical align on mobile phones */
  margin: 0; /* Important for vertical align on mobile phones */
}

/* Add a red background color to navbar links on hover */
.navbar a:hover, .dropdown:hover .dropbtn {
  background-color: red;
}

/* Dropdown content (hidden by default) */
.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  z-index: 1;
}

/* Links inside the dropdown */
.dropdown-content a {
  float: none;
  color: black;
  padding: 12px 16px;
  text-decoration: none;
  display: block;
  text-align: left;
}

/* Add a grey background color to dropdown links on hover */
.dropdown-content a:hover {
  background-color: #ddd;
}

/* Show the dropdown menu on hover */
.dropdown:hover .dropdown-content {
  display: block;
}

Comment: No i want it that when you hover over Link 1 there is another Dropdown menu.
Comment: Ahhh ok i see, slightly more complex as you need to add some floats on hover to the current drop down items, css script explains this step by step how to create a drop down menu like that

https://www.cssscript.com/create-a-multi-level-drop-down-menu-with-pure-css/
Comment: Working example here https://codesandbox.io/s/awesome-shockley-qosw6 @Idunno

A Navigation bar with hover effect


How to set flags and usage glnamedBufferStorage in new OpenGL 4.4+ (GL_STATIC_DRAW)?

Question: In the documentation I see that the final parameter for glNamedBufferStorage is flags and that flags:

Specifies the intended usage of the buffer's data store. Must be a bitwise combination of the following flags. GL_DYNAMIC_STORAGE_BIT, GL_MAP_READ_BIT GL_MAP_WRITE_BIT, GL_MAP_PERSISTENT_BIT, GL_MAP_COHERENT_BIT, and GL_CLIENT_STORAGE_BIT.

However, in the older glBufferData we use to specify a usage flag which would include things such as GL_STATIC_DRAW to specify expected usage patterns.
Where do we include that with the newer OpenGL?
Answer: The usage flag in BufferData was basically useless. There is no functional difference between each value and drivers used other ways to decide how to handle its data.
The flags parameter on the other hand actually changes what you can do with the buffer.


Excel - If the value is already present in the above rows, then its option A else option B

Question: I am looking to check if a value is already present in the above rows of a column using an excel formula. If it is already present then the output is "yes" else it is a "No"
For Example,
<code>Name Present
AS    No
AD    No
AF    No
AS    Yes
AS    Yes
AD    Yes
</code>
My values are there in the column Name and the expected outputs are there in the column Present.
We can do this using Macro but is there an excel formula that can help us get this?
Answer: In B7 enter:
<code>=IF(COUNTIF($A$1:A6,A7)>0,"yes","No")
</code>
and copy upwards through B2


c++ not validating string input

Question: int main() {
    Population town;
    int population;
    int numBirths, numDeaths;
    string city, intTest;
    bool isValid = true;

    do {
        cout << "Enter name of city: ";
        getline(cin, city);
        for (int i = 0; i < city.length(); i++) {
            if (!isalpha(city[i])) {
                isValid = false;
                break;
            }
        }
    } while(!isValid);

Its not properly checking to see if the input is a string or not. Not sure whats wrong with the code.
Comment: What input did you try and what was the result?
Comment: `isValid = std::all_of(city.brgin(), city.end(), [](char ch) { return isalpha(ch)!=0; });`
Answer: if (!(isalpha(city[i]))) {
   isValid = false;
}
else {
    isValid = true;
    break;
}

The first time this loop finds an alphabetic character, it will set isValid to true and then break out of the loop. As your code stands, isValid is true if there is any alphabetic character in the string and false otherwise after the loop.
You probably actually want something like:
string city; //populate this
bool isValid = true; //Innocent till proven guilty

do {
    city = ... ; //get new city
    isValid = true; //Don't forget to reset!!
    for (int i = 0; i < city.length(); i++) {
        if(!isalpha(city[i])) {
            isValid = false;
            break; //If we're invalid, doesn't matter what the rest is
        }
    }
while(!isValid);

Furthermore, for whatever reason, you're reading into city twice.
First you read a single word:
cin >> city;

and then you read a full line:
getline(cin, city);

If the city will only be a single word, use the first and delete the second. Otherwise, if the city will be multiple words (that the user will enter terminated by a newline (enter key)), delete the first and use the second.
Comment: @user8799094 I'm going to need a little more detail than that if you want help. The code I've posted is working fine for me. What is your input and what is your expected output vs. actual output? Does your input have a space? If so, remember that the space won't be an alphabetic character
Comment: So the program is suppose to only take in a string. If it has numbers or symbols in the word it's suppose to ask for the input again (jidnba21892) and keep asking until its a string. 2 word strings are acceptable because there are cities with 2 words. The output im getting is, the program keeps asking me to enter a city name, no matter what I type in
Comment: @user8799094 Can you update your question with your updated code? Again, it's hard to tell you what's happening with only that explanation. I've given you some code but I have no way of knowing how you've incorporated it.
Comment: @user8799094 ahh you need to remember to reset `isValid` to true at the start of each loop when you look at the next input. See my edit.
Answer: You are using two lines for reading into city.
    cin >> city;
    getline(cin, city);

You need only one of them.
If the name of a city does not contain spaces in them, for your application, use the first one. Otherwise, use the second one. Don't use both.

c++ not validating string input


Merge tags 'og' and 'organic-groups'

Question: Please consider merging og and organic-groups; "og" is always used as shorthand for Drupal's "Organic Groups."
Answer: That makes sense, I've added the synonym.
Comment: Great.  Thanks, @googletorp.

Merge tags 'og' and 'organic-groups'


OpenGL implement level of detail

Question: I'd like to implement a level of detail algorithm for my polygons into my 3d engine. What I got is the following:
1. An entity with multiple amounts of polygons, e.g.:
House:

1. -Entity1:   10000 polygons            viewrange[0,100]
2. -Entity1:   5000  polygons            viewrange[100,300]
3. -Entity1:   800   polygons            viewrange[300,1000]
4. -Entity1:   100   polygons            viewrange[1000,infinity]

Usually, I would create a new VAO including the VBO's for each Entity but is there a smarter way of implementing this? Could I use only one single VAO and adjust the level of detail by changing the indices buffer?
I created an example. I am dealing with terrain grids at the moment and need to apply LoD to them:

Example for different indices buffer, but how would I swap them? Is that efficient?
What is the best way for implementing LoD in OpenGL? Do I need multiple VAO's or is one VAO enough?
Answer: You can store both, the data and the indexing information in one VAO. If you add together all the indices in one buffer, you can adjust which level you want to draw by specifying the start index and the amount of indices in the draw command.
For your example, you would create a index buffer with 30 indices, where index 0-5 is for level 1, 6-29 for level 2. You can then draw level 1 by calling:
glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);

and level 2 by calling:
glDrawElements(GL_TRIANGLES, 24, GL_UNSIGNED_INT, (void*)(6 * sizeof(GLuint)));

Note, that this method requires you to have all the levels in storage at all time. This might, depending on your needs, not be what you want.
Comment: If I have a terrain consisting of a regular grid, then I would go for dynamic tessellation by using a tessellation shader. Especially for a terrain, you'll need more details closer to the camera anyway. About multiple VAOs: In the end it boils down to: Do you want to load all data in the beginning or do you want to load and delete levels from memory when they are not necessary.
Comment: That sounds good. But what method would be more efficient if I have terrain grids where the highest LOD is at around 256x256 vertices? Would you still store all of them in one buffer or start using multiple VAOs?
Comment: I might generate the terrain procedural. But I am not sure about that yet. Would it make a big difference?
Comment: It depends :). If your terrain generation algorithm is fast enough to generate it on the fly -> tessellation shader and implement it there. If it is too slow -> generate a heightmap offline  and use that. If terrain cannot be represented by heightmap (which I doubt because that would require something more complex than a regular grid as basis) -> tile it up and stream tiles from HD (or main memory).
Comment: Next time try to ask the real question in first place. "How can I handle level-of-detail for a procedural terrain?" is quite different from "Do I need multiple VAOs to store multiple levels?".
Comment: Why would I use a height map? Why not apply the height map to the grid before loading it into my VAO? Yeah you are right, sorry for that :)

OpenGL implement level of detail


In Tiny Death Star, is there any significance to an all zero skilled bitizen?

Question: Is there an Emperor mission or something with them?
Comment: I feel like Stass sometimes.
Comment: Don't we all . . .
Answer: Thus far, I have seen no mission involving unskilled labor. The stats are randomly generated. And, this is just a bitizen begging to be blown out the airlock. Nothing more.
Better yet, drop them in their dream job, collect the 1 Bux, and then blow them out the airlock.
Comment: +1 for "And this is just a bitizen begging to be blown out the airlock".
Answer: No, that person is just uniquely awful.  Now that you've shown their terribleness off to the world, evict them.
I've got one genuine Wilhuff Tarkin on my station, and I keep him around just for his awesome name.  He has a purple cape, fedora, and green shoes, and gives pedicures at the spa.
Comment: I'm not sure I get what you keep him around for . . . Sure, he's clearly fabulous in his outfit, but ?huh?
Comment: It's THE WIlhuff Tarkin.  You know, the Grand Moff?
Comment: Actually, The Moff is a 9 at his dream job in the spa.
Comment: I suggested an edit to your post to make it a tiny bit clearer.  Before, I thought you kept him around to evict people or something.  That's why it didn't make sense.  And, I find it hard to believe that Grand Moff Tarkin lacks any skills.  Have you considered the possibility that he's an imposter?
Comment: Ah, gotcha.  Just a brag, then.  +1 for employing the Grand Moff, himself.
Answer:
In answer to your question:  I immediately delete people like the one I have pictured above!  They are of no use in the game.
Sadly, Scerra Iblis never achieved her lifelong dream of working in the Statuary Park.  Unskilled and unattractive, she drifted about the galaxy, and landing on Tatooine thought herself lucky when she found employment scraping the poop and dismembered limbs from the bottom of a Rancor pit. Unfortunately, a young upstart Jedi named Luke Skywalker arrived at Jabba's Palace, and made her job obsolete . . . Packing up her things, she mumbled something about being better off inside a Sarlacc and left . . .
Answer: They don't mean anything for missions, but they are still worth keeping around if you can get them in their dream job. Dream job workers double the amount they stock (and they do it in the same amount of time that a non-dream-job bitizen would.) It's better for you to have a level zero dream job bitizen working than a level nine non-dteam-job. One dream job bitizen on the floor means the lowest level item will have double stock, two dream job bitizens mean the first and second items will be double stocked, and three dream job bitizens means all three stock items will be double stocked. I don't evict anyone for being a low skill unless I still have three bitizens with that dream job.
Comment: Ya, you'll have a much better time if you set an "evict on sight" policy.  To start off, sure you can keep most of the unskilled bitizens, but you should always have at least 1 spot for someone to move in, and also 1 open job (so you can avoid the new "I find your lack of jobs disturbing" message).  My current strategy at 57 total levels is to evict anyone with less than 8 skill on their dream job, and not bother doing cross-skill jobs lower than 7.
Answer: Well if your resident's skill is under 5, it'll take longer to make an item.  But then, if all your residents skill in the shop is 9, it will subtract 3 minutes to make 1 item.
Comment: I'm not sure I follow...the time is directly proportional to the total skill on a given floor, I don't think there's a triple-9 bonus.


How can I disconnect this sprayer hose?

Question:
I've already removed the faucet and am trying to disconnect this line so I can remove the weight and pull all the lines through. Does anyone know how I can disassemble this?
Comment: I would look at the bottom of the faucet , with no flats on either side that may be a swivel joint.  If the fitting on the bottom of the faucet is small enough it may slide through the weight as I don't see a split and that fitting is larger than the metal flex. If the top fitting is smaller that may be the way to go.
Comment: If it's being replace (and doesn't need to be saved), apply a heavy pair of tin snips to the braided line and simply cut it.
Answer: I would try vise grip pliers.
If there are no flats spots on the chrome articulated hose's fitting to accept a wrench then i would use a cloth and vise grip pliers to clamp onto the chrome fitting. ( wrap the cloth around the fitting to protect it from the jaws of the pliers )
Try to clamp onto the ring of thicker metal closest to the brass fitting  side of the braided hose. Try a not to tight grip first and see if it spins. Tighten up the vise grips if the spins.
Once the vise grip pliers are clamped you can use an adjustable wrench on the brass fitting to see if you can loosen the connection.
If you do not care about the finish of the chrome  then do not use the towel.
FYI: Vise Grip is a brand name that is commonly use to describe all locking pliers.

How can I disconnect this sprayer hose?