Java Looping a switch-case statement on "invalid input"

Question: I am looking to update my code to loop my swtich statement if a user inputs anything that doesn't have an option defined in it. I have scoured the numerous pages here that return from various search terms and have come close but so far no luck still.
My code here should get any one that wants to take a stab at it going.
 java.util.Scanner;
 //import java.lang.Character.*;
 //Thought this was needed to grab single char but its not
 public class caseloop {
 //main Method
 public static void main(String[] args)
 {
  Scanner input=new Scanner(System.in); //make so you can give input
  boolean go = true; // for starting main outer loop
  boolean run=true; // start inner loop
  while (go==true)
  {
    while (run==true)
    {
       //Output
       System.out.println("Enter option \n 1-Do this \n 2-Do this thing \n 3-Do this other thing");
       int option= input.nextInt(); //grab option number

       switch(option)
       {
         /*
          * This needs to loop and prompt user again if anything other than 1,2, or 3 is entered.
          */
         case 1:
           System.out.println("Option1");
           break;
         case 2:
           System.out.println("Option2");
           break;
         case 3:
           System.out.println("Option3");
           break;
         /*case 4:
           System.out.println("Option1");
           System.out.println("Option2");
           System.out.println("Option3");

           break;
         *
         *
         * Case 4 was for debug
         *
         */
         default:
           System.err.println("Invalid option selected");
           /*
            * On input that is not defined with in the switch-case it will revert to "default"
            * this fault staement needs to tell ther usere their option is not vaild and then
            * prompt them to try it again to enter an option. I can not get it to reprompt.
            * I have tried a while and an if loop both sorta worked but did not actually loop
            * back to display again. I have been instucted that I am to not use a  try catch statment
            * unless of course that is the only viable option in whichcase I will use it anyways.
            */

           //stupid default statement and its redundent built in "break;"

       }
      run=false;
      }

   /*
    * Outer Loop to prompt user if they want to run the entire program again with new entries.
    */
   if (run == false)
   {
     System.out.println("Would you like to run again? Y/N");
     char again = input.next().charAt(0);
     again = Character.toUpperCase(again); //force all leters inputed to upper case, lower would work too if i change if conditions
     if (again == 'Y')
     {
       run = true;
     }
     else if (again == 'N')
     {
       System.out.println("Goodbye.");
       go=false;
     }
     else
     {
       System.err.println("Invalid entry. Try again.");
     }
   }
  }
 }
  //System.err.println("An error occured please try again");

}

Any assistance in this would be much appreciated.
Comment: Upon further testing using all suggestions here I ended up using both methods inside of another while loop in the final program. Thanks for the help everyone. :D
Answer: You are using the run variable in a very odd way. Since you set the run to false at the end of the loop, the loop will never repeat. If you change it around so that only the valid options set run=false, inputting the wrong option will cause the loop to run one more time.
Remove run=false at the end of the switch statement, add it after the System.out.println("OptionX");
Comment: Many thanks for the fast response. Online community is of great help.
Answer: The "run=false" part is not in the right place, it's executed whatever the answer (valid or not).
You should move the "run=false;" inside each valid case statement,like :
case 1:
       System.out.println("Option1");
       run=false;
       break;

By the way : "while (run==true)" is redundant, you can write "while(run)"
Comment: original implementation has while(run)
If I could up vote and/or have 2 accepted answers, I would.
Answer: You can Add a label to your loop. This way when you got the right option you'll exit the loop.
loop: switch(option)
  {
 /*
  * This needs to loop and prompt user again if anything other than 1,2, or 3 is entered.
  */
 case 1:
   System.out.println("Option1");
   break loop;
 case 2:
   System.out.println("Option2");
   break loop;
 case 3:
   System.out.println("Option3");
   break loop;
 /*case 4:
   System.out.println("Option1");
   System.out.println("Option2");
   System.out.println("Option3");

   break;
 *
 *
 * Case 4 was for debug
 *
 */
 default:
   System.err.println("Invalid option selected");
   continue; //this causes control to go back to loop condition

}

Answer: The problem is that after executing statement under default, it sets the boolean run to false, and thus, comes out of the loop. What we need is a way to skip this:-
run = false;

and instead go directly to loop condition. One solution would be to add a 'continue' statement under default:-
 switch(option)
   {
     /*
      * This needs to loop and prompt user again if anything other than 1,2, or 3 is entered.
      */
     case 1:
       System.out.println("Option1");
       break;
     case 2:
       System.out.println("Option2");
       break;
     case 3:
       System.out.println("Option3");
       break;
     /*case 4:
       System.out.println("Option1");
       System.out.println("Option2");
       System.out.println("Option3");

       break;
     *
     *
     * Case 4 was for debug
     *
     */
     default:
       System.err.println("Invalid option selected");
       continue; //this causes control to go back to loop condition

   }

Comment: A good option since it has minimal code changes but in a small scale implementations such as this, the continue works great. However in a larger environment where there are the 2 while loops, with several if loops ultimately  ending in else which leads to to the switch it too loops to the top of the inner while loop prompting for all input again rather than just the input for the switch-case


How to delete file Using SubString of that File Name

Question: I have file like
LOG_EXPORT_TIME_STAMP_IMAGES-LOG1-T20130119_000817
LOG_EXPORT_TIME_STAMP_IMAGES-LOG1-T20130119_000818
LOG_EXPORT_TIME_STAMP_IMAGES-LOG1-T20130119_000819

at location "C:\temp" I want to delete all files whatever starting with "LOG_EXPORT_TIME_STAMP_IMAGES".I have done some Google and got the code like
File file = new File("c:\\Temp\\LOG_EXPORT_TIME_STAMP_IMAGES-LOG1-T20130119_000817");

file.delete()

but what I observed I will have to pass full name of the file. Can I do it by passing the sub string of that file?
Comment: be sure to check if the directory is really a directory and that each of the files you get back is really a file.  that's why I suggested looking at the recursive directory lister.
Answer: First list the files in the directory
File[] files = directory.listFiles();

Then iterate over the array and delete each file individually. This should give you more control to select files to delete.
Something on these lines:
File directory = new File("C:\temp");
File[] files = directory.listFiles();
for (File f : files)
{
    if (f.getName().startsWith("LOG_EXPORT_TIME_STAMP_IMAGES"))
    {
      f.delete();
    }
}

Answer: Use a FilenameFilter to process filenames with known patterns.
In your case, try something like this:
File[] files = directory.listFiles(new FilenameFilter()
     {
         public boolean accept(File dir, String name)
         {
             if(name.startsWith(<your string here>)
             {
                 return true;
             }
             return false;
         }

     });

Then iterate over the return file array to delete them.
Comment: dont forget to check if that "file" is actually a file and not another directory.
Comment: Thanks Pater. I will take care of it.
Answer: You need the full file name, so you have to get a list of the files in the directory and iterate over them to determine which files to delete.
This post shows how to get the list of files and use it. It does deal with directories inside directories. list all files from directories and subdirectories in Java


Algorithm to find sum of summing pair idexes

Question: I am working to create a function which, given a list of numbers and target number, returns the sum of the indexes of the list associated with numbers which can be paired with one other number in the list to create the target number. When possible, this sum should be minimized.
For example, f([0, 0, 0, 0, 1, 1], 1) should return 10 because there are two pairs of numbers which sum to one, and the lowest valued indexes of these pairs are (0,4) and (1,5), and 0+1+4+5=10.
f([1, 1, 1], 2) should yield 1 - the lowest value summing pairs indexes are (0,1) and 0+1 = 1
Here is my attempt so far. I don't understand why my algorithm doesn't work for the second case. My strategy is to search from lowest to highest index, ensuring that lower values indexes are logged first.
function pairwise(arr, arg)
{
  // initiate log with all zeros
  var log = [];
  for (var i = 1; i <= arr.length; i++)
  {
   log.push(0);
  }
  // look for summing pairs
  for (i = 0; i < arr.length; i++)
  {
    for (j = i; j < arr.length; j++)
    {
       // check if summing pair
      if(arr[i] + arr[j] == arg

        // also check if either number has been logged
        && log[i] == 0
        && log[j] == 0)
      {
        log[i] = 1;
        log[j] = 1;
      }
    }
  }

  // include only indexes with summing pairs in sum
  var summ = 0;
  for (var i = 1; i < arr.length; i++)
  {
    summ = summ + log[i] * i;
  }
  return summ;
}

pairwise([1, 1, 1], 2); // returns 3 not 1

Comment: very interesting. let me see if i can attempt to fix you algo
Comment: the main problem with pairwise([1,1,1], 2) is that you have already set the log[j] to be 1 (which is the second index) and you're not resetting it for the check against the second time the outer loop enters. your summing loop should probably be inside the i loop and adjusted accordingly
Answer: To avoid comparing an element with itself, you should use:
  for (i = 0; i < arr.length-1; i++)
  {
    for (j = i+1; j < arr.length; j++)


Dagger 2 Object cannot be provided without an @Inject constructor

Question: I'm fairly new to Dagger 2 and I have the following classes.
I have 2 modules:
DaoSessionModule
@Module
public class DaoSessionModule {

    private DaoSession daoSession;
    private Context context;

    public DaoSessionModule(Context context) {
        this.context = context;
        if(daoSession == null) {
            DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this.context, "my_pocket");
            Database db = helper.getWritableDb();
            daoSession = new DaoMaster(db).newSession();
        }
    }

    @Provides
    LanguageDao providesLanguageDao() {
        return daoSession.getLanguageDao();
    }

    @Provides
    CategoryDao providesCategoryDao() {
        return daoSession.getCategoryDao();
    }

}

and GlobalPrefModule
@Module
public class GlobalPrefModule {

    private GlobalPref globalPerf;

    public GlobalPrefModule(GlobalPref globalPerf) {
        this.globalPerf = globalPerf;
    }

    @Provides
    public GlobalPref providesGlobalPref() {
        return this.globalPerf;
    }

}

and their components go as:
@Singleton
@Component(modules = {DaoSessionModule.class})
public interface DaoSessionComponent {
    void inject(SplashActivity activity);
}

and
@Singleton
@Component(modules = {GlobalPrefModule.class })
public interface GlobalPrefComponent {
    void inject(SplashActivity activity);
}

and I build both in my application class:
daoSessionComponent = DaggerDaoSessionComponent.builder()
                .daoSessionModule(new DaoSessionModule(this))
                .build();

globalPrefComponent = DaggerGlobalPrefComponent.builder()
                .globalPrefModule(new GlobalPrefModule(new GlobalPref()))
                .build();

and inject them in my splash activity:
public class SplashActivity extends BaseActivity {

    @Inject
    LanguageDao languageDao;

    @Inject
    GlobalPref globalPerf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initInjections();

    }

    private void initInjections() {
        ZoopiApplication.app().getDaoSessionComponent().injectDao(this);
        ZoopiApplication.app().getGlobalPrefComponent().injectGlobalPref(this);
    }
}

