text:
Q: Zend framework 1.12 front controller configuration I am trying to register my modules with the front controller using the bootstrap class by using the code below:
$this->bootstrap('FrontController');
$front = $this->getResource('FrontController');
$front->addModuleDirectory(APPLICATION_PATH."/modules");
$front->setParam('prefixDefaultModule', true);

This works fine and all the modules are registered. But when I do the following my module directory is not registered and I get the "controller not found error".
$front = Zend_Controller_Front::getInstance();
$front->addModuleDirectory(APPLICATION_PATH."/modules");
$front->setParam('prefixDefaultModule', true);

As the front controller implements the singleton design pattern shouldn't both the code blocks refer to the same instance and both of my code blocks should work?

A: The issue is this line in your application.ini:
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"

The file structure you gave doesn't include this directory, so I think you can remove it and it will solve your problem.
Longer explanation of why it works one way and not the other:
There are two ways of configuring resources with Zend Application: class resources and plugin resources. The resources.xxx lines in application.ini are plugin resources, and the _init methods are class resources. Class resources run before plugin resources, but if you run $this->bootstrap('...') it will ensure that resource has been initialized (regardless of type).
So in your first code example, $this->bootstrap('FrontController'); triggers the frontController resource which you defined in your application.ini. This then sets the controller directory using the path you gave it. You then add a module directory which seems to be what your application actually uses.
In your second code example, you get an instance of the front controller and then add your module directory to it (all good). But then the plugin resource will run (as remember these run after). This will grab your existing front controller instance, but setting the controller directory overrides the module directory, so this is what causes your error later on.
I generally try and avoid mixing and matching plugin and class resources as it can cause some weird problems. So either put it all in application.ini or all in the Bootstrap class. Personally I find the latter more readable.
If you do need the controller directory as well, adding $this->bootstrap('FrontController'); to the start of your second code example should work as well, since that will trigger the plugin resource.

A: Here is what is going on. Tim Fountain is correct. The following line in your application.ini file is the culprit. If you remove it, your application should load correctly.
resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"

You may also have to remove this line since it is part of the frontcontroller too.
resources.frontController.params.displayExceptions = 1

But you also have 2 other options to be able to use Zend_Controller_Front::getInstance()
Option 1. You change your index.php to bootstrap specific resources:
$application->bootstrap(array('FrontController', 'ModuleConfig'))->run();

This will bootstrap your FrontController first from your application.ini and then run your initModuleConfig method. Essentially this allows you to control what resources are loaded and in what order. This is helpful when you have resources that you only want to bootstrap at specific times.
I think if you do not provide an array to the bootstrap method here, then it will call all methods prefixed with init in the order they are declared.
Option 2. You could do the configuration of your of your module directory within your application.ini
resources.frontController.moduleDirectory = APPLICATION_PATH "/modules"
resources.frontController.params.prefixDefaultModule = 1
resources.frontController.params.displayExceptions = 1

This will do what you were trying to do in code. One thing to note is that you may want to bootstrap your FrontController in the constructor of your Bootstrap class. This is just in case you need to use it during your custom initialization.

Now here is an explanation for why option 1 works.
This is a method from Zend_Application_Bootstrap_BootstrapAbstract
protected function _bootstrap($resource = null)
{
    if (null === $resource) {
        foreach ($this->getClassResourceNames() as $resource) {
            $this->_executeResource($resource);
        }

        foreach ($this->getPluginResourceNames() as $resource) {
            $this->_executeResource($resource);
        }
    } elseif (is_string($resource)) {
        $this->_executeResource($resource);
    } elseif (is_array($resource)) {
        foreach ($resource as $r) {
            $this->_executeResource($r);
        }
    } else {
        throw new Zend_Application_Bootstrap_Exception('Invalid argument passed to ' . __METHOD__);
    }
}

