Programs & Examples On #Launch4j

Cross-platform Java executable wrapper for creating lightweight Windows native EXEs. Provides better user experience.

Modifying a file inside a jar

You can use the u option for jar

From the Java Tutorials:

jar uf jar-file input-file(s)

"Any files already in the archive having the same pathname as a file being added will be overwritten."

See Updating a JAR File.

Much better than making the whole jar all over again. Invoking this from within your program sounds possible too. Try Running Command Line in Java

Uncaught TypeError: Cannot read property 'ownerDocument' of undefined

Make sure you're passing a selector to jQuery, not some form of data:

$( '.my-selector' )

not:

$( [ 'my-data' ] )

Increasing Heap Size on Linux Machines

Changing Tomcat config wont effect all JVM instances to get theses settings. This is not how it works, the setting will be used only to launch JVMs used by Tomcat, not started in the shell.

Look here for permanently changing the heap size.

Why are primes important in cryptography?

Because factorization algorithms speed up considerably with each factor found. Making both private keys prime ensures the first factor found will also be the last. Ideally, both private keys will also be nearly equal in value since only the strength of the weaker key matters.

How to get absolute value from double - c-language

I have found that using cabs(double), cabsf(float), cabsl(long double), __cabsf(float), __cabs(double), __cabsf(long double) is the solution

How can I compare time in SQL Server?

I am assuming your startHour column and @startHour variable are both DATETIME; In that case, you should be converting to a string:

SELECT timeEvent
FROM tbEvents
WHERE convert(VARCHAR(8), startHour, 8) >= convert(VARCHAR(8), @startHour, 8)

How to convert numpy arrays to standard TensorFlow format?

You can use placeholders and feed_dict.

Suppose we have numpy arrays like these:

trX = np.linspace(-1, 1, 101) 
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 

You can declare two placeholders:

X = tf.placeholder("float") 
Y = tf.placeholder("float")

Then, use these placeholders (X, and Y) in your model, cost, etc.: model = tf.mul(X, w) ... Y ... ...

Finally, when you run the model/cost, feed the numpy arrays using feed_dict:

with tf.Session() as sess:
.... 
    sess.run(model, feed_dict={X: trY, Y: trY})

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception

Many times I have been facing this problem, I have experienced ClassNotFoundException. if jar is not at physical location.

So make sure .jar file(mysql connector) in the physical location of WEB-INF lib folder. and make sure restarting Tomcat by using shutdown command in cmd. it should work.

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

On Windows 10 since I had npm, I installed rimraf package. npm install rimraf -g

Backup all your databases one by one using command pg_dump -U $username --format=c --file=$mydatabase.sqlc $dbname

Then Installed Latest PostgreSQL Version i.e. 11.2 which prompted me to use port 5433 this time.

Followed by Uninstall of older versions of PostgreSQL mine was 10. Note the uninstaller may give a warning of not deleting folder C:\PostgreSQL\10\data. That's why we have the next step using rimraf to permanently delete the folder and it's sub-folders.

change into PostgreSQL install directory and ran the command rimraf 10. 10 is a directory name. Note use your older version of PostgreSQL i.e. 9.5 or something.

Now add C:\PostgreSQL\pg11\bin, C:\PostgreSQL\pg11\lib into the Windows environmental variables. Note my new installed version is 11 thus why I am using pg11.

Navigate to C:\PostgreSQL\data\pg11 then open postgresql.conf edit port = 5433 to port = 5432

That's it. Open cmd and type psql -U postgres

You can now restore all your backed databases one by one using the command pg_restore -U $username --dbname=$databasename $filename

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

SEVERE: Error listenerStart

This boils down to that a ServletContextListener which is registered by either @WebListener annotation on the class, or by a <listener> declaration in web.xml, has thrown an unhandled exception inside the contextInitialized() method. This is usually caused by a developer's mistake (a bug) and needs to be fixed. For example, a NullPointerException.

The full exception should be visible in webapp-specific startup log as well as the IDE console, before the particular line which you've copypasted. If there is none and you still can't figure the cause of the exception by just looking at the code, put the entire contextInitialized() code in a try-catch wherein you log the exception to a reliable output and then interpret and fix it accordingly.

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

Open the file gradle/wrapper/gradle-wrapper.properties in your project. Change the version in the distributionUrl to use the version you want to use, e.g.,

distributionUrl=https\://services.gradle.org/distributions/gradle-2.10-all.zip

Verify a method call using Moq

You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

You should be doing something more like this:

class MyClassTest
{
    [TestMethod]
    public void MyMethodTest()
    {
        string action = "test";
        Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();

        mockSomeClass.Setup(mock => mock.DoSomething());

        MyClass myClass = new MyClass(mockSomeClass.Object);
        myClass.MyMethod(action);

        // Explicitly verify each expectation...
        mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());

        // ...or verify everything.
        // mockSomeClass.VerifyAll();
    }
}

In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

LINQ extension methods - Any() vs. Where() vs. Exists()

foreach (var item in model.Where(x => !model2.Any(y => y.ID == x.ID)).ToList())
{
enter code here
}

same work you also can do with Contains

secondly Where is give you new list of values. thirdly using Exist is not a good practice, you can achieve your target from Any and contains like

EmployeeDetail _E = Db.EmployeeDetails.where(x=>x.Id==1).FirstOrDefault();

Hope this will clear your confusion.

Makefile: How to correctly include header file and its directory?

The preprocessor is looking for StdCUtil/split.h in

and in

  • $INC_DIR (i.e. ../StdCUtil/ = /root/Core/../StdCUtil/ = /root/StdCUtil/). So ../StdCUtil/ + StdCUtil/split.h = ../StdCUtil/StdCUtil/split.h and the file is missing

You can fix the error changing the $INC_DIR variable (best solution):

$INC_DIR = ../

or the include directive:

#include "split.h"

but in this way you lost the "path syntax" that makes it very clear what namespace or module the header file belongs to.

Reference:

EDIT/UPDATE

It should also be

CXX = g++
CXXFLAGS = -c -Wall -I$(INC_DIR)

...

%.o: %.cpp $(DEPS)
    $(CXX) -o $@ $< $(CXXFLAGS)

cleanest way to skip a foreach if array is empty

Best practice is to define variable as an array at the very top of your code.

foreach((array)$myArr as $oneItem) { .. }

will also work but you will duplicate this (array) conversion everytime you need to loop through the array.

since it's important not to duplicate even a word of your code, you do better to define it as an empty array at top.

Get User Selected Range

You can loop through the Selection object to see what was selected. Here is a code snippet from Microsoft (http://msdn.microsoft.com/en-us/library/aa203726(office.11).aspx):

Sub Count_Selection()
    Dim cell As Object
    Dim count As Integer
    count = 0
    For Each cell In Selection
        count = count + 1
    Next cell
    MsgBox count & " item(s) selected"
End Sub

How do I check if a given string is a legal/valid file name under Windows?

To complement the other answers, here are a couple of additional edge cases that you might want to consider.

How to use Bootstrap in an Angular project?

You can try to use Prettyfox UI library http://ng.prettyfox.org

This library use bootstrap 4 styles and not need jquery.

Method has the same erasure as another method in type

This is because Java Generics are implemented with Type Erasure.

Your methods would be translated, at compile time, to something like:

Method resolution occurs at compile time and doesn't consider type parameters. (see erickson's answer)

void add(Set ii);
void add(Set ss);

Both methods have the same signature without the type parameters, hence the error.

Create an Array of Arraylists

To declare an array of ArrayLists statically for, say, sprite positions as Points:

ArrayList<Point>[] positionList = new ArrayList[2];

public Main(---) {
    positionList[0] = new ArrayList<Point>(); // Important, or you will get a NullPointerException at runtime
    positionList[1] = new ArrayList<Point>();
}

dynamically:

ArrayList<Point>[] positionList;
int numberOfLists;

public Main(---) {
    numberOfLists = 2;
    positionList = new ArrayList[numberOfLists];
    for(int i = 0; i < numberOfLists; i++) {
        positionList[i] = new ArrayList<Point>();
    }
}

Despite the cautions and some complex suggestions here, I have found an array of ArrayLists to be an elegant solution to represent related ArrayLists of the same type.

if statement in ng-click

Here's a hack I discovered that might work for you, although its not pretty and I'd personally be embarrassed to use such a line of code:

ng-click="profileForm.$valid ? updateMyProfile() : alert('failed')"

Now, you must be thinking 'but I don't want it to alert("failed") if my profileForm isn't valid. Well that's the ugly part. For me, no matter what I put in the else clause of this ternary statement doesn't get executed ever.

Yet if its removed an error is thrown. So you can just stuff it with a pointless alert.
I told you it was ugly... but I don't even get any errors when I do something like this.
The proper way to do this is as Chen-Tsu mentioned, but to each their own.

How do I check if a type is a subtype OR the type of an object?

If you're trying to do it in a Xamarin Forms PCL project, the above solutions using IsAssignableFrom gives an error:

Error: 'Type' does not contain a definition for 'IsAssignableFrom' and no extension method 'IsAssignableFrom' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)

because IsAssignableFrom asks for a TypeInfo object. You can use the GetTypeInfo() method from System.Reflection:

typeof(BaseClass).GetTypeInfo().IsAssignableFrom(typeof(unknownType).GetTypeInfo())

Jquery in React is not defined

It happens mostly when JQuery is not installed in your project. Install JQuery in your project by following commands according to your package manager.

Yarn

yarn add jquery

npm

npm i jquery --save

After this just import $ in your project file. import $ from 'jquery'

Executing command line programs from within python

I am not familiar with sox, but instead of making repeated calls to the program as a command line, is it possible to set it up as a service and connect to it for requests? You can take a look at the connection interface such as sqlite for inspiration.

NULL vs nullptr (Why was it replaced?)

One reason: the literal 0 has a bad tendency to acquire the type int, e.g. in perfect argument forwarding or more in general as argument with templated type.

Another reason: readability and clarity of code.

How to calculate sum of a formula field in crystal Reports?

You Can simply Right Click Formula Fields- > new Give it a name like TotalCount then Right this code:

if(isnull(sum(count({YOURCOLUMN})))) then
0
else
(sum(count({YOURCOLUMN})))

and Save then Drag and drop TotalCount this field in header/footer. After you open the "count" bracket you can drop your column there from the above section.See the example in the Pictureenter image description here

MongoDB/Mongoose querying at a specific date?

You can use following approach for API method to get results from specific day:

# [HTTP GET]
getMeals: (req, res) ->
  options = {}
  # eg. api/v1/meals?date=Tue+Jan+13+2015+00%3A00%3A00+GMT%2B0100+(CET)
  if req.query.date?
    date = new Date req.query.date
    date.setHours 0, 0, 0, 0
    endDate = new Date date
    endDate.setHours 23, 59, 59, 59
    options.date =
      $lt: endDate
      $gte: date

  Meal.find options, (err, meals) ->
      if err or not meals
        handleError err, meals, res
      else
        res.json createJSON meals, null, 'meals'

get an element's id

Yes you can simply say:


function getID(oObject) 
{
    var id = oObject.id;
    alert("This object's ID attribute is set to \"" + id + "\"."); 
}

Check this out: ID Attribute | id Property

Copy data from one existing row to another existing row in SQL?

Copy a value from one row to any other qualified rows within the same table (or different tables):

UPDATE `your_table` t1, `your_table` t2
SET t1.your_field = t2.your_field
WHERE t1.other_field = some_condition
AND t1.another_field = another_condition
AND t2.source_id = 'explicit_value'

Start off by aliasing the table into 2 unique references so the SQL server can tell them apart

Next, specify the field(s) to copy.

Last, specify the conditions governing the selection of the rows

Depending on the conditions you may copy from a single row to a series, or you may copy a series to a series. You may also specify different tables, and you can even use sub-selects or joins to allow using other tables to control the relationships.

How to obtain the chat_id of a private Telegram channel?

NEEDED ANSWER:

You should add & make your BOT as administrator of the PRIVATE channel, otherwise chat not found error happens.

Intellij JAVA_HOME variable

The problem is your "Project SDK" is none! Add a "Project SDK" by clicking "New ..." and choose the path of JDK. And then it should be OK.

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Difference between FetchType LAZY and EAGER in Java Persistence API?

The main difference between the two types of fetching is a moment when data gets loaded into a memory.
I have attached 2 photos to help you understand this.

Eager fetch
 Eager fetch

Lazy fetch Lazy fetch

Left align block of equations

Try this:

\begin{flalign*}
    &|\vec a| = \sqrt{3^{2}+1^{2}} = \sqrt{10} & \\
    &|\vec b| = \sqrt{1^{2}+23^{2}} = \sqrt{530} &\\ 
    &\cos v = \frac{26}{\sqrt{10} \cdot \sqrt{530}} &\\
    &v = \cos^{-1} \left(\frac{26}{\sqrt{10} \cdot \sqrt{530}}\right) &\\
\end{flalign*}

The & sign separates two columns, so an & at the beginning of a line means that the line starts with a blank column.

Can I use break to exit multiple nested 'for' loops?

Break any number of loops by just one bool variable see below :

bool check = true;

for (unsigned int i = 0; i < 50; i++)
{
    for (unsigned int j = 0; j < 50; j++)
    {
        for (unsigned int k = 0; k < 50; k++)
        {
            //Some statement
            if (condition)
            {
                check = false;
                break;
            }
        }
        if (!check)
        {
            break;
        }
    }
    if (!check)
    {
        break;
    }
}

In this code we break; all the loops.

Get current rowIndex of table in jQuery

Try this,