now the problem I'm facing is that if I only inject DaoSession in my splash and comment out the GlobalPref impl it'll simply work but the moment I add GlobalPref along side with Daosession it fails to build and gives me the following error messages:
Error:(8, 52) error: cannot find symbol class DaggerDaoSessionComponent
Error:(9, 52) error: cannot find symbol class DaggerGlobalPrefComponent

Error:(16, 10) error: mypocket.com.zoopi.GlobalPref cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.
mypocket.com.zoopi.GlobalPref is injected at
mypocket.com.zoopi.activities.SplashActivity.globalPerf
mypocket.com.zoopi.activities.SplashActivity is injected at
mypocket.com.zoopi.dagger.dagger2.components.DaoSessionComponent.injectDao(activity)

Error:(16, 10) error: mypocket.com.zoopi.models.LanguageDao cannot be provided without an @Inject constructor or from an @Provides- or @Produces-annotated method.
mypocket.com.zoopi.models.LanguageDao is injected at
mypocket.com.zoopi.activities.SplashActivity.languageDao
mypocket.com.zoopi.activities.SplashActivity is injected at
mypocket.com.zoopi.dagger.dagger2.components.GlobalPrefComponent.injectGlobalPref(activity)

and both generated classes DaggerDaoSessionComponent and DaggerGlobalPrefComponent are generated in the build foloder.
What could be the reason that I can't inject both objects into the same activity?
Comment: Have you tried with single component with two modules?
Comment: @RuwankaMadhushan I thought about that but then I'll have many more modules soon and I don't know if it's a good idea to have one component to handle all modules... I don't know understand why this doesn't work
Answer: Injection has to be done from one component, and one component only.
It should be easy to see that the error message states that the object that can't be provided is the one you try to inject by the other component.
Dagger does not do "half" injections and one component has to inject all the fields. If partial injection would be possible you could end up with inconsistent states, since Dagger has no way of knowing how, when, or where you'd inject the rest of the fields. In short, it's just not possible. You'll have to use a single component.

but then I'll have many more modules soon and I don't know if it's a good idea to have one component to handle all modules...

That's okay. You will end up with quite a bunch of modules and possible quite a few components, depending on your setup. Make sure to use SubComponents where appropriate and you can even have modules include other modules, if you have big dependency groups split over multiple modules.


Dropbox install stuck at 99%, how do I fix it? (and any dpkg errors)

Question: I tried to install Dropbox using How to install Dropbox?, or with apt-get install nautilus-dropbox.
Dropbox loads until 99% and then hangs, causing the system to go to 100% cpu usage.
If I reboot or close the terminal, I sometimes get dpkg errors which prevent me from using apt-get or Software Center to perform any package management functions.
I would like to resolve all these and just get Dropbox working. How do I do that?

Note: This question is possibly answered in two parts:

The accepted answer tells you how to install Dropbox.
But if you  have dpkg errors, see this answer before you use answer 1 to install Dropbox.
Comment: Can you confirm this is **Ubuntu 12.04**, 32/64bit ?
Comment: If that post doesn't solve it for you, unfortunately it's quite possibly another bug.
Comment: Added a 12.04 tag for clarity
Answer: There already is a bug filed: 1016559
If you have a LaunchPad account, don't forget to add your name to the bug.
Work arounds are listed here.

