Programs & Examples On #Unit testing

Unit testing is a method by which individual units of source code are tested to determine if they are fit for use.

How to tell a Mockito mock object to return something different the next time it is called?

For all who search to return something and then for another call throw exception:

when(mockFoo.someMethod())
        .thenReturn(obj1)
        .thenReturn(obj2)
        .thenThrow(new RuntimeException("Fail"));

or

when(mockFoo.someMethod())
        .thenReturn(obj1, obj2)
        .thenThrow(new RuntimeException("Fail"));

Python unittest passing arguments

Have a same problem. My solution is after you handle with parsing arguments using argparse or other way, remove arguments from sys.argv

sys.argv = sys.argv[:1]  

If you need you can filter unittest arguments from main.parseArgs()

Enzyme - How to access and set <input> value?

I am using create-react-app which comes with jest by default and enzyme 2.7.0.

This worked for me:

const wrapper = mount(<EditableText defaultValue="Hello" />);
const input = wrapper.find('input')[index]; // where index is the position of the input field of interest
input.node.value = 'Change';
input.simulate('change', input);
done();

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

Unit Testing C Code

You also might want to take a look at libtap, a C testing framework which outputs the Test Anything Protocol (TAP) and thus integrates well with a variety of tools coming out for this technology. It's mostly used in the dynamic language world, but it's easy to use and becoming very popular.

An example:

#include <tap.h>

int main () {
    plan(5);

    ok(3 == 3);
    is("fnord", "eek", "two different strings not that way?");
    ok(3 <= 8732, "%d <= %d", 3, 8732);
    like("fnord", "f(yes|no)r*[a-f]$");
    cmp_ok(3, ">=", 10);

    done_testing();
}

Configuring IntelliJ IDEA for unit testing with JUnit

In my case (IntelliJ 2020-02, Kotlin dev) JUnit library was already included by Create project wizard. I needed to enable JUnit plugin:

IntelliJ JUnit plugin

to get green Run test icons next to each test class and method:

enter image description here

and CTRL+Shift+R will run test under caret, and CTRL+shift+D to debug.

Test class with a new() call in it with Mockito

You can use a factory to create the login context. Then you can mock the factory and return whatever you want for your test.

public class TestedClass {
  private final LoginContextFactory loginContextFactory;

  public TestedClass(final LoginContextFactory loginContextFactory) {
    this.loginContextFactory = loginContextFactory;
  }

  public LoginContext login(String user, String password) {
    LoginContext lc = loginContextFactory.createLoginContext();
  }
}

public interface LoginContextFactory {
  public LoginContext createLoginContext();
}

Mockito. Verify method arguments

argThat plus lambda

that is how you can fail your argument verification:

    verify(mock).mymethod(argThat(
      (x)->false
    ));

where

import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;

argThat plus asserts

the above test will "say" Expected: lambda$... Was: YourClass.toSting.... You can get a more specific cause of the failure if to use asserts in the the lambda:

    verify(mock).mymethod(argThat( x -> {
      assertThat(x).isNotNull();
      assertThat(x.description).contains("KEY");
      return true;
    }));

??BUT??: THIS ONLY WORKS WHEN

  • THE CALL IS EXPECTED 1 TIME, or
  • the call is expected 2+ times, but all the times the verifier matches (returns true).

If the verified method called 2+ times, mockito passes all the called combinations to each verifier. So mockito expects your verifier silently returns true for one of the argument set, and false (no assert exceptions) for other valid calls. That expectation is not a problem for 1 method call - it should just return true 1 time.

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.Mockito.verify;

Now the failed test will say: Expected: Obj.description to contain 'KEY'. Was: 'Actual description'. NOTE: I used assertJ asserts, but it's up to you which assertion framework to use.


argThat with multiple arguments.

If you use argThat, all arguments must be provided with matches. E.g.:

    verify(mock).mymethod(eq("VALUE_1"), argThat((x)->false));
    // above is correct as eq() is also an argument matcher.

verify(mock).mymethod("VALUE_1", argThat((x)->false));

// above is incorrect; an exceptoin will be thrown, as the fist arg. is given without an argument matcher.

where:

import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;

eq matcher

the easiest way to check if the argument is equal:

verify(mock).mymethod(eq(expectedValue));
// NOTE:   ^ where the parentheses must be closed.

direct argument

if comparison by ref is acceptable, then go on with:

verify(mock).mymethod(expectedArg);
// NOTE:   ^ where the parentheses must be closed.