$('td').click(function(){
   var row_index = $(this).parent().index();
   var col_index = $(this).index();
});

If you need the index of table contain td then you can change it to

var row_index = $(this).parent('table').index(); 

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

Copy tables from one database to another in SQL Server

This should work:

SELECT * 
INTO DestinationDB..MyDestinationTable 
FROM SourceDB..MySourceTable 

It will not copy constraints, defaults or indexes. The table created will not have a clustered index.

Alternatively you could:

INSERT INTO DestinationDB..MyDestinationTable 
SELECT * FROM SourceDB..MySourceTable

If your destination table exists and is empty.

How to disable scientific notation?

format(99999999,scientific = F)

gives

99999999

Convert seconds to Hour:Minute:Second

You can use the gmdate() function:

echo gmdate("H:i:s", 685);

How to pass variable number of arguments to a PHP function

This is now possible with PHP 5.6.x, using the ... operator (also known as splat operator in some languages):

Example:

function addDateIntervalsToDateTime( DateTime $dt, DateInterval ...$intervals )
{
    foreach ( $intervals as $interval ) {
        $dt->add( $interval );
    }
    return $dt;
}

addDateIntervaslToDateTime( new DateTime, new DateInterval( 'P1D' ), 
        new DateInterval( 'P4D' ), new DateInterval( 'P10D' ) );

Why is char[] preferred over String for passwords?

I don't think this is a valid suggestion, but, I can at least guess at the reason.

I think the motivation is wanting to make sure that you can erase all trace of the password in memory promptly and with certainty after it is used. With a char[] you could overwrite each element of the array with a blank or something for sure. You can't edit the internal value of a String that way.

But that alone isn't a good answer; why not just make sure a reference to the char[] or String doesn't escape? Then there's no security issue. But the thing is that String objects can be intern()ed in theory and kept alive inside the constant pool. I suppose using char[] forbids this possibility.

How to load external webpage in WebView

You can do like this.

webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("Your URL goes here");

Error loading the SDK when Eclipse starts

Check the

  • Android wear ARM EABI
  • Android wear Intel x86

Than delete them and restart Eclipse IDE. This should fix the problem.

Is it possible to run a .NET 4.5 app on XP?

Try mono:

http://www.go-mono.com/mono-downloads/download.html

This download works on all versions of Windows XP, 2003, Vista and Windows 7.

Task.Run with Parameter(s)?

private void RunAsync()
{
    string param = "Hi";
    Task.Run(() => MethodWithParameter(param));
}

private void MethodWithParameter(string param)
{
    //Do stuff
}

Edit

Due to popular demand I must note that the Task launched will run in parallel with the calling thread. Assuming the default TaskScheduler this will use the .NET ThreadPool. Anyways, this means you need to account for whatever parameter(s) being passed to the Task as potentially being accessed by multiple threads at once, making them shared state. This includes accessing them on the calling thread.

In my above code that case is made entirely moot. Strings are immutable. That's why I used them as an example. But say you're not using a String...

One solution is to use async and await. This, by default, will capture the SynchronizationContext of the calling thread and will create a continuation for the rest of the method after the call to await and attach it to the created Task. If this method is running on the WinForms GUI thread it will be of type WindowsFormsSynchronizationContext.

The continuation will run after being posted back to the captured SynchronizationContext - again only by default. So you'll be back on the thread you started with after the await call. You can change this in a variety of ways, notably using ConfigureAwait. In short, the rest of that method will not continue until after the Task has completed on another thread. But the calling thread will continue to run in parallel, just not the rest of the method.

This waiting to complete running the rest of the method may or may not be desirable. If nothing in that method later accesses the parameters passed to the Task you may not want to use await at all.

Or maybe you use those parameters much later on in the method. No reason to await immediately as you could continue safely doing work. Remember, you can store the Task returned in a variable and await on it later - even in the same method. For instance, once you need to access the passed parameters safely after doing a bunch some other work. Again, you do not need to await on the Task right when you run it.

Anyways, a simple way to make this thread-safe with respect to the parameters passed to Task.Run is to do this:

You must first decorate RunAsync with async:

private async void RunAsync()

Important Note

Preferably the method marked async should not return void, as the linked documentation mentions. The common exception to this is event handlers such as button clicks and such. They must return void. Otherwise I always try to return a Task or Task<TResult> when using async. It's good practice for a quite a few reasons.

Now you can await running the Task like below. You cannot use await without async.

await Task.Run(() => MethodWithParameter(param));
//Code here and below in the same method will not run until AFTER the above task has completed in one fashion or another

So, in general, if you await the task you can avoid treating passed in parameters as a potentially shared resource with all the pitfalls of modifying something from multiple threads at once. Also, beware of closures. I won't cover those in depth but the linked article does a great job of it.

Side Note

A bit off topic, but be careful using any type of "blocking" on the WinForms GUI thread due to it being marked with [STAThread]. Using await won't block at all, but I do sometimes see it used in conjunction with some sort of blocking.

"Block" is in quotes because you technically cannot block the WinForms GUI thread. Yes, if you use lock on the WinForms GUI thread it will still pump messages, despite you thinking it's "blocked". It's not.

This can cause bizarre issues in very rare cases. One of the reasons you never want to use a lock when painting, for example. But that's a fringe and complex case; however I've seen it cause crazy issues. So I noted it for completeness sake.

JSON post to Spring Controller

Do the following thing if you want to use json as a http request and response. So we need to make changes in [context].xml

<!-- Configure to plugin JSON as request and response in method handler -->
<beans:bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
    <beans:property name="messageConverters">
        <beans:list>
            <beans:ref bean="jsonMessageConverter"/>
        </beans:list>
    </beans:property>
</beans:bean>
<!-- Configure bean to convert JSON to POJO and vice versa -->
<beans:bean id="jsonMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
</beans:bean>   

MappingJackson2HttpMessageConverter to the RequestMappingHandlerAdapter messageConverters so that Jackson API kicks in and converts JSON to Java Beans and vice versa. By having this configuration, we will be using JSON in request body and we will receive JSON data in the response.

I am also providing small code snippet for controller part:

    @RequestMapping(value = EmpRestURIConstants.DUMMY_EMP, method = RequestMethod.GET)

    public @ResponseBody Employee getDummyEmployee() {
    logger.info("Start getDummyEmployee");
    Employee emp = new Employee();
    emp.setId(9999);
    emp.setName("Dummy");
    emp.setCreatedDate(new Date());
    empData.put(9999, emp);
    return emp;
}

So in above code emp object will directly convert into json as a response. same will happen for post also.

Counting array elements in Python

len is a built-in function that calls the given container object's __len__ member function to get the number of elements in the object.

Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).

Using obj.__len__() wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

For any one who is having multidex enable write this

inside build.gradle

apply plugin: 'com.android.application'

android {
 defaultConfig {
      multiDexEnabled true
  }
 dexOptions {
        javaMaxHeapSize "4g"
    }
}

dependencies {
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.google.android.gms:play-services:+'
    compile 'com.android.support:multidex:1.0.1'
}

write a class EnableMultiDex like below

import android.content.Context;
import android.support.multidex.MultiDexApplication;

public class EnableMultiDex extends MultiDexApplication {
    private static EnableMultiDex enableMultiDex;
    public static Context context;

    public EnableMultiDex(){
        enableMultiDex=this;
    }

    public static EnableMultiDex getEnableMultiDexApp() {
        return enableMultiDex;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        context = getApplicationContext();

    }
}

and in AndroidManifest.xml write this className inside Application tag

 <application
    android:name="YourPakageName.EnableMultiDex"
    android:hardwareAccelerated="true"
    android:icon="@drawable/wowio_launch_logo"
    android:label="@string/app_name"
    android:largeHeap="true"
    tools:node="replace">

Running an executable in Mac Terminal

To run an executable in mac

1). Move to the path of the file:

cd/PATH_OF_THE_FILE

2). Run the following command to set the file's executable bit using the chmod command:

chmod +x ./NAME_OF_THE_FILE

3). Run the following command to execute the file:

./NAME_OF_THE_FILE

Once you have run these commands, going ahead you just have to run command 3, while in the files path.

Generating Fibonacci Sequence

Here's a simple function to iterate the Fibonacci sequence into an array using arguments in the for function more than the body of the loop:

fib = function(numMax){
    for(var fibArray = [0,1], i=0,j=1,k=0; k<numMax;i=j,j=x,k++ ){
        x=i+j;
        fibArray.push(x);
    }
    console.log(fibArray);
}

fib(10)

[ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89 ]

What is a NoReverseMatch error, and how do I fix it?

The NoReverseMatch error is saying that Django cannot find a matching url pattern for the url you've provided in any of your installed app's urls.

The NoReverseMatch exception is raised by django.core.urlresolvers when a matching URL in your URLconf cannot be identified based on the parameters supplied.

To start debugging it, you need to start by disecting the error message given to you.

  • NoReverseMatch at /my_url/

    This is the url that is currently being rendered, it is this url that your application is currently trying to access but it contains a url that cannot be matched

  • Reverse for 'my_url_name'

    This is the name of the url that it cannot find

  • with arguments '()' and

    These are the non-keyword arguments its providing to the url

  • keyword arguments '{}' not found.

    These are the keyword arguments its providing to the url

  • n pattern(s) tried: []

    These are the patterns that it was able to find in your urls.py files that it tried to match against

Start by locating the code in your source relevant to the url that is currently being rendered - the url, the view, and any templates involved. In most cases, this will be the part of the code you're currently developing.

Once you've done this, read through the code in the order that django would be following until you reach the line of code that is trying to construct a url for your my_url_name. Again, this is probably in a place you've recently changed.

Now that you've discovered where the error is occuring, use the other parts of the error message to work out the issue.

The url name

  • Are there any typos?
  • Have you provided the url you're trying to access the given name?
  • If you have set app_name in the app's urls.py (e.g. app_name = 'my_app') or if you included the app with a namespace (e.g. include('myapp.urls', namespace='myapp'), then you need to include the namespace when reversing, e.g. {% url 'myapp:my_url_name' %} or reverse('myapp:my_url_name').

Arguments and Keyword Arguments

The arguments and keyword arguments are used to match against any capture groups that are present within the given url which can be identified by the surrounding () brackets in the url pattern.

Assuming the url you're matching requires additional arguments, take a look in the error message and first take a look if the value for the given arguments look to be correct.

If they aren't correct:

  • The value is missing or an empty string

    This generally means that the value you're passing in doesn't contain the value you expect it to be. Take a look where you assign the value for it, set breakpoints, and you'll need to figure out why this value doesn't get passed through correctly.

  • The keyword argument has a typo

    Correct this either in the url pattern, or in the url you're constructing.

If they are correct:

  • Debug the regex

    You can use a website such as regexr to quickly test whether your pattern matches the url you think you're creating, Copy the url pattern into the regex field at the top, and then use the text area to include any urls that you think it should match against.

    Common Mistakes:

    • Matching against the . wild card character or any other regex characters

      Remember to escape the specific characters with a \ prefix

    • Only matching against lower/upper case characters

      Try using either a-Z or \w instead of a-z or A-Z

  • Check that pattern you're matching is included within the patterns tried

    If it isn't here then its possible that you have forgotten to include your app within the INSTALLED_APPS setting (or the ordering of the apps within INSTALLED_APPS may need looking at)

Django Version

In Django 1.10, the ability to reverse a url by its python path was removed. The named path should be used instead.


If you're still unable to track down the problem, then feel free to ask a new question that includes what you've tried, what you've researched (You can link to this question), and then include the relevant code to the issue - the url that you're matching, any relevant url patterns, the part of the error message that shows what django tried to match, and possibly the INSTALLED_APPS setting if applicable.

How to calculate a logistic sigmoid function in Python?

Vectorized method when using pandas DataFrame/Series or numpy array:

The top answers are optimized methods for single point calculation, but when you want to apply these methods to a pandas series or numpy array, it requires apply, which is basically for loop in the background and will iterate over every row and apply the method. This is quite inefficient.

To speed up our code, we can make use of vectorization and numpy broadcasting:

x = np.arange(-5,5)
np.divide(1, 1+np.exp(-x))

0    0.006693
1    0.017986
2    0.047426
3    0.119203
4    0.268941
5    0.500000
6    0.731059
7    0.880797
8    0.952574
9    0.982014
dtype: float64

Or with a pandas Series:

x = pd.Series(np.arange(-5,5))
np.divide(1, 1+np.exp(-x))

How do I make an asynchronous GET request in PHP?

Nobody seems to mention Guzzle, which is a PHP HTTP client that makes it easy to send HTTP requests. It can work with or without Curl. It can send both synchronous and asynchronous requests.