This _bootstrap is called when you call the public bootstrap method. Example $this->bootstrap("FrontController") or $this->bootstrap();
Notice the case when you don't pass in a parameter. This will call the null case which is the case you get in your index.php - $application->bootstrap()->run();
First it will load your class resources and then it will also call your plugin resources. Notice that the the plugin resources are not loaded in the other cases.
If you follow the method calls for class resources, it is basically call your init methods in your bootstrap call class.
The plugin resources are called afterward and one of the plugin resources. I'm not entirely sure how all the plugin resources are loaded, but I believe one source is in your application.ini file. These will be the lines that start with resources. Examples includes views, frontcontroller, db.
So in your situation where you call $application->bootstrap()->run();, your init methods are loaded first. But your FrontController is not bootstrapped yet. It eventually gets bootstrapped as a plugin resource which is taken from your application.ini. This apparently overwrites what you did in your bootstrap class.
Another question you may be asking is why is the FrontController instance not overridden when you call $this->bootstrap("FrontController) explicitly. I guess this pretty obvious but personally I had this question myself.
In the Bootstrap class, there is a method called _executeResource and this will check if the resource has already been bootstrapped. It uses an associative array to keep track. The associative array is called $this->_started.
This is why the plugin resource for the front controller is not called in your first case where you explicitly bootstrap the front controller. Hence your front controller instance is not replaced.

A: You need to bootstrap the front controller first so it is initialized. Once done in the cycle you could always retrieve it with the static getInstance.


text:
Q: hiding access keys and tokens for client side JS libraries in Angular For example, I am using Rollbar to track and log errors, and their JS documentation tells me to input the access token in the JS code. Anyone inspecting the source can find this token and call Rollbar using it.
// https://docs.rollbar.com/docs/angular
const rollbarConfig = {
  accessToken: 'POST_CLIENT_ITEM_TOKEN',
  captureUncaught: true,
  captureUnhandledRejections: true,
};

The same can be said of Mixpanel for analytics. I believe Google Analytics has a whitelist domain settings, which seems good enough.
As a general solution, how should I secure these client side libraries access tokens and keys?
It's a huge pain to move everything to the server side via API calls, but even if I do, it would only be secured via JWT tokens, so those will be valid until they expire, which isn't a real solution either.

redpajama_set_name: RedPajamaStackExchange


text:
Q: UUID.fromString() returns an invalid UUID? In my Android app I've got this method which takes a UUID. Unfortunately when I do this:
OverviewEvent overviewevent = eventAdapter.getOverviewEvent(UUID.fromString("0f14d0ab-9605-4a62-a9e4-5ed26688389b"));

I get an error saying java.lang.IllegalArgumentException: Invalid UUID: 100
The implementation of the getOverviewEvent is as follows:
public OverviewEvent getOverviewEvent(UUID uuid) throws Exception {
    // Do stuff
}

Does anybody know how I can solve this?

A: Here is a workaround which avoids using this method,
String s = "0f14d0ab-9605-4a62-a9e4-5ed26688389b";
String s2 = s.replace("-", "");
UUID uuid = new UUID(
        new BigInteger(s2.substring(0, 16), 16).longValue(),
        new BigInteger(s2.substring(16), 16).longValue());
System.out.println(uuid);

prints
0f14d0ab-9605-4a62-a9e4-5ed26688389b

A: Did you copy and paste the code, I have found that a few characters that look correct are in fact the wrong ACSII code.
Remove the - and replace them again.
I have had this often with " as different editors/computers may use a slightly different code.

A: I had this problem too. I think this is because my Java version is low. I found that in my Android application, uuid.split("-") and uuid.replace("-") are both useless. I guess it may be caused by that Java regards "-" as a regular expression. However when I try uuid.split("\\-") and uuid.replace("\\-"), they didn't work either. I don't know why this happened. I think it's a bug of Java.
According to Fildor's comment, in Android's implementation, uuid.split("-") is used to split the uuid string into 5 parts. Then because of the mentioned bug, the uuid string couldn't be spliced into 5 parts. So "Invalid UUID" exception is thrown.
However, we can modify android's source code to avoid this problem. Using substring() method, we can split the uuid string into 5 parts. And then we can make the uuid.
The following codes worked for me:
public static UUID makeUuid(String uuidString) {
    String[] parts = {
            uuidString.substring(0, 7),
            uuidString.substring(9, 12),
            uuidString.substring(14, 17),
            uuidString.substring(19, 22),
            uuidString.substring(24, 35)
    };
    long m1 = Long.parseLong(parts[0], 16);
    long m2 = Long.parseLong(parts[1], 16);
    long m3 = Long.parseLong(parts[2], 16);
    long lsb1 = Long.parseLong(parts[3], 16);
    long lsb2 = Long.parseLong(parts[4], 16);
    long msb = (m1 << 32) | (m2 << 16) | m3;
    long lsb = (lsb1 << 48) | lsb2;
    return new UUID(msb, lsb);
}


text:
Q: Create a multichannel audio with Pydub I'm trying to create an multichannel audio file with Pydub but I received an error. I know that each channels should be the exact same length, but also the frame count. I don't know how to verify if they are at the same frame count but they are at the same size.
    from pydub import AudioSegment
from pydub.playback import play
from playsound import playsound

left_channel = AudioSegment.from_wav("scripts_OUN\Single Cricket Chirping Effect.wav")
right_channel = AudioSegment.from_wav("scripts_OUN\d.wav")
left_channel_v2 = left_channel + AudioSegment.silent(duration=152009)
left = left_channel_v2.set_channels(1)
right = right_channel.set_channels(1)
print(len(left_channel_v2))
print(len(right_channel))
print(len(left_channel_v2)==len(right_channel))
print(left_channel.set_frame_rate
)
mutli_channel = AudioSegment.from_mono_audiosegments(left,right)
mutli_channel.export("v3.wav", format="wav")

My errors messages :
<bound method AudioSegment.set_frame_rate of <pydub.audio_segment.AudioSegment object at 0x000002ACB8076A40>>
and :
ValueError: attempt to assign array of size 12324755 to extended slice of size 12324781

A: <bound method AudioSegment.set_frame_rate of <pydub.audio_segment.AudioSegment object at 0x000002ACB8076A40>> is not an error, it is reference to a method you are printing.
For ValueError: attempt to assign array of size 12324755 to extended slice of size 12324781, this error depicts you using different slice sizes of audio for your left and right channel, hence the pydub library is not able to merge it together as multichannel audio. Use same size audio or extend the smaller audio by repeating the sound to make it equal to the size of bigger audio.


text:
Q: Are there replays of bad (new) players with commentary? I know, sounds dumb, but bear with me a sec.
People here have posted links to tons of high-level replays with commentary. (Thanks.) They're awesome fun, and I can learn a little.
But since I'm a low-level player, it's a lot like watching Iron Chef: experts way above my current skill/understanding level duke it out, while expert commentators point out strategy errors so subtle that I often don't even understand why they're errors.
Are there commentary replays of low-to-mid level matches?
Tutorials like SC2 Noob School and Shokz are great, but they're not the same as watching a real match. And while it wouldn't be as sexy a gig for the commentators, it'd be a great teaching tool: watching 1,000 things go wrong, and having an expert point out which are most common, and which are most important to fix.

A: Apparently casting low-level games is the latest fad, because Husky is jumping on the bandwagon too.  He recently revived his old series called Lets Learn Starcraft 2.
The original episode can be found here.
The latest episode can be found here.

A: X, of "X's Adventures in Minecraft" fame, has started to do a lot of Starcraft 2 videos.  He's currently in silver league.
He's done some basic tutorial videos, as well as commenting his own replays and live streams.  The live streams are interesting because he does a pretty good job of explaining his thought process as he plays.
It looks like his Starcraft 2 Playlist isn't quite up-to-date at the moment, so hopefully he'll update that soon.  They're all fairly recent, so they should be easy to find on his channel.
EDIT: It looks like the playlist has been updated. Just look for the videos marked "Live Commentary".

A: HuskyStarCraft has his Bronze League Heroes series where he cast only Bronze League games. I don't have a link handy, but you should just be able to look up HuskyStarCraft on youtube.

A: TotalBiscuit has a series called I Suck at Starcraft where he comments on his own noob games, focusing on what mistakes were made and how to improve.
The series starts out very basic, explaining economy, supply, teching, and the uses of some individual units.  It should be understandable even for someone brand-new to SC2.  The downside to this is that it may be too basic for many players.  However, over the course of about 15 videos, he moves into (somewhat) more advanced concepts.

A: As mentioned by Ivo Flipse, Day9 has done a few casts of inexperienced players. These are the ones I could dig up (a couple casts were during the beta, so some things may be out of date, but the main ideas are still there):
Day[9] Daily #115 - A Fun 2v2 of My Housemates
Let's take a break from the usual analysis to admire the beauty of Starcraft 2: the game can create epic matches between players of all skill levels. In #115, we get the chance to watch a game between players I live with! I got the chance to see this game happen live, and it was quite a treat to see :D
Day[9] Daily #121 - Plugging Leaks in Silver Level Play
In this episode, we examine a silver and gold level players to point out some classic leaks of inexperienced regulars.
Day[9] Daily #146 - Gold Level 2v2 Analysis
For anyone looking for silver and gold level 2v2 strategy, this is a must watch. I look at a replay from some very average players and discuss general strategy for 2v2 play.
Day[9] Daily #163 - Gold Level: Fixing the Little Things
In this episode, we take another look at Gold and Platinum level play and how to really improve, what to think about during the game, how to watch your own replays to improve, and other basic topics to help you be a better gamer.
Day[9] Daily #164 - Low Level Reps - In-game Decision Making
This time, we examine the importance of going into a game with a plan, especially for lower level players. We talk about a players starting plan, we see how it does and look at how to change your plan in the middle of the game when it's necessary. We also really look at the little things that are important that non-diamond players often forget.
Day[9] Daily #208 - Live coaching with djWHEAT (this one is very interesting)
We'll be doing a live coaching session w/ DJWheat direct from Phoenix Arizona where we'll help try to find some of Wheat's leaks and point out how to be thinking during a ladder match.

A: After Dave Andersen made his post, Day[9] started a new weekly event called Newbie Tuesday, where he does exactly what we're looking for:  every week, he goes over a silver/gold/platinum level game and explains what they did wrong.
I'll keep a list of them here as they come out.

Day[9] Daily #184 - Newbie Tuesday #1
This is the first in the series of Tuesday episodes dedicated to players below the Diamond level. Day[9] examines the common mistakes of Bronze through Platinum level players, shows what to focus on and what not to really worry about until you're a top Diamond player. This particular episode is a PvT, although the concepts apply to all races.
Day[9] Daily #189 - Newbie Tuesday: Losing to Early Pressure
In this Newbie Tuesday special, we examine how to avoid losing to early aggression in a variety of matchups.
Day[9] Daily #194 - Newbie Tuesday: Drone Timing
In this Newbie Tuesday episode, we focus on the timing of making Drones as a Zerg player. Specifically, how to figure out if it you need to make an army or build your economy at any given time. We look at using scouting info, harassment, and defensive strategies to optimize your economy while not actually dying.
Day[9] Daily #198 - Newbie Tuesday: Banshee Harass
In this episode of Newbie Tuesday, we address the common problem of being harassed by Banshees at different stages of the game.
Day[9] Daily #201 - Newbie Tuesday: Using Drops
In this episode, we look at how to effectively use drops to gain an advantage, and point out common mistakes.
Day[9] Daily #205 - Newbie Tuesday: Dealing with Colossi
In this Newbie Tuesday, we focus on what the different races can do when faced against the mighty Colossus!
Day[9] Daily #210 - Newbie Tuesday: 2v2 Strategy
This time, we'll take a look at early game 2v2 and see why people lose to rushes so much! We really examine the rush as a valid strategy, and look at how to cope with them and still win!


text:
Q: 'Undefined References' Error during OpenGL Pgm Compiling (freeglut3) I tried to run an openGL pgm in my Ubuntu 14.04 and i have freeglut3 and dev installed. But it returns some 'Undefined References' to all the functions that i have used in my pgm.
rahul@rahul-System-Product-Name:~$ g++ -lGL -lGLU -lglut nrs1.c
/tmp/ccIsCRgh.o: In function `myInit()':
nrs1.c:(.text+0x2a): undefined reference to `glClearColor'
nrs1.c:(.text+0x37): undefined reference to `glPointSize'
nrs1.c:(.text+0x43): undefined reference to `glMatrixMode'
nrs1.c:(.text+0x48): undefined reference to `glLoadIdentity'
nrs1.c:(.text+0x88): undefined reference to `glOrtho'
nrs1.c:(.text+0xca): undefined reference to `gluLookAt'
nrs1.c:(.text+0xd6): undefined reference to `glMatrixMode'
nrs1.c:(.text+0xdb): undefined reference to `glLoadIdentity'
/tmp/ccIsCRgh.o: In function `triangle(float*, float*, float*)':
nrs1.c:(.text+0xee): undefined reference to `glVertex3fv'
nrs1.c:(.text+0xf9): undefined reference to `glVertex3fv'
nrs1.c:(.text+0x104): undefined reference to `glVertex3fv'
/tmp/ccIsCRgh.o: In function `tetra(float*, float*, float*, float*)':
nrs1.c:(.text+0x118): undefined reference to `glColor3fv'
nrs1.c:(.text+0x13d): undefined reference to `glColor3fv'
nrs1.c:(.text+0x162): undefined reference to `glColor3fv'
nrs1.c:(.text+0x187): undefined reference to `glColor3fv'
/tmp/ccIsCRgh.o: In function `display()':
nrs1.c:(.text+0x4cb): undefined reference to `glClear'
nrs1.c:(.text+0x4d7): undefined reference to `glBegin'
nrs1.c:(.text+0x50e): undefined reference to `glEnd'
nrs1.c:(.text+0x513): undefined reference to `glFlush'
/tmp/ccIsCRgh.o: In function `main':
nrs1.c:(.text+0x530): undefined reference to `glutInit'
nrs1.c:(.text+0x53c): undefined reference to `glutInitDisplayMode'
nrs1.c:(.text+0x550): undefined reference to `glutInitWindowSize'
nrs1.c:(.text+0x564): undefined reference to `glutInitWindowPosition'
nrs1.c:(.text+0x570): undefined reference to `glutCreateWindow'
nrs1.c:(.text+0x57c): undefined reference to `glutDisplayFunc'
nrs1.c:(.text+0x588): undefined reference to `glEnable'
nrs1.c:(.text+0x592): undefined reference to `glutMainLoop'

Please suggest solutions.
Thanks.


text:
Q: How To Manage Response From Task Node With Slow Internet? I access My Task node in Main Scene Like below.
m.Response = CreateObject("roSGNode", "TaskNodeFile")
m.Response.control = "RUN"

And Task node Code Like below.
sub init()
   ?"init() - Start"
   readdata = CreateObject("roUrlTransfer")

   data = "http://Domain:Port"
   readdata.setUrl(data)

   readdata.SetMinimumTransferRate(1, 75)

   ? "data is " data
   m.port = CreateObject("roMessagePort")
   readdata.setport(m.port)
   readdata.gettostring()
   readdata.SetRequest("POST")

   request = readdata.AsyncPostFromString(data)
   ?"request : " request
   while (true)
      msg = Wait(3000, m.port) 'Here It's Crashed. I also tried with the 0 MilliSecond. " It's Give a Execution Time Out
      statusCode = msg.GetResponseCode()
      if (Type(msg) = "roUrlEvent")
         statusCode = msg.GetResponseCode()
         headers = msg.GetResponseHeaders()
         if msg.getresponsecode() = 200 then
            Response = msg.getstring()
            headers = msg.getresponseheadersarray()
            ?"Response : " Response
            exit while
         else
            m.top.isError = "true"
            m.readdata.asynccancel()
            exit while
         end if
      else
         ? "wait for data"
      end if
      end while
end sub

Here the issue is: I tested this Code with 2 Roku premiere+ devices.

*

*In 1st Device Internet Speed: 10mbps and

*In 2nd Device Internet Speed: 50mbps.

I checked My API Response using the Postman tool :

*

*With 10mbps: It takes an 1800 MilliSeconds

*With 50mbps: It takes a 350 MilliSeconds
In My Case With 10 Mbps, The Application crashed with this line msg = Wait(3000, m.port). Here, I also tried with the 0 MilliSeconds. After also It's Crashed and Gives Execution Timeout. If Some Internet issues, It's no waiting. It's Directly Crashed. Does anyone Found Good solutions or How to handle this Scenario?.


text:
Q: Dispatch_once singleton error objective c I am relatively new to GCD, I am currently using it to create a singleton object in my application. After doing some research I found using GCD's dispatch_once() method is the best way to achieve the singleton design pattern. For some reason, my code is breaking and I can not figure it out for the life of me. Below, I have pasted my singleton creation/init code, and the responding error.
+(id)sharedErrorMapper {

static dispatch_once_t onceToken;
static id sharedInstance;
dispatch_once(&onceToken, ^
{
    sharedInstance = [[self alloc] init];
});
return sharedInstance;

}

-(id)init {
//creating the ErrorMap data structure
//currently loading in dummy JSON data..
self = [super init];
if (self != nil) {
    NSError *error = [[NSError alloc] init];
    NSData *resourceData = [[NSData alloc] initWithContentsOfFile:
                        @"/Users/acuram/Desktop/GitHubWorkspaces/ios-sdk-src/ios-here-sdk/PPHSDKTests/Resources"];
    self.errorMap = [[NSDictionary alloc] init];
    self.errorMap = [NSJSONSerialization JSONObjectWithData:resourceData options:kNilOptions error:&error];
}
return self;
}

After setting some breakpoints and doing some stack tracing, my code is breaking at the dispatch_once() function call. The error I get back is a "NSInvalidArgumentException", it complains that my data parameter is nil. I am pretty shocked because I followed a legit tutorial video on youtube to implement this, I am also looking at my companies code base and they seem to do it in a similar way....


text:
Q: Which tense do I use when giving multiple verbs? I'm trying to say that we will test a product and make sure it works, but I don't know if I should say:
"After we finish testing and making sure it works..."
or
"After we finish testing and make sure it works..."
In the first example, "making" and "testing" are the same tense, so it makes sense. But in the second, "make" and "finish" are the same tense, and that also sounds right. Which one is correct? Or are they both correct?

A: This would ensure the verb tenses align: "After we finish testing it and making sure it works..."
Two other possible statements might be: "After we finish testing it to make sure it works..." and "After we test it to make sure it works..."

A: In the first sentence "finish" is the simple predicate, and "testing" and "making" are gerunds functioning as the objects of finish. In the second sentence both "finish" and "make" function as verbs. Both sentences are correct, but the second sentence by using the verb emphasizes the concern with the product working (I would interpret the second sentence as implying doubt about the product's success).
Merriam Webster
gerund : an English noun formed from a verb by adding -ing


text:
Q: application terminate help in my project i have two forms ,when i clicked show form 2 button in form1 ,form2 will pop up ,i want to terminate my whole application by clicking close button on form2 ,
can anyone  please tell me how can i do this ?

A: If you mean when a TButton called Close is clicked, then in the Button.OnClick event call Application.Terminate;
If you mean when the form's X button is clicked, then in Form2's OnClose event, call Application.Terminate;

A: Do not use Application.Terminate if you want your OnCloseQuery and OnClose handlers of the main app form to be called (for example to be able to cancel this or to ask whether to save modified files or such).
You can call
Application.MainForm.Close;

instead, from all forms (even the main form itself).

A: Another option is to send a wm_Close message to the application/application.mainform
PostMessage(Application.Handle,wm_Close,0,0);

or
PostMessage(Application.MainForm.Handle,wm_Close,0,0);

This places the close request in the message queue, existing messages already in the message queue will continue to process first.

A: The post easiest mode is to user
TerminateProcess(GetCurrentProcessID, 0);
no ask, no freeze, no s*iet.


text:
Q: Exception messages for exception nesting Consider I am developing a library. When this library encounters an exception it can't handle itself (e.g. a WebException) it will wrap that exception to hide implementation details from clients and provide them a uniform way of exception handling.
Regarding the message of such an exception, what are the best practices / guidelines / do's /don'ts?
Option 1: Wrapper does not include anything
My personal favorite, each exception is responsible for its own message. The wrapper uses a more general wording than the one being expected from the inner exception.
try
{
  // ...
}
catch (WebException ex)
{
  throw new MyLibraryException("An error occured accessing a web ressource", ex);
}

Option 2: Display the inner message
What more could you want to say, than that what the inner exception has to say? Not sure whether this is viable...
try
{
  // ...
}
catch (WebException ex)
{
  throw new MyLibraryException(ex.Message, ex);
}

Option 3: Concatenate it
I don't believe that this is a good idea, but it came up in a discussion we had locally, so I want to present it as an option.
The outer exception will take care of concatenating inner exception messages.
try
{
  // ...
}
catch (WebException ex)
{
  string message = string.Format("An error occured accessing a web ressource: {0}", ex.Message);
  throw new MyLibraryException(message, ex);
}

I feel that there must be clear guidelines on that topic (e.g. MSDN), but I was not able to find them. I already checked Best Practices for Exceptions, but for no avail.
Option 4: Don't care
From the comments:

do not waste time catching exceptions you cannot handle. Let the caller deal with it.

I don't think that this option is viable, because though I can't handle the exception myself I know that it can occur and I want to hide specifics from the caller (e.g. which exception type to handle?). This is important, because I could someday switch to another framework providing me with Web-Access and thus the exceptions could change. The wrapping helps to maintain the abstraction (IMHO).
edit: There seems to be a lot of confusion. I don't plan to apply this pattern to each and every exception. I will usually ignore or rethrow (throw;) exceptions like FileNotFoundException and many other core framework exceptions. However, there are cases when I want to hide and how am I supposed to do this in the best way possible?
Read this question as: If I had a good reason to nest exceptions, how should my messages look like?
Discussions on if you want to nest exceptions better belong here.

A: If you need extensive logging it might be wise to capture the error high up the chain to be able to provide as much details as possible about the error in the log message. After logging you should re-throw the exception. Make sure that you use throw; instead of throw ex; to preserve the stack trace.

A: Option 4: do not waste time catching exceptions you cannot handle. Let the caller deal with it. Does it really matter to the caller whether they catch MyLibraryException or WebException? If the caller can handle and recover from WebExceptions, then they will want to catch that, not your MyLibraryException.
Also if the exception is thrown up through several layers, with your reasoning each layer would add its own wrapping, which means the top layer then has to drill down through multiple inner exceptions to get to the actual error - ugh!
The very top level can always have a catch all to catch and log any exceptions that have not already been handled.
Finally, you should document what (underlying) exceptions are likely to be thrown from your library, or the code it calls.
Edit: regarding abstraction: abstracting the exception in your MyLibraryException does not help the caller - they cannot recover from a MyLibraryException without knowing the ultimate cause, which is the exception you have wrapped, therefore you might as well not bother wrapping it in the first place, and let the caller catch it directly. If the caller cannot recover from the ultimate exception, then they will probably just catch everything and log the fact that an error occurred, and perhaps then terminate the application.
A concrete example: a FileIOException occurs in your library because of a missing file. Surely it is better for this to be thrown to the caller so they can recover from it (perhaps the user forgot a critical file), rather than the caller having to interpret your MyLibraryException?


text:
Q: What are the ways to check if DataFrames are empty other than doing a count check in Spark using Java? if(df.count()== 0){
    System.out.println("df is an empty dataframe");
 }

The above is a way to check if a DataFrame is empty or not without getting a
null pointer exception.
Is there any other best way to do so in Spark as I am worried that if the DataFrame df gets millions of records, the above statement will be taking a long time to get executed.

A: I recently come across one such scenario. The following are some of the ways to check if a dataframe is empty.

*

*df.count() == 0

*df.head().isEmpty

*df.rdd.isEmpty

*df.first().isEmpty

Although it is better to avoid count() since it is more expensive. However there might be some situations where you are very certain that the dataframe would have either a single row or no record at all (For ex: Executing a max() function in an Hive query). In such situations, it is okay to use count().

A: Taking the count can be slower. Instead you can just check if the head element is not empty.
df.head(1).isEmpty

Add an exception handling to this as it will throw java.util.NoSuchElementException if df is empty.
Update: Check out How to check if spark dataframe is empty


text:
Q: Load Linux library through a Windows client several years I used to come on the bible of coding and I have (maybe) a question rarely asked. First of all thanks to all people which takes time to answer us.
I have a network with a Linux server and some Windows clients. On the server I have to use a Java application (I don't have source code) but it's hard to use it on the server : graphic card drivers are not update then the resolution of the screen is "small" and not expandable. It's a problem because layouts of the app are not dynamics then some important buttons are not displayed (is it so hard to use a JScrollPane ???). And I don't really want to learn how many times I have to use Tab for each hidden button.
Then one solution is to launch the app on a Windows client through MobaXterm. It works well but at one moment a process need a library.
I tried to launch the app by adding the library path of the library, a *.so file, but didn't work.
The question is : a java application installed on Linux and launched through a windows client need *.so or *.dll library ?
Thanks.
Florent


text:
Q: Upload file to Box.com (Android) I've been following the example code on https://github.com/box/box-android-sdk/ as well as the documentation. However whenever I try to upload a file to box.com I receive the following error:

11-13 18:25:45.222 20996-21555/com.caa.capturebox W/System.err: com.box.androidsdk.content.BoxException: An error occurred while sending the request (401)
  11-13 18:25:45.237 20996-21555/com.caa.capturebox W/System.err:     at com.box.androidsdk.content.requests.BoxRequestUpload.send(BoxRequestUpload.java:114)
  11-13 18:25:45.238 20996-21555/com.caa.capturebox W/System.err:     at com.caa.capturebox.MainActivity$5.run(MainActivity.java:441)

Below is the last attempt I made however whether I try to upload from an input stream or from a local file I get the same error above.
    private void uploadFile() {
    mDialog = ProgressDialog.show(MainActivity.this, getText(R.string.boxsdk_Please_wait), getText(R.string.boxsdk_Please_wait));
    new Thread() {
        @Override
        public void run() {
            try {
                Log.e("mya", "uploadFile: entered try");
                FileInputStream uploadStream = new FileInputStream(image_name);
                //InputStream uploadStream = getResources().getAssets().open(uploadFileName);
                String destinationFolderId = "0";
                String uploadName = "BoxSDKUpload.jpg";

                //BoxRequestsFile.UploadFile request = mFileApi.getUploadRequest(uploadStream, uploadName, destinationFolderId);
                BoxRequestsFile.UploadFile request = mFileApi.getUploadRequest(image_name, "0");
                final BoxFile uploadFileInfo = request.send();
                showToast("Uploaded " + uploadFileInfo.getName());
                loadRootFolder();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (BoxException e) {
                e.printStackTrace();
                BoxError error = e.getAsBoxError();
                if (error != null && error.getStatus() == HttpStatus.SC_CONFLICT) {
                    ArrayList<BoxEntity> conflicts = error.getContextInfo().getConflicts();
                    if (conflicts != null && conflicts.size() == 1 && conflicts.get(0) instanceof BoxFile) {
                        //uploadNewVersion((BoxFile) conflicts.get(0));
                        return;
                    }
                }
                showToast("Upload failed");
            } finally {
                mDialog.dismiss();
            }
        }
    }.start();
}

A: since you have (401) response, I assume that it's Not Authorized http code returned. Have you been login to box : box login documentation
Please login in order to use box services with this code:
BoxSession session = new BoxSession(context);
session.authenticate();


text:
Q: Problem with endfloat in combination with sidewaystables I am using endfloat and pdflscape to create sidewaystables at the end of my document. The problem is I want to generate a long sidewaystable, i.e. over 2 pages. However, the second part of the table (on the second page) is much different from the first, i.e. in the amount of columns etc. So I made a new sidewaystable. This looks perfectly fine in the normal document (looks as one full table over 2 pages), but with endfloat, 2 links will be generated, as one would expect, instead of only one for the first table.
Is there any way to fix this? I.e. within the table there should be only one link:
[Table 1 about here...],
instead of two links. So the link [Table 2 about here...] should be removed.
Example to show the problem:
\documentclass{article}
\usepackage{caption}
\usepackage{booktabs}
\usepackage{rotating}
\usepackage{longtable} % for 'longtable' environment
\usepackage{pdflscape} % for 'landscape' environment
\usepackage{endfloat}

\DeclareDelayedFloatFlavor{sidewaystable}{table}

\begin{document}

\section{Start}

\begin{sidewaystable}
\noindent
\captionbox{This is the first table.\label{tab:one}}{%
  \begin{tabular}{ccccc}\toprule
  \textbf{a} & \textbf{b} & \textbf{c} & \textbf{d} & \textbf{e} \\ \midrule
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  \bottomrule
  \end{tabular}
}
\end{sidewaystable}

\begin{sidewaystable}
\noindent
\captionbox{This is the second table.\label{tab:two}}{%
  \begin{tabular}{ccccc}\toprule
  \textbf{a} & \textbf{b} & \textbf{c} & \textbf{d} & \textbf{e} \\ \midrule
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  \bottomrule
  \end{tabular}
}
\end{sidewaystable}

\section{End}
\end{document}

A: The way endfloat works is that is detects the start of certain environments and clips the code from there to the end of the environment out of the document and into another file.  You can put pretty much anything inside the environment, including several pages worth of floats or non-floats.
This solution uses a wrapper environment to do precisely that.
\documentclass{article}
\usepackage{caption}
\usepackage{booktabs}
\usepackage{rotating}
\usepackage{longtable} % for 'longtable' environment
\usepackage{pdflscape} % for 'landscape' environment
\usepackage{endfloat}

\newenvironment{wrapper}{}{}
\DeclareDelayedFloatFlavor{wrapper}{table}
\DeclareDelayedFloatFlavor{sidewaystable}{table}% to check for conflicts

\begin{document}

\section{Start}

\begin{wrapper}
\begin{sidewaystable}
\noindent
\captionbox{This is the first table.\label{tab:one}}{%
  \begin{tabular}{ccccc}\toprule
  \textbf{a} & \textbf{b} & \textbf{c} & \textbf{d} & \textbf{e} \\ \midrule
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  \bottomrule
  \end{tabular}
}
\end{sidewaystable}

\begin{sidewaystable}
\noindent
\captionbox{This is the second table.\label{tab:two}}{%
  \begin{tabular}{ccccc}\toprule
  \textbf{a} & \textbf{b} & \textbf{c} & \textbf{d} & \textbf{e} \\ \midrule
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  1 & 2 & 3 & 4 & 5\\
  \bottomrule
  \end{tabular}
}
\end{sidewaystable}
\end{wrapper}

\section{End}
\end{document}


text:
Q: Distribution of a Random variable bounded by another random variable
Suppose that $X$ and $Y$ are independent
  exponential r.v.'s with parameters $\lambda$ and $\mu$.
  If $X$ is bounded by $Y$, how do I find the expression of $P(X<x)$?

Regarding this question, I have some doubts on the format of the probability. I can take it as a conditional probability $P(X<x|X<Y)=\frac{P(X<x\,\cap\, X<Y)}{P(X<Y)}$. In this case, how to compute $P(X<x\cap X<Y)$?
On the other hand, I think I can also write as $P(X<Y<x)$ (or some other forms?), which one is correct? If this one is correct, then how to compute it?

Edit 1: adding the background of the question.
Assume there are $N+1$ objects, and each object has an arrival process. The first $N$ of them arrive with rate $\lambda_i,~i=\{1,2,...,N\}$, and the last one arrive with rate $\mu$. Let $X_i$ denote the inter-arrival times of the first $N$ objects, and let $Y$ denote the inter-arrival time for the $N+1$-th object. All the inter-arrival times are exponentially distributed.
Question: think of the situation that there are at least $C$ distinct ($C$ is a constant) objects arrive before the $N+1$-th object arrives. If this case happens, find the shortest time duration $\tau$, during which exactly $C$ distinct objects arrive.
Extra info: By definition, $\tau$ is a random variable, but current research has verified that it can be regarded as a constant.

My analysis: for an object $i$ that belongs to  the $C$ objects, its inter-arrival time $X_i$ must be smaller than $Y$, and I need to find out its distribution function $F_i(x)=P_i(X_i<x|X_i<Y)$ (which must be different from its original distribution function). Then define an indicator function $I_i$, $I_i=1$ if $X_i$ is smaller than $\tau$, otherwise $I_i=0$, so we have $\sum_{i=1}^N I_i=C$. Taking average on both sides, we get $\sum_{i=1}^N E[I_i]=\sum_{i=1}^N P(X_i<\tau|X_i<Y) = C$. If I have the expression for $P(X_i<\tau|X_i<Y) = C$, maybe I can get $\tau$.
Note that the above analysis uses the memoryless property of a Poisson process. Please correct me if I am wrong.

A: $$
P(X<Y,X>x)=\int_x^\infty P(Y>t)\lambda e^{-\lambda t}\mathrm dt\\
=\int_x^\infty e^{-\mu t}\lambda e^{-\lambda t}\mathrm dt=\frac{\lambda}{\lambda+\mu}e^{-(\lambda+\mu)x}.
$$
And
$$
P(X<Y)=\int_{0}^\infty P(Y>t)\lambda e^{-\lambda t}\mathrm dt=\frac{\lambda}{\lambda+\mu},
$$
hence:
$$
P(X>x|X<Y)=e^{-(\lambda+\mu)x}.
$$

Another way of looking at the problem is based on the fact that the exponential probability distribution is memoryless, meaning that:
$$
P(X>y|X>x)=P(X>y-x) 1(y-x\geq 0)+1(y-x< 0)
\\=e^{-\lambda(y-x)}1(y-x\geq 0)+1(y-x< 0).
$$
So
$$
P(X>Y|X>x)=E(e^{-\lambda(Y-x)}1(Y-x\geq 0)+1(Y-x< 0))\\
=(1-e^{-\mu x})+e^{\lambda x}\int_x e^{-\lambda t}\mu e^{-\mu t}\mathrm dt\\
=1-\frac{\lambda}{\lambda+\mu}e^{-\mu x}.
$$
Using this you can again arrive at the same result.

A: Not an answer but too much for a comment.
$P(X<x)$ is an expression for the probability that $X<x$, period!
It is a real number in $[0,1]$ and completely unsensitive for circumstantial conditions. The formulation "If $X$ is bounded by $Y$" gives the impression that you are after the probability that $X<x$ under condition that $X<Y$.
If so then - as you stated allready - you are after $P(X<x\mid X<Y)$ which asks for calculation of $P(X<x\wedge X<Y)$ and $P(X<Y)$.
The expression $P(X<Y<x)$ stands for something different. In the first place you are not working under the condition $X<Y$ anymore (it wipes away the words "if $X$ is bounded by $Y$") and secondly next to $X<Y$ you are also demanding that $Y<x$ (so that consequently also $X<x$).
Main question: conditional or not? Can you clarify (e.g. by saying something about the source of the problem)?


text:
Q: Using Commands to make chests with stuff inside Every time I try to make a filled chest it is always empty. I am trying to fill it up with raw meat for a restaurant I am doing
/give TehFireFace chest{display:{Name:"\"FOOD THAT NEEDS TO BE COOKED\""},BlockEntityTag:{Items:[{Slot:0,id:beef,Count:64},{Slot:1,id:beef,Count:64},{Slot:2,id:beef,Count:64},{Slot:3,id:chicken,Count:64},{Slot:4,id:chicken,Count:64},{Slot:5,id:chicken,Count:64},{Slot:6,id:cod,Count:64},{Slot:7,id:cod,Count:64},{Slot:8,id:cod,Count:64},{Slot:9,id:porkchop,Count:64},{Slot:10,id:porkchop,Count:64},{Slot:11,id:salmon,Count:64},{Slot:12,id:salmon,Count:64}]}} 64

A: Depending on the version of the game you are using, the command may differ.
In my case, I was using Version 1.8.9.
According to a post from Skylinerw on the minecraft forums, this is how you give a chest with items:
/give [USER] minecraft:chest 1 0 {BlockEntityTag:{Items:[{Slot:0,id:minecraft:stone,Count:1}]}}

So for your case it would be:
/give TehFireFace minecraft:chest 1 0 {BlockEntityTag:{Items:[{Slot:0,id:minecraft:beef,Count:64},{Slot:1,id:minecraft:beef,Count:64},{Slot:2,id:minecraft:beef,Count:64},{Slot:3,id:minecraft:chicken,Count:64},{Slot:4,id:minecraft:chicken,Count:64},{Slot:5,id:minecraft:chicken,Count:64},{Slot:6,id:minecraft:cod,Count:64},{Slot:7,id:minecraft:cod,Count:64},{Slot:8,id:minecraft:cod,Count:64},{Slot:9,id:minecraft:porkchop,Count:64},{Slot:10,id:minecraft:porkchop,Count:64},{Slot:11,id:minecraft:salmon,Count:64},{Slot:12,id:minecraft:salmon,Count:64}]},display:{Name:"\"FOOD THAT NEEDS TO BE COOKED\""}}


text:
Q: "have access" vs. "get access"
Through the application, the user can select any element of the page by moving the mouse over it and (get or have ?) access to its static and dynamic information.

Is there any difference between get access and have access.

A: There's nothing wrong using "get/have access to"; you can use either of the verbs in this sentence, without any semantic difference. But, as a matter of fact and as commented by JMB, when it comes to a computer system, you usually use the word access as a verb:
"......... and access its static and dynamic information".

A:
Through the application, the user can select any element of the page by moving the mouse over it and (get or have ?) access to its static and dynamic information.

What the user is "getting" or "having" here is not access to information (he/she already has access), but the information itself.  The user may not realize he/she has access, but you are telling them they do and how to get the information.
It would be better to word it one of these ways.

The user has access to an element's static and dynamic information at any time by selecting any element of the page and moving the mouse over it.
The user can get an element's static and dynamic information at any time by selecting any element of the page and moving the mouse over it.

A: have access = it's more formal and use frequently as compare to "get access".
Also, the use of get/have access means that the person either used to have or doesn't have access to a specific folder or files which is why a permission was requested.


text:
Q: Including phonon environment setup in Qt Creator On Windows XP, I ran "configure", and Qt says that I'm configured to use phonon, but I'm not sure how to set up my environment correctly in Qt Creator. According to the Qt documentation, I need to call:
Set DXSDK_DIR=C:\Program Files\Microsoft DirectX SDK (February 2007)
%DXSDK_DIR%\utilities\bin\dx_setenv.cmd
C:\program files\Microsoft Platform SDK\setenv.cmd
How do I do this in the Qt Creator IDE?
Thanks!

A: As far as i understand those sets are required if you want to build phonon itself, but if you rely on already build qt that has phonon enabled, those are not required.
However, if it indeed turns out that you need those too, optimal way would be that you first look into those 2 scripts, extract all the environment variables those 2 scripts set and then go to Control Panel->System->Advanced Tab->Environment Variable Button and set the variables there manually.
There's also a tool call setx available somewhere that you can use, check this thread for example: http://forums.techarena.in/windows-xp-support/1152405.htm


text:
Q: My TouchableOpacity is not working in react-native I have just started React-Native. But here my TouchableOpacity is not working.please check the code
import React, { Component } from 'react'
import { View, Text , StyleSheet, TouchableOpacity, TouchableNativeFeedback } from 'react-native'
import firebase from 'firebase'

    class Article extends Component {

        handleOnPress = () => {
            firebase.auth().signOut();
          }
        render(){
        return (

            <View style={styles.container}>
                <View >
                    <Text>You are logged in </Text>

                    <TouchableOpacity style={styles.buttonContainer}
                    onPress={this.handleOnPress}>
                        <Text>Log Out</Text>
                    </TouchableOpacity>
                </View>

            </View>
        )}
    }

    export default Article

    const styles = StyleSheet.create({
        container:{
            flex:1,
            justifyContent:'center',
            alignItems:'center',
            backgroundColor:'red'
            },
            button:{
                color:'white',
                justifyContent:'center',
                alignItems:'center',
                textAlign:'center',
                fontWeight:'bold',
                fontSize:25
            },

            buttonContainer:{
                backgroundColor:'green',
                color:'white',
                padding:10,
                borderRadius:8,
                width:300,
                height:50,
                textAlign:'center',
                padding:10,
                alignSelf:'center',
                marginTop:50
            }
        }
    )

A: Try this:
import React, { Component } from 'react'
import { View, Text , StyleSheet, TouchableOpacity} from 'react-native'
import firebase from 'firebase'

export default class Article extends Component {
  handleOnPress = () => {
    alert('Called') //just to see if the function it's called
    firebase.auth().signOut();
  }

 render() {
   return (
      <View style={styles.container}>
        <Text>You are logged in </Text>
        <TouchableOpacity style={styles.buttonContainer} onPress={this.handleOnPress}>
            <Text>Log Out</Text>
        </TouchableOpacity>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container:{
      flex:1,
      justifyContent:'center',
      alignItems:'center',
      backgroundColor:'red'
    },
    button:{
      color:'white',
      justifyContent:'center',
      alignItems:'center',
      textAlign:'center',
      fontWeight:'bold',
      fontSize:25
    },
    buttonContainer:{
      backgroundColor:'green',
      color:'white',
      padding:10,
      borderRadius:8,
      width:300,
      height:50,
      textAlign:'center',
      padding:10,
      alignSelf:'center',
      marginTop:50
    }
})


text:
Q: cx_Freeze : Importing modules fails I would like to compile a Python3 project with cx_Freeze, but no matter what I do I can never import my own .py files.
Here's my directory structure:
projectname/
 setup.py
 app/
    code/
       __init__.py
       config.py
       run.py
       run - editeur.py
       ...
    image/
       ...
    level/
       ...

My setup.py :
import sys, os
from cx_Freeze import setup, Executable

path = sys.path
includes = []
excludes = []
packages = ["app/code"]
includefiles = ["app/image", "app/level"]

optimize = 0
silent = True

options = {"path": path,
       "includes": includes,
       "excludes": excludes,
       "packages": packages,
       "include_files": includefiles,
       "optimize": optimize,
       "silent": silent
       }

base = Win32GUI

cible_1 = Executable(
    script="app/code/run.py",
    )

cible_2 = Executable(
    script="app/code/run - editeur.py",
    )

setup(
    name="project",
    version="1.0",
    description="blabla",
    options={"build_exe": options},
    executables=[cible_1, cible_2]
    )

The cx_Freeze compilation is going well and I get my 2 executables.
But when I try to launch one, every time I get the same error:
[...]
File "app/code/run.py", line 7, in <module>
import config
ImportError: No module named 'config'

I really have to miss something stupid since I have no problem with the plug-ins.
It may also be a problem of path or something else I don't know...
Anyone know how to help me a little ? Thanks !

A: EDIT: I've managed to freeze a simplified example based on your directory structure with the following modification of the setup.py script:
path = sys.path + ['app/code']
packages = []

Alternatively, you could also try the following structure (modifying the import paths accordingly):
projectname/
   setup.py
   config.py
   run.py
   run - editeur.py
   ...
   image/
      ...
   level/
      ...


text:
Q: How to know the sender of a javascript function? In HTML, I have some images and a javascript function.

...

When user is on an image. I want to change my header text according to the language selected.
I need a way to have a "reference" to the sender of my function in javascript.
But I have no idea because I have not used javascript for years. Please Help me !
function repl() {

    // Missing Solution
    // var lang = sender.attr("class"); <= Please correct me

    var headerText = "";
    if (lang == 'FR') {
        headerText = "Cliquez sur le drapeau"
    } else {
        headerText = "Click on flag"
    }

A: The best solution would be to bind the event using addEventListener.  Give all your images the same class, select them, then add events.  I also suggest using data-* attributes to store the language.

Then in your JavaScript:
window.onload = function(){// Make sure DOM is ready
    // Get the images
    var imgs = document.getElementsByClassName('repl');

    // Loop over them
    for(var i = 0, len = imgs.length; i < len; i++){
        // Add the event
        imgs[i].addEventListener('mouseover', function(){
            // Get the language. "this" is the element we hovered over
            var lang = this.getAttribute('data-lang');

            var headerText = "";
            if (lang == 'FR') {
                headerText = "Cliquez sur le drapeau"
            } else {
                headerText = "Click on flag"
            }
        });
    }
};

DEMO: http://jsfiddle.net/cT7Tj/1/

A: First you need to send the sender to your function:
<img onmouseover="repl(this)" class="EN" ...

Then:
function repl(sender) {
//you have the element that sent the event
    var lang = sender.getAttribute('data-lang');
    var headerText = "";
    if (lang == 'FR') {
        headerText = "Cliquez sur le drapeau"
    } else {
        headerText = "Click on flag"
    }
}

A: var lang = this.getAttribute('class');
You should rather use a "data-lang" attribute.

A:     function repl() {

   var lang = navigator.language || navigator.userLanguage; //this will fetch the current browser language
   var headerText = "";

   switch (lang) {
       case 'fr':
           document.getElementById('your_id').innerHTML = "Cliquez sur le drapeau";
           break;
       default:
           document.getElementById('your_id').innerHTML = "Click on flag"
   }


text:
Q: Datepicker event noncalling I have a mobile datepicker that works except for its event functions, which are not called. What is the problem?
<script type="text/javascript">
$("#calendar").datepicker({
    onSelect: function () { alert('1'); },
    beforeShow: function () { alert('2'); },
    beforeShowDay: function () { alert('3'); }
});
</script>

<div>
<input id="calendar" type="date"/>
</div>

A: Sorry before I haven't realised of the input type that's not correct. Datepicker usually works with input type text.
Date is a new input type on HTML5, you are using that calendar instead of jQuery datepicker, that's why events doesn't work.
Check this fiddle for your example.
I would suggest you to use datepicker because input=date isn't supported by many browsers and has less options.
I expect that in near future we could use HTML 5 features supported by all browsers and write less javascript code.


text:
Q: How to calculate max current taken by coolers? I have:

*

*3 coolers - Lian Li BR lite 120 rgb

*Asus x570 I motherboard

I'm thinking if I can connect all three coolers to one MB header.
In the motherboard manual it says that coolers header max current should be 1A.
On the cooler it's says "0.17A" but on the package it also mentions that input current is 0.32A (Max 0.45A). See attached photos.
Is my understanding correct that I should take 0.17A to calculate max current that all coolers will take - 0.17A * 3 = 0,51A, and it's safe to connect all of them to single header?


text:
Q: Transition starts too early, while css style hasn't applied completely yet My code is here.
There are three position:zero(0,0),end(200,200),random(0,200).
A div is in the position random(0,200) at the beginning.
I want to :
step 1) set the div in the position zero(0,0). this step no animation
step 2) move it from position zero to position end by transition. this step has animation
Code like this does't work very well:
document.getElementById('x').className = 'pos_zero';    // set the div to the position zero(0,0)
move();
// in function move:
// document.getElementById('x').className = ' trans';
// document.getElementById('x').className += ' pos_end' ;

It seems that transition starts too early, while css style(className = 'pos_zero') hasn't applied completely yet. It just directly moves from position random to position end. And what I really want is the animation to position end from position zero, not from random.
Code like this  works:
document.getElementById('x').className = 'pos_zero';    // set the div to the position zero(0,0)
setTimeout('move()',1);

This code do successfully by using a timeout function. This code sets the div in the position pos_zero first and then do transition asynchronously by a timeout function. And the timeout function seems not very professional.
So, I'm looking for a  more professional solution.
By the way. I wonder. If there is any way to ensure the style is applied completely, like "Style.flush()" or something?
@Inerdial It does work!Many thanks.To force an update (to force an immediate, synchronous reflow or relayout), your javascript should read a property that's affected by the change, e.g. the location of someSpan and otherSpan.` The new code works without Timeout.
document.getElementById('x').className = 'pos_zero';
var tmp = document.getElementById('x').offsetTop; // read a property to force an update.
move();

Thank you guys all. And sorry for the confusing made by me.

A: Thanks to @Inerdial. It does work!.
Actually this answer is coming from his comment.
To force an update (to force an immediate, synchronous reflow or relayout), your javascript should read a property that's affected by the change, e.g. the location of someSpan and otherSpan.`  - stackoverflow.com/a/1397505/41655
The new code works without Timeout(jsfiddle.net/vd6V8):
document.getElementById('x').className = 'pos_zero';
var tmp = document.getElementById('x').offsetTop; // read a property to force an update.
move();

Thank you guys all. And sorry for the confusing made by me.

A: This is actually the only way, because between CSS changes the browser needs to "disengage" from the currently running code.
When you use setTimeout() the code exits, CSS gets applied and then your other code gets run. This yields the expected behaviour.


text:
Q: Matrix, orthogonal and cross product Let A be ortogonal $3\times3$ matrix. How do I show that
$$A(v\times w)=(\det A)(Av\times Aw)$$
Here \times is crossproduct and v and w are $3$-dim vector.

A: Restate the claim as $A^T(Av\times Aw)=(\det A)(v\times w)$. The $i$th component of the left-hand side is$$A_{ij}^T\epsilon_{jkl}(Av)_k(Aw)_l=\epsilon_{jkl}A_{ji}A_{km}A_{ln}v_mw_n=(\det A)\epsilon_{imn}v_mv_n,$$which is the $i$th component of the right-hand side.


text:
Q: Indexing zip files with Lucene Is it possible to index zipped folders in lucene. If i unzip it the content is too large.
If i just index the bunch of zipped folders containing textfiles,
The serach does not work properly.
Is it possible for lucene to index with out extracting the zip file.

A: Lucene is just a search library and there's no way it can "know" every possible scenario - e.g. how to index XML documents, word files, files inside .zip, files created by Chernobyl power plant, etc.
But what Lucene does it to provide the API for you to hook your data into Lucene.
If unzipping the contents of the archive file is not an option, you could write a class that reads the zip file (but does not unzip it on the disk) and feeds this data into Lucene.
If your primary concern is the size of the index, there's nothing much you can do to reduce it. There are a few tips though:

*

*try indexing without stopwords

*do not store the fields, only index them (hint: Field.Store.NO)

*always lowercase all terms to reduce term count


text:
Q: How to query Lucene to retrieve only documents with field values in given ranges? I need to perform basic Lucene query with sql-like characteristics: retrieve only documents which have numeric field values in specific ranges.
Like "text:hello world AND numeric_x:between 50 and 100 AND numeric_Y: between 100 and 200".
Thank you?

A: Depending on your requirement - including 100 and 200:
numeric_Y:[100 TO 200]

excluding 100 and 200 (between 100 and 200):
numeric_Y:{100 TO 200}

.. or a combination, including 101 and 200:
numeric_Y:{100 TO 200]


text:
Q: Windows Authentication with Authorization tags for certain ASP.NET pages I am developing an intranet asp.net application. We will be using Windows authentication, so the authentication mode is set to windows in web.config.
I want to restrict some pages to only certain users so I am using the
 tag with the  tag to allow/deny certain users.
Scenario :
User1 is not allowed access to page "Reports.aspx" (this page has restricted access using the authorization tag in web.config)
User2 is allowed access to this page.
Both of them are in the MYCOMPANY domain.
When User1 tries to access this page he is shown a credentials popup - he will enter the details of "User2" since user2 is allowed access ; subsequently, user1 is now able to access this page(by using user2's details).
Now user1 goes back to some other page which is not restricted by authorization tag. Lets say he goes to homepage. Now again from homepage, he will try to access Reports.aspx. At this point logically speaking, again a prompt for login credentials must come up . But instead no popup comes up and the user1 is allowed access to REports page.
I decided to check the username using HTTPContext.Current.User.Identity.Name in this scenario. When the user1 is trying to access Reports.aspx for second time(after having logged in successfully first time) his credentials are being stored in the browser(I guess) because this time around, when the page loads, the credentials show up as User2 in code behind.
How to prevent this and force a login prompt every time for this page ?

A: Guess I was a n00b back when I asked this.
For the benefit of people who might have faced a scenario - when you login again, the original credentials are no longer maintained and ASP.NET always recognizes you as the User2 hereafter.


text:
Q: Checkstyle Can't Generate Report With Custom Check I am trying to create my own custom check for Checkstyle. I created an artifact and gave it on the classpath (dependency in the POM). Then included it in my configuration.xml file. I am getting the following error:
 An error has occurred in Checkstyle report generation.: Failed during checkstyle configuration: cannot initialize module TreeWalker - Unable to instantiate 'com.lft.cos.checkstyle.custom.MethodsOrderCheck' class.

Can someone point me to what I am doing wrong?


text:
Q: Dynamic References to Specify Secret Manager Values in AWS Cloudformation Is there anyway we can pass dynamic references to Secret Manager to AWS Launch Config User Data?
Here is the code snippet I tried:
"SampleLaunchConfig": {
            "Type": "AWS::AutoScaling::LaunchConfiguration",
             "Properties": {
                "ImageId": {
                    "Fn::FindInMap": [
                        "AWSRegionArch2AMI",
                        {
                            "Ref": "AWS::Region"
                        },
                        "AMI"
                    ]
                },
                "UserData": {
                    "Fn::Base64": {
                        "Fn::Join": [
                            "",
                            [
                                "#!/bin/bash -xe\n",
                                "yum update -y\n",
                                "useradd -p <<pwd>>{{resolve:secretsmanager:Credentials:SecretString:userName}}\n",
                                "\n"
                            ]
                        ]
                    }
                }
        }
    }

Seems error in getting the useradd: invalid user name '{{resolve:secretsmanager:Credentials:SecretString:userName}}'
How can I pass Secret Manager secret value to cloudformation user data ?

A: I am not sure why this is not expanded correctly for you. However, you probably do not want CFN to expand your secret in the user data because the password would be embedded in the base64 encoded user data script which is visible in the EC2 console.
Instead you should take advantage of the fact that you have a script that executes on the host and call secrets manager at script execution time (warning untested):
"SampleLaunchConfig": {
        "Type": "AWS::AutoScaling::LaunchConfiguration",
         "Properties": {
            "ImageId": {
                "Fn::FindInMap": [
                    "AWSRegionArch2AMI",
                    {
                        "Ref": "AWS::Region"
                    },
                    "AMI"
                ]
            },
            "UserData": {
                "Fn::Base64": {
                    "Fn::Join": [
                        "",
                        [
                            "#!/bin/bash -xe\n",
                            "yum update -y\n",
                            "yum install -y jq\n",
                            !Sub "useradd -p `aws --region ${AWS::Region} secretsmanager get-secret-value --secret-id Credentials --query SecretString --output text | jq -r .passwordKey` `aws --region ${AWS::Region} secretsmanager get-secret-value --secret-id Credentials --query SecretString --output text | jq -r .userName`\n",
                            "\n"
                        ]
                    ]
                }
            }
    }
}

This is not ideal since it expands the password on the command line. It might be made more secure by putting the password in a file first and reading it from there and then shredding the file.

A: I can confirm that @JoeB's "warning untested" answer works, with the caveat that the machine in question must have permission to read the secret. You'll need something like
  MyInstancePolicy:
    Type: AWS::IAM::Policy
    Properties:
      PolicyName: MyPolicy
      PolicyDocument:
        Version: 2012-10-17
        Statement:
          -
            Effect: Allow
            Action:
              - secretsmanager:GetSecretValue
            Resource: !Join
              - ''
              - - !Sub "arn:aws:secretsmanager:${AWS::Region}:"
                - !Sub "${AWS::AccountId}:secret:Credentials-??????"

Note a couple of things:
Unlike S3 buckets, you can't do arn:aws:secretsmanager:::secret.... If you don't want to explicitly declare the region and account, you need to use a wildcard. Buried at the bottom of Using Identity-based Policies (IAM Policies) for Secrets Manager

If you don't care about the region or account that owns a secret,
  you must specify a wildcard character * (not an empty field) for the
  region and account ID number fields of the ARN.

Perhaps less important, and less likely to cause unexpected failures, but still worth note:

Using '??????' as a wildcard to match the 6 random characters that
  are assigned by Secrets Manager avoids a problem that occurs if you
  use the '*' wildcard instead. If you use the syntax
  "another_secret_name-*", it matches not just the intended secret with
  the 6 random characters, but it also matches
  "another_secret_name-a1b2c3". Using the '??????' syntax
  enables you to securely grant permissions to a secret that doesn't yet
  exist.

A: It seems that {{resolve:...}} dynamic references are only expanded in certain contexts within a template.
There is no precise information in the AWS docs about exactly where in a template you can use these references.  The current wording with regard to {{resolve:secretsmanager:...}} says:

"The secretsmanager dynamic reference can be used in all resource properties"

However this is contradicted by your example, and I've also observed dynamic references failing to resolve inside of CloudFormation::Init data.
I have an active Support case open with AWS about this, they have agreed that the behaviour of dynamic references is inadequately documented.  I'll update this answer as I learn more.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/dynamic-references.html#dynamic-references-secretsmanager

A: Variant on @JoeB's answer:
Resources:
  SampleLaunchConfig:
    Type: AWS::AutoScaling::LaunchConfiguration
    Properties:
      ImageId: !FindInMap [ AWSRegionArch2AMI, !Ref: 'AWS::Region', AMI ]
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash -xe
          exec > >(tee /var/log/user-data.log | logger -t user-data) 2>&1

          yum update -y
          yum install -y jq

          username=$(aws secretsmanager get-secret-value --secret-id Credentials \
                                                         --query SecretString \
                                                         --region ${AWS::Region} --output text | jq -r .userName)
          password=$(aws secretsmanager get-secret-value --secret-id Credentials \
                                                         --query SecretString \
                                                         --region ${AWS::Region} --output text | jq -r .passwordKey)
          useradd -p "$password" $username

UserData in JSON is painful to watch these days.
I've also added a technique to split out the UserData logic to it's own log file, as otherwise it goes in cloud-init.log, which is also painful to read.

A: The proper way to do it is to call secret manager to get your data, here is how I succeded doing it :
SftpCredsUserPasswordSecret:
    Type: 'AWS::SecretsManager::Secret'
    Properties:
      Name: 'sftp-creds-user-password-secret'
      Description: DB Credentials
      GenerateSecretString:
        SecretStringTemplate: '{"username":"sftpuser"}'
        GenerateStringKey: "password"
        PasswordLength: 30
        ExcludePunctuation: true

  Ec2SftpRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument: # Tells that Ec2 can assume this role
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Action:
              - sts:AssumeRole
            Principal:
              Service:
                - ec2.amazonaws.com
      Policies: # Tells that you can call for the secret value
        - PolicyName: "root"
          PolicyDocument:
            Version: "2012-10-17"
            Statement:
              - Effect: Allow
                Action: "secretsmanager:GetSecretValue"
                Resource: !Ref SftpCredsUserPasswordSecret
      RoleName: 'role-ec2-sftp'

  Ec2SftpIamInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      InstanceProfileName:  'instance-profile-ec2-sftp'
      Roles:
        - !Ref Ec2SftpRole

  Ec2Sftp:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: "ami-06ce3edf0cff21f07"
      InstanceType: t2.micro
      SecurityGroupIds:
        - !ImportValue SgBridgeId
        - !ImportValue SgSftpId
      SubnetId: !ImportValue PublicSubnetAZbId
      KeyName: !Ref KeyName
      UserData:
        Fn::Base64: !Sub
        - |
          #!/bin/bash

          # Get Variables
          secret=`aws --region ${AWS::Region} secretsmanager get-secret-value --secret-id ${secretRef} --query SecretString --output text`
          sftpuser=`echo "$secret" | sed -n 's/.*"username":["]*\([^(",})]*\)[",}].*/\1/p'`
          sftppassword=`echo "$secret" | sed -n 's/.*"password":["]*\([^(",})]*\)[",}].*/\1/p'`

          # Create Sftp User
          adduser $sftpuser
          echo "$sftpuser:$sftppassword" | chpasswd

          # Configure sftp connection
          echo "" >> /etc/ssh/sshd_config
          echo "Match User $sftpuser" >> /etc/ssh/sshd_config
          echo "    PasswordAuthentication yes" >> /etc/ssh/sshd_config
          echo "    ForceCommand /usr/libexec/openssh/sftp-server" >> /etc/ssh/sshd_config

          # Restart the service
          systemctl restart sshd
        -
          secretRef: !Ref SftpCredsUserPasswordSecret
      IamInstanceProfile: !Ref Ec2SftpIamInstanceProfile
      Tags:
        - Key: Name
          Value: 'ec2-sftp'

A: I have a cfn template similar to below working
Parameters:
  ASecret:
    Type: String
    Default: '{{resolve:secretsmanager:ASecret}}'
-
-
-
UserData:
        Fn::Base64: !Sub |
            #!/bin/bash -xe

            echo ${ASecret}

A: AWS CloudFormation enhances the existing dynamic referencing of AWS Systems Manager Parameter Store parameters in CloudFormation templates. You can now reference the latest Systems Manager parameter values in CloudFormation templates without specifying parameter versions.
See more
https://aws.amazon.com/about-aws/whats-new/2021/04/now-reference-latest-aws-systems-manager-parameter-values-in-aws-cloudformation-templates-without-specifying-parameter-versions/


text:
Q: Error for knn: no missing values are allowed - I don't have any missing values in the data I am working on a data mining project (as a total coding outsider) and am trying to run a K-Nearest Neighbor analysis. However, I keep getting the "no missing values are allowed" error. My data does not have missing values so something must be wrong with my code. Can anyone help?
AirbnbNYCApril = read.delim(file=file.choose(),
                            header = T,
                            sep = ",",
                            stringsAsFactors = F)
> str(AirbnbNYCApril)
AirbnbNYCApril = na.omit(AirbnbNYCApril)
set.seed(1)
n = nrow(AirbnbNYCApril)

Train_indices = 1:round(0.75*n)
Test_indices = (round(0.75*n)+1):n
AirbnbNYCApril_shuffle = AirbnbNYCApril[sample(n),]
AirbnbNYCApril_Train = AirbnbNYCApril_shuffle[Train_indices,]

AirbnbNYCApril_Test = AirbnbNYCApril_shuffle[Test_indices,]
Train_labels = AirbnbNYCApril_Train$neighborhood
Test_labels = AirbnbNYCApril_Test$neighborhood
AirbnbNYCApril_Train$neighborhood = NULL
AirbnbNYCApril_Test$neighborhood = NULL
min_reviews = min(AirbnbNYCApril_Train$reviews)
max_reviews = max(AirbnbNYCApril_Train$reviews)
AirbnbNYCApril_Train$reviews = (AirbnbNYCApril_Train$reviews - min_reviews)/(max_reviews - min_reviews)
AirbnbNYCApril_Test$reviews = (AirbnbNYCApril_Test$reviews - min_reviews)/(max_reviews - min_reviews)
min_accommodates = min(AirbnbNYCApril_Train$accommodates)
max_accommodates = max(AirbnbNYCApril_Train$accommodates)
AirbnbNYCApril_Train$accommodates = (AirbnbNYCApril_Train$accommodates - min_accommodates)/(max_accommodates - min_accommodates)
min_price = min(AirbnbNYCApril_Train$price)
max_price = max(AirbnbNYCApril_Train$price)
AirbnbNYCApril_Train$price = (AirbnbNYCApril_Train$price - min_price)/(max_price - min_price)
AirbnbNYCApril_Test$price = (AirbnbNYCApril_Test$price - min_price)/(max_price - min_price)
min_lat = min(AirbnbNYCApril_Train$latitude)
max_lat = max(AirbnbNYCApril_Train$latitutde)
AirbnbNYCApril_Train$latitude = (AirbnbNYCApril_Train$latitude - min_lat)/(max_lat - min_lat)
AirbnbNYCApril_Test$latitude = (AirbnbNYCApril_Test$latitude - min_lat)/(max_lat - min_lat)
min_lon = min(AirbnbNYCApril_Train$longitude)
max_lon = max(AirbnbNYCApril_Train$longitude)
AirbnbNYCApril_Train$longitude = (AirbnbNYCApril_Train$longitude - min_lon)/(max_lon - min_lon)
AirbnbNYCApril_Test$longitude = (AirbnbNYCApril_Test$longitude - min_lon)/(max_lon - min_lon)

neighborhood_prediction = knn(train = AirbnbNYCApril_Train[,-1], test = AirbnbNYCApril_Test[,-1], cl = Train_labels, k=5)

confusion_matrix = table(Test_labels, neighborhood_prediction)

print(confusion_matrix)


text:
Q: How make $resource wait more timeout than 30s? Conbsider the code:
var searchResource = function(token) {
    var _url = ['my_url', '/somePAth'].join('');
    return $resource(_url, {}, {
        query: {
            timeout: 300000,
            method: 'GET',
            headers: {
                Auth: 'my_token'
            }
        }
    });
};

When I user timeout: 10 I got timeout exception immidiatelly but when I set it to 300000 any responce ends up with 30s (not 300s). It there another settings for timeout, say maxTimeout for all angularjs resources? How to make $resource wait more time than 30s?
Browser is GoogleChrome 65.0.3325.181
Angularjs version 1.5.11

A: The problem was on backend, not at angular side. (https://docs.aws.amazon.com/apigateway/api-reference/resource/integration/#timeoutInMillis)
Many thanks for comments about backend.


text:
Q: (*it).second. How this keyword works? for(it=visited.begin(); it!=visited.end();++it)
        {
            if((*it).second>ttl){
                ++count;
            }
        }

What does the line if((*it).second>ttl) means here ?
For better understanding see this code please .... http://ideone.com/NY4ofJ  .
Thanks in Advance .

A: A map is a collection of pair ; with a key and a value. To access to the key you use the member first and to access to the value you use member second.
(*it).second or it->second dereference the iterator and get the second value of the pair contains in the map.
So, the value contained by the iterator is tested with the value contained by the ttl variable.

A: The line in the question points to the second value of a Map or Pair ... for more :
See Here


text:
Q: Help with debugging JQuery Fade Script For one of my first ventures into JQuery, I have the very simple goal of stepping through the children of a div and fading them in and out one by one.  For some reason though, if I manually define an index for nth-child, say 1, then the first child fades in and out four times.  If I use the variable "i", however, then all of the children fade in and out four times.  Why is this happening?
Here is my code:

Text1

Text2

Test3

Text4

Each of the paragraphs is set to display: none; initially.

A: When you manually enter a index (1), then you loop 4 times and fadein the first child 4 times.
When you use i they will all fadeIn four times since i inside a string is not a reference to the i variable, it's just part of the string.
$(document).ready(function() {
        var $elements = $('#slideshow').children();
        var len = $elements.length;
        var i = 1;
        for (i=1;i<=len;i++)
        {
            $("#slideshow p:nth-child("+i+")").fadeIn("slow").delay(800).fadeOut("slow");
        }
});

Should work, notice "+i+"
A better way to do this is:
$(function(){
    $('#slideshow p').each(function(i, node){
         setTimeout(function(){
             $(node).fadeIn("slow").delay(800).fadeOut("slow");
             node = null; //prevent memory leak
         }, i * 800);
    });
});

A: You need to escape i. Right now, nth-child is looking for the child that has an index of i, not of 0, 1, 2, etc. So instead, use:
$('#slideshow p:nth-child(' + i + ')').fadeIn('slow').delay(800).fadeOut('slow');

However, I don't think that will do one at a time; in fact, I'm pretty sure it won't. If it doesn't, try something like this:
var delay = 0;
$('#slideshow p').each(
    function (index, item)
    {
        $(this).delay(delay).fadeIn('slow').delay(800).fadeOut('slow');
        delay += 2200;
    }
);

That's untested, but should be decent pseudocode at the very least.

A: I am not saying this impossible but in the end it will be pointless to use even if you get it to work, as it will fail on IE.
refer here.
http://css-tricks.com/how-nth-child-works/


text:
Q: Spotify long term login with Android SDK I'm looking forward to implement an app which connects to Spotify. To use Spotify services, I need a token, which I can get with the Spotify SDK, however this token is intended for quick expiring not for long term use. In the web API I can make calls from within my server to get new access tokens via refresh_token. I know this must be done in a call server to server. But, I don't know how should I manage the info provided by the Android Spotify SDK to get the refresh_token from the server. I don't even know if this can be achieved via the Spotify SDK or will I have to implement the whole authorization. I've searched info in the web but I can't find info related to this subject. Hope someone can help.

A: A few months ago I have developed an app which also uses Spotify's services. Since I wanted to query audio features of a song, I had to use Spotify's Web API instead as Spotify's Android SDK hasn't provided such thing yet. When I implemented the app I didn't think about it too much so every time when I need to do queries I'd get the access token again. You can get the token using the following code, inside the json string also comes with a expires_in property that tells you how many seconds the token will expire, therefore it should be easy to achieve what you want with some slight modification.
private String getAccessTokenFromJsonStr(String spotifyJsonStr) throws JSONException {
    final String OWM_ACCESS_TOKEN = "access_token";
    String accessToken;

    try {
        JSONObject spotifyJson = new JSONObject(spotifyJsonStr);
        accessToken = spotifyJson.getString(OWM_ACCESS_TOKEN);
    } catch (JSONException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
        e.printStackTrace();
    }

    return accessToken;
}

private String getSpotifyAccessToken(){
    String response;
    String accessToken;
    try {
        String serviceURL = "https://accounts.spotify.com/api/token";
        URL myURL = new URL(serviceURL);

        HttpsURLConnection myURLConnection = (HttpsURLConnection) myURL.openConnection();

        String userCredentials = "YOUR_USER_CREDENTIALS:YOUR_USER_CREDENTIALS";
        int flags = Base64.NO_WRAP | Base64.URL_SAFE;
        byte[] encodedString = Base64.encode(userCredentials.getBytes(), flags);
        String basicAuth = "Basic " + new String(encodedString);
        myURLConnection.setRequestProperty("Authorization", basicAuth);

        myURLConnection.setRequestMethod("POST");
        myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        myURLConnection.setUseCaches(false);
        myURLConnection.setDoInput(true);
        myURLConnection.setDoOutput(true);
        System.setProperty("http.agent", "");

        HashMap postDataParams = new HashMap<String, String>();
        postDataParams.put("grant_type", "client_credentials");
        OutputStream os = myURLConnection.getOutputStream();
        BufferedWriter writer = new BufferedWriter(
                new OutputStreamWriter(os, "UTF-8"));
        writer.write(getPostDataString(postDataParams));

        writer.flush();
        writer.close();
        os.close();

        response = "";
        int responseCode=myURLConnection.getResponseCode();

        Log.d(LOG_TAG, "response code is " + responseCode);

        if (responseCode == HttpsURLConnection.HTTP_OK) {
            String line;
            BufferedReader br=new BufferedReader(new InputStreamReader(myURLConnection.getInputStream()));
            while ((line=br.readLine()) != null) {
                response+=line;
            }
        }
        else {
            response="";
            String errLine;
            String errResponse = "";
            BufferedReader br=new BufferedReader(new InputStreamReader(myURLConnection.getErrorStream()));
            while ((errLine=br.readLine()) != null) {
                errResponse += errLine;
            }
            Log.d(LOG_TAG, "error response is " + errResponse);

        }

        Log.d(LOG_TAG, "response is " + response);

    } catch (Exception e){
        e.printStackTrace();
    }

    String accessTokenJsonStr = response.toString();
    try {
        accessToken = getAccessTokenFromJsonStr(accessTokenJsonStr);
        return accessToken;
    } catch (Exception e) {
        e.printStackTrace();
    }

    return "";
}

Authorization-guide

A: Basically if you need a refresh token (the token provided by SDK lasts for one hour, and then you have to request another one) you need to use the web api to fetch this token. In this case you would not use the SDK for any part of the authentication process. Technically you don't have to use a server↔server component for the passing secret to Spotify server auth step, it's just best practice (security wise) to avoid hard coding the secret into your app, but technically there is nothing preventing you from doing all the authentication steps app↔spotify server utilizing the pertinent web api calls.


text:
Q: Securing the Django web site which is run with Apache mod_wsgi I have made a website in Django 1.6 with PostgreSQL database which is hosted on Ubuntu 12.04.3 with Apache 2.2.22 and I have recently noticed lots of hacking (probing) attempts from various IPs constantly every day which fills my inbox with reports which starts to being just annoying.
Some excerpts from server requests (paths and IPs are masked):
 'PATH_INFO': u'/myadmin/scripts/setup.php',
 'PATH_TRANSLATED': '/path/to/my/project/project.wsgi/myadmin/scripts/setup.php',
 'QUERY_STRING': '',
 'REMOTE_ADDR': 'XXX.XXX.XXX.XXX',
 'REMOTE_PORT': '62637',
 'REQUEST_METHOD': 'GET',
 'REQUEST_URI': '/myadmin/scripts/setup.php',

 'PATH_INFO': u'/phpTest/zologize/axa.php',
 'PATH_TRANSLATED': '/path/to/my/project/project.wsgi/phpTest/zologize/axa.php',
 'QUERY_STRING': '',
 'REMOTE_ADDR': 'XXX.XXX.XXX.XXX',
 'REMOTE_PORT': '60853',
 'REQUEST_METHOD': 'GET',
 'REQUEST_URI': '/phpTest/zologize/axa.php',

 'PATH_INFO': u'/pma/scripts/setup.php',
 'PATH_TRANSLATED': '/path/to/my/project/project.wsgi/pma/scripts/setup.php',
 'QUERY_STRING': '',
 'REMOTE_ADDR': 'XXX.XXX.XXX.XXX',
 'REMOTE_PORT': '64751',
 'REQUEST_METHOD': 'GET',
 'REQUEST_URI': '/pma/scripts/setup.php',

 'CSRF_COOKIE': u'bmbTHkbfWOeldHyAWBwj6rLb2yEopMnZ',
 'PATH_TRANSLATED': '/path/to/my/project/project.wsgi/HNAP1/',
 'QUERY_STRING': '',
 'REMOTE_ADDR': 'XXX.XXX.XXX.XXX',
 'REMOTE_PORT': '57303',
 'REQUEST_METHOD': 'GET',
 'REQUEST_URI': '/HNAP1/',

In some way, I am not concerned with those attempts since they are mostly checking for php vulnerabilities (as far as I have noticed), but I'd like to do something about it more than only fail2ban those IPs.
Since this is the first time I am struggling with this, I'd like to be sure that my web server is really secured enough and I wonder what could I do to be sure that those bots won't do any harm to my web site and database. The information in db itself is not so extra-important and even if someone get a copy of it no one will be hurt, but still... :)
So, my questions are:
1) Is my website and database really "safe" so far since I am not serving any PHP sites on it?
2) Is there anything I can do with Python/Django to gather more info about this attempt except the IP/PORT and PATH they were requesting (e.g. to get the source of the actual script which a "person" tried to run)?
3) Is there any list of very well known IPs which are used for scanning such vulnerabilities so I can automatically update my banned IPs list?
4) Is there any service where I could report IPs which I collected?
5) What are the best practices in general to make your website/server safe from not only those scripts, but any other common penetration attempts (I am aware there may be tons of various attempts, but I'm curious about my specific server configuration only - Django/PostgreSQL/Apache/Ubuntu)?
Thank you very much for any help and tips regarding this!

A: You can for example use mod_security to limit a volume of probe requests from single IP address.
Something like this:
LoadModule security2_module modules/mod_security2.so

<IfModule !mod_unique_id.c>
        LoadModule unique_id_module modules/mod_unique_id.so
</IfModule>

SecRuleEngine On
SecRequestBodyAccess Off
SecResponseBodyAccess Off
SecTmpDir /var/lib/mod_security
SecDataDir /var/lib/mod_security

SecRule REQUEST_URI "\.php$" id:1,phase:request,initcol:IP=%{REMOTE_ADDR},pass,nolog
SecRule IP:COUNTER "@gt 5" d:2,phase:request,t:none,setvar:IP.COUNTER=+1,expirevar:IP.COUNTER=900,deny,status:503,nolog
SecRule REQUEST_URI "\.php$" id:3,phase:request,t:none,setvar:IP.COUNTER=+1,expirevar:IP.COUNTER=900,nolog

This would return 503 Service Unavailable to any IP which tried to access URI with .php more than 5 times, with less that 15 minutes pause between tries.
Don't do this if you have anything running on PHP on your server.


text:
Q: require_once path error in init.php when using composer Hi friends this is my folder structure
googleauth
    -app
       --classes
           ---googleauth.php
       --init.php
   -vendor
     --autoload.php

I have given the following path in init.php
 require_once 'vendor/autoload.php';
 require_once 'classes/GoogleAuth.php';

then the error is shown as
Warning: require_once(vendor/autoload.php): failed to open stream: No such
file or directory in C:\xampp\htdocs\tutorials\googleauth\app\init.php on
line 5
Fatal error: require_once(): Failed opening required 'vendor/autoload.php'
(include_path='C:\xampp\php\PEAR') in
C:\xampp\htdocs\tutorials\googleauth\app\init.php on line 5

So how can I resolve it by giving the correct path for the file

A: You have to use '../vendor/autoload.php' because the path is from the file you running it in.

A: User below code
require_once '../vendor/autoload.php';   // ".." for parent directory
require_once './classes/GoogleAuth.php'; // "." for same dir.
if you are using linux (it is case sensitive), then file name will be the same. like if your file name is "googleauth.php" then you can't use it as "GoogleAuth.php".


text:
Q: Why is this code showing anomalous behaviour? (form not submitted) I'm trying to submit a form using PHP and Ajax. But the problem is that sometimes it inserts one value, sometimes 2, sometimes all, and now it is inserting nothing. Why is it happening? How can I correct it?
Here's my code:
Ajax
$(document).ready(function(){
$("button").click(function(){
$.ajax({
    url: "submitform.php",
    type: "POST",
    data: $("form").serialize(),
    success: function(data){
        alert("well");
    },
    error: function(){
            alert("Error");
            }
        });
    });
 });

HTML
<form id="signupform" name="form1" method="post" enctype="multipart/form-data">

                        <input type="text" name="name" placeholder="Enter your name" required />

                          <input id="imgInput" type="file" name="image"/>

                        <input type="text" name="username" placeholder="Enter username" required />

                        <input id="digits" type="text" name="phone" maxlength="10" placeholder="Enter your phone no." required />

                        <input type="password" name="password" maxlength="12" placeholder="Enter password" required />
                        <input id="button" type="submit" name="submit" value="Sign Up" />

</form>

PHP
<?php
$conn=mysqli_connect("localhost", "root", "", "winkcage");
//$im=$_SESSION["pathsession"];
$nam=""; $usernam=""; $phon=""; $pass="";
$nam=$_POST["name"];
$usernam=$_POST["username"];
$phon=$_POST["phone"];
$pass=$_POST["password"];
$signquery="INSERT INTO signup(name, username, phone, password) VALUES('$nam', '$usernam', '$phon', '$pass')";
$signqueryrun=mysqli_query($conn, $signquery);
?>

NOTE: I don't want to insert image value right now. I'll insert it later when this problem is fixed.

A: Since you are using a form with a submit button, when you click the button it will submit the form. You may be having a conflict between the AJAX action and the form submit. Try preventing the default action on the button click and see if it works as follows:
$(document).ready(function(){
$("#button").click(function(event){
if($("form").get()[0].checkValidity()){
  $.ajax({
      url: "submitform.php",
      type: "POST",
      data: $("form").serialize(),
      success: function(data){
          alert("well");
      },
      error: function(){
              alert("Error");
              }
          });
      });
    }
    event.preventDefault();
 });

A: You may have entered a ' quote and it killed your sql statement. This is called sql injection. To prevent sql injection you can use pdo prepared statements. You will also want to hash passwords to prevent people from stealling them if they get access to your database. Hashing password is a one way encryption that is easy to check.
$pdo = new PDO("mysql:host=$db_host;dbname=$DB_name", $user, $pass);
$sql = "INSERT INTO signup(name, username, phone, password) VALUES(':name', ':username', ':phone', ':pass')";
if ($con = $pdo->prepare($sql)) {
    $con->execute([
        ':name' => $_POST["name"],
        ':username' => $_POST["username"],
        ':phone' => $_POST["username"],
        ':pass' => $_POST["password"]
    ]);
}

As far as the html and javascript goes. Catch the submitted form with jquerys .submit() function.
$('form').submit(function(e){
        e.preventDefault();
        $.post('submit.php',$(this).serialize(),function(response){
            alert('complete');
        }).error(function(){
            alert('wrong');
        });
    });

This makes sure than any submit event triggers the ajax.

A: You assign your onclick to a button element, but there is no button element on your page, your button is an input element. Change that to a button and it may work. I personally would advise using ids, rather than element types, I think it makes things clearer, and will allow you to have more than one element of the same type without breaking your code.
Change
$("button").click(function(){

to
$("#button").click(function(){

and
data: $("form").serialize(),

to
data: $("#signupform").serialize(),


text:
Q: how to keep dropdown selected after refresh I tried to keep retain selected item after reloading the page
this is my drop-down list

after refreshed it looks like this

I used this code for the load drop-down list
<select
     data-bind="value:SelectedOrganisationData,
                options: GridAllOrganisationDataList,
                event: { change: tanantNameSelect } ,
                optionsText:'TenantName',optionsCaption: 'Choose your organisation ...',
                optionsId:'SelectTenantName'"
                class="dropdown">
</select>

function tanantNameSelect() {
        var data = PayrollIntegrationVM.SelectedOrganisationData().TenantName;

        DisplayMessage(data);
    }

using this script I can get the selected value,

A: If you need to retain the data after reloading the page, you have to save the selected value to the database and get the value if the user reloads the page.

A: To me it look like you are most of the way there.  You just need to set the SelectedOrganisationName.

var data = [
  {id: 1, name: 'Test1'},
  {id: 2, name: 'Test2'},
  {id: 3, name: 'Test3'},
  {id: 4, name: 'Test4'},
  {id: 5, name: 'Test5'}
]

function ViewModel(){
  var self = this;
  self.selectedOption = ko.observable();
  self.availableOptions = ko.observableArray(data);

  self.setSelectedOption = function(item){
    self.selectedOption(item);
  }
}
var viewModel = new ViewModel()
ko.applyBindings(viewModel);

<select data-bind="options: availableOptions, optionsText: 'name', optionsId:'id', value: selectedOption"></select>

Press button to set the selection

<button data-bind="text: name, click: $parent.setSelectedOption"></button>

A: The only way too save the data even if you refresh the page is:
Save the data you want there in a database. With doing so, when you refresh the page, the data will still be there.
Thanks. Hope it helps :)It helped me too.

A: Another answer is to make an ajax post instead of full post. That way your selected item will remain selected. Ajax does not refresh the page but only parts of the page that needs refresh.