Download the Dropbox .deb file from: https://www.dropbox.com/install?os=lnx
Open the .deb with Ubuntu Software Center and begin installation
When you see the screen saying "Start Dropbox to finish installation", press CLOSE
Install the dropbox daemon (nautilus-dropbox) using this command (from https://www.dropbox.com/install?os=lnx):
cd ~ && wget -O - "https://www.dropbox.com/download?plat=lnx.x86_64" | tar xzf -

[ for 32bit, just change detail to ?plat=lnx.x86 ]
Restart computer

Now you should have Dropbox working, including the notification icon
  and the Dropbox icon overlays in Nautilus.

Forum thread on the Dropbox Forums
Another thread from the Dropbox forums
Comment: The bug still persists in 2015 and I solved with this answer
Answer: If you have dpkg errors from trying to manually install, fix them first!

Run sudo dpkg -r nautilus-dropbox

You may get an error the first time, followed by a popup saying "Dropbox requires Nautilus to be restarted -- just Close it.

Run sudo dpkg -r nautilus-dropbox again, and it should end with Removing nautilus-dropbox ...

That's it! Do a sudo apt-get update just to refresh everything. Then follow the steps in the accepted answer to successfully install Dropbox.
Comment: My problems with the dpkg lock persist.
Comment: It was caused by the 99%-issue, but okay.
Answer: I couldn't uninstall dropbox nor use sudo dpkg --configure -a because of a lock on dpkg base.
To resolve it I had to kill all dropbox processes (you can find them by using ps -a | grep dropbox) then use sudo kill -s 15 pid_of_dropbox.
After that all problems I succeded to uninstall dropbox but it took me while to find how to do it.
Answer: The accepted answer didn't work for me maybe because things have changed since or my situation was not exactly as the answer-providers? There was a missing step needed before it all came together. Maybe there's not a lot of difference as the Dropbox daemon would have started when the system was restarted as advised.
However, the Dropbox-recommended way gives immediate success feedback and is less Windowsy than the accepted answer. Hope this helps!
The instructions I reproduce below from the Dropbox website worked for me on Ubuntu Desktop 12.10
Install Dropbox via command line
The Dropbox daemon works fine on all 32-bit and 64-bit Linux servers. To install, run the following command in your Linux terminal.
32-bit:
    cd ~ && wget -O - "https://www.dropbox.com/download?plat=lnx.x86" | tar xzf -

64-bit:
    cd ~ && wget -O - "https://www.dropbox.com/download?plat=lnx.x86_64" | tar xzf -

Next, run the Dropbox daemon from the newly created .dropbox-dist folder.
    ~/.dropbox-dist/dropboxd

Comment: This solution solves the always "Connecting..." status problem on my Dropbox installation on Ubuntu 12.04.5
Answer: After you start Ubuntu, and you are at the login screen, you need to press Control Alt F1. You will then see a screen with a login prompt. Log into your account from there. Next, you will need to run the following commands:
sudo apt-get -y install nautilus-dropbox &&
 sudo apt-get purge nautilus-dropbox
This will install Dropbox on your system, since it was not installed properly before and might not be removed correctly, and then fully Dropbox.
Answer: Well, I had exactly the same problem; I also followed the link you gave and it didn't solve it for me! The thing is, that I did that 3 days ago and I don't quite remember the whole process very well. Sorry for this...
These are the steps I did and solved the problem (NOTE THAT  the fact that it worked for me doesn't mean that it will work for you!):

Run this from the terminal (to open the terminal hit Ctrl+Alt+T):

32 bit
wget -O ~/dropbox.tar.gz "https://www.dropbox.com/download?plat=lnx.x86"

64 bit
wget -O ~/dropbox.tar.gz "https://www.dropbox.com/download?plat=lnx.x86_64"

Open nautilus to your home directory and untar the dropbox.tar.gz file

A hidden directory (.dropbox-dist) will be created. Click on the icon, right from your username on the upper right corner of your screen, and then click on startup applications. Click on add:

In the 'Name' field add 'Dropbox', and in the 'Command' field click on 'Browse...', then head to your home directory, give Ctrl+H to reveal hidden files, click on dropbox-dist and then select the file dropboxd. In the 'Comment' field, add whatever you want.

That is the part that I don't remember very well...Open a terminal and give
cd ~/.dropbox-dist;./dropboxd

It will ask you for your account info as usual, I think, or it will say that dropbox isn't installed (and it will say to run dropbox -i start). Do whatever necessary (sorry :( i don't remember what I did) so as to fill your account info and such and to login into your dropbox account!

After all this, check if dropbox is running (open system monitor), and if it is, then stop it (kill it or whatever :D). Install hamster-indicator and set it to start on system startup.

Restart your computer!

Now you should have the dropbox running and a working indicator of it! You can now uninstall hamster-indicator (I told you to install it so as to have a working indicator, that's how I fixed mine!)

Sorry if this don't work for you....
Answer: For 32 bit machines make sure to use:
cd ~ && wget -O - "https://www.dropbox.com/download?plat=lnx.x86" | tar xzf -

... as indicated in the instructions.  I was not paying attention and thought the warning applied only to the original package downloaded from the dropbox web site, and had to redo the whole thing (the instructions provided above are for 64 bit).
The answer provided works if you follow the directions exactly. Other solutions, that I found elsewhere, did not work.
Answer: You can find the complete solution here.
Comment: Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.
Answer: I (believe) followed all the instructions here and could not finish installing Dropbox correctly. I had read in a recent post in
https://bugs.launchpad.net/ubuntu/+source/nautilus-dropbox/+bug/1016559
that the installation bug was fixed but apparently something I have done before is not permiting me to finis my installation.
I even followed the purge instructions posted in
http://forums.dropbox.com/topic.php?id=62952
but still could not get Dropbox to run.
When I followed the workaround and finally
typed ~/.dropbox-dist/dropboxd I got:
Traceback (most recent call last):
  File "__main__dropbox__.py", line 16, in <module>
  File "explicit_imports.py", line 11, in <module>
  File "ui/common/selective_sync.py", line 12, in <module>
  File "arch/__init__.py", line 24, in <module>
  File "arch/posix_common/util.py", line 16, in <module>
ImportError: /home/ale/.dropbox-dist/netifaces-0.5-py2.5-linux-i686.egg/netifaces.so: wrong ELF class: ELFCLASS32

I am running Ubuntu 12.04 on 3.2.0-26-generic kernel x86_64.
So I deleted the /.dropbox-dist/netifaces-0.5-py2.5-linux-i686.egg/ folder and now dropbox started and recognized everything.


What does "<<=" do in sbt settings?

Question: I am learning to write some more advanced sbt build files, and I came across sbt-proguard's code:
  binaryDeps <<= compile in Compile map { _.relations.allBinaryDeps.toSeq },
  inputs <<= fullClasspath in Runtime map { _.files },
  libraries <<= (binaryDeps, inputs) map { (deps, in) => deps filterNot in.toSet },
  outputs <<= artifactPath map { Seq(_) },

I want to know what does <<= mean in this context?
How do I understand the map function at the 3rd line?
Comment: In a more recent build (sbt >= 0.13), we would write it in a simpler way: `libraries := binaryDeps.value filterNot inputs.value.toSet`.
Comment: See [How is an sbt task defined using <<= different from one defined with := that references another setting's .value?](http://stackoverflow.com/questions/20642575/how-is-an-sbt-task-defined-using-different-from-one-defined-with-that-ref).
Answer: The <<= is a method on DefinableSetting (mixed in by TaskKey, InputKey, and SettingKey) which provides a way to initialise a build setting. It's described in the older docs here:
:= assigns a value, overwriting any existing value. <<= uses existing values to initialize a setting.

Essentially, in 0.12 (and current versions, for compatibility) it was a way to define a build setting in terms of some other build setting(s).
As @sjrd points out, in 0.13 a new task setting syntax was introduced allowing you to do this with := instead.
The map in the third line is creating a new settings value by getting only dependency items from binaryDeps which are not already in inputs, i.e. transform these two settings into this new one.

What does "<<=" do in sbt settings?


Use different AppData folders for Debug and Release builds of an application

Question: If I have an application named MyApplication, is it possible to have a custom location for the local AppData directory of this application? E.g.: C:\Users\User1\AppData\Local\MyApplication2. I can't find anywhere how to change this.
EDIT
Clarification: I don't want to create an auxiliary directoy called C:\Users\User1\AppData\Local\MyApplication2. I want the system to recognize C:\Users\User1\AppData\Local\MyApplication2 as the actual local AppData directory of MyApplication.
EDIT 2:
I really need a way to have both debug and release versions installed on my computer in order to be as close as possible to reality. Until now I managed to change where the application is installed and other application level identificators, but I couldn't change the AppData in order for each of them to use different settings files.
Comment: Out of curiosity, what would you expect this to accomplish? It's a system wide setting, so all you'd do is make it so any other app (or the OS itself) that uses %LOCALAPPDATA% would end up creating its folders beneath your application folder there.
Comment: I really need a way to have both debug and release versions installed on my computer in order to be as close as possible to reality. Until now I managed to change where the application is installed and other application level identificators, but I couldn't change the `AppData` in order for each of them to use different settings files.
Comment: So why do you need to change the entire OS location of LOCALAPPDATA? Create two folders (%LOCALAPPDATA%\MyApp\Debug and %LOCALAPPDATA%\MyApp\Release) and a compiler define or command line switch or whatever based on whether it's debug or release to use the appropriate folder. E.g., #IFDEF DEBUG.
Comment: Hmm, this never crossed my mind. Can you add this as an answer in order for me to accept it? I will actually leave the release version like it is (because users have already installed the application) and I will create a `%LOCALAPPDATA%\MyApp\Debug` like you said, for the debug version only on my PC.
Comment: I can do that, if you can edit your question to put the contents of your previous comment (the one starting with *I really need a way*) so that there's something in the question I can answer.  :-)
Comment: I added the explanation as to why I need this
Comment: I added an answer, with an example of one way to approach the issue. It may give you an idea of how to handle things without the global change.
Answer: There's no need to move the location of {localappdata} if you're just wanting to change the location while developing your code on your machine. In fact, there's no need to get Inno Setup involved in this at all.
Just define a local variable in your code based on the value of a compiler define (such as #IFDEF DEBUG, for instance). Create the %LOCALAPPDATA%\MyApplication2 folder during the installation. When DEBUG is defined, append to that location at runtime (which would be during development) to read/write your configuration info from a Debug folder.
I don't know what language you're coding in, but in Delphi it would go something like this:
{$IFDEF DEBUG}
const
  ConfigDir = 'Debug\';
{$ENDIF}

// At application startup, retrieve the contents of %LOCALAPPDATA% via API call
// or by retrieving the contents of the environmental variable (say into the
// DataDir variable). Then...
{$IFDEF DEBUG}
DataDir := DataDir + ConfigDir;
// If needed, you can check here for whether the folder exists and
// create it if it doesn't.
{$ENDIF}

Now all of your code accessing the config info just retrieves it from DataDir, which will adjust based on whether you're in Debug or Release mode.


Move grounds to subpanel when I moved 8 single pole breakers to same subpanel?

Question: When I move 8 breakers from main panel to a subpanel (a few feet away) can I simply move the hot and neutral only to subpanel? The 8 breakers are grounded in the main panel already.
A 100 amp breaker feeds the subpanel (240V) using aluminum SE 2-2-2-4. I got subpanel neutral bus connected to main neutral bus. I got subpanel ground bus connected to main ground bus.
The subpanel has ground and neutral disconnected. Any NEC code reference would be welcome.
The right side of main panel (16 red wire twist caps) extend the 12 AWG wire to middle panel.
Picture of setup:
Comment: If this is NM cable, there would be no way to move the hots and neutrals but leave the grounds behind. I assume that under all circumstances the ground for each paired hot and neutral would go to the subpanel. I'm not putting this as an answer because I am not an expert.
Comment: What wiring method is in play here?  NM/Romex? Armored or metal-clad cable? Conduit?
Comment: @ThreePhaseEel I updated original with picture and some text (notice my Type CC 100mA fuse holder).
Comment: How long is the conduit run between the main panel and the 100A subpanel?
Comment: @ThreePhaseEel 1 1/2" EMT is 30 inches long between main and middle panel
Comment: Nice work! That looks really good.
Answer: The grounding should be fine...
What you're doing here is running multiple circuits (the feeder out to the subpanel and the branch circuits back) through a single raceway with a single equipment grounding conductor, as implicitly provided for in NEC 250.122(C):

(C) Multiple Circuits. Where a single equipment grounding conductor is run with multiple circuits in the same
  raceway, cable, or cable tray, it shall be sized for the largest
  overcurrent device protecting conductors in the raceway,
  cable, or cable tray. Equipment grounding conductors installed in cable trays shall meet the minimum requirements
  of 392.10(B)(1)(c).

This, plus the fact that a single EGC can branch into multiple EGCs downstream of a panel when a multi-circuit raceway splits into individual circuits, means that you are fine on the grounding standpoint.
However, that poor, sweltering feeder cable isn't!
That feeder cable, on the other hand, is very not-fine.  Putting 18 current-carrying wires (8 branch circuit hots and neutrals each, as well as the 2 feeder hots) into a single raceway forces a whopping 50% derate on the conductors (as per Table 310.15(B)(3)(a)), and 30" is a bit too long for the short-raceway provisions in 310.15(B)(3)(a) point 2, which are limited to raceways 24" or shorter.  This means that your 2/2/2/4 SE cable is limited to 50A(!) and your 12AWG branch circuit wires can only handle 15A.
Fixing this would require re-running the middle panel's feeder and returning branch circuits using properly sized wires -- the branch-circuit wires would need to be bumped up to 10AWG, and the feeder hot wires would need to be bumped up to 1/0AWG (although a smaller neutral could be acceptable here, depending on the amount of unbalanced load anticipated in the subpanel).  With your 1.5" EMT, the 10AWG THHN branch circuit wires (at 13.61mm2 of fill each), and compact stranded XHHW-2 singles for the feeder hot conductors, this leaves you with 422.96mm2 of fill used out of 526mm2 usable, before accounting for the neutral -- a full-size 1/0AWG neutral takes up another 102.6mm2 of fill, pushing you to the very limit of what that conduit can handle.
As a result, I'd recommend replacing it with 2" EMT to provide room for growth, or running two more EMTs (1/2" will do, with 72mm2 used vs 78mm2 usable) to allow the use of 12AWG wire for the branch circuits coming back via the new conduits.  (Adding the extra conduits doesn't change the grounding logic from above at all, by the way.)
Comment: Would it be okay to mount a junction box above and to the right of the main panel, move 8 branch circuits out of main panel and into junction box, then bring the NM-2 cables across ceiling and into top of middle panel? That way those 8, 16 current carrying conductors, will completely bypass the main and EMT connecting main and middle panels. I would also pull the grounds out of main and put through same path. Would that avoid the derating issues?
Comment: @ptay -- that'd work, yes.
Comment: @ptay -- however, you'd still need to use 10AWG between the middle panel and the new junction box unless you split the run across two conduits.
Comment: Would rerouting the 8 x 12/2 NM that currently goes into the top of main through a junction box require the use of conduit? At the top of the main panel I planned to simply pull out the existing 8 x 12/2 circuits and bend it to the right and terminate into junction box (~2" away). Then splice with longer 8 x 12/2 NM and run that across ceiling on running board (about 20 inches) then parallel with joists and straight down into top of middle panel. Could I mount the junction box on the ceiling to avoid conduit requirements?
Comment: @ptay -- if you're making the run from the j-box to the panel with NM, you don't need to use conduit for it, no
Comment: I heading to local hardware store to grab the stuff. Would a 8" x 8" x 4" junction box suffice (256 cu. in.)?
Comment: @ptay -- that would be ample space :)
Answer: You need a serious case of Harper's Junction Boxes
My panels are distinctive because all around them are junction boxes 6-18" away. And then, many circuits come into those junction boxes, get spliced in those boxes, and onto the main panel.  I do that because breaker thieves cut all the wires at the edge of the panels, leaving every wire 2' short.
But I find it useful for lots of things.  Want to add GFCI to a circuit? Don't spend $45 on a GFCI breaker, spend $16 on a GFCI deadfront and $1 for a receptacle cover for that box.
Anyway, in your case, you don't necessarily need to use EMT, but the general idea is the same: pull the cable out of the main panel, bring it to a right-positioned box, splice there, and onto the new panel.  However if you do use EMT, that's your ground path.  And you can make those junction boxes attached to the ground of the subpanel, where it belongs.
In retrofitting grounds, the ground must go back to the same panel as the conductors come out of.  In a "network of EMT" like you have here where the whole works is the ground, it's almost moot... almost.
The thing to beware of is throwing a bunch of circuits down your 1-1/2" conduit - you have to watch out for the derate table. Because of the derates already present on 14, 12 and 10 AWG wire, that derate table has no effect with 4 or fewer cables in one conduit, raceway or bundle. However it does affect subpanel feeder more acutely, so watch out.
Comment: What do you mean by "breaker thieves"? Are they stealing the breakers or the copper wire? Is theft now so common that one has to design the wiring for easier repair after a theft? Could you post a picture of one of your panels with all these junction boxes around it?
Comment: @JimStewart The breakers.  The $4 breakers.   I have no idea why.  It was a really old panel, maybe they thought the breakers were scarce, maybe they had no idea what to take. Given the stuff they *didn't* take, it's clear they weren't MIT graduates...
Comment: @Harper Can I get one large junction box for the 8 circuits, install upper right of my main, then bring the 12/2 solid Romex NM-B from junction box into top of middle subpanel? I would save room in main, it would bypass the EMT between main and subpanel, and be grounded in subpanel.
Comment: Yes, you could have one big junction box. You need roughly 5 cubic inches per splice, plus 5 c.i. once.   I used these lovely 6x6x10s (600c.i.) that I fed with 4-5 conduits to keep to the 4 circuit per conduit max. ( tge entire building was conduit ).   Remember the 4-max rule also applies to closely bundled NM.


and the web.config transformation just won't work.... won't work grrrrr

Question: I am using Visual Studio 2010. I have this web.config
<?xml version="1.0"?>
<configuration>
  <system.web>
      <compilation debug="true" targetFramework="4.0" />
      <authorization>
        <allow roles="domain\allow" />
        <deny users="*" />
      </authorization>
    </system.web>
</configuration>

Now I have gone to solution -> Configuration Manager and added a new configuration called "Production"
Now I came and right click on my web.config and clicked "Add Config Transforms"
Now I can see a file called web.Production.config
I go and add this to my file
<?xml version="1.0"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
  <connectionStrings>
    <add name="FooDB" connectionString="Data Source=FooServer;Initial Catalog=FooDB;Integrated Security=True;" xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
  </connectionStrings>
  <system.web>
    <compilation xdt:Transform="RemoveAttributes(debug)" />
  </system.web>
</configuration>

Now when I build and publish my project I see an error message
Web.Production.config(17,4): Warning : No element in the source document matches '/configuration/connectionStrings'

Comment: Are you setting the publish profile to `Production` during the publishing?
Comment: Maybe because the `connectionStrings` element does not exist in your base `Web.config`. You could try adding an empty node for it. Mine has a value I want for local debugging and I use **replace** transform instead of **add**.
Comment: Yes. I double checked and the profile does use 'Production' as build configuration. However I did notice an error in the output `\Web.Production.config(3,4): Warning : No element in the source document matches '/configuration/connectionStrings'`
Answer: I had the same problem when I was trying to use publish profiles. Here's what worked for me:
Call your additional Web.config files Web.Debug.config (Test) and Web.Release.config (Production) then during publishing you associate Debug configuration to the Test publish profile and Release configuration to the Production publish profile.
EDIT:
Try changing the xdt:Transform to Insert and removing the xdt:Locator attribute.
Answer: Move connectionStrings to the main web.config. The only things that should appear in your production config are the transformations.
Comment: My point is that there is no connectionString to transform so there's no need for it to be there. So either move it to web.config or remove it entirely.
Comment: I'm just assuming that he doesn't want the connectionString to be present during debugging, since he's going through the trouble of adding it with a publish profile.
Comment: I do need the the connection string during development. that is why I in configuration manager I have a profile called Development.
Comment: When I say _debugging_ I'm referring to you building locally and running the application from localhost, which means you wouldn't be publishing. Like I said earlier, the Web.config file should have your _local_ settings and the publish profiles should be how you want the deployed application to be configured on your various environments (Production, Test, etc...)


Laravel, PHP 7.3 nginx 502 upstream prematurely closed FastCGI stdout

Question: I have a laravel application behind nginx and recently updated php from version 7.1 to 7.3 (docker image 7.1-fpm-alpine to 7.3-fpm-alpine).
I use exceptions that have a render() function to output error pages. Laravel logs the exception message and complete stacktrace.
Since updating to php 7.3, nginx shows it's default 502 error page and logs [error] 11#11: *61 upstream prematurely closed FastCGI stdout while reading response header from upstream, client: [...]. The stacktrace in nginx is truncated after 2048 bytes.
The serverfault question "Nginx/PHP-FPM long log lines get truncated" suggests that nginx handles only errors up to 2048 bytes.
In PHP 7.1 the stacktrace was truncated already.
Am I right, that the problem is that PHP now logs the complete stack trace instead of truncating it?
Is there a way to truncate log output in PHP to return to the behaviour of PHP 7.1?
Answer: By default, PHP 7.3 should function the same as previous versions (it will truncate at 1024 characters), but there is new configuration to allow more characters:

log_limit integer
  Log limit for the logged lines which allows to log messages longer than 1024 characters without wrapping. Default value: 1024. Available as of PHP 7.3.0.

I had this issue when using the official Docker PHP 7.3 container, which is specifically overwriting the default in the Dockerfile:
echo 'log_limit = 8192';

It can be fixed by overriding log_limit so it falls under nginx's limit of 2048:
[global]
log_limit = 1024

Comment: Relevant bit from [this answer](https://stackoverflow.com/a/19084625/2532203): "**You need to recompile Nginx if you want log lines longer than 2048 bytes.**"
So it is not usually possible in a Docker environment to modify this limit, hence overriding the log limit as per your answer is pretty much required.
Answer: My app uses errorlog log driver, and I came across the same problem. In Laravel, I modified app/Exceptions/Handler.php in the following way (much inspired by your question, actually):
public function report(Exception $exception)
{
    $message = get_class($exception) . ": {$exception->getMessage()}. Trace:\n{$exception->getTraceAsString()}";
    error_log(substr($message, 0, 2048));
}

The substr() part is what does the trick. I still have to develop a nicer and more universal solution though, cuz this is just a quick-n-dirty fix.
Comment: It'd be great if you could update your answer if you've found a better solution.
Comment: Seems like a good workaround, thanks for the answer. I'll mark it as accepted if there is no better solution in a while.


Nested Destructuring in JavaScript Inside Objects

Question: I need to declare the orderItems inside a nested object in my React app.
Sometimes order is null so orderItems is not found. So the error is of course Cannot read property of orderItems of null. How do I fix this?
 const { order: { orderItems = [] } = {} } = res.cartFind

Answer:
Sometimes order is null so orderItems is not found.

Since it's null (not undefined), we can't work around it with defaults (since they only apply to things that are missing or undefined, specifically). But since it's at the top level of res.cartFind, we can work around it with nullish coalescing. Remove the {order: ....} part and move .order to the end, then default it with ?? {}, and destructure that:
const { orderItems = [] } = res.cartFind.order ?? {};

Live Example:

function example(res) {
    const { orderItems = [] } = res.cartFind.order ?? {};
    console.log(orderItems);
}

console.log("When order is null:");
example({
    cartFind: {
        order: null,
    },
});

console.log("When order is not null:");
example({
    cartFind: {
        order: {
            orderItems: [1, 2, 3],
        },
    },
});

In comments I think you've asked what if order is there and it has orderItems: null in it. With the above, you'd end up with null, because (again) defaults only get used when something is missing or undefined.
The two things that handle both undefined and null (we call those "nullish" values) are nullish coalescing (which we used above), ??, and optional chaining, ?..
If order may be missing, or it may be present but with orderItems: null in it, you can handle that with a combination of the two:
const orderItems = res.cartFind.order?.orderItems ?? [];

Here's how that works:

If res.cartFind.order is null or undefined (or missing,which is effectively undefined), then res.cartFind.order?.orderItems results in undefined (it doesn't throw an error the way it would if there weren't a ? after order). If res.cartFind.order isn't null or undefined (nullish), then we try to get orderItems from it.
So now res.cartFind.order?.orderItems has been evaluated and given us either undefined or the value of orderItems (which may be anything). By using thatResultValue ?? [] we're saying "use thatResultValue if it isn't null or undefined, but use [] if it is."

Live Example:

function example(res) {
    const orderItems = res.cartFind.order?.orderItems ?? [];
    console.log(orderItems);
}

console.log("When order is null:");
example({
    cartFind: {
        order: null,
    },
});

console.log("When order is not null and has a valid orderItems:");
example({
    cartFind: {
        order: {
            orderItems: [1, 2, 3],
        },
    },
});

console.log("When order is not null but doesn't have orderItems:");
example({
    cartFind: {
        order: {
        },
    },
});

console.log("When order is not null and has orderItems but it's null:");
example({
    cartFind: {
        order: {
            orderItems: null,
        },
    },
});
.as-console-wrapper {
    max-height: 100% !important;
}
Comment: @Joseph With `{ cartFind: { order: { orderItems: null } } }` you will end up with `const orderItems = null` as well, not an empty array. If you need to prevent that, you cannot use destructuring with default values, I recommend `const orderItems = res.cartFind.order?.orderItems ?? [];`.
Comment: @Joseph - See the end of [Bergi's comment here](https://stackoverflow.com/questions/68517436/nested-destructuring-in-javascript-inside-objects/68517462?noredirect=1#comment121093107_68517462), they've already shown you how to handle that with a combination of [nullish coalescing](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) and [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining).
Comment: @Joseph See above. You'll need two statements, one to destructure `const {loading, error, data} = useQuery(…);`, the other to safely access `orderItems` from the data.
Comment: if any variable found in the future inside res.cartFind.order that is null would be automatically be fine, right?
Comment: @Joseph - I'm afraid I don't understand the question.
Comment: if there objects, array or variables that is located inside `res.cartFind.order` that its value is undefined or null then I don't have to worry about getting that same error as mine before cause you already use the nullish coalescing?
Comment: Not with the code above getting `orderItems`, no.
Comment: Thanks guys @Bergi @T.J. How about this one? What would be a good look for this? This is different example by the way.
`data: { cartFind: { order: { orderItems} } = {} } = {}`
Comment: @Joseph That's incomplete, currently a syntax error. And like in the other cases, defaults in destructuring never handle `null` values.
Comment: @Bergi. this is the complete one `const {
    loading,
    error,
    data: { cartFind: { order: { orderItems} } = {} } = {},
  } = useQuery(GET_ORDER, {
    variables: { page: '111' },
  })`
Comment: @Joseph Ah, ok. But no, the problem is still the same.
Comment: @Bergi. How would fix it? if orderItems is sometimes null?
Comment: @Joseph - I've added to the answer to show handling `order: { orderItems: null }`.


How can a vector space $V$ over a field have $V$ as a basis?

Question: I think my question is related to Free vector space over a set, Non-numerical vector space examples and Formal (series/sum/derivative…).
I'm reading a paper, which starts with the following sentence (the original source is "Flag Algebras" by Razborov)

Let $\mathbb{R}F$ be the real vector space with basis comprised of all elements of $F$; in other words, the space of all formal, finite $\mathbb{R}$-linear combinations of elements of $F$.

Let me summarize my understandings first. We can define the set $\mathbb{R}F$ as a formal sum as $\mathbb{R}F=\{\sum_{f \in F} \lambda_f f | \lambda_f \in \mathbb{R}\}$ and construct the structure of a vector space as described in Free vector space over a set.
Now, here is my trouble: If $\mathbb{R}F$ is supposed to be a vector space, then, due to the vector space axioms, the following must be satisfied: Let $a, b \in F$, then $a+b=c \in F, \forall a,b \in F$, without defining the actual operation "+" of our vector space (since we speak of "formal" sum here). But if $F$ is the basis of our vector space, then all elements of $F$ must be linear independent, thus there cannot exist a $c \in F$ for which $a+b=c$ with $a,b \in F$. (my definition for a vector space is taken from "Advanced Linear Algebra" by Steven Roman").
I would suppose that we define the vector space as the set of all formal sums of elements of $F$ with real coefficients and take the axioms for granted. This works fine for associativity, the inverse element, etc., since we do not define "+" and "juxtaposition" anyway, but I don't see how the basis can be the whole set $F$.
My question is, how can the vector space axioms be satisfied? Can someone give me some examples, or clarifications?
Comment: You cannot add elements of $F$. $\mathbb{R}F$ is the vector space, not $F$. So you don't want to write $a+b=c\in F$ but rather $(\sum_i \lambda_i f_i)  \,\,+ \,\,(\sum_j \lambda_j f_j) = \ldots$ (another formal sum).
Comment: Usually a way to construct this is to take $\mathbb{R}F$ as the set of all finitely supported functions $f\colon F \to \mathbb{R}$. Realising it as a subspace of an existing vector space (one still has the prove that the "finitely supported" property is preserved under addition and scalar multiplication) shortcuts around having to check a lot of axioms. Then expressions like $a + 2b$ for $a, b \in F$ can be understood just as shorthand notation for these finitely supported functions.
Answer: You did not apply the vector space axioms correctly.  If $\mathbb{R} F$ is a vector space, then for all $a,b \in \mathbb{R} F$ (not $F$, as you stated), we have some $c \in \mathbb{R} F$ (not $F$) with $c = a + b$.
Comment: The sum of $f_1$ and $f_2$ in $\mathbb{R} F$ is the formal sum $f_1 + f_2$ as an element of $\mathbb{R} F$, i.e., from your description of $\mathbb{R} F$, it is the element defined by $\lambda_{f_1} = 1$ and $\lambda_{f_2} = 1$ and $\lambda_x = 0$ for all $x \ne f_1, f_2$ (assuming $f_1 \ne f_2$).
Comment: Okay, thank you for the quick answer. Just to be sure: Let $f_1, f_2 \in F$ be two elements of our basis, $f_1+f_2$ then is in $\mathbb{R}F$ as the sum of two elements of $F$ for which we do not define what the result of this sum actually is?
Answer: You're misunderstanding what the author denotes $\Bbb RF$. It is different from $F$. Actually,what he/she denotes this way (not a very good notation, in my opinion) is usually denoted as
$$\Bbb R^{(F)},$$
which is the set of maps from $F$ into $\Bbb R$ with finite support. A well-known example is the vector space $\Bbb R^{(\Bbb N)}$, which is known, when endowed with the relevant multiplication (Cauchy product), as the ring of polynomials with real coefficients.
More generally, for any set $X$,  one defines the free $K$-vector space with basis $X$ as $K^{(X)}$ (where $K$ is the base field). The construction of the author is further generalised to the situation where the base field is only a ring $R$ (in this case, it is called an $R$-module) and it can be used to prove that any $R$-module is the quotient of a free $R$-module (all modules, contrary to vector spaces, do not have a basis).
Comment: I only meant that  the generalisation of this construct is also valid for modules over a ring. I didn't say  that $\mathbf R$ became a ring, but that the construct is valid in a more general situation.  Afield is also a ring (+ some more properties).
Comment: No they wouldn't collapse into a single number, for the same reason as, when you consider the vector space $\mathbf R^{3}$ and its canonical basis, $e_1+e_2=(1,1,0)$, not the number  $2$. So to say, in $\mathbf R^{(F)}$, $e_f$ and $e_g$  do not live in the same copy of $\mathbf R$.
Comment: Could you clarify why the base field (in my case $\mathbb{R}$) is only a ring and not a field?
Comment: I had let your answer sink in for the last couple of days. I get the idea via the construction of our vector space as you have described.However, why can we write the set as all formal sum of elements of $F$ with real scalars? Shouldn't it then be the set of all formal sums of maps from $F$ into $\mathbb{R}$, e.g. if $f_1,f_2 \in \mathbb{R}^{(F)}$, then $f_1 + f_2 \in \mathbb{R}^{(F)}$, whereby $f_1, f_2$ are mappings? What's the reason for mapping into the real numbers, other than satisfying the vector space axioms? All sums would collaps into a single number.Would highly appreciate your help


Search number of elements in List by time

Question: I have list of objects. Object has fields: name, surname and time(in long). I want to check how many items from this list have the same hour. I convert long to HH:mm and now I need to know for exampole how many items have time 0, how many time have time 1 etc. Something like this:
hours - number of elements
0     - 10
1     - 2
2     - 4
...
23    - 13
etc until get all day hours.

Any idea how can I simply achieve this idea
Answer: ArrayList<Person> people;
int[] count = new int[24];

for(Person p : people) {
    count[hourOf(p.time)]++;
}

Not sure how you have the time stored (i.e. what the long represents), but if you have HH:mm as a String, then you can compute the hour easily:
int hourOf(String hhmm) {
    return Integer.parseInt(hhmm.substring(0, hhmm.indexOf(':')));
}

where hhmm.indexOf(':') can be replaced by 2 if all hours are 0 padded.


Xamarin.Android How to Get Google Play Store app version number using Dcsoup Nuget Plugin?

Question: I am trying to get the latest version number of my store app in order to notify user for updates if they are using an older version.
This is my code so far but its obviously just retrieving the div containing the text "Version Number". How do I get the actual version number (in this case 1.1) referring to the attached screenshot of the DOM tree?
public static string GetAndroidStoreAppVersion()
        {
            string androidStoreAppVersion = null;

            try
            {
                using (var client = new HttpClient())
                {
                    var doc = client.GetAsync("https://play.google.com/store/apps/details?id=" + AppInfo.PackageName + "&hl=en_CA").Result.Parse();
                    var versionElement = doc.Select("div:containsOwn(Current Version)");
                    androidStoreAppVersion = versionElement.Text;
                }
            }
            catch (Exception ex)
            {
                // do something
                Console.WriteLine(ex.Message);
            }

            return androidStoreAppVersion;
        }

Answer: According to the parser doc,the containsOwm selector selects elements that directly contain the specified text.
As a result, your code
var versionElement = doc.Select("div:containsOwn(Current Version)");

will surely return "Current Version". The real element you would like to get is the child of the child of the sibling of  "Current Version" element. So you would have to get that element using the selector.
So you can get the version number in this way:
            var versionElement = doc.Select("div:containsOwn(Current Version)");
            Element headElement = versionElement[0];
            Elements siblingsOfHead = headElement.SiblingElements;
            Element contentElement = siblingsOfHead.First;
            Elements childrenOfContentElement = contentElement.Children;
            Element childOfContentElement = childrenOfContentElement.First;
            Elements childrenOfChildren = childOfContentElement.Children;
            Element childOfChild = childrenOfChildren.First;
            androidStoreAppVersion = childOfChild.Text;

Comment: That is correct but how do I write that in code? That is where I am stuck at. I will keep trying.
Comment: Thank you so much!
Comment: Is `Elements` an array or list. Not seeing the data type in XF namespace?


How can I get paint to come off more evenly with a heat gun?

Question: I'm stripping some paint from a very old door in my house - it's probably about 120 years old. Given the age, it's picked up several layers of paint over the years. I've already stripped the skirting boards that are of a similar age with no problems: the paint just peeled right off.
On the door, however, the paint is coming off in a rather inconsistent way. The top two layers seem relatively thin, and are coming off without too much hassle, though the paint is turning into what seems more like glue than paint as it's coming off. The lower layers (pictured) are much harder to get off (in other words, it's not coming off in one go).
For the lower layers, even leaving the heat gun on an area for a little while, the paint doesn't 'bubble' and just softens (or comes off unevenly, as in the picture). As a result, I'm having to be quite rough with it to remove it, essentially using the heat to soften it up and then scrape it off manually with force.
I was wondering, is there anything I can do to make this easier? Or is it just the case that the many layers and years on this door will mean I just need to keep going? I'd just like to get rid of the paint enough to make it sufficiently smooth to fix some of the knocks and dents in it, and then re-paint.
Answer: Perhaps you should consider using a chemical help to supplement your heat gun approach. Obviously the very old paint has lost most of the oils and resins that can help it bubble for heat removal. You are probably dealing with mostly pigments (many metal based, including lead) and very dry resins.
There are newer less caustic strippers, such as citrus based products, that take several hours to cut through the old paint and may need a subsequent application. But they may allow more complete removal without gouging the old wood.

Once you stop making satisfactory progress with the heat gun, let the wood cool than then test the stripper in a small area. NOTE - Do not, under any circumstances, use the heat gun when there is a chemical stripper on the wood. Serious chemical reaction or fire could result!
You also could try cabinet scrapers. these are much less likely to gouge than the heavy duty paint scrapers. Some have sharp corners or curves that allow you to scrape out moldings and insets. Again, these could be used once you have removed a good bit of the old paint with the heat gun.

NOTE 2 - Given the age of the paint, there is almost certainly lead (and maybe other unpleasant metals) present in the finish. Use a mask to avoid breathing the dust and chips with all these techniques.
Answer: You'll want to look up the EPA RRP (Repair Renovation and Painting) rules, for techniques for safely removing such paint. Heat over a certain temperature is a banned practice.
Since you're repainting, eventually you just give up.  If it's that well attached it's a fine surface to paint over.


How to create a peephole in a door without a hole?

Question: the entrance door is without hole, but I would like to be with a peephole. How we can create this
Comment: There are security cameras/doorbells that you can attach to the exterior of the door without the need to drill a hole.
Comment: Maybe if you explained more about your problem another solution might be suggested.  But I'm not aware of any "peephole" devices that don't require a hole to be drilled.
Comment: I mean is it possible just to drill a hole and create it or it should a new door be oredered
Comment: That is a nice looking door , anything on it would take away its charm.  So many other options out there .
Comment: Try on the ceiling a smoke with camera in it..
Comment: @RobertMoody what is a "on the ceiling a smoke..."?
Comment: To Solar Mike   they make smoke detectors with spy cameras in them.
Comment: @Robert Oh so a "smoke" is a smoke alarm... A "smoke" is also a cigarette... just asking for clarity...
Comment: Trade slang .  Same as gfci.
Answer: If when you say the door is without a hole, but you are allowed to drill one then it is a question of deciding the height and a suitable diameter.
If you cannot drill a hole then some sort of miniature camera will be needed...
When drilling a hole through the door, making sure you go through square is crucial and a tiny pilot hole then drilling from both sides gets a clean hole - at least in my experience.
Here is one possibility: Peephole on Amazon
Comment: I liked the land lord comment and  needs to be a factor  .
Answer: If you are renting, get the permission of the landlord or you might get charged for unauthorized modification considered to be damage. Some landlords might want to do the installation themselves.
Note that you generally buy the peephole and then follow the instructions for that peephole.
Some peepholes have a little cover on the inside that swings out of the way. Some peepholes give a sharp image at long distance focus and some require close focus. At age 74 I need 2.5 D reading glasses so I can tell the difference, but a young person might not detect any difference. Through some peepholes I get a sharper image with my readers on.
Comment: Also, if it's a fire door (which an apartment front door probably should be) any modification could invalidate its fire door approval.


Reading a spellbook costing all my money

Question: After reading a "dog eared spellbook" in Nethack 3.6.0, all my money is lost. I've made some search on the Wiki, but nothing relevant can be found.
So what's that evil spellbook? Is this a new feature added since Nethack 3.6.0?
Comment: That doesn't sound like a very effective hack...
Answer: No, this feature exists in 3.4.3 as well. Upon failing to read a spellbook, one of the possible effects is

All your (visible) gold vanishes: "You notice you have no gold!" ("money" in 3.6.0) (or "You feel a strange sensation.", if you had no gold).

Other possible effects include paralysis (always occurs, even with free action), random teleportation, blindness or confusion, strength and/or HP loss, and so on. The spellbook itself is also sometimes destroyed.
This is why you should never read an unidentified spellbook (unless you are a wizard, in which case you will be warned before reading too-difficult spellbooks). Always price-ID spellbooks before reading them.
As a general rule of thumb, your experience level should be around 4-5 times the level of the spellbook you're trying to read, assuming an Intelligence of ~15. When in doubt, check the formula for success rate on the wiki.
Comment: Sometimes I would read an expensive spellbook in a store on purpose, so that I may escape from(in case of teleportation) that store with all unpaid items.
Comment: Also note that a blessed spellbook is always safe to read (as mentioned in the wiki), no matter the level of the book, intelligence or experience level.
Answer: The spellbook could be anything. Your experience level is too low to read it.
Comment: Any evidence to support this?


How do you check an items attribute and swap it for an image using jQuery?

Question: I have a list of items, each having an attribute containing a list of locations.
What I would essentially like to do is some type of "if statement" (i assume) to check of the "container" attribute, swap out the text and replace it with an image.
So, if the container attribute reads "United Kingdom, Spain", I would like to say, if the container attribute equals "United Kingdom", remove the text and replace with an image of the UK flag. So if the attribute contains multiple locations, instead of text, it'll contain icons of each locations flag. For demonstration purposes, I have included the below;
$('.location.container').attr('location');

Any help regarding this would be greatly appreciated.
Comment: What do you mean by list? dropdown list?
Comment: Good question. To clarify, I have 20 "Location Containers" on the page, each containing different information. One piece of that information would be "Location" information. So by list, I was referencing many containers (divs) on the page. :)
Comment: Why not use `data-location`?
Answer: Try this:Link
Html:

United Kingdom, Spain

United Kingdom, Spain

JS
$('.location-container').each(function(){

  if( $(this).attr('Location').toString().indexOf("United Kingdom")!=-1) {
   $(this).find('.text-container').text(
   $(this).find('.text-container').text().replace('United Kingdom',''));
 //   $(this).find('.text-//container').html($(thi//s).find('.text-container').text());

  }
if($(this).attr('Location').toString().indexOf("Spain")!=-1) {

  $(this).find('.text-container').text(  $(this).find('.text-container').text().replace('Spain',''));

  }
   $(this).find('.text-container').html($(this).find('.text-container').text());
});

Comment: This worked a charm. Thanks Slacker. Appreciated. Thanks to everyone who responded, appreciate your time and approaches. Actually learned alot looking at these examples.
Comment: Slacker, I did find one concern with this which you maybe able to help me with. If I have five "Location.Containers" on the page, one of which has an attribute that equals united kingdom, the 'listitemid' will be changed for them all, as there's no reference to the single container you are looking at. Each location container has the same DIV structure inside. Anyway for it to be specific to each location container? Thanks again :)
Comment: http://codepen.io/anon/pen/mxcgH - Here's an example. Same div structure, different values for the Location attribute, but both are affected because the JS is looking at everything.
Comment: Brilliant, thanks Slacker. You're great. - On a side note, how do we chat on this site? I'd like to contact you about something you wrote if that's fine with you?
Comment: Hi Tron, I have updated the code. Plz check this link: http://codepen.io/anon/pen/ckjtJ
Answer: Try :
Jquery Data
HTML :
XYZ
XYZ

Javascript :
var location = $('.location.container').data('location');
//similarly also get name = $('.location.container').data('name');

if(location === "United Kingdom"){
//replace flag
}
else{
//retain flag
}

Answer:

  United Kingdom

$(".location").each{
  function(){
    var text = $(this).closest(".text");
    text.hide();
    var flagUrl = 'http://blabla/flags/' + text.text() + '.jpg';
    $(this).append('').attr('src', flagUrl );
  }
}

You will also have to split 'text' in case of multiple locations, and iterate on them but this should get you started.
Answer: Assuming you have a map of countries to flags:
var flags = {
    "United Kingdom": "/images/uk.gif",
    "Spain": "/images/spain.gif"
}

$('.location.container').each(function() {
    var locations = $(this).attr('location').split(/,\s*/);

    for (var i = 0, n = locations.length; i < n; ++i) {
        $(this).append('');
    }
});


Fundamental understanding of the Del Operator

Question: I've encountered the Del operator while reading about gradient descent methods and I simply don't understand it. Here is an example of it's usage in gradient descent:
$b = a - \gamma \nabla F(a)$
I've seen some examples of the formula itself but for the whole understanding I need to know the meaning of the $\nabla$ operator.
Comment: What do you men by "meaning"?
Comment: Oh ok, want to now what kind of computation it does and of what cause.
Comment: Can you clarify what $a$,$b$,$\gamma$ and $F$ are? (i.e. are they scalars or vectors)
Comment: $b$ is the starting point of computation (which should be minimized within a matrix I guess), $a$ is the neighbour point of $b$, $\gamma$ is the step width of the descendence and $F(a)$ is, as far as I know, the gradient function of descendence
Comment: If $F(a)$ is actually some multivariate function $F(a_1,a_2,\dots)$, then $\nabla F(a)$ is the vector of partial derivatives with respect to each of the components of $a$.
Answer: The Del symbol (more properly, nabla) $\nabla$ indicates taking the gradient.  That is, for a scalar function $F$ the gradient $\nabla{F}$ is the vector of first partial derivatives.  The direction given by the gradient vector is the steepest increase (ascent) of the function's value.  Thus the formula for root-finding involves adjust a current estimate of the root location by an amount proportional to the gradient, taking into account the steepness of the slope there.


angularjs scope not accessable in directive

Question: I am trying to load a chart using angularjs directive. I want to load the chart after data comes from server response. But scope is empty. My code is

                                                <canvas id="canvas1" width="250" height="250" draw-chart>

                                                </canvas>

and my controller is
controller(){
 $scope.teamStrengths =  {};
 $scope.loadingIsDone = false;

 $http({
        url: "url",
          method: "POST",
          data: {"userUids":uids}
         }).success(function(response){

             $scope.teamStrengths =  response.resource.strengths;//data loads successfully

             $scope.loadingIsDone = true;

             //rest of code is skipped
}

and my directive is
Directives.directive('drawChart', function() {
       return function(scope, element, attrs) {

           console.debug("element :"+element);
           console.debug("attrs :"+attrs);

             graphDraw('canvas1',scope.teamStrengths.value1,scope.teamStrengths.value2,scope.teamStrengths.value3)
         //grap loads successfully with static data

       };
     });

kindly help me, i shall be thankful
Answer: $http call is asynchronous. Directive need to $watch changes in the scope. Add this in your directive:
 scope.$watch('teamStrengths', function(newValue, oldValue) {
     if (newValue)
        graphDraw('canvas1',scope.teamStrengths.value1,scope.teamStrengths.value2,scope.teamStrengths.value3)
 }, true);

Or watch for $scope.loadingIsDone change:
 scope.$watch('loadingIsDone', function(newValue, oldValue) {
     if (newValue == true)
        graphDraw('canvas1',scope.teamStrengths.value1,scope.teamStrengths.value2,scope.teamStrengths.value3)
 }, true);


Kafka 8.2.1 - How should I use KafkaConsumer.poll - it just returns null?

Question: New to Kafka.
I'm using kafka 0.8.2.1 java library:
    <dependency>
        <groupId>org.apache.kafka</groupId>
        <artifactId>kafka-clients</artifactId>
        <version>0.8.2.1</version>
    </dependency>

I tried to use consumer.poll  However it returns immediately.  When I look at the source code I see that it just returns null?

Am I looking at the wrong thing?  is 0.8.2.1 not the right version for kafka 0.8?
Is KafkaConsumer supported only after 9 release and not available in the 8 release?
What is the most stable API for Kafka currently?  I thought it was 0.8?
Answer: The consumer API with poll support is only available in Kafka 0.9 which is the last released version. For earlier versions you have to use the older consumer implementations under the kafka.consumer package in kafka/core.


jQuery works on the second event, but no the first one

Question: I couldn't find out why my code doesn't work correctly
I have this function:
<code>function checkIt(input_name, input_value){
   if (input_name === 'firstname') {
       y = regs[0];
   } else if (input_name === 'lastname') {
       y = regs[1];
   } else if (input_name === 'phone') {
       y = regs[2];
   } else if (input_name === 'mail') {
       y = regs[3];
   } else {
       y = regs[4];
   }
   z = input_value.match(y1);

   if (z !== null) {
       rez = true;
   } else {
       rez = false;
   }

   return rez;
}
</code>
and then im doing this:
<code>$(document).on("blur", "input[name=firstname]", function(){
    p = $(this).prop("name");
    q = $(this).val();
    r = checkIt(p, q);
    if (r) {
         // something
    } else {
         // something
    }
});
</code>
and my problem is that my code doesn't work on first blur. it's starting executing on second blur and does everything perfecty... :/
Comment: Just one thing: `z = input_value.match(y1);` Do you mean `y` instead of `y1`? BTW, why using global variables?
Comment: what does the console window tell you (hit F12)?
Comment: What is regs-array, and what is checkIt-function supposed to do, check that all required fields are filled?
Comment: thx a lot, it recorrected and working fine.. which global variable do u mean?
Answer: try using on("blur", "input", function) without parameter name, because do u have the var p with prop of this input.
<code> $(document).on("blur", "input", function(){
        p = $(this).prop("name");
        q = $(this).val();
        r = checkIt(p, q);
        if (r) {
             // something
        } else {
             // something
        }
    });
</code>


Shorten or merge multiple lines of `&> /dev/null &`

Question: Every time starting the machine, I run the following program:
$ cat start.sh
#! /bin/bash
google-chrome &> /dev/null &
lantern &> /dev/null &
xdg-open . &> /dev/null &
emacs &> /dev/null  &
code ~/Programs/ &> /dev/null &
xdg-open ~/Reference/topic_regex.md &> /dev/null &

Cumbersome &> /dev/null &...
How could I shorten the logic?
Comment: You can put all or most of those programs in your [Startup Applications](https://help.ubuntu.com/stable/ubuntu-help/startup-applications.html.en).
Comment: great, fantastic application. Errors usually occurred to  gnome-session causing abrupt crashing, so I start them from tmux server. @DennisWilliamson
Answer: The part &> /dev/null means output redirection. You can redirect multiple commands to the same file by grouping them into a block:
#! /bin/bash
{
google-chrome &
lantern &
xdg-open . &
emacs  &
code ~/Programs/ &
xdg-open ~/Reference/topic_regex.md &
} &> /dev/null

The same thing, however, cannot be used to start individual commands in the background (&). Putting & after the block would mean running the whole block as a single script in the background.
Comment: @multithr3at3d A Bashism incompatible with POSIX? Sure! Deprecated or obsolete? **No**, regardless of what the three authors of this list last edited in 2015 think. It is a short form, and shortening command lines is exactly OP's goal here. If someone runs a `#!/bin/bash` script in a different shell without checking for portability first it's definitely not Bash's fault if it doesn't work.
Comment: Do note that the `&>` syntax is deprecated and should be replaced with `>/dev/null 2>&1` http://wiki-dev.bash-hackers.org/scripting/obsolete
Comment: I assume that i can not have it on s!ngle line..
Answer: I wrote a function and put it into my .bashrc to run
things detached from my terminal:
detach ()
{
    ( "$@" &> /dev/null & )
}

... and then:
detach google-chrome
detach xdg-open ~/Reference/topic_regex.md

And because I'm lazy, I also wrote a shortcut for xdg-open:
xo ()
{
    for var in "$@"; do
        detach xdg-open "$var";
    done
}

Because xdg-open expects exactly one argument, the function xo iterates
over all given arguments and calls xdg-open for each one separately.
This allows for:
detach google-chrome
xo . ~/Reference/topic_regex.md

Answer: You could redirect the output for all subsequent commands with
exec 1>/dev/null
exec 2>/dev/null

Answer: I created a special file like /dev/null with a shorter path to shorten the redirection. I used /n as the new file's path:
sudo mknod -m 0666 /n c 1 3

This way you can shorten the individual lines to e.g.:
google-chrome &>/n &

Source: How to create /dev/null?
Answer: You could create a loop and give it the commands as arguments:
for i in google-chrome "xdg-open ." "code ~/Programs/"; do
  $i &
done &>/dev/null

Note that this way exactly as with the subshell approach with curly braces it's possible to sum up the outputs and redirect all of them at once.


"Try Ubuntu without installing" appears on one computer, not on another

Question: I am trying to run Ubuntu 12.04.05 via USB. It shows the option to run via USB on one of my computers, but not the other 2. How can I get it to display on these other computers?
1) On my oldest computer (32 bit Intel), it shows the following screen which is fine:

2) On my 2 newer computers (which are both barebones / nuc computers, one is 64 bit Intel, another is AMD 32 bit) I get the following GRUB screen which doesn't offer the option to run from USB:
Answer: The best way to know why it is behaving like this is to go thru the source code of Ubuntu 12.04.05. Ubuntu is open source and you can go thru it. Essentially the kernel modules which are interacting with H/W and to some extend of the installer routines. Any time installers are running they probe the underlying hardware and based on that they behave. Your old computer may be having USB 2.0 interface only plus a lot of stuff(in terms of old hardware) which makes the installer make a decision how to behave. Please specify full details of all the H/W configuration and the screen shots to logically find out why it is doing something like that.
Comment: Thanks for the suggestion. While I like reading code, I'm not confident enough to reason about kernel source code!


Applying a Math Formula in a more elegant way (maybe a recursive call would do the trick)

Question: This is my first post in Math section. I've been redirected here from StackOverflow, users from there suggested me to ask here.
This could appear a little bit complex at first sight but afterall there's nothing special.
We are in a poker touranment, there are 'n' players, each one has a stack of chips. There are only 'p' places to be paid at the end of the tournament.
We want to apply a math formula to convert the actual players' stacks into money. So we call 'equity' the probability of each player to finish the tournament in each paid place.
I'll hypothesize there are 4 players (P1,P2,P3,P4) and 3 paid places:
Equity on 1st place is:
<code>$eq1_1 = ($P1_stack / $total_chips);
$eq2_1 = ($P2_stack / $total_chips);
$eq3_1 = ($P3_stack / $total_chips);
$eq4_1 = ($P4_stack / $total_chips);
</code>
Equity on 2nd place:
To calculate the equity of each player on 2nd place we have to hypothesize that each one of the remanent players has won the first prize, subtract his(the winner's) stack from the total chips, divide the player 2 chips by the remanent chips, and multiply this number by the probability(equity on 1st prize of the player who won the 1st prize). I know, brains' explosions have been reported here.
<code>//-if P2 wins the tornament
$eq1_2 = $eq2_1*($P1_stack/($total_chips-$P2_stack));
//-if P3 wins the tornament
$eq1_2 = $eq1_2 + $eq3_1*($P1_stack/($total_chips-$P3_stack));
//-if P4 wins the tornament
$eq1_2 = $eq1_2 + $eq4_1*($P1_stack/($total_chips-$P4_stack));
</code>
if there would have been more players the cycle should have continued.
Equity on 3rd place
If your brain hasn't exploded yet, it will after you'll read this :p To calculate P1 equity on 3rd place we have to: 1) Subtract the winner AND the second winner stacks from the total chips. 2) Subtract P1 stack from the number we got. (Remainingstack) 3) Calculate the equity of the second winner on second place after a winner has been hypothesized. 4) Multiply the number we got (3)(P1_stack/ Remainingstack)Equity of the winner on 1st place.
I've written a working code so far but it works only if there are 3 paid placed. I'd like to modify it to get a more elegant and versatile way to get equity even if the paid places are more than 3.
This is my code: http://codepad.org/Q62l2wfv
I'm not an expert coder but maybe by doing it with a recursive call it should be faster and equity on 4th, 5th, 6th place can be calculated with no difficulties.
Comment: Yes, it sounds exactly like a recursive call. But first, let me see if I've got this straight. What you're doing appears to be equivalent to the following procedure: Pick a random chip. Whoever it belongs to gets first place, and their chips are discarded. Repeat to pick second place, third place, and so on. Then the equity of player $i$ on $j$th place is the probability that player $i$ gets $j$th place after this procedure. Right?
Comment: Yes! it's exactly that!
Answer: Okay, let's represent the stacks by a (given) vector $s = [s_1, s_2, \ldots, s_n]$, and the equity by an (unknown) $n\times n$ matrix
$$E = \begin{bmatrix}
e_{11} & e_{12} & \ldots & e_{1n} \\
e_{21} & e_{22} & \ldots & e_{2n} \\
\vdots & \vdots & \ddots & \vdots \\
e_{n1} & e_{n2} & \ldots & e_{nn}
\end{bmatrix}$$
representing the probability that player $i$ gets place $j$. This matrix is a function of $s$, let's say $E = f(s)$. Note that I'm filling up all $n$ places; if you have fewer, just ignore the later columns.
Suppose player $i$ were to get first place. If this happens, you remove him from the game, find the places of the other players, and then shift them all down by one to put player $i$ back in 1st place. So:

Remove player $i$ from the stacks, giving $s\setminus s_i = [s_1, s_2 \ldots, s_{i-1}, s_{i+1}, \ldots, s_n]$.
Do a recursive call on $s\setminus s_i$, yielding the matrix $E'_i = f(s\setminus s_i)$ representing the equity of everyone else if player $i$ did not exist.
$E'_i$ is an $(n-1)\times(n-1)$ matrix. Add a column of zeros at the beginning (everyone else has probability zero of being in first place), and insert a row $[1, 0, \ldots, 0]$ at the $i$th position (the only place player $i$ can have is first). This new $n\times n$ matrix is the equity of all players, conditional on player $i$ getting first place. Call this matrix $E_i$.

Of course, player $i$ only gets first place with probability
$$p_i = \frac{s_i}{\sum s_j}.$$
So the actual value of $E$, taking into account all the players' probability of winning, is simply
$$E = \sum p_i E_i.$$
Comment: I am re-reading your answer two years later. It's really one of the greatest anwer I've ever had in this website. I don't know if you're familiar with some coding languages, however I've created a PHP version of your "model"; however it's too slow for my purpouses. Could you recomend some other languages to make it faster? Or, in alternative, is it possible to simplify your "model"? Thanks in advance.
Comment: I coded it up in Mathematica to see if the result simplifies at all. It doesn't. If you have $s=\{a,b,c,d\}$, here's what the first row of $E$ looks like. The first element is $\frac a{a+b+c+d}$ obviously, the second element is $\frac b{a+b+c+d}\cdot\frac a{a+c+d} + \frac c{a+b+c+d}\cdot\frac a{a+b+d} + \frac d{a+b+c+d}\cdot\frac a{a+b+c}$ (either $b$ wins and $a$ comes second, or $c$ wins and $a$ comes second, or $d$ wins and $a$ comes second), the third element is $\frac b{a+b+c+d}\cdot\frac c{a+c+d}\cdot\frac a{a+d} + \cdots$ with five other terms...
Comment: My algorithm has a cost of $T(n) = nT(n-1) + O(n^3)$, which seems to be superpolynomial, so it will get pretty expensive if $n$ is large. I don't have any ideas for a faster approximate algorithm. You could try reimplementing in C/C++ and see if that's fast enough for you, or you could start a bounty on this question asking for an asymptotically faster algorithm.


What is the proper name for this rubber edging trim for fibreglass?

Question: I have a fibreglass seat pan, and it was damaged.  What's the correct name for the edging stuff?   I hope that I can find something large enough to cover the road-rash.

There's a springy steel-toothed core, and it slips over the raw edge of a fibreglass shape to protect it.
Comment: Not sure why this is garnering close votes, we get plenty of "identify this part" questions. If it happened to be a trim strip for a fiberglass shower surround instead of fiberglass bike seat, there wouldn't be any question at all.
Comment: Agree with @FreeMan.  Can see that being used for quite a few things besides a bike seat.  Have a table that has something similar along the bottom edge.
Comment: This happens to be a seat from a recumbent bicycle, but the question is generic.  This kind of bike seat is uncommon so not really suitable for bicycles.SE, and teh DIYers of the world are more likely to know the right words.
Comment: I'm voting to close this question because it's not about DIY Home Improvement. If someone wants to ask a similar question about some sort of similar edging used somewhere in a home then they're free to do so...
Comment: @brhans Fair observation, which is why I framed it as an ***identification*** question rather than a "bike repair"  The latter I can do perfectly well.   That "DIY" is not directly interchangeable with "Home Improvement" was covered in https://diy.meta.stackexchange.com/questions/266/diy-vs-home-improvement
Comment: Not sure exactly what you're referring to in that meta link, but the big banner at the top of the page literally reads "Home Improvement". Don't be mislead by the page URL - the fact that you want to Do **It** Yourself doesn't necessarily make **It** on-topic here.. https://diy.stackexchange.com/help/on-topic
Answer: So possible search terms are:
edging, protective edging or edge protector or edge protector strip or U channel ...
Often used with door & protector
Searching on Bay of Fleas gives many results with and without the internal spring.
Answer: In Norway, it goes under the name of Volvolist, named after a certain car brand.
The proper name for it is edge protection, and vendors such as RS Online have multiple hits when you search for edge protection.


Is there a way to bypass the Steam region lock?

Question: I want to check out a game but when I view it from Steam, it says:
"This item is currently unavailable in your region"
Is there a way to go around this limitation? Not simply by using a proxy to view the website but to actually get the game and play it?
Comment: If you proxy your internet connection, and have a means of payment that is registered to an address in the target country, you should be able to buy the game.
Comment: Will something like Tunnelbear work?
Answer: The simplest and safest way to get a game that is unavailable in your region is to have somebody else buy it for you, there is a myriad ways to wire the money to them. The only exceptions are some (but not all) games that are unavailable due to censorship in your country, so look out for that if you live in Germany, Australia or another country with similarly ridiculous censorship laws.
Comment: What if the game is free-to-play?
Comment: Then this solution won't work for you. Out of interest, do you have a particular game and country in mind?
Comment: Sure thing, [Ragnarok Online 2](http://store.steampowered.com/app/231060/) and Philippines. I ran Tunnelbear and I can view the game store page. But when I start up Steam client, it won't connect to the internet if Tunnelbear is running.
Comment: I would suggest trying another VPN provider, apparently some have problems with Steam (or maybe it's the other way around) while others do not.
Answer:
Open Steam Client
Press Steam Top Left
Press Settings
Change Your Region In Download Region
You Can Bypass The Region Lock And Once You Installed It You Can Change The Region Again

Hope I Helped
Comment: -1 **Incorrect** | Your download region only determines where the files are downloaded from. Your store settings (which dictate which version of the game you get) is determined by your account settings, and all download regions cache the different versions of each game (if there are ROW and non-ROW versions).


How to grab at least 10,000 tweets given the Twitter API Rate Lmit?

Question: As per title, how can I grab at least 10,000 tweets given that Twitter has their own limit ?
Twitter allows 180 queries per 15 minutes. So I was planning to use Timer and TimerTask to set an interval and keep running the code until I get 10,000 tweets like this:
timer.schedule((TimerTask) getTweets("$FB up"),0,900000);

The problem is that, every 15 minutes it will get back the same data as the first 15 minutes. How do I make it a continuation from where it stops in the previous 15 minutes ?
Below is the function for the
getTweets(String term)
int wantedTweets = 10000;
        long lastSearchID = Long.MAX_VALUE;
        int remainingTweets = wantedTweets;
        Query query = new Query(term);
         try{

          while(remainingTweets > 0)
          {
            remainingTweets = wantedTweets - tweets.size();
            if(remainingTweets > 100)
            {
              query.count(100);
            }
            else
            {
             query.count(remainingTweets);
            }
            QueryResult result = twitter.search(query);
            tweets.addAll(result.getTweets());
            Status s = tweets.get(tweets.size()-1);
            long firstQueryID = s.getId();
            query.setMaxId(firstQueryID);
            remainingTweets = wantedTweets - tweets.size();
          }

          for (int i=0 ; i < tweets.size() ; i++) {
               b = tweets.get(i);
              //System.out.println(s);
              //System.out.println("@" + b.getUser().getScreenName() +  " - " + b.getText());
          }
        }
        catch(TwitterException te)
        {
          System.out.println("Failed to search tweets: " + te.getMessage());
        }
         return b;

Answer: Use the twitter streaming API instead
Comment: I have overlooked that. Thanks for the suggestion. How do I set a limit on it ? It looks like its in real time.
Comment: There is no real limit other than that the stream is sampled data. You can stay connected (in theory) forever.
Comment: I think it answers exactly what OP wanted. To follow what you said is to be so narrow minded as to be useless.


Examples of liminf sequences

Question: I am looking to find an example of $(a_n)$ and $(b_n)$ such that
liminf $a_n$ + liminf $b_n$ < liminf $(a_n+b_n)$
Ive found the proof for this thing but I am having the worse trouble coming up with an example for it. I would appreciate any help, thanks.
Comment: **HINT** Think about two alternate sequences whose sum is constant
Answer: What about
$$a_n = (-1)^n \quad \text{and} \quad b_n = (-1)^{n+1} \quad ?$$

Examples of liminf sequences


PHP read XML and write in Database

Question: i have a XML file and need the data in a database after i checked them. so i display the data in a table and after that i try to write the data in a database. but with my code i get only the first set of data from the xml in my database. but there are at least 20  or more in each xml. How can i write all data in the database?
with this code i display the data from the xml
<form action="insert.php" method="post" />

            Typ
            Kennzeichen
            Fahrer

    <?php
      $url = ('./cars.xml');
      $xml = simplexml_load_file( urlencode($url), null, true);

       foreach ( $xml->car as $cars ) :?>

            <input type="hidden" name="name" value="<?php echo $cars->typ; ?>"><?php echo $cars->typ; ?>
            <input type="hidden" name="kfz-nr" value="<?php echo $cars->plate; ?>"><?php echo $cars->plate; ?>
            <input type="hidden" name="fahrer" value="<?php echo $cars->driver; ?>"><?php echo $cars->driver; ?>

<?php endforeach; ?>

    <input type="submit" name="senden" value="XML speichern" />
</form>

and with this code i try to write the data in the database. but i get only the first row from my table. not the others.
<?php

     error_reporting(E_ALL);
        $MYSQL_HOST = 'localhost';
        $MYSQL_USER = 'username';
        $MYSQL_PASS = 'password';
        $MYSQL_DATA = 'database';

        $connid = @mysql_connect($MYSQL_HOST, $MYSQL_USER, $MYSQL_PASS) OR die("Error: ".mysql_error());
        mysql_select_db($MYSQL_DATA) OR die("Error: ".mysql_error());

       if (isset($_POST['senden']))
    {
      $sql =
              "INSERT INTO myTable
              (fahrzeug,
               kennzeichen,
               fahrer
              )
              VALUES
              ('".mysql_real_escape_string(trim($_POST['name']))."',
               '".mysql_real_escape_string(trim($_POST['kfz-nr']))."',
               '".mysql_real_escape_string(trim($_POST['fahrer']))."');
                mysql_query($sql) OR die("
\n".$sql."
\n".mysql_error());
                mysql_query("SET NAMES 'utf8'");
    }
?>

i hope some one can help me. :)
Comment: This is completely correct, that you have only one value. Cause you are sending only one value.
Answer: In your foreach loop, you write multiple sets of hidden inputs with different values, but all of those have the same name so after submitting only one of the inputs gets sent with POST.
So in your database code, you just add that single input that gets passed.
In conclusion, you need to have different names for each hidden input and a loop in your database insertion to loop through all sent results.
One approach would be to add [] behind input names, making it return an array.
<input type="hidden" name="name[]" value="<?php echo $cars->typ; ?>">
<input type="hidden" name="kfz-nr[]" value="<?php echo $cars->plate; ?>">
<input type="hidden" name="fahrer[]" value="<?php echo $cars->driver; ?>">

will result in something like:
$_POST[kfz-nr][0]=="ABC123";
$_POST[kfz-nr][1]=="KLM901";
$_POST[kfz-nr][2]=="RGB255";

and so on. Then in your insertion method you do:
if (isset($_POST['senden']))
{
$count = count($_POST['name']);
for($i=0;$i<$count;$i++){
  $sql =
          "INSERT INTO myTable
          (fahrzeug,
           kennzeichen,
           fahrer
          )
          VALUES
          ('".mysql_real_escape_string(trim($_POST['name'][$i]))."',
           '".mysql_real_escape_string(trim($_POST['kfz-nr'][$i]))."',
           '".mysql_real_escape_string(trim($_POST['fahrer'][$i]))."');
            mysql_query($sql) OR die("
\n".$sql."
\n".mysql_error());
            mysql_query("SET NAMES 'utf8'");
}
}

Comment: thanks. both of you. i tried the methode from Ergo and it works perfect. :)
Answer:
send data from html
save data as array, not one element ( php example below )
do not use mysql in php. mysqli or PDO

$values = array();
for( $i=0; $i < count( $_POST['names'] ); $i++ ){
    $values[] = "(" .
             "\"" . mysql_real_escape_string(trim($_POST['name'][$i]).""\",".
             "\"" . mysql_real_escape_string(trim($_POST['kfz-nr'][$i])."\",".
             "\"" . mysql_real_escape_string(trim($_POST['fahrer'][$i])."\"".
             ")";
}

$sql = "INSERT INTO myTable (fahrzeug, kennzeichen, fahrer ) VALUES " . implode($values);
mysql_query($sql) OR die("

" . $sql . "

".mysql_error());
mysql_query("SET NAMES 'utf8'");

PHP read XML and write in Database


What does this shutoff switch in a 100 year old house control? Located in plaster wall near top of basment steps

Question: This shutoff switch, near the top of the basement steps in an old home confounds us.
Comment: Looks like an old light switch to me.
Comment: It releases the shackled clowns from the abandoned lunatic asylum in the basement. Don't touch it!!
Comment: I had one like this in the foyer of my 110 year old house. Played with it for weeks but never saw anything go on or off. Eventually I got a letter from a woman in Germany that said "Hör auf damit!"
Comment: Might be a very old electrical switch. For a very old basement light, say, or one that is no longer connected.
Comment: I think it's an on/off switch for an old doorbell.
Comment: Is A.I. Breveleri an anagram for Steven Wright?
Comment: There are no 'A's' in Steven Wright. So, it can't be an anagram.
Comment: Steven Wright is my illegitimate father. He never told me who my mother was.
Answer: If it's an on/off switch that as far as you can tell controls nothing, I'd start by pulling the switch away from the wall and attempting to figure out where the wiring goes and to what if any fusebox it connects to.