$client = new GuzzleHttp\Client();
$promise = $client->requestAsync('GET', 'http://httpbin.org/get');
$promise->then(
    function (ResponseInterface $res) {
        echo $res->getStatusCode() . "\n";
    },
    function (RequestException $e) {
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
);

How to use OAuth2RestTemplate?

In the answer from @mariubog (https://stackoverflow.com/a/27882337/1279002) I was using password grant types too as in the example but needed to set the client authentication scheme to form. Scopes were not supported by the endpoint for password and there was no need to set the grant type as the ResourceOwnerPasswordResourceDetails object sets this itself in the constructor.

...

public ResourceOwnerPasswordResourceDetails() {
    setGrantType("password");
}

...

The key thing for me was the client_id and client_secret were not being added to the form object to post in the body if resource.setClientAuthenticationScheme(AuthenticationScheme.form); was not set.

See the switch in: org.springframework.security.oauth2.client.token.auth.DefaultClientAuthenticationHandler.authenticateTokenRequest()

Finally, when connecting to Salesforce endpoint the password token needed to be appended to the password.

@EnableOAuth2Client
@Configuration
class MyConfig {

@Value("${security.oauth2.client.access-token-uri}")
private String tokenUrl;

@Value("${security.oauth2.client.client-id}")
private String clientId;

@Value("${security.oauth2.client.client-secret}")
private String clientSecret;

@Value("${security.oauth2.client.password-token}")
private String passwordToken;

@Value("${security.user.name}")
private String username;

@Value("${security.user.password}")
private String password;


@Bean
protected OAuth2ProtectedResourceDetails resource() {

    ResourceOwnerPasswordResourceDetails resource = new ResourceOwnerPasswordResourceDetails();

    resource.setAccessTokenUri(tokenUrl);
    resource.setClientId(clientId);
    resource.setClientSecret(clientSecret);
    resource.setClientAuthenticationScheme(AuthenticationScheme.form);
    resource.setUsername(username);
    resource.setPassword(password + passwordToken);

    return resource;
}

@Bean
 public OAuth2RestOperations restTemplate() {
    return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(new DefaultAccessTokenRequest()));
    }
}


@Service
@SuppressWarnings("unchecked")
class MyService {
    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

How to echo JSON in PHP

Native JSON support has been included in PHP since 5.2 in the form of methods json_encode() and json_decode(). You would use the first to output a PHP variable in JSON.

Programmatically set left drawable in a TextView

there are two ways of doing it either you can use XML or Java for it. If it's static and requires no changes then you can initialize in XML.

  android:drawableLeft="@drawable/cloud_up"
    android:drawablePadding="5sp"

Now if you need to change the icons dynamically then you can do it by calling the icons based on the events

       textViewContext.setText("File Uploaded");
textViewContext.setCompoundDrawablesWithIntrinsicBounds(R.drawable.uploaded, 0, 0, 0);

JPA - Returning an auto generated id after persist()

This is how I did it:

EntityManager entityManager = getEntityManager();
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
entityManager.persist(object);
transaction.commit();
long id = object.getId();
entityManager.close();

Read remote file with node.js (http.get)

http.get(options).on('response', function (response) {
    var body = '';
    var i = 0;
    response.on('data', function (chunk) {
        i++;
        body += chunk;
        console.log('BODY Part: ' + i);
    });
    response.on('end', function () {

        console.log(body);
        console.log('Finished');
    });
});

Changes to this, which works. Any comments?

Finding Number of Cores in Java

int cores = Runtime.getRuntime().availableProcessors();

If cores is less than one, either your processor is about to die, or your JVM has a serious bug in it, or the universe is about to blow up.

OpenCV - DLL missing, but it's not?

The ".a" at the end of your DLL files is a problem, and those are there because you didn't use CMAKE to build OpenCV 2.0. Additionally you do not link to the DLL files, you link to the library files, and again, the reason you do not see the correct library files is because you didn't use CMAKE to build OpenCV 2.0. If you want to use OpenCV 2.0 you must build it for it to work correctly in Visual Studio. If you do not want to build it then I would suggest downgrading to OpenCV 1.1pre, it comes pre-built and is much more forgiving in Visual Studio.

Another option (and the one I would recommend) is to abandon OpenCV and go with EmguCV. I have been playing with OpenCV for about a year and things got much easier when I switched to EmguCV because EmguCV works with .NET, so you can use a language like C# that does not come with all the C++ baggage of pointers, header files, and memory allocation problem.

And as for the question of 64bit vs. 32bit, OpenCV does not officially support 64bit. To be on the safe side open your project properties and change the "Platform Target" under the "Build" tab from "Any CPU" to "X86". This should be done any time you do anything with OpenCV, even if you are using a wrapper like EmguCV.

Cursor inside cursor

Do you do any more fetches? You should show those as well. You're only showing us half the code.

It should look like:

FETCH NEXT FROM @Outer INTO ...
WHILE @@FETCH_STATUS = 0
BEGIN
  DECLARE @Inner...
  OPEN @Inner
  FETCH NEXT FROM @Inner INTO ...
  WHILE @@FETCH_STATUS = 0
  BEGIN
  ...
    FETCH NEXT FROM @Inner INTO ...
  END
  CLOSE @Inner
  DEALLOCATE @Inner
  FETCH NEXT FROM @Outer INTO ...
END
CLOSE @Outer
DEALLOCATE @Outer

Also, make sure you do not name the cursors the same... and any code (check your triggers) that gets called does not use a cursor that is named the same. I've seen odd behavior from people using 'theCursor' in multiple layers of the stack.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

I've read, this is a symbol of Arrow Functions in ES6

this

var a2 = a.map(function(s){ return s.length });

using Arrow Function can be written as

var a3 = a.map( s => s.length );

MDN Docs

Convert seconds to hh:mm:ss in Python

Besides the fact that Python has built in support for dates and times (see bigmattyh's response), finding minutes or hours from seconds is easy:

minutes = seconds / 60
hours = minutes / 60

Now, when you want to display minutes or seconds, MOD them by 60 so that they will not be larger than 59

bash string compare to multiple correct values

As @Renich suggests (but with an important typo that has not been fixed unfortunately), you can also use extended globbing for pattern matching. So you can use the same patterns you use to match files in command arguments (e.g. ls *.pdf) inside of bash comparisons.

For your particular case you can do the following.

if [[ "${cms}" != @(wordpress|magento|typo3) ]]

The @ means "Matches one of the given patterns". So this is basically saying cms is not equal to 'wordpress' OR 'magento' OR 'typo3'. In normal regular expression syntax @ is similar to just ^(wordpress|magento|typo3)$.

Mitch Frazier has two good articles in the Linux Journal on this Pattern Matching In Bash and Bash Extended Globbing.

For more background on extended globbing see Pattern Matching (Bash Reference Manual).

TypeScript error TS1005: ';' expected (II)

  • Remove C:\Program Files (x86)\Microsoft SDKs\TypeScript\1.0 directory.

  • Now run :

    npm install -g typescript 
    

    this will install the latest version and then re-try.

Using SSH keys inside docker container

In later versions of docker (17.05) you can use multi stage builds. Which is the safest option as the previous builds can only ever be used by the subsequent build and are then destroyed

See the answer to my stackoverflow question for more info

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

Not including the action attribute opens the page up to iframe clickjacking attacks, which involve a few simple steps:

  • An attacker wraps your page in an iframe
  • The iframe URL includes a query param with the same name as a form field
  • When the form is submitted, the query value is inserted into the database
  • The user's identifying information (email, address, etc) has been compromised

References

What causes java.lang.IncompatibleClassChangeError?

If this is a record of possible occurences of this error then:

I just got this error on WAS (8.5.0.1), during the CXF (2.6.0) loading of the spring (3.1.1_release) configuration where a BeanInstantiationException rolled up a CXF ExtensionException, rolling up a IncompatibleClassChangeError. The following snippet shows the gist of the stack trace:

Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.apache.cxf.bus.spring.SpringBus]: Constructor threw exception; nested exception is org.apache.cxf.bus.extension.ExtensionException
            at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
            at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)
            ... 116 more
Caused by: org.apache.cxf.bus.extension.ExtensionException
            at org.apache.cxf.bus.extension.Extension.tryClass(Extension.java:167)
            at org.apache.cxf.bus.extension.Extension.getClassObject(Extension.java:179)
            at org.apache.cxf.bus.extension.ExtensionManagerImpl.activateAllByType(ExtensionManagerImpl.java:138)
            at org.apache.cxf.bus.extension.ExtensionManagerBus.<init>(ExtensionManagerBus.java:131)
            [etc...]
            at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
            ... 118 more

Caused by: java.lang.IncompatibleClassChangeError: 
org.apache.neethi.AssertionBuilderFactory
            at java.lang.ClassLoader.defineClassImpl(Native Method)
            at java.lang.ClassLoader.defineClass(ClassLoader.java:284)
            [etc...]
            at com.ibm.ws.classloader.CompoundClassLoader.loadClass(CompoundClassLoader.java:586)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:658)
            at org.apache.cxf.bus.extension.Extension.tryClass(Extension.java:163)
            ... 128 more

In this case, the solution was to change the classpath order of the module in my war file. That is, open up the war application in the WAS console under and select the client module(s). In the module configuration, set the class-loading to be "parent last".

This is found in the WAS console:

  • Applicatoins -> Application Types -> WebSphere Enterprise Applications
  • Click link representing your application (war)
  • Click "Manage Modules" under "Modules" section
  • Click link for the underlying module(s)
  • Change "Class loader order" to be "(parent last)".

How to get phpmyadmin username and password

 Step 1:

    Locate phpMyAdmin installation path.

    Step 2:

    Open phpMyAdmin>config.inc.php in your favourite text editor.

    Step 3:

    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = true;
    $cfg['Lang'] = '';

How to use MySQL DECIMAL?

Although the answers above seems correct, just a simple explanation to give you an idea of how it works.

Suppose that your column is set to be DECIMAL(13,4). This means that the column will have a total size of 13 digits where 4 of these will be used for precision representation.

So, in summary, for that column you would have a max value of: 999999999.9999

Best Practices for Custom Helpers in Laravel 5

Custom Blade Directives in Laravel 5

Yes, there is another way to do this!

Step 1: Register a custom Blade directive:

<?php // code in app/Providers/AppServiceProvider.php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Blade; // <-- This is important! Without it you'll get an exception.

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
     public function boot()
     {
         // Make a custom blade directive:
         Blade::directive('shout', function ($string) {
             return trim(strtoupper($string), '(\'\')');
         });

         // And another one for good measure:
         Blade::directive('customLink', function () {
             return '<a href="#">Custom Link</a>';
         });
     }
    ...

Step 2: Use your custom Blade directive:

<!-- // code in resources/views/view.blade.php -->

@shout('this is my custom blade directive!!')
<br />
@customLink

Outputs:

THIS IS MY CUSTOM BLADE DIRECTIVE!!
Custom Link


Source: https://laravel.com/docs/5.1/blade#extending-blade

Additional Reading: https://mattstauffer.co/blog/custom-conditionals-with-laravels-blade-directives


If you want to learn how to best make custom classes that you can use anywhere, see Custom Classes in Laravel 5, the Easy Way

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

SQL Server: Filter output of sp_who2

Slight improvement to Astander's answer. I like to put my criteria at top, and make it easier to reuse day to day:

DECLARE @Spid INT, @Status VARCHAR(MAX), @Login VARCHAR(MAX), @HostName VARCHAR(MAX), @BlkBy VARCHAR(MAX), @DBName VARCHAR(MAX), @Command VARCHAR(MAX), @CPUTime INT, @DiskIO INT, @LastBatch VARCHAR(MAX), @ProgramName VARCHAR(MAX), @SPID_1 INT, @REQUESTID INT

    --SET @SPID = 10
    --SET @Status = 'BACKGROUND'
    --SET @LOGIN = 'sa'
    --SET @HostName = 'MSSQL-1'
    --SET @BlkBy = 0
    --SET @DBName = 'master'
    --SET @Command = 'SELECT INTO'
    --SET @CPUTime = 1000
    --SET @DiskIO = 1000
    --SET @LastBatch = '10/24 10:00:00'
    --SET @ProgramName = 'Microsoft SQL Server Management Studio - Query'
    --SET @SPID_1 = 10
    --SET @REQUESTID = 0

    SET NOCOUNT ON 
    DECLARE @Table TABLE(
            SPID INT,
            Status VARCHAR(MAX),
            LOGIN VARCHAR(MAX),
            HostName VARCHAR(MAX),
            BlkBy VARCHAR(MAX),
            DBName VARCHAR(MAX),
            Command VARCHAR(MAX),
            CPUTime INT,
            DiskIO INT,
            LastBatch VARCHAR(MAX),
            ProgramName VARCHAR(MAX),
            SPID_1 INT,
            REQUESTID INT
    )
    INSERT INTO @Table EXEC sp_who2
    SET NOCOUNT OFF
    SELECT  *
    FROM    @Table
    WHERE
    (@Spid IS NULL OR SPID = @Spid)
    AND (@Status IS NULL OR Status = @Status)
    AND (@Login IS NULL OR Login = @Login)
    AND (@HostName IS NULL OR HostName = @HostName)
    AND (@BlkBy IS NULL OR BlkBy = @BlkBy)
    AND (@DBName IS NULL OR DBName = @DBName)
    AND (@Command IS NULL OR Command = @Command)
    AND (@CPUTime IS NULL OR CPUTime >= @CPUTime)
    AND (@DiskIO IS NULL OR DiskIO >= @DiskIO)
    AND (@LastBatch IS NULL OR LastBatch >= @LastBatch)
    AND (@ProgramName IS NULL OR ProgramName = @ProgramName)
    AND (@SPID_1 IS NULL OR SPID_1 = @SPID_1)
    AND (@REQUESTID IS NULL OR REQUESTID = @REQUESTID)

How to change MySQL column definition?

Do you mean altering the table after it has been created? If so you need to use alter table, in particular:

ALTER TABLE tablename MODIFY COLUMN new-column-definition

e.g.

ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);

Why does ASP.NET webforms need the Runat="Server" attribute?

If you use it on normal html tags, it means that you can programatically manipulate them in event handlers etc, eg change the href or class of an anchor tag on page load... only do that if you have to, because vanilla html tags go faster.

As far as user controls and server controls, no, they just wont work without them, without having delved into the innards of the aspx preprocessor, couldn't say exactly why, but would take a guess that for probably good reasons, they just wrote the parser that way, looking for things explicitly marked as "do something".

If @JonSkeet is around anywhere, he will probably be able to provide a much better answer.

Is there any way to debug chrome in any IOS device

Old Answer (July 2016):

You can't directly debug Chrome for iOS due to restrictions on the published WKWebView apps, but there are a few options already discussed in other SO threads:

  1. If you can reproduce the issue in Safari as well, then use Remote Debugging with Safari Web Inspector. This would be the easiest approach.

  2. WeInRe allows some simple debugging, using a simple client-server model. It's not fully featured, but it may well be enough for your problem. See instructions on set up here.

  3. You could try and create a simple WKWebView browser app (some instructions here), or look for an existing one on GitHub. Since Chrome uses the same rendering engine, you could debug using that, as it will be close to what Chrome produces.

There's a "bug" opened up for WebKit: Allow Web Inspector usage for release builds of WKWebView. If and when we get an API to WKWebView, Chrome for iOS would be debuggable.

Update January 2018:

Since my answer back in 2016, some work has been done to improve things.

There is a recent project called RemoteDebug iOS WebKit Adapter, by some of the Microsoft team. It's an adapter that handles the API differences between Webkit Remote Debugging Protocol and Chrome Debugging Protocol, and this allows you to debug iOS WebViews in any app that supports the protocol - Chrome DevTools, VS Code etc.

Check out the getting started guide in the repo, which is quite detailed.

If you are interesting, you can read up on the background and architecture here.

jQuery: keyPress Backspace won't fire?

Use keyup instead of keypress. This gets all the key codes when the user presses something

List to array conversion to use ravel() function

Use the following code:

import numpy as np

myArray=np.array([1,2,4])  #func used to convert [1,2,3] list into an array
print(myArray)

TypeScript Objects as Dictionary types as in C#

In newer versions of typescript you can use:

type Customers = Record<string, Customer>

In older versions you can use:

var map: { [email: string]: Customer; } = { };
map['[email protected]'] = new Customer(); // OK
map[14] = new Customer(); // Not OK, 14 is not a string
map['[email protected]'] = 'x'; // Not OK, 'x' is not a customer

You can also make an interface if you don't want to type that whole type annotation out every time:

interface StringToCustomerMap {
    [email: string]: Customer;
}

var map: StringToCustomerMap = { };
// Equivalent to first line of above

Get HTML code from website in C#

You can use WebClient to download the html for any url. Once you have the html, you can use a third-party library like HtmlAgilityPack to lookup values in the html as in below code -

public static string GetInnerHtmlFromDiv(string url)
    {
        string HTML;
        using (var wc = new WebClient())
        {
            HTML = wc.DownloadString(url);
        }
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(HTML);
        
        HtmlNode element = doc.DocumentNode.SelectSingleNode("//div[@id='<div id here>']");
        if (element != null)
        {
            return element.InnerHtml.ToString();
        }   
        return null;            
    }

How to undo the last commit in git

I think you haven't messed up yet. Try:

git reset HEAD^

This will bring the dir to state before you've made the commit, HEAD^ means the parent of the current commit (the one you don't want anymore), while keeping changes from it (unstaged).

How to save an activity state using save instance state?

The savedInstanceState is only for saving state associated with a current instance of an Activity, for example current navigation or selection info, so that if Android destroys and recreates an Activity, it can come back as it was before. See the documentation for onCreate and onSaveInstanceState

For more long lived state, consider using a SQLite database, a file, or preferences. See Saving Persistent State.

Do we need type="text/css" for <link> in HTML5

Don’t need to specify a type value of “text/css”

Every time you link to a CSS file:

<link rel="stylesheet" type="text/css" href="file.css">

You can simply write:

<link rel="stylesheet" href="file.css">

How do I drop a foreign key constraint only if it exists in sql server?

Declare @FKeyRemoveQuery NVarchar(max)

IF EXISTS(SELECT 1 FROM sys.foreign_keys WHERE parent_object_id = OBJECT_ID(N'dbo.TableName'))

BEGIN
    SELECT @FKeyRemoveQuery='ALTER TABLE dbo.TableName DROP CONSTRAINT [' + LTRIM(RTRIM([name])) + ']'   
    FROM sys.foreign_keys
    WHERE parent_object_id = OBJECT_ID(N'dbo.TableName')

    EXECUTE Sp_executesql @FKeyRemoveQuery 

END

Converting Swagger specification JSON to HTML documentation

Try to use redoc-cli.

I was using bootprint-openapi by which I was generating a bunch of files (bundle.js, bundle.js.map, index.html, main.css and main.css.map) and then you can convert it into a single .html file using html-inline to generate a simple index.html file.

Then I found redoc-cli very easy to to use and output is really-2 awesome, a single and beautiful index.html file.

Installation:

npm install -g redoc-cli

Usage:

redoc-cli bundle -o index.html swagger.json

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

The common name in the certicate for api.evercam.io is for *.herokuapp.com and there are no alternative subject names in the certificate. This means, that the certificate for api.evercam.io does not match the hostname and therefore the certificate verification fails. Same as true for www.evercam.io, e.g. try https://www.evercam.io with a browser and you get the error message, that the name in the certificate does not match the hostname.

So it is a problem which needs to be fixed by evercam.io. If you don't care about security, man-in-the-middle attacks etc you might disable verification of the certificate (curl --insecure), but then you should ask yourself why you use https instead of http at all.

Checking if my Windows application is running

Enter a guid in your assembly data. Add this guid to the registry. Enter a reg key where the application read it's own name and add the name as value there.

The other task watcher read the reg key and knows the app name.

socket connect() vs bind()

I think it would help your comprehension if you think of connect() and listen() as counterparts, rather than connect() and bind(). The reason for this is that you can call or omit bind() before either, although it's rarely a good idea to call it before connect(), or not to call it before listen().

If it helps to think in terms of servers and clients, it is listen() which is the hallmark of the former, and connect() the latter. bind() can be found - or not found - on either.

If we assume our server and client are on different machines, it becomes easier to understand the various functions.

bind() acts locally, which is to say it binds the end of the connection on the machine on which it is called, to the requested address and assigns the requested port to you. It does that irrespective of whether that machine will be a client or a server. connect() initiates a connection to a server, which is to say it connects to the requested address and port on the server, from a client. That server will almost certainly have called bind() prior to listen(), in order for you to be able to know on which address and port to connect to it with using connect().

If you don't call bind(), a port and address will be implicitly assigned and bound on the local machine for you when you call either connect() (client) or listen() (server). However, that's a side effect of both, not their purpose. A port assigned in this manner is ephemeral.

An important point here is that the client does not need to be bound, because clients connect to servers, and so the server will know the address and port of the client even though you are using an ephemeral port, rather than binding to something specific. On the other hand, although the server could call listen() without calling bind(), in that scenario they would need to discover their assigned ephemeral port, and communicate that to any client that it wants to connect to it.

I assume as you mention connect() you're interested in TCP, but this also carries over to UDP, where not calling bind() before the first sendto() (UDP is connection-less) also causes a port and address to be implicitly assigned and bound. One function you cannot call without binding is recvfrom(), which will return an error, because without an assigned port and bound address, there is nothing to receive from (or too much, depending on how you interpret the absence of a binding).

How can I use external JARs in an Android project?

I know the OP ends his question with reference to the Eclipse plugin, but I arrived here with a search that didn't specify Eclipse. So here goes for Android Studio:

  1. Add jar file to libs directory (such as copy/paste)
  2. Right-Click on jar file and select "Add as Library..."
  3. click "Ok" on next dialog or renamed if you choose to.

That's it!

Showing data values on stacked bar chart in ggplot2

From ggplot 2.2.0 labels can easily be stacked by using position = position_stack(vjust = 0.5) in geom_text.

ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
  geom_bar(stat = "identity") +
  geom_text(size = 3, position = position_stack(vjust = 0.5))

enter image description here

Also note that "position_stack() and position_fill() now stack values in the reverse order of the grouping, which makes the default stack order match the legend."


Answer valid for older versions of ggplot:

Here is one approach, which calculates the midpoints of the bars.

library(ggplot2)
library(plyr)

# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year), 
   transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)

# library(dplyr) ## If using dplyr... 
# Data <- group_by(Data,Year) %>%
#    mutate(pos = cumsum(Frequency) - (0.5 * Frequency))

# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
     geom_bar(aes(fill = Category), stat="identity") +
     geom_text(aes(label = Frequency, y = pos), size = 3)

Resultant chart

How to select data where a field has a min value in MySQL?

this will give you result that has the minimum price on all records.

SELECT *
FROM pieces
WHERE price =  ( SELECT MIN(price) FROM pieces )

Getting multiple values with scanf()

Passable for getting multiple values with scanf()

int r,m,v,i,e,k;

scanf("%d%d%d%d%d%d",&r,&m,&v,&i,&e,&k);

Running a cron job at 2:30 AM everyday

crontab -e

add:

30 2 * * * /your/command

"Unable to acquire application service" error while launching Eclipse

in my opinion, if after trying all solution nothing wors then simply delete eclipse folder from your C://use/{pc}/eclipse and then again install the same eclipse . You will get all your data no need to worry.

This happens because of unexpected shutdown of your eclipse

Class Diagrams in VS 2017

the following procedure worked for me:

  • Close VS.
  • Run Visual Studio Installer.
  • Click on the 'Modify' button under 'Visual Studio Professional 2017'
  • In the new window, scroll down and select 'Visual Studio Extension Development' under 'Other Toolsets'.
  • Then on the right, if not selected yet, click on 'Class Designer'
  • Click on 'Modify' to confirm

Where is Java's Array indexOf?

Unlike in C# where you have the Array.IndexOf method, and JavaScript where you have the indexOf method, Java's API (the Array and Arrays classes in particular) have no such method.

This method indexOf (together with its complement lastIndexOf) is defined in the java.util.List interface. Note that indexOf and lastIndexOf are not overloaded and only take an Object as a parameter.

If your array is sorted, you are in luck because the Arrays class defines a series of overloads of the binarySearch method that will find the index of the element you are looking for with best possible performance (O(log n) instead of O(n), the latter being what you can expect from a sequential search done by indexOf). There are four considerations:

  1. The array must be sorted either in natural order or in the order of a Comparator that you provide as an argument, or at the very least all elements that are "less than" the key must come before that element in the array and all elements that are "greater than" the key must come after that element in the array;

  2. The test you normally do with indexOf to determine if a key is in the array (verify if the return value is not -1) does not hold with binarySearch. You need to verify that the return value is not less than zero since the value returned will indicate the key is not present but the index at which it would be expected if it did exist;

  3. If your array contains multiple elements that are equal to the key, what you get from binarySearch is undefined; this is different from indexOf that will return the first occurrence and lastIndexOf that will return the last occurrence.

  4. An array of booleans might appear to be sorted if it first contains all falses and then all trues, but this doesn't count. There is no override of the binarySearch method that accepts an array of booleans and you'll have to do something clever there if you want O(log n) performance when detecting where the first true appears in an array, for instance using an array of Booleans and the constants Boolean.FALSE and Boolean.TRUE.

If your array is not sorted and not primitive type, you can use List's indexOf and lastIndexOf methods by invoking the asList method of java.util.Arrays. This method will return an AbstractList interface wrapper around your array. It involves minimal overhead since it does not create a copy of the array. As mentioned, this method is not overloaded so this will only work on arrays of reference types.

If your array is not sorted and the type of the array is primitive, you are out of luck with the Java API. Write your own for loop, or your own static utility method, which will certainly have performance advantages over the asList approach that involves some overhead of an object instantiation. In case you're concerned that writing a brute force for loop that iterates over all of the elements of the array is not an elegant solution, accept that that is exactly what the Java API is doing when you call indexOf. You can make something like this:

public static int indexOfIntArray(int[] array, int key) {
    int returnvalue = -1;
    for (int i = 0; i < array.length; ++i) {
        if (key == array[i]) {
            returnvalue = i;
            break;
        }
    }
    return returnvalue;
}

If you want to avoid writing your own method here, consider using one from a development framework like Guava. There you can find an implementation of indexOf and lastIndexOf.

How can I parse a CSV string with JavaScript, which contains comma in data?

I've used regex a number of times, but I always have to relearn it each time, which is frustrating :-)

So Here's a non-regex solution:

function csvRowToArray(row, delimiter = ',', quoteChar = '"'){
    let nStart = 0, nEnd = 0, a=[], nRowLen=row.length, bQuotedValue;
    while (nStart <= nRowLen) {
        bQuotedValue = (row.charAt(nStart) === quoteChar);
        if (bQuotedValue) {
            nStart++;
            nEnd = row.indexOf(quoteChar + delimiter, nStart)
        } else {
            nEnd = row.indexOf(delimiter, nStart)
        }
        if (nEnd < 0) nEnd = nRowLen;
        a.push(row.substring(nStart,nEnd));
        nStart = nEnd + delimiter.length + (bQuotedValue ? 1 : 0)
    }
    return a;
}

How it works:

  1. Pass in the csv string in row.
  2. While the start position of the next value is within the row, do the following:
    • If this value has been quoted, set nEnd to the closing quote.
    • Else if value has NOT been quoted, set nEnd to the next delimiter.
    • Add the value to an array.
    • Set nStart to nEnd plus the length of the delimeter.

Sometimes it's good to write your own small function, rather than use a library. Your own code is going to perform well and use only a small footprint. In addition, you can easily tweak it to suit your own needs.

Vector of Vectors to create matrix

As it is, both dimensions of your vector are 0.

Instead, initialize the vector as this:

vector<vector<int> > matrix(RR);
for ( int i = 0 ; i < RR ; i++ )
   matrix[i].resize(CC);

This will give you a matrix of dimensions RR * CC with all elements set to 0.

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

No Need to manually start an application every time at time of development to implements changes use 'spring-boot-devtool' maven dependency.

Automatic Restart : To use the module you simply need to add it as a dependency in your Maven POM:

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>

When you have the spring-boot-devtools module included, any classpath file changes will automatically trigger an application restart. We do some tricks to try and keep restarts fast, so for many microservice style applications this technique might be good enough.

Make ABC Ordered List Items Have Bold Style

You could do something like this also:

ol {
  font-weight: bold;
}

ol > li > * {
  font-weight: normal;
}

So you have no "style" attributes in your HTML

How to grant remote access permissions to mysql server for user?

In my case I was trying to connect to a remote mysql server on cent OS. After going through a lot of solutions (granting all privileges, removing ip bindings,enabling networking) problem was still not getting solved.

As it turned out, while looking into various solutions,I came across iptables, which made me realize mysql port 3306 was not accepting connections.

Here is a small note on how I checked and resolved this issue.

  • Checking if port is accepting connections:
telnet (mysql server ip) [portNo]

-Adding ip table rule to allow connections on the port:

iptables -A INPUT -i eth0 -p tcp -m tcp --dport 3306 -j ACCEPT

-Would not recommend this for production environment, but if your iptables are not configured properly, adding the rules might not still solve the issue. In that case following should be done:

service iptables stop

Hope this helps.

How to change JFrame icon

Here is an Alternative that worked for me:

yourFrame.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource(Filepath)));

It's very similar to the accepted Answer.

?: operator (the 'Elvis operator') in PHP

It evaluates to the left operand if the left operand is truthy, and the right operand otherwise.

In pseudocode,

foo = bar ?: baz;

roughly resolves to

foo = bar ? bar : baz;

or

if (bar) {
    foo = bar;
} else {
    foo = baz;
}

with the difference that bar will only be evaluated once.

You can also use this to do a "self-check" of foo as demonstrated in the code example you posted:

foo = foo ?: bar;

This will assign bar to foo if foo is null or falsey, else it will leave foo unchanged.

Some more examples:

<?php
    var_dump(5 ?: 0); // 5
    var_dump(false ?: 0); // 0
    var_dump(null ?: 'foo'); // 'foo'
    var_dump(true ?: 123); // true
    var_dump('rock' ?: 'roll'); // 'rock'
?>

By the way, it's called the Elvis operator.

Elvis operator

postgresql COUNT(DISTINCT ...) very slow

You can use this:

SELECT COUNT(*) FROM (SELECT DISTINCT column_name FROM table_name) AS temp;

This is much faster than:

COUNT(DISTINCT column_name)

Call a Vue.js component method from outside the component

In the end I opted for using Vue's ref directive. This allows a component to be referenced from the parent for direct access.

E.g.

Have a compenent registered on my parent instance:

var vm = new Vue({
    el: '#app',
    components: { 'my-component': myComponent }
});

Render the component in template/html with a reference:

<my-component ref="foo"></my-component>

Now, elsewhere I can access the component externally

<script>
vm.$refs.foo.doSomething(); //assuming my component has a doSomething() method
</script>

See this fiddle for an example: https://jsfiddle.net/xmqgnbu3/1/

(old example using Vue 1: https://jsfiddle.net/6v7y6msr/)

A required class was missing while executing org.apache.maven.plugins:maven-war-plugin:2.1.1:war

This should fix the error

<plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-resources-plugin</artifactId>
     <version>2.7</version>
     <dependencies>
         <dependency>
             <groupId>org.apache.maven.shared</groupId>
             <artifactId>maven-filtering</artifactId>
             <version>1.3</version>
          </dependency>
      </dependencies>
</plugin>

Setting an image for a UIButton in code

You can put the image in either of the way:

UIButton *btnTwo = [UIButton buttonWithType:UIButtonTypeRoundedRect]; 
btnTwo.frame = CGRectMake(40, 140, 240, 30);
[btnTwo setTitle:@"vc2:v1" forState:UIControlStateNormal];
[btnTwo addTarget:self 
           action:@selector(goToOne) 
 forControlEvents:UIControlEventTouchUpInside];


[btnTwo setImage:[UIImage imageNamed:@"name.png"] forState:UIControlStateNormal];

//OR setting as background image

[btnTwo setBackgroundImage:[UIImage imageNamed:@"name.png"] 
                  forState:UIControlStateNormal];

[self.view addSubview:btnTwo];

How to compile C++ under Ubuntu Linux?

Update your apt-get:

$ sudo apt-get update
$ sudo apt-get install g++

Run your program.cpp:

$ g++ program.cpp
$ ./a.out

Set icon for Android application

You have to follow steps like:

  • You will see your default icons ic_launcher.png like:

enter image description here

  • You have to change all the images which are in mipmap-xxxx folders. First of you have to create your own logo or pick up image that you want to place as icon of launcher and upload here Android Asset Studio - Icon Generator - Launcher icons, You will get all the set of mipmap-xxxx and web_icon also from that link.

enter image description here

  • Now you have to copy all the folders which are in side of res folder,

enter image description here

  • Now go to Android Studio Project -> Right click on res folder -> Paste. It will prompt you like File 'ic_launcher.png' already exists in directory, You can press Overwrite all. It will paste/replace images in respective folder.

Now you can run and see your application icon with new image.

Happy Coding :) :)

Embed Google Map code in HTML with marker

USE this , Don't forget to get a google api key from

https://console.developers.google.com/apis/credentials

and replace it

    <div id="map" style="width:100%;height:400px;"></div>

<script>
function myMap() {

var map = new google.maps.Map(document.getElementById("map"), mapOptions);
  var myCenter = new google.maps.LatLng(38.224905, 48.252143);
  var mapCanvas = document.getElementById("map");
  var mapOptions = {center: myCenter, zoom: 16};
  var map = new google.maps.Map(mapCanvas, mapOptions);
  var marker = new google.maps.Marker({position:myCenter});
  marker.setMap(map);
}
</script>

<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=myMap"></script>

Laravel Migration Change to Make a Column Nullable

For Laravel 4.2, Unnawut's answer above is the best one. But if you are using table prefix, then you need to alter your code a little.

function up()
{
    $table_prefix = DB::getTablePrefix();
    DB::statement('ALTER TABLE `' . $table_prefix . 'throttle` MODIFY `user_id` INTEGER UNSIGNED NULL;');
}

And to make sure you can still rollback your migration, we'll do the down() as well.

function down()
{
    $table_prefix = DB::getTablePrefix();
    DB::statement('ALTER TABLE `' . $table_prefix . 'throttle` MODIFY `user_id` INTEGER UNSIGNED NOT NULL;');
}

How to get string objects instead of Unicode from JSON?

I ran into this problem too, and having to deal with JSON, I came up with a small loop that converts the unicode keys to strings. (simplejson on GAE does not return string keys.)

obj is the object decoded from JSON:

if NAME_CLASS_MAP.has_key(cls):
    kwargs = {}
    for i in obj.keys():
        kwargs[str(i)] = obj[i]
    o = NAME_CLASS_MAP[cls](**kwargs)
    o.save()

kwargs is what I pass to the constructor of the GAE application (which does not like unicode keys in **kwargs)

Not as robust as the solution from Wells, but much smaller.

How to find out the server IP address (using JavaScript) that the browser is connected to?

Try this as a shortcut, not as a definitive solution (see comments):

<script type="text/javascript">
    var ip = location.host;
    alert(ip);
</script>

This solution cannot work in some scenarios but it can help for quick testing. Regards

Is there a quick change tabs function in Visual Studio Code?

@SC_Chupacabra has correct answer for modifying behavior.

I generally prefer CTRL + PAGE UP / DOWN for my navigation, rather than using the TAB key.

    {
        "key": "ctrl+pageUp",
        "command": "workbench.action.nextEditor"
    },
    {
        "key": "ctrl+pageDown",
        "command": "workbench.action.previousEditor"
    }

Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Because that's exactly how the spec says it should work. The number input can accept floating-point numbers, including negative symbols and the e or E character (where the exponent is the number after the e or E):

A floating-point number consists of the following parts, in exactly the following order:

  1. Optionally, the first character may be a "-" character.
  2. One or more characters in the range "0—9".
  3. Optionally, the following parts, in exactly the following order:
    1. a "." character
    2. one or more characters in the range "0—9"
  4. Optionally, the following parts, in exactly the following order:
    1. a "e" character or "E" character
    2. optionally, a "-" character or "+" character
    3. One or more characters in the range "0—9".

How to style the parent element when hovering a child element?

I know it is an old question, but I just managed to do so without a pseudo child (but a pseudo wrapper).

If you set the parent to be with no pointer-events, and then a child div with pointer-events set to auto, it works:)
Note that <img> tag (for example) doesn't do the trick.
Also remember to set pointer-events to auto for other children which have their own event listener, or otherwise they will lose their click functionality.

_x000D_
_x000D_
div.parent {  _x000D_
    pointer-events: none;_x000D_
}_x000D_
_x000D_
div.child {_x000D_
    pointer-events: auto;_x000D_
}_x000D_
_x000D_
div.parent:hover {_x000D_
    background: yellow;_x000D_
}    
_x000D_
<div class="parent">_x000D_
  parent - you can hover over here and it won't trigger_x000D_
  <div class="child">hover over the child instead!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Edit:
As Shadow Wizard kindly noted: it's worth to mention this won't work for IE10 and below. (Old versions of FF and Chrome too, see here)

How can I safely create a nested directory?

I found this Q/A and I was initially puzzled by some of the failures and errors I was getting. I am working in Python 3 (v.3.5 in an Anaconda virtual environment on an Arch Linux x86_64 system).

Consider this directory structure:

+-- output/         ## dir
   +-- corpus       ## file
   +-- corpus2/     ## dir
   +-- subdir/      ## dir

Here are my experiments/notes, which clarifies things:

# ----------------------------------------------------------------------------
# [1] https://stackoverflow.com/questions/273192/how-can-i-create-a-directory-if-it-does-not-exist

import pathlib

""" Notes:
        1.  Include a trailing slash at the end of the directory path
            ("Method 1," below).
        2.  If a subdirectory in your intended path matches an existing file
            with same name, you will get the following error:
            "NotADirectoryError: [Errno 20] Not a directory:" ...
"""
# Uncomment and try each of these "out_dir" paths, singly:

# ----------------------------------------------------------------------------
# METHOD 1:
# Re-running does not overwrite existing directories and files; no errors.

# out_dir = 'output/corpus3'                ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/'               ## works
# out_dir = 'output/corpus3/doc1'           ## no error but no dir created (missing tailing /)
# out_dir = 'output/corpus3/doc1/'          ## works
# out_dir = 'output/corpus3/doc1/doc.txt'   ## no error but no file created (os.makedirs creates dir, not files!  ;-)
# out_dir = 'output/corpus2/tfidf/'         ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/'         ## works
# out_dir = 'output/corpus3/a/b/c/d/'       ## works

# [2] https://docs.python.org/3/library/os.html#os.makedirs

# Uncomment these to run "Method 1":

#directory = os.path.dirname(out_dir)
#os.makedirs(directory, mode=0o777, exist_ok=True)

# ----------------------------------------------------------------------------
# METHOD 2:
# Re-running does not overwrite existing directories and files; no errors.

# out_dir = 'output/corpus3'                ## works
# out_dir = 'output/corpus3/'               ## works
# out_dir = 'output/corpus3/doc1'           ## works
# out_dir = 'output/corpus3/doc1/'          ## works
# out_dir = 'output/corpus3/doc1/doc.txt'   ## no error but creates a .../doc.txt./ dir
# out_dir = 'output/corpus2/tfidf/'         ## fails with "Errno 20" (existing file named "corpus2")
# out_dir = 'output/corpus3/tfidf/'         ## works
# out_dir = 'output/corpus3/a/b/c/d/'       ## works

# Uncomment these to run "Method 2":

#import os, errno
#try:
#       os.makedirs(out_dir)
#except OSError as e:
#       if e.errno != errno.EEXIST:
#               raise
# ----------------------------------------------------------------------------

Conclusion: in my opinion, "Method 2" is more robust.

[1] How can I create a directory if it does not exist?

[2] https://docs.python.org/3/library/os.html#os.makedirs

npm WARN enoent ENOENT: no such file or directory, open 'C:\Users\Nuwanst\package.json'

If you already have package-lock.json file just delete it and try again.

Does the Java &= operator apply & or &&?

From the Java Language Specification - 15.26.2 Compound Assignment Operators.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

So a &= b; is equivalent to a = a & b;.

(In some usages, the type-casting makes a difference to the result, but in this one b has to be boolean and the type-cast does nothing.)

And, for the record, a &&= b; is not valid Java. There is no &&= operator.


In practice, there is little semantic difference between a = a & b; and a = a && b;. (If b is a variable or a constant, the result is going to be the same for both versions. There is only a semantic difference when b is a subexpression that has side-effects. In the & case, the side-effect always occurs. In the && case it occurs depending on the value of a.)

On the performance side, the trade-off is between the cost of evaluating b, and the cost of a test and branch of the value of a, and the potential saving of avoiding an unnecessary assignment to a. The analysis is not straight-forward, but unless the cost of calculating b is non-trivial, the performance difference between the two versions is too small to be worth considering.

HTTP POST with Json on Body - Flutter/Dart

This one is for using HTTPClient class

 request.headers.add("body", json.encode(map));

I attached the encoded json body data to the header and added to it. It works for me.