THE ROOT CAUSE of original question failure was the wrong place of the paranthes: verify(mock.mymethod.... That was wrong. The right would be: verify(mock).*

How to mock void methods with Mockito

First of all: you should always import mockito static, this way the code will be much more readable (and intuitive):

import static org.mockito.Mockito.*;

For partial mocking and still keeping original functionality on the rest mockito offers "Spy".

You can use it as follows:

private World world = spy(new World());

To eliminate a method from being executed you could use something like this:

doNothing().when(someObject).someMethod(anyObject());

to give some custom behaviour to a method use "when" with an "thenReturn":

doReturn("something").when(this.world).someMethod(anyObject());

For more examples please find the excellent mockito samples in the doc.

Easy way to get a test file into JUnit

You can try doing:

String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");

Controlling execution order of unit tests in Visual Studio

Merge your tests into one giant test will work. To make the test method more readable, you can do something like

[TestMethod]
public void MyIntegratonTestLikeUnitTest()
{
    AssertScenarioA();

    AssertScenarioB();

    ....
}

private void AssertScenarioA()
{
     // Assert
}

private void AssertScenarioB()
{
     // Assert
}

Actually the issue you have suggests you probably should improve the testability of the implementation.

Comparison of C++ unit test frameworks

Boost Test Library is a very good choice especially if you're already using Boost.

// TODO: Include your class to test here.
#define BOOST_TEST_MODULE MyTest
#include <boost/test/unit_test.hpp>

BOOST_AUTO_TEST_CASE(MyTestCase)
{
    // To simplify this example test, let's suppose we'll test 'float'.
    // Some test are stupid, but all should pass.
    float x = 9.5f;

    BOOST_CHECK(x != 0.0f);
    BOOST_CHECK_EQUAL((int)x, 9);
    BOOST_CHECK_CLOSE(x, 9.5f, 0.0001f); // Checks differ no more then 0.0001%
}

It supports:

  • Automatic or manual tests registration
  • Many assertions
  • Automatic comparison of collections
  • Various output formats (including XML)
  • Fixtures / Templates...

PS: I wrote an article about it that may help you getting started: C++ Unit Testing Framework: A Boost Test Tutorial

Verifying a specific parameter with Moq

Had one of these as well, but the parameter of the action was an interface with no public properties. Ended up using It.Is() with a seperate method and within this method had to do some mocking of the interface

public interface IQuery
{
    IQuery SetSomeFields(string info);
}

void DoSomeQuerying(Action<IQuery> queryThing);

mockedObject.Setup(m => m.DoSomeQuerying(It.Is<Action<IQuery>>(q => MyCheckingMethod(q)));

private bool MyCheckingMethod(Action<IQuery> queryAction)
{
    var mockQuery = new Mock<IQuery>();
    mockQuery.Setup(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition())
    queryAction.Invoke(mockQuery.Object);
    mockQuery.Verify(m => m.SetSomeFields(It.Is<string>(s => s.MeetsSomeCondition(), Times.Once)
    return true
}

Conditionally ignoring tests in JUnit 4

The JUnit way is to do this at run-time is org.junit.Assume.

 @Before
 public void beforeMethod() {
     org.junit.Assume.assumeTrue(someCondition());
     // rest of setup.
 }

You can do it in a @Before method or in the test itself, but not in an @After method. If you do it in the test itself, your @Before method will get run. You can also do it within @BeforeClass to prevent class initialization.

An assumption failure causes the test to be ignored.

Edit: To compare with the @RunIf annotation from junit-ext, their sample code would look like this:

@Test
public void calculateTotalSalary() {
    assumeThat(Database.connect(), is(notNull()));
    //test code below.
}

Not to mention that it is much easier to capture and use the connection from the Database.connect() method this way.

Can Mockito stub a method without regard to the argument?

Use like this:

when(
  fooDao.getBar(
    Matchers.<Bazoo>any()
  )
).thenReturn(myFoo);

Before you need to import Mockito.Matchers

Mocking python function based on input arguments

Although side_effect can achieve the goal, it is not so convenient to setup side_effect function for each test case.

I write a lightweight Mock (which is called NextMock) to enhance the built-in mock to address this problem, here is a simple example:

from nextmock import Mock

m = Mock()

m.with_args(1, 2, 3).returns(123)

assert m(1, 2, 3) == 123
assert m(3, 2, 1) != 123

It also supports argument matcher:

from nextmock import Arg, Mock

m = Mock()

m.with_args(1, 2, Arg.Any).returns(123)

assert m(1, 2, 1) == 123
assert m(1, 2, "123") == 123

Hope this package could make testing more pleasant. Feel free to give any feedback.

How to use JUnit to test asynchronous processes

This is what I'm using nowadays if the test result is produced asynchronously.

public class TestUtil {

    public static <R> R await(Consumer<CompletableFuture<R>> completer) {
        return await(20, TimeUnit.SECONDS, completer);
    }

    public static <R> R await(int time, TimeUnit unit, Consumer<CompletableFuture<R>> completer) {
        CompletableFuture<R> f = new CompletableFuture<>();
        completer.accept(f);
        try {
            return f.get(time, unit);
        } catch (InterruptedException | TimeoutException e) {
            throw new RuntimeException("Future timed out", e);
        } catch (ExecutionException e) {
            throw new RuntimeException("Future failed", e.getCause());
        }
    }
}

Using static imports, the test reads kinda nice. (note, in this example I'm starting a thread to illustrate the idea)

    @Test
    public void testAsync() {
        String result = await(f -> {
            new Thread(() -> f.complete("My Result")).start();
        });
        assertEquals("My Result", result);
    }

If f.complete isn't called, the test will fail after a timeout. You can also use f.completeExceptionally to fail early.

Assert equals between 2 Lists in Junit

If you don't care about the order of the elements, I recommend ListAssert.assertEquals in junit-addons.

Link: http://junit-addons.sourceforge.net/

For lazy Maven users:

    <dependency>
        <groupId>junit-addons</groupId>
        <artifactId>junit-addons</artifactId>
        <version>1.4</version>
        <scope>test</scope>
    </dependency>

Outputting data from unit test in Python

Another option - start a debugger where the test fails.

Try running your tests with Testoob (it will run your unittest suite without changes), and you can use the '--debug' command line switch to open a debugger when a test fails.

Here's a terminal session on windows:

C:\work> testoob tests.py --debug
F
Debugging for failure in test: test_foo (tests.MyTests.test_foo)
> c:\python25\lib\unittest.py(334)failUnlessEqual()
-> (msg or '%r != %r' % (first, second))
(Pdb) up
> c:\work\tests.py(6)test_foo()
-> self.assertEqual(x, y)
(Pdb) l
  1     from unittest import TestCase
  2     class MyTests(TestCase):
  3       def test_foo(self):
  4         x = 1
  5         y = 2
  6  ->     self.assertEqual(x, y)
[EOF]
(Pdb)

Unit testing private methods in C#

Yes, don't Test private methods.... The idea of a unit test is to test the unit by its public 'API'.

If you are finding you need to test a lot of private behavior, most likely you have a new 'class' hiding within the class you are trying to test, extract it and test it by its public interface.

One piece of advice / Thinking tool..... There is an idea that no method should ever be private. Meaning all methods should live on a public interface of an object.... if you feel you need to make it private, it most likely lives on another object.

This piece of advice doesn't quite work out in practice, but its mostly good advice, and often it will push people to decompose their objects into smaller objects.

Example of Mockito's argumentCaptor

The steps in order to make a full check are:

Prepare the captor :

ArgumentCaptor<SomeArgumentClass> someArgumentCaptor = ArgumentCaptor.forClass(SomeArgumentClass.class);

verify the call to dependent on component (collaborator of subject under test). times(1) is the default value, so ne need to add it.

verify(dependentOnComponent, times(1)).send(someArgumentCaptor.capture());

Get the argument passed to collaborator

SomeArgumentClass someArgument = messageCaptor.getValue();

someArgument can be used for assertions

Mocking static methods with Mockito

You can do it with a little bit of refactoring:

public class MySQLDatabaseConnectionFactory implements DatabaseConnectionFactory {

    @Override public Connection getConnection() {
        try {
            return _getConnection(...some params...);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //method to forward parameters, enabling mocking, extension, etc
    Connection _getConnection(...some params...) throws SQLException {
        return DriverManager.getConnection(...some params...);
    }
}

Then you can extend your class MySQLDatabaseConnectionFactory to return a mocked connection, do assertions on the parameters, etc.

The extended class can reside within the test case, if it's located in the same package (which I encourage you to do)

public class MockedConnectionFactory extends MySQLDatabaseConnectionFactory {

    Connection _getConnection(...some params...) throws SQLException {
        if (some param != something) throw new InvalidParameterException();

        //consider mocking some methods with when(yourMock.something()).thenReturn(value)
        return Mockito.mock(Connection.class);
    }
}

What is Mocking?

Mock is a method/object that simulates the behavior of a real method/object in controlled ways. Mock objects are used in unit testing.

Often a method under a test calls other external services or methods within it. These are called dependencies. Once mocked, the dependencies behave the way we defined them.

With the dependencies being controlled by mocks, we can easily test the behavior of the method that we coded. This is Unit testing.

What is the purpose of mock objects?

Mocks vs stubs

Unit tests vs Functional tests

New to unit testing, how to write great tests?

Try writing a Unit Test before writing the method it is going to test.

That will definitely force you to think a little differently about how things are being done. You'll have no idea how the method is going to work, just what it is supposed to do.

You should always be testing the results of the method, not how the method gets those results.

Using Spring MVC Test to unit test multipart POST request

Since MockMvcRequestBuilders#fileUpload is deprecated, you'll want to use MockMvcRequestBuilders#multipart(String, Object...) which returns a MockMultipartHttpServletRequestBuilder. Then chain a bunch of file(MockMultipartFile) calls.

Here's a working example. Given a @Controller

@Controller
public class NewController {

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public String saveAuto(
            @RequestPart(value = "json") JsonPojo pojo,
            @RequestParam(value = "some-random") String random,
            @RequestParam(value = "data", required = false) List<MultipartFile> files) {
        System.out.println(random);
        System.out.println(pojo.getJson());
        for (MultipartFile file : files) {
            System.out.println(file.getOriginalFilename());
        }
        return "success";
    }

    static class JsonPojo {
        private String json;

        public String getJson() {
            return json;
        }

        public void setJson(String json) {
            this.json = json;
        }

    }
}

and a unit test

@WebAppConfiguration
@ContextConfiguration(classes = WebConfig.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class Example {

    @Autowired
    private WebApplicationContext webApplicationContext;

    @Test
    public void test() throws Exception {

        MockMultipartFile firstFile = new MockMultipartFile("data", "filename.txt", "text/plain", "some xml".getBytes());
        MockMultipartFile secondFile = new MockMultipartFile("data", "other-file-name.data", "text/plain", "some other type".getBytes());
        MockMultipartFile jsonFile = new MockMultipartFile("json", "", "application/json", "{\"json\": \"someValue\"}".getBytes());

        MockMvc mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
        mockMvc.perform(MockMvcRequestBuilders.multipart("/upload")
                        .file(firstFile)
                        .file(secondFile)
                        .file(jsonFile)
                        .param("some-random", "4"))
                    .andExpect(status().is(200))
                    .andExpect(content().string("success"));
    }
}

And the @Configuration class

@Configuration
@ComponentScan({ "test.controllers" })
@EnableWebMvc
public class WebConfig extends WebMvcConfigurationSupport {
    @Bean
    public MultipartResolver multipartResolver() {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
        return multipartResolver;
    }
}

The test should pass and give you output of

4 // from param
someValue // from json file
filename.txt // from first file
other-file-name.data // from second file

The thing to note is that you are sending the JSON just like any other multipart file, except with a different content type.

How do I assert an Iterable contains elements with a certain property?

Its not especially Hamcrest, but I think it worth to mention here. What I use quite often in Java8 is something like:

assertTrue(myClass.getMyItems().stream().anyMatch(item -> "foo".equals(item.getName())));

(Edited to Rodrigo Manyari's slight improvement. It's a little less verbose. See comments.)

It may be a little bit harder to read, but I like the type and refactoring safety. Its also cool for testing multiple bean properties in combination. e.g. with a java-like && expression in the filter lambda.

How to output in CLI during execution of PHP Unit tests?

You can use PHPunit default way of showing messages to debug your variables inside your test like this:

$this->assertTrue(false,$your_variable);

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0

It was fixed this kind of error after migrate to AndroidX

  • Go to Refactor ---> Migrate to AndroidX

How to get selenium to wait for ajax response?

The code (C#) bellow ensures that the target element is displayed:

        internal static bool ElementIsDisplayed()
        {
          IWebDriver driver = new ChromeDriver();
          driver.Url = "http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp";
          WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
          By locator = By.CssSelector("input[value='csharp']:first-child");
          IWebElement myDynamicElement = wait.Until<IWebElement>((d) =>
          {
            return d.FindElement(locator);
          });
          return myDynamicElement.Displayed;
        }

If the page supports jQuery it can be used the jQuery.active function to ensure that the target element is retrieved after all the ajax calls are finished:

 public static bool ElementIsDisplayed()
    {
        IWebDriver driver = new ChromeDriver();
        driver.Url = "http://www.seleniumhq.org/docs/04_webdriver_advanced.jsp";
        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
        By locator = By.CssSelector("input[value='csharp']:first-child");
        return wait.Until(d => ElementIsDisplayed(d, locator));
    }

    public static bool ElementIsDisplayed(IWebDriver driver, By by)
    {
        try
        {
            if (driver.FindElement(by).Displayed)
            {
                //jQuery is supported.
                if ((bool)((IJavaScriptExecutor)driver).ExecuteScript("return window.$ != undefined"))
                {
                    return (bool)((IJavaScriptExecutor)driver).ExecuteScript("return $.active == 0");
                }
                else
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

Unit Tests not discovered in Visual Studio 2017

For C++:

As there is no special question for C++ tests, but the topic is very much the same, here is what helped me when I had the trouble with test discovery.

If you have only installed Desktop development with C++, then the solution is to also install Universal Windows Platform development with the optional C++ Universal Windows Platform tools. You can select these in the visual studio web installer.

Afterwards, rebuild your test project and the test discovery should work.

Btw, I created the unit test project in VS2017. It might be important, because some users mentioned, that they had discovery issues in projects, that were migrated from VS2015 to VS2017.

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.

How to unit test abstract classes: extend with stubs?

Write a Mock object and use them just for testing. They usually are very very very minimal (inherit from the abstract class) and not more.Then, in your Unit Test you can call the abstract method you want to test.

You should test abstract class that contain some logic like all other classes you have.

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

How to use ArgumentCaptor for stubbing?

Assuming the following method to test:

public boolean doSomething(SomeClass arg);

Mockito documentation says that you should not use captor in this way:

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);
assertThat(argumentCaptor.getValue(), equalTo(expected));

Because you can just use matcher during stubbing:

when(someObject.doSomething(eq(expected))).thenReturn(true);

But verification is a different story. If your test needs to ensure that this method was called with a specific argument, use ArgumentCaptor and this is the case for which it is designed:

ArgumentCaptor<SomeClass> argumentCaptor = ArgumentCaptor.forClass(SomeClass.class);
verify(someObject).doSomething(argumentCaptor.capture());
assertThat(argumentCaptor.getValue(), equalTo(expected));

How to test that no exception is thrown?

If you want to test that whether your test target consumes the exception. Just leave the test as (mock collaborator using jMock2):

@Test
public void consumesAndLogsExceptions() throws Exception {

    context.checking(new Expectations() {
        {
            oneOf(collaborator).doSth();
            will(throwException(new NullPointerException()));
        }
    });

    target.doSth();
 }

The test would pass if your target does consume the exception thrown, otherwise the test would fail.

If you want to test your exception consumption logic, things get more complex. I suggest delegating the consumption to a collaborator which could be mocked. Therefore the test could be:

@Test
public void consumesAndLogsExceptions() throws Exception {
    Exception e = new NullPointerException();
    context.checking(new Expectations() {
        {
            allowing(collaborator).doSth();
            will(throwException(e));

            oneOf(consumer).consume(e);
        }
    });

    target.doSth();
 }

But sometimes it's over-designed if you just want to log it. In this case, this article(http://java.dzone.com/articles/monitoring-declarative-transac, http://blog.novoj.net/2008/09/20/testing-aspect-pointcuts-is-there-an-easy-way/) may help if you insist tdd in this case.

Mocking HttpClient in unit tests

All you need is a test version of HttpMessageHandler class which you pass to HttpClient ctor. The main point is that your test HttpMessageHandler class will have a HttpRequestHandler delegate that the callers can set and simply handle the HttpRequest the way they want.

public class FakeHttpMessageHandler : HttpMessageHandler
    {
        public Func<HttpRequestMessage, CancellationToken, HttpResponseMessage> HttpRequestHandler { get; set; } =
        (r, c) => 
            new HttpResponseMessage
            {
                ReasonPhrase = r.RequestUri.AbsoluteUri,
                StatusCode = HttpStatusCode.OK
            };


        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            return Task.FromResult(HttpRequestHandler(request, cancellationToken));
        }
    }

You can use an instance of this class to create a concrete HttpClient instance. Via the HttpRequestHandler delegate you have full control over outgoing http requests from HttpClient.

How do I generate a stream from a string?

Add this to a static string utility class:

public static Stream ToStream(this string str)
{
    MemoryStream stream = new MemoryStream();
    StreamWriter writer = new StreamWriter(stream);
    writer.Write(str);
    writer.Flush();
    stream.Position = 0;
    return stream;
}

This adds an extension function so you can simply:

using (var stringStream = "My string".ToStream())
{
    // use stringStream
}

Tests not running in Test Explorer

I found that in the project it was not referencing the Microsoft.VisualStudio.QualityTools.UnitTestFramework assembly. Instead, it was referencing Microsoft.VisualStudio.TestPlatform.TestFramework and Microsoft.VisualStudio.TestPlatform.TestFramework.Extensions. When I removed those two references and added the reference to the Microsoft.VisualStudio.QualityTools.UnitTestFramework assembly the tests that were previously marked with the blue exclamation point suddenly became active and started working.

Unit tests not run with wrong assembly

With the right assembly, the tests run

How to set up googleTest as a shared library on Linux

The following method avoids manually messing with the /usr/lib directory while also requiring minimal change in your CMakeLists.txt file. It also lets your package manager cleanly uninstall libgtest-dev.

The idea is that when you get the libgtest-dev package via

sudo apt install libgtest-dev

The source is stored in location /usr/src/googletest

You can simply point your CMakeLists.txt to that directory so that it can find the necessary dependencies

Simply replace FindGTest with add_subdirectory(/usr/src/googletest gtest)

At the end, it should look like this

add_subdirectory(/usr/src/googletest gtest)
target_link_libraries(your_executable gtest)

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

The most common culprit for me has been Visual Studio trying to run the tests using a different architecture than the library it's testing. Unfortunately there are multiple places where it seems this can go wrong.

In VS 2017, try creating a Run Settings file, e.g. Default.runsettings in your test project. If your main lib is x64, the contents should be:

<?xml version="1.0" encoding="utf-8"?>
<RunSettings>
  <RunConfiguration>
    <TargetPlatform>x64</TargetPlatform>
  </RunConfiguration>
</RunSettings>

Then choose this file from Test -> Test Settings -> Select Test Settings File.

Then, under Test -> Test Settings, Default Processor Architecture, choose the correct architecture again.

Be sure to Clean and Build the entire solution. You may need to close and reopen the Test Explorer window. Look for any additional errors in the Output -> Test window, for more clues about incorrect architecture types.

FYI additional Test Settings entries can be found here.

Unit test naming best practices

I should add that the keeping your tests in the same package but in a parallel directory to the source being tested eliminates the bloat of the code once your ready to deploy it without having to do a bunch of exclude patterns.

I personally like the best practices described in "JUnit Pocket Guide" ... it's hard to beat a book written by the co-author of JUnit!

What's the best strategy for unit-testing database-driven applications?

I'm always running tests against an in-memory DB (HSQLDB or Derby) for these reasons:

  • It makes you think which data to keep in your test DB and why. Just hauling your production DB into a test system translates to "I have no idea what I'm doing or why and if something breaks, it wasn't me!!" ;)
  • It makes sure the database can be recreated with little effort in a new place (for example when we need to replicate a bug from production)
  • It helps enormously with the quality of the DDL files.

The in-memory DB is loaded with fresh data once the tests start and after most tests, I invoke ROLLBACK to keep it stable. ALWAYS keep the data in the test DB stable! If the data changes all the time, you can't test.

The data is loaded from SQL, a template DB or a dump/backup. I prefer dumps if they are in a readable format because I can put them in VCS. If that doesn't work, I use a CSV file or XML. If I have to load enormous amounts of data ... I don't. You never have to load enormous amounts of data :) Not for unit tests. Performance tests are another issue and different rules apply.

Using Mockito to test abstract classes

You can achieve this by using a spy (use the latest version of Mockito 1.8+ though).

public abstract class MyAbstract {
  public String concrete() {
    return abstractMethod();
  }
  public abstract String abstractMethod();
}

public class MyAbstractImpl extends MyAbstract {
  public String abstractMethod() {
    return null;
  }
}

// your test code below

MyAbstractImpl abstractImpl = spy(new MyAbstractImpl());
doReturn("Blah").when(abstractImpl).abstractMethod();
assertTrue("Blah".equals(abstractImpl.concrete()));

Using Mockito's generic "any()" method

As I needed to use this feature for my latest project (at one point we updated from 1.10.19), just to keep the users (that are already using the mockito-core version 2.1.0 or greater) up to date, the static methods from the above answers should be taken from ArgumentMatchers class:

import static org.mockito.ArgumentMatchers.isA;
import static org.mockito.ArgumentMatchers.any;

Please keep this in mind if you are planning to keep your Mockito artefacts up to date as possibly starting from version 3, this class may no longer exist:

As per 2.1.0 and above, Javadoc of org.mockito.Matchers states:

Use org.mockito.ArgumentMatchers. This class is now deprecated in order to avoid a name clash with Hamcrest * org.hamcrest.Matchers class. This class will likely be removed in version 3.0.

I have written a little article on mockito wildcards if you're up for further reading.

Why does visual studio 2012 not find my tests?

One issue I've run into repetitively is not running Visual Studio (explicitly) as Administrator on Windows 8+. I tried several of the suggestions listed, but they did not get the unit tests to appear until I ran VS 2013 as Administrator (even though my shortcut is set to open VS that way, either opening the solution file or sometimes clicking the shortcut it doesn't actually open as admin).

How to spyOn a value property (rather than a method) with Jasmine

In February 2017, they merged a PR adding this feature, they released in April 2017.

so to spy on getters/setters you use: const spy = spyOnProperty(myObj, 'myGetterName', 'get'); where myObj is your instance, 'myGetterName' is the name of that one defined in your class as get myGetterName() {} and the third param is the type get or set.

You can use the same assertions that you already use with the spies created with spyOn.

So you can for example:

const spy = spyOnProperty(myObj, 'myGetterName', 'get'); // to stub and return nothing. Just spy and stub.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.returnValue(1); // to stub and return 1 or any value as needed.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.callThrough(); // Call the real thing.

Here's the line in the github source code where this method is available if you are interested.

https://github.com/jasmine/jasmine/blob/7f8f2b5e7a7af70d7f6b629331eb6fe0a7cb9279/src/core/requireInterface.js#L199

Answering the original question, with jasmine 2.6.1, you would:

const spy = spyOnProperty(myObj, 'valueA', 'get').andReturn(1);
expect(myObj.valueA).toBe(1);
expect(spy).toHaveBeenCalled();

Java Project: Failed to load ApplicationContext

I faced this issue, and that is when a Bean (@Bean) was not instantiated properly as it was not given the correct parameters in my test class.

Explain the "setUp" and "tearDown" Python methods used in test cases

You can use these to factor out code common to all tests in the test suite.

If you have a lot of repeated code in your tests, you can make them shorter by moving this code to setUp/tearDown.

You might use this for creating test data (e.g. setting up fakes/mocks), or stubbing out functions with fakes.

If you're doing integration testing, you can use check environmental pre-conditions in setUp, and skip the test if something isn't set up properly.

For example:

class TurretTest(unittest.TestCase):

    def setUp(self):
        self.turret_factory = TurretFactory()
        self.turret = self.turret_factory.CreateTurret()

    def test_turret_is_on_by_default(self):
        self.assertEquals(True, self.turret.is_on())

    def test_turret_turns_can_be_turned_off(self):
        self.turret.turn_off()
        self.assertEquals(False, self.turret.is_on())

JUnit 4 compare Sets

Apache commons to the rescue again.

assertTrue(CollectionUtils.isEqualCollection(coll1, coll2));

Works like a charm. I don't know why but I found that with collections the following assertEquals(coll1, coll2) doesn't always work. In the case where it failed for me I had two collections backed by Sets. Neither hamcrest nor junit would say the collections were equal even though I knew for sure that they were. Using CollectionUtils it works perfectly.

Build Maven Project Without Running Unit Tests

If you call your classes tests Maven seems to run them automatically, at least they did for me. Rename the classes and Maven will just go through to verification without running them.

Best way to test exceptions with Assert to ensure they will be thrown

Mark the test with the ExpectedExceptionAttribute (this is the term in NUnit or MSTest; users of other unit testing frameworks may need to translate).

How do I use Assert to verify that an exception has been thrown?

You can download a package from Nuget using: PM> Install-Package MSTestExtensions that adds Assert.Throws() syntax in the style of nUnit/xUnit to MsTest.

High level instructions: download the assembly and inherit from BaseTest and you can use the Assert.Throws() syntax.

The main method for the Throws implementation looks as follows:

public static void Throws<T>(Action task, string expectedMessage, ExceptionMessageCompareOptions options) where T : Exception
{
    try
    {
        task();
    }
    catch (Exception ex)
    {
        AssertExceptionType<T>(ex);
        AssertExceptionMessage(ex, expectedMessage, options);
        return;
    }

    if (typeof(T).Equals(new Exception().GetType()))
    {
        Assert.Fail("Expected exception but no exception was thrown.");
    }
    else
    {
        Assert.Fail(string.Format("Expected exception of type {0} but no exception was thrown.", typeof(T)));
    }
}

Disclosure: I put together this package.

More Info: http://www.bradoncode.com/blog/2012/01/asserting-exceptions-in-mstest-with.html

Get name of currently executing test in JUnit 4

JUnit 4 does not have any out-of-the-box mechanism for a test case to get it’s own name (including during setup and teardown).

What's the difference between unit tests and integration tests?

A unit test is done in (as far as possible) total isolation.

An integration test is done when the tested object or module is working like it should be, with other bits of code.

How to test the type of a thrown exception in Jest

Further to Peter Danis' post, I just wanted to emphasize the part of his solution involving "[passing] a function into expect(function).toThrow(blank or type of error)".

In Jest, when you test for a case where an error should be thrown, within your expect() wrapping of the function under testing, you need to provide one additional arrow function wrapping layer in order for it to work. I.e.

Wrong (but most people's logical approach):

expect(functionUnderTesting();).toThrow(ErrorTypeOrErrorMessage);

Right:

expect(() => { functionUnderTesting(); }).toThrow(ErrorTypeOrErrorMessage);

It's very strange, but it should make the testing run successfully.

Unit testing with mockito for constructors

You can use PowerMockito

See the example:

Second second = Mockito.mock(Second.class);
whenNew(Second.class).withNoArguments().thenReturn(second);

But re-factoring is better decision.

How to read a text-file resource into Java unit test?

Right to the point :

ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("file/test.xml").getFile());

Create Test Class in IntelliJ

Use @Test annotation on one of the test methods or annotate your test class with @RunWith(JMockit.class) if using jmock. Intellij should identify that as test class & enable navigation. Also make sure junit plugin is enabled.

annotation to make a private method public only for test classes

dp4j has what you need. Essentially all you have to do is add dp4j to your classpath and whenever a method annotated with @Test (JUnit's annotation) calls a method that's private it will work (dp4j will inject the required reflection at compile-time). You may also use dp4j's @TestPrivates annotation to be more explicit.

If you insist on also annotating your private methods you may use Google's @VisibleForTesting annotation.

JUnit Testing private variables?

If you create your test classes in a seperate folder which you then add to your build path,

Then you could make the test class an inner class of the class under test by using package correctly to set the namespace. This gives it access to private fields and methods.

But dont forget to remove the folder from the build path for your release build.

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

Please see Why does the property I want to mock need to be virtual?

You may have to write a wrapper interface or mark the property as virtual/abstract as Moq creates a proxy class that it uses to intercept calls and return your custom values that you put in the .Returns(x) call.

Mockito: InvalidUseOfMatchersException

For my case, the exception was raised because I tried to mock a package-access method. When I changed the method access level from package to protected the exception went away. E.g. inside below Java class,

public class Foo {
    String getName(String id) {
        return mMap.get(id);
    }
}

the method String getName(String id) has to be AT LEAST protected level so that the mocking mechanism (sub-classing) can work.

Assert an object is a specific type

You can use the assertThat method and the Matchers that comes with JUnit.

Take a look at this link that describes a little bit about the JUnit Matchers.

Example:

public class BaseClass {
}

public class SubClass extends BaseClass {
}

Test:

import org.junit.Test;

import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;

/**
 * @author maba, 2012-09-13
 */
public class InstanceOfTest {

    @Test
    public void testInstanceOf() {
        SubClass subClass = new SubClass();
        assertThat(subClass, instanceOf(BaseClass.class));
    }
}

How do I run all Python unit tests in a directory?

This is now possible directly from unittest: unittest.TestLoader.discover.

import unittest
loader = unittest.TestLoader()
start_dir = 'path/to/your/test/files'
suite = loader.discover(start_dir)

runner = unittest.TextTestRunner()
runner.run(suite)

C# "internal" access modifier when doing unit testing

Keep using private by default. If a member shouldn't be exposed beyond that type, it shouldn't be exposed beyond that type, even to within the same project. This keeps things safer and tidier - when you're using the object, it's clearer which methods you're meant to be able to use.

Having said that, I think it's reasonable to make naturally-private methods internal for test purposes sometimes. I prefer that to using reflection, which is refactoring-unfriendly.

One thing to consider might be a "ForTest" suffix:

internal void DoThisForTest(string name)
{
    DoThis(name);
}

private void DoThis(string name)
{
    // Real implementation
}

Then when you're using the class within the same project, it's obvious (now and in the future) that you shouldn't really be using this method - it's only there for test purposes. This is a bit hacky, and not something I do myself, but it's at least worth consideration.

Running unittest with typical test directory structure

You can't import from the parent directory without some voodoo. Here's yet another way that works with at least Python 3.6.

First, have a file test/context.py with the following content:

import sys
import os
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

Then have the following import in the file test/test_antigravity.py:

import unittest
try:
    import context
except ModuleNotFoundError:
    import test.context    
import antigravity

Note that the reason for this try-except clause is that

  • import test.context fails when run with "python test_antigravity.py" and
  • import context fails when run with "python -m unittest" from the new_project directory.

With this trickery they both work.

Now you can run all the test files within test directory with:

$ pwd
/projects/new_project
$ python -m unittest

or run an individual test file with:

$ cd test
$ python test_antigravity

Ok, it's not much prettier than having the content of context.py within test_antigravity.py, but maybe a little. Suggestions are welcome.

What's the best mock framework for Java?

We are heavily using EasyMock and EasyMock Class Extension at work and are pretty happy with it. It basically gives you everything you need. Take a look at the documentation, there's a very nice example which shows you all the features of EasyMock.

Can a unit test project load the target application's app.config file?

If you are using NUnit, take a look at this post. Basically you'll need to have your app.config in the same directory as your .nunit file.

PATH issue with pytest 'ImportError: No module named YadaYadaYada'

conftest solution

The least invasive solution is adding an empty file named conftest.py in the repo/ directory:

$ touch repo/conftest.py

That's it. No need to write custom code for mangling the sys.path or remember to drag PYTHONPATH along, or placing __init__.py into dirs where it doesn't belong (using python -m pytest as suggested in Apteryx's answer is a good solution though!).

The project directory afterwards:

repo
+-- conftest.py
+-- app.py
+-- settings.py
+-- models.py
+-- tests
     +-- test_app.py

Explanation

pytest looks for the conftest modules on test collection to gather custom hooks and fixtures, and in order to import the custom objects from them, pytest adds the parent directory of the conftest.py to the sys.path (in this case the repo directory).

Other project structures

If you have other project structure, place the conftest.py in the package root dir (the one that contains packages but is not a package itself, so does not contain an __init__.py), for example:

repo
+-- conftest.py
+-- spam
¦   +-- __init__.py
¦   +-- bacon.py
¦   +-- egg.py
+-- eggs
¦   +-- __init__.py
¦   +-- sausage.py
+-- tests
     +-- test_bacon.py
     +-- test_egg.py

src layout

Although this approach can be used with the src layout (place conftest.py in the src dir):

repo
+-- src
¦   +-- conftest.py
¦   +-- spam
¦   ¦   +-- __init__.py
¦   ¦   +-- bacon.py
¦   ¦   +-- egg.py
¦   +-- eggs 
¦       +-- __init__.py
¦       +-- sausage.py
+-- tests
     +-- test_bacon.py
     +-- test_egg.py

beware that adding src to PYTHONPATH mitigates the meaning and benefits of the src layout! You will end up with testing the code from repository and not the installed package. If you need to do it, maybe you don't need the src dir at all.

Where to go from here

Of course, conftest modules are not just some files to help the source code discovery; it's where all the project-specific enhancements of the pytest framework and the customization of your test suite happen. pytest has a lot of information on conftest modules scattered throughout their docs; start with conftest.py: local per-directory plugins

Also, SO has an excellent question on conftest modules: In py.test, what is the use of conftest.py files?

Mockito : how to verify method was called on an object created within a method?

Yes, if you really want / need to do it you can use PowerMock. This should be considered a last resort. With PowerMock you can cause it to return a mock from the call to the constructor. Then do the verify on the mock. That said, csturtz's is the "right" answer.

Here is the link to Mock construction of new objects

How to test my servlet using JUnit

First off, in a real application, you would never get database connection info in a servlet; you would configure it in your app server.

There are ways, however, of testing Servlets without having a container running. One is to use mock objects. Spring provides a set of very useful mocks for things like HttpServletRequest, HttpServletResponse, HttpServletSession, etc:

http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/mock/web/package-summary.html

Using these mocks, you could test things like

What happens if username is not in the request?

What happens if username is in the request?

etc

You could then do stuff like:

import static org.junit.Assert.assertEquals;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.Before;
import org.junit.Test;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

public class MyServletTest {
    private MyServlet servlet;
    private MockHttpServletRequest request;
    private MockHttpServletResponse response;

    @Before
    public void setUp() {
        servlet = new MyServlet();
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
    }

    @Test
    public void correctUsernameInRequest() throws ServletException, IOException {
        request.addParameter("username", "scott");
        request.addParameter("password", "tiger");

        servlet.doPost(request, response);

        assertEquals("text/html", response.getContentType());

        // ... etc
    }
}

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.

For that we have provide one setter method for myobj and set the myobj value with mocked object.

class MyClass {
    MyInterface myObj;

    public void abc() {
        myObj.myMethodToBeVerified (new String("a"), new String("b"));
    }

    public void setMyObj(MyInterface obj)
    {
        this.myObj=obj;
    }
}

In our Test class, we have to write below code

class MyClassTest {

MyClass myClass = new MyClass();

    @Mock
    MyInterface myInterface;

    @test
    testAbc() {
        myclass.setMyObj(myInterface); //it is good to have in @before method
        myClass.abc();
        verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
     }
}

How to test enum types?

you can test if have exactly some values, by example:

for(MyBoolean b : MyBoolean.values()) {
    switch(b) {
    case TRUE:
        break;
    case FALSE:
        break;
    default:
        throw new IllegalArgumentException(b.toString());
}

for(String s : new String[]{"TRUE", "FALSE" }) {
    MyBoolean.valueOf(s);
}

If someone removes or adds a value, some of test fails.

Mock functions in Go

Warning: This might inflate executable file size a little bit and cost a little runtime performance. IMO, this would be better if golang has such feature like macro or function decorator.

If you want to mock functions without changing its API, the easiest way is to change the implementation a little bit:

func getPage(url string) string {
  if GetPageMock != nil {
    return GetPageMock()
  }

  // getPage real implementation goes here!
}

func downloader() {
  if GetPageMock != nil {
    return GetPageMock()
  }

  // getPage real implementation goes here!
}

var GetPageMock func(url string) string = nil
var DownloaderMock func() = nil

This way we can actually mock one function out of the others. For more convenient we can provide such mocking boilerplate:

// download.go
func getPage(url string) string {
  if m.GetPageMock != nil {
    return m.GetPageMock()
  }

  // getPage real implementation goes here!
}

func downloader() {
  if m.GetPageMock != nil {
    return m.GetPageMock()
  }

  // getPage real implementation goes here!
}

type MockHandler struct {
  GetPage func(url string) string
  Downloader func()
}

var m *MockHandler = new(MockHandler)

func Mock(handler *MockHandler) {
  m = handler
}

In test file:

// download_test.go
func GetPageMock(url string) string {
  // ...
}

func TestDownloader(t *testing.T) {
  Mock(&MockHandler{
    GetPage: GetPageMock,
  })

  // Test implementation goes here!

  Mock(new(MockHandler)) // Reset mocked functions
}

How to test code dependent on environment variables using JUnit?

The usual solution is to create a class which manages the access to this environmental variable, which you can then mock in your test class.

public class Environment {
    public String getVariable() {
        return System.getenv(); // or whatever
    }
}

public class ServiceTest {
    private static class MockEnvironment {
        public String getVariable() {
           return "foobar";
        }
    }

    @Test public void testService() {
        service.doSomething(new MockEnvironment());
    }
}

The class under test then gets the environment variable using the Environment class, not directly from System.getenv().

How can I write output from a unit test?

Are you sure you're running your unit tests in Debug? Debug.WriteLine won't be called in Release builds.

Two options to try are:

  • Trace.WriteLine(), which is built into release builds as well as debug

  • Undefine DEBUG in your build settings for the unit test

Mockito verify order / sequence of method calls

Note that you can also use the InOrder class to verify that various methods are called in order on a single mock, not just on two or more mocks.

Suppose I have two classes Foo and Bar:

public class Foo {
  public void first() {}
  public void second() {}
}

public class Bar {
  public void firstThenSecond(Foo foo) {
    foo.first();
    foo.second();
  }
}

I can then add a test class to test that Bar's firstThenSecond() method actually calls first(), then second(), and not second(), then first(). See the following test code:

public class BarTest {
  @Test
  public void testFirstThenSecond() {
    Bar bar = new Bar();
    Foo mockFoo = Mockito.mock(Foo.class);
    bar.firstThenSecond(mockFoo);

    InOrder orderVerifier = Mockito.inOrder(mockFoo);
    // These lines will PASS
    orderVerifier.verify(mockFoo).first();
    orderVerifier.verify(mockFoo).second();

    // These lines will FAIL
    // orderVerifier.verify(mockFoo).second();
    // orderVerifier.verify(mockFoo).first();
  }
}

How can I tell Moq to return a Task?

You only need to add .Returns(Task.FromResult(0)); after the Callback.

Example:

mock.Setup(arg => arg.DoSomethingAsync())
    .Callback(() => { <my code here> })
    .Returns(Task.FromResult(0));

'No JUnit tests found' in Eclipse

Any solution didn't work for me until I change the name of the my test method. When name of test method starts with "test" is OK. I am new in android programing and it was for me big surprise.

How to run test methods in specific order in JUnit4?

Its one of the main issue which I faced when I worked on Junit and I came up with following solution which works fine for me:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;

public class OrderedRunner extends BlockJUnit4ClassRunner {

    public OrderedRunner(Class<?> clazz) throws InitializationError {
        super(clazz);
    }

    @Override
    protected List<FrameworkMethod> computeTestMethods() {
        List<FrameworkMethod> list = super.computeTestMethods();
        List<FrameworkMethod> copy = new ArrayList<FrameworkMethod>(list);
        Collections.sort(copy, new Comparator<FrameworkMethod>() {

            @Override
            public int compare(FrameworkMethod f1, FrameworkMethod f2) {
                Order o1 = f1.getAnnotation(Order.class);
                Order o2 = f2.getAnnotation(Order.class);

                if (o1 == null || o2 == null) {
                    return -1;
                }

                return o1.order() - o2.order();
            }
        });
        return copy;
    }
}

also create a interface like below:

 @Retention(RetentionPolicy.RUNTIME)


@Target({ ElementType.METHOD})

public @interface Order {
public int order();
}

Now suppose you have class A where you have written several test cases like below:

(@runWith=OrderRunner.class)
Class A{
@Test
@Order(order = 1)

void method(){

//do something

}

}

So execution will start from method named "method()". Thanks!

How to create unit tests easily in eclipse

You can use my plug-in to create tests easily:

  1. highlight the method
  2. press Ctrl+Alt+Shift+U
  3. it will create the unit test for it.

The plug-in is available here. Hope this helps.

JavaScript unit test tools for TDD

You have "runs on actual browser" as a pro, but in my experience that is a con because it is slow. But what makes it valuable is the lack of sufficient JS emulation from the non-browser alternatives. It could be that if your JS is complex enough that only an in browser test will suffice, but there are a couple more options to consider:

HtmlUnit: "It has fairly good JavaScript support (which is constantly improving) and is able to work even with quite complex AJAX libraries, simulating either Firefox or Internet Explorer depending on the configuration you want to use." If its emulation is good enough for your use then it will be much faster than driving a browser.

But maybe HtmlUnit has good enough JS support but you don't like Java? Then maybe:

Celerity: Watir API running on JRuby backed by HtmlUnit.

or similarly

Schnell: another JRuby wrapper of HtmlUnit.

Of course if HtmlUnit isn't good enough and you have to drive a browser then you might consider Watir to drive your JS.

How to assert two list contain the same elements in Python?

Given

l1 = [a,b]
l2 = [b,a]

In Python >= 3.0

assertCountEqual(l1, l2) # True

In Python >= 2.7, the above function was named:

assertItemsEqual(l1, l2) # True

In Python < 2.7

import unittest2
assertItemsEqual(l1, l2) # True

Via six module (Any Python version)

import unittest
import six
class MyTest(unittest.TestCase):
    def test(self):
        six.assertCountEqual(self, self.l1, self.l2) # True

Visual Studio 2015 or 2017 does not discover unit tests

In Visual Studio 2015(Update 3) if you want to attach the tests in the test explorer then have to install the NUnit Test Adapter.Download the adapter from Tools->Extension And Updates->Online tab(you have to search for the adapter)->Download. By restarting the Visual Studio you can see the change for the test framework.

Unit testing with Spring Security

I asked the same question myself over here, and just posted an answer that I recently found. Short answer is: inject a SecurityContext, and refer to SecurityContextHolder only in your Spring config to obtain the SecurityContext

How to set JVM parameters for Junit Unit Tests?

In IntelliJ you can specify default settings for each run configuration. In Run/Debug configuration dialog (the one you use to configure heap per test) click on Defaults and JUnit. These settings will be automatically applied to each new JUnit test configuration. I guess similar setting exists for Eclipse.

However there is no simple option to transfer such settings (at least in IntelliJ) across environments. You can commit IntelliJ project files to your repository: it might work, but I do not recommend it.

You know how to set these for maven-surefire-plugin. Good. This is the most portable way (see Ptomli's answer for an example).

For the rest - you must remember that JUnit test cases are just a bunch of Java classes, not a standalone program. It is up to the runner (let it be a standalone JUnit runner, your IDE, maven-surefire-plugin to set those options. That being said there is no "portable" way to set them, so that memory settings are applied irrespective to the runner.

To give you an example: you cannot define Xmx parameter when developing a servlet - it is up to the container to define that. You can't say: "this servlet should always be run with Xmx=1G.

Is Unit Testing worth the effort?

Unit Testing is one of the most adopted methodologies for high quality code. Its contribution to a more stable, independent and documented code is well proven . Unit test code is considered and handled as an a integral part of your repository, and as such requires development and maintenance. However, developers often encounter a situation where the resources invested in unit tests where not as fruitful as one would expect. In an ideal world every method we code will have a series of tests covering it’s code and validating it’s correctness. However, usually due to time limitations we either skip some tests or write poor quality ones. In such reality, while keeping in mind the amount of resources invested in unit testing development and maintenance, one must ask himself, given the available time, which code deserve testing the most? And from the existing tests, which tests are actually worth keeping and maintaining? See here

What's the difference between faking, mocking, and stubbing?

Stub - an object that provides predefined answers to method calls.

Mock - an object on which you set expectations.

Fake - an object with limited capabilities (for the purposes of testing), e.g. a fake web service.

Test Double is the general term for stubs, mocks and fakes. But informally, you'll often hear people simply call them mocks.

How should I unit test multithreaded code?

Awaitility can also be useful to help you write deterministic unit tests. It allows you to wait until some state somewhere in your system is updated. For example:

await().untilCall( to(myService).myMethod(), greaterThan(3) );

or

await().atMost(5,SECONDS).until(fieldIn(myObject).ofType(int.class), equalTo(1));

It also has Scala and Groovy support.

await until { something() > 4 } // Scala example

Change default timeout for mocha

By default Mocha will read a file named test/mocha.opts that can contain command line arguments. So you could create such a file that contains:

--timeout 5000

Whenever you run Mocha at the command line, it will read this file and set a timeout of 5 seconds by default.

Another way which may be better depending on your situation is to set it like this in a top level describe call in your test file:

describe("something", function () {
    this.timeout(5000); 

    // tests...
});

This would allow you to set a timeout only on a per-file basis.

You could use both methods if you want a global default of 5000 but set something different for some files.


Note that you cannot generally use an arrow function if you are going to call this.timeout (or access any other member of this that Mocha sets for you). For instance, this will usually not work:

describe("something", () => {
    this.timeout(5000); //will not work

    // tests...
});

This is because an arrow function takes this from the scope the function appears in. Mocha will call the function with a good value for this but that value is not passed inside the arrow function. The documentation for Mocha says on this topic:

Passing arrow functions (“lambdas”) to Mocha is discouraged. Due to the lexical binding of this, such functions are unable to access the Mocha context.

Unit tests vs Functional tests

UNIT TESTING

Unit testing includes testing of smallest unit of code which usually are functions or methods. Unit testing is mostly done by developer of unit/method/function, because they understand the core of a function. The main goal of the developer is to cover code by unit tests.

It has a limitation that some functions cannot be tested through unit tests. Even after the successful completion of all the unit tests; it does not guarantee correct operation of the product. The same function can be used in few parts of the system while the unit test was written only for one usage.

FUNCTIONAL TESTING

It is a type of Black Box testing where testing will be done on the functional aspects of a product without looking into the code. Functional testing is mostly done by a dedicated Software tester. It will include positive, negative and BVA techniques using un standardized data for testing the specified functionality of product. Test coverage is conducted in an improved manner by functional tests than by unit tests. It uses application GUI for testing, so it’s easier to determine what exactly a specific part of the interface is responsible for rather to determine what a code is function responsible for.

How to print to console in pytest?

By default, py.test captures the result of standard out so that it can control how it prints it out. If it didn't do this, it would spew out a lot of text without the context of what test printed that text.

However, if a test fails, it will include a section in the resulting report that shows what was printed to standard out in that particular test.

For example,

def test_good():
    for i in range(1000):
        print(i)

def test_bad():
    print('this should fail!')
    assert False

Results in the following output:

>>> py.test tmp.py
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items

tmp.py .F

=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________

    def test_bad():
        print('this should fail!')
>       assert False
E       assert False

tmp.py:7: AssertionError
------------------------------- Captured stdout --------------------------------
this should fail!
====================== 1 failed, 1 passed in 0.04 seconds ======================

Note the Captured stdout section.

If you would like to see print statements as they are executed, you can pass the -s flag to py.test. However, note that this can sometimes be difficult to parse.

>>> py.test tmp.py -s
============================= test session starts ==============================
platform darwin -- Python 2.7.6 -- py-1.4.20 -- pytest-2.5.2
plugins: cache, cov, pep8, xdist
collected 2 items

tmp.py 0
1
2
3
... and so on ...
997
998
999
.this should fail!
F

=================================== FAILURES ===================================
___________________________________ test_bad ___________________________________

    def test_bad():
        print('this should fail!')
>       assert False
E       assert False

tmp.py:7: AssertionError
====================== 1 failed, 1 passed in 0.02 seconds ======================

Running a single test from unittest.TestCase via the command line

If you organize your test cases, that is, follow the same organization like the actual code and also use relative imports for modules in the same package, you can also use the following command format:

python -m unittest mypkg.tests.test_module.TestClass.test_method

# In your case, this would be:
python -m unittest testMyCase.MyCase.testItIsHot

Python 3 documentation for this: Command-Line Interface

Does Visual Studio have code coverage for unit tests?

For anyone that is looking for an easy solution in Visual Studio Community 2019, Fine Code Coverage is simple but it works well.

It cannot give accurate numbers on the precise coverage, but it will tell which lines are being covered with green/red gutters.

How do you test that a Python function throws an exception?

You can use context manager to run the faulty function and assert it raises the exception with a certain message using assertRaisesMessage

with self.assertRaisesMessage(SomeException,'Some error message e.g 404 Not Found'):
    faulty_funtion()

How to mock static methods in c# using MOQ framework?

Moq (and other DynamicProxy-based mocking frameworks) are unable to mock anything that is not a virtual or abstract method.

Sealed/static classes/methods can only be faked with Profiler API based tools, like Typemock (commercial) or Microsoft Moles (free, known as Fakes in Visual Studio 2012 Ultimate /2013 /2015).

Alternatively, you could refactor your design to abstract calls to static methods, and provide this abstraction to your class via dependency injection. Then you'd not only have a better design, it will be testable with free tools, like Moq.

A common pattern to allow testability can be applied without using any tools altogether. Consider the following method:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = FileUtil.ReadDataFromFile(fileName);
        return data;
    }
}

Instead of trying to mock FileUtil.ReadDataFromFile, you could wrap it in a protected virtual method, like this:

public class MyClass
{
    public string[] GetMyData(string fileName)
    {
        string[] data = GetDataFromFile(fileName);
        return data;
    }

    protected virtual string[] GetDataFromFile(string fileName)
    {
        return FileUtil.ReadDataFromFile(fileName);
    }
}

Then, in your unit test, derive from MyClass and call it TestableMyClass. Then you can override the GetDataFromFile method to return your own test data.

Hope that helps.

Python unittest - opposite of assertRaises?

Hi - I want to write a test to establish that an Exception is not raised in a given circumstance.

That's the default assumption -- exceptions are not raised.

If you say nothing else, that's assumed in every single test.

You don't have to actually write an any assertion for that.

How do I test a private function or a class that has private methods, fields or inner classes?

Today, I pushed a Java library to help testing private methods and fields. It has been designed with Android in mind, but it can really be used for any Java project.

If you got some code with private methods or fields or constructors, you can use BoundBox. It does exactly what you are looking for. Here below is an example of a test that accesses two private fields of an Android activity to test it:

@UiThreadTest
public void testCompute() {

    // Given
    boundBoxOfMainActivity = new BoundBoxOfMainActivity(getActivity());

    // When
    boundBoxOfMainActivity.boundBox_getButtonMain().performClick();

    // Then
    assertEquals("42", boundBoxOfMainActivity.boundBox_getTextViewMain().getText());
}

BoundBox makes it easy to test private/protected fields, methods and constructors. You can even access stuff that is hidden by inheritance. Indeed, BoundBox breaks encapsulation. It will give you access to all that through reflection, BUT everything is checked at compile time.

It is ideal for testing some legacy code. Use it carefully. ;)

https://github.com/stephanenicolas/boundbox

Best practices to test protected methods with PHPUnit

I'd like to propose a slight variation to getMethod() defined in uckelman's answer.

This version changes getMethod() by removing hard-coded values and simplifying usage a little. I recommend adding it to your PHPUnitUtil class as in the example below or to your PHPUnit_Framework_TestCase-extending class (or, I suppose, globally to your PHPUnitUtil file).

Since MyClass is being instantiated anyways and ReflectionClass can take a string or an object...

class PHPUnitUtil {
    /**
     * Get a private or protected method for testing/documentation purposes.
     * How to use for MyClass->foo():
     *      $cls = new MyClass();
     *      $foo = PHPUnitUtil::getPrivateMethod($cls, 'foo');
     *      $foo->invoke($cls, $...);
     * @param object $obj The instantiated instance of your class
     * @param string $name The name of your private/protected method
     * @return ReflectionMethod The method you asked for
     */
    public static function getPrivateMethod($obj, $name) {
      $class = new ReflectionClass($obj);
      $method = $class->getMethod($name);
      $method->setAccessible(true);
      return $method;
    }
    // ... some other functions
}

I also created an alias function getProtectedMethod() to be explicit what is expected, but that one's up to you.

Web scraping with Java

You might look into jwht-scrapper!

This is a complete scrapping framework that has all the features a developper could expect from a web scrapper:

It works with (jwht-htmltopojo)[https://github.com/whimtrip/jwht-htmltopojo) lib which itsef uses Jsoup mentionned by several other people here.

Together they will help you built awesome scrappers mapping directly HTML to POJOs and bypassing any classical scrapping problems in only a matter of minutes!

Hope this might help some people here!

Disclaimer, I am the one who developed it, feel free to let me know your remarks!

How to empty a list?

lst *= 0

has the same effect as

lst[:] = []

It's a little simpler and maybe easier to remember. Other than that there's not much to say

The efficiency seems to be about the same

Proper use of errors

Simple solution to emit and show message by Exception.

try {
  throw new TypeError("Error message");
}
catch (e){
  console.log((<Error>e).message);//conversion to Error type
}

Caution

Above is not a solution if we don't know what kind of error can be emitted from the block. In such cases type guards should be used and proper handling for proper error should be done - take a look on @Moriarty answer.

Using CSS :before and :after pseudo-elements with inline CSS?

No you cant target the pseudo-classes or pseudo-elements in inline-css as David Thomas said. For more details see this answer by BoltClock about Pseudo-classes

No. The style attribute only defines style properties for a given HTML element. Pseudo-classes are a member of the family of selectors, which don't occur in the attribute .....

We can also write use same for the pseudo-elements

No. The style attribute only defines style properties for a given HTML element. Pseudo-classes and pseudo-elements the are a member of the family of selectors, which don't occur in the attribute so you cant style them inline.

Transparent color of Bootstrap-3 Navbar

.navbar {
   background-color: transparent;
   background: transparent;
   border-color: transparent;
}

.navbar li { color: #000 } 

http://bootply.com/106969

How to get the fields in an Object via reflection?

I've an object (basically a VO) in Java and I don't know its type. I need to get values which are not null in that object.

Maybe you don't necessary need reflection for that -- here is a plain OO design that might solve your problem:

  1. Add an interface Validation which expose a method validate which checks the fields and return whatever is appropriate.
  2. Implement the interface and the method for all VO.
  3. When you get a VO, even if it's concrete type is unknown, you can typecast it to Validation and check that easily.

I guess that you need the field that are null to display an error message in a generic way, so that should be enough. Let me know if this doesn't work for you for some reason.

What is the difference between Normalize.css and Reset CSS?

I work on normalize.css.

The main differences are:

  1. Normalize.css preserves useful defaults rather than "unstyling" everything. For example, elements like sup or sub "just work" after including normalize.css (and are actually made more robust) whereas they are visually indistinguishable from normal text after including reset.css. So, normalize.css does not impose a visual starting point (homogeny) upon you. This may not be to everyone's taste. The best thing to do is experiment with both and see which gels with your preferences.

  2. Normalize.css corrects some common bugs that are out of scope for reset.css. It has a wider scope than reset.css, and also provides bug fixes for common problems like: display settings for HTML5 elements, the lack of font inheritance by form elements, correcting font-size rendering for pre, SVG overflow in IE9, and the button styling bug in iOS.

  3. Normalize.css doesn't clutter your dev tools. A common irritation when using reset.css is the large inheritance chain that is displayed in browser CSS debugging tools. This is not such an issue with normalize.css because of the targeted stylings.

  4. Normalize.css is more modular. The project is broken down into relatively independent sections, making it easy for you to potentially remove sections (like the form normalizations) if you know they will never be needed by your website.

  5. Normalize.css has better documentation. The normalize.css code is documented inline as well as more comprehensively in the GitHub Wiki. This means you can find out what each line of code is doing, why it was included, what the differences are between browsers, and more easily run your own tests. The project aims to help educate people on how browsers render elements by default, and make it easier for them to be involved in submitting improvements.

I've written in greater detail about this in an article about normalize.css

How long do browsers cache HTTP 301s?

as answer of @thomasrutter

If you previously issued a 301 redirect but want to un-do that

If people still have the cached 301 redirect in their browser they will continue to be taken to the target page regardless of whether the source page still has the redirect in place. Your options for fixing this include:

The simplest and best solution is to issue another 301 redirect back again.

The browser will realise it is being directed back to what it previously thought was a decommissioned URL, and this should cause it re-fetch that URL again to confirm that the old redirect isn't still there.

If you don't have control over the site where the previous redirect target went to, then you are outta luck. Try and beg the site owner to redirect back to you.

In fact, this means:

  1. a.com 301 to b.com

  2. delete a.com 's 301

  3. add b.com 301 to a.com

Then it works.

Delete last N characters from field in a SQL Server database

I got the answer to my own question, ant this is:

select reverse(stuff(reverse('a,b,c,d,'), 1, N, ''))

Where N is the number of characters to remove. This avoids to write the complex column/string twice

How to check how many letters are in a string in java?

1) To answer your question:

  String s="Java";
  System.out.println(s.length()); 

Using if elif fi in shell scripts

Change [ to [[, and ] to ]].

"Char cannot be dereferenced" error

The type char is a primitive -- not an object -- so it cannot be dereferenced

Dereferencing is the process of accessing the value referred to by a reference. Since a char is already a value (not a reference), it can not be dereferenced.

use Character class:

if(Character.isLetter(c)) {

What is the HTML tabindex attribute?

tabindex is a global attribute responsible for two things:

  1. it sets the order of "focusable" elements and
  2. it makes elements "focusable".

In my mind the second thing is even more important than the first one. There are very few elements that are focusable by default (e.g. <a> and form controls). Developers very often add some JavaScript event handlers (like 'onclick') on not focusable elements (<div>, <span> and so on), and the way to make your interface be responsive not only to mouse events but also to keyboard events (e.g. 'onkeypress') is to make such elements focusable. Lastly, if you don't want to set the order but just make your element focusable use tabindex="0" on all such elements:

<div tabindex="0"></div>

Also, if you don't want it to be focusable via the tab key then use tabindex="-1". For example, the below link will not be focused while using tab keys to traverse.

<a href="#" tabindex="-1">Tab key cannot reach here!</a>

String concatenation in Ruby

You can do that in several ways:

  1. As you shown with << but that is not the usual way
  2. With string interpolation

    source = "#{ROOT_DIR}/#{project}/App.config"
    
  3. with +

    source = "#{ROOT_DIR}/" + project + "/App.config"
    

The second method seems to be more efficient in term of memory/speed from what I've seen (not measured though). All three methods will throw an uninitialized constant error when ROOT_DIR is nil.

When dealing with pathnames, you may want to use File.join to avoid messing up with pathname separator.

In the end, it is a matter of taste.

How can I find out a file's MIME type (Content-Type)?

Use file. Examples:

> file --mime-type image.png
image.png: image/png

> file -b --mime-type image.png
image/png

> file -i FILE_NAME
image.png: image/png; charset=binary

Is it still valid to use IE=edge,chrome=1?

It's still valid to use IE=edge,chrome=1.

But, since the chrome frame project has been wound down the chrome=1 part is redundant for browsers that don't already have the chrome frame plug in installed.

I use the following for correctness nowadays

<meta http-equiv="X-UA-Compatible" content="IE=edge" />

Convert Json String to C# Object List

public static class Helper
{
    public static string AsJsonList<T>(List<T> tt)
    {
        return new JavaScriptSerializer().Serialize(tt);
    }
    public static string AsJson<T>(T t)
    {
        return new JavaScriptSerializer().Serialize(t);
    }
    public static List<T> AsObjectList<T>(string tt)
    {
        return new JavaScriptSerializer().Deserialize<List<T>>(tt);
    }
    public static T AsObject<T>(string t)
    {
        return new JavaScriptSerializer().Deserialize<T>(t);
    }
}

Unrecognized escape sequence for path string containing backslashes

string foo = "D:\\Projects\\Some\\Kind\\Of\\Pathproblem\\wuhoo.xml";

This will work, or the previous examples will, too. @"..." means treat everything between the quote marks literally, so you can do

@"Hello
world"

To include a literal newline. I'm more old school and prefer to escape "\" with "\\"

How to make an unaware datetime timezone aware in python

I agree with the previous answers, and is fine if you are ok to start in UTC. But I think it is also a common scenario for people to work with a tz aware value that has a datetime that has a non UTC local timezone.

If you were to just go by name, one would probably infer replace() will be applicable and produce the right datetime aware object. This is not the case.

the replace( tzinfo=... ) seems to be random in its behaviour. It is therefore useless. Do not use this!

localize is the correct function to use. Example:

localdatetime_aware = tz.localize(datetime_nonaware)

Or a more complete example:

import pytz
from datetime import datetime
pytz.timezone('Australia/Melbourne').localize(datetime.now())

gives me a timezone aware datetime value of the current local time:

datetime.datetime(2017, 11, 3, 7, 44, 51, 908574, tzinfo=<DstTzInfo 'Australia/Melbourne' AEDT+11:00:00 DST>)

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

As answered by @Dark Falcon, I simply dealt with it.

In my case, I am using node.js server, and creating a session if it does not exist. Since the OPTIONS method does not have the session details in it, it ended up creating a new session for every POST method request.

So in my app routine to create-session-if-not-exist, I just added a check to see if method is OPTIONS, and if so, just skip session creating part:

    app.use(function(req, res, next) {
        if (req.method !== "OPTIONS") {
            if (req.session && req.session.id) {
                 // Session exists
                 next();
            }else{
                 // Create session
                 next();
          }
        } else {
           // If request method is OPTIONS, just skip this part and move to the next method.
           next(); 
        }
    }

NuGet Package Restore Not Working

Automatic Package Restore will fail for any of the following reasons:

  1. You did not remove the NuGet.exe and NuGet.targets files from the solution's .nuget folder (which can be found in your solution root folder)
  2. You did not enable automatic package restore from the Tools >> Options >> Nuget Package Manager >> General settings.
  3. You forgot to manually remove references in all your projects to the Nuget.targets file
  4. You need to restart Visual Studio (make sure the process is killed from your task manager before starting up again).

The following article outlines in more detail how to go about points 1-3: https://docs.nuget.org/consume/package-restore/migrating-to-automatic-package-restore

Error: Cannot find module html

Use

res.sendFile()

instead of

res.render().

What your trying to do is send a whole file.

This worked for me.

Shorter syntax for casting from a List<X> to a List<Y>?

In case when X derives from Y you can also use ToList<T> method instead of Cast<T>

listOfX.ToList<Y>()

Ruby objects and JSON serialization (without Rails)

I used to virtus. Really powerful tool, allows to create a dynamic Ruby structure structure based on your specified classes. Easy DSL, possible to create objects from ruby hashes, there is strict mode. Check it out.

Why should you use strncpy instead of strcpy?

strncpy combats buffer overflow by requiring you to put a length in it. strcpy depends on a trailing \0, which may not always occur.

Secondly, why you chose to only copy 5 characters on 7 character string is beyond me, but it's producing expected behavior. It's only copying over the first n characters, where n is the third argument.

The n functions are all used as defensive coding against buffer overflows. Please use them in lieu of older functions, such as strcpy.

How to declare array of zeros in python (or an array of a certain size)

The question says "How to declare array of zeros ..." but then the sample code references the Python list:

buckets = []   # this is a list

However, if someone is actually wanting to initialize an array, I suggest:

from array import array

my_arr = array('I', [0] * count)

The Python purist might claim this is not pythonic and suggest:

my_arr = array('I', (0 for i in range(count)))

The pythonic version is very slow and when you have a few hundred arrays to be initialized with thousands of values, the difference is quite noticeable.

Bootstrap Columns Not Working

Try this:

DEMO

<div class="container-fluid"> <!-- If Needed Left and Right Padding in 'md' and 'lg' screen means use container class -->
            <div class="row">
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#">About</a>
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <img src="image.png" />
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#myModal1" data-toggle="modal">SHARE</a>
                </div>
            </div>
        </div>

When to use Spring Security`s antMatcher()?

I'm updating my answer...

antMatcher() is a method of HttpSecurity, it doesn't have anything to do with authorizeRequests(). Basically, http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

The authorizeRequests().antMatchers() is then used to apply authorization to one or more paths you specify in antMatchers(). Such as permitAll() or hasRole('USER3'). These only get applied if the first http.antMatcher() is matched.

Copy array items into another array

instead of push() function use concat function for IE. example,

var a=a.concat(a,new Array('amin'));

Bootstrap 4 img-circle class not working

In Bootstrap 4 it was renamed to .rounded-circle

Usage :

<div class="col-xs-7">
    <img src="img/gallery2.JPG" class="rounded-circle" alt="HelPic>
</div>

See migration docs from bootstrap.

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The HTTP 502 "Bad Gateway" response is generated when Apache web server does not receive a valid HTTP response from the upstream server, which in this case is your Tomcat web application.

Some reasons why this might happen:

  • Tomcat may have crashed
  • The web application did not respond in time and the request from Apache timed out
  • The Tomcat threads are timing out
  • A network device is blocking the request, perhaps as some sort of connection timeout or DoS attack prevention system

If the problem is related to timeout settings, you may be able to resolve it by investigating the following:

  • ProxyTimeout directive of Apache's mod_proxy
  • Connector config of Apache Tomcat
  • Your network device's manual

How do you get the currently selected <option> in a <select> via JavaScript?

Using the selectedOptions property:

var yourSelect = document.getElementById("your-select-id");
alert(yourSelect.selectedOptions[0].value);

It works in all browsers except Internet Explorer.

Difference between Relative path and absolute path in javascript

Completely relative:

<img src="kitten.png"/>

this is a relative path indeed.

Absolute in all respects:

<img src="http://www.foo.com/images/kitten.png"/>

this is a URL, and it can be seen in some way as an absolute path, but it's not representative for this matter.

The difference between relative and absolute paths is that when using relative paths you take as reference the current working directory while with absolute paths you refer to a certain, well known directory. Relative paths are useful when you make some program that has to use resources from certain folders that can be opened using the working directory as a starting point.

Example of relative paths:

  • image.png, which is the equivalent to .\image.png (in Windows) or ./image.png (anywhere else). The . explicitly specifies that you're expressing a path relative to the current working directory, but this is implied whenever the path doesn't begin at a root directory (designated with a slash), so you don't have to use it necessarily (except in certain contexts where a default directory (or a list of directories to search) will be applied unless you explicitly specify some directory).

  • ..\images\image2.jpg This way you can access resources from directories one step up the folders tree.  The ..\ means you've exited the current folder, entering the directory that contains both the working and images folders.  Again, use \ in Windows and / anywhere else.

Example of absolute paths:

  • D:\documents\something.doc
  • E:\music\good_music.mp3

and so on.

How the single threaded non blocking IO model works in Node.js

Okay, most things should be clear so far... the tricky part is the SQL: if it is not in reality running in another thread or process in it’s entirety, the SQL-execution has to be broken down into individual steps (by an SQL processor made for asynchronous execution!), where the non-blocking ones are executed, and the blocking ones (e.g. the sleep) actually can be transferred to the kernel (as an alarm interrupt/event) and put on the event list for the main loop.

That means, e.g. the interpretation of the SQL, etc. is done immediately, but during the wait (stored as an event to come in the future by the kernel in some kqueue, epoll, ... structure; together with the other IO operations) the main loop can do other things and eventually check if something happened of those IOs and waits.

So, to rephrase it again: the program is never (allowed to get) stuck, sleeping calls are never executed. Their duty is done by the kernel (write something, wait for something to come over the network, waiting for time to elapse) or another thread or process. – The Node process checks if at least one of those duties is finished by the kernel in the only blocking call to the OS once in each event-loop-cycle. That point is reached, when everything non-blocking is done.

Clear? :-)

I don’t know Node. But where does the c.query come from?

jQuery: How to capture the TAB keypress within a Textbox

An important part of using a key down on tab is knowing that tab will always try to do something already, don't forget to "return false" at the end.

Here is what I did. I have a function that runs on .blur and a function that swaps where my form focus is. Basically it adds an input to the end of the form and goes there while running calculations on blur.

$(this).children('input[type=text]').blur(timeEntered).keydown(function (e) {
        var code = e.keyCode || e.which;
        if (code == "9") {
            window.tabPressed = true;
            // Here is the external function you want to call, let your external
            // function handle all your custom code, then return false to
            // prevent the tab button from doing whatever it would naturally do.
            focusShift($(this));
            return false;
        } else {
            window.tabPressed = false;
        }
        // This is the code i want to execute, it might be different than yours
        function focusShift(trigger) {
            var focalPoint = false;
            if (tabPressed == true) {
                console.log($(trigger).parents("td").next("td"));
                focalPoint = $(trigger).parents("td").next("td");

            }
            if (focalPoint) {
                $(focalPoint).trigger("click");
            }
        }
    });

Examples of good gotos in C or C++

Knuth has written a paper "Structured programming with GOTO statements", you can get it e.g. from here. You'll find many examples there.

Getting ssh to execute a command in the background on target machine

You can do it like this...

sudo /home/script.sh -opt1 > /tmp/script.out &

How to generate a Dockerfile from an image?

Update Dec 2018 to BMW's answer

chenzj/dfimage - as described on hub.docker.com regenerates Dockerfile from other images. So you can use it as follows:

docker pull chenzj/dfimage
alias dfimage="docker run -v /var/run/docker.sock:/var/run/docker.sock --rm chenzj/dfimage"
dfimage IMAGE_ID > Dockerfile

Show div #id on click with jQuery

The problem you're having is that the event-handlers are being bound before the elements are present in the DOM, if you wrap the jQuery inside of a $(document).ready() then it should work perfectly well:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").show("slow");
        });

    });

An alternative is to place the <script></script> at the foot of the page, so it's encountered after the DOM has been loaded and ready.

To make the div hide again, once the #music element is clicked, simply use toggle():

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").toggle();
        });
    });

JS Fiddle demo.

And for fading:

$(document).ready(
    function(){
        $("#music").click(function () {
            $("#musicinfo").fadeToggle();
        });
    });

JS Fiddle demo.

HTTP 404 Page Not Found in Web Api hosted in IIS 7.5

Try this webconfg.. replace "NewsApi.dll" with your main dll!


<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\NewsApi.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
    </system.webServer>
  </location>
</configuration>

Build not visible in itunes connect

Building on @sreedeep-kesav's answer (not enough rep to comment), Privacy - Camera Usage Description and Privacy - Photo Library Usage Description can be set by opening your Info.plist file in Xcode and selecting the plus button next to Information Property List:

enter image description here

Go build: "Cannot find package" (even though GOPATH is set)

Edit: since you meant GOPATH, see fasmat's answer (upvoted)

As mentioned in "How do I make go find my package?", you need to put a package xxx in a directory xxx.

See the Go language spec:

package math

A set of files sharing the same PackageName form the implementation of a package.
An implementation may require that all source files for a package inhabit the same directory.

The Code organization mentions:

When building a program that imports the package "widget" the go command looks for src/pkg/widget inside the Go root, and then—if the package source isn't found there—it searches for src/widget inside each workspace in order.

(a "workspace" is a path entry in your GOPATH: that variable can reference multiple paths for your 'src, bin, pkg' to be)


(Original answer)

You also should set GOPATH to ~/go, not GOROOT, as illustrated in "How to Write Go Code".

The Go path is used to resolve import statements. It is implemented by and documented in the go/build package.

The GOPATH environment variable lists places to look for Go code.
On Unix, the value is a colon-separated string.
On Windows, the value is a semicolon-separated string.
On Plan 9, the value is a list.

That is different from GOROOT:

The Go binary distributions assume they will be installed in /usr/local/go (or c:\Go under Windows), but it is possible to install them in a different location.
If you do this, you will need to set the GOROOT environment variable to that directory when using the Go tools.

Replace all occurrences of a String using StringBuilder?

Yes. It is very simple to use String.replaceAll() method:

package com.test;

public class Replace {

    public static void main(String[] args) {
        String input = "Hello World";
        input = input.replaceAll("o", "0");
        System.out.println(input);
    }
}

Output:

Hell0 W0rld

If you really want to use StringBuilder.replace(int start, int end, String str) instead then here you go:

public static void main(String args[]) {
    StringBuilder sb = new StringBuilder("This is a new StringBuilder");

    System.out.println("Before: " + sb);

    String from = "new";
    String to = "replaced";
    sb = sb.replace(sb.indexOf(from), sb.indexOf(from) + from.length(), to);

    System.out.println("After: " + sb);
}

Output:

Before: This is a new StringBuilder
After: This is a replaced StringBuilder

Left function in c#

Just write what you really wanted to know:

fac.GetCachedValue("Auto Print Clinical Warnings").ToLower().StartsWith("y")

It's much simpler than anything with substring.

How do I detect "shift+enter" and generate a new line in Textarea?

Another Solution for detecting Shift+Enter Key with Angular2+

Inside Component.html

<input type="text" (keydown.shift.enter)="newLine($event)">

Inside Component.ts

newLine(event){
      if(event.keyCode==13 && event.shiftKey){
        alert('Shift+Enter key Pressed');
      }
  }

print memory address of Python variable

There is no way to get the memory address of a value in Python 2.7 in general. In Jython or PyPy, the implementation doesn't even know your value's address (and there's not even a guarantee that it will stay in the same place—e.g., the garbage collector is allowed to move it around if it wants).

However, if you only care about CPython, id is already returning the address. If the only issue is how to format that integer in a certain way… it's the same as formatting any integer:

>>> hex(33)
0x21
>>> '{:#010x}'.format(33) # 32-bit
0x00000021
>>> '{:#018x}'.format(33) # 64-bit
0x0000000000000021

… and so on.

However, there's almost never a good reason for this. If you actually need the address of an object, it's presumably to pass it to ctypes or similar, in which case you should use ctypes.addressof or similar.

Zooming MKMapView to fit annotation pins?

Based on answers above you can use universal method to zoom map to fit all annotations and overlays at the same time.

-(MKMapRect)getZoomingRectOnMap:(MKMapView*)map toFitAllOverlays:(BOOL)overlays andAnnotations:(BOOL)annotations includeUserLocation:(BOOL)userLocation {
    if (!map) {
        return MKMapRectNull;
    }

    NSMutableArray* overlaysAndAnnotationsCoordinateArray = [[NSMutableArray alloc]init];        
    if (overlays) {
        for (id <MKOverlay> overlay in map.overlays) {
            MKMapPoint overlayPoint = MKMapPointForCoordinate(overlay.coordinate);
            NSArray* coordinate = @[[NSNumber numberWithDouble:overlayPoint.x], [NSNumber numberWithDouble:overlayPoint.y]];
            [overlaysAndAnnotationsCoordinateArray addObject:coordinate];
        }
    }

    if (annotations) {
        for (id <MKAnnotation> annotation in map.annotations) {
            MKMapPoint annotationPoint = MKMapPointForCoordinate(annotation.coordinate);
            NSArray* coordinate = @[[NSNumber numberWithDouble:annotationPoint.x], [NSNumber numberWithDouble:annotationPoint.y]];
            [overlaysAndAnnotationsCoordinateArray addObject:coordinate];
        }
    }

    MKMapRect zoomRect = MKMapRectNull;
    if (userLocation) {
        MKMapPoint annotationPoint = MKMapPointForCoordinate(map.userLocation.coordinate);
        zoomRect = MKMapRectMake(annotationPoint.x, annotationPoint.y, 0.1, 0.1);
    }

    for (NSArray* coordinate in overlaysAndAnnotationsCoordinateArray) {
        MKMapRect pointRect = MKMapRectMake([coordinate[0] doubleValue], [coordinate[1] doubleValue], 0.1, 0.1);
        zoomRect = MKMapRectUnion(zoomRect, pointRect);
    }

    return zoomRect;
}

And then:

MKMapRect mapRect = [self getZoomingRectOnMap:mapView toFitAllOverlays:YES andAnnotations:YES includeUserLocation:NO];
[mapView setVisibleMapRect:mapRect edgePadding:UIEdgeInsetsMake(10.0, 10.0, 10.0, 10.0) animated:YES];

What does the 'L' in front a string mean in C++?

L is a prefix used for wide strings. Each character uses several bytes (depending on the size of wchar_t). The encoding used is independent from this prefix. I mean it must not be necessarily UTF-16 unlike stated in other answers here.

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

You can also add -oHostKeyAlgorithms=+ssh-dss in your ssh line:

ssh -oHostKeyAlgorithms=+ssh-dss user@host

Powershell script does not run via Scheduled Tasks

I had very similar issue, i was keeping the VSC window with powershell script all the time when running the schedule task manually. Just closed it and it started working as expected.

live output from subprocess command

import os

def execute(cmd, callback):
    for line in iter(os.popen(cmd).readline, ''): 
            callback(line[:-1])

execute('ls -a', print)

How to check if a column exists in a datatable

It is much more accurate to use IndexOf:

If dt.Columns.IndexOf("ColumnName") = -1 Then
    'Column not exist
End If

If the Contains is used it would not differentiate between ColumName and ColumnName2.

How to scroll the page when a modal dialog is longer than the screen?

I wanted to add my pure CSS answer to this problem of modals with dynamic width and height. The following code also works with the following requirements:

  1. Place modal in center of screen
  2. If modal is higher than viewport, scroll dimmer (not modal content)

HTML:

<div class="modal">
    <div class="modal__content">
        (Long) Content
    </div>
</div>

CSS/LESS:

.modal {
    position: fixed;
    display: flex;
    align-items: center;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    padding: @qquad;
    overflow-y: auto;
    background: rgba(0, 0, 0, 0.7);
    z-index: @zindex-modal;

    &__content {
        width: 900px;
        margin: auto;
        max-width: 90%;
        padding: @quad;
        background: white;
        box-shadow: 0 0 5px 0 rgba(0, 0, 0, 0.75);
    }
}

This way the modal is always within the viewport. The width and height of the modal are as flexible as you like. I removed my close icon from this for simplicity.

Correct syntax to compare values in JSTL <c:if test="${values.type}=='object'">

The comparison needs to be evaluated fully inside EL ${ ... }, not outside.

<c:if test="${values.type eq 'object'}">

As to the docs, those ${} things are not JSTL, but EL (Expression Language) which is a whole subject at its own. JSTL (as every other JSP taglib) is just utilizing it. You can find some more EL examples here.

<c:if test="#{bean.booleanValue}" />
<c:if test="#{bean.intValue gt 10}" />
<c:if test="#{bean.objectValue eq null}" />
<c:if test="#{bean.stringValue ne 'someValue'}" />
<c:if test="#{not empty bean.collectionValue}" />
<c:if test="#{not bean.booleanValue and bean.intValue ne 0}" />
<c:if test="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

See also:


By the way, unrelated to the concrete problem, if I guess your intent right, you could also just call Object#getClass() and then Class#getSimpleName() instead of adding a custom getter.

<c:forEach items="${list}" var="value">
    <c:if test="${value['class'].simpleName eq 'Object'}">
        <!-- code here -->
    </c:if>
</c:forEeach>

See also:

phpMyAdmin + CentOS 6.0 - Forbidden

None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:

Edit file phpMyAdmin.conf

sudo nano /etc/httpd/conf.d/phpMyAdmin.conf

And replace this at the top:

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
     <RequireAny>
       #Require ip 127.0.0.1
       #Require ip ::1
       Require all granted
     </RequireAny>
   </IfModule>
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     Deny from All
     Allow from 127.0.0.1
     Allow from ::1
   </IfModule>
</Directory>

Querying Windows Active Directory server using ldapsearch from command line

The short answer is "yes". A sample ldapsearch command to query an Active Directory server is:

ldapsearch \
    -x -h ldapserver.mydomain.com \
    -D "[email protected]" \
    -W \
    -b "cn=users,dc=mydomain,dc=com" \
    -s sub "(cn=*)" cn mail sn

This would connect to an AD server at hostname ldapserver.mydomain.com as user [email protected], prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com subtree.

See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.

Convert a file path to Uri in Android

Below code works fine before 18 API :-

public String getRealPathFromURI(Uri contentUri) {

        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery( contentUri,
                        proj, // Which columns to return
                        null,       // WHERE clause; which rows to return (all rows)
                        null,       // WHERE clause selection arguments (none)
                        null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
}

below code use on kitkat :-

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

see below link for more info:-

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

How to hide a status bar in iOS?

Well the easiest way that I do it is by typing the following into the .m file.

- (BOOL) prefersStatusBarHidden
{
    return YES;
}

This should work!

Disable back button in android

Try this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
 if (keyCode == KeyEvent.KEYCODE_BACK) {

   return true;
 }
   return super.onKeyDown(keyCode, event);    
}

Private pages for a private Github repo

Jan. 2021: this is now possible for GitHub Enterprise (so: not yet for github.com).
See:

Access control for GitHub Pages

GitHub Pages now gives you the option to limit access, making the site visible only to users with access to the repository that published the Page.

With access control, you can use GitHub Pages to publish and share internal documentation and knowledge across your enterprise.

As part of this release, we are introducing the following capabilities:

  • Repo admins can select whether GitHub Pages sites are publicly visible or limited to users who have access to the repository.
  • Both private and internal repositories support private visibility. With an internal repository, everyone in your enterprise will be able to view the Page with the same credentials they use to login to github.com
  • Org admins can configure the visibility options that members will be able to select for their Page. For example, you can enforce that your members can only publish content privately.

This feature is generally available today on GitHub Enterprise Cloud.
To enable access control on Pages, navigate to your repository settings, and click the dropdown menu to toggle between public and private visibility for your site.

Private publishing for GitHub Pages -- https://i2.wp.com/user-images.githubusercontent.com/55514721/101868473-46f81880-3b32-11eb-9708-a8537f41adaf.png?ssl=1

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.

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

my problem was with @WebServelet annotation and it was because of the name was repeated, I had two of @WebServlet("/route")in my code by mistake(I copy and pasted and forgot to change the route name)

Why does Java's hashCode() in String use 31 as a multiplier?

On (mostly) old processors, multiplying by 31 can be relatively cheap. On an ARM, for instance, it is only one instruction:

RSB       r1, r0, r0, ASL #5    ; r1 := - r0 + (r0<<5)

Most other processors would require a separate shift and subtract instruction. However, if your multiplier is slow this is still a win. Modern processors tend to have fast multipliers so it doesn't make much difference, so long as 32 goes on the correct side.

It's not a great hash algorithm, but it's good enough and better than the 1.0 code (and very much better than the 1.0 spec!).

Using routes in Express-js

The route-map express example matches url paths with objects which in turn matches http verbs with functions. This lays the routing out in a tree, which is concise and easy to read. The apps's entities are also written as objects with the functions as enclosed methods.

var express = require('../../lib/express')
  , verbose = process.env.NODE_ENV != 'test'
  , app = module.exports = express();

app.map = function(a, route){
  route = route || '';
  for (var key in a) {
    switch (typeof a[key]) {
      // { '/path': { ... }}
      case 'object':
        app.map(a[key], route + key);
        break;
      // get: function(){ ... }
      case 'function':
        if (verbose) console.log('%s %s', key, route);
        app[key](route, a[key]);
        break;
    }
  }
};

var users = {
  list: function(req, res){
    res.send('user list');
  },

  get: function(req, res){
    res.send('user ' + req.params.uid);
  },

  del: function(req, res){
    res.send('delete users');
  }
};

var pets = {
  list: function(req, res){
    res.send('user ' + req.params.uid + '\'s pets');
  },

  del: function(req, res){
    res.send('delete ' + req.params.uid + '\'s pet ' + req.params.pid);
  }
};

app.map({
  '/users': {
    get: users.list,
    del: users.del,
    '/:uid': {
      get: users.get,
      '/pets': {
        get: pets.list,
        '/:pid': {
          del: pets.del
        }
      }
    }
  }
});

app.listen(3000);

How do I center content in a div using CSS?

To align horizontally it's pretty straight forward:

    <style type="text/css"> 
body  {
    margin: 0; 
    padding: 0;
    text-align: center;
}
.bodyclass #container { 
    width: ???px; /*SET your width here*/
    margin: 0 auto;
    text-align: left;
} 
</style>
<body class="bodyclass ">
<div id="container">type your content here</div>
</body>

and for vertical align, it's a bit tricky: here's the source

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
  <title>Universal vertical center with CSS</title>
  <style>
    .greenBorder {border: 1px solid green;} /* just borders to see it */
  </style>
</head>

<body>
  <div class="greenBorder" style="display: table; height: 400px; #position: relative; overflow: hidden;">
    <div style=" #position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
      <div class="greenBorder" style=" #position: relative; #top: -50%">
        any text<br>
        any height<br>
        any content, for example generated from DB<br>
        everything is vertically centered
      </div>
    </div>
  </div>
</body>
</html>

Difference between os.getenv and os.environ.get

In Python 2.7 with iPython:

>>> import os
>>> os.getenv??
Signature: os.getenv(key, default=None)
Source:
def getenv(key, default=None):
    """Get an environment variable, return None if it doesn't exist.
    The optional second argument can specify an alternate default."""
    return environ.get(key, default)
File:      ~/venv/lib/python2.7/os.py
Type:      function

So we can conclude os.getenv is just a simple wrapper around os.environ.get.

(Excel) Conditional Formatting based on Adjacent Cell Value

You need to take out the $ signs before the row numbers in the formula....and the row number used in the formula should correspond to the first row of data, so if you are applying this to the ("applies to") range $B$2:$B$5 it must be this formula

=$B2>$C2

by using that "relative" version rather than your "absolute" one Excel (implicitly) adjusts the formula for each row in the range, as if you were copying the formula down

How to set tint for an image view programmatically in android?

Better simplified extension function thanks to ADev

fun ImageView.setTint(@ColorRes colorRes: Int) {
    ImageViewCompat.setImageTintList(this, ColorStateList.valueOf(ContextCompat.getColor(context, colorRes)))
}

Usage:-

imageView.setTint(R.color.tintColor)

Is HTML considered a programming language?

List it under technologies or something. I'd just leave it off if I were you as it's pretty much expected that you know HTML and XML at this point.

Download JSON object as a file from browser

If you prefer console snippet, raser, than filename, you can do this:

window.open(URL.createObjectURL(
    new Blob([JSON.stringify(JSON)], {
      type: 'application/binary'}
    )
))

Can you have if-then-else logic in SQL?

The CASE statement is the closest to an IF statement in SQL, and is supported on all versions of SQL Server:

SELECT CASE <variable> 
           WHEN <value>      THEN <returnvalue> 
           WHEN <othervalue> THEN <returnthis> 
           ELSE <returndefaultcase> 
       END 
  FROM <table> 

Failed to connect to mailserver at "localhost" port 25

For sending mails using php mail function is used. But mail function requires SMTP server for sending emails. we need to mention SMTP host and SMTP port in php.ini file. Upon successful configuration of SMTP server mails will be sent successfully sent through php scripts.

The import org.apache.commons cannot be resolved in eclipse juno

Look for "poi-3.17.jar"!!!

  1. Download from "https://poi.apache.org/download.html".
  2. Click the one Binary Distribution -> poi-bin-3.17-20170915.tar.gz
  3. Unzip the file download and look for this "poi-3.17.jar".

Problem solved and errors disappeared.

The module ".dll" was loaded but the entry-point was not found

I had this problem and

dumpbin /exports mydll.dll

and

depends mydll.dll

showed 'DllRegisterServer'.

The problem was that there was another DLL in the system that had the same name. After renaming mydll the registration succeeded.

Border around tr element doesn't show?

Add this to the stylesheet:

table {
  border-collapse: collapse;
}

JSFiddle.

The reason why it behaves this way is actually described pretty well in the specification:

There are two distinct models for setting borders on table cells in CSS. One is most suitable for so-called separated borders around individual cells, the other is suitable for borders that are continuous from one end of the table to the other.

... and later, for collapse setting:

In the collapsing border model, it is possible to specify borders that surround all or part of a cell, row, row group, column, and column group.

PreparedStatement with list of parameters in a IN clause

You might want to check this link:

http://www.javaranch.com/journal/200510/Journal200510.jsp#a2

It explains the pros and cons of different methods of creating PreparedStatement with in clause.

EDIT:

An obvious approach is to dynamically generate the '?' part at runtime, but I don't want to merely suggest just this approach because depending on the way you use it, it might be inefficient (since the PreparedStatement will need to be 'compiled' every time it gets used)

Java naming convention for static final variables

These variables are constants, i.e. private static final whether they're named in all caps or not. The all-caps convention simply makes it more obvious that these variables are meant to be constants, but it isn't required. I've seen

private static final Logger log = Logger.getLogger(MyClass.class);

in lowercase before, and I'm fine with it because I know to only use the logger to log messages, but it does violate the convention. You could argue that naming it log is a sub-convention, I suppose. But in general, naming constants in uppercase isn't the One Right Way, but it is The Best Way.

How to get POSTed JSON in Flask?

For all those whose issue was from the ajax call, here is a full example :

Ajax call : the key here is to use a dict and then JSON.stringify

    var dict = {username : "username" , password:"password"};

    $.ajax({
        type: "POST", 
        url: "http://127.0.0.1:5000/", //localhost Flask
        data : JSON.stringify(dict),
        contentType: "application/json",
    });

And on server side :

from flask import Flask
from flask import request
import json

app = Flask(__name__)

@app.route("/",  methods = ['POST'])
def hello():
    print(request.get_json())
    return json.dumps({'success':True}), 200, {'ContentType':'application/json'} 

if __name__ == "__main__":
    app.run()

How to reset the state of a Redux store?

You can null the reducers' data by adding this code to action file,

import all types first:

import * as types from './types';

add this code to logout action

for(let key of Object.values(types)) {
        dispatch({ type: key, payload: [] });
    }

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_

ImportError: No module named win32com.client

I realize this post is old but I wanted to add that I had to take an extra step to get this to work.

Instead of just doing:

pip install pywin32

I had use use the -m flag to get this to work properly. Without it I was running into an issue where I was still getting the error ImportError: No module named win32com.

So to fix this you can give this a try:

python -m pip install pywin32

This worked for me and has worked on several version of python where just doing pip install pywin32 did not work.

Versions tested on:

3.6.2, 3.7.6, 3.8.0, 3.9.0a1.

How to call a function, PostgreSQL

For Postgresql you can use PERFORM. PERFORM is only valid within PL/PgSQL procedure language.

DO $$ BEGIN
    PERFORM "saveUser"(3, 'asd','asd','asd','asd','asd');
END $$;

The suggestion from the postgres team:

HINT: If you want to discard the results of a SELECT, use PERFORM instead.

How to run wget inside Ubuntu Docker image?

You need to install it first. Create a new Dockerfile, and install wget in it:

FROM ubuntu:14.04
RUN  apt-get update \
  && apt-get install -y wget \
  && rm -rf /var/lib/apt/lists/*

Then, build that image:

docker build -t my-ubuntu .

Finally, run it:

docker run my-ubuntu wget https://downloads-packages.s3.amazonaws.com/ubuntu-14.04/gitlab_7.8.2-omnibus.1-1_amd64.deb

How to change css property using javascript

Use document.getElementsByClassName('className').style = your_style.

var d = document.getElementsByClassName("left1");
d.className = d.className + " otherclass";

Use single quotes for JS strings contained within an html attribute's double quotes

Example

<div class="somelclass"></div>

then document.getElementsByClassName('someclass').style = "NewclassName";

<div class='someclass'></div>

then document.getElementsByClassName("someclass").style = "NewclassName";

This is personal experience.

One liner to check if element is in the list

 public class Itemfound{ 
        public static void main(String args[]){

                if( Arrays.asList("a","b","c").contains("a"){
                      System.out.println("It is here");
         }
    }

}

This is what you looking for. The contains() method simply checks the index of element in the list. If the index is greater than '0' than element is present in the list.

public boolean contains(Object o) {
return indexOf(o) >= 0;
}

Export pictures from excel file into jpg using VBA

If i remember correctly, you need to use the "Shapes" property of your sheet.

Each Shape object has a TopLeftCell and BottomRightCell attributes that tell you the position of the image.

Here's a piece of code i used a while ago, roughly adapted to your needs. I don't remember the specifics about all those ChartObjects and whatnot, but here it is:

For Each oShape In ActiveSheet.Shapes
    strImageName = ActiveSheet.Cells(oShape.TopLeftCell.Row, 1).Value
    oShape.Select
    'Picture format initialization
    Selection.ShapeRange.PictureFormat.Contrast = 0.5: Selection.ShapeRange.PictureFormat.Brightness = 0.5: Selection.ShapeRange.PictureFormat.ColorType = msoPictureAutomatic: Selection.ShapeRange.PictureFormat.TransparentBackground = msoFalse: Selection.ShapeRange.Fill.Visible = msoFalse: Selection.ShapeRange.Line.Visible = msoFalse: Selection.ShapeRange.Rotation = 0#: Selection.ShapeRange.PictureFormat.CropLeft = 0#: Selection.ShapeRange.PictureFormat.CropRight = 0#: Selection.ShapeRange.PictureFormat.CropTop = 0#: Selection.ShapeRange.PictureFormat.CropBottom = 0#: Selection.ShapeRange.ScaleHeight 1#, msoTrue, msoScaleFromTopLeft: Selection.ShapeRange.ScaleWidth 1#, msoTrue, msoScaleFromTopLeft
    '/Picture format initialization
    Application.Selection.CopyPicture
    Set oDia = ActiveSheet.ChartObjects.Add(0, 0, oShape.Width, oShape.Height)
    Set oChartArea = oDia.Chart
    oDia.Activate
    With oChartArea
        .ChartArea.Select
        .Paste
        .Export ("H:\Webshop_Zpider\Strukturbildene\" & strImageName & ".jpg")
    End With
    oDia.Delete 'oChartArea.Delete
Next

How to enable native resolution for apps on iPhone 6 and 6 Plus?

Note that iPhone 6 will use the 320pt (640px) resolution if you have enabled the 'Display Zoom' in iPhone > Settings > Display & Brightness > View.

Removing a model in rails (reverse of "rails g model Title...")

  1. To remove migration (if you already migrated the migration)

    rake db:migrate:down VERSION="20130417185845" #Your migration version
    
  2. To remove Model

    rails d model name  #name => Your model name
    

An example of how to use getopts in bash

#!/bin/bash

usage() { echo "Usage: $0 [-s <45|90>] [-p <string>]" 1>&2; exit 1; }

while getopts ":s:p:" o; do
    case "${o}" in
        s)
            s=${OPTARG}
            ((s == 45 || s == 90)) || usage
            ;;
        p)
            p=${OPTARG}
            ;;
        *)
            usage
            ;;
    esac
done
shift $((OPTIND-1))

if [ -z "${s}" ] || [ -z "${p}" ]; then
    usage
fi

echo "s = ${s}"
echo "p = ${p}"

Example runs:

$ ./myscript.sh
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -h
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s "" -p ""
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 10 -p foo
Usage: ./myscript.sh [-s <45|90>] [-p <string>]

$ ./myscript.sh -s 45 -p foo
s = 45
p = foo

$ ./myscript.sh -s 90 -p bar
s = 90
p = bar

What does it mean to bind a multicast (UDP) socket?

To bind a UDP socket when receiving multicast means to specify an address and port from which to receive data (NOT a local interface, as is the case for TCP acceptor bind). The address specified in this case has a filtering role, i.e. the socket will only receive datagrams sent to that multicast address & port, no matter what groups are subsequently joined by the socket. This explains why when binding to INADDR_ANY (0.0.0.0) I received datagrams sent to my multicast group, whereas when binding to any of the local interfaces I did not receive anything, even though the datagrams were being sent on the network to which that interface corresponded.

Quoting from UNIX® Network Programming Volume 1, Third Edition: The Sockets Networking API by W.R Stevens. 21.10. Sending and Receiving

[...] We want the receiving socket to bind the multicast group and port, say 239.255.1.2 port 8888. (Recall that we could just bind the wildcard IP address and port 8888, but binding the multicast address prevents the socket from receiving any other datagrams that might arrive destined for port 8888.) We then want the receiving socket to join the multicast group. The sending socket will send datagrams to this same multicast address and port, say 239.255.1.2 port 8888.

Figure out size of UILabel based on String in Swift

For multiline text this answer is not working correctly. You can build a different String extension by using UILabel

extension String {
func height(constraintedWidth width: CGFloat, font: UIFont) -> CGFloat {
    let label =  UILabel(frame: CGRect(x: 0, y: 0, width: width, height: .greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.text = self
    label.font = font
    label.sizeToFit()

    return label.frame.height
 }
}

The UILabel gets a fixed width and the .numberOfLines is set to 0. By adding the text and calling .sizeToFit() it automatically adjusts to the correct height.

Code is written in Swift 3

How to change column order in a table using sql query in sql server 2005?

You have to explicitly list the fields in the order you want them to be returned instead of using * for the 'default' order.

original query:

select * from foobar

returns

foo bar
--- ---
  1   2

now write

select bar, foo from foobar

bar foo
--- ---
  2   1

No connection could be made because the target machine actively refused it (PHP / WAMP)

Just Go to your Control-panel and start Apache & MySQL Services.

What happens to C# Dictionary<int, int> lookup if the key does not exist?

You should probably use:

if(myDictionary.ContainsKey(someInt))
{
  // do something
}

The reason why you can't check for null is that the key here is a value type.

Is it possible to disable scrolling on a ViewPager

New class ViewPager2 from androidx allows to disable scrolling with method setUserInputEnabled(false)

private val pager: ViewPager2 by bindView(R.id.pager)

override fun onCreate(savedInstanceState: Bundle?) {
    pager.isUserInputEnabled = false
}

add item in array list of android

you can use this add string to list on a button click

final String a[]={"hello","world"};
final ArrayAdapter<String> at=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a);
final ListView sp=(ListView)findViewById(R.id.listView1);
sp.setAdapter(at);
final EditText et=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() 
        {

            @Override
            public void onClick(View v) 
            {
                // TODO Auto-generated method stub
                int k=sp.getCount();
                String a1[]=new String[k+1];
                for(int i=0;i<k;i++)
                    a1[i]=sp.getItemAtPosition(i).toString();
                a1[k]=et.getText().toString();
                ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
                sp.setAdapter(ats);
            }
        });

So on a button click it will get string from edittext and store in listitem. you can change this to your needs.

How can I verify if a Windows Service is running

I guess something like this would work:

Add System.ServiceProcess to your project references (It's on the .NET tab).

using System.ServiceProcess;

ServiceController sc = new ServiceController(SERVICENAME);

switch (sc.Status)
{
    case ServiceControllerStatus.Running:
        return "Running";
    case ServiceControllerStatus.Stopped:
        return "Stopped";
    case ServiceControllerStatus.Paused:
        return "Paused";
    case ServiceControllerStatus.StopPending:
        return "Stopping";
    case ServiceControllerStatus.StartPending:
        return "Starting";
    default:
        return "Status Changing";
}

Edit: There is also a method sc.WaitforStatus() that takes a desired status and a timeout, never used it but it may suit your needs.

Edit: Once you get the status, to get the status again you will need to call sc.Refresh() first.

Reference: ServiceController object in .NET.

Window.Open with PDF stream instead of PDF location

It looks like window.open will take a Data URI as the location parameter.

So you can open it like this from the question: Opening PDF String in new window with javascript:

window.open("data:application/pdf;base64, " + base64EncodedPDF);

Here's an runnable example in plunker, and sample pdf file that's already base64 encoded.

Then on the server, you can convert the byte array to base64 encoding like this:

string fileName = @"C:\TEMP\TEST.pdf";
byte[] pdfByteArray = System.IO.File.ReadAllBytes(fileName);
string base64EncodedPDF = System.Convert.ToBase64String(pdfByteArray);

NOTE: This seems difficult to implement in IE because the URL length is prohibitively small for sending an entire PDF.

Sequelize.js delete query?

Sequelize methods return promises, and there is no delete() method. Sequelize uses destroy() instead.

Example

Model.destroy({
  where: {
    some_field: {
      //any selection operation
      // for example [Op.lte]:new Date()
    }
  }
}).then(result => {
  //some operation
}).catch(error => {
  console.log(error)
})

Documentation for more details: https://www.codota.com/code/javascript/functions/sequelize/Model/destroy

PHP mPDF save file as PDF

The Go trough this link state that the first argument of Output() is the file path, second is the saving mode - you need to set it to 'F'.

 $upload_dir = public_path(); 
             $filename = $upload_dir.'/testing7.pdf'; 
              $mpdf = new \Mpdf\Mpdf();
              //$test = $mpdf->Image($pro_image, 0, 0, 50, 50);

              $html ='<h1> Project Heading </h1>';
              $mail = ' <p> Project Heading </p> ';
              
              $mpdf->autoScriptToLang = true;
              $mpdf->autoLangToFont = true;
              $mpdf->WriteHTML($mail);

              $mpdf->Output($filename,'F'); 
              $mpdf->debug = true;

Example :

 $mpdf->Output($filename,'F');

Example #2

$mpdf = new \Mpdf\Mpdf();
$mpdf->WriteHTML('Hello World');

// Saves file on the server as 'filename.pdf'
$mpdf->Output('filename.pdf', \Mpdf\Output\Destination::FILE);

Attach IntelliJ IDEA debugger to a running Java process

Also, don't forget you need to add "-Xdebug" flag in app JAVA_OPTS if you want connect in debug mode.

How to set a variable to current date and date-1 in linux?

You can try:

#!/bin/bash
d=$(date +%Y-%m-%d)
echo "$d"

EDIT: Changed y to Y for 4 digit date as per QuantumFool's comment.

What Are The Best Width Ranges for Media Queries

Try this one with retina display

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
/* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
/* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
/* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
/* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
/* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
/* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
/* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
/* Styles */
}

/* iPhone 4 ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
/* Styles */
}

Update

/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen and (min-width: 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen and (max-width: 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) {
  /* Styles */
}

/* iPad 3 (landscape) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPad 3 (portrait) ----------- */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen and (min-width: 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen and (min-width: 1824px) {
  /* Styles */
}

/* iPhone 4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: landscape) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (orientation: portrait) and (-webkit-min-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 5 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 568px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (landscape) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6 (portrait) ----------- */
@media only screen and (min-device-width: 375px) and (max-device-height: 667px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (landscape) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ (portrait) ----------- */
@media only screen and (min-device-width: 414px) and (max-device-height: 736px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S3 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* Samsung Galaxy S4 (landscape) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S4 (portrait) ----------- */
@media only screen and (min-device-width: 320px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (landscape) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: landscape) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

/* Samsung Galaxy S5 (portrait) ----------- */
@media only screen and (min-device-width: 360px) and (max-device-height: 640px) and (orientation: portrait) and (-webkit-device-pixel-ratio: 3) {
  /* Styles */
}

How to create a new file in unix?

Try > workdirectory/filename.txt

This would:

  • truncate the file if it exists
  • create if it doesn't exist

You can consider it equivalent to:

rm -f workdirectory/filename.txt; touch workdirectory/filename.txt

[Vue warn]: Property or method is not defined on the instance but referenced during render

I got this error when I tried assigning a component property to a state property during instantiation

export default {
 props: ['value1'],
 data() {
  return {
   value2: this.value1 // throws the error
   }
  }, 
 created(){
  this.value2 = this.value1 // safe
 }
}

How are "mvn clean package" and "mvn clean install" different?

What clean does (common in both the commands) - removes all files generated by the previous build


Coming to the difference between the commands package and install, you first need to understand the lifecycle of a maven project


These are the default life cycle phases in maven

  • validate - validate the project is correct and all necessary information is available
  • compile - compile the source code of the project
  • test - test the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed
  • package - take the compiled code and package it in its distributable format, such as a JAR.
  • verify - run any checks on results of integration tests to ensure quality criteria are met
  • install - install the package into the local repository, for use as a dependency in other projects locally
  • deploy - done in the build environment, copies the final package to the remote repository for sharing with other developers and projects.

How Maven works is, if you run a command for any of the lifecycle phases, it executes each default life cycle phase in order, before executing the command itself.

order of execution

validate >> compile >> test (optional) >> package >> verify >> install >> deploy

So when you run the command mvn package, it runs the commands for all lifecycle phases till package

validate >> compile >> test (optional) >> package

And as for mvn install, it runs the commands for all lifecycle phases till install, which includes package as well

validate >> compile >> test (optional) >> package >> verify >> install


So, effectively what it means is, install commands does everything that package command does and some more (install the package into the local repository, for use as a dependency in other projects locally)

Source: Maven lifecycle reference

How to scroll to bottom in react?

This is how you would solve this in TypeScript (using the ref to a targeted element where you scroll to):

class Chat extends Component <TextChatPropsType, TextChatStateType> {
  private scrollTarget = React.createRef<HTMLDivElement>();
  componentDidMount() {
    this.scrollToBottom();//scroll to bottom on mount
  }

  componentDidUpdate() {
    this.scrollToBottom();//scroll to bottom when new message was added
  }

  scrollToBottom = () => {
    const node: HTMLDivElement | null = this.scrollTarget.current; //get the element via ref

    if (node) { //current ref can be null, so we have to check
        node.scrollIntoView({behavior: 'smooth'}); //scroll to the targeted element
    }
  };

  render <div>
    {message.map((m: Message) => <ChatMessage key={`chat--${m.id}`} message={m}/>}
     <div ref={this.scrollTarget} data-explanation="This is where we scroll to"></div>
   </div>
}

For more information about using ref with React and Typescript you can find a great article here.

Best way to do multi-row insert in Oracle?

Cursors may also be used, although it is inefficient. The following stackoverflow post discusses the usage of cursors :

INSERT and UPDATE a record using cursors in oracle

Length of string in bash

If you want to use this with command line or function arguments, make sure you use size=${#1} instead of size=${#$1}. The second one may be more instinctual but is incorrect syntax.

How to remove "onclick" with JQuery?

Old Way (pre-1.7):

$("...").attr("onclick", "").unbind("click");

New Way (1.7+):

$("...").prop("onclick", null).off("click");

(Replace ... with the selector you need.)

_x000D_
_x000D_
// use the "[attr=value]" syntax to avoid syntax errors with special characters (like "$")_x000D_
$('[id="a$id"]').prop('onclick',null).off('click');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
_x000D_
<a id="a$id" onclick="alert('get rid of this')" href="javascript:void(0)"  class="black">Qualify</a>
_x000D_
_x000D_
_x000D_

Mocking static methods with Mockito

To mock static method you should use a Powermock look at: https://github.com/powermock/powermock/wiki/MockStatic. Mockito doesn't provide this functionality.

You can read nice a article about mockito: http://refcardz.dzone.com/refcardz/mockito

Import SQL dump into PostgreSQL database

I noticed that many examples are overcomplicated for localhost where just postgres user without password exist in many cases:

psql -d db_name -f dump.sql

How do I create a table based on another table

select * into newtable from oldtable

How do I find the number of arguments passed to a Bash script?

to add the original reference:

You can get the number of arguments from the special parameter $#. Value of 0 means "no arguments". $# is read-only.

When used in conjunction with shift for argument processing, the special parameter $# is decremented each time Bash Builtin shift is executed.

see Bash Reference Manual in section 3.4.2 Special Parameters:

  • "The shell treats several parameters specially. These parameters may only be referenced"

  • and in this section for keyword $# "Expands to the number of positional parameters in decimal."

Can you issue pull requests from the command line on GitHub?

I ended up making my own, I find that it works better the other solutions that were around.

https://npmjs.org/package/pullr

CASE .. WHEN expression in Oracle SQL

You could use an IN clause

Something like

SELECT
  status,
  CASE
    WHEN STATUS IN('a1','a2','a3')
    THEN 'Active'
    WHEN STATUS = 'i'
    THEN 'Inactive'
    WHEN STATUS = 't'
    THEN 'Terminated'
  END AS STATUSTEXT
FROM
  STATUS

Have a look at this demo

SQL Fiddle DEMO

Difference between $.ajax() and $.get() and $.load()

Everyone explained the topic very well. There is one more point i would like add about .load() method.

As per Load document if you add suffixed selector in data url then it will not execute scripts in loading content.

Working Plunker

            $(document).ready(function(){
                $("#secondPage").load("mySecondHtmlPage.html #content");
            })

On the other hand, after removing selector in url, scripts in new content will run. Try this example

after removing #content in url in index.html file

            $(document).ready(function(){
                $("#secondPage").load("mySecondHtmlPage.html");
            })

There is no such in-built feature provided by other methods in discussion.

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

How can I detect whether an iframe is loaded?

You may try this (using jQuery)

_x000D_
_x000D_
$(function(){_x000D_
    $('#MainPopupIframe').load(function(){_x000D_
        $(this).show();_x000D_
        console.log('iframe loaded successfully')_x000D_
    });_x000D_
        _x000D_
    $('#click').on('click', function(){_x000D_
        $('#MainPopupIframe').attr('src', 'https://heera.it');    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Using plain javascript

_x000D_
_x000D_
window.onload=function(){_x000D_
    var ifr=document.getElementById('MainPopupIframe');_x000D_
    ifr.onload=function(){_x000D_
        this.style.display='block';_x000D_
        console.log('laod the iframe')_x000D_
    };_x000D_
    var btn=document.getElementById('click');    _x000D_
    btn.onclick=function(){_x000D_
        ifr.src='https://heera.it';    _x000D_
    };_x000D_
};
_x000D_
<button id='click'>click me</button>_x000D_
_x000D_
<iframe style="display:none" id='MainPopupIframe' src='' /></iframe>
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Update: Also you can try this (dynamic iframe)

_x000D_
_x000D_
$(function(){_x000D_
    $('#click').on('click', function(){_x000D_
        var ifr=$('<iframe/>', {_x000D_
            id:'MainPopupIframe',_x000D_
            src:'https://heera.it',_x000D_
            style:'display:none;width:320px;height:400px',_x000D_
            load:function(){_x000D_
                $(this).show();_x000D_
                alert('iframe loaded !');_x000D_
            }_x000D_
        });_x000D_
        $('body').append(ifr);    _x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button id='click'>click me</button><br />
_x000D_
_x000D_
_x000D_

jsfiddle DEMO.

Object Library Not Registered When Adding Windows Common Controls 6.0

...and on my 64 bit W7 machine, with VB6 installed... in DOS, as Admin, this worked to solve an OCX problem I was having with a VB6 App:

cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

YES! This solution solved the problem I had using MSCAL.OCX (The Microsoft Calendar Control) in VB6.

Thank you guys! :-)

Using SUMIFS with multiple AND OR conditions

Speed

SUMPRODUCT is faster than SUM arrays, i.e. having {} arrays in the SUM function. SUMIFS is 30% faster than SUMPRODUCT.

{SUM(SUMIFS({}))} vs SUMPRODUCT(SUMIFS({})) both works fine, but SUMPRODUCT feels a bit easier to write without the CTRL-SHIFT-ENTER to create the {}.

Preference

I personally prefer writing SUMPRODUCT(--(ISNUMBER(MATCH(...)))) over SUMPRODUCT(SUMIFS({})) for multiple criteria.

However, if you have a drop-down menu where you want to select specific characteristics or all, SUMPRODUCT(SUMIFS()), is the only way to go. (as for selecting "all", the value should enter in "<>" + "Whatever word you want as long as it's not part of the specific characteristics".

Difference between onLoad and ng-init in angular

From angular's documentation,

ng-init SHOULD NOT be used for any initialization. It should be used only for aliasing. https://docs.angularjs.org/api/ng/directive/ngInit

onload should be used if any expression needs to be evaluated after a partial view is loaded (by ng-include). https://docs.angularjs.org/api/ng/directive/ngInclude

The major difference between them is when used with ng-include.

<div ng-include="partialViewUrl" onload="myFunction()"></div>

In this case, myFunction is called everytime the partial view is loaded.

<div ng-include="partialViewUrl" ng-init="myFunction()"></div>

Whereas, in this case, myFunction is called only once when the parent view is loaded.

PHP ini file_get_contents external url

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);

is best for http url, But how to open https url help me

Angular - "has no exported member 'Observable'"

Just put:

import { Observable} from 'rxjs';

Just like that. Nothing more or less.

Trigger standard HTML5 validation (form) without using submit button?

form.submit() doesn't work cause the HTML5 validation is performed before the form submition. When you click on a submit button, the HTML5 validation is trigerred and then the form is submited if validation was successfull.

Can I run a 64-bit VMware image on a 32-bit machine?

Yes, running a 64-bit OS in VMWare is possible from a 32-bit OS if you have a 64 bit processor.

I have an old Intel Core 2 Duo with Windows XP Professional 2002 running on it, and I got it to work.

First of all, see if your CPU is capable of running a 64-bit OS. Search for 'Processor check for 64-bit compatibility' on the VMware site. Run the program.

If it says your processor is capable, restart your computer and go into the BIOS and see if you have 'Virtualization' and are able to enable it. I was able to and got Windows Server 2008 R2 running under VMware on this old laptop.

I hope it works for you!

Switch php versions on commandline ubuntu 16.04

please follow the steps :

i.e : your current version is : current_version = 7.3 , and you want to change it to : new_version = 7.2

1) sudo a2dismod php(current_version) 
2) sudo a2enmod php(new_version)
3) sudo update-alternatives --config php (here you need to select php version number) 
4) restart apache through : 
  sudo /etc/init.d/apache2 restart OR
  sudo service apache2 restart

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

How to run python script in webpage

As others have pointed out, there are many web frameworks for Python.

But, seeing as you are just getting started with Python, a simple CGI script might be more appropriate:

  1. Rename your script to index.cgi. You also need to execute chmod +x index.cgi to give it execution privileges.

  2. Add these 2 lines in the beginning of the file:

#!/usr/bin/python   
print('Content-type: text/html\r\n\r')

After this the Python code should run just like in terminal, except the output goes to the browser. When you get that working, you can use the cgi module to get data back from the browser.

Note: this assumes that your webserver is running Linux. For Windows, #!/Python26/python might work instead.

Angular ng-if="" with multiple arguments

Yes, it's possible. for example checkout:

<div class="singleMatch" ng-if="match.date | date:'ddMMyyyy' === main.date &&  match.team1.code === main.team1code && match.team2.code === main.team2code">
    //Do something here
    </div>

fatal: does not appear to be a git repository

It is most likely that you got your repo's SSH URL wrong.

To confirm, go to your repository on Github and click the clone or download button. Then click the use SSH link.

ssh link

Now copy your official repo's SSH link. Mine looked like this - [email protected]:borenho/que-ay.git

You can now do git remote add origin [email protected]:borenho/que-ay.git if you didn't have origin yet.

If you had set origin before, change it by using git remote set-url origin [email protected]:borenho/que-ay.git

Now push with git push -u origin master

php var_dump() vs print_r()

The var_dump function displays structured information about variables/expressions including its type and value. Arrays are explored recursively with values indented to show structure. It also shows which array values and object properties are references.

The print_r() displays information about a variable in a way that's readable by humans. array values will be presented in a format that shows keys and elements. Similar notation is used for objects.

Example:

$obj = (object) array('qualitypoint', 'technologies', 'India');

var_dump($obj) will display below output in the screen.

object(stdClass)#1 (3) {
 [0]=> string(12) "qualitypoint"
 [1]=> string(12) "technologies"
 [2]=> string(5) "India"
}

And, print_r($obj) will display below output in the screen.

stdClass Object ( 
 [0] => qualitypoint
 [1] => technologies
 [2] => India
)

More Info

What is the difference between a port and a socket?

A socket represents a single connection between two network applications. These two applications nominally run on different computers, but sockets can also be used for interprocess communication on a single computer. Applications can create multiple sockets for communicating with each other. Sockets are bidirectional, meaning that either side of the connection is capable of both sending and receiving data. Therefore a socket can be created theoretically at any level of the OSI model from 2 upwards. Programmers often use sockets in network programming, albeit indirectly. Programming libraries like Winsock hide many of the low-level details of socket programming. Sockets have been in widespread use since the early 1980s.

A port represents an endpoint or "channel" for network communications. Port numbers allow different applications on the same computer to utilize network resources without interfering with each other. Port numbers most commonly appear in network programming, particularly socket programming. Sometimes, though, port numbers are made visible to the casual user. For example, some Web sites a person visits on the Internet use a URL like the following:

http://www.mairie-metz.fr:8080/ In this example, the number 8080 refers to the port number used by the Web browser to connect to the Web server. Normally, a Web site uses port number 80 and this number need not be included with the URL (although it can be).

In IP networking, port numbers can theoretically range from 0 to 65535. Most popular network applications, though, use port numbers at the low end of the range (such as 80 for HTTP).

Note: The term port also refers to several other aspects of network technology. A port can refer to a physical connection point for peripheral devices such as serial, parallel, and USB ports. The term port also refers to certain Ethernet connection points, such as those on a hub, switch, or router.

ref http://compnetworking.about.com/od/basicnetworkingconcepts/l/bldef_port.htm

ref http://compnetworking.about.com/od/itinformationtechnology/l/bldef_socket.htm

What is the Python equivalent for a case/switch statement?

The direct replacement is if/elif/else.

However, in many cases there are better ways to do it in Python. See "Replacements for switch statement in Python?".

Location of the mongodb database on mac

If mongodb is installed via Homebrew the default location is:

/usr/local/var/mongodb

See the answer from @simonbogarde for the location of other interesting files that are different when using Homebrew.

Adding Git-Bash to the new Windows Terminal

There are below things to do.

  1. Make sure your git command can be run successfully in CMD

That means you need to add git to path when install git or add it to system environment later.

enter image description here

  1. Update the config file profile.json

Open Settings, add following snippet inside the word profiles:

        { 
            "tabTitle": "Git Bash",
            "acrylicOpacity" : 0.75, 
            "closeOnExit" : true, 
            "colorScheme" : "Campbell", 
            "commandline" : "C:/Program Files/Git/bin/bash.exe --login", 
            "cursorColor" : "#FFFFFF", 
            "cursorShape" : "bar", 
            "fontFace" : "Consolas", 
            "fontSize" : 12, 
            "guid" : "{14ad203f-52cc-4110-90d6-d96e0f41b64d}", 
            "historySize" : 9001, 
            "icon": "ms-appdata:///roaming/git-bash_32px.ico",
            "name" : "Git Bash", 
            "padding" : "0, 0, 0, 0", 
            "snapOnInput" : true, 
            "useAcrylic" : true 
        }

The icon can be obtained here: git-bash_32px.ico

You can add icons for Tab to this location:

%LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState

Put 32x32 PNG/icons in this folder, and then in profile.json you can reference the image resource with the path starting with ms-appdata:// .

Note that, please make sure the Guidis correct and it matches the corresponding correct configs.

  1. Test git bash works well in Windows Terminal

The final result is below: enter image description here

How to ping multiple servers and return IP address and Hostnames using batch script?

the problem with ping is if the host is not alive often your local machine will return an answer that the pinged host is not available, thus the errorcode of ping will be 0 and your code will run in error because not recognizing the down state.

better do it this way

ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)

this way you look for a typical string ttl which is always in the well done ping result and check error on this findstr instead of irritating ping

overall this looks like this:

@echo off
SetLocal


set log=path/to/logfile.txt
set check=path/to/checkfile.txt

:start
echo. some echo date >>%log%

:check
for /f %%r in (%check%) do (call :ping %%r)
goto :eof

:ping
ping -n 4 %1 | findstr TTL
if %errorlevel%==0 (goto :eof) else (goto :error)

:error
echo. some errormessage to >>%log%
echo. some blat to mail?

:eof
echo. some good message to >>%log%

how to generate a unique token which expires after 24 hours?

Use Dictionary<string, DateTime> to store token with timestamp:

static Dictionary<string, DateTime> dic = new Dictionary<string, DateTime>();

Add token with timestamp whenever you create new token:

dic.Add("yourToken", DateTime.Now);

There is a timer running to remove any expired tokens out of dic:

 timer = new Timer(1000*60); //assume run in 1 minute
 timer.Elapsed += timer_Elapsed;

 static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        var expiredTokens = dic.Where(p => p.Value.AddDays(1) <= DateTime.Now)
                              .Select(p => p.Key);

        foreach (var key in expiredTokens)
            dic.Remove(key);
    }

So, when you authenticate token, just check whether token exists in dic or not.

What's wrong with overridable method calls in constructors?

I guess for Wicket it's better to call add method in the onInitialize() (see components lifecycle) :

public abstract class BasicPage extends WebPage {

    public BasicPage() {
    }

    @Override
    public void onInitialize() {
        add(new Label("title", getTitle()));
    }

    protected abstract String getTitle();
}

Any reason to prefer getClass() over instanceof when generating .equals()?

If you want to ensure only that class will match then use getClass() ==. If you want to match subclasses then instanceof is needed.

Also, instanceof will not match against a null but is safe to compare against a null. So you don't have to null check it.

if ( ! (obj instanceof MyClass) ) { return false; }

Conditional statement in a one line lambda function in python?

In case you want to be lazier:

#syntax lambda x : (false,true)[Condition]

In your case:

rate = lambda(T) : (400*exp(-T),200*exp(-T))[T>200]

receiving json and deserializing as List of object at spring mvc controller

For me below code worked, first sending json string with proper headers

$.ajax({
        type: "POST",
        url : 'save',
        data : JSON.stringify(valObject),
        contentType:"application/json; charset=utf-8",
        dataType:"json",
        success : function(resp){
            console.log(resp);
        },
        error : function(resp){
            console.log(resp);
        }
    });

And then on Spring side -

@RequestMapping(value = "/save", 
                method = RequestMethod.POST,
                consumes="application/json")
public @ResponseBody String  save(@RequestBody ArrayList<KeyValue> keyValList) {
    //Saving call goes here
    return "";
}

Here KeyValue is simple pojo that corresponds to your JSON structure also you can add produces as you wish, I am simply returning string.

My json object is like this -

[{"storedKey":"vc","storedValue":"1","clientId":"1","locationId":"1"},
 {"storedKey":"vr","storedValue":"","clientId":"1","locationId":"1"}]

A potentially dangerous Request.Form value was detected from the client

If you're just looking to tell your users that < and > are not to be used BUT, you don't want the entire form processed/posted back (and lose all the input) before-hand could you not simply put in a validator around the field to screen for those (and maybe other potentially dangerous) characters?

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

For Android 6.0 at least, the ARM Translation thing is apparently unnecessary.

Just grab an x86 + Android 6.0 package (nano is fine) from OpenGApps and install by dragging-and-dropping and telling it to flash.

It seems the ARM translation thing was previously required, before the x86 package was available. You might still need the ARM translation if you want to install ARM-only apps though.

Random float number generation

I wasn't satisfied by any of the answers so far so I wrote a new random float function. It makes bitwise assumptions about the float data type. It still needs a rand() function with at least 15 random bits.

//Returns a random number in the range [0.0f, 1.0f).  Every
//bit of the mantissa is randomized.
float rnd(void){
  //Generate a random number in the range [0.5f, 1.0f).
  unsigned int ret = 0x3F000000 | (0x7FFFFF & ((rand() << 8) ^ rand()));
  unsigned short coinFlips;

  //If the coin is tails, return the number, otherwise
  //divide the random number by two by decrementing the
  //exponent and keep going. The exponent starts at 63.
  //Each loop represents 15 random bits, a.k.a. 'coin flips'.
  #define RND_INNER_LOOP() \
    if( coinFlips & 1 ) break; \
    coinFlips >>= 1; \
    ret -= 0x800000
  for(;;){
    coinFlips = rand();
    RND_INNER_LOOP(); RND_INNER_LOOP(); RND_INNER_LOOP();
    //At this point, the exponent is 60, 45, 30, 15, or 0.
    //If the exponent is 0, then the number equals 0.0f.
    if( ! (ret & 0x3F800000) ) return 0.0f;
    RND_INNER_LOOP(); RND_INNER_LOOP(); RND_INNER_LOOP();
    RND_INNER_LOOP(); RND_INNER_LOOP(); RND_INNER_LOOP();
    RND_INNER_LOOP(); RND_INNER_LOOP(); RND_INNER_LOOP();
    RND_INNER_LOOP(); RND_INNER_LOOP(); RND_INNER_LOOP();
  }
  return *((float *)(&ret));
}

Responsive Images with CSS

check the images first with php if it is small then the standerd size for logo provide it any other css class and dont change its size

i think you have to take up scripting in between

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

How to check if a Ruby object is a Boolean

Simplest way I can think of:

# checking whether foo is a boolean
!!foo == foo

Converting a double to an int in C#

Because Convert.ToInt32 rounds:

Return Value: rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

...while the cast truncates:

When you convert from a double or float value to an integral type, the value is truncated.

Update: See Jeppe Stig Nielsen's comment below for additional differences (which however do not come into play if score is a real number as is the case here).

AngularJS: Uncaught Error: [$injector:modulerr] Failed to instantiate module?

You have to play with JSFiddle loading option :

set it to "No wrap - in body" instead of "onload"

Working fiddle : http://jsfiddle.net/zQv9n/1/

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

My solution (for .net core 2.0) was that i had forgot to add the port number in the applicationUrl, under iisExpress in launchSettings.json

"iisExpress": {
  "applicationUrl": "https://localhost:50770",
  "sslPort": 50770
}

Difference between attr_accessor and attr_accessible

Many people on this thread and on google explain very well that attr_accessible specifies a whitelist of attributes that are allowed to be updated in bulk (all the attributes of an object model together at the same time) This is mainly (and only) to protect your application from "Mass assignment" pirate exploit.

This is explained here on the official Rails doc : Mass Assignment

attr_accessor is a ruby code to (quickly) create setter and getter methods in a Class. That's all.

Now, what is missing as an explanation is that when you create somehow a link between a (Rails) model with a database table, you NEVER, NEVER, NEVER need attr_accessor in your model to create setters and getters in order to be able to modify your table's records.

This is because your model inherits all methods from the ActiveRecord::Base Class, which already defines basic CRUD accessors (Create, Read, Update, Delete) for you. This is explained on the offical doc here Rails Model and here Overwriting default accessor (scroll down to the chapter "Overwrite default accessor")

Say for instance that: we have a database table called "users" that contains three columns "firstname", "lastname" and "role" :

SQL instructions :

CREATE TABLE users (
  firstname string,
  lastname string
  role string
);

I assumed that you set the option config.active_record.whitelist_attributes = true in your config/environment/production.rb to protect your application from Mass assignment exploit. This is explained here : Mass Assignment

Your Rails model will perfectly work with the Model here below :

class User < ActiveRecord::Base

end

However you will need to update each attribute of user separately in your controller for your form's View to work :

def update
    @user = User.find_by_id(params[:id])
    @user.firstname = params[:user][:firstname]
    @user.lastname = params[:user][:lastname]

    if @user.save
        # Use of I18 internationalization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

Now to ease your life, you don't want to make a complicated controller for your User model. So you will use the attr_accessible special method in your Class model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname

end

So you can use the "highway" (mass assignment) to update :

def update
    @user = User.find_by_id(params[:id])

    if @user.update_attributes(params[:user])
        # Use of I18 internationlization t method for the flash message
        flash[:success] = t('activerecord.successful.messages.updated', :model => User.model_name.human)
    end

    respond_with(@user)
end

You didn't add the "role" attributes to the attr_accessible list because you don't let your users set their role by themselves (like admin). You do this yourself on another special admin View.

Though your user view doesn't show a "role" field, a pirate could easily send a HTTP POST request that include "role" in the params hash. The missing "role" attribute on the attr_accessible is to protect your application from that.

You can still modify your user.role attribute on its own like below, but not with all attributes together.

@user.role = DEFAULT_ROLE

Why the hell would you use the attr_accessor?

Well, this would be in the case that your user-form shows a field that doesn't exist in your users table as a column.

For instance, say your user view shows a "please-tell-the-admin-that-I'm-in-here" field. You don't want to store this info in your table. You just want that Rails send you an e-mail warning you that one "crazy" ;-) user has subscribed.

To be able to make use of this info you need to store it temporarily somewhere. What more easy than recover it in a user.peekaboo attribute ?

So you add this field to your model :

class User < ActiveRecord::Base

  attr_accessible :firstname, :lastname
  attr_accessor :peekaboo

end

So you will be able to make an educated use of the user.peekaboo attribute somewhere in your controller to send an e-mail or do whatever you want.

ActiveRecord will not save the "peekaboo" attribute in your table when you do a user.save because she don't see any column matching this name in her model.

SQL Statement using Where clause with multiple values

Select t1.SongName
From tablename t1
left join tablename t2
 on t1.SongName = t2.SongName
    and t1.PersonName <> t2.PersonName
    and t1.Status = 'Complete' -- my assumption that this is necessary
    and t2.Status = 'Complete' -- my assumption that this is necessary
    and t1.PersonName IN ('Holly', 'Ryan')
    and t2.PersonName IN ('Holly', 'Ryan')

Having a UITextField in a UITableViewCell

Here's how its done i believe the correct way. It works on Ipad and Iphone as i tested it. We have to create our own customCells by classing a uitableviewcell:

start off in interfaceBuilder ... create a new UIViewcontroller call it customCell (volunteer for a xib while your there) Make sure customCell is a subclass of uitableviewcell

erase all views now and create one view make it the size of a individual cell. make that view subclass customcell. now create two other views (duplicate the first).
Go to your connections inspector and find 2 IBOutlets you can connect to these views now.

-backgroundView -SelectedBackground

connect these to the last two views you just duplicated and dont worry about them. the very first view that extends customCell, put your label and uitextfield inside of it. got into customCell.h and hook up your label and textfield. Set the height of this view to say 75 (height of each cell) all done.

In your customCell.m file make sure the constructor looks something like this:

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
if (self) {
    // Initialization code
    NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:@"CustomCell"       owner:self options:nil]; 
    self = [nibArray objectAtIndex:0];
}
return self;
}

Now create a UITableViewcontroller and in this method use the customCell class like this :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
// lets use our customCell which has a label and textfield already installed for us

customCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    //cell = [[[customCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];


    NSArray *topLevelsObjects = [[NSBundle mainBundle] loadNibNamed:@"NewUserCustomCell" owner:nil options:nil];
    for (id currentObject in topLevelsObjects){
        if ([currentObject  isKindOfClass:[UITableViewCell class]]){
            cell = (customCell *) currentObject;
            break;
        }
    }

    NSUInteger row = [indexPath row];

switch (row) {
    case 0:
    {

        cell.titleLabel.text = @"First Name"; //label we made (uitextfield also available now)

        break;
    }


        }
return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

return 75.0;
}

How to return a PNG image from Jersey REST service method to the browser

If you have a number of image resource methods, it is well worth creating a MessageBodyWriter to output the BufferedImage:

@Produces({ "image/png", "image/jpg" })
@Provider
public class BufferedImageBodyWriter implements MessageBodyWriter<BufferedImage>  {
  @Override
  public boolean isWriteable(Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return type == BufferedImage.class;
  }

  @Override
  public long getSize(BufferedImage t, Class<?> type, Type type1, Annotation[] antns, MediaType mt) {
    return -1; // not used in JAX-RS 2
  }

  @Override
  public void writeTo(BufferedImage image, Class<?> type, Type type1, Annotation[] antns, MediaType mt, MultivaluedMap<String, Object> mm, OutputStream out) throws IOException, WebApplicationException {
    ImageIO.write(image, mt.getSubtype(), out);
  } 
}

This MessageBodyWriter will be used automatically if auto-discovery is enabled for Jersey, otherwise it needs to be returned by a custom Application sub-class. See JAX-RS Entity Providers for more info.

Once this is set up, simply return a BufferedImage from a resource method and it will be be output as image file data:

@Path("/whatever")
@Produces({"image/png", "image/jpg"})
public Response getFullImage(...) {
  BufferedImage image = ...;
  return Response.ok(image).build();
}

A couple of advantages to this approach:

  • It writes to the response OutputSteam rather than an intermediary BufferedOutputStream
  • It supports both png and jpg output (depending on the media types allowed by the resource method)

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

curious - why doesn't the 'nothing easier than this' answer (above) not work? it looks logical? http://206.251.38.181/jquery-learn/ajax/iframe.html

Disable Copy or Paste action for text box?

Check this fiddle.

 $('#email').bind("cut copy paste",function(e) {
     e.preventDefault();
 });

You need to bind what should be done on cut, copy and paste. You prevent default behavior of the action.

You can find a detailed explanation here.

Find unique lines

You could also print out the unique value in "file" using the cat command by piping to sort and uniq

cat file | sort | uniq -u

Alternative to a goto statement in Java

There isn't any direct equivalent to the goto concept in Java. There are a few constructs that allow you to do some of the things you can do with a classic goto.

  • The break and continue statements allow you to jump out of a block in a loop or switch statement.
  • A labeled statement and break <label> allow you to jump out of an arbitrary compound statement to any level within a given method (or initializer block).
  • If you label a loop statement, you can continue <label> to continue with the next iteration of an outer loop from an inner loop.
  • Throwing and catching exceptions allows you to (effectively) jump out of many levels of a method call. (However, exceptions are relatively expensive and are considered to be a bad way to do "ordinary" control flow1.)
  • And of course, there is return.

None of these Java constructs allow you to branch backwards or to a point in the code at the same level of nesting as the current statement. They all jump out one or more nesting (scope) levels and they all (apart from continue) jump downwards. This restriction helps to avoid the goto "spaghetti code" syndrome inherent in old BASIC, FORTRAN and COBOL code2.


1- The most expensive part of exceptions is the actual creation of the exception object and its stacktrace. If you really, really need to use exception handling for "normal" flow control, you can either preallocate / reuse the exception object, or create a custom exception class that overrides the fillInStackTrace() method. The downside is that the exception's printStackTrace() methods won't give you useful information ... should you ever need to call them.

2 - The spaghetti code syndrome spawned the structured programming approach, where you limited in your use of the available language constructs. This could be applied to BASIC, Fortran and COBOL, but it required care and discipline. Getting rid of goto entirely was a pragmatically better solution. If you keep it in a language, there is always some clown who will abuse it.

C# DateTime to "YYYYMMDDHHMMSS" format

This site has great examples check it out

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}",      dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}",      dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}",      dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",          dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",               dt);  // "5 05"            minute
String.Format("{0:s ss}",               dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}",      dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}",      dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",               dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",           dt);  // "-6 -06 -06:00"   time zone

// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}",           dt);  // "3/9/2008"
String.Format("{0:MM/dd/yyyy}",         dt);  // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}",   dt);  // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}",           dt);  // "03/09/08"
String.Format("{0:MM/dd/yyyy}",         dt);  // "03/09/2008"

Standard DateTime Formatting

String.Format("{0:t}", dt);  // "4:05 PM"                           ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                          ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                        LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"            LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"    LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                  ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"               ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                          MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                       YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"     RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"               SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"              UniversalSortableDateTime

/*
Specifier   DateTimeFormatInfo property     Pattern value (for en-US culture)
    t           ShortTimePattern                    h:mm tt
    d           ShortDatePattern                    M/d/yyyy
    T           LongTimePattern                     h:mm:ss tt
    D           LongDatePattern                     dddd, MMMM dd, yyyy
    f           (combination of D and t)            dddd, MMMM dd, yyyy h:mm tt
    F           FullDateTimePattern                 dddd, MMMM dd, yyyy h:mm:ss tt
    g           (combination of d and t)            M/d/yyyy h:mm tt
    G           (combination of d and T)            M/d/yyyy h:mm:ss tt
    m, M        MonthDayPattern                     MMMM dd
    y, Y        YearMonthPattern                    MMMM, yyyy
    r, R        RFC1123Pattern                      ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
    s           SortableDateTi­mePattern             yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
    u           UniversalSorta­bleDateTimePat­tern    yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
                                                    (*) = culture independent   
*/

Update using c# 6 string interpolation format

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

$"{dt:y yy yyy yyyy}";  // "8 08 008 2008"   year
$"{dt:M MM MMM MMMM}";  // "3 03 Mar March"  month
$"{dt:d dd ddd dddd}";  // "9 09 Sun Sunday" day
$"{dt:h hh H HH}";      // "4 04 16 16"      hour 12/24
$"{dt:m mm}";           // "5 05"            minute
$"{dt:s ss}";           // "7 07"            second
$"{dt:f ff fff ffff}";  // "1 12 123 1230"   sec.fraction
$"{dt:F FF FFF FFFF}";  // "1 12 123 123"    without zeroes
$"{dt:t tt}";           // "P PM"            A.M. or P.M.
$"{dt:z zz zzz}";       // "-6 -06 -06:00"   time zone

// month/day numbers without/with leading zeroes
$"{dt:M/d/yyyy}";    // "3/9/2008"
$"{dt:MM/dd/yyyy}";  // "03/09/2008"

// day/month names
$"{dt:ddd, MMM d, yyyy}";    // "Sun, Mar 9, 2008"
$"{dt:dddd, MMMM d, yyyy}";  // "Sunday, March 9, 2008"

// two/four digit year
$"{dt:MM/dd/yy}";    // "03/09/08"
$"{dt:MM/dd/yyyy}";  // "03/09/2008"

Oracle: how to add minutes to a timestamp?

Based on what you're asking for, you want the HH24:MI format for to_char.

How to return a struct from a function in C++?

Here is an edited version of your code which is based on ISO C++ and which works well with G++:

#include <string.h>
#include <iostream>
using namespace std;

#define NO_OF_TEST 1

struct studentType {
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;
    int arrayMarks[4];
    double avgMarks;
};

studentType input() {
    studentType newStudent;
    cout << "\nPlease enter student information:\n";

    cout << "\nFirst Name: ";
    cin >> newStudent.firstName;

    cout << "\nLast Name: ";
    cin >> newStudent.lastName;

    cout << "\nStudent ID: ";
    cin >> newStudent.studentID;

    cout << "\nSubject Name: ";
    cin >> newStudent.subjectName;

    for (int i = 0; i < NO_OF_TEST; i++) {
        cout << "\nTest " << i+1 << " mark: ";
        cin >> newStudent.arrayMarks[i];
    }

    return newStudent;
}

int main() {
    studentType s;
    s = input();

    cout <<"\n========"<< endl << "Collected the details of "
        << s.firstName << endl;

    return 0;
}

Fit cell width to content

Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.

One option is to replace table with CSS4 flex divs:

https://css-tricks.com/snippets/css/a-guide-to-flexbox/

That works in new browsers i.e. IE11+ see table at the bottom of the article.

mat-form-field must contain a MatFormFieldControl

I had same issue

issue is simple

only you must import two modules to your project

MatFormFieldModule MatInputModule

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Problem

I specifically got the "[module_name]:prepareDebugUnitTestDependencies" task not found error, every time I ran gradle build. This happened to me after updating my Android Studio to 3.0.0.

Investigation

I had previously added command-line options to the gradle-based compiler, which you can find under: File -> Settings -> Build, Execution, Deployment -> Compiler -> Command-line Options. Specifically, I had excluded a number of tasks, including the aforementioned task. While that worked fine on the previous stable version (2.3 at that time), it seems like this was the reason behind the build failure.

Solution

This is one of many possible solutions. Make sure you have the correct command-line options specified in the settings under: File -> Settings -> Build, Execution, Deployment -> Compiler -> Command-line Options, and that none of them is causing this problem.

In my case, I removed the exclusion of this task (and other tasks that seemed related), left the unrelated tasks excluded, and it worked!

Using an HTML button to call a JavaScript function

I would say it would be better to add the javascript in an un-obtrusive manner...

if using jQuery you could do something like:

<script>
  $(document).ready(function(){
    $('#MyButton').click(function(){
       CapacityChart();
    });
  });
</script>

<input type="button" value="Capacity Chart" id="MyButton" >

Javascript Date Validation ( DD/MM/YYYY) & Age Checking

It is two problems - is the slashes the right places and is it a valid date. I would suggest you catch input changes and put the slashes in yourself. (annoying for the user)

The interesting problem is whether they put in a valid date and I would suggest exploiting how flexible js is:

_x000D_
_x000D_
function isValidDate(str) {_x000D_
  var newdate = new Date();_x000D_
  var yyyy = 2000 + Number(str.substr(4, 2));_x000D_
  var mm = Number(str.substr(2, 2)) - 1;_x000D_
  var dd = Number(str.substr(0, 2));_x000D_
  newdate.setFullYear(yyyy);_x000D_
  newdate.setMonth(mm);_x000D_
  newdate.setDate(dd);_x000D_
  return dd == newdate.getDate() && mm == newdate.getMonth() && yyyy == newdate.getFullYear();_x000D_
}_x000D_
console.log(isValidDate('jk'));//false_x000D_
console.log(isValidDate('290215'));//false_x000D_
console.log(isValidDate('290216'));//true_x000D_
console.log(isValidDate('292216'));//false
_x000D_
_x000D_
_x000D_

Viewing root access files/folders of android on windows

I was looking long and hard for a solution to this problem and the best I found was a root FTP server on the phone that you connect to on Windows with an FTP client like FileZilla, on the same WiFi network of course.

The root FTP server app I ended up using is FTP Droid. I tried a lot of other FTP apps with bigger download numbers but none of them worked for me for whatever reason. So install this app and set a user with home as / or wherever you want.

Then make note of the phone IP and connect with FileZilla and you should have access to the root of the phone. The biggest benefit I found is I can download entire folders and FTP will just queue it up and take care of it. So I downloaded all of my /data/data/ folder when I was looking for an app and could search on my PC. Very handy.

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

OK, two steps to this - first is to write a function that does the translation you want - I've put an example together based on your pseudo-code:

def label_race (row):
   if row['eri_hispanic'] == 1 :
      return 'Hispanic'
   if row['eri_afr_amer'] + row['eri_asian'] + row['eri_hawaiian'] + row['eri_nat_amer'] + row['eri_white'] > 1 :
      return 'Two Or More'
   if row['eri_nat_amer'] == 1 :
      return 'A/I AK Native'
   if row['eri_asian'] == 1:
      return 'Asian'
   if row['eri_afr_amer']  == 1:
      return 'Black/AA'
   if row['eri_hawaiian'] == 1:
      return 'Haw/Pac Isl.'
   if row['eri_white'] == 1:
      return 'White'
   return 'Other'

You may want to go over this, but it seems to do the trick - notice that the parameter going into the function is considered to be a Series object labelled "row".

Next, use the apply function in pandas to apply the function - e.g.

df.apply (lambda row: label_race(row), axis=1)

Note the axis=1 specifier, that means that the application is done at a row, rather than a column level. The results are here:

0           White
1        Hispanic
2           White
3           White
4           Other
5           White
6     Two Or More
7           White
8    Haw/Pac Isl.
9           White

If you're happy with those results, then run it again, saving the results into a new column in your original dataframe.

df['race_label'] = df.apply (lambda row: label_race(row), axis=1)

The resultant dataframe looks like this (scroll to the right to see the new column):

      lname   fname rno_cd  eri_afr_amer  eri_asian  eri_hawaiian   eri_hispanic  eri_nat_amer  eri_white rno_defined    race_label
0      MOST    JEFF      E             0          0             0              0             0          1       White         White
1    CRUISE     TOM      E             0          0             0              1             0          0       White      Hispanic
2      DEPP  JOHNNY    NaN             0          0             0              0             0          1     Unknown         White
3     DICAP     LEO    NaN             0          0             0              0             0          1     Unknown         White
4    BRANDO  MARLON      E             0          0             0              0             0          0       White         Other
5     HANKS     TOM    NaN             0          0             0              0             0          1     Unknown         White
6    DENIRO  ROBERT      E             0          1             0              0             0          1       White   Two Or More
7    PACINO      AL      E             0          0             0              0             0          1       White         White
8  WILLIAMS   ROBIN      E             0          0             1              0             0          0       White  Haw/Pac Isl.
9  EASTWOOD   CLINT      E             0          0             0              0             0          1       White         White

ReactJS lifecycle method inside a function Component

if you using react 16.8 you can use react Hooks... React Hooks are functions that let you “hook into” React state and lifecycle features from function components... docs

php: Get html source code with cURL

I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

RabbitMQ / AMQP: single queue, multiple consumers for same message?

Just read the rabbitmq tutorial. You publish message to exchange, not to queue; it is then routed to appropriate queues. In your case, you should bind separate queue for each consumer. That way, they can consume messages completely independently.

Remove scrollbar from iframe

Add scrolling="no" attribute to the iframe.

Can I get JSON to load into an OrderedDict?

You could always write out the list of keys in addition to dumping the dict, and then reconstruct the OrderedDict by iterating through the list?

"SyntaxError: Unexpected token < in JSON at position 0"

On a general level this error occurs when a JSON object is parsed that has syntax errors in it. Think of something like this, where the message property contains unescaped double quotes:

{
    "data": [{
        "code": "1",
        "message": "This message has "unescaped" quotes, which is a JSON syntax error."
    }]
}

If you have JSON in your app somewhere then it's good to run it through JSONLint to verify that it doesn't have a syntax error. Usually this isn't the case though in my experience, it's usually JSON returned from an API that's the culprit.

When an XHR request is made to an HTTP API that returns a response with a Content-Type:application/json; charset=UTF-8 header which contains invalid JSON in the response body you'll see this error.

If a server-side API controller is improperly handling a syntax error, and it's being printed out as part of the response, that will break the structure of JSON returned. A good example of this would be an API response containing a PHP Warning or Notice in the response body:

<b>Notice</b>:  Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
{
    "success": false,
    "data": [{ ... }]
}

95% of the time this is the source of the issue for me, and though it's somewhat addressed here in the other responses I didn't feel it was clearly described. Hopefully this helps, if you're looking for a handy way to track down which API response contains a JSON syntax error I've written an Angular module for that.

Here's the module:

/**
 * Track Incomplete XHR Requests
 * 
 * Extend httpInterceptor to track XHR completions and keep a queue 
 * of our HTTP requests in order to find if any are incomplete or 
 * never finish, usually this is the source  of the issue if it's 
 * XHR related
 */
angular.module( "xhrErrorTracking", [
        'ng',
        'ngResource'
    ] )
    .factory( 'xhrErrorTracking', [ '$q', function( $q ) {
        var currentResponse = false;

        return {
            response: function( response ) {
                currentResponse = response;
                return response || $q.when( response );
            },
            responseError: function( rejection ) {
                var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
                if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );

                console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );

                return $q.reject( rejection );
            }
        };
    } ] )
    .config( [ '$httpProvider', function( $httpProvider ) {
        $httpProvider.interceptors.push( 'xhrErrorTracking' );
    } ] );

More details can be found in the blog article referenced above, I haven't posted everything found there here as it's probably not all relevant.

Database Diagram Support Objects cannot be Installed ... no valid owner

you must enter as administrator right click to microsofft sql server management studio and run as admin

Creating executable files in Linux

Make file executable:

chmod +x file

Find location of perl:

which perl

This should return something like

/bin/perl sometimes /usr/local/bin

Then in the first line of your script add:

#!"path"/perl with path from above e.g.

#!/bin/perl

Then you can execute the file

./file

There may be some issues with the PATH, so you may want to change that as well ...

PHP simple foreach loop with HTML

This will work although when embedding PHP in HTML it is better practice to use the following form:

<table>
    <?php foreach($array as $key=>$value): ?>
    <tr>
        <td><?= $key; ?></td>
    </tr>
    <?php endforeach; ?>
</table>

You can find the doc for the alternative syntax on PHP.net

How do I parse a string into a number with Dart?

In Dart 2 int.tryParse is available.

It returns null for invalid inputs instead of throwing. You can use it like this:

int val = int.tryParse(text) ?? defaultValue;

javax.faces.application.ViewExpiredException: View could not be restored

I was getting this error : javax.faces.application.ViewExpiredException.When I using different requests, I found those having same JsessionId, even after restarting the server. So this is due to the browser cache. Just close the browser and try, it will work.

PPT to PNG with transparent background

You can select the shapes within a slide (Word Art also) and right click on the selection and choose "Save As Picture". It will save as a transparent PNG.

CSS: auto height on containing div, 100% height on background div inside containing div

Somewhere you will need to set a fixed height, instead of using auto everywhere. You will find that if you set a fixed height on your content and/or container, then using auto for things inside it will work.

Also, your boxes will still expand height-wise with more content in, even though you have set a height for it - so don't worry about that :)

#container {
  height:500px;
  min-height:500px;
}

Visual Studio 64 bit?

no, but it runs fine on win64, and can create win64 .EXEs

phpMyAdmin access denied for user 'root'@'localhost' (using password: NO)

Edit the file xampp/mysql/bin/my.ini

Add

skip-grant-tables

under [mysqld]

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

Printing Exception Message in java

try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}

What does the term "canonical form" or "canonical representation" in Java mean?

Another good example might be: you have a class that supports the use of cartesian (x, y, z), spherical (r, theta, phi) and cylindrical coordinates (r, phi, z). For purposes of establishing equality (equals method), you would probably want to convert all representations to one "canonical" representation of your choosing, e.g. spherical coordinates. (Or maybe you would want to do this in general - i.e. use one internal representation.) I am not an expert, but this did occur to me as maybe a good concrete example.

How to list all the files in android phone by using adb shell?

Some Android phones contain Busybox. Was hard to find.

To see if busybox was around:

ls -lR / | grep busybox

If you know it's around. You need some read/write space. Try you flash drive, /sdcard

cd /sdcard
ls -lR / >lsoutput.txt

upload to your computer. Upload the file. Get some text editor. Search for busybox. Will see what directory the file was found in.

busybox find /sdcard -iname 'python*'

to make busybox easier to access, you could:

cd /sdcard
ln -s /where/ever/busybox/is  busybox
/sdcard/busybox find /sdcard -iname 'python*'

Or any other place you want. R

WCF timeout exception detailed investigation

Are you closing the connection to the WCF service in between requests? If you don't, you'll see this exact timeout (eventually).

Android set bitmap to Imageview

Please try this:

byte[] decodedString = Base64.decode(person_object.getPhoto(),Base64.NO_WRAP);
InputStream inputStream  = new ByteArrayInputStream(decodedString);
Bitmap bitmap  = BitmapFactory.decodeStream(inputStream);
user_image.setImageBitmap(bitmap);

Code not running in IE 11, works fine in Chrome

text.indexOf("newString") is the best method instead of startsWith.

Example:

var text = "Format";
if(text.indexOf("Format") == 0) {
    alert(text + " = Format");
} else {
    alert(text + " != Format");
}

"Could not get any response" response when using postman with subdomain

I had the same issue. It was caused by a newline at the end of the "Authorization" header's value, which I had set manually by copy-pasting the bearer token (which accidentally contained the newline at its end)