Programs & Examples On #Webdriver

WebDriver is an API for controlling web browsers, imitating a real user. It's mostly used for automated tests. WebDriver has multiple language bindings and drivers (allowing to control various browsers). If your question is specific to one of them, make sure to also include the appropriate tag.

How to switch to the new browser window, which opens after click on the button?

Just to add to the content ...

To go back to the main window(default window) .

use driver.switchTo().defaultContent();

How do you fix the "element not interactable" exception?

It's worth noting that there is a sleep function built into Selenium.

driver.implicitly_wait(5)

Selenium WebDriver How to Resolve Stale Element Reference Exception?

Use the Expected Conditions provided by Selenium to wait for the WebElement.

While you debug, the client is not as fast as if you just run a unit test or a maven build. This means in debug mode the client has more time to prepare the element, but if the build is running the same code he is much faster and the WebElement your looking for is might not visible in the DOM of the Page.

Trust me with this, I had the same problem.

for example:

inClient.waitUntil(ExpectedConditions.visibilityOf(YourElement,2000))

This easy method calls wait after his call for 2 seconds on the visibility of your WebElement on DOM.

Wait for page load in Selenium

You can use wait. there are basically 2 types of wait in selenium

  • Implicit wait
  • Explicit wait

- Implicit wait

This is very simple please see syntax below:

driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);

- Explicit wait

Explicitly wait or conditional wait in this wait until given condition is occurred.

WebDriverWait wait = new WebDriverWait(driver, 40);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid")));

You can use other properties like visblityOf(), visblityOfElement()

Execute JavaScript using Selenium WebDriver in C#

I prefer to use an extension method to get the scripts object:

public static IJavaScriptExecutor Scripts(this IWebDriver driver)
{
    return (IJavaScriptExecutor)driver;
}

Used as this:

driver.Scripts().ExecuteScript("some script");

Is it possible to run selenium (Firefox) web driver without a GUI?

Yes. You can use HTMLUnitDriver instead for FirefoxDriver while starting webdriver. This is headless browser setup. Details can be found here.

Selenium WebDriver: Wait for complex page with JavaScript to load

Thanks Ashwin !

In my case I should need wait for a jquery plugin execution in some element.. specifically "qtip"

based in your hint, it worked perfectly for me :

wait.until( new Predicate<WebDriver>() {
            public boolean apply(WebDriver driver) {
                return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
            }
        }
    );

Note: I'm using Webdriver 2

Can Selenium WebDriver open browser windows silently in the background?

I used this code for Firefox in Windows and got answer(reference here):

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

Options = Options()
Options.headless = True

Driver = webdriver.Firefox(options=Options, executable_path='geckodriver.exe')
Driver.get(...)
...

But I didn't test it for other browsers.

WebDriver - wait for element using Java

We're having a lot of race conditions with elementToBeClickable. See https://github.com/angular/protractor/issues/2313. Something along these lines worked reasonably well even if a little brute force

Awaitility.await()
        .atMost(timeout)
        .ignoreException(NoSuchElementException.class)
        .ignoreExceptionsMatching(
            Matchers.allOf(
                Matchers.instanceOf(WebDriverException.class),
                Matchers.hasProperty(
                    "message",
                    Matchers.containsString("is not clickable at point")
                )
            )
        ).until(
            () -> {
                this.driver.findElement(locator).click();
                return true;
            },
            Matchers.is(true)
        );

Webdriver Screenshot

WebDriver driver = new FirefoxDriver();
driver.get("http://www.google.com/");
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("c:\\NewFolder\\screenshot1.jpg"));

How to select an option from drop down using Selenium WebDriver C#?

You just need to pass the value and enter key:

driver.FindElement(By.Name("education")).SendKeys("Jr.High"+Keys.Enter);

Refreshing Web Page By WebDriver When Waiting For Specific Condition

One important thing to note is that the driver.navigate().refresh() call sometimes seems to be asynchronous, meaning it does not wait for the refresh to finish, it just "kicks off the refresh" and doesn't block further execution while the browser is reloading the page.

While this only seems to happen in a minority of cases, we figured that it's better to make sure this works 100% by adding a manual check whether the page really started reloading.

Here's the code I wrote for that in our base page object class:

public void reload() {
    // remember reference to current html root element
    final WebElement htmlRoot = getDriver().findElement(By.tagName("html"));

    // the refresh seems to sometimes be asynchronous, so this sometimes just kicks off the refresh,
    // but doesn't actually wait for the fresh to finish
    getDriver().navigate().refresh();

    // verify page started reloading by checking that the html root is not present anymore
    final long startTime = System.currentTimeMillis();
    final long maxLoadTime = TimeUnit.SECONDS.toMillis(getMaximumLoadTime());
    boolean startedReloading = false;
    do {
        try {
            startedReloading = !htmlRoot.isDisplayed();
        } catch (ElementNotVisibleException | StaleElementReferenceException ex) {
            startedReloading = true;
        }
    } while (!startedReloading && (System.currentTimeMillis() - startTime < maxLoadTime));

    if (!startedReloading) {
        throw new IllegalStateException("Page " + getName() + " did not start reloading in " + maxLoadTime + "ms");
    }

    // verify page finished reloading
    verify();
}

Some notes:

  • Since you're reloading the page, you can't just check existence of a given element, because the element will be there before the reload starts and after it's done as well. So sometimes you might get true, but the page didn't even start loading yet.
  • When the page reloads, checking WebElement.isDisplayed() will throw a StaleElementReferenceException. The rest is just to cover all bases
  • getName(): internal method that gets the name of the page
  • getMaximumLoadTime(): internal method that returns how long page should be allowed to load in seconds
  • verify(): internal method makes sure the page actually loaded

Again, in a vast majority of cases, the do/while loop runs a single time because the code beyond navigate().refresh() doesn't get executed until the browser actually reloaded the page completely, but we've seen cases where it actually takes seconds to get through that loop because the navigate().refresh() didn't block until the browser finished loading.

Selenium WebDriver and DropDown Boxes

You can use this

(new SelectElement(driver.FindElement(By.Id(""))).SelectByText("");

How to check if an alert exists using WebDriver?

public boolean isAlertPresent() {

try 
{ 
    driver.switchTo().alert(); 
    system.out.println(" Alert Present");
}  
catch (NoAlertPresentException e) 
{ 
    system.out.println("No Alert Present");
}    

}

How can I start InternetExplorerDriver using Selenium WebDriver

package Browser;

import org.openqa.selenium.WebDriver; import org.openqa.selenium.ie.InternetExplorerDriver;

public class Hello {

public static void main(String[] args) {


    // setting IEdriver property
    System.setProperty("webdriver.ie.driver",
            "paste the path of the IEDriverserver.exe");

    WebDriver driver = new InternetExplorerDriver();

    // launching the google home screen
    driver.get("https://www.google.com/?gws_rd=ssl");

}

} //Hope this will work

Selenium C# WebDriver: Wait until element is present

You do not want to wait too long before the element changes. In this code the webdriver waits for up to 2 seconds before it continues.


WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromMilliseconds(2000));
wait.Until(ExpectedConditions.VisibilityOfAllElementsLocatedBy(By.Name("html-name")));

How do I set the selenium webdriver get timeout?

The solution of driver.manage().timeouts().pageLoadTimeout(10, TimeUnit.SECONDS) will work on the pages with synch loading. This does not solve, however, the problem on pages loading stuff in async, then the tests will fail all the time if we set the pageLoadTimeOut.

selenium get current url after loading a page

It's been a little while since I coded with selenium, but your code looks ok to me. One thing to note is that if the element is not found, but the timeout is passed, I think the code will continue to execute. So you can do something like this:

boolean exists = driver.findElements(By.xpath("//*[@id='someID']")).size() != 0

What does the above boolean return? And are you sure selenium actually navigates to the expected page? (That may sound like a silly question but are you actually watching the pages change... selenium can be run remotely you know...)

How to get attribute of element from Selenium?

As the recent developed Web Applications are using JavaScript, jQuery, AngularJS, ReactJS etc there is a possibility that to retrieve an attribute of an element through Selenium you have to induce WebDriverWait to synchronize the WebDriver instance with the lagging Web Client i.e. the Web Browser before trying to retrieve any of the attributes.

Some examples:

  • Python:

    • To retrieve any attribute form a visible element (e.g. <h1> tag) you need to use the expected_conditions as visibility_of_element_located(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "org"))).get_attribute("attribute_name")
      
    • To retrieve any attribute form an interactive element (e.g. <input> tag) you need to use the expected_conditions as element_to_be_clickable(locator) as follows:

      attribute_value = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.ID, "org"))).get_attribute("attribute_name")
      

HTML Attributes

Below is a list of some attributes often used in HTML

HTML Attributes

Note: A complete list of all attributes for each HTML element, is listed in: HTML Attribute Reference

ImportError: No module named 'selenium'

Navigate to your scripts folder in Python directory (C:\Python27\Scripts) and open command line there (Hold shift and right click then select open command window here). Run pip install -U selenium
If you don't have pip installed, go ahead and install pip first

How can I check if some text exist or not in the page using Selenium?

There is no verifyTextPresent in Selenium 2 webdriver, so you've to check for the text within the page source. See some practical examples below.

Python

In Python driver you can write the following function:

def is_text_present(self, text):
    return str(text) in self.driver.page_source

then use it as:

try: self.is_text_present("Some text.")
except AssertionError as e: self.verificationErrors.append(str(e))

To use regular expression, try:

def is_regex_text_present(self, text = "(?i)Example|Lorem|ipsum"):
    self.assertRegex(self.driver.page_source, text)
    return True

See: FooTest.py file for full example.

Or check below few other alternatives:

self.assertRegexpMatches(self.driver.find_element_by_xpath("html/body/div[1]/div[2]/div/div[1]/label").text, r"^[\s\S]*Weather[\s\S]*$")
assert "Weather" in self.driver.find_element_by_css_selector("div.classname1.classname2>div.clearfix>label").text

Source: Another way to check (assert) if text exists using Selenium Python

Java

In Java the following function:

public void verifyTextPresent(String value)
{
  driver.PageSource.Contains(value);
}

and the usage would be:

try
{
  Assert.IsTrue(verifyTextPresent("Selenium Wiki"));
  Console.WriteLine("Selenium Wiki test is present on the home page");
}
catch (Exception)
{
  Console.WriteLine("Selenium Wiki test is not present on the home page");
}

Source: Using verifyTextPresent in Selenium 2 Webdriver


Behat

For Behat, you can use Mink extension. It has the following methods defined in MinkContext.php:

/**
 * Checks, that page doesn't contain text matching specified pattern
 * Example: Then I should see text matching "Bruce Wayne, the vigilante"
 * Example: And I should not see "Bruce Wayne, the vigilante"
 *
 * @Then /^(?:|I )should not see text matching (?P<pattern>"(?:[^"]|\\")*")$/
 */
public function assertPageNotMatchesText($pattern)
{
    $this->assertSession()->pageTextNotMatches($this->fixStepArgument($pattern));
}

/**
 * Checks, that HTML response contains specified string
 * Example: Then the response should contain "Batman is the hero Gotham deserves."
 * Example: And the response should contain "Batman is the hero Gotham deserves."
 *
 * @Then /^the response should contain "(?P<text>(?:[^"]|\\")*)"$/
 */
public function assertResponseContains($text)
{
    $this->assertSession()->responseContains($this->fixStepArgument($text));
}

Get HTML source of WebElement in Selenium WebDriver using Python

Sure we can get all HTML source code with this script below in Selenium Python:

elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")

If you you want to save it to file:

with open('c:/html_source_code.html', 'w') as f:
    f.write(source_code.encode('utf-8'))

I suggest saving to a file because source code is very very long.

Need to find element in selenium by css

You can describe your css selection like cascading style sheet dows:

protected override void When()
{
   SUT.Browser.FindElements(By.CssSelector("#carousel > a.tiny.button"))
}

How to save and load cookies using Python + Selenium WebDriver

This is a solution that saves the profile directory for Firefox (similar to the user-data-dir (user data directory) in Chrome) (it involves manually copying the directory around. I haven't been able to find another way):

It was tested on Linux.


Short version:

  • To save the profile
driver.execute_script("window.close()")
time.sleep(0.5)
currentProfilePath = driver.capabilities["moz:profile"]
profileStoragePath = "/tmp/abc"
shutil.copytree(currentProfilePath, profileStoragePath,
                ignore_dangling_symlinks=True
                )
  • To load the profile
driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
                 firefox_profile=FirefoxProfile(profileStoragePath)
                )

Long version (with demonstration that it works and a lot of explanation -- see comments in the code)

The code uses localStorage for demonstration, but it works with cookies as well.

#initial imports

from selenium.webdriver import Firefox, FirefoxProfile

import shutil
import os.path
import time

# Create a new profile

driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
                  # * I'm using this particular version. If yours is
                  # named "geckodriver" and placed in system PATH
                  # then this is not necessary
                )

# Navigate to an arbitrary page and set some local storage
driver.get("https://DuckDuckGo.com")
assert driver.execute_script(r"""{
        const tmp = localStorage.a; localStorage.a="1";
        return [tmp, localStorage.a]
    }""") == [None, "1"]

# Make sure that the browser writes the data to profile directory.
# Choose one of the below methods
if 0:
    # Wait for some time for Firefox to flush the local storage to disk.
    # It's a long time. I tried 3 seconds and it doesn't work.
    time.sleep(10)

elif 1:
    # Alternatively:
    driver.execute_script("window.close()")
    # NOTE: It might not work if there are multiple windows!

    # Wait for a bit for the browser to clean up
    # (shutil.copytree might throw some weird error if the source directory changes while copying)
    time.sleep(0.5)

else:
    pass
    # I haven't been able to find any other, more elegant way.
    #`close()` and `quit()` both delete the profile directory


# Copy the profile directory (must be done BEFORE driver.quit()!)
currentProfilePath = driver.capabilities["moz:profile"]
assert os.path.isdir(currentProfilePath)
profileStoragePath = "/tmp/abc"
try:
    shutil.rmtree(profileStoragePath)
except FileNotFoundError:
    pass

shutil.copytree(currentProfilePath, profileStoragePath,
                ignore_dangling_symlinks=True # There's a lock file in the
                                              # profile directory that symlinks
                                              # to some IP address + port
               )

driver.quit()
assert not os.path.isdir(currentProfilePath)
# Selenium cleans up properly if driver.quit() is called,
# but not necessarily if the object is destructed


# Now reopen it with the old profile

driver=Firefox(executable_path="geckodriver-v0.28.0-linux64",
               firefox_profile=FirefoxProfile(profileStoragePath)
              )

# Note that the profile directory is **copied** -- see FirefoxProfile documentation
assert driver.profile.path!=profileStoragePath
assert driver.capabilities["moz:profile"]!=profileStoragePath

# Confusingly...
assert driver.profile.path!=driver.capabilities["moz:profile"]
# And only the latter is updated.
# To save it again, use the same method as previously mentioned

# Check the data is still there

driver.get("https://DuckDuckGo.com")

data = driver.execute_script(r"""return localStorage.a""")
assert data=="1", data

driver.quit()

assert not os.path.isdir(driver.capabilities["moz:profile"])
assert not os.path.isdir(driver.profile.path)

What doesn't work:

  • Initialize Firefox(capabilities={"moz:profile": "/path/to/directory"}) -- the driver will not be able to connect.
  • options=Options(); options.add_argument("profile"); options.add_argument("/path/to/directory"); Firefox(options=options) -- same as above.

How to check if an element is visible with WebDriver

element instanceof RenderedWebElement should work.

How to verify element present or visible in selenium 2 (Selenium WebDriver)

Try using below code:

private enum ElementStatus{
        VISIBLE,
        NOTVISIBLE,
        ENABLED,
        NOTENABLED,
        PRESENT,
        NOTPRESENT
    }
    private ElementStatus isElementVisible(WebDriver driver, By by,ElementStatus getStatus){
        try{
            if(getStatus.equals(ElementStatus.ENABLED)){
                if(driver.findElement(by).isEnabled())
                    return ElementStatus.ENABLED;
                return ElementStatus.NOTENABLED; 
            }
            if(getStatus.equals(ElementStatus.VISIBLE)){
                if(driver.findElement(by).isDisplayed())
                    return ElementStatus.VISIBLE;
                return ElementStatus.NOTVISIBLE;
            }
            return ElementStatus.PRESENT;
        }catch(org.openqa.selenium.NoSuchElementException nse){
            return ElementStatus.NOTPRESENT;
        }
    }

Getting the URL of the current page using Selenium WebDriver

Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium

How can I select checkboxes using the Selenium Java WebDriver?

The below code will first get all the checkboxes present on the page, and then deselect all the checked boxes.

List<WebElement> allCheckbox = driver.findElements(By
    .xpath("//input[@type='checkbox']"));

for (WebElement ele : allCheckbox) {
    if (ele.isSelected()) {
        ele.click();
    }
}

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

I’m going to hold the unpopular on SO selenium tag opinion that XPath is preferable to CSS in the longer run.

This long post has two sections - first I'll put a back-of-the-napkin proof the performance difference between the two is 0.1-0.3 milliseconds (yes; that's 100 microseconds), and then I'll share my opinion why XPath is more powerful.


Performance difference

Let's first tackle "the elephant in the room" – that xpath is slower than css.

With the current cpu power (read: anything x86 produced since 2013), even on browserstack/saucelabs/aws VMs, and the development of the browsers (read: all the popular ones in the last 5 years) that is hardly the case. The browser's engines have developed, the support of xpath is uniform, IE is out of the picture (hopefully for most of us). This comparison in the other answer is being cited all over the place, but it is very contextual – how many are running – or care about – automation against IE8?

If there is a difference, it is in a fraction of a millisecond.

Yet, most higher-level frameworks add at least 1ms of overhead over the raw selenium call anyways (wrappers, handlers, state storing etc); my personal weapon of choice – RobotFramework – adds at least 2ms, which I am more than happy to sacrifice for what it provides. A network roundtrip from an AWS us-east-1 to BrowserStack's hub is usually 11 milliseconds.

So with remote browsers if there is a difference between xpath and css, it is overshadowed by everything else, in orders of magnitude.


The measurements