Jackson with JSON: Unrecognized field, not marked as ignorable

The first answer is almost correct, but what is needed is to change getter method, NOT field -- field is private (and not auto-detected); further, getters have precedence over fields if both are visible.(There are ways to make private fields visible, too, but if you want to have getter there's not much point)

So getter should either be named getWrapper(), or annotated with:

@JsonProperty("wrapper")

If you prefer getter method name as is.

Set content of HTML <span> with Javascript

The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).

The way I would actually do it is to use jQuery's .text().

Get operating system info

When you go to a website, your browser sends a request to the web server including a lot of information. This information might look something like this:

GET /questions/18070154/get-operating-system-info-with-php HTTP/1.1  
Host: stackoverflow.com  
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 
            (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8  
Accept-Language: en-us,en;q=0.5  
Accept-Encoding: gzip,deflate,sdch  
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7  
Keep-Alive: 300  
Connection: keep-alive  
Cookie: <cookie data removed> 
Pragma: no-cache  
Cache-Control: no-cache

These information are all used by the web server to determine how to handle the request; the preferred language and whether compression is allowed.

In PHP, all this information is stored in the $_SERVER array. To see what you're sending to a web server, create a new PHP file and print out everything from the array.

<pre><?php print_r($_SERVER); ?></pre>

This will give you a nice representation of everything that's being sent to the server, from where you can extract the desired information, e.g. $_SERVER['HTTP_USER_AGENT'] to get the operating system and browser.

Can I run Keras model on gpu?

See if your script is running GPU in Task manager. If not, suspect your CUDA version is right one for the tensorflow version you are using, as the other answers suggested already.

Additionally, a proper CUDA DNN library for the CUDA version is required to run GPU with tensorflow. Download/extract it from here and put the DLL (e.g., cudnn64_7.dll) into CUDA bin folder (e.g., C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin).

Dynamically replace img src attribute with jQuery

In my case, I replaced the src taq using:

_x000D_
_x000D_
   $('#gmap_canvas').attr('src', newSrc);
_x000D_
_x000D_
_x000D_

HowTo Generate List of SQL Server Jobs and their owners

try this

Jobs

select s.name,l.name
 from  msdb..sysjobs s 
 left join master.sys.syslogins l on s.owner_sid = l.sid

Packages

select s.name,l.name 
from msdb..sysssispackages s 
 left join master.sys.syslogins l on s.ownersid = l.sid

What are the integrity and crossorigin attributes?

integrity - defines the hash value of a resource (like a checksum) that has to be matched to make the browser execute it. The hash ensures that the file was unmodified and contains expected data. This way browser will not load different (e.g. malicious) resources. Imagine a situation in which your JavaScript files were hacked on the CDN, and there was no way of knowing it. The integrity attribute prevents loading content that does not match.

Invalid SRI will be blocked (Chrome developer-tools), regardless of cross-origin. Below NON-CORS case when integrity attribute does not match:

enter image description here

Integrity can be calculated using: https://www.srihash.org/ Or typing into console (link):

openssl dgst -sha384 -binary FILENAME.js | openssl base64 -A

crossorigin - defines options used when the resource is loaded from a server on a different origin. (See CORS (Cross-Origin Resource Sharing) here: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS). It effectively changes HTTP requests sent by the browser. If the “crossorigin” attribute is added - it will result in adding origin: <ORIGIN> key-value pair into HTTP request as shown below.

enter image description here

crossorigin can be set to either “anonymous” or “use-credentials”. Both will result in adding origin: into the request. The latter however will ensure that credentials are checked. No crossorigin attribute in the tag will result in sending a request without origin: key-value pair.

Here is a case when requesting “use-credentials” from CDN:

<script 
        src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js"
        integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" 
        crossorigin="use-credentials"></script>

A browser can cancel the request if crossorigin incorrectly set.

enter image description here

Links
- https://www.w3.org/TR/cors/
- https://tools.ietf.org/html/rfc6454
- https://developer.mozilla.org/en-US/docs/Web/HTML/Element/link

Blogs
- https://frederik-braun.com/using-subresource-integrity.html
- https://web-security.guru/en/web-security/subresource-integrity

What's the difference of $host and $http_host in Nginx

$host is a variable of the Core module.

$host

This variable is equal to line Host in the header of request or name of the server processing the request if the Host header is not available.

This variable may have a different value from $http_host in such cases: 1) when the Host input header is absent or has an empty value, $host equals to the value of server_name directive; 2)when the value of Host contains port number, $host doesn't include that port number. $host's value is always lowercase since 0.8.17.

$http_host is also a variable of the same module but you won't find it with that name because it is defined generically as $http_HEADER (ref).

$http_HEADER

The value of the HTTP request header HEADER when converted to lowercase and with 'dashes' converted to 'underscores', e.g. $http_user_agent, $http_referer...;


Summarizing:

  • $http_host equals always the HTTP_HOST request header.
  • $host equals $http_host, lowercase and without the port number (if present), except when HTTP_HOST is absent or is an empty value. In that case, $host equals the value of the server_name directive of the server which processed the request.

Python read next()

When you do : f.readlines() you already read all the file so f.tell() will show you that you are in the end of the file, and doing f.next() will result in a StopIteration error.

Alternative of what you want to do is:

filne = "D:/testtube/testdkanimfilternode.txt"

with open(filne, 'r+') as f:
    for line in f:
        if line.startswith("anim "):
            print f.next() 
            # Or use next(f, '') to return <empty string> instead of raising a  
            # StopIteration if the last line is also a match.
            break

How do I tell if a regular file does not exist in Bash?

There are three distinct ways to do this:

  1. Negate the exit status with bash (no other answer has said this):

    if ! [ -e "$file" ]; then
        echo "file does not exist"
    fi
    

    Or:

    ! [ -e "$file" ] && echo "file does not exist"
    
  2. Negate the test inside the test command [ (that is the way most answers before have presented):

    if [ ! -e "$file" ]; then
        echo "file does not exist"
    fi
    

    Or:

    [ ! -e "$file" ] && echo "file does not exist"
    
  3. Act on the result of the test being negative (|| instead of &&):

    Only:

    [ -e "$file" ] || echo "file does not exist"
    

    This looks silly (IMO), don't use it unless your code has to be portable to the Bourne shell (like the /bin/sh of Solaris 10 or earlier) that lacked the pipeline negation operator (!):

    if [ -e "$file" ]; then
        :
    else
        echo "file does not exist"
    fi
    

How to stop event bubbling on checkbox click

Here's a trick that worked for me:

handleClick = e => {
    if (e.target === e.currentTarget) {
        // do something
    } else {
        // do something else
    }
}

Explanation: I attached handleClick to a backdrop of a modal window, but it also fired on every click inside of a modal window (because it was IN the backdrop div). So I added the condition (e.target === e.currentTarget), which is only fulfilled when a backdrop is clicked.

MySQL Check if username and password matches in Database

//set vars
$user = $_POST['user'];
$pass = md5($_POST['pass']);

if ($user&&$pass) 
{
//connect to db
$connect = mysql_connect("$server","$username","$password") or die("not connecting");
mysql_select_db("users") or die("no db :'(");
$query = mysql_query("SELECT * FROM $tablename WHERE username='$user'");

$numrows = mysql_num_rows($query);


if ($numrows!=0)
{
//while loop
  while ($row = mysql_fetch_assoc($query))
  {
    $dbusername = $row['username'];
    $dbpassword = $row['password'];
  }
  else
      die("incorrect username/password!");
}
else
  echo "user does not exist!";
} 
else
    die("please enter a username and password!");

HTML5 and frameborder

style="border:none; scrolling:no; frameborder:0;  marginheight:0; marginwidth:0; "

Examples of good gotos in C or C++

Heres one trick I've heard of people using. I've never seen it in the wild though. And it only applies to C because C++ has RAII to do this more idiomatically.

void foo()
{
    if (!doA())
        goto exit;
    if (!doB())
        goto cleanupA;
    if (!doC())
        goto cleanupB;

    /* everything has succeeded */
    return;

cleanupB:
    undoB();
cleanupA:
    undoA();
exit:
    return;
}

System.web.mvc missing

Just in case someone is a position where he get's the same error. In my case downgrading Microsoft.AspNet.Mvc and then upgrading it again helped. I had this problem after installing Glimpse and removing it. System.Web.Mvc was references wrong somehow, cleaning the solution or rebuilding it didin't worked in my case. Just give it try if none of the above answers works for you.

Printing HashMap In Java

Java 8 new feature forEach style

import java.util.HashMap;

public class PrintMap {
    public static void main(String[] args) {
        HashMap<String, Integer> example = new HashMap<>();
        example.put("a", 1);
        example.put("b", 2);
        example.put("c", 3);
        example.put("d", 5);

        example.forEach((key, value) -> System.out.println(key + " : " + value));

//      Output:
//      a : 1
//      b : 2
//      c : 3
//      d : 5

    }
}

SQL Server 2005 Setting a variable to the result of a select query

What do you mean exactly? Do you want to reuse the result of your query for an other query?

In that case, why don't you combine both queries, by making the second query search inside the results of the first one (SELECT xxx in (SELECT yyy...)

What is a good Hash Function?

A good hash function should

  1. be bijective to not loose information, where possible, and have the least collisions
  2. cascade as much and as evenly as possible, i.e. each input bit should flip every output bit with probability 0.5 and without obvious patterns.
  3. if used in a cryptographic context there should not exist an efficient way to invert it.

A prime number modulus does not satisfy any of these points. It is simply insufficient. It is often better than nothing, but it's not even fast. Multiplying with an unsigned integer and taking a power-of-two modulus distributes the values just as well, that is not well at all, but with only about 2 cpu cycles it is much faster than the 15 to 40 a prime modulus will take (yes integer division really is that slow).

To create a hash function that is fast and distributes the values well the best option is to compose it from fast permutations with lesser qualities like they did with PCG for random number generation.

Useful permutations, among others, are:

  • multiplication with an uneven integer
  • binary rotations
  • xorshift

Following this recipe we can create our own hash function or we take splitmix which is tested and well accepted.

If cryptographic qualities are needed I would highly recommend to use a function of the sha family, which is well tested and standardised, but for educational purposes this is how you would make one:

First you take a good non-cryptographic hash function, then you apply a one-way function like exponentiation on a prime field or k many applications of (n*(n+1)/2) mod 2^k interspersed with an xorshift when k is the number of bits in the resulting hash.

Get the last inserted row ID (with SQL statement)

If your SQL Server table has a column of type INT IDENTITY (or BIGINT IDENTITY), then you can get the latest inserted value using:

INSERT INTO dbo.YourTable(columns....)
   VALUES(..........)

SELECT SCOPE_IDENTITY()

This works as long as you haven't inserted another row - it just returns the last IDENTITY value handed out in this scope here.

There are at least two more options - @@IDENTITY and IDENT_CURRENT - read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.

Invalid column count in CSV input on line 1 Error

The final column of my database (it's column F in the spreadsheet) is not used and therefore empty. When I imported the excel CSV file I got the "column count" error.

This is because excel was only saving the columns I use. A-E

Adding a 0 to the first row in F solved the problem, then I deleted it after upload was successful.

Hope this helps and saves someone else time and loss of hair :)

A Space between Inline-Block List Items

I have seen this and answered on it before:

After further research I have discovered that inline-block is a whitespace dependent method and is dependent on the font setting. In this case 4px is rendered.

To avoid this you could run all your lis together in one line, or block the end tags and begin tags together like this:

<ul>
        <li>
            <div>first</div>
        </li><li>
            <div>first</div>
        </li><li>
            <div>first</div>
        </li><li>
            <div>first</div>
        </li>
</ul>

Example here.


As mentioned by other answers and comments, the best practice for solving this is to add font-size: 0; to the parent element:

ul {
    font-size: 0;
}

ul li {
    font-size: 14px;
    display: inline-block;
}

This is better for HTML readability (avoiding running the tags together etc). The spacing effect is because of the font's spacing setting, so you must reset it for the inlined elements and set it again for the content within.

How can I change text color via keyboard shortcut in MS word 2010

Press Alt+H(h) and then you'll see the shortcuts on the toolbar, press FC to operate color menu and press A(Automatic) for black or browse through other colors using arrow keys.

C#: List All Classes in Assembly

I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:

Assembly myAssembly = Assembly.GetExecutingAssembly();

System.Reflection namespace.

If you want to examine an assembly that you have no reference to, you can use either of these:

Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);

If you intend to instantiate your type once you've found it:

Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);

See the Assembly class documentation for more information.

Once you have the reference to the Assembly object, you can use assembly.GetTypes() like Jon already demonstrated.

How to Automatically Start a Download in PHP?

Send the following headers before outputting the file:

header("Content-Disposition: attachment; filename=\"" . basename($File) . "\"");
header("Content-Type: application/octet-stream");
header("Content-Length: " . filesize($File));
header("Connection: close");

@grom: Interesting about the 'application/octet-stream' MIME type. I wasn't aware of that, have always just used 'application/force-download' :)

How can I style a PHP echo text?

You cannot style a variable such as $ip['countryName']

You can only style elements like p,div, etc, or classes and ids.

If you want to style $ip['countryName'] there are several ways.

You can echo it within an element:

echo '<p id="style">'.$ip['countryName'].'</p>';
echo '<span id="style">'.$ip['countryName'].'</span>';
echo '<div id="style">'.$ip['countryName'].'</div>';

If you want to style both the variables the same style, then set a class like:

echo '<p class="style">'.$ip['cityName'].'</p>';
echo '<p class="style">'.$ip['countryName'].'</p>';

You could also embed the variables within your actual html rather than echoing them out within the code.

$city = $ip['cityName'];  
$country = $ip['countryName'];
?>
<div class="style"><?php echo $city ?></div>
<div class="style"><?php echo $country?></div>

SQL Server replace, remove all after certain character

For situations when I need to replace or match(find) something against string I prefer using regular expressions.

Since, the regular expressions are not fully supported in T-SQL you can implement them using CLR functions. Furthermore, you do not need any C# or CLR knowledge at all as all you need is already available in the MSDN String Utility Functions Sample.

In your case, the solution using regular expressions is:

SELECT [dbo].[RegexReplace] ([MyColumn], '(;.*)', '')
FROM [dbo].[MyTable]

But implementing such function in your database is going to help you solving more complex issues at all.


The example below shows how to deploy only the [dbo].[RegexReplace] function, but I will recommend to you to deploy the whole String Utility class.

  1. Enabling CLR Integration. Execute the following Transact-SQL commands:

    sp_configure 'clr enabled', 1
    GO
    RECONFIGURE
    GO  
    
  2. Bulding the code (or creating the .dll). Generraly, you can do this using the Visual Studio or .NET Framework command prompt (as it is shown in the article), but I prefer to use visual studio.

    • create new class library project:

      enter image description here

    • copy and paste the following code in the Class1.cs file:

      using System;
      using System.IO;
      using System.Data.SqlTypes;
      using System.Text.RegularExpressions;
      using Microsoft.SqlServer.Server;
      
      public sealed class RegularExpression
      {
          public static string Replace(SqlString sqlInput, SqlString sqlPattern, SqlString sqlReplacement)
          {
              string input = (sqlInput.IsNull) ? string.Empty : sqlInput.Value;
              string pattern = (sqlPattern.IsNull) ? string.Empty : sqlPattern.Value;
              string replacement = (sqlReplacement.IsNull) ? string.Empty : sqlReplacement.Value;
              return Regex.Replace(input, pattern, replacement);
          }
      }
      
    • build the solution and get the path to the created .dll file:

      enter image description here

    • replace the path to the .dll file in the following T-SQL statements and execute them:

      IF OBJECT_ID(N'RegexReplace', N'FS') is not null
      DROP Function RegexReplace;
      GO
      
      IF EXISTS (SELECT * FROM sys.assemblies WHERE [name] = 'StringUtils')
      DROP ASSEMBLY StringUtils;
      GO
      
      DECLARE @SamplePath nvarchar(1024)
      -- You will need to modify the value of the this variable if you have installed the sample someplace other than the default location.
      Set @SamplePath = 'C:\Users\gotqn\Desktop\StringUtils\StringUtils\StringUtils\bin\Debug\'
      CREATE ASSEMBLY [StringUtils] 
      FROM @SamplePath + 'StringUtils.dll'
      WITH permission_set = Safe;
      GO
      
      
      CREATE FUNCTION [RegexReplace] (@input nvarchar(max), @pattern nvarchar(max), @replacement nvarchar(max))
      RETURNS nvarchar(max)
      AS EXTERNAL NAME [StringUtils].[RegularExpression].[Replace]
      GO
      
    • That's it. Test your function:

      declare @MyTable table ([id] int primary key clustered, MyText varchar(100))
      insert into @MyTable ([id], MyText)
      select 1, 'some text; some more text'
      union all select 2, 'text again; even more text'
      union all select 3, 'text without a semicolon'
      union all select 4, null -- test NULLs
      union all select 5, '' -- test empty string
      union all select 6, 'test 3 semicolons; second part; third part'
      union all select 7, ';' -- test semicolon by itself    
      
      SELECT [dbo].[RegexReplace] ([MyText], '(;.*)', '')
      FROM @MyTable
      
      select * from @MyTable
      

How to serialize an Object into a list of URL query parameters?

Just for the record and in case you have a browser supporting ES6, here's a solution with reduce:

Object.keys(obj).reduce((prev, key, i) => (
  `${prev}${i!==0?'&':''}${key}=${obj[key]}`
), '');

And here's a snippet in action!

_x000D_
_x000D_
// Just for test purposes_x000D_
let obj = {param1: 12, param2: "test"};_x000D_
_x000D_
// Actual solution_x000D_
let result = Object.keys(obj).reduce((prev, key, i) => (_x000D_
  `${prev}${i!==0?'&':''}${key}=${obj[key]}`_x000D_
), '');_x000D_
_x000D_
// Run the snippet to show what happens!_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Getting the parent div of element

You're looking for parentNode, which Element inherits from Node:

parentDiv = pDoc.parentNode;

Handy References:

  • DOM2 Core specification - well-supported by all major browsers
  • DOM2 HTML specification - bindings between the DOM and HTML
  • DOM3 Core specification - some updates, not all supported by all major browsers
  • HTML5 specification - which now has the DOM/HTML bindings in it

How can I get the number of days between 2 dates in Oracle 11g?

Or you could have done this:

select trunc(sysdate) - to_date('2009-10-01', 'yyyy-mm-dd') from dual

This returns a NUMBER of whole days:

SQL> create view v as 
  2  select trunc(sysdate) - to_date('2009-10-01', 'yyyy-mm-dd') diff 
  3  from dual;

View created.

SQL> select * from v;

      DIFF
----------
        29

SQL> desc v
 Name                   Null?    Type
 ---------------------- -------- ------------------------
 DIFF                            NUMBER(38)

how to sort pandas dataframe from one column

This worked for me

df.sort_values(by='Column_name', inplace=True, ascending=False)

How to edit HTML input value colour?

Please try this:

<input class="col-xs-12 col-sm-8 col-sm-offset-2 col-md-8 col-md-offset-2" type="text" name="name" value="" placeholder="Your Name" style="background-color:blue;"/>

You basically put all the CSS inside the style part of the input tag and it works.

Upload files with FTP using PowerShell

I am not sure you can 100% bullet proof the script from not hanging or crashing, as there are things outside your control (what if the server loses power mid-upload?) - but this should provide a solid foundation for getting you started:

# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create("ftp://localhost/me.png")
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential("anonymous","anonymous@localhost")
$ftp.UseBinary = $true
$ftp.UsePassive = $true
# read in the file to upload as a byte array
$content = [System.IO.File]::ReadAllBytes("C:\me.png")
$ftp.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()

How to remove text before | character in notepad++

Please use regex to remove anything before |

example

dsfdf | fdfsfsf
dsdss|gfghhghg
dsdsds |dfdsfsds

Use find and replace in notepad++

find: .+(\|) replace: \1

output

| fdfsfsf
|gfghhghg
|dfdsfsds

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

How can I change the font size using seaborn FacetGrid?

I've made small modifications to @paul-H code, such that you can set the font size for the x/y axes and legend independently. Hope it helps:

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults                                                                                                         
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', fontsize=20,bbox_to_anchor=(0, 1.1))
ax.set_xlabel('X_axi',fontsize=20);
ax.set_ylabel('Y_axis',fontsize=20);

plt.show()

This is the output:

enter image description here

How can I check if a user is logged-in in php?

You need this on all pages before you check for current sessions:

session_start();

Check if $_SESSION["loggedIn"] (is not) true - If not, redirect them to the login page.

if($_SESSION["loggedIn"] != true){
    echo 'not logged in';
    header("Location: login.php");
    exit;
}

How do you test running time of VBA code?

The Timer function in VBA gives you the number of seconds elapsed since midnight, to 1/100 of a second.

Dim t as single
t = Timer
'code
MsgBox Timer - t

How to install python-dateutil on Windows?

If you are offline and have untared the package, you can use command prompt.

Navigate to the untared folder and run:

python setup.py install

Update date + one year in mysql

You could use DATE_ADD : (or ADDDATE with INTERVAL)

UPDATE table SET date = DATE_ADD(date, INTERVAL 1 YEAR) 

How to create a POJO?

POJO class acts as a bean which is used to set and get the value.

public class Data
{


private int id;
    private String deptname;
    private String date;
    private String name;
    private String mdate;
    private String mname;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getDeptname() {
        return deptname;
    }

    public void setDeptname(String deptname) {
        this.deptname = deptname;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getMdate() {
        return mdate;
    }

    public void setMdate(String mdate) {
        this.mdate = mdate;
    }

    public String getMname() {
        return mname;
    }

    public void setMname(String mname) {
        this.mname = mname;
    }
}

How to enable back/left swipe gesture in UINavigationController after setting leftBarButtonItem?

Swift 3:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    self.navigationController?.interactivePopGestureRecognizer?.delegate = self
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return true
}

func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool {
    return (otherGestureRecognizer is UIScreenEdgePanGestureRecognizer)
}

Determine if 2 lists have the same elements, regardless of order?

This seems to work, though possibly cumbersome for large lists.

>>> A = [0, 1]
>>> B = [1, 0]
>>> C = [0, 2]
>>> not sum([not i in A for i in B])
True
>>> not sum([not i in A for i in C])
False
>>> 

However, if each list must contain all the elements of other then the above code is problematic.

>>> A = [0, 1, 2]
>>> not sum([not i in A for i in B])
True

The problem arises when len(A) != len(B) and, in this example, len(A) > len(B). To avoid this, you can add one more statement.

>>> not sum([not i in A for i in B]) if len(A) == len(B) else False
False

One more thing, I benchmarked my solution with timeit.repeat, under the same conditions used by Aaron Hall in his post. As suspected, the results are disappointing. My method is the last one. set(x) == set(y) it is.

>>> def foocomprehend(): return not sum([not i in data for i in data2])
>>> min(timeit.repeat('fooset()', 'from __main__ import fooset, foocount, foocomprehend'))
25.2893661496
>>> min(timeit.repeat('foosort()', 'from __main__ import fooset, foocount, foocomprehend'))
94.3974742993
>>> min(timeit.repeat('foocomprehend()', 'from __main__ import fooset, foocount, foocomprehend'))
187.224562545

Set margins in a LinearLayout programmatically

Here is a little code to accomplish it:

LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
     LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

layoutParams.setMargins(30, 20, 30, 0);

Button okButton=new Button(this);
okButton.setText("some text");
ll.addView(okButton, layoutParams);

Scrolling an iframe with JavaScript?

Inspired by Nelson's and Chris' comments, I've found a way to workaround the same origin policy with a div and an iframe:

HTML:

<div id='div_iframe'><iframe id='frame' src='...'></iframe></div>

CSS:

#div_iframe {
  border-style: inset;
  border-color: grey;
  overflow: scroll;
  height: 500px;
  width: 90%
}

#frame {
  width: 100%;
  height: 1000%;   /* 10x the div height to embrace the whole page */
}

Now suppose I want to skip the first 438 (vertical) pixels of the iframe page, by scrolling to that position.

JS solution:

document.getElementById('div_iframe').scrollTop = 438

JQuery solution:

$('#div_iframe').scrollTop(438)

CSS solution:

#frame { margin-top: -438px }

(Each solution alone is enough, and the effect of the CSS one is a little different since you can't scroll up to see the top of the iframed page.)

jQuery ajax upload file in asp.net mvc

If you posting form using ajax then you can not send image using $.ajax method, you have to use classic xmlHttpobject method for saving image, other alternative of it use submit type instead of button

How to best display in Terminal a MySQL SELECT returning too many fields?

If you are using MySQL interactively, you can set your pager to use sed like this:

$ mysql -u <user> p<password>
mysql> pager sed 's/,/\n/g' 
PAGER set to 'sed 's/,/\n/g''
mysql> SELECT blah FROM blah WHERE blah = blah 
.
.
.
"blah":"blah"
"blah":"blah"
"blah":"blah"

If you don't use sed as the pager, the output is like this:

"blah":"blah","blah":"blah","blah":"blah"

What method in the String class returns only the first N characters?

public static string TruncateLongString(this string str, int maxLength)
{
    return str.Length <= maxLength ? str : str.Remove(maxLength);
}

How to uncheck a radio button?

You can also simulate the radiobutton behavior using only checkboxes:

<input type="checkbox" class="fakeRadio" checked />
<input type="checkbox" class="fakeRadio" />
<input type="checkbox" class="fakeRadio" />

Then, you can use this simple code to work for you:

$(".fakeRadio").click(function(){
    $(".fakeRadio").prop( "checked", false );
    $(this).prop( "checked", true );
});

It works fine and you have more control over the behavior of each button.

You can try it by yourself at: http://jsfiddle.net/almircampos/n1zvrs0c/

This fork also let's you unselect all as requested in a comment: http://jsfiddle.net/5ry8n4f4/

When to use RSpec let()?

let is functional as its essentially a Proc. Also its cached.

One gotcha I found right away with let... In a Spec block that is evaluating a change.

let(:object) {FactoryGirl.create :object}

expect {
  post :destroy, id: review.id
}.to change(Object, :count).by(-1)

You'll need to be sure to call let outside of your expect block. i.e. you're calling FactoryGirl.create in your let block. I usually do this by verifying the object is persisted.

object.persisted?.should eq true

Otherwise when the let block is called the first time a change in the database will actually happen due to the lazy instantiation.

Update

Just adding a note. Be careful playing code golf or in this case rspec golf with this answer.

In this case, I just have to call some method to which the object responds. So I invoke the _.persisted?_ method on the object as its truthy. All I'm trying to do is instantiate the object. You could call empty? or nil? too. The point isn't the test but bringing the object ot life by calling it.

So you can't refactor

object.persisted?.should eq true

to be

object.should be_persisted 

as the object hasn't been instantiated... its lazy. :)

Update 2

leverage the let! syntax for instant object creation, which should avoid this issue altogether. Note though it will defeat a lot of the purpose of the laziness of the non banged let.

Also in some instances you might actually want to leverage the subject syntax instead of let as it may give you additional options.

subject(:object) {FactoryGirl.create :object}

Does Index of Array Exist

You could check if the index is less than the length of the array. This doesn't check for nulls or other odd cases where the index can be assigned a value but hasn't been given one explicitly.

Printing Lists as Tabular Data

I would try to loop through the list and use a CSV formatter to represent the data you want.

You can specify tabs, commas, or any other char as the delimiter.

Otherwise, just loop through the list and print "\t" after each element

http://docs.python.org/library/csv.html

What does "var" mean in C#?

It means that the type of the local being declared will be inferred by the compiler based upon its first assignment:

// This statement:
var foo = "bar";
// Is equivalent to this statement:
string foo = "bar";

Notably, var does not define a variable to be of a dynamic type. So this is NOT legal:

var foo = "bar";
foo = 1; // Compiler error, the foo variable holds strings, not ints

var has only two uses:

  1. It requires less typing to declare variables, especially when declaring a variable as a nested generic type.
  2. It must be used when storing a reference to an object of an anonymous type, because the type name cannot be known in advance: var foo = new { Bar = "bar" };

You cannot use var as the type of anything but locals. So you cannot use the keyword var to declare field/property/parameter/return types.

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

Mac OS X and multiple Java versions

To install more recent versions of OpenJDK, I use this. Example for OpenJDK 14:

brew info adoptopenjdk
brew tap adoptopenjdk/openjdk
brew cask install adoptopenjdk14

See https://github.com/AdoptOpenJDK/homebrew-openjdk for current info.

.jar error - could not find or load main class

Thanks jbaliuka for the suggestion. I opened the registry editor (by typing regedit in cmd) and going to HKEY_CLASSES_ROOT > jarfile > shell > open > command, then opening (Default) and changing the value from

"C:\Program Files\Java\jre7\bin\javaw.exe" -jar "%1" %*

to

"C:\Program Files\Java\jre7\bin\java.exe" -jar "%1" %*

(I just removed the w in javaw.exe.) After that you have to right click a jar -> open with -> choose default program -> navigate to your java folder and open \jre7\bin\java.exe (or any other java.exe file in you java folder). If it doesn't work, try switching to javaw.exe, open a jar file with it, then switch back.

I don't know anything about editing the registry except that it's dangerous, so you might wanna back it up before doing this (in the top bar, File>Export).

How to pass an object into a state using UI-router?

1)