There are not that many public comparisons (I've really seen only the cited one), so – here's a rough single-case, dummy and simple one.
It will locate an element by the two strategies X times, and compare the average time for that.

The target – BrowserStack's landing page, and its "Sign Up" button; a screenshot of the html as writing this post:

enter image description here

Here's the test code (python):

from selenium import webdriver
import timeit


if __name__ == '__main__':

    xpath_locator = '//div[@class="button-section col-xs-12 row"]'
    css_locator = 'div.button-section.col-xs-12.row'

    repetitions = 1000

    driver = webdriver.Chrome()
    driver.get('https://www.browserstack.com/')

    css_time = timeit.timeit("driver.find_element_by_css_selector(css_locator)", 
                             number=repetitions, globals=globals())
    xpath_time = timeit.timeit('driver.find_element_by_xpath(xpath_locator)', 
                             number=repetitions, globals=globals())

    driver.quit()

    print("css total time {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, css_time, (css_time/repetitions)*1000))
    print("xpath total time for {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, xpath_time, (xpath_time/repetitions)*1000))

For those not familiar with Python – it opens the page, and finds the element – first with the css locator, then with the xpath; the find operation is repeated 1,000 times. The output is the total time in seconds for the 1,000 repetitions, and average time for one find in milliseconds.

The locators are:

  • for xpath – "a div element having this exact class value, somewhere in the DOM";
  • the css is similar – "a div element with this class, somewhere in the DOM".

Deliberately chosen not to be over-tuned; also, the class selector is cited for the css as "the second fastest after an id".

The environment – Chrome v66.0.3359.139, chromedriver v2.38, cpu: ULV Core M-5Y10 usually running at 1.5GHz (yes, a "word-processing" one, not even a regular i7 beast).

Here's the output:

css total time 1000 repeats: 8.84s, per find: 8.84ms

xpath total time for 1000 repeats: 8.52s, per find: 8.52ms

Obviously the per find timings are pretty close; the difference is 0.32 milliseconds. Don't jump "the xpath is faster" – sometimes it is, sometimes it's css.


Let's try with another set of locators, a tiny-bit more complicated – an attribute having a substring (common approach at least for me, going after an element's class when a part of it bears functional meaning):

xpath_locator = '//div[contains(@class, "button-section")]'
css_locator = 'div[class~=button-section]'

The two locators are again semantically the same – "find a div element having in its class attribute this substring".
Here are the results:

css total time 1000 repeats: 8.60s, per find: 8.60ms

xpath total time for 1000 repeats: 8.75s, per find: 8.75ms

Diff of 0.15ms.


As an exercise - the same test as done in the linked blog in the comments/other answer - the test page is public, and so is the testing code.

They are doing a couple of things in the code - clicking on a column to sort by it, then getting the values, and checking the UI sort is correct.
I'll cut it - just get the locators, after all - this is the root test, right?

The same code as above, with these changes in:

  • The url is now http://the-internet.herokuapp.com/tables; there are 2 tests.

  • The locators for the first one - "Finding Elements By ID and Class" - are:

css_locator = '#table2 tbody .dues'
xpath_locator = "//table[@id='table2']//tr/td[contains(@class,'dues')]"

And here is the outcome:

css total time 1000 repeats: 8.24s, per find: 8.24ms

xpath total time for 1000 repeats: 8.45s, per find: 8.45ms

Diff of 0.2 milliseconds.

The "Finding Elements By Traversing":

css_locator = '#table1 tbody tr td:nth-of-type(4)'
xpath_locator = "//table[@id='table1']//tr/td[4]"

The result:

css total time 1000 repeats: 9.29s, per find: 9.29ms

xpath total time for 1000 repeats: 8.79s, per find: 8.79ms

This time it is 0.5 ms (in reverse, xpath turned out "faster" here).

So 5 years later (better browsers engines) and focusing only on the locators performance (no actions like sorting in the UI, etc), the same testbed - there is practically no difference between CSS and XPath.


So, out of xpath and css, which of the two to choose for performance? The answer is simple – choose locating by id.

Long story short, if the id of an element is unique (as it's supposed to be according to the specs), its value plays an important role in the browser's internal representation of the DOM, and thus is usually the fastest.

Yet, unique and constant (e.g. not auto-generated) ids are not always available, which brings us to "why XPath if there's CSS?"


The XPath advantage

With the performance out of the picture, why do I think xpath is better? Simple – versatility, and power.

Xpath is a language developed for working with XML documents; as such, it allows for much more powerful constructs than css.
For example, navigation in every direction in the tree – find an element, then go to its grandparent and search for a child of it having certain properties.
It allows embedded boolean conditions – cond1 and not(cond2 or not(cond3 and cond4)); embedded selectors – "find a div having these children with these attributes, and then navigate according to it".
XPath allows searching based on a node's value (its text) – however frowned upon this practice is, it does come in handy especially in badly structured documents (no definite attributes to step on, like dynamic ids and classes - locate the element by its text content).

The stepping in css is definitely easier – one can start writing selectors in a matter of minutes; but after a couple of days of usage, the power and possibilities xpath has quickly overcomes css.
And purely subjective – a complex css is much harder to read than a complex xpath expression.

Outro ;)

Finally, again very subjective - which one to chose?

IMO, there is no right or wrong choice - they are different solutions to the same problem, and whatever is more suitable for the job should be picked.

Being "a fan" of XPath I'm not shy to use in my projects a mix of both - heck, sometimes it is much faster to just throw a CSS one, if I know it will do the work just fine.

How to handle windows file upload using Selenium WebDriver?

// assuming driver is a healthy WebDriver instance
WebElement fileInput = driver.findElement(By.name("uploadfile"));
fileInput.sendKeys("C:/path/to/file.jpg");

Hey, that's mine from somewhere :).


In case of the Zamzar web, it should work perfectly. You don't click the element. You just type the path into it. To be concrete, this should be absolutely ok:

driver.findElement(By.id("inputFile")).sendKeys("C:/path/to/file.jpg");

In the case of the Uploadify web, you're in a pickle, since the upload thing is no input, but a Flash object. There's no API for WebDriver that would allow you to work with browser dialogs (or Flash objects).

So after you click the Flash element, there'll be a window popping up that you'll have no control over. In the browsers and operating systems I know, you can pretty much assume that after the window has been opened, the cursor is in the File name input. Please, make sure this assumption is true in your case, too.

If not, you could try to jump to it by pressing Alt + N, at least on Windows...

If yes, you can "blindly" type the path into it using the Robot class. In your case, that would be something in the way of:

driver.findElement(By.id("SWFUpload_0")).click();
Robot r = new Robot();
r.keyPress(KeyEvent.VK_C);        // C
r.keyRelease(KeyEvent.VK_C);
r.keyPress(KeyEvent.VK_COLON);    // : (colon)
r.keyRelease(KeyEvent.VK_COLON);
r.keyPress(KeyEvent.VK_SLASH);    // / (slash)
r.keyRelease(KeyEvent.VK_SLASH);
// etc. for the whole file path

r.keyPress(KeyEvent.VK_ENTER);    // confirm by pressing Enter in the end
r.keyRelease(KeyEvent.VK_ENTER);

It sucks, but it should work. Note that you might need these: How can I make Robot type a `:`? and Convert String to KeyEvents (plus there is the new and shiny KeyEvent#getExtendedKeyCodeForChar() which does similar work, but is available only from JDK7).


For Flash, the only alternative I know (from this discussion) is to use the dark technique:

First, you modify the source code of you the flash application, exposing internal methods using the ActionScript's ExternalInterface API. Once exposed, these methods will be callable by JavaScript in the browser.

Second, now that JavaScript can call internal methods in your flash app, you use WebDriver to make a JavaScript call in the web page, which will then call into your flash app.

This technique is explained further in the docs of the flash-selenium project. (http://code.google.com/p/flash-selenium/), but the idea behind the technique applies just as well to WebDriver.

How to select a drop-down menu value with Selenium using Python?

Unless your click is firing some kind of ajax call to populate your list, you don't actually need to execute the click.

Just find the element and then enumerate the options, selecting the option(s) you want.

Here is an example:

from selenium import webdriver
b = webdriver.Firefox()
b.find_element_by_xpath("//select[@name='element_name']/option[text()='option_text']").click()

You can read more in:
https://sqa.stackexchange.com/questions/1355/unable-to-select-an-option-using-seleniums-python-webdriver

Driver executable must be set by the webdriver.ie.driver system property

The error message says

"The path to the driver executable must be set by the webdriver.ie.driver system property;"

You are setting the path for the Chrome Driver with "webdriver.chrome.driver" property. You are not setting the file location when for InternetExplorerDriver, to do that you must set "webdriver.ie.driver" property.

You can set these properties in your shell, via maven, or your IDE with the -DpropertyName=Value

-Dwebdriver.ie.driver="C:/.../IEDriverServer.exe" 

You need to use quotes because of spaces or slashes in your path on windows machines, or alternatively reverse the slashes other wise they are the string string escape prefix.

You could also use

System.setProperty("webdriver.ie.driver","C:/.../IEDriverServer.exe"); 

inside your code.

Locating child nodes of WebElements in selenium

If you have to wait there is a method presenceOfNestedElementLocatedBy that takes the "parent" element and a locator, e.g. a By.xpath:

WebElement subNode = new WebDriverWait(driver,10).until(
    ExpectedConditions.presenceOfNestedElementLocatedBy(
        divA, By.xpath(".//div/span")
    )
);

Webdriver findElements By xpath

The XPath turns into this:

Get me all of the div elements that have an id equal to container.

As for getting the first etc, you have two options.

Turn it into a .findElement() - this will just return the first one for you anyway.

or

To explicitly do this in XPath, you'd be looking at:

(//div[@id='container'])[1]

for the first one, for the second etc:

(//div[@id='container'])[2]

Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:

(//div[@id='container'])[last()]

Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.

As for getting the parent 'node', well, you can use parent:

//div[@id='container']/parent::*

That would get the div's direct parent.

You could then go further and say I want the first *div* with an id of container, and I want his parent:

(//div[@id='container'])[1]/parent::*

Hope that helps!

Selenium WebDriver.get(url) does not open the URL

Please have a look at this HowTo: http://www.qaautomation.net/?p=373 Have a close look at section "Instantiating WebDriver"

I think you are missing the following code line:

wait = new WebDriverWait(driver, 30);

Put it between

driver = webdriver.Firefox();

and

driver.getUrl("http://www.google.com");

Haven't tested it, because I'm not using Selenium at the moment. I'm familiar with Selenium 1.x.

Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click

In case you need to use it with Javascript

We can use arguments[0].click() to simulate click operation.

var element = element(by.linkText('webdriverjs'));
browser.executeScript("arguments[0].click()",element);

How I can check whether a page is loaded completely or not in web driver?

Selenium does it for you. Or at least it tries its best. Sometimes it falls short, and you must help it a little bit. The usual solution is Implicit Wait which solves most of the problems.

If you really know what you're doing, and why you're doing it, you could try to write a generic method which would check whether the page is completely loaded. However, it can't be done for every web and for every situation.


Related question: Selenium WebDriver : Wait for complex page with JavaScript(JS) to load, see my answer there.

Shorter version: You'll never be sure.

The "normal" load is easy - document.readyState. This one is implemented by Selenium, of course. The problematic thing are asynchronous requests, AJAX, because you can never tell whether it's done for good or not. Most of today's webpages have scripts that run forever and poll the server all the time.

The various things you could do are under the link above. Or, like 95% of other people, use Implicit Wait implicity and Explicit Wait + ExpectedConditions where needed.

E.g. after a click, some element on the page should become visible and you need to wait for it:

WebDriverWait wait = new WebDriverWait(driver, 10);  // you can reuse this one

WebElement elem = driver.findElement(By.id("myInvisibleElement"));
elem.click();
wait.until(ExpectedConditions.visibilityOf(elem));

How to get HTTP Response Code using Selenium WebDriver

It is possible to get the response code of a http request using Selenium and Chrome or Firefox. All you have to do is start either Chrome or Firefox in logging mode. I will show you some examples below.

java + Selenium + Chrome Here is an example of java + Selenium + Chrome, but I guess that it can be done in any language (python, c#, ...).

All you need to do is tell chromedriver to do "Network.enable". This can be done by enabling Performance logging.

LoggingPreferences logPrefs = new LoggingPreferences();
logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

After the request is done, all you have to do is get and iterate the Perfomance logs and find "Network.responseReceived" for the requested url:

LogEntries logs = driver.manage().logs().get("performance");

Here is the code:

import java.util.Iterator;
import java.util.logging.Level;

import org.json.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.logging.LogEntries;
import org.openqa.selenium.logging.LogEntry;
import org.openqa.selenium.logging.LogType;
import org.openqa.selenium.logging.LoggingPreferences;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

public class TestResponseCode
{
    public static void main(String[] args)
    {
        // simple page (without many resources so that the output is
        // easy to understand
        String url = "http://www.york.ac.uk/teaching/cws/wws/webpage1.html";

        DownloadPage(url);
    }

    private static void DownloadPage(String url)
    {
        ChromeDriver driver = null;

        try
        {
            ChromeOptions options = new ChromeOptions();
            // add whatever extensions you need
            // for example I needed one of adding proxy, and one for blocking
            // images
            // options.addExtensions(new File(file, "proxy.zip"));
            // options.addExtensions(new File("extensions",
            // "Block-image_v1.1.crx"));

            DesiredCapabilities cap = DesiredCapabilities.chrome();
            cap.setCapability(ChromeOptions.CAPABILITY, options);

            // set performance logger
            // this sends Network.enable to chromedriver
            LoggingPreferences logPrefs = new LoggingPreferences();
            logPrefs.enable(LogType.PERFORMANCE, Level.ALL);
            cap.setCapability(CapabilityType.LOGGING_PREFS, logPrefs);

            driver = new ChromeDriver(cap);

            // navigate to the page
            System.out.println("Navigate to " + url);
            driver.navigate().to(url);

            // and capture the last recorded url (it may be a redirect, or the
            // original url)
            String currentURL = driver.getCurrentUrl();

            // then ask for all the performance logs from this request
            // one of them will contain the Network.responseReceived method
            // and we shall find the "last recorded url" response
            LogEntries logs = driver.manage().logs().get("performance");

            int status = -1;

            System.out.println("\nList of log entries:\n");

            for (Iterator<LogEntry> it = logs.iterator(); it.hasNext();)
            {
                LogEntry entry = it.next();

                try
                {
                    JSONObject json = new JSONObject(entry.getMessage());

                    System.out.println(json.toString());

                    JSONObject message = json.getJSONObject("message");
                    String method = message.getString("method");

                    if (method != null
                            && "Network.responseReceived".equals(method))
                    {
                        JSONObject params = message.getJSONObject("params");

                        JSONObject response = params.getJSONObject("response");
                        String messageUrl = response.getString("url");

                        if (currentURL.equals(messageUrl))
                        {
                            status = response.getInt("status");

                            System.out.println(
                                    "---------- bingo !!!!!!!!!!!!!! returned response for "
                                            + messageUrl + ": " + status);

                            System.out.println(
                                    "---------- bingo !!!!!!!!!!!!!! headers: "
                                            + response.get("headers"));
                        }
                    }
                } catch (JSONException e)
                {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            System.out.println("\nstatus code: " + status);
        } finally
        {
            if (driver != null)
            {
                driver.quit();
            }
        }
    }
}

The output looks like this:

    Navigate to http://www.york.ac.uk/teaching/cws/wws/webpage1.html

    List of log entries:

    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameAttached","params":{"parentFrameId":"172.1","frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStartedLoading","params":{"frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameNavigated","params":{"frame":{"securityOrigin":"://","loaderId":"172.1","name":"chromedriver dummy frame","id":"172.2","mimeType":"text/html","parentId":"172.1","url":"about:blank"}}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStoppedLoading","params":{"frameId":"172.2"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStartedLoading","params":{"frameId":"3928.1"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.requestWillBeSent","params":{"request":{"headers":{"Upgrade-Insecure-Requests":"1","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"},"initialPriority":"VeryHigh","method":"GET","mixedContentType":"none","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html"},"frameId":"3928.1","requestId":"3928.1","documentURL":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","initiator":{"type":"other"},"loaderId":"3928.1","wallTime":1.47619492749007E9,"type":"Document","timestamp":20226.652971}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.responseReceived","params":{"frameId":"3928.1","requestId":"3928.1","response":{"headers":{"Accept-Ranges":"bytes","Keep-Alive":"timeout=4, max=100","Cache-Control":"max-age=300","Server":"Apache/2.2.22 (Ubuntu)","Connection":"Keep-Alive","Content-Encoding":"gzip","Vary":"Accept-Encoding","Expires":"Tue, 11 Oct 2016 14:13:47 GMT","Content-Length":"1957","Date":"Tue, 11 Oct 2016 14:08:47 GMT","Content-Type":"text/html"},"connectionReused":false,"timing":{"pushEnd":0,"workerStart":-1,"proxyEnd":-1,"workerReady":-1,"sslEnd":-1,"pushStart":0,"requestTime":20226.65335,"sslStart":-1,"dnsStart":0,"sendEnd":31.6569999995409,"connectEnd":31.4990000006219,"connectStart":0,"sendStart":31.5860000009707,"dnsEnd":0,"receiveHeadersEnd":115.645999998378,"proxyStart":-1},"encodedDataLength":-1,"remotePort":80,"mimeType":"text/html","headersText":"HTTP/1.1 200 OK\r\nDate: Tue, 11 Oct 2016 14:08:47 GMT\r\nServer: Apache/2.2.22 (Ubuntu)\r\nAccept-Ranges: bytes\r\nCache-Control: max-age=300\r\nExpires: Tue, 11 Oct 2016 14:13:47 GMT\r\nVary: Accept-Encoding\r\nContent-Encoding: gzip\r\nContent-Length: 1957\r\nKeep-Alive: timeout=4, max=100\r\nConnection: Keep-Alive\r\nContent-Type: text/html\r\n\r\n","securityState":"neutral","requestHeadersText":"GET /teaching/cws/wws/webpage1.html HTTP/1.1\r\nHost: www.york.ac.uk\r\nConnection: keep-alive\r\nUpgrade-Insecure-Requests: 1\r\nUser-Agent: Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36\r\nAccept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8\r\nAccept-Encoding: gzip, deflate, sdch\r\nAccept-Language: en-GB,en-US;q=0.8,en;q=0.6\r\n\r\n","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","protocol":"http/1.1","fromDiskCache":false,"fromServiceWorker":false,"requestHeaders":{"Accept":"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8","Upgrade-Insecure-Requests":"1","Connection":"keep-alive","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36","Host":"www.york.ac.uk","Accept-Encoding":"gzip, deflate, sdch","Accept-Language":"en-GB,en-US;q=0.8,en;q=0.6"},"remoteIPAddress":"144.32.128.84","statusText":"OK","connectionId":11,"status":200},"loaderId":"3928.1","type":"Document","timestamp":20226.770012}}}
    ---------- bingo !!!!!!!!!!!!!! returned response for http://www.york.ac.uk/teaching/cws/wws/webpage1.html: 200
    ---------- bingo !!!!!!!!!!!!!! headers: {"Accept-Ranges":"bytes","Keep-Alive":"timeout=4, max=100","Cache-Control":"max-age=300","Server":"Apache/2.2.22 (Ubuntu)","Connection":"Keep-Alive","Content-Encoding":"gzip","Vary":"Accept-Encoding","Expires":"Tue, 11 Oct 2016 14:13:47 GMT","Content-Length":"1957","Date":"Tue, 11 Oct 2016 14:08:47 GMT","Content-Type":"text/html"}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.dataReceived","params":{"dataLength":2111,"requestId":"3928.1","encodedDataLength":1460,"timestamp":20226.770425}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameNavigated","params":{"frame":{"securityOrigin":"http://www.york.ac.uk","loaderId":"3928.1","id":"3928.1","mimeType":"text/html","url":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html"}}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.dataReceived","params":{"dataLength":1943,"requestId":"3928.1","encodedDataLength":825,"timestamp":20226.782673}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.loadingFinished","params":{"requestId":"3928.1","encodedDataLength":2285,"timestamp":20226.770199}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.loadEventFired","params":{"timestamp":20226.799391}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.frameStoppedLoading","params":{"frameId":"3928.1"}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Page.domContentEventFired","params":{"timestamp":20226.845769}}}
    {"webview":"3b8eaedb-bd0f-4baa-938d-4aee4039abfe","message":{"method":"Network.requestWillBeSent","params":{"request":{"headers":{"Referer":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","User-Agent":"Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.143 Safari/537.36"},"initialPriority":"High","method":"GET","mixedContentType":"none","url":"http://www.york.ac.uk/favicon.ico"},"frameId":"3928.1","requestId":"3928.2","documentURL":"http://www.york.ac.uk/teaching/cws/wws/webpage1.html","initiator":{"type":"other"},"loaderId":"3928.1","wallTime":1.47619492768527E9,"type":"Other","timestamp":20226.848174}}}

    status code: 200

java + Selenium + Firefox I have finally found the trick for Firefox too. You need to start firefox using MOZ_LOG and MOZ_LOG_FILE environment variables, and log http requests at debug level (4 = PR_LOG_DEBUG) - map.put("MOZ_LOG", "timestamp,sync,nsHttp:4"). Save the log in a temporary file. After that, get the content of the saved log file and parse it for the response code (using some simple regular expressions). First detect the start of the request, identifying its id (nsHttpChannel::BeginConnect [this=000000CED8094000]), then at the second step, find the response code for that request id (nsHttpChannel::ProcessResponse [this=000000CED8094000 httpStatus=200]).

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.GeckoDriverService;

public class TestFirefoxResponse
{
  public static void main(String[] args)
      throws InterruptedException, IOException
  {
    GeckoDriverService service = null;

    // tell firefox to log http requests
    // at level 4 = PR_LOG_DEBUG: debug messages, notices
    // you could log everything at level 5, but the log file will 
    // be larger. 
    // create a temporary log file that will be parsed for
    // response code
    Map<String, String> map = new HashMap<String, String>();
    map.put("MOZ_LOG", "timestamp,sync,nsHttp:4");
    File tempFile = File.createTempFile("mozLog", ".txt");    
    map.put("MOZ_LOG_FILE", tempFile.getAbsolutePath());      

    GeckoDriverService.Builder builder = new GeckoDriverService.Builder();
    service = builder.usingAnyFreePort()
      .withEnvironment(map)
      .build();

    service.start();      

    WebDriver driver = new FirefoxDriver(service);

    // test 200
     String url = "https://api.ipify.org/?format=text";
    // test 404
    // String url = "https://www.advancedwebranking.com/lsdkjflksdjfldksfj";
    driver.get(url);

    driver.quit();

    String logContent = FileUtils.readFileToString(tempFile);

    ParseLog(logContent, url);
  }

  private static void ParseLog(String logContent, String url) throws MalformedURLException
  {
    // this is how the log looks like when the request starts
    // I have to get the id of the request using a regular expression
    // and use that id later to get the response
    //
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::BeginConnect [this=000000BFF27A5000]
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp host=api.ipify.org port=-1
    //    2017-11-02 14:14:01.170000 UTC - [Main Thread]: D/nsHttp uri=https://api.ipify.org/?format=text
    String pattern = "BeginConnect \\[this=(.*?)\\](?:.*?)uri=(.*?)\\s";

    Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = p.matcher(logContent);

    String urlID = null;
    while (m.find())
    {
      String id = m.group(1);
      String uri = m.group(2);

      if (uri.equals(url))
      {
        urlID = id;
        break;
      }      
    }

    System.out.println("request id = " + urlID);

    // this is how the response looks like in the log file
    // ProcessResponse [this=000000CED8094000 httpStatus=200]
    // I will use another regular espression to get the httpStatus
    //
    //    2017-11-02 14:45:39.296000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::OnStartRequest [this=000000CED8094000 request=000000CED8014BB0 status=0]
    //    2017-11-02 14:45:39.296000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::ProcessResponse [this=000000CED8094000 httpStatus=200]    

    pattern = "ProcessResponse \\[this=" + urlID + " httpStatus=(.*?)\\]";

    p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    m = p.matcher(logContent);

    if (m.find())
    {
      String responseCode = m.group(1);
      System.out.println("response code found " + responseCode);
    }
    else
    {
      System.out.println("response code not found");
    }
  }
}

The output for this will be

request id = 0000007653D67000 response code found 200

The response headers can also be found in the log file. You can get them if you want.

    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp http response [
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   HTTP/1.1 404 Not Found
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Accept-Ranges: bytes
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Cache-control: no-cache="set-cookie"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Type: text/html; charset=utf-8
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Date: Thu, 02 Nov 2017 14:54:36 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   ETag: "7969-55bc076a61e80"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Last-Modified: Tue, 17 Oct 2017 16:17:46 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Server: Apache/2.4.23 (Amazon) PHP/5.6.24
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Set-Cookie: AWSELB=5F256FFA816C8E72E13AE0B12A17A3D540582F804C87C5FEE323AF3C9B638FD6260FF473FF64E44926DD26221AAD2E9727FD739483E7E4C31784C7A495796B416146EE83;PATH=/
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Length: 31081
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Connection: keep-alive
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp     OriginalHeaders
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Accept-Ranges: bytes
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Cache-control: no-cache="set-cookie"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Type: text/html; charset=utf-8
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Date: Thu, 02 Nov 2017 14:54:36 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   ETag: "7969-55bc076a61e80"
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Last-Modified: Tue, 17 Oct 2017 16:17:46 GMT
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Server: Apache/2.4.23 (Amazon) PHP/5.6.24
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Set-Cookie: AWSELB=5F256FFA816C8E72E13AE0B12A17A3D540582F804C87C5FEE323AF3C9B638FD6260FF473FF64E44926DD26221AAD2E9727FD739483E7E4C31784C7A495796B416146EE83;PATH=/
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Content-Length: 31081
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp   Connection: keep-alive
    2017-11-02 14:54:36.775000 UTC - [Socket Thread]: I/nsHttp ]
    2017-11-02 14:54:36.775000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::OnStartRequest [this=0000008A65D85000 request=0000008A65D1F900 status=0]
    2017-11-02 14:54:36.775000 UTC - [Main Thread]: D/nsHttp nsHttpChannel::ProcessResponse [this=0000008A65D85000 httpStatus=404]

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

My problem was a bug in php-webdriver. My code was:

$chromeOptions = new ChromeOptions();
$chromeOptions->addArguments([
    '--headless',
    '--no-sandbox',
    '--disable-gpu',
    '--disable-dev-shm-usage',
    '--no-proxy-server'
]);
$chromeOptions->setExperimentalOption('detach', true);
$capabilities = DesiredCapabilities::chrome();
$capabilities->setCapability(
    ChromeOptions::CAPABILITY,
    $chromeOptions
);

as you can see, everything is in line with the rest of possible reasons.

But actually capabilities weren't passing to chromedriver. I had to change setting chrome options capability to:

$capabilities->setCapability(
    ChromeOptions::CAPABILITY_W3C, // <<< Have to use W3C capabilities with recent versions of Chromedriver.
    $chromeOptions->toArray() // <<<<< bug in php-webdriver 1.9, object not getting serialized automatically like with the deprecated capability ChromeOptions::CAPABILITY
);

My setup was:

$ chromedriver --version
ChromeDriver 79.0.3945.36 (3582db32b33893869b8c1339e8f4d9ed1816f143-refs/branch-heads/3945@{#614})
$ java -jar selenium-server-standalone-3.141.59.jar --version
Selenium server version: 3.141.59, revision: e82be7d358

Made a bug report and a PR to fix this bug in php-webdriver

https://github.com/php-webdriver/php-webdriver/issues/849

How do I setup the InternetExplorerDriver so it works

Basically you need to download the IEDriverServer.exe from Selenium HQ website without executing anything just remmeber the location where you want it and then put the code on Eclipse like this

System.setProperty("webdriver.ie.driver", "C:\\Users\\juan.torres\\Desktop\\QA stuff\\IEDriverServer_Win32_2.32.3\\IEDriverServer.exe");
WebDriver driver= new InternetExplorerDriver();

driver.navigate().to("http://www.youtube.com/");

for the path use double slash //

ok have fun !!

Difference between webdriver.get() and webdriver.navigate()

Otherwise you prob want the get method:

Load a new web page in the current browser window. This is done using an
HTTP GET operation, and the method will block until the load is complete.

Navigate allows you to work with browser history as far as i understand it.

CSS selector (id contains part of text)

Try this:

a[id*='Some:Same'][id$='name']

This will get you all a elements with id containing

Some:Same

and have the id ending in

name

Equivalent of waitForVisible/waitForElementPresent in Selenium WebDriver tests using Java?

Another way to wait for maximum of certain amount say 10 seconds of time for the element to be displayed as below:

(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver d) {
                return d.findElement(By.id("<name>")).isDisplayed();

            }
        });

Setting Remote Webdriver to run tests in a remote computer using Java

By Default the InternetExplorerDriver listens on port "5555". Change your huburl to match that. you can look on the cmd box window to confirm.

setting request headers in selenium

Had the same issue today, except that I needed to set different referer per test. I ended up using a middleware and a class to pass headers to it. Thought I'd share (or maybe there's a cleaner solution?):

lib/request_headers.rb:

class CustomHeadersHelper
  cattr_accessor :headers
end

class RequestHeaders
  def initialize(app, helper = nil)
    @app, @helper = app, helper
  end

  def call(env)
    if @helper
      headers = @helper.headers

      if headers.is_a?(Hash)
        headers.each do |k,v|
          env["HTTP_#{k.upcase.gsub("-", "_")}"] = v
        end
      end
    end

    @app.call(env)
  end
end

config/initializers/middleware.rb

require 'request_headers'

if %w(test cucumber).include?(Rails.env)
  Rails.application.config.middleware.insert_before Rack::Lock, "RequestHeaders", CustomHeadersHelper
end

spec/support/capybara_headers.rb

require 'request_headers'

module CapybaraHeaderHelpers
  shared_context "navigating within the site" do
    before(:each) { add_headers("Referer" => Capybara.app_host + "/") }
  end

  def add_headers(custom_headers)
    if Capybara.current_driver == :rack_test
      custom_headers.each do |name, value|
        page.driver.browser.header(name, value)
      end
    else
      CustomHeadersHelper.headers = custom_headers
    end
  end
end

spec/spec_helper.rb

...
config.include CapybaraHeaderHelpers

Then I can include the shared context wherever I need, or pass different headers in another before block. I haven't tested it with anything other than Selenium and RackTest, but it should be transparent, as header injection is done before the request actually hits the application.

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

Very often this error appears if you use incompatible versions of Selenium and ChromeDriver.

Selenium 3.0.1 for Maven project:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.0.1</version>
    </dependency>

ChromeDriver 2.27: https://sites.google.com/a/chromium.org/chromedriver/downloads

How to switch to new window in Selenium for Python?

We can handle the different windows by moving between named windows using the “switchTo” method:

driver.switch_to.window("windowName")

<a href="somewhere.html" target="windowName">Click here to open a new window</a>

Alternatively, you can pass a “window handle” to the “switchTo().window()” method. Knowing this, it’s possible to iterate over every open window like so:

for handle in driver.window_handles:
    driver.switch_to.window(handle)

How to run Selenium WebDriver test cases in Chrome

Download the EXE file of chromedriver and extract it in the current project location.

Here is the link, where we can download the latest version of chromedriver:

https://sites.google.com/a/chromium.org/chromedriver/

Here is the simple code for the launch browser and navigate to a URL.

System.setProperty("webdriver.chrome.driver", "path of chromedriver.exe");

WebDriver driver = new ChromeDriver();

driver.get("https://any_url.com");

Checking if element exists with Python Selenium

None of the solutions provided seemed at all easiest to me, so I'd like to add my own way.

Basically, you get the list of the elements instead of just the element and then count the results; if it's zero, then it doesn't exist. Example:

if driver.find_elements_by_css_selector('#element'):
    print "Element exists"

Notice the "s" in find_elements_by_css_selector to make sure it can be countable.

EDIT: I was checking the len( of the list, but I recently learned that an empty list is falsey, so you don't need to get the length of the list at all, leaving for even simpler code.

Also, another answer says that using xpath is more reliable, which is just not true. See What is the difference between css-selector & Xpath? which is better(according to performance & for cross browser testing)?

How to get selected option using Selenium WebDriver with Java

var option = driver.FindElement(By.Id("employmentType"));
        var selectElement = new SelectElement(option);
        Task.Delay(3000).Wait();
        selectElement.SelectByIndex(2);
        Console.Read();

How can I ask the Selenium-WebDriver to wait for few seconds in Java?

Answer : wait for few seconds before element visibility using Selenium WebDriver go through below methods.

implicitlyWait() : WebDriver instance wait until full page load. You muse use 30 to 60 seconds to wait full page load.

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

ExplicitlyWait WebDriverWait() : WebDriver instance wait until full page load.

WebDriverWait wait = new WebDriverWait(driver, 60);

wait.until(ExpectedConditions.visibilityOf(textbox));

driver.findElement(By.id("Year")).sendKeys(allKeys);

Note : Please use ExplicitlyWait WebDriverWait() to handle any particular WebElement.

Open web in new tab Selenium + Python

browser.execute_script('''window.open("http://bings.com","_blank");''')

Where browser is the webDriver

How to verify a Text present in the loaded page through WebDriver

Note: Not in boolean

WebDriver driver=new FirefoxDriver();
driver.get("http://www.gmail.com");

if(driver.getPageSource().contains("Ur message"))
  {
    System.out.println("Pass");
  }
else
  {
    System.out.println("Fail");
  }

How to select an item from a dropdown list using Selenium WebDriver with java?

To find a particular dropdown box element:

Select gender = new Select(driver.findElement(By.id("gender")));

To get the list of all the elements contained in the dropdown box:

for(int j=1;j<3;j++)
    System.out.println(gender.getOptions().get(j).getText());

To select it through visible text displayed when you click on it:

gender.selectByVisibleText("Male");

To select it by index (starting at 0):

gender.selectByIndex(1);

how to use List<WebElement> webdriver

Try the following code:

//...
By mySelector = By.xpath("/html/body/div[1]/div/section/div/div[2]/form[1]/div/ul/li");
List<WebElement> myElements = driver.findElements(mySelector);
for(WebElement e : myElements) {
  System.out.println(e.getText());
}

It will returns with the whole content of the <li> tags, like:

<a class="extra">Vše</a> (950)</li>

But you can easily get the number now from it, for example by using split() and/or substring().

How do I set proxy for chrome in python webdriver?

from selenium import webdriver
from selenium.webdriver.common.proxy import *

myProxy = "86.111.144.194:3128"
proxy = Proxy({
    'proxyType': ProxyType.MANUAL,
    'httpProxy': myProxy,
    'ftpProxy': myProxy,
    'sslProxy': myProxy,
    'noProxy':''})

driver = webdriver.Firefox(proxy=proxy)
driver.set_page_load_timeout(30)
driver.get('http://whatismyip.com')

Selenium WebDriver findElement(By.xpath()) not working for me

Just need to add * at the beginning of xpath and closing bracket at last.

element = findElement(By.xpath("//*[@test-id='test-username']"));

Can Selenium interact with an existing browser session?

All the solutions so far were lacking of certain functionality. Here is my solution:

public class AttachedWebDriver extends RemoteWebDriver {

    public AttachedWebDriver(URL url, String sessionId) {
        super();
        setSessionId(sessionId);
        setCommandExecutor(new HttpCommandExecutor(url) {
            @Override
            public Response execute(Command command) throws IOException {
                if (command.getName() != "newSession") {
                    return super.execute(command);
                }
                return super.execute(new Command(getSessionId(), "getCapabilities"));
            }
        });
        startSession(new DesiredCapabilities());
    }
}

WebDriver: check if an element exists?

You could alternatively do:

driver.findElements( By.id("...") ).size() != 0

Which saves the nasty try/catch

p.s.

Or more precisely by @JanHrcek here

!driver.findElements(By.id("...")).isEmpty()

Cannot find firefox binary in PATH. Make sure firefox is installed. OS appears to be: VISTA

File pathBinary = new File("Firefox.exe location");
FirefoxBinary ffBinary = new FirefoxBinary(pathBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
FirefoxDriver driver = new FirefoxDriver(ffBinary,firefoxProfile);

You need to add binary of the browser

or

Best and forever solution: Just add Firefox.exe location to environmental variables

Random "Element is no longer attached to the DOM" StaleElementReferenceException

I was facing the same problem today and made up a wrapper class, which checks before every method if the element reference is still valid. My solution to retrive the element is pretty simple so i thought i'd just share it.

private void setElementLocator()
{
    this.locatorVariable = "selenium_" + DateTimeMethods.GetTime().ToString();
    ((IJavaScriptExecutor)this.driver).ExecuteScript(locatorVariable + " = arguments[0];", this.element);
}

private void RetrieveElement()
{
    this.element = (IWebElement)((IJavaScriptExecutor)this.driver).ExecuteScript("return " + locatorVariable);
}

You see i "locate" or rather save the element in a global js variable and retrieve the element if needed. If the page gets reloaded this reference will not work anymore. But as long as only changes are made to doom the reference stays. And that should do the job in most cases.

Also it avoids re-searching the element.

John

Display a RecyclerView in Fragment

Make sure that you have the correct layout, and that the RecyclerView id is inside the layout. Otherwise, you will be getting this error. I had the same problem, then I noticed the layout was wrong.

    public class ColorsFragment extends Fragment {

         public ColorsFragment() {}

         @Override
         public View onCreateView(LayoutInflater inflater, ViewGroup container,
             Bundle savedInstanceState) {

==> make sure you are getting the correct layout here. R.layout...

             View rootView = inflater.inflate(R.layout.fragment_colors, container, false); 

Render HTML to PDF in Django site

https://github.com/nigma/django-easy-pdf

Template:

{% extends "easy_pdf/base.html" %}

{% block content %}
    <div id="content">
        <h1>Hi there!</h1>
    </div>
{% endblock %}

View:

from easy_pdf.views import PDFTemplateView

class HelloPDFView(PDFTemplateView):
    template_name = "hello.html"

If you want to use django-easy-pdf on Python 3 check the solution suggested here.

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

How do I get a value of datetime.today() in Python that is "timezone aware"?

pytz is a Python library that allows accurate and cross platform timezone calculations using Python 2.3 or higher.

With the stdlib, this is not possible.

See a similar question on SO.

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/

"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:

Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."

Pass element ID to Javascript function

The problem for me was as simple as just not knowing Javascript well. I was trying to pass the name of the id using double quotes, when I should have been using single. And it worked fine.

This worked:

validateSelectizeDropdown('#PartCondition')

This did not:

validateSelectizeDropdown("#PartCondition")

And the function:

    function validateSelectizeDropdown(name) {
    if ($(name).val() === "") {
         //do something
    }
}

How to select option in drop down using Capybara

If you take a look at the source of the select method, you can see that what it does when you pass a from key is essentially:

find(:select, from, options).find(:option, value, options).select_option

In other words, it finds the <select> you're interested in, then finds the <option> within that, then calls select_option on the <option> node.

You've already pretty much done the first two things, I'd just rearrange them. Then you can tack the select_option method on the end:

find('#organizationSelect').find(:xpath, 'option[2]').select_option

Can I force a UITableView to hide the separator between empty cells?

For Swift:

override func viewDidLoad() {
    super.viewDidLoad()
    tableView.tableFooterView = UIView()  // it's just 1 line, awesome!
}

When and why do I need to use cin.ignore() in C++?

Ignore is exactly what the name implies.

It doesn't "throw away" something you don't need instead, it ignores the amount of characters you specify when you call it, up to the char you specify as a breakpoint.

It works with both input and output buffers.

Essentially, for std::cin statements you use ignore before you do a getline call, because when a user inputs something with std::cin, they hit enter and a '\n' char gets into the cin buffer. Then if you use getline, it gets the newline char instead of the string you want. So you do a std::cin.ignore(1000,'\n') and that should clear the buffer up to the string that you want. (The 1000 is put there to skip over a specific amount of chars before the specified break point, in this case, the \n newline character.)

Is it safe to delete a NULL pointer?

Yes it is safe.

There's no harm in deleting a null pointer; it often reduces the number of tests at the tail of a function if the unallocated pointers are initialized to zero and then simply deleted.


Since the previous sentence has caused confusion, an example — which isn't exception safe — of what is being described:

void somefunc(void)
{
    SomeType *pst = 0;
    AnotherType *pat = 0;

    …
    pst = new SomeType;
    …
    if (…)
    {
        pat = new AnotherType[10];
        …
    }
    if (…)
    {
        …code using pat sometimes…
    }

    delete[] pat;
    delete pst;
}

There are all sorts of nits that can be picked with the sample code, but the concept is (I hope) clear. The pointer variables are initialized to zero so that the delete operations at the end of the function do not need to test whether they're non-null in the source code; the library code performs that check anyway.

What is the best way to declare global variable in Vue.js?

For any Single File Component users, here is how I set up global variable(s)

  1. Assuming you are using Vue-Cli's webpack template
  2. Declare your variable(s) in somewhere variable.js

    const shallWeUseVuex = false;
    
  3. Export it in variable.js

    module.exports = { shallWeUseVuex : shallWeUseVuex };
    
  4. Require and assign it in your vue file

    export default {
        data() {
            return {
                shallWeUseVuex: require('../../variable.js')
            };
        }
    }
    

Ref: https://vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch

Pandas dataframe fillna() only some columns in place

You can using dict , fillna with different value for different column

df.fillna({'a':0,'b':0})
Out[829]: 
     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

After assign it back

df=df.fillna({'a':0,'b':0})
df
Out[831]: 
     a    b    c
0  1.0  4.0  NaN
1  2.0  5.0  NaN
2  3.0  0.0  7.0
3  0.0  6.0  8.0

Android Closing Activity Programmatically

you can use finishAffinity(); to close all the activity..

How can I find the last element in a List<>?

Why not just use the Count property on the List?

for(int cnt3 = 0; cnt3 < integerList.Count; cnt3++)

How to find out which JavaScript events fired?

You can use getEventListeners in your Google Chrome developer console.

getEventListeners(object) returns the event listeners registered on the specified object.

getEventListeners(document.querySelector('option[value=Closed]'));

NUnit vs. MbUnit vs. MSTest vs. xUnit.net

I wouldn't go with MSTest. Although it's probably the most future proof of the frameworks with Microsoft behind it's not the most flexible solution. It won't run stand alone without some hacks. So running it on a build server other than TFS without installing Visual Studio is hard. The visual studio test-runner is actually slower than Testdriven.Net + any of the other frameworks. And because the releases of this framework are tied to releases of Visual Studio there are less updates and if you have to work with an older VS you're tied to an older MSTest.

I don't think it matters a lot which of the other frameworks you use. It's really easy to switch from one to another.

I personally use XUnit.Net or NUnit depending on the preference of my coworkers. NUnit is the most standard. XUnit.Net is the leanest framework.

round() doesn't seem to be rounding properly

Formatting works correctly even without having to round:

"%.1f" % n

fopen deprecated warning

If you want it to be used on many platforms, you could as commented use defines like:

#if defined(_MSC_VER) || defined(WIN32)  || defined(_WIN32) || defined(__WIN32__) \
                        || defined(WIN64)    || defined(_WIN64) || defined(__WIN64__) 

        errno_t err = fopen_s(&stream,name, "w");

#endif

#if defined(unix)        || defined(__unix)      || defined(__unix__) \
                        || defined(linux)       || defined(__linux)     || defined(__linux__) \
                        || defined(sun)         || defined(__sun) \
                        || defined(BSD)         || defined(__OpenBSD__) || defined(__NetBSD__) \
                        || defined(__FreeBSD__) || defined __DragonFly__ \
                        || defined(sgi)         || defined(__sgi) \
                        || defined(__MACOSX__)  || defined(__APPLE__) \
                        || defined(__CYGWIN__) 

        stream = fopen(name, "w");

#endif

Angular no provider for NameService

The error No provider for NameService is a common issue that many Angular2 beginners face.

Reason: Before using any custom service you first have to register it with NgModule by adding it to the providers list:

Solution:

@NgModule({
    imports: [...],
    providers: [CustomServiceName]
})

Are 64 bit programs bigger and faster than 32 bit versions?

I'm coding a chess engine named foolsmate. The best move extraction using a minimax-based tree search to depth 9 (from a certain position) took:

on Win32 configuration: ~17.0s;

after switching to x64 configuration: ~10.3s;

This is 41% of acceleration!

Check if a class `active` exist on element with jquery

If Condition to check, currently class active or not

$('#next').click(function(){
    if($('p:last').hasClass('active'){
       $('.active').removeClass();
    }else{
       $('.active').addClass();
    }
});

SQL: how to select a single id ("row") that meets multiple criteria from a single column

SELECT DISTINCT (user_id) 
FROM [user]
WHERE user.user_id In (select user_id from user where ancestry = 'England') 
    And user.user_id In (select user_id from user where ancestry = 'France') 
    And user.user_id In (select user_id from user where ancestry = 'Germany');`

Which browser has the best support for HTML 5 currently?

To test your browser, go to http://html5test.com/. The code is being maintained at: github dot com slash NielsLeenheer slash html5test.

Make a simple fade in animation in Swift?

Swift only solution

Similar to Luca's anwer, I use a UIView extension. Compared to his solution I use DispatchQueue.main.async to make sure animations are done on the main thread, alpha parameter for fading to a specific value and optional duration parameters for cleaner code.

extension UIView {
  func fadeTo(_ alpha: CGFloat, duration: TimeInterval = 0.3) {
    DispatchQueue.main.async {
      UIView.animate(withDuration: duration) {
        self.alpha = alpha
      }
    }
  }

  func fadeIn(_ duration: TimeInterval = 0.3) {
    fadeTo(1.0, duration: duration)
  }

  func fadeOut(_ duration: TimeInterval = 0.3) {
    fadeTo(0.0, duration: duration)
  }
}

How to use it:

// fadeIn() - always animates to alpha = 1.0
yourView.fadeIn()     // uses default duration of 0.3
yourView.fadeIn(1.0)  // uses custom duration (1.0 in this example)

// fadeOut() - always animates to alpha = 0.0
yourView.fadeOut()    // uses default duration of 0.3
yourView.fadeOut(1.0) // uses custom duration (1.0 in this example)

// fadeTo() - used if you want a custom alpha value
yourView.fadeTo(0.5)  // uses default duration of 0.3
yourView.fadeTo(0.5, duration: 1.0)

C# Linq Where Date Between 2 Dates

If you have date interval filter condition and you need to select all records which falls partly into this filter range. Assumption: records has ValidFrom and ValidTo property.

DateTime intervalDateFrom = new DateTime(1990, 01, 01);
DateTime intervalDateTo = new DateTime(2000, 01, 01);

var itemsFiltered = allItems.Where(x=> 
    (x.ValidFrom >= intervalDateFrom && x.ValidFrom <= intervalDateTo) ||
    (x.ValidTo >= intervalDateFrom && x.ValidTo <= intervalDateTo) ||
    (intervalDateFrom >= x.ValidFrom && intervalDateFrom <= x.ValidTo) ||
    (intervalDateTo >= x.ValidFrom && intervalDateTo <= x.ValidTo)
);

How to install Guest addition in Mac OS as guest and Windows machine as host

You can use SSH and SFTP as suggested here.

  1. In the Guest OS (Mac OS X), open System Preferences > Sharing, then activate Remote Login; note the ip address specified in the Remote Login instructions, e.g. ssh [email protected]
  2. In VirtualBox, open Devices > Network > Network Settings > Advanced > Port Forwarding and specify Host IP = 127.0.0.1, Host Port 2222, Guest IP 10.0.2.15, Guest Port 22
  3. On the Host OS, run the following command sftp -P 2222 [email protected]; if you prefer a graphical interface, you can use FileZilla

Replace user and 10.0.2.15 with the appropriate values relevant to your configuration.

How do I get the path of the current executed file in Python?

The short answer is that there is no guaranteed way to get the information you want, however there are heuristics that work almost always in practice. You might look at How do I find the location of the executable in C?. It discusses the problem from a C point of view, but the proposed solutions are easily transcribed into Python.

submit form on click event using jquery

Why not simply use the submit button to run the code you want. If your function returns false, it will cancel the submission.

$("#testForm").submit(function() {
    /* Do Something */
    return false;
});

Best way to style a TextBox in CSS

You Also wanna put some text (placeholder) in the empty input box for the

_x000D_
_x000D_
.myClass {_x000D_
   ::-webkit-input-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
   ::-moz-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
  /* firefox 19+ */_x000D_
   :-ms-input-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
  /* ie */_x000D_
  input:-moz-placeholder {_x000D_
    color: #f00;_x000D_
  }_x000D_
}
_x000D_
<input type="text" class="myClass" id="fname" placeholder="Enter First Name Here!">
_x000D_
_x000D_
_x000D_

user to understand what to type.

How to symbolicate crash log Xcode?

From Apple's docs:

Symbolicating Crash Reports With Xcode Xcode will automatically attempt to symbolicate all crash reports that it encounters. All you need to do for symbolication is to add the crash report to the Xcode Organizer.

  • Connect an iOS device to your Mac
  • Choose "Devices" from the "Window" menu
  • Under the "DEVICES" section in the left column, choose a device
  • Click the "View Device Logs" button under the "Device Information" section on the right hand panel
  • Drag your crash report onto the left column of the presented panel
  • Xcode will automatically symbolicate the crash report and display the results To symbolicate a crash report, Xcode needs to be able to locate the following:

    1. The crashing application's binary and dSYM file.

    2. The binaries and dSYM files for all custom frameworks that the application links against. For frameworks that were built from source with the application, their dSYM files are copied into the archive alongside the application's dSYM file. For frameworks that were built by a third-party, you will need to ask the author for the dSYM file.

    3. Symbols for the OS that the that application was running on when it crashed. These symbols contain debug information for the frameworks included in a specific OS release (e.g, iOS 9.3.3). OS symbols are architecture specific - a release of iOS for 64-bit devices won't include armv7 symbols. Xcode will automatically copy OS symbols from each device that you connect to your Mac.

If any of these are missing Xcode may not be able to symbolicate the crash report, or may only partially symbolicate the crash report.

"Missing return statement" within if / for / while

That's because the function needs to return a value. Imagine what happens if you execute myMethod() and it doesn't go into if(condition) what would your function returns? The compiler needs to know what to return in every possible execution of your function

Checking Java documentation:

Definition: If a method declaration has a return type then there must be a return statement at the end of the method. If the return statement is not there the missing return statement error is thrown.

This error is also thrown if the method does not have a return type and has not been declared using void (i.e., it was mistakenly omitted).

You can do to solve your problem:

public String myMethod()
{
    String result = null;
    if(condition)
    {
       result = x;
    }
    return result;
}

MVC 4 Edit modal form using Bootstrap

You should use partial views. I use the following approach:

Use a view model so you're not passing your domain models to your views:

public class EditPersonViewModel
{
    public int Id { get; set; }   // this is only used to retrieve record from Db
    public string Name { get; set; }
    public string Age { get; set; }
}

In your PersonController:

[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{  
    var viewModel = new EditPersonViewModel();
    viewModel.Id = id;
    return PartialView("_EditPersonPartial", viewModel);
}

[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
    if (ModelState.IsValid)
    {
        var toUpdate = personRepo.Find(viewModel.Id);
        toUpdate.Name = viewModel.Name;
        toUpdate.Age = viewModel.Age;
        personRepo.InsertOrUpdate(toUpdate);
        personRepo.Save();
        return View("Index");
    }
}

Next create a partial view called _EditPersonPartial. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.

@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
                    new AjaxOptions
                    {
                        InsertionMode = InsertionMode.Replace,
                        HttpMethod = "POST",
                        UpdateTargetId = "list-of-people"
                    }))
{
    @Html.ValidationSummary()
    @Html.AntiForgeryToken()
    <div class="modal-body">
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
        @Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
    </div>
    <div class="modal-footer">
        <button class="btn btn-inverse" type="submit">Save</button>
    </div>
}

Now somewhere in your application, say another partial _peoplePartial.cshtml etc:

<div>
   @foreach(var person in Model.People)
    {
        <button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
    }
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
    <div id="edit-person-container"></div>
</div>

    <script type="text/javascript">
    $(document).ready(function () {
        $('.edit-person').click(function () {
            var url = "/Person/EditPerson"; // the url to the controller
            var id = $(this).attr('data-id'); // the id that's given to each button in the list
            $.get(url + '/' + id, function (data) {
                $('#edit-person-container').html(data);
                $('#edit-person').modal('show');
            });
        });
     });
   </script>

Multiple github accounts on the same computer?

You do not have to maintain two different accounts for personal and work. In fact, Github Recommends you maintain a single account and helps you merge both.

Follow the below link to merge if you decide there is no need to maintain multiple accounts.

https://help.github.com/articles/merging-multiple-user-accounts/

Spring Boot application can't resolve the org.springframework.boot package

It's not necessary to remove relative path. Just change the version parent of springframework boot. The following version 2.1.2 works successfully.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.2.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.appsdeveloperblog.app.ws</groupId>
    <artifactId>mobile-app-ws</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>mobile-app-ws</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.appsdeveloperblog.app.ws</groupId>
            <artifactId>mobile-app-ws</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

Customize Bootstrap checkboxes

_x000D_
_x000D_
/* The customcheck */_x000D_
.customcheck {_x000D_
    display: block;_x000D_
    position: relative;_x000D_
    padding-left: 35px;_x000D_
    margin-bottom: 12px;_x000D_
    cursor: pointer;_x000D_
    font-size: 22px;_x000D_
    -webkit-user-select: none;_x000D_
    -moz-user-select: none;_x000D_
    -ms-user-select: none;_x000D_
    user-select: none;_x000D_
}_x000D_
_x000D_
/* Hide the browser's default checkbox */_x000D_
.customcheck input {_x000D_
    position: absolute;_x000D_
    opacity: 0;_x000D_
    cursor: pointer;_x000D_
}_x000D_
_x000D_
/* Create a custom checkbox */_x000D_
.checkmark {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    height: 25px;_x000D_
    width: 25px;_x000D_
    background-color: #eee;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* On mouse-over, add a grey background color */_x000D_
.customcheck:hover input ~ .checkmark {_x000D_
    background-color: #ccc;_x000D_
}_x000D_
_x000D_
/* When the checkbox is checked, add a blue background */_x000D_
.customcheck input:checked ~ .checkmark {_x000D_
    background-color: #02cf32;_x000D_
    border-radius: 5px;_x000D_
}_x000D_
_x000D_
/* Create the checkmark/indicator (hidden when not checked) */_x000D_
.checkmark:after {_x000D_
    content: "";_x000D_
    position: absolute;_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
/* Show the checkmark when checked */_x000D_
.customcheck input:checked ~ .checkmark:after {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
/* Style the checkmark/indicator */_x000D_
.customcheck .checkmark:after {_x000D_
    left: 9px;_x000D_
    top: 5px;_x000D_
    width: 5px;_x000D_
    height: 10px;_x000D_
    border: solid white;_x000D_
    border-width: 0 3px 3px 0;_x000D_
    -webkit-transform: rotate(45deg);_x000D_
    -ms-transform: rotate(45deg);_x000D_
    transform: rotate(45deg);_x000D_
}
_x000D_
<div class="container">_x000D_
 <h1>Custom Checkboxes</h1></br>_x000D_
 _x000D_
        <label class="customcheck">One_x000D_
          <input type="checkbox" checked="checked">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Two_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Three_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
        <label class="customcheck">Four_x000D_
          <input type="checkbox">_x000D_
          <span class="checkmark"></span>_x000D_
        </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

php: loop through json array

Use json_decode to convert the JSON string to a PHP array, then use normal PHP array functions on it.

$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$data = json_decode($json);

var_dump($data[0]['var1']); // outputs '9'

Android: disabling highlight on listView click

in code

listView.setSelector(getResources().getDrawable(R.drawable.transparent));

and add small transparent image to drawable folder.

Like: transparent.xml

<?xml version="1.0" encoding="utf-8"?>    
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#00000000"/>
</shape>

sql insert into table with select case values

If FName and LName contain NULL values, then you will need special handling to avoid unnecessary extra preceeding, trailing, and middle spaces. Also, if Address1 contains NULL values, then you need to have special handling to prevent adding unnecessary ', ' at the beginning of your address string.

If you are using SQL Server 2012, then you can use CONCAT (NULLs are automatically treated as empty strings) and IIF:

INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(CONCAT(FName, ' ', Middle, ' ', LName))), '  ', ' ')
    , Address = CONCAT(Address1, IIF(Address2 IS NOT NULL, CONCAT(', ', Address2), ''))
    , City
    , Zip
FROM tblImport (NOLOCK);

Otherwise, this will work:

INSERT INTO TblStuff (FullName, Address, City, Zip)
SELECT FullName = REPLACE(RTRIM(LTRIM(ISNULL(FName, '') + ' ' + ISNULL(Middle, '') + ' ' + ISNULL(LName, ''))), '  ', ' ')
    , Address = ISNULL(Address1, '') + CASE
        WHEN Address2 IS NOT NULL THEN ', ' + Address2
        ELSE '' END
    , City
    , Zip
FROM tblImport (NOLOCK);

How does true/false work in PHP?

Since I've visited this page several times, I've decided to post an example (loose) comparison test.

Results:

""        -> false
"0"       -> false
"1"       -> true
"01"      -> true
"abc"     -> true
"true"    -> true
"false"   -> true
0         -> false
0.1       -> true
1         -> true
1.1       -> true
-42       -> true
"NAN"     -> true
0         -> false
          -> true
null      -> false
true      -> true
false     -> false
[]        -> false
["a"]     -> true
{}        -> true
{}        -> true
{"s":"f"} -> true

Code:

class Vegetable {}

class Fruit {
    public $s = "f";
}

$cases = [
    "",
    "0",
    "1",
    "01",
    "abc",
    "true",
    "false",
    0,
    0.1,
    1,
    1.1,
    -42,
    "NAN",
    (float) "NAN",
    NAN,
    null,
    true,
    false,
    [],
    ["a"],
    new stdClass(),
    new Vegetable(),
    new Fruit(),
];

echo "<pre>" . PHP_EOL;

foreach ($cases as $case) {
    printf("%s -> %s" . PHP_EOL, str_pad(json_encode($case), 9, " ", STR_PAD_RIGHT), json_encode( $case == true ));
}

When a strict (===) comparison is done, everything except true returns false.

Dynamic function name in javascript?

You can use Dynamic Function Name and parameters like this.

1) Define function Separate and call it

let functionName = "testFunction";
let param = {"param1":1 , "param2":2};

var func = new Function(
   "return " + functionName 
)();

func(param);

function testFunction(params){
   alert(params.param1);
}

2) Define function code dynamic

let functionName = "testFunction(params)";
let param = {"param1":"1" , "param2":"2"};
let functionBody = "{ alert(params.param1)}";

var func = new Function(
    "return function " + functionName + functionBody 
)();

func(param);

Iterate over a Javascript associative array in sorted order

_x000D_
_x000D_
var a = new Array();_x000D_
a['b'] = 1;_x000D_
a['z'] = 1;_x000D_
a['a'] = 1;_x000D_
_x000D_
_x000D_
var keys=Object.keys(a).sort();_x000D_
for(var i=0,key=keys[0];i<keys.length;key=keys[++i]){_x000D_
  document.write(key+' : '+a[key]+'<br>');_x000D_
}
_x000D_
_x000D_
_x000D_

Why do I need an IoC container as opposed to straightforward DI code?

you do not need a framework to achieve dependency injection. You can do this by core java concepts as well. http://en.wikipedia.org/wiki/Dependency_injection#Code_illustration_using_Java

Efficiently updating database using SQLAlchemy ORM

SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session.

So if you say

for c in session.query(Stuff).all():
    c.foo = c.foo+1
session.commit()

it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one.

Instead you should do this:

session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1}))
session.commit()

This will execute as one query as you would expect, and because at least the default session configuration expires all data in the session on commit you don't have any stale data issues.

In the almost-released 0.5 series you could also use this method for updating:

session.query(Stuff).update({Stuff.foo: Stuff.foo + 1})
session.commit()

That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add synchronize_session=False to the update statement and get rid of that select.

python selenium click on button

Remove space between classes in css selector:

driver.find_element_by_css_selector('.button .c_button .s_button').click()
#                                           ^         ^

=>

driver.find_element_by_css_selector('.button.c_button.s_button').click()

Make 2 functions run at the same time

Do this:

from threading import Thread

def func1():
    print('Working')

def func2():
    print("Working")

if __name__ == '__main__':
    Thread(target = func1).start()
    Thread(target = func2).start()

Download image with JavaScript

As @Ian explained, the problem is that jQuery's click() is not the same as the native one.

Therefore, consider using vanilla-js instead of jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

Demo

How do I configure Apache 2 to run Perl CGI scripts?

There are two ways to handle CGI scripts, SetHandler and AddHandler.

SetHandler cgi-script

applies to all files in a given context, no matter how they are named, even index.html or style.css.

AddHandler cgi-script .pl

is similar, but applies to files ending in .pl, in a given context. You may choose another extension or several, if you like.

Additionally, the CGI module must be loaded and Options +ExecCGI configured. To activate the module, issue

a2enmod cgi

and restart or reload Apache. Finally, the Perl CGI script must be executable. So the execute bits must be set

chmod a+x script.pl

and it should start with

#! /usr/bin/perl

as its first line.


When you use SetHandler or AddHandler (and Options +ExecCGI) outside of any directive, it is applied globally to all files. But you may restrict the context to a subset by enclosing these directives inside, e.g. Directory

<Directory /path/to/some/cgi-dir>
    SetHandler cgi-script
    Options +ExecCGI
</Directory>

Now SetHandler applies only to the files inside /path/to/some/cgi-dir instead of all files of the web site. Same is with AddHandler inside a Directory or Location directive, of course. It then applies to the files inside /path/to/some/cgi-dir, ending in .pl.

How to import multiple csv files in a single load?

val df = spark.read.option("header", "true").csv("C:spark\\sample_data\\*.csv)

will consider files tmp, tmp1, tmp2, ....

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

What is the proper way to comment functions in Python?

Use a docstring:

A string literal that occurs as the first statement in a module, function, class, or method definition. Such a docstring becomes the __doc__ special attribute of that object.

All modules should normally have docstrings, and all functions and classes exported by a module should also have docstrings. Public methods (including the __init__ constructor) should also have docstrings. A package may be documented in the module docstring of the __init__.py file in the package directory.

String literals occurring elsewhere in Python code may also act as documentation. They are not recognized by the Python bytecode compiler and are not accessible as runtime object attributes (i.e. not assigned to __doc__ ), but two types of extra docstrings may be extracted by software tools:

  1. String literals occurring immediately after a simple assignment at the top level of a module, class, or __init__ method are called "attribute docstrings".
  2. String literals occurring immediately after another docstring are called "additional docstrings".

Please see PEP 258 , "Docutils Design Specification" [2] , for a detailed description of attribute and additional docstrings...

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

When you generate a JAXB model from an XML Schema, global elements that correspond to named complex types will have that metadata captured as an @XmlElementDecl annotation on a create method in the ObjectFactory class. Since you are creating the JAXBContext on just the DocumentType class this metadata isn't being processed. If you generated your JAXB model from an XML Schema then you should create the JAXBContext on the generated package name or ObjectFactory class to ensure all the necessary metadata is processed.

Example solution:

JAXBContext jaxbContext = JAXBContext.newInstance(my.generatedschema.dir.ObjectFactory.class);
DocumentType documentType = ((JAXBElement<DocumentType>) jaxbContext.createUnmarshaller().unmarshal(inputStream)).getValue();

WebDriver - wait for element using Java

Above wait statement is a nice example of Explicit wait.

As Explicit waits are intelligent waits that are confined to a particular web element(as mentioned in above x-path).

By Using explicit waits you are basically telling WebDriver at the max it is to wait for X units(whatever you have given as timeoutInSeconds) of time before it gives up.

How to parse unix timestamp to time.Time

The time.Parse function does not do Unix timestamps. Instead you can use strconv.ParseInt to parse the string to int64 and create the timestamp with time.Unix:

package main

import (
    "fmt"
    "time"
    "strconv"
)

func main() {
    i, err := strconv.ParseInt("1405544146", 10, 64)
    if err != nil {
        panic(err)
    }
    tm := time.Unix(i, 0)
    fmt.Println(tm)
}

Output:

2014-07-16 20:55:46 +0000 UTC

Playground: http://play.golang.org/p/v_j6UIro7a

Edit:

Changed from strconv.Atoi to strconv.ParseInt to avoid int overflows on 32 bit systems.

How to margin the body of the page (html)?

I would say: (simple zero will work, 0px is a zero ;))

<body style="margin: 0;">

but maybe something overwrites your css. (assigns different style after you ;))

If you use Firefox - check out firebug plugin.

And in Chrome - just right-click on the page and chose "inspect element" in the menu. Find BODY in elements tree and check its properties.

Facebook Android Generate Key Hash

One line solution to generate for facebook

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

How to disassemble a memory range with GDB?

This isn't the direct answer to your question, but since you seem to just want to disassemble the binary, perhaps you could just use objdump:

objdump -d program

This should give you its dissassembly. You can add -S if you want it source-annotated.

Best way to store date/time in mongodb

The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.

> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }

The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.

If you need to, you can easily convert Date objects to and from Unix timestamps1), using the getTime() method and Date(milliseconds) constructor, respectively.

1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.

Presenting a UIAlertController properly on an iPad using iOS 8

On iPad the alert will be displayed as a popover using the new UIPopoverPresentationController, it requires that you specify an anchor point for the presentation of the popover using either a sourceView and sourceRect or a barButtonItem

  • barButtonItem
  • sourceView
  • sourceRect

In order to specify the anchor point you will need to obtain a reference to the UIAlertController's UIPopoverPresentationController and set one of the properties as follows:

alertController.popoverPresentationController.barButtonItem = button;

sample code:

UIAlertAction *actionDelete = nil;
UIAlertAction *actionCancel = nil;

// create action sheet
UIAlertController *alertController = [UIAlertController
                                      alertControllerWithTitle:actionTitle message:nil
                                      preferredStyle:UIAlertControllerStyleActionSheet];

// Delete Button
actionDelete = [UIAlertAction
                actionWithTitle:NSLocalizedString(@"IDS_LABEL_DELETE", nil)
                style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {

                    // Delete
                    // [self deleteFileAtCurrentIndexPath];
                }];

// Cancel Button
actionCancel = [UIAlertAction
                actionWithTitle:NSLocalizedString(@"IDS_LABEL_CANCEL", nil)
                style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                    // cancel
                    // Cancel code
                }];

// Add Cancel action
[alertController addAction:actionCancel];
[alertController addAction:actionDelete];

// show action sheet
alertController.popoverPresentationController.barButtonItem = button;
alertController.popoverPresentationController.sourceView = self.view;

[self presentViewController:alertController animated:YES
                 completion:nil];

How to set the JSTL variable value in javascript?

<script ...
  function(){
   var someJsVar = "<c:out value='${someJstLVarFromBackend}'/>";

  }
</script>

This works even if you dont have a hidden/non-hidden input field set somewhere in the jsp.

Localhost : 404 not found

open D:\xampp\apache\conf\extra\httpd-vhosts.conf

ServerName localhost DocumentRoot "D:\xampp\htdocs" SetEnv APPLICATION_ENV "development"
DirectoryIndex index.php AllowOverride FileInfo Require all granted

Restart Apache server

and then refresh your given url

How do I use disk caching in Picasso?

Add followning code in Application.onCreate then use it normal

    Picasso picasso = new Picasso.Builder(context)
            .downloader(new OkHttp3Downloader(this,Integer.MAX_VALUE))
            .build();
    picasso.setIndicatorsEnabled(true);
    picasso.setLoggingEnabled(true);
    Picasso.setSingletonInstance(picasso);

If you cache images first then do something like this in ProductImageDownloader.doBackground

final Callback callback = new Callback() {
            @Override
            public void onSuccess() {
                downLatch.countDown();
                updateProgress();
            }

            @Override
            public void onError() {
                errorCount++;
                downLatch.countDown();
                updateProgress();
            }
        };
        Picasso.with(context).load(Constants.imagesUrl+productModel.getGalleryImage())
                .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);
        Picasso.with(context).load(Constants.imagesUrl+productModel.getLeftImage())
                .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);
        Picasso.with(context).load(Constants.imagesUrl+productModel.getRightImage())
                .memoryPolicy(MemoryPolicy.NO_CACHE).fetch(callback);

        try {
            downLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if(errorCount == 0){
            products.remove(productModel);
            productModel.isDownloaded = true;
            productsDatasource.updateElseInsert(productModel);
        }else {
            //error occurred while downloading images for this product
            //ignore error for now
            // FIXME: 9/27/2017 handle error
            products.remove(productModel);

        }
        errorCount = 0;
        downLatch = new CountDownLatch(3);

        if(!products.isEmpty() /*&& testCount++ < 30*/){
            startDownloading(products.get(0));
        }else {
            //all products with images are downloaded
            publishProgress(100);
        }

and load your images like normal or with disk caching

    Picasso.with(this).load(Constants.imagesUrl+batterProduct.getGalleryImage())
        .networkPolicy(NetworkPolicy.OFFLINE)
        .placeholder(R.drawable.GalleryDefaultImage)
        .error(R.drawable.GalleryDefaultImage)
        .into(viewGallery);

Note:

Red color indicates that image is fetched from network.

Green color indicates that image is fetched from cache memory.

Blue color indicates that image is fetched from disk memory.

Before releasing the app delete or set it false picasso.setLoggingEnabled(true);, picasso.setIndicatorsEnabled(true); if not required. Thankx

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

CMD what does /im (taskkill)?

it allows you to kill a task based on the image name like taskkill /im iexplore.exe or taskkill /im notepad.exe

Enable PHP Apache2

You can use a2enmod or a2dismod to enable/disable modules by name.

From terminal, run: sudo a2enmod php5 to enable PHP5 (or some other module), then sudo service apache2 reload to reload the Apache2 configuration.

error: ORA-65096: invalid common user or role name in oracle

99.9% of the time the error ORA-65096: invalid common user or role name means you are logged into the CDB when you should be logged into a PDB.

But if you insist on creating users the wrong way, follow the steps below.

DANGER

Setting undocumented parameters like this (as indicated by the leading underscore) should only be done under the direction of Oracle Support. Changing such parameters without such guidance may invalidate your support contract. So do this at your own risk.

Specifically, if you set "_ORACLE_SCRIPT"=true, some data dictionary changes will be made with the column ORACLE_MAINTAINED set to 'Y'. Those users and objects will be incorrectly excluded from some DBA scripts. And they may be incorrectly included in some system scripts.

If you are OK with the above risks, and don't want to create common users the correct way, use the below answer.


Before creating the user run:

alter session set "_ORACLE_SCRIPT"=true;  

I found the answer here

Android Studio Gradle Already disposed Module

I figured out this problem by:

  1. ./gradlew clean
  2. Restart Android Studio

What do 'lazy' and 'greedy' mean in the context of regular expressions?

Taken From www.regular-expressions.info

Greediness: Greedy quantifiers first tries to repeat the token as many times as possible, and gradually gives up matches as the engine backtracks to find an overall match.

Laziness: Lazy quantifier first repeats the token as few times as required, and gradually expands the match as the engine backtracks through the regex to find an overall match.

Enterprise app deployment doesn't work on iOS 7.1

I had the same problem and although I was already using an SSL server, simply changing the links to https wasn't working as there was an underlying problem.

enter image description here Click here for image

That highlighted bit told me that we should be given the option to trust the certificate, but since this is the app store, working through Safari that recovery suggestion just isn't presented.


I wasn't happy with the existing solutions because:

  • Some options require dependance on a third party (Dropbox)
  • We weren't willing to pay for an SSL certificate
    • Free SSL certificates are only a temporary solution.

I finally found a solution by creating a Self Signed Root Certificate Authority and generating our server's SSL certificate using this.

I used Keychain Access and OSX Server, but there are other valid solutions to each step


Creating a Certificate Authority

From what I gather, certificate authorities are used to verify that certificates are genuine. Since we're about to create one ourselves, it's not exactly secure, but it means that you can trust all certificates from a given authority. A list of these authorities is usually included by default in your browsers as these are actually trusted. (GeoTrust Global CA, Verisign etc)

  • Open Keychain and use the certificate assistant to create an authority

enter image description here

  • Fill in your Certificate Authority Information

enter image description here

  • I don't know if it's necessary, but I made the authority trusted.

enter image description here


Generating a Certificate Signing Request

In our case, certificate signing requests are generated by the server admin. Simply it's a file that asks "Can I have a certificate with this information for my site please".

  • Next you'll have to create your Certificate Signing Request (I used OSX Server's Certificates manager for this bit

enter image description here

  • Fill in your certificate information (Must contain only ascii chars!, thanks @Jasper Blues)

enter image description here

  • Save the generate CSR somewhere

enter image description here


Creating the Certificate

Acting as the certificate authority again, it's up to you to decide if the person who sent you the CSR is genuine and they're not pretending to be somebody else. Real authorities have their own ways of doing this, but since you are hopefully quite sure that you are you, your verification should be quite certain :)

  • Go back to Keychain Access and open the "Create A Certificate.." option as shown

enter image description here

  • Drag in your saved CSR to the box indicated

enter image description here

  • Click the "Let me override defaults for this request button"

enter image description here

  • I like to increase the validity period.

enter image description here

  • For some reason, we have to fill in some information again

enter image description here

  • Click continue on this screen

enter image description here

  • MAKE SURE YOU CLICK SSL SERVER AUTHENTICATION, this one caused me some headaches.

enter image description here

  • You can click continue through the rest of the options.

  • The Mail app will open giving you the chance to send the certificate. Instead of emailing, right click it and save it.

enter image description here


Installing the Certificate

We now need to set up the server to use the certificate we just created for it's SSL traffic.

  • If the device your working on is your server, you might find the certificate is already installed.

enter image description here

  • If not though, double click the Pending certificate and drag the PEM file that we just saved from the email into the space indicated. (Alternatively, you can export your PEM from keychain if you didn't save it.)

enter image description here

  • Update your server to use this new certificate. If you find that the new certificate won't "stick" and keeps reverting, go back to the bit in BOLD ITALIC CAPS

enter image description here


Setting Up Devices

Each device you need to install apps on will need to have a copy of this certificate authority so that they know they can trust SSL certificates from that authority

  • Go back to Keychain Access and export your certificate authority as a .cer

enter image description here

  • I then put this file on my server with my OTA apps, users can click this link and download the authority certificate. Emailing the certificate directly to users is also a valid option.

enter image description here

  • Install the certificate on your device.

enter image description here


Test

  • Make sure your plist links are https

    • Try and install an app! It should now work. The certificate authority is trusted and the SSL certificate came from that authority.

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

How to test if a double is zero?

The safest way would be bitwise OR ing your double with 0. Look at this XORing two doubles in Java

Basically you should do if ((Double.doubleToRawLongBits(foo.x) | 0 ) ) (if it is really 0)

Laravel 5 PDOException Could Not Find Driver

You should install PDO on your server. Edit your php.ini (look at your phpinfo(), "Loaded Configuration File" line, to find the php.ini file path). Find and uncomment the following line (remove the ; character):

;extension=pdo_mysql.so

Then, restart your Apache server. For more information, please read the documentation.

The term 'Get-ADUser' is not recognized as the name of a cmdlet

Open Turn On/Off Windows Features.

Make sure you have Active Directory Domain Services selected. If not, install it. enter image description here

What is the difference between "long", "long long", "long int", and "long long int" in C++?

This looks confusing because you are taking long as a datatype itself.

long is nothing but just the shorthand for long int when you are using it alone.

long is a modifier, you can use it with double also as long double.

long == long int.

Both of them take 4 bytes.

Using getResources() in non-activity class

In simple class declare context and get data from file from res folder

public class FileData
{
      private Context context;

        public FileData(Context current){
            this.context = current;
        }
        void  getData()
        {
        InputStream in = context.getResources().openRawResource(R.raw.file11);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        //write stuff to get Data

        }
}

In the activity class declare like this

public class MainActivity extends AppCompatActivity 
{
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        FileData fileData=new FileData(this);
     }

}

How to convert HTML file to word?

When doing this I found it easiest to:

  1. Visit the page in a web browser
  2. Save the page using the web browser with .htm extension (and maybe a folder with support files)
  3. Start Word and open the saved htmfile (Word will open it correctly)
  4. Make any edits if needed
  5. Select Save As and then choose the extension you would like doc, docx, etc.

Javascript call() & apply() vs bind()?

Use .bind() when you want that function to later be called with a certain context, useful in events. Use .call() or .apply() when you want to invoke the function immediately, and modify the context.

Call/apply call the function immediately, whereas bind returns a function that, when later executed, will have the correct context set for calling the original function. This way you can maintain context in async callbacks and events.

I do this a lot:

function MyObject(element) {
    this.elm = element;

    element.addEventListener('click', this.onClick.bind(this), false);
};

MyObject.prototype.onClick = function(e) {
     var t=this;  //do something with [t]...
    //without bind the context of this function wouldn't be a MyObject
    //instance as you would normally expect.
};

I use it extensively in Node.js for async callbacks that I want to pass a member method for, but still want the context to be the instance that started the async action.

A simple, naive implementation of bind would be like:

Function.prototype.bind = function(ctx) {
    var fn = this;
    return function() {
        fn.apply(ctx, arguments);
    };
};

There is more to it (like passing other args), but you can read more about it and see the real implementation on the MDN.

Hope this helps.

UnicodeDecodeError: 'ascii' codec can't decode byte 0xef in position 1

i solve that problem changing in the file settings.py with 'ENGINE': 'django.db.backends.mysql', don´t use 'ENGINE': 'mysql.connector.django',

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

It could be because of the property pageable -> pageSizes: true.

Remove this and check again.

This could be due to the service endpoint binding not using the HTTP protocol

I've had this same error and the problem was serialization. I managed to find the real problem using Service Trace Viewer http://msdn.microsoft.com/en-us/library/ms732023.aspx and solved it easy. Maybe this will help someone.

What does the 'export' command do?

export in sh and related shells (such as bash), marks an environment variable to be exported to child-processes, so that the child inherits them.

export is defined in POSIX:

The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.

Catching exceptions from Guzzle

I want to update the answer for exception handling in Psr-7 Guzzle, Guzzle7 and HTTPClient(expressive, minimal API around the Guzzle HTTP client provided by laravel).

Guzzle7 (same works for Guzzle 6 as well)

Using RequestException, RequestException catches any exception that can be thrown while transferring requests.

try{
  $client = new \GuzzleHttp\Client(['headers' => ['Authorization' => 'Bearer ' . $token]]);
  
  $guzzleResponse = $client->get('/foobar');
  // or can use
  // $guzzleResponse = $client->request('GET', '/foobar')
    if ($guzzleResponse->getStatusCode() == 200) {
         $response = json_decode($guzzleResponse->getBody(),true);
         //perform your action with $response 
    } 
}
catch(\GuzzleHttp\Exception\RequestException $e){
   // you can catch here 400 response errors and 500 response errors
   // You can either use logs here use Illuminate\Support\Facades\Log;
   $error['error'] = $e->getMessage();
   $error['request'] = $e->getRequest();
   if($e->hasResponse()){
       if ($e->getResponse()->getStatusCode() == '400'){
           $error['response'] = $e->getResponse(); 
       }
   }
   Log::error('Error occurred in get request.', ['error' => $error]);
}catch(Exception $e){
   //other errors 
}

Psr7 Guzzle

use GuzzleHttp\Psr7;
use GuzzleHttp\Exception\RequestException;

try {
    $client->request('GET', '/foo');
} catch (RequestException $e) {
    $error['error'] = $e->getMessage();
    $error['request'] = Psr7\Message::toString($e->getRequest());
    if ($e->hasResponse()) {
        $error['response'] = Psr7\Message::toString($e->getResponse());
    }
    Log::error('Error occurred in get request.', ['error' => $error]);
}

For HTTPClient

use Illuminate\Support\Facades\Http;
try{
    $response = Http::get('http://api.foo.com');
    if($response->successful()){
        $reply = $response->json();
    }
    if($response->failed()){
        if($response->clientError()){
            //catch all 400 exceptions
            Log::debug('client Error occurred in get request.');
            $response->throw();
        }
        if($response->serverError()){
            //catch all 500 exceptions
            Log::debug('server Error occurred in get request.');
            $response->throw();
        }
        
    }
 }catch(Exception $e){
     //catch the exception here
 }

Run a vbscript from another vbscript

As Martin's Answer didn't work at all for me ("File not found") and atesio's Answer does not allow to call two scripts which include repeating variable definitions, here is another alternative which finally worked for me:

filepath =  Chr(34) & "C:\...\helloworld.vbs" & Chr(34)
Set objshell= CreateObject("WScript.Shell") 
objshell.Run "wscript " & filepath, , True
Set objshell= Nothing

(Windows 8.1)

How to redirect a page using onclick event in php?

You can't use php code client-side. You need to use javascript.

<input type="button" value="Home" class="homebutton" id="btnHome" 
onClick="document.location.href='some/page'" />

However, you really shouldn't be using inline js (like onclick here). Study about this here: https://www.google.com/search?q=Why+is+inline+js+bad%3F

Here's a clean way of doing this: Live demo (click).

Markup:

<button id="myBtn">Redirect</button>

JavaScript:

var btn = document.getElementById('myBtn');
btn.addEventListener('click', function() {
  document.location.href = 'some/page';
});

If you need to write in the location with php:

  <button id="myBtn">Redirect</button>
  <script>
    var btn = document.getElementById('myBtn');
    btn.addEventListener('click', function() {
      document.location.href = '<?php echo $page; ?>';
    });
  </script>

Unable to start MySQL server

In my case, I went for

MySQL install Uninstall only the MySQL Server Install again

Make sure the Path is the same for example (if your installer warns you of a conflict): C:\Program Files...etc... C:\Program Files...etc...

If they are the same, it should work fine.

Why does SSL handshake give 'Could not generate DH keypair' exception?

This is a quite old post, but if you use Apache HTTPD, you can limit the DH size. See http://httpd.apache.org/docs/current/ssl/ssl_faq.html#javadh

Convert JSONArray to String Array

You can input json array to this function get output as string array

example Input - { "gender" : ["male", "female"] }

output - {"male", "female"}

private String[] convertToStringArray(Object array) throws Exception {
   return StringUtils.stripAll(array.toString().substring(1, array.toString().length()-1).split(","));
}

Changing navigation title programmatically

Swift 3

I created an outlet for the navigation title bar item that comes with the navigation bar (from the Object Browser) in the storyboard. Then I sued the line below:

navigationBarTitleItem.title = "Hello Bar"

how to remove the dotted line around the clicked a element in html

Removing outline will harm accessibility of a website.Therefore i just leave that there but make it invisible.

a {
   outline: transparent;
}

What are the sizes used for the iOS application splash screen?

With iOS 7+, static Launch Images are now deprecated.

You should create a custom view that composes slices of images, which sizes to all screens like a normal UIViewController view.

https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/LaunchImages.html

Is there a way to automatically build the package.json file for Node.js projects

use command npm init -f to generate package.json file and after that use --save after each command so that each module will automatically get updated inside your package.json for ex: npm install express --save

Reading PDF documents in .Net

public string ReadPdfFile(object Filename, DataTable ReadLibray)
{
    PdfReader reader2 = new PdfReader((string)Filename);
    string strText = string.Empty;

    for (int page = 1; page <= reader2.NumberOfPages; page++)
    {
    ITextExtractionStrategy its = new iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy();
    PdfReader reader = new PdfReader((string)Filename);
    String s = PdfTextExtractor.GetTextFromPage(reader, page, its);

    s = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(s)));
    strText = strText + s;
    reader.Close();
    }
    return strText;
}

How do I compile C++ with Clang?

The command clang is for C, and the command clang++ is for C++.

How to remove tab indent from several lines in IDLE?

If you're using IDLE, you can use Ctrl+] to indent and Ctrl+[ to unindent.

What should I use to open a url instead of urlopen in urllib3

With gazpacho you could pipeline the page straight into a parse-able soup object:

from gazpacho import Soup
url = "http://www.thefamouspeople.com/singers.php"
soup = Soup.get(url)

And run finds on top of it:

soup.find("div")

Using jQuery's ajax method to retrieve images as a blob

A big thank you to @Musa and here is a neat function that converts the data to a base64 string. This may come handy to you when handling a binary file (pdf, png, jpeg, docx, ...) file in a WebView that gets the binary file but you need to transfer the file's data safely into your app.

// runs a get/post on url with post variables, where:
// url ... your url
// post ... {'key1':'value1', 'key2':'value2', ...}
//          set to null if you need a GET instead of POST req
// done ... function(t) called when request returns
function getFile(url, post, done)
{
   var postEnc, method;
   if (post == null)
   {
      postEnc = '';
      method = 'GET';
   }
   else
   {
      method = 'POST';
      postEnc = new FormData();
      for(var i in post)
         postEnc.append(i, post[i]);
   }
   var xhr = new XMLHttpRequest();
   xhr.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200)
      {
         var res = this.response;
         var reader = new window.FileReader();
         reader.readAsDataURL(res); 
         reader.onloadend = function() { done(reader.result.split('base64,')[1]); }
      }
   }
   xhr.open(method, url);
   xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
   xhr.send('fname=Henry&lname=Ford');
   xhr.responseType = 'blob';
   xhr.send(postEnc);
}

Unix shell script find out which directory the script file resides?

INTRODUCTION

This answer corrects the very broken but shockingly top voted answer of this thread (written by TheMarko):

#!/usr/bin/env bash

BASEDIR=$(dirname "$0")
echo "$BASEDIR"

WHY DOES USING dirname "$0" ON IT'S OWN NOT WORK?

dirname $0 will only work if user launches script in a very specific way. I was able to find several situations where this answer fails and crashes the script.

First of all, let's understand how this answer works. He's getting the script directory by doing

dirname "$0"

$0 represents the first part of the command calling the script (it's basically the inputted command without the arguments:

/some/path/./script argument1 argument2

$0="/some/path/./script"

dirname basically finds the last / in a string and truncates it there. So if you do:

  dirname /usr/bin/sha256sum

you'll get: /usr/bin

This example works well because /usr/bin/sha256sum is a properly formatted path but

  dirname "/some/path/./script"

wouldn't work well and would give you:

  BASENAME="/some/path/." #which would crash your script if you try to use it as a path

Say you're in the same dir as your script and you launch it with this command

./script   

$0 in this situation will be ./script and dirname $0 will give:

. #or BASEDIR=".", again this will crash your script

Using:

sh script

Without inputting the full path will also give a BASEDIR="."

Using relative directories:

 ../some/path/./script

Gives a dirname $0 of:

 ../some/path/.

If you're in the /some directory and you call the script in this manner (note the absence of / in the beginning, again a relative path):

 path/./script.sh

You'll get this value for dirname $0:

 path/. 

and ./path/./script (another form of the relative path) gives:

 ./path/.

The only two situations where basedir $0 will work is if the user use sh or touch to launch a script because both will result in $0:

 $0=/some/path/script

which will give you a path you can use with dirname.

THE SOLUTION

You'd have account for and detect every one of the above mentioned situations and apply a fix for it if it arises:

#!/bin/bash
#this script will only work in bash, make sure it's installed on your system.

#set to false to not see all the echos
debug=true

if [ "$debug" = true ]; then echo "\$0=$0";fi


#The line below detect script's parent directory. $0 is the part of the launch command that doesn't contain the arguments
BASEDIR=$(dirname "$0") #3 situations will cause dirname $0 to fail: #situation1: user launches script while in script dir ( $0=./script)
                                                                     #situation2: different dir but ./ is used to launch script (ex. $0=/path_to/./script)
                                                                     #situation3: different dir but relative path used to launch script
if [ "$debug" = true ]; then echo 'BASEDIR=$(dirname "$0") gives: '"$BASEDIR";fi                                 

if [ "$BASEDIR" = "." ]; then BASEDIR="$(pwd)";fi # fix for situation1

_B2=${BASEDIR:$((${#BASEDIR}-2))}; B_=${BASEDIR::1}; B_2=${BASEDIR::2}; B_3=${BASEDIR::3} # <- bash only
if [ "$_B2" = "/." ]; then BASEDIR=${BASEDIR::$((${#BASEDIR}-1))};fi #fix for situation2 # <- bash only
if [ "$B_" != "/" ]; then  #fix for situation3 #<- bash only
        if [ "$B_2" = "./" ]; then
                #covers ./relative_path/(./)script
                if [ "$(pwd)" != "/" ]; then BASEDIR="$(pwd)/${BASEDIR:2}"; else BASEDIR="/${BASEDIR:2}";fi
        else
                #covers relative_path/(./)script and ../relative_path/(./)script, using ../relative_path fails if current path is a symbolic link
                if [ "$(pwd)" != "/" ]; then BASEDIR="$(pwd)/$BASEDIR"; else BASEDIR="/$BASEDIR";fi
        fi
fi

if [ "$debug" = true ]; then echo "fixed BASEDIR=$BASEDIR";fi

scp from remote host to local host

There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.

And then you can copy for example the file "test.txt" from a remote host to the local host

scp [email protected]:test.txt /local/dir


@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.

In UNIX, absolute paths must start with '/'.

How to pass the -D System properties while testing on Eclipse?

This will work for junit. for TestNG use following command

-ea -Dmykey="value" -Dmykey2="value2"

Insert the same fixed value into multiple rows

You're looking for UPDATE not insert.

UPDATE mytable
SET    table_column = 'test';

UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).

Excel VBA - select multiple columns not in sequential order

Some of the code looks a bit complex to me. This is very simple code to select only the used rows in two discontiguous columns D and H. It presumes the columns are of unequal length and thus more flexible vs if the columns were of equal length.

As you most likely surmised 4=column D and 8=column H

Dim dlastRow As Long
Dim hlastRow As Long

dlastRow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
hlastRow = ActiveSheet.Cells(Rows.Count, 8).End(xlUp).Row
Range("D2:D" & dlastRow & ",H2:H" & hlastRow).Select

Hope you find useful - DON'T FORGET THAT COMMA BEFORE THE SECOND COLUMN, AS I DID, OR IT WILL BOMB!!

Recursively list all files in a directory including files in symlink directories

find -L /var/www/ -type l

# man find
-L     Follow  symbolic links.  When find examines or prints information about files, the information used shall be taken from the

properties of the file to which the link points, not from the link itself (unless it is a broken symbolic link or find is unable to examine the file to which the link points). Use of this option implies -noleaf. If you later use the -P option, -noleaf will still be in effect. If -L is in effect and find discovers a symbolic link to a subdirectory during its search, the subdirectory pointed to by the symbolic link will be searched.

How can I avoid Java code in JSP files, using JSP 2?

  1. Make your values and parameters inside your servlet classes
  2. Fetch those values and parameters within your JSP using JSTL/Taglib

The good thing about this approach is that your code is also HTML like code!

Android: Tabs at the BOTTOM

This may not be exactly what you're looking for (it's not an "easy" solution to send your Tabs to the bottom of the screen) but is nevertheless an interesting alternative solution I would like to flag to you :

ScrollableTabHost is designed to behave like TabHost, but with an additional scrollview to fit more items ...

maybe digging into this open-source project you'll find an answer to your question. If I see anything easier I'll come back to you.

Does C have a "foreach" loop construct?

Here is a full program example of a for-each macro in C99:

#include <stdio.h>

typedef struct list_node list_node;
struct list_node {
    list_node *next;
    void *data;
};

#define FOR_EACH(item, list) \
    for (list_node *(item) = (list); (item); (item) = (item)->next)

int
main(int argc, char *argv[])
{
    list_node list[] = {
        { .next = &list[1], .data = "test 1" },
        { .next = &list[2], .data = "test 2" },
        { .next = NULL,     .data = "test 3" }
    };

    FOR_EACH(item, list)
        puts((char *) item->data);

    return 0;
}

How can I check if given int exists in array?

You almost never have to write your own loops in C++. Here, you can use std::find.

const int toFind = 42;
int* found = std::find (myArray, std::end (myArray), toFind);
if (found != std::end (myArray))
{
  std::cout << "Found.\n"
}
else
{
  std::cout << "Not found.\n";
}

std::end requires C++11. Without it, you can find the number of elements in the array with:

const size_t numElements = sizeof (myArray) / sizeof (myArray[0]);

...and the end with:

int* end = myArray + numElements;

Java: How to check if object is null?

Use google guava libs to handle is-null-check (deamon's update)

Drawable drawable = Optional.of(Common.getDrawableFromUrl(this, product.getMapPath())).or(getRandomDrawable());

SQL JOIN - WHERE clause vs. ON clause

For an inner join, WHERE and ON can be used interchangeably. In fact, it's possible to use ON in a correlated subquery. For example:

update mytable
set myscore=100
where exists (
select 1 from table1
inner join table2
on (table2.key = mytable.key)
inner join table3
on (table3.key = table2.key and table3.key = table1.key)
...
)

This is (IMHO) utterly confusing to a human, and it's very easy to forget to link table1 to anything (because the "driver" table doesn't have an "on" clause), but it's legal.

Safely override C++ virtual functions

Something like C#'s override keyword is not part of C++.

In gcc, -Woverloaded-virtual warns against hiding a base class virtual function with a function of the same name but a sufficiently different signature that it doesn't override it. It won't, though, protect you against failing to override a function due to mis-spelling the function name itself.

Linux command-line call not returning what it should from os.system?

Your code returns 0 if the execution of the commands passed is successful and non zero if it fails. The following program works on python2.7, haven checked 3 and versions above. Try this code.

>>> import commands
>>> ret = commands.getoutput("ps -p 2993 -o time --no-headers")
>>> print ret

How to get xdebug var_dump to show full object/array

I know this is a super old post, but I figured this may still be helpful.

If you're comfortable with reading json format you could replace your var_dump with:

return json_encode($myvar);

I've been using this to help troubleshoot a service I've been building that has some deeply nested arrays. This will return every level of your array without truncating anything or requiring you to change your php.ini file.

Also, because the json_encoded data is a string it means you can write it to the error log easily

error_log(json_encode($myvar));

It probably isn't the best choice for every situation, but it's a choice!

I forgot the password I entered during postgres installation

  1. find the file pg_hba.conf - it may be located, for example in /etc/postgresql-9.1/pg_hba.conf.

    cd /etc/postgresql-9.1/

  2. Back it up

    cp pg_hba.conf pg_hba.conf-backup

  3. place the following line (as either the first uncommented line, or as the only one):

For all occurrence of below (local and host) , exepct replication section if you don't have any it has to be changed as follow ,no MD5 or Peer autehication should be present.

local  all   all   trust
  1. restart your PostgreSQL server (e.g., on Linux:)

    sudo /etc/init.d/postgresql restart

    If the service (daemon) doesn't start reporting in log file:

    local connections are not supported by this build

    you should change

    local all all trust

    to

    host all all 127.0.0.1/32 trust

  2. you can now connect as any user. Connect as the superuser postgres (note, the superuser name may be different in your installation. In some systems it is called pgsql, for example.)

    psql -U postgres

    or

    psql -h 127.0.0.1 -U postgres

    (note that with the first command you will not always be connected with local host)

  3. Reset password ('replace my_user_name with postgres since you are resetting postgres user)

    ALTER USER my_user_name with password 'my_secure_password';

  4. Restore the old pg_hba.conf as it is very dangerous to keep around

    cp pg_hba.conf-backup pg_hba.conf

  5. restart the server, in order to run with the safe pg_hba.conf

    sudo /etc/init.d/postgresql restart

Further Reading about that pg_hba file: http://www.postgresql.org/docs/9.1/static/auth-pg-hba-conf.html

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

How to manually trigger click event in ReactJS?

How about just plain old js ? example:

autoClick = () => {
 if (something === something) {
    var link = document.getElementById('dashboard-link');
    link.click();
  }
};
  ......      
var clickIt = this.autoClick();            
return (
  <div>
     <Link id="dashboard-link" to={'/dashboard'}>Dashboard</Link>
  </div>
);

How to check if an alert exists using WebDriver?

I would suggest to use ExpectedConditions and alertIsPresent(). ExpectedConditions is a wrapper class that implements useful conditions defined in ExpectedCondition interface.

WebDriverWait wait = new WebDriverWait(driver, 300 /*timeout in seconds*/);
if(wait.until(ExpectedConditions.alertIsPresent())==null)
    System.out.println("alert was not present");
else
    System.out.println("alert was present");

Replacing objects in array

Thanks to ES6 we can made it with easy way -> for example on util.js module ;))).

  1. Merge 2 array of entity

    export const mergeArrays = (arr1, arr2) => 
       arr1 && arr1.map(obj => arr2 && arr2.find(p => p.id === obj.id) || obj);
    

gets 2 array and merges it.. Arr1 is main array which is priority is high on merge process

  1. Merge array with same type of entity

    export const mergeArrayWithObject = (arr, obj) => arr && arr.map(t => t.id === obj.id ? obj : t);
    

it merges the same kind of array of type with some kind of type for

example: array of person ->

[{id:1, name:"Bir"},{id:2, name: "Iki"},{id:3, name:"Uc"}]   
second param Person {id:3, name: "Name changed"}   

result is

[{id:1, name:"Bir"},{id:2, name: "Iki"},{id:3, name:"Name changed"}]

A JNI error has occurred, please check your installation and try again in Eclipse x86 Windows 8.1

The programs which has been written on one version of jdk won't support the JNI platform of another version of jdk. If in case we are using jdk10 and jdk8,eclipse configured for jdk10 and code written on jdk10. Now, i don't want to use jdk10 and started using jdk8 as jvm and tried to run the code which is written on jdk10, so eclipse will through error of JNI. So, to come out of this error, please add the current JVM path to eclipse.ini file, after this copy the written code to clipboard and delete the project in eclipse and create new project and check in copied code and run.

Where does MySQL store database files on Windows and what are the names of the files?

I have a default my-default.ini file in the root and there is one server configuration:

[mysqld]
sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES 

So that does not tell me the path.

The best way is to connect to the database and run this query:

SHOW VARIABLES WHERE Variable_Name LIKE "%dir" ;

Here's the result of that:

basedir                     C:\Program Files (x86)\MySQL\MySQL Server 5.6\
character_sets_dir          C:\Program Files (x86)\MySQL\MySQL Server 5.6\share\charsets\

datadir                     C:\ProgramData\MySQL\MySQL Server 5.6\Data\
innodb_data_home_dir    
innodb_log_group_home_dir   .\
lc_messages_dir             C:\Program Files (x86)\MySQL\MySQL Server 5.6\share\

plugin_dir                  C:\Program Files (x86)\MySQL\MySQL Server 5.6\lib\plugin\

slave_load_tmpdir           C:\Windows\SERVIC~2\NETWOR~1\AppData\Local\Temp
tmpdir                      C:\Windows\SERVIC~2\NETWOR~1\AppData\Local\Temp

If you want to see all the parameters configured for the database execute this:

SHOW VARIABLES;

The storage_engine variable will tell you if you're using InnoDb or MyISAM.

In Firebase, is there a way to get the number of children of a node without loading all the node data?

This is a little late in the game as several others have already answered nicely, but I'll share how I might implement it.

This hinges on the fact that the Firebase REST API offers a shallow=true parameter.

Assume you have a post object and each one can have a number of comments:

{
 "posts": {
  "$postKey": {
   "comments": {
     ...  
   }
  }
 }
}

You obviously don't want to fetch all of the comments, just the number of comments.

Assuming you have the key for a post, you can send a GET request to https://yourapp.firebaseio.com/posts/[the post key]/comments?shallow=true.

This will return an object of key-value pairs, where each key is the key of a comment and its value is true:

{
 "comment1key": true,
 "comment2key": true,
 ...,
 "comment9999key": true
}

The size of this response is much smaller than requesting the equivalent data, and now you can calculate the number of keys in the response to find your value (e.g. commentCount = Object.keys(result).length).

This may not completely solve your problem, as you are still calculating the number of keys returned, and you can't necessarily subscribe to the value as it changes, but it does greatly reduce the size of the returned data without requiring any changes to your schema.

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

With me was the same problem, but it was caused, because i was using the mysql server on 32 (bit) and the workbench was running on 64(bit) version. the server and the workbench need to has the same version.

xpress

How to Save Console.WriteLine Output to Text File

For the question:

How to save Console.Writeline Outputs to text file?

I would use Console.SetOut as others have mentioned.


However, it looks more like you are keeping track of your program flow. I would consider using Debug or Trace for keeping track of the program state.

It works similar the console except you have more control over your input such as WriteLineIf.

Debug will only operate when in debug mode where as Trace will operate in both debug or release mode.

They both allow for listeners such as output files or the console.

TextWriterTraceListener tr1 = new TextWriterTraceListener(System.Console.Out);
Debug.Listeners.Add(tr1);

TextWriterTraceListener tr2 = new TextWriterTraceListener(System.IO.File.CreateText("Output.txt"));
Debug.Listeners.Add(tr2);

-http://support.microsoft.com/kb/815788

How to get input field value using PHP

Example of using PHP to get a value from a form:

Put this in foobar.php:

<html>
<body>
  <form action="foobar_submit.php" method="post">
    <input name="my_html_input_tag"  value="PILLS HERE"/>

    <input type="submit" name="my_form_submit_button" 
           value="Click here for penguins"/>

    </form>
</body>
</html>

Read the above code so you understand what it is doing:

"foobar.php is an HTML document containing an HTML form. When the user presses the submit button inside the form, the form's action property is run: foobar_submit.php. The form will be submitted as a POST request. Inside the form is an input tag with the name "my_html_input_tag". It's default value is "PILLS HERE". That causes a text box to appear with text: 'PILLS HERE' on the browser. To the right is a submit button, when you click it, the browser url changes to foobar_submit.php and the below code is run.

Put this code in foobar_submit.php in the same directory as foobar.php:

<?php
  echo $_POST['my_html_input_tag'];
  echo "<br><br>";
  print_r($_POST); 
?>

Read the above code so you know what its doing:

The HTML form from above populated the $_POST superglobal with key/value pairs representing the html elements inside the form. The echo prints out the value by key: 'my_html_input_tag'. If the key is found, which it is, its value is returned: "PILLS HERE".

Then print_r prints out all the keys and values from $_POST so you can peek as to what else is in there.

The value of the input tag with name=my_html_input_tag was put into the $_POST and you retrieved it inside another PHP file.

Filtering JSON array using jQuery grep()

_x000D_
_x000D_
var data = {_x000D_
  "items": [{_x000D_
    "id": 1,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 2,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 3,_x000D_
    "category": "cat1"_x000D_
  }, {_x000D_
    "id": 4,_x000D_
    "category": "cat2"_x000D_
  }, {_x000D_
    "id": 5,_x000D_
    "category": "cat1"_x000D_
  }]_x000D_
};_x000D_
//Filters an array of numbers to include only numbers bigger then zero._x000D_
//Exact Data you want..._x000D_
var returnedData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1" && element.id === 3;_x000D_
}, false);_x000D_
console.log(returnedData);_x000D_
$('#id').text('Id is:-' + returnedData[0].id)_x000D_
$('#category').text('Category is:-' + returnedData[0].category)_x000D_
//Filter an array of numbers to include numbers that are not bigger than zero._x000D_
//Exact Data you don't want..._x000D_
var returnedOppositeData = $.grep(data.items, function(element) {_x000D_
  return element.category === "cat1";_x000D_
}, true);_x000D_
console.log(returnedOppositeData);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<p id='id'></p>_x000D_
<p id='category'></p>
_x000D_
_x000D_
_x000D_

The $.grep() method eliminates items from an array as necessary so that only remaining items carry a given search. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

How can I dynamically add items to a Java array?

You can use an ArrayList and then use the toArray() method. But depending on what you are doing, you might not even need an array at all. Look into seeing if Lists are more what you want.

See: Java List Tutorial

How can I use JavaScript in Java?

I just wanted to answer something new for this question - J2V8.

Author Ian Bull says "Rhino and Nashorn are two common JavaScript runtimes, but these did not meet our requirements in a number of areas:

Neither support ‘Primitives‘. All interactions with these platforms require wrapper classes such as Integer, Double or Boolean. Nashorn is not supported on Android. Rhino compiler optimizations are not supported on Android. Neither engines support remote debugging on Android.""

Highly Efficient Java & JavaScript Integration

Github link

Allow docker container to connect to a local/host postgres database

To set up something simple that allows a Postgresql connection from the docker container to my localhost I used this in postgresql.conf:

listen_addresses = '*'

And added this pg_hba.conf:

host    all             all             172.17.0.0/16           password

Then do a restart. My client from the docker container (which was at 172.17.0.2) could then connect to Postgresql running on my localhost using host:password, database, username and password.

Calculate text width with JavaScript

The code-snips below, "calculate" the width of the span-tag, appends "..." to it if its too long and reduces the text-length, until it fits in its parent (or until it has tried more than a thousand times)

CSS

div.places {
  width : 100px;
}
div.places span {
  white-space:nowrap;
  overflow:hidden;
}

HTML

<div class="places">
  <span>This is my house</span>
</div>
<div class="places">
  <span>And my house are your house</span>
</div>
<div class="places">
  <span>This placename is most certainly too wide to fit</span>
</div>

JavaScript (with jQuery)

// loops elements classed "places" and checks if their child "span" is too long to fit
$(".places").each(function (index, item) {
    var obj = $(item).find("span");
    if (obj.length) {
        var placename = $(obj).text();
        if ($(obj).width() > $(item).width() && placename.trim().length > 0) {
            var limit = 0;
            do {
                limit++;
                                    placename = placename.substring(0, placename.length - 1);
                                    $(obj).text(placename + "...");
            } while ($(obj).width() > $(item).width() && limit < 1000)
        }
    }
});

Object Dump JavaScript

for better readability you can convert the object to a json string as below:

console.log(obj, JSON.stringify(obj));

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

How to truncate float values?

Something simple enough to fit in a list-comprehension, with no libraries or other external dependencies. For Python >=3.6, it's very simple to write with f-strings.

The idea is to let the string-conversion do the rounding to one more place than you need and then chop off the last digit.

>>> nout = 3  # desired number of digits in output
>>> [f'{x:.{nout+1}f}'[:-1] for x in [2/3, 4/5, 8/9, 9/8, 5/4, 3/2]]
['0.666', '0.800', '0.888', '1.125', '1.250', '1.500']

Of course, there is rounding happening here (namely for the fourth digit), but rounding at some point is unvoidable. In case the transition between truncation and rounding is relevant, here's a slightly better example:

>>> nacc = 6  # desired accuracy (maximum 15!)
>>> nout = 3  # desired number of digits in output
>>> [f'{x:.{nacc}f}'[:-(nacc-nout)] for x in [2.9999, 2.99999, 2.999999, 2.9999999]]
>>> ['2.999', '2.999', '2.999', '3.000']

Bonus: removing zeros on the right

>>> nout = 3  # desired number of digits in output
>>> [f'{x:.{nout+1}f}'[:-1].rstrip('0') for x in [2/3, 4/5, 8/9, 9/8, 5/4, 3/2]]
['0.666', '0.8', '0.888', '1.125', '1.25', '1.5']

How does createOrReplaceTempView work in Spark?

createOrReplaceTempView creates (or replaces if that view name already exists) a lazily evaluated "view" that you can then use like a hive table in Spark SQL. It does not persist to memory unless you cache the dataset that underpins the view.

scala> val s = Seq(1,2,3).toDF("num")
s: org.apache.spark.sql.DataFrame = [num: int]

scala> s.createOrReplaceTempView("nums")

scala> spark.table("nums")
res22: org.apache.spark.sql.DataFrame = [num: int]

scala> spark.table("nums").cache
res23: org.apache.spark.sql.Dataset[org.apache.spark.sql.Row] = [num: int]

scala> spark.table("nums").count
res24: Long = 3

The data is cached fully only after the .count call. Here's proof it's been cached:

Cached nums temp view/table

Related SO: spark createOrReplaceTempView vs createGlobalTempView

Relevant quote (comparing to persistent table): "Unlike the createOrReplaceTempView command, saveAsTable will materialize the contents of the DataFrame and create a pointer to the data in the Hive metastore." from https://spark.apache.org/docs/latest/sql-programming-guide.html#saving-to-persistent-tables

Note : createOrReplaceTempView was formerly registerTempTable

Count distinct values

You can use this:

select count(customer) as count, pets
from table
group by pets

How to loop over files in directory and change path and add suffix to filename

A couple of notes first: when you use Data/data1.txt as an argument, should it really be /Data/data1.txt (with a leading slash)? Also, should the outer loop scan only for .txt files, or all files in /Data? Here's an answer, assuming /Data/data1.txt and .txt files only:

#!/bin/bash
for filename in /Data/*.txt; do
    for ((i=0; i<=3; i++)); do
        ./MyProgram.exe "$filename" "Logs/$(basename "$filename" .txt)_Log$i.txt"
    done
done

Notes:

  • /Data/*.txt expands to the paths of the text files in /Data (including the /Data/ part)
  • $( ... ) runs a shell command and inserts its output at that point in the command line
  • basename somepath .txt outputs the base part of somepath, with .txt removed from the end (e.g. /Data/file.txt -> file)

If you needed to run MyProgram with Data/file.txt instead of /Data/file.txt, use "${filename#/}" to remove the leading slash. On the other hand, if it's really Data not /Data you want to scan, just use for filename in Data/*.txt.

how to open Jupyter notebook in chrome on windows

You don't have to change anything in the jupyter config code, you just have to make Chrome as your default browser in the setting. Jupyter opens whichever is the default.

Scripting Language vs Programming Language

Back when the world was young and in the PC world you chose from .exe or .bat, the delineation was simple. Unix systems have always had shell scripts (/bin/sh, /bin/csh, /bin/ksh, etc) and Compiled languages (C/C++/Fortran).

To differentiate roles and responsibilities, the compiled languages (often referred to as 3rd Generation Languages) were seen a 'programming' languages and 'scripting' languages were seen as those that invoked an interpreter (often referred to as 4th Generation Languages). Scripting languages were often used as 'glue' to connect between multiple commands/compiled programs so that the user didn't have to worry about a set of steps in order to carry out their task - they developed a single file, that delineated what steps they wanted to accomplish, and this became a 'script' for anyone to follow.

Various people/groups wrote new interpreters to solve a specific problem domain. awk is one of the better-known ones, and it was used mostly for pattern matching and applying a series of data transforms on input. It worked well, but had a limited problem domain. The expansion of that domain was all but impossible because the source code was unavailable. Perl (Larry Wall, principle author/architect) tool scripting to the next level - and developed an interpreter that not only allowed the user to run system commands, manipulate input and output data, supported typeless variables, but also to access Unix system level APIs as functions from within the scripts themselves. It was probably one of the first widely used high-level scripting languages. It is with Perl (IMHO) that scripting languages crossed the arbitrary line and added the capabilities of programming languages.

Your question was specifically about Python. Because the python interpreter runs against a text file containing the python code, and that the python code can run anywhere that there is a python interpreter, I would say that it is a scripting language (in the same vein as Perl). You do not need to recompile the user python command file for each different OS/CPU Architecture (as you would with C/C++/Fortran), making it significantly more portable and easier to use.

Credit for this answer goes to Jerrold (Jerry) Heyman. Original thread: https://www.researchgate.net/post/Is_Python_a_Programming_language_or_Scripting_Language

jQuery function after .append

the Jquery append function returns a jQuery object so you can just tag a method on the end

$("#root").append(child).anotherJqueryMethod();

How can I simulate mobile devices and debug in Firefox Browser?

Use the Responsive Design Tool using Ctrl + Shift + M.

Getting an odd error, SQL Server query using `WITH` clause

;WITH 
    CteProductLookup(ProductId, oid) 
    AS 
...

Naming threads and thread-pools of ExecutorService

The home-grown core Java solution that I use to decorate existing factories:

public class ThreadFactoryNameDecorator implements ThreadFactory {
    private final ThreadFactory defaultThreadFactory;
    private final String suffix;

    public ThreadFactoryNameDecorator(String suffix) {
        this(Executors.defaultThreadFactory(), suffix);
    }

    public ThreadFactoryNameDecorator(ThreadFactory threadFactory, String suffix) {
        this.defaultThreadFactory = threadFactory;
        this.suffix = suffix;
    }

    @Override
    public Thread newThread(Runnable task) {
        Thread thread = defaultThreadFactory.newThread(task);
        thread.setName(thread.getName() + "-" + suffix);
        return thread;
    }
}

In action:

Executors.newSingleThreadExecutor(new ThreadFactoryNameDecorator("foo"));

Converting unix time into date-time via excel

in case the above does not work for you. for me this did not for some reasons;

the UNIX numbers i am working on are from the Mozilla place.sqlite dates.

to make it work : i splitted the UNIX cells into two cells : one of the first 10 numbers (the date) and the other 4 numbers left (the seconds i believe)

Then i used this formula, =(A1/86400)+25569 where A1 contains the cell with the first 10 number; and it worked

Remove all files in a directory

Although this is an old question, I think none has already answered using this approach:

# python 2.7
import os

d='/home/me/test'
filesToRemove = [os.path.join(d,f) for f in os.listdir(d)]
for f in filesToRemove:
    os.remove(f) 

In C#, how to check whether a string contains an integer?

        string text = Console.ReadLine();
        bool isNumber = false;

        for (int i = 0; i < text.Length; i++)
        {
            if (char.IsDigit(text[i]))
            {
                isNumber = true;
                break;
            }
        }

        if (isNumber)
        {
            Console.WriteLine("Text contains number.");
        }
        else
        {
            Console.WriteLine("Text doesn't contain number.");
        }

        Console.ReadKey();

Or Linq:

        string text = Console.ReadLine();

        bool isNumberOccurance =text.Any(letter => char.IsDigit(letter));
        Console.WriteLine("{0}",isDigitPresent ? "Text contains number." : "Text doesn't contain number.");
        Console.ReadKey();

Throwing multiple exceptions in a method of an interface in java

I think you are asking for something like the code below:

public interface A
{
    void foo() 
        throws AException;
}

public class B
    implements A
{
    @Overrides 
    public void foo()
        throws AException,
               BException
    {
    }
}

This will not work unless BException is a subclass of AException. When you override a method you must conform to the signature that the parent provides, and exceptions are part of the signature.

The solution is to declare the the interface also throws a BException.

The reason for this is you do not want code like:

public class Main
{
    public static void main(final String[] argv)
    {
        A a;

        a = new B();

        try
        {
            a.foo();
        }
        catch(final AException ex)
        {
        }
        // compiler will not let you write a catch BException if the A interface
        // doesn't say that it is thrown.
    }
}

What would happen if B::foo threw a BException? The program would have to exit as there could be no catch for it. To avoid situations like this child classes cannot alter the types of exceptions thrown (except that they can remove exceptions from the list).

New to unit testing, how to write great tests?

Unit testing is about the output you get from a function/method/application. It does not matter at all how the result is produced, it just matters that it is correct. Therefore, your approach of counting calls to inner methods and such is wrong. What I tend to do is sit down and write what a method should return given certain input values or a certain environment, then write a test which compares the actual value returned with what I came up with.

Restart pods when configmap updates in Kubernetes?

The current best solution to this problem (referenced deep in https://github.com/kubernetes/kubernetes/issues/22368 linked in the sibling answer) is to use Deployments, and consider your ConfigMaps to be immutable.

When you want to change your config, create a new ConfigMap with the changes you want to make, and point your deployment at the new ConfigMap. If the new config is broken, the Deployment will refuse to scale down your working ReplicaSet. If the new config works, then your old ReplicaSet will be scaled to 0 replicas and deleted, and new pods will be started with the new config.

Not quite as quick as just editing the ConfigMap in place, but much safer.

How to perform .Max() on a property of all objects in a collection and return the object with maximum value

This would require a sort (O(n log n)) but is very simple and flexible. Another advantage is being able to use it with LINQ to SQL:

var maxObject = list.OrderByDescending(item => item.Height).First();

Note that this has the advantage of enumerating the list sequence just once. While it might not matter if list is a List<T> that doesn't change in the meantime, it could matter for arbitrary IEnumerable<T> objects. Nothing guarantees that the sequence doesn't change in different enumerations so methods that are doing it multiple times can be dangerous (and inefficient, depending on the nature of the sequence). However, it's still a less than ideal solution for large sequences. I suggest writing your own MaxObject extension manually if you have a large set of items to be able to do it in one pass without sorting and other stuff whatsoever (O(n)):

static class EnumerableExtensions {
    public static T MaxObject<T,U>(this IEnumerable<T> source, Func<T,U> selector)
      where U : IComparable<U> {
       if (source == null) throw new ArgumentNullException("source");
       bool first = true;
       T maxObj = default(T);
       U maxKey = default(U);
       foreach (var item in source) {
           if (first) {
                maxObj = item;
                maxKey = selector(maxObj);
                first = false;
           } else {
                U currentKey = selector(item);
                if (currentKey.CompareTo(maxKey) > 0) {
                    maxKey = currentKey;
                    maxObj = item;
                }
           }
       }
       if (first) throw new InvalidOperationException("Sequence is empty.");
       return maxObj;
    }
}

and use it with:

var maxObject = list.MaxObject(item => item.Height);

How to change the scrollbar color using css

Your css will only work in IE browser. And the css suggessted by hayk.mart will olny work in webkit browsers. And by using different css hacks you can't style your browsers scroll bars with a same result.

So, it is better to use a jQuery/Javascript plugin to achieve a cross browser solution with a same result.

Solution:

By Using jScrollPane a jQuery plugin, you can achieve a cross browser solution

See This Demo

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

How would I create a UIAlertView in Swift?

In Swift 4.2 and Xcode 10

Method 1 :

SIMPLE ALERT

let alert = UIAlertController(title: "Your title", message: "Your message", preferredStyle: .alert)
    
     let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
     })
     alert.addAction(ok)
     let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
     })
     alert.addAction(cancel)
     DispatchQueue.main.async(execute: {
        self.present(alert, animated: true)
})

Method 2 :

ALERT WITH SHARED CLASS

If you want Shared class style(Write once use every where)

import UIKit
class SharedClass: NSObject {//This is shared class
static let sharedInstance = SharedClass()

    //Show alert
    func alert(view: UIViewController, title: String, message: String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "OK", style: .default, handler: { action in
        })
        alert.addAction(defaultAction)
        DispatchQueue.main.async(execute: {
            view.present(alert, animated: true)
        })
    }

    private override init() {
    }
}

Now call alert like this in every ware

SharedClass.sharedInstance.alert(view: self, title: "Your title here", message: "Your message here")

Method 3 :

PRESENT ALERT TOP OF ALL WINDOWS

If you want to present alert on top of all views, use this code

func alertWindow(title: String, message: String) {
    DispatchQueue.main.async(execute: {
        let alertWindow = UIWindow(frame: UIScreen.main.bounds)
        alertWindow.rootViewController = UIViewController()
        alertWindow.windowLevel = UIWindowLevelAlert + 1
    
        let alert2 = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let defaultAction2 = UIAlertAction(title: "OK", style: .default, handler: { action in
        })
        alert2.addAction(defaultAction2)
    
        alertWindow.makeKeyAndVisible()
    
        alertWindow.rootViewController?.present(alert2, animated: true, completion: nil)
    })
}

Function calling

SharedClass.sharedInstance.alertWindow(title:"This your title", message:"This is your message")

Method 4 :

Alert with Extension

extension  UIViewController {

    func showAlert(withTitle title: String, withMessage message:String) {
        let alert = UIAlertController(title: title, message: message, preferredStyle: .alert)
        let ok = UIAlertAction(title: "OK", style: .default, handler: { action in
        })
        let cancel = UIAlertAction(title: "Cancel", style: .default, handler: { action in
        })
        alert.addAction(ok)
        alert.addAction(cancel)
        DispatchQueue.main.async(execute: {
            self.present(alert, animated: true)
        })
    }
}

Now call like this

//Call showAlert function in your class
@IBAction func onClickAlert(_ sender: UIButton) {
    showAlert(withTitle:"Your Title Here", withMessage: "YourCustomMessageHere")
}

Method 5 :

ALERT WITH TEXTFIELDS

If you want to add textfields to alert.

//Global variables
var name:String?
var login:String?

//Call this function like this:  alertWithTF() 
//Add textfields to alert 
func alertWithTF() {
    
    let alert = UIAlertController(title: "Login", message: "Enter username&password", preferredStyle: .alert)
    // Login button
    let loginAction = UIAlertAction(title: "Login", style: .default, handler: { (action) -> Void in
        // Get TextFields text
        let usernameTxt = alert.textFields![0]
        let passwordTxt = alert.textFields![1]
        //Asign textfileds text to our global varibles
        self.name = usernameTxt.text
        self.login = passwordTxt.text
        
        print("USERNAME: \(self.name!)\nPASSWORD: \(self.login!)")
    })
    
    // Cancel button
    let cancel = UIAlertAction(title: "Cancel", style: .destructive, handler: { (action) -> Void in })
    
    //1 textField for username
    alert.addTextField { (textField: UITextField) in
        textField.placeholder = "Enter username"
        //If required mention keyboard type, delegates, text sixe and font etc...
        //EX:
        textField.keyboardType = .default
    }
    
    //2nd textField for password
    alert.addTextField { (textField: UITextField) in
        textField.placeholder = "Enter password"
        textField.isSecureTextEntry = true
    }
    
    // Add actions
    alert.addAction(loginAction)
    alert.addAction(cancel)
    self.present(alert, animated: true, completion: nil)
    
}

Method 6:

Alert in SharedClass with Extension

//This is your shared class
import UIKit

 class SharedClass: NSObject {

 static let sharedInstance = SharedClass()

 //Here write your code....

 private override init() {
 }
}

//Alert function in shared class
extension UIViewController {
    func showAlert(title: String, msg: String) {
        DispatchQueue.main.async {
            let alert = UIAlertController(title: title, message: msg, preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }
    }
}

Now call directly like this

self.showAlert(title: "Your title here...", msg: "Your message here...")

Method 7:

Alert with out shared class with Extension in separate class for alert.

Create one new Swift class, and import UIKit. Copy and paste below code.

//This is your Swift new class file
import UIKit
import Foundation

extension UIAlertController {
    class func alert(title:String, msg:String, target: UIViewController) {
        let alert = UIAlertController(title: title, message: msg, preferredStyle: UIAlertControllerStyle.alert)
        alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default) {
        (result: UIAlertAction) -> Void in
        })
        target.present(alert, animated: true, completion: nil)
    }
}

Now call alert function like this in all your classes (Single line).

UIAlertController.alert(title:"Title", msg:"Message", target: self)

How is it....

How to fix "Your Ruby version is 2.3.0, but your Gemfile specified 2.2.5" while server starting

You better install Ruby 2.2.5 for compatibility. The Ruby version in your local machine is different from the one declared in Gemfile.

If you're using rvm:

rvm install 2.2.5
rvm use 2.2.5

else if you're using rbenv:

rbenv install 2.2.5
rbenv local 2.2.5

else if you can not change ruby version by rbenv, read here

Getting RSA private key from PEM BASE64 Encoded private key file

As others have responded, the key you are trying to parse doesn't have the proper PKCS#8 headers which Oracle's PKCS8EncodedKeySpec needs to understand it. If you don't want to convert the key using openssl pkcs8 or parse it using JDK internal APIs you can prepend the PKCS#8 header like this:

static final Base64.Decoder DECODER = Base64.getMimeDecoder();

private static byte[] buildPKCS8Key(File privateKey) throws IOException {
  final String s = new String(Files.readAllBytes(privateKey.toPath()));
  if (s.contains("--BEGIN PRIVATE KEY--")) {
    return DECODER.decode(s.replaceAll("-----\\w+ PRIVATE KEY-----", ""));
  }
  if (!s.contains("--BEGIN RSA PRIVATE KEY--")) {
    throw new RuntimeException("Invalid cert format: "+ s);
  }

  final byte[] innerKey = DECODER.decode(s.replaceAll("-----\\w+ RSA PRIVATE KEY-----", ""));
  final byte[] result = new byte[innerKey.length + 26];
  System.arraycopy(DECODER.decode("MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKY="), 0, result, 0, 26);
  System.arraycopy(BigInteger.valueOf(result.length - 4).toByteArray(), 0, result, 2, 2);
  System.arraycopy(BigInteger.valueOf(innerKey.length).toByteArray(), 0, result, 24, 2);
  System.arraycopy(innerKey, 0, result, 26, innerKey.length);
  return result;
}

Once that method is in place you can feed it's output to the PKCS8EncodedKeySpec constructor like this: new PKCS8EncodedKeySpec(buildPKCS8Key(privateKey));

Angular 2: How to access an HTTP response body?

This should work. You can get body using response.json() if its a json response.

   this.http.request('http://thecatapi.com/api/images/get?format=html&results_per_page=10').
      subscribe((res: Response.json()) => {
        console.log(res);
      })

How do you test that a Python function throws an exception?

Use TestCase.assertRaises (or TestCase.failUnlessRaises) from the unittest module, for example:

import mymod

class MyTestCase(unittest.TestCase):
    def test1(self):
        self.assertRaises(SomeCoolException, mymod.myfunc)

npm command to uninstall or prune unused packages in Node.js

You can use npm-prune to remove extraneous packages.

npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]

This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.

Extraneous packages are packages that are not listed on the parent package's dependencies list.

If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.

If the --dry-run flag is used then no changes will actually be made.

If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.

In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.

If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.

Use npm-dedupe to reduce duplication

npm dedupe
npm ddp

Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.

For example, consider this dependency graph:

a
+-- b <-- depends on [email protected]
|    `-- [email protected]
`-- d <-- depends on c@~1.0.9
     `-- [email protected]

In this case, npm-dedupe will transform the tree to:

 a
 +-- b
 +-- d
 `-- [email protected]

Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.

The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.

Order of execution of tests in TestNG

The ordering of methods in the class file is unpredictable, so you need to either use dependencies or include your methods explicitly in XML.

By default, TestNG will run your tests in the order they are found in the XML file. If you want the classes and methods listed in this file to be run in an unpredictible order, set the preserve-order attribute to false

Correct way of using log4net (logger naming)

My Answer might be coming late, but I think it can help newbie. You shall not see logs executed unless the changes are made as below.

2 Files have to be changes when you implement Log4net.


  1. Add Reference of log4net.dll in the project.
  2. app.config
  3. Class file where you will implement Logs.

Inside [app.config] :

First, under 'configSections', you need to add below piece of code;

<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

Then, under 'configuration' block, you need to write below piece of code.(This piece of code is customised as per my need , but it works like charm.)

<log4net debug="true">
    <logger name="log">
      <level value="All"></level>
      <appender-ref ref="RollingLogFileAppender" />
    </logger>

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="log.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <maxSizeRollBackups value="1" />
      <maximumFileSize value="1MB" />
      <staticLogFileName value="true" />

      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %C.%M [%line] %-5level - %message %newline %exception %newline" />
      </layout>
    </appender>
</log4net>

Inside Calling Class :

Inside the class where you are going to use this log4net, you need to declare below piece of code.

 ILog log = LogManager.GetLogger("log");

Now, you are ready call log wherever you want in that same class. Below is one of the method you can call while doing operations.

log.Error("message");

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

The erudite suggestions mentioned above will solve the problem in 99.99% of the cases. It was my luck that they did not. In my case it turned out I was including a header file from a different Windows project. Sure enough, at the very bottom of that file I found the directive:

#pragma comment(linker, "/subsystem:Windows")

Needless to say, removing this line solved my problem.

How can I list all commits that changed a specific file?

git log path should do what you want. From the git log man:

[--] <path>…

Show only commits that affect any of the specified paths. To prevent confusion with 
options and branch names, paths may need to be prefixed with "-- " to separate them
from options or refnames.

Normalize data in pandas

You can use apply for this, and it's a bit neater:

import numpy as np
import pandas as pd

np.random.seed(1)

df = pd.DataFrame(np.random.randn(4,4)* 4 + 3)

          0         1         2         3
0  9.497381  0.552974  0.887313 -1.291874
1  6.461631 -6.206155  9.979247 -0.044828
2  4.276156  2.002518  8.848432 -5.240563
3  1.710331  1.463783  7.535078 -1.399565

df.apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))

          0         1         2         3
0  0.515087  0.133967 -0.651699  0.135175
1  0.125241 -0.689446  0.348301  0.375188
2 -0.155414  0.310554  0.223925 -0.624812
3 -0.484913  0.244924  0.079473  0.114448

Also, it works nicely with groupby, if you select the relevant columns:

df['grp'] = ['A', 'A', 'B', 'B']

          0         1         2         3 grp
0  9.497381  0.552974  0.887313 -1.291874   A
1  6.461631 -6.206155  9.979247 -0.044828   A
2  4.276156  2.002518  8.848432 -5.240563   B
3  1.710331  1.463783  7.535078 -1.399565   B


df.groupby(['grp'])[[0,1,2,3]].apply(lambda x: (x - np.mean(x)) / (np.max(x) - np.min(x)))

     0    1    2    3
0  0.5  0.5 -0.5 -0.5
1 -0.5 -0.5  0.5  0.5
2  0.5  0.5  0.5 -0.5
3 -0.5 -0.5 -0.5  0.5

CSS :: child set to change color on parent hover, but changes also when hovered itself

Update

The below made sense for 2013. However, now, I would use the :not() selector as described below.


CSS can be overwritten.

DEMO: http://jsfiddle.net/persianturtle/J4SUb/

Use this:

_x000D_
_x000D_
.parent {
  padding: 50px;
  border: 1px solid black;
}

.parent span {
  position: absolute;
  top: 200px;
  padding: 30px;
  border: 10px solid green;
}

.parent:hover span {
  border: 10px solid red;
}

.parent span:hover {
  border: 10px solid green;
}
_x000D_
<a class="parent">
    Parent text
    <span>Child text</span>    
</a>
_x000D_
_x000D_
_x000D_

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

At the current version of Spring-Boot (1.4.1.RELEASE) , each pooling datasource implementation has its own prefix for properties.

For instance, if you are using tomcat-jdbc:

spring.datasource.tomcat.max-wait=10000

You can find the explanation out here

spring.datasource.max-wait=10000

this have no effect anymore.

Remove new lines from string and replace with one empty space

Line breaks in text are generally represented as:

\r\n - on a windows computer

\r - on an Apple computer

\n - on Linux

//Removes all 3 types of line breaks

$string = str_replace("\r", "", $string);

$string = str_replace("\n", "", $string);

How to split elements of a list?

Try iterating through each element of the list, then splitting it at the tab character and adding it to a new list.

for i in list:
    newList.append(i.split('\t')[0])

Parse date string and change format

>>> from_date="Mon Feb 15 2010"
>>> import time                
>>> conv=time.strptime(from_date,"%a %b %d %Y")
>>> time.strftime("%d/%m/%Y",conv)
'15/02/2010'

Test whether string is a valid integer

Latecomer to the party here. I'm extremely surprised none of the answers mention the simplest, fastest, most portable solution; the case statement.

case ${variable#[-+]} in
  *[!0-9]* | '') echo Not a number ;;
  * ) echo Valid number ;;
esac

The trimming of any sign before the comparison feels like a bit of a hack, but that makes the expression for the case statement so much simpler.

Javascript loop through object array?

The suggested for loop is quite fine but you have to check the properties with hasOwnProperty. I'd rather suggest using Object.keys() that only returns 'own properties' of the object (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)

_x000D_
_x000D_
var data = {_x000D_
    "messages": [{_x000D_
        "msgFrom": "13223821242",_x000D_
        "msgBody": "Hi there"_x000D_
    }, {_x000D_
        "msgFrom": "Bill",_x000D_
        "msgBody": "Hello!"_x000D_
    }]_x000D_
};_x000D_
_x000D_
data.messages.forEach(function(message, index) {_x000D_
    console.log('message index '+ index);_x000D_
    Object.keys(message).forEach(function(prop) {    _x000D_
        console.log(prop + " = " + message[prop]);_x000D_
    });_x000D_
});
_x000D_
_x000D_
_x000D_

replace \n and \r\n with <br /> in java

That should work, but don't kill yourself trying to figure it out. Just use 2 passes.

str  = str.replaceAll("(\r\n)", "<br />");
str  = str.replaceAll("(\n)", "<br />");

Disclaimer: this is not very efficient.

IndexOf function in T-SQL

One very small nit to pick:

The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:

"john@work"@myemployer.com

This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:

SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1

More information:

http://en.wikipedia.org/wiki/Email_address

Change New Google Recaptcha (v2) Width

For the new version of noCaptcha Recaptcha the following works for me:

<div class="g-recaptcha"
data-sitekey="6LcVkQsTAAAAALqSUcqN1zvzOE8sZkOq2GMBE-RK"
style="transform:scale(0.7);transform-origin:0;-webkit-transform:scale(0.7);
transform:scale(0.7);-webkit-transform-origin:0 0;transform-origin:0 0;"></div>

Ref

How to show SVG file on React Native?

Note: Svg does not work for android release versions so do not consider for android. It will work for android in debug mode only. But it works fine for ios.

Use https://github.com/vault-development/react-native-svg-uri

Install

npm install react-native-svg-uri --save
react-native link react-native-svg # not react-native-svg-uri

Usage

import SvgUri from 'react-native-svg-uri';


<SvgUri source={require('./path_to_image/image.svg')} />

Unmount the directory which is mounted by sshfs in Mac

If your problem is that you mounted a network drive with SSHFS, but the ssh connection got cut and you simply cannot remount it because of an error like mount_osxfuse: mount point /Users/your_user/mount_folder is itself on a OSXFUSE volume, the github user theunsa found a solution that works for me. Quoting his answer:


My current workaround is to:

Find the culprit sshfs process:

$ pgrep -lf sshfs

Kill it:

$ kill -9 <pid_of_sshfs_process>

sudo force unmount the "unavailable" directory:

$ sudo umount -f <mounted_dir>

Remount the now "available" directory with sshfs ... and then tomorrow morning go back to step 1.

How To Change DataType of a DataColumn in a DataTable?

I've taken a bit of a different approach. I needed to parse a datetime from an excel import that was in the OA date format. This methodology is simple enough to build from... in essence,

  1. Add column of type you want
  2. Rip through the rows converting the value
  3. Delete the original column and rename to the new to match the old

    private void ChangeColumnType(System.Data.DataTable dt, string p, Type type){
            dt.Columns.Add(p + "_new", type);
            foreach (System.Data.DataRow dr in dt.Rows)
            {   // Will need switch Case for others if Date is not the only one.
                dr[p + "_new"] =DateTime.FromOADate(double.Parse(dr[p].ToString())); // dr[p].ToString();
            }
            dt.Columns.Remove(p);
            dt.Columns[p + "_new"].ColumnName = p;
        }
    

Converting a generic list to a CSV string

I like a nice simple extension method

 public static string ToCsv(this List<string> itemList)
         {
             return string.Join(",", itemList);
         }

Then you can just call the method on the original list:

string CsvString = myList.ToCsv();

Cleaner and easier to read than some of the other suggestions.

SSRS custom number format

am assuming that you want to know how to format numbers in SSRS

Just right click the TextBox on which you want to apply formatting, go to its expression.

suppose its expression is something like below

=Fields!myField.Value

then do this

=Format(Fields!myField.Value,"##.##") 

or

=Format(Fields!myFields.Value,"00.00")

difference between the two is that former one would make 4 as 4 and later one would make 4 as 04.00

this should give you an idea.

also: you might have to convert your field into a numerical one. i.e.

  =Format(CDbl(Fields!myFields.Value),"00.00")

so: 0 in format expression means, when no number is present, place a 0 there and # means when no number is present, leave it. Both of them works same when numbers are present ie. 45.6567 would be 45.65 for both of them:

UPDATE :

if you want to apply variable formatting on the same column based on row values i.e. you want myField to have no formatting when it has no decimal value but formatting with double precision when it has decimal then you can do it through logic. (though you should not be doing so)

Go to the appropriate textbox and go to its expression and do this:

=IIF((Fields!myField.Value - CInt(Fields!myField.Value)) > 0, 
    Format(Fields!myField.Value, "##.##"),Fields!myField.Value)

so basically you are using IIF(condition, true,false) operator of SSRS, ur condition is to check whether the number has decimal value, if it has, you apply the formatting and if no, you let it as it is.

this should give you an idea, how to handle variable formatting.

ngrok command not found

I had followed the instructions as per the ngrok download instructions:

enter image description here

So the file downloaded to ~/Downloads

But I still needed to move ngrok into my binaries folder, like so:

mv ~/Downloads/ngrok /usr/local/bin

Then running ngrok in terminal works

Error while installing json gem 'mkmf.rb can't find header files for ruby'

For those who are getting this on Mac OS X you may need to run the following command to install the XCode command-line tools, even if you already have XCode installed:

sudo xcode-select --install

Also you must agree the terms and conditions of XCode by running the following command:

sudo xcodebuild -license

java.net.ConnectException :connection timed out: connect?

Number (1): The IP was incorrect - is the correct answer. The /etc/hosts file (a.k.a. C:\Windows\system32\drivers\etc\hosts ) had an incorrect entry for the local machine name. Corrected the 'hosts' file and Camel runs very well. Thanks for the pointer.

Python pip install fails: invalid command egg_info

I also meet a similar error message "Command 'python setup.py egg_info' failed with error code 1" when I want to install cairosvg with command pip install cairosvg in a virtual environment.

Then I have tried both pip install --upgrade pip and pip install --upgrade setuptools before running pip3 install cairosvg, but I still get this error.

I can get rid of this error with sudo in front of the installation command : sudo pip install cairosvg. But note that the command with sudo will install the package for the system python rather than the virtual environment.

So, I further check the error message and find that I get the error while installing the cairocffi. Then I install a certain version of cairocffi (refer to this answer) before install cairosvg. That is how I solve my problem.

Getting attribute of element in ng-click function in angularjs

Even more simple, pass the $event object to ng-click to access the event properties. As an example:

<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>

Within your clickEvent() = function(obj) {} function you can access the data value like this:

var dataValue = obj.target.attributes.data.value;

Which would return exampleData.

Here's a full jsFiddle.

JSP : JSTL's <c:out> tag

As said Will Wagner, in old version of jsp you should always use c:out to output dynamic text.

Moreover, using this syntax:

<c:out value="${person.name}">No name</c:out>

you can display the text "No name" when name is null.

Printing Even and Odd using two Threads in Java

public class OddEven implements Runnable {
    public  int count = 0;

    @Override
    public void run() {
        try {
            increment();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    synchronized void increment() throws Exception {
        while(true) {
            if(count<10) {
                count++;
                System.out.println(Thread.currentThread().getName()+"  " +count);
                notify();
                wait();
            }else {
                break;
            }
        }
    }

    public static void main(String[] args) {
        OddEven n1 = new OddEven();
        Thread r1 = new Thread(n1);
        Thread r2 = new Thread(n1);

        r1.start();
        r2.start();

    }

}

How to enter a series of numbers automatically in Excel

Enter the formula =ROW() into any cell and that cell will show the row number as its value.

If you want 1001, 1002 etc just enter =1000+ROW()

How can I delete one element from an array by value

I'm not sure if anyone has stated this, but Array.delete() and -= value will delete every instance of the value passed to it within the Array. In order to delete the first instance of the particular element you could do something like

arr = [1,3,2,44,5]
arr.delete_at(arr.index(44))

#=> [1,3,2,5]

There could be a simpler way. I'm not saying this is best practice, but it is something that should be recognized.

Are the shift operators (<<, >>) arithmetic or logical in C?

GCC does

  1. for -ve - > Arithmetic Shift

  2. For +ve -> Logical Shift

Property '...' has no initializer and is not definitely assigned in the constructor

Just go to tsconfig.json and set

"strictPropertyInitialization": false

to get rid of the compilation error.

Otherwise you need to initialize all your variables which is a little bit annoying

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

ASP.NET DateTime Picker

If you would like to work with a textbox, be aware that setting the TextMode property to "Date" will not work on Internet Explorer 11, because it does not currently support the "Date", "DateTime", nor "Time" values.

This example illustrates how to implement it using a textbox, including validation of the dates (since the user could enter just numbers). It will work on Internet Explorer 11 as well other web browsers.

<asp:Content ID="Content"
         ContentPlaceHolderID="MainContent"
         runat="server">

<link rel="stylesheet"
    href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" />
   <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
   <script>
   $(function () {
   $("#
   <%= txtBoxDate.ClientID %>").datepicker();
   });
 </script>
 <asp:TextBox ID="txtBoxDate"
           runat="server"
           Width="135px"
           AutoPostBack="False"
           TabIndex="1"
           placeholder="mm/dd/yyyy"
           autocomplete="off"
           MaxLength="10"></asp:TextBox>
 <asp:CompareValidator ID="CompareValidator1"
                    runat="server"
                    ControlToValidate="txtBoxDate"
                    Operator="DataTypeCheck"
                    Type="Date">Date invalid, please check format. 
 </asp:CompareValidator>
 </asp:Content>

Linq to SQL how to do "where [column] in (list of values)"

You could also use:

List<int> codes = new List<int>();

codes.add(1);
codes.add(2);

var foo = from codeData in channel.AsQueryable<CodeData>()
          where codes.Any(code => codeData.CodeID.Equals(code))
          select codeData;

How do I add the Java API documentation to Eclipse?

Eclipse doesn't pull the tooltips from the javadoc location. It only uses the javadoc location to prepend to the link if you say open in browser, you need to download and attach the source for the JDK in order to get the tooltips. For all the JARs under the JRE you should have the following for the javadoc location: http://java.sun.com/javase/6/docs/api/. For resources.jar, rt.jar, jsse.jar, jce.jar and charsets.jar you should attach the source available here.

How do you stash an untracked file?

If you want to stash untracked files, but keep indexed files (the ones you're about to commit for example), just add -k (keep index) option to the -u

git stash -u -k

How can I set the request header for curl?

To pass multiple headers in a curl request you simply add additional -H or --header to your curl command.

Example

//Simplified
$ curl -v -H 'header1:val' -H 'header2:val' URL

//Explanatory
$ curl -v -H 'Connection: keep-alive' -H 'Content-Type: application/json'  https://www.example.com

Going Further

For standard HTTP header fields such as User-Agent, Cookie, Host, there is actually another way to setting them. The curl command offers designated options for setting these header fields:

  • -A (or --user-agent): set "User-Agent" field.
  • -b (or --cookie): set "Cookie" field.
  • -e (or --referer): set "Referer" field.
  • -H (or --header): set "Header" field

For example, the following two commands are equivalent. Both of them change "User-Agent" string in the HTTP header.

    $ curl -v -H "Content-Type: application/json" -H "User-Agent: UserAgentString" https://www.example.com
    $ curl -v -H "Content-Type: application/json" -A "UserAgentString" https://www.example.com

Difference between .on('click') vs .click()

.on() is the recommended way to do all your event binding as of jQuery 1.7. It rolls all the functionality of both .bind() and .live() into one function that alters behavior as you pass it different parameters.

As you have written your example, there is no difference between the two. Both bind a handler to the click event of #whatever. on() offers additional flexibility in allowing you to delegate events fired by children of #whatever to a single handler function, if you choose.

// Bind to all links inside #whatever, even new ones created later.
$('#whatever').on('click', 'a', function() { ... });

MVC Razor Radio Button

In order to do this for multiple items do something like:

foreach (var item in Model)
{
    @Html.RadioButtonFor(m => m.item, "Yes") @:Yes
    @Html.RadioButtonFor(m => m.item, "No") @:No
}

How to use breakpoints in Eclipse

Breakpoints are just used to check the execution of your code, wherever you will put breakpoints the execution will stop there, so you can just check that your project execution is going forward or not. To get more details follow link:-

http://javapapers.com/core-java/top-10-java-debugging-tips-with-eclipse/

How to print register values in GDB?

p $eax works as of GDB 7.7.1

As of GDB 7.7.1, the command you've tried works:

set $eax = 0
p $eax
# $1 = 0
set $eax = 1
p $eax
# $2 = 1

This syntax can also be used to select between different union members e.g. for ARM floating point registers that can be either floating point or integers:

p $s0.f
p $s0.u

From the docs:

Any name preceded by ‘$’ can be used for a convenience variable, unless it is one of the predefined machine-specific register names.

and:

You can refer to machine register contents, in expressions, as variables with names starting with ‘$’. The names of registers are different for each machine; use info registers to see the names used on your machine.

But I haven't had much luck with control registers so far: OSDev 2012 http://f.osdev.org/viewtopic.php?f=1&t=25968 || 2005 feature request https://www.sourceware.org/ml/gdb/2005-03/msg00158.html || alt.lang.asm 2013 https://groups.google.com/forum/#!topic/alt.lang.asm/JC7YS3Wu31I

ARM floating point registers

See: https://reverseengineering.stackexchange.com/questions/8992/floating-point-registers-on-arm/20623#20623

Get the date (a day before current time) in Bash

MAC OSX

For yesterday's date:

date -v-1d +%F

where 1d defines current day minus 1 day. Similarly,

date -v-1w +%F - for previous week date

date -v-1m +%F - for previous month date

IF YOU HAVE GNU DATE,

date --date="1 day ago"

More info: https://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html

ASP.NET: Session.SessionID changes between requests

This was changing for me beginning with .NET 4.7.2 and it was due to the SameSite property on the session cookie. See here for more info: https://devblogs.microsoft.com/aspnet/upcoming-samesite-cookie-changes-in-asp-net-and-asp-net-core/

The default value changed to "Lax" and started breaking things. I changed it to "None" and things worked as expected.

CSS vertical-align: text-bottom;

if your text doesn't spill over two rows then you can do line-height: ; in your CSS, the more line-height you give, the lower on the container it will hold.

add/remove active class for ul list with jquery?

Try this,

 $('.nav-list li').click(function() {

    $('.nav-list li.active').removeClass('active');
    $(this).addClass('active');
});

In your context $(this) will points to the UL element not the Li. Hence you are not getting the expected results.

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

In ubuntu OS in '/etc/php5/apache2/php.ini' file do configurations that this page said.

Simple VBA selection: Selecting 5 cells to the right of the active cell

This copies the 5 cells to the right of the activecell. If you have a range selected, the active cell is the top left cell in the range.

Sub Copy5CellsToRight()
    ActiveCell.Offset(, 1).Resize(1, 5).Copy
End Sub

If you want to include the activecell in the range that gets copied, you don't need the offset:

Sub ExtendAndCopy5CellsToRight()
    ActiveCell.Resize(1, 6).Copy
End Sub

Note that you don't need to select before copying.