$stateProvider
        .state('app.example1', {
                url: '/example',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/example.html',
                        controller: 'ExampleCtrl'
                    }
                }
            })
            .state('app.example2', {
                url: '/example2/:object',
                views: {
                    'menuContent': {
                        templateUrl: 'templates/example2.html',
                        controller: 'Example2Ctrl'
                    }
                }
            })

2)

.controller('ExampleCtrl', function ($state, $scope, UserService) {


        $scope.goExample2 = function (obj) {

            $state.go("app.example2", {object: JSON.stringify(obj)});
        }

    })
    .controller('Example2Ctrl', function ($state, $scope, $stateParams) {

        console.log(JSON.parse($state.params.object));


    })

Getting the last argument passed to a shell script

$ set quick brown fox jumps

$ echo ${*: -1:1} # last argument
jumps

$ echo ${*: -1} # or simply
jumps

$ echo ${*: -2:1} # next to last
fox

The space is necessary so that it doesnt get interpreted as a default value.

Note that this is bash-only.

Javascript: how to validate dates in format MM-DD-YYYY?

This function will validate the date to see if it's correct or if it's in the proper format of: DD/MM/YYYY.

function isValidDate(date)
{
    var matches = /^(\d{2})[-\/](\d{2})[-\/](\d{4})$/.exec(date);
    if (matches == null) return false;
    var d = matches[1];
    var m = matches[2]-1;
    var y = matches[3];
    var composedDate = new Date(y, m, d);
    return composedDate.getDate() == d &&
           composedDate.getMonth() == m &&
           composedDate.getFullYear() == y;
}
console.log(isValidDate('10-12-1961'));
console.log(isValidDate('12/11/1961'));
console.log(isValidDate('02-11-1961'));
console.log(isValidDate('12/01/1961'));
console.log(isValidDate('13-11-1961'));
console.log(isValidDate('11-31-1961'));
console.log(isValidDate('11-31-1061'));

Compiled vs. Interpreted Languages

The Python Book © 2015 Imagine Publishing Ltd, simply distunguishes the difference by the following hint mentioned in page 10 as:

An interpreted language such as Python is one where the source code is converted to machine code and then executed each time the program runs. This is different from a compiled language such as C, where the source code is only converted to machine code once – the resulting machine code is then executed each time the program runs.

Best practice for storing and protecting private API keys in applications

The App-Secret key should be kept private - but when releasing the app they can be reversed by some guys.

for those guys it will not hide, lock the either the ProGuard the code. It is a refactor and some payed obfuscators are inserting a few bitwise operators to get back the jk433g34hg3 String. You can make 5 -15 min longer the hacking if you work 3 days :)

Best way is to keep it as it is, imho.

Even if you store at server side( your PC ) the key can be hacked and printed out. Maybe this takes the longest? Anyhow it is a matter of few minutes or a few hours in best case.

A normal user will not decompile your code.

nuget 'packages' element is not declared warning

This works and remains even after adding a new package:

Add the following !DOCTYPE above the <packages> element:

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE packages [
  <!ELEMENT packages (package*)>
  <!ELEMENT package EMPTY>
  <!ATTLIST package
  id CDATA #REQUIRED
  version CDATA #REQUIRED
  targetFramework CDATA #REQUIRED
  developmentDependency CDATA #IMPLIED>
]>

How do I check if an array includes a value in JavaScript?

  1. Either use Array.indexOf(Object).
  2. With ECMA 7 one can use the Array.includes(Object).
  3. With ECMA 6 you can use Array.find(FunctionName) where FunctionName is a user defined function to search for the object in the array.

    Hope this helps!

Extract number from string with Oracle function

If you are looking for 1st Number with decimal as string has correct decimal places, you may try regexp_substr function like this:

regexp_substr('stack12.345overflow', '\.*[[:digit:]]+\.*[[:digit:]]*')

How to add default signature in Outlook

I figured out a way, but it may be too sloppy for most. I've got a simple Db and I want it to be able to generate emails for me, so here's the down and dirty solution I used:

I found that the beginning of the body text is the only place I see the "<div class=WordSection1>" in the HTMLBody of a new email, so I just did a simple replace, replacing

"<div class=WordSection1><p class=MsoNormal><o:p>"

with

"<div class=WordSection1><p class=MsoNormal><o:p>" & sBody

where sBody is the body content I want inserted. Seems to work so far.

.HTMLBody = Replace(oEmail.HTMLBody, "<div class=WordSection1><p class=MsoNormal><o:p>", "<div class=WordSection1><p class=MsoNormal><o:p>" & sBody)

simple custom event

You haven't created an event. To do that write:

public event EventHandler<Progress> Progress;

Then, you can call Progress from within the class where it was declared like normal function or delegate:

Progress(this, new Progress("some status"));

So, if you want to report progress in TestClass, the event should be in there too and it should be also static. You can the subscribe to it from your form like this:

TestClass.Progress += SetStatus;

Also, you should probably rename Progress to ProgressEventArgs, so that it's clear what it is.

How can I make an entire HTML form "readonly"?

There is no built-in way that I know of to do this so you will need to come up with a custom solution depending on how complicated your form is. You should read this post:

Convert HTML forms to read-only (Update: broken post link, archived link)

EDIT: Based on your update, why are you so worried about having it read-only? You can do it via client-side but if not you will have to add the required tag to each control or convert the data and display it as raw text with no controls. If you are trying to make it read-only so that the next post will be unmodified then you have a problem because anyone can mess with the post to produce whatever they want so when you do in fact finally receive the data you better be checking it again to make sure it is valid.

Debug/run standard java in Visual Studio Code IDE and OS X?

Code Runner Extension will only let you "run" java files.

To truly debug 'Java' files follow the quick one-time setup:

  • Install Java Debugger Extension in VS Code and reload.
  • open an empty folder/project in VS code.
  • create your java file (s).
  • create a folder .vscode in the same folder.
  • create 2 files inside .vscode folder: tasks.json and launch.json
  • copy paste below config in tasks.json:
{
    "version": "2.0.0",
    "type": "shell",
    "presentation": {
        "echo": true,
        "reveal": "always",
        "focus": false,
        "panel": "shared"
    },
    "isBackground": true,
    "tasks": [
        {
            "taskName": "build",
            "args": ["-g", "${file}"],
            "command": "javac"
        }
    ]
}
  • copy paste below config in launch.json:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Debug Java",
            "type": "java",
            "request": "launch",
            "externalConsole": true,                //user input dosen't work if set it to false :(
            "stopOnEntry": true,
            "preLaunchTask": "build",                 // Runs the task created above before running this configuration
            "jdkPath": "${env:JAVA_HOME}/bin",        // You need to set JAVA_HOME enviroment variable
            "cwd": "${workspaceRoot}",
            "startupClass": "${workspaceRoot}${file}",
            "sourcePath": ["${workspaceRoot}"],   // Indicates where your source (.java) files are
            "classpath": ["${workspaceRoot}"],    // Indicates the location of your .class files
            "options": [],                             // Additional options to pass to the java executable
            "args": []                                // Command line arguments to pass to the startup class
        }

    ],
    "compounds": []
}

You are all set to debug java files, open any java file and press F5 (Debug->Start Debugging).


Tip: *To hide .class files in the side explorer of VS code, open settings of VS code and paste the below config:

"files.exclude": {
        "*.class": true
    }

enter image description here

Send data from javascript to a mysql database

The other posters are correct you cannot connect to MySQL directly from javascript. This is because JavaScript is at client side & mysql is server side.

So your best bet is to use ajax to call a handler as quoted above if you can let us know what language your project is in we can better help you ie php/java/.net

If you project is using php then the example from Merlyn is a good place to start, I would personally use jquery.ajax() to cut down you code and have a better chance of less cross browser issues.

http://api.jquery.com/jQuery.ajax/

(413) Request Entity Too Large | uploadReadAheadSize

In my case, I was getting this error message because I was changed the service's namespace and services tag was pointed to the older namespace. I refreshed the namespace and the error disapear:

<services>
  <service name="My.Namespace.ServiceName"> <!-- Updated name -->
    <endpoint address="" 
              binding="wsHttpBinding" 
              bindingConfiguration="MyBindingConfiguratioName" 
              contract="My.Namespace.Interface" <!-- Updated contract -->
    />
  </service>
</services>

What file uses .md extension and how should I edit them?

I suggest StackEdit. It is simple WISIWIG editor. You can use both editor and markdown syntax. There is a quick markdown help syntax there. Undo/redo, comments, GoogleDrive, Dropbox interconnection.

C#: How to access an Excel cell?

Simple.

To open a workbook. Use xlapp.workbooks.Open()

where you have previously declared and instanitated xlapp as so.. Excel.Application xlapp = new Excel.Applicaton();

parameters are correct.

Next make sure you use the property Value2 when assigning a value to the cell using either the cells property or the range object.

Firefox 'Cross-Origin Request Blocked' despite headers

I came across this question having found requests in Firefox were being blocked with the message:

Reason: CORS request did not succeed

After pulling my hair out I found out that a newly installed Firefox extension, Privacy Badger, was blocking the requests.

If you come to this question after scratching your head, try checking to see what extensions you have installed to see if any of them are blocking requests.

See Reason: CORS request did not succeed on MDN for details.

Count the number of commits on a Git branch

As the OP references Number of commits on branch in git I want to add that the given answers there also work with any other branch, at least since git version 2.17.1 (and seemingly more reliably than the answer by Peter van der Does):

working correctly:

git checkout current-development-branch
git rev-list --no-merges --count master..
62
git checkout -b testbranch_2
git rev-list --no-merges --count current-development-branch..
0

The last command gives zero commits as expected since I just created the branch. The command before gives me the real number of commits on my development-branch minus the merge-commit(s)

not working correctly:

git checkout current-development-branch
git rev-list --no-merges --count HEAD
361
git checkout -b testbranch_1
git rev-list --no-merges --count HEAD
361

In both cases I get the number of all commits in the development branch and master from which the branches (indirectly) descend.

How to avoid java.util.ConcurrentModificationException when iterating through and removing elements from an ArrayList

While iterating the list, if you want to remove the element is possible. Let see below my examples,

ArrayList<String>  names = new ArrayList<String>();
        names.add("abc");
        names.add("def");
        names.add("ghi");
        names.add("xyz");

I have the above names of Array list. And i want to remove the "def" name from the above list,

for(String name : names){
    if(name.equals("def")){
        names.remove("def");
    }
}

The above code throws the ConcurrentModificationException exception because you are modifying the list while iterating.

So, to remove the "def" name from Arraylist by doing this way,

Iterator<String> itr = names.iterator();            
while(itr.hasNext()){
    String name = itr.next();
    if(name.equals("def")){
        itr.remove();
    }
}

The above code, through iterator we can remove the "def" name from the Arraylist and try to print the array, you would be see the below output.

Output : [abc, ghi, xyz]

Command output redirect to file and terminal

In case somebody needs to append the output and not overriding, it is possible to use "-a" or "--append" option of "tee" command :

ls 2>&1 | tee -a /tmp/ls.txt
ls 2>&1 | tee --append /tmp/ls.txt