Programs & Examples On #Log files

apache server reached MaxClients setting, consider raising the MaxClients setting

When you use Apache with mod_php apache is enforced in prefork mode, and not worker. As, even if php5 is known to support multi-thread, it is also known that some php5 libraries are not behaving very well in multithreaded environments (so you would have a locale call on one thread altering locale on other php threads, for example).

So, if php is not running in cgi way like with php-fpm you have mod_php inside apache and apache in prefork mode. On your tests you have simply commented the prefork settings and increased the worker settings, what you now have is default values for prefork settings and some altered values for the shared ones :

StartServers       20
MinSpareServers    5
MaxSpareServers    10
MaxClients         1024
MaxRequestsPerChild  0

This means you ask apache to start with 20 process, but you tell it that, if there is more than 10 process doing nothing it should reduce this number of children, to stay between 5 and 10 process available. The increase/decrease speed of apache is 1 per minute. So soon you will fall back to the classical situation where you have a fairly low number of free available apache processes (average 2). The average is low because usually you have something like 5 available process, but as soon as the traffic grows they're all used, so there's no process available as apache is very slow in creating new forks. This is certainly increased by the fact your PHP requests seems to be quite long, they do not finish early and the apache forks are not released soon enough to treat another request.

See on the last graphic the small amount of green before the red peak? If you could graph this on a 1 minute basis instead of 5 minutes you would see that this green amount was not big enough to take the incoming traffic without any error message.

Now you set 1024 MaxClients. I guess the cacti graph are not taken after this configuration modification, because with such modification, when no more process are available, apache would continue to fork new children, with a limit of 1024 busy children. Take something like 20MB of RAM per child (or maybe you have a big memory_limit in PHP and allows something like 64MB or 256MB and theses PHP requests are really using more RAM), maybe a DB server... your server is now slowing down because you have only 768MB of RAM. Maybe when apache is trying to initiate the first 20 children you already reach the available RAM limit.

So. a classical way of handling that is to check the amount of memory used by an apache fork (make some top commands while it is running), then find how many parallel request you can handle with this amount of RAM (that mean parallel apache children in prefork mode). Let's say it's 12, for example. Put this number in apache mpm settings this way:

<IfModule prefork.c>
  StartServers       12
  MinSpareServers    12
  MaxSpareServers    12
  MaxClients         12
  MaxRequestsPerChild  300
</IfModule>

That means you do not move the number of fork while traffic increase or decrease, because you always want to use all the RAM and be ready for traffic peaks. The 300 means you recyclate each fork after 300 requests, it's better than 0, it means you will not have potential memory leaks issues. MaxClients is set to 12 25 or 50 which is more than 12 to handle the ListenBacklog queue, which can enqueue some requests, you may take a bigger queue, but you would get some timeouts maybe (removed this strange sentende, I can't remember why I said that, if more than 12 requests are incoming the next one will be pushed in the Backlog queue, but you should set MaxClient to your targeted number of processes).

And yes, that means you cannot handle more than 12 parallel requests.

If you want to handle more requests:

  • buy some more RAM
  • try to use apache in worker mode, but remove mod_php and use php as a parallel daemon with his own pooler settings (this is called php-fpm), connect it with fastcgi. Note that you will certainly need to buy some RAM to allow a big number of parallel php-fpm process, but maybe less than with mod_php
  • Reduce the time spent in your php process. From your cacti graphs you have to potential problems: a real traffic peak around 11:25-11:30 or some php code getting very slow. Fast requests will reduce the number of parallel requests.

If your problem is really traffic peaks, solutions could be available with caches, like a proxy-cache server. If the problem is a random slowness in PHP then... it's an application problem, do you do some HTTP query to another site from PHP, for example?

And finally, as stated by @Jan Vlcinsky you could try nginx, where php will only be available as php-fpm. If you cannot buy RAM and must handle a big traffic that's definitively desserve a test.

Update: About internal dummy connections (if it's your problem, but maybe not).

Check this link and this previous answer. This is 'normal', but if you do not have a simple virtualhost theses requests are maybe hitting your main heavy application, generating slow http queries and preventing regular users to acces your apache processes. They are generated on graceful reload or children managment.

If you do not have a simple basic "It works" default Virtualhost prevent theses requests on your application by some rewrites:

  RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
  RewriteRule .* - [F,L]

Update:

Having only one Virtualhost does not protect you from internal dummy connections, it is worst, you are sure now that theses connections are made on your unique Virtualhost. So you should really avoid side effects on your application by using the rewrite rules.

Reading your cacti graphics, it seems your apache is not in prefork mode bug in worker mode. Run httpd -l or apache2 -l on debian, and check if you have worker.c or prefork.c. If you are in worker mode you may encounter some PHP problems in your application, but you should check the worker settings, here is an example:

<IfModule worker.c>
  StartServers           3
  MaxClients           500
  MinSpareThreads       75
  MaxSpareThreads      250 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

You start 3 processes, each containing 25 threads (so 3*25=75 parallel requests available by default), you allow 75 threads doing nothing, as soon as one thread is used a new process is forked, adding 25 more threads. And when you have more than 250 threads doing nothing (10 processes) some process are killed. You must adjust theses settings with your memory. Here you allow 500 parallel process (that's 20 process of 25 threads). Your usage is maybe more:

<IfModule worker.c>
  StartServers           2
  MaxClients           250
  MinSpareThreads       50
  MaxSpareThreads      150 
  ThreadsPerChild       25
  MaxRequestsPerChild  300
</IfModule>

What is the purpose of "&&" in a shell command?

See the example:

mkdir test && echo "Something" > test/file

Shell will try to create directory test and then, only if it was successfull will try create file inside it.

So you may interrupt a sequence of steps if one of them failed.

mongodb/mongoose findMany - find all documents with IDs listed in array

The find function in mongoose is a full query to mongoDB. This means you can use the handy mongoDB $in clause, which works just like the SQL version of the same.

model.find({
    '_id': { $in: [
        mongoose.Types.ObjectId('4ed3ede8844f0f351100000c'),
        mongoose.Types.ObjectId('4ed3f117a844e0471100000d'), 
        mongoose.Types.ObjectId('4ed3f18132f50c491100000e')
    ]}
}, function(err, docs){
     console.log(docs);
});

This method will work well even for arrays containing tens of thousands of ids. (See Efficiently determine the owner of a record)

I would recommend that anybody working with mongoDB read through the Advanced Queries section of the excellent Official mongoDB Docs

How to remove item from a python list in a loop?

x = [i for i in x if len(i)==2]

Http Post request with content type application/x-www-form-urlencoded not working in Spring

replace contentType : "application/x-www-form-urlencoded", by dataType : "text" as wildfly 11 doesn't support mentioned contenttype..

How can I make a UITextField move up when the keyboard is present - on starting to edit?

Very lightweight solution could be using KeyboardAnimator.

project got the sample implementation, documentation is still in progress...

Appropriate usage :: It's have a specific implementation for UITextField & UITextView

Limitation:: It's fully on objective-c, swift version will be available soon.

.gitignore exclude folder but include specific subfolder

@Chris Johnsen's answer is great, but with a newer versions of Git (1.8.2 or later), there is a double asterisk pattern you can leverage for a bit more shorthand solution:

# assuming the root folder you want to ignore is 'application'
application/**/*

# the subfolder(s) you want to track:
!application/language/gr/

This way you don't have to "unignore" parent directory of the subfolder you want to track.


With Git 2.17.0 (Not sure how early before this version. Possibly back to 1.8.2), using the ** pattern combined with excludes for each subdirectory leading up to your file(s) works. For example:

# assuming the root folder you want to ignore is 'application'
application/**

# Explicitly track certain content nested in the 'application' folder:
!application/language/
!application/language/gr/
!application/language/gr/** # Example adding all files & folder in the 'gr' folder
!application/language/gr/SomeFile.txt # Example adding specific file in the 'gr' folder

HTTP GET request in JavaScript?

// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest()

// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'restUrl', true)

request.onload = function () {
  // Begin accessing JSON data here
}

// Send request
request.send()

What is "pass-through authentication" in IIS 7?

Normally, IIS would use the process identity (the user account it is running the worker process as) to access protected resources like file system or network.

With passthrough authentication, IIS will attempt to use the actual identity of the user when accessing protected resources.

If the user is not authenticated, IIS will use the application pool identity instead. If pool identity is set to NetworkService or LocalSystem, the actual Windows account used is the computer account.

The IIS warning you see is not an error, it's just a warning. The actual check will be performed at execution time, and if it fails, it'll show up in the log.

Right query to get the current number of connections in a PostgreSQL DB

The following query is very helpful

select  * from
(select count(*) used from pg_stat_activity) q1,
(select setting::int res_for_super from pg_settings where name=$$superuser_reserved_connections$$) q2,
(select setting::int max_conn from pg_settings where name=$$max_connections$$) q3;

Extracting numbers from vectors of strings

Here's an alternative to Arun's first solution, with a simpler Perl-like regular expression:

as.numeric(gsub("[^\\d]+", "", years, perl=TRUE))

How to print a float with 2 decimal places in Java?

Try this:-

private static String getDecimalFormat(double value) {

    String getValue = String.valueOf(value).split("[.]")[1];

      if (getValue.length() == 1) {
          return String.valueOf(value).split("[.]")[0] +
                "."+ getValue.substring(0, 1) + 
                String.format("%0"+1+"d", 0);
       } else {
          return String.valueOf(value).split("[.]")[0]
            +"." + getValue.substring(0, 2);
      }


 }

Chrome Dev Tools - Modify javascript and reload

Great news, the fix is coming in March 2018, see this link: https://developers.google.com/web/updates/2018/01/devtools

"Local Overrides let you make changes in DevTools, and keep those changes across page loads. Previously, any changes that you made in DevTools would be lost when you reloaded the page. Local Overrides work for most file types

How it works:

  • You specify a directory where DevTools should save changes. When you make changes in DevTools, DevTools saves a copy of the modified file to your directory.
  • When you reload the page, DevTools serves the local, modified file, rather than the network resource.

To set up Local Overrides:

  1. Open the Sources panel.
  2. Open the Overrides tab.
  3. Click Setup Overrides.
  4. Select which directory you want to save your changes to.
  5. At the top of your viewport, click Allow to give DevTools read and write access to the directory.
  6. Make your changes."

UPDATE (March 19, 2018): It's live, detailed explanations here: https://developers.google.com/web/updates/2018/01/devtools#overrides

How to remove all the null elements inside a generic list in one go?

You'll probably want the following.

List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
parameterList.RemoveAll(item => item == null);

Comparing two .jar files

Here is my script to do the process described by sje397:

    #!/bin/sh

    # Needed if running on Windows
    FIND="/usr/bin/find"
    DIFF="diff -r"

    # Extract the jar (war or ear)
    JAR_FILE1=$1
    JAR_FILE2=$2

    JAR_DIR=${PWD}          # to assign to a variable
    TEMP_DIR=$(mktemp -d)

    echo "Extracting jars in $TEMP_DIR"

    EXT_DIR1="${TEMP_DIR}/${JAR_FILE1%.*}"
    EXT_DIR2="${TEMP_DIR}/${JAR_FILE2%.*}"

    mkdir ${EXT_DIR1}
    cd ${EXT_DIR1}
    jar xf ${JAR_DIR}/${JAR_FILE1}
    jad -d . -o -t2 -safe -space -b -ff -s java -r **/*.class
    cd ..

    mkdir ${EXT_DIR2}
    cd ${EXT_DIR2}
    jar xf ${JAR_DIR}/${JAR_FILE2}
    jad -d . -o -t2 -safe -space -b -ff -s java -r **/*.class
    cd ..

    # remove class files so the diff is clean
    ${FIND} ${TEMP_DIR} -name '*.class' | xargs rm

    # diff recursively 
    ${DIFF} ${EXT_DIR1} ${EXT_DIR2}

I can run it on Windows using GIT for Windows. Just open a command prompt. Run bash and then execute the script from there.

href around input type submit

I agree with Quentin. It doesn't make sense as to why you want to do it like that. It's part of the Semantic Web concept. You have to plan out the objects of your web site for future integration/expansion. Another web app or web site cannot interact with your content if it doesn't follow the proper use-case.

IE and Firefox are two different beasts. There are a lot of things that IE allows that Firefox and other standards-aware browsers reject.

If you're trying to create buttons without actually submitting data then use a combination of DIV/CSS.

How to add an extra source directory for maven to compile and include in the build jar?

You can use the Build Helper Plugin, e.g:

<project>
  ...
  <build>
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>build-helper-maven-plugin</artifactId>
        <version>3.2.0</version>
        <executions>
          <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals>
              <goal>add-source</goal>
            </goals>
            <configuration>
              <sources>
                <source>some directory</source>
                ...
              </sources>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>

Show loading gif after clicking form submit using jQuery

The show() method only affects the display CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button element is a button and does not raise a submit event. You would need to change your selector to the form for that to work:

$('#login_form').submit(function() {
    $('#gif').css('visibility', 'visible');
});

Also note that return true; is redundant in your logic, so it can be removed.

Difference between "module.exports" and "exports" in the CommonJs Module System

Renee's answer is well explained. Addition to the answer with an example:

Node does a lot of things to your file and one of the important is WRAPPING your file. Inside nodejs source code "module.exports" is returned. Lets take a step back and understand the wrapper. Suppose you have

greet.js

var greet = function () {
   console.log('Hello World');
};

module.exports = greet;

the above code is wrapped as IIFE(Immediately Invoked Function Expression) inside nodejs source code as follows:

(function (exports, require, module, __filename, __dirname) { //add by node

      var greet = function () {
         console.log('Hello World');
      };

      module.exports = greet;

}).apply();                                                  //add by node

return module.exports;                                      //add by node

and the above function is invoked (.apply()) and returned module.exports. At this time module.exports and exports pointing to the same reference.

Now, imagine you re-write greet.js as

exports = function () {
   console.log('Hello World');
};
console.log(exports);
console.log(module.exports);

the output will be

[Function]
{}

the reason is : module.exports is an empty object. We did not set anything to module.exports rather we set exports = function()..... in new greet.js. So, module.exports is empty.

Technically exports and module.exports should point to same reference(thats correct!!). But we use "=" when assigning function().... to exports, which creates another object in the memory. So, module.exports and exports produce different results. When it comes to exports we can't override it.

Now, imagine you re-write (this is called Mutation) greet.js (referring to Renee answer) as

exports.a = function() {
    console.log("Hello");
}

console.log(exports);
console.log(module.exports);

the output will be

{ a: [Function] }
{ a: [Function] }

As you can see module.exports and exports are pointing to same reference which is a function. If you set a property on exports then it will be set on module.exports because in JS, objects are pass by reference.

Conclusion is always use module.exports to avoid confusion. Hope this helps. Happy coding :)

When is it appropriate to use C# partial classes?

Aside from the other answers...

I've found them helpful as a stepping-stone in refactoring god-classes. If a class has multiple responsibilities (especially if it's a very large code-file) then I find it beneficial to add 1x partial class per-responsibility as a first-pass for organizing and then refactoring the code.

This helps greatly because it can help with making the code much more readable without actually effecting the executing behavior. It also can help identify when a responsibility is easy to refactor out or is tightly tangled with other aspects.

However--to be clear--this is still bad code, at the end of development you still want one responsibility per-class (NOT per partial class). It's just a stepping-stone :)

assign headers based on existing row in dataframe in R

Very similar to Vishnu's answer but uses the lapply to map all the data to characters then to assign them as the headers. This is really helpful if your data is imported as factors.

DF[] <- lapply(DF, as.character)
colnames(DF) <- DF[1, ]
DF <- DF[-1 ,]

note that that if you have a lot of numeric data or factors you want you'll need to convert them back. In this case it may make sense to store the character data frame, extract the row you want, and then apply it to the original data frame

tempDF <- DF
tempDF[] <- lapply(DF, as.character)
colnames(DF) <- tempDF[1, ]
DF <- DF[-1 ,]
tempDF <- NULL

How to prevent a browser from storing passwords

One way would be to generate random input names and work with them.

This way, browsers will be presented with the new form each time and won't be able to pre-populate the input fields.

If you provide us with some sample code (do you have a JavaScript single-page application (SPA) app or some server side rendering) I would be happy to help you in the implementation.

Check if a Class Object is subclass of another Class Object in Java

In addition to @To-kra's answer. If someone doesn't like recurrence:

    public static boolean isSubClassOf(Class<?> clazz, Class<?> superClass) {
        if(Object.class.equals(superClass)) {
            return true;
        }

        for(; !Object.class.equals(clazz); clazz = clazz.getSuperclass()) {
            if(clazz.getSuperclass().equals(superClass)) {
                return true;
            }
        }

        return false;
    }

NOTE: no null checking for clarity.

Where can I find Android source code online?

I stumbled across Android XRef the other day and found it useful, especially since it is backed by OpenGrok which offers insanely awesome and blindingly fast search.

Checking images for similarity with OpenCV

Sam's solution should be sufficient. I've used combination of both histogram difference and template matching because not one method was working for me 100% of the times. I've given less importance to histogram method though. Here's how I've implemented in simple python script.

import cv2

class CompareImage(object):

    def __init__(self, image_1_path, image_2_path):
        self.minimum_commutative_image_diff = 1
        self.image_1_path = image_1_path
        self.image_2_path = image_2_path

    def compare_image(self):
        image_1 = cv2.imread(self.image_1_path, 0)
        image_2 = cv2.imread(self.image_2_path, 0)
        commutative_image_diff = self.get_image_difference(image_1, image_2)

        if commutative_image_diff < self.minimum_commutative_image_diff:
            print "Matched"
            return commutative_image_diff
        return 10000 //random failure value

    @staticmethod
    def get_image_difference(image_1, image_2):
        first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])
        second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])

        img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA)
        img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]
        img_template_diff = 1 - img_template_probability_match

        # taking only 10% of histogram diff, since it's less accurate than template method
        commutative_image_diff = (img_hist_diff / 10) + img_template_diff
        return commutative_image_diff


    if __name__ == '__main__':
        compare_image = CompareImage('image1/path', 'image2/path')
        image_difference = compare_image.compare_image()
        print image_difference

jQuery - hashchange event

Note that in case of IE 7 and IE 9 if statment will give true for ("onhashchange" in windows) but the window.onhashchange will never fire, so its better to store hash and check it after every 100 millisecond whether its changed or not for all versions of IE.

    if (("onhashchange" in window) && !($.browser.msie)) { 
         window.onhashchange = function () { 
              alert(window.location.hash);             
         }            
         // Or $(window).bind( 'hashchange',function(e) {  
         //       alert(window.location.hash); 
         //   });              
    }
    else { 
        var prevHash = window.location.hash;
        window.setInterval(function () {
           if (window.location.hash != prevHash) {
              prevHash = window.location.hash;
              alert(window.location.hash);
           }
        }, 100);
    }

Scala: what is the best way to append an element to an Array?

The easiest might be:

Array(1, 2, 3) :+ 4

Actually, Array can be implcitly transformed in a WrappedArray

log4j configuration via JVM argument(s)?

If you are using gradle. You can apply 'aplication' plugin and use the following command

  applicationDefaultJvmArgs = [
             "-Dlog4j.configurationFile=your.xml",
                              ]

What is the difference between x86 and x64

x86 is a family of backward-compatible instruction set architectures based on the Intel 8086 CPU and its Intel 8088 variant.

An instruction set architecture (ISA) is an abstract model of a computer. It is also referred to as architecture or computer architecture.

A realization of an ISA is called an implementation. An ISA permits multiple implementations that may vary in performance, physical size, and monetary cost (among other things); because the ISA serves as the interface between software and hardware.

Software that has been written for an ISA can run on different implementations of the same ISA (Exp: 32bit or 64bit). This has enabled binary compatibility between different generations of computers to be easily achieved, and the development of computer families.

Both of these developments have helped to lower the cost of computers and to increase their applicability. For these reasons, the ISA is one of the most important abstractions in computing today.

How to add a custom HTTP header to every WCF call?

If you just want to add the same header to all the requests to the service, you can do it with out any coding!
Just add the headers node with required headers under the endpoint node in your client config file

<client>  
  <endpoint address="http://localhost/..." >  
    <headers>  
      <HeaderName>Value</HeaderName>  
    </headers>   
 </endpoint>  

SQL Server Profiler - How to filter trace to only display events from one database?

By experiment I was able to observe this:

When SQL Profiler 2005 or SQL Profiler 2000 is used with database residing in SQLServer 2000 - problem mentioned problem persists, but when SQL Profiler 2005 is used with SQLServer 2005 database, it works perfect!

In Summary, the issue seems to be prevalent in SQLServer 2000 & rectified in SQLServer 2005.

The solution for the issue when dealing with SQLServer 2000 is (as explained by wearejimbo)

  1. Identify the DatabaseID of the database you want to filter by querying the sysdatabases table as below

    SELECT * 
    FROM master..sysdatabases 
    WHERE name like '%your_db_name%'   -- Remove this line to see all databases
    ORDER BY dbid
    
  2. Use the DatabaseID Filter (instead of DatabaseName) in the New Trace window of SQL Profiler 2000

java.security.AccessControlException: Access denied (java.io.FilePermission

Within your <jre location>\lib\security\java.policy try adding:

grant { permission java.security.AllPermission; };

And see if it allows you. If so, you will have to add more granular permissions.

See:

Java 8 Documentation for java.policy files

and

http://java.sun.com/developer/onlineTraining/Programming/JDCBook/appA.html

SQLAlchemy create_all() does not create tables

If someone is having issues with creating tables by using files dedicated to each model, be aware of running the "create_all" function from a file different from the one where that function is declared. So, if the filesystem is like this:

Root  
--app.py     <-- file from which app will be run
--models
----user.py      <-- file with "User" model
----order.py    <-- file with "Order" model
----database.py <-- file with database and "create_all" function declaration

Be careful about calling the "create_all" function from app.py.

This concept is explained better by the answer to this thread posted by @SuperShoot

How do I remove blank pages coming between two chapters in Appendix?

If you specify the option 'openany' in the \documentclass declaration each chapter in the book (I'm guessing you're using the book class as chapters open on the next page in reports and articles don't have chapters) will open on a new page, not necessarily the next odd-numbered page.

Of course, that's not quite what you want. I think you want to set openany for chapters in the appendix. 'fraid I don't know how to do that, I suspect that you need to roll up your sleeves and wrestle with TeX itself

How to load a resource bundle from a file resource in Java?

I think that you want the file's parent to be on the classpath, not the actual file itself.

Try this (may need some tweaking):

String path = "c:/temp/mybundle.txt";
java.io.File fl = new java.io.File(path);

try {
   resourceURL = fl.getParentFile().toURL();
} catch (MalformedURLException e) {
   e.printStackTrace();                     
}               

URLClassLoader urlLoader = new URLClassLoader(new java.net.URL[]{resourceURL});
java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("mybundle.txt", 
                java.util.Locale.getDefault(), urlLoader );

'System.OutOfMemoryException' was thrown when there is still plenty of memory free

32bit windows has a 2GB process memory limit. The /3GB boot option others have mentioned will make this 3GB with just 1gb remaining for OS kernel use. Realistically if you want to use more than 2GB without hassle then a 64bit OS is required. This also overcomes the problem whereby although you may have 4GB of physical RAM, the address space requried for the video card can make a sizeable chuck of that memory unusable - usually around 500MB.

How Connect to remote host from Aptana Studio 3

From the Project Explorer, expand the project you want to hook up to a remote site (or just right click and create a new Web project that's empty if you just want to explore a remote site from there). There's a "Connections" node, right click it and select "Add New connection...". A dialog will appear, at bottom you can select the destination as Remote and then click the "New..." button. There you can set up an FTP/FTPS/SFTP connection.

That's how you set up a connection that's tied to a project, typically for upload/download/sync between it and a project.

You can also do Window > Show View > Remote. From that view, you can click the globe icon in the upper right to add connections and in this view you can just browse your remote connections.

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

I agree with above answer. But here is another way of CSS compression.

You can concat your CSS by using YUI compressor:

module.exports = function(grunt) {
  var exec = require('child_process').exec;
   grunt.registerTask('cssmin', function() {
    var cmd = 'java -jar -Xss2048k '
      + __dirname + '/../yuicompressor-2.4.7.jar --type css '
      + grunt.template.process('/css/style.css') + ' -o '
      + grunt.template.process('/css/style.min.css')
    exec(cmd, function(err, stdout, stderr) {
      if(err) throw err;
    });
  });
}; 

Convert floating point number to a certain precision, and then copy to string

It's not print that does the formatting, It's a property of strings, so you can just use

newstring = "%.9f" % numvar

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

The version I'm using I think is the good one, since is the exact same as the Android Developer Docs, except for the name of the string, they used "view" and I used "webview", for the rest is the same

No, it is not.

The one that is new to the N Developer Preview has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request)

The one that is supported by all Android versions, including N, has this method signature:

public boolean shouldOverrideUrlLoading(WebView view, String url)

So why should I do to make it work on all versions?

Override the deprecated one, the one that takes a String as the second parameter.

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

You can use Object.values([]), you might need this polyfill if you don't already:

const objectToValuesPolyfill = (object) => {
  return Object.keys(object).map(key => object[key]);
};
Object.values = Object.values || objectToValuesPolyfill;

https://stackoverflow.com/a/54822153/846348

Then you can just do:

var object = {1: 'hello', 2: 'world'};
var array = Object.values(object);

Just remember that arrays in js can only use numerical keys so if you used something else in the object then those will become `0,1,2...x``

It can be useful to remove duplicates for example if you have a unique key.

var obj = {};
object[uniqueKey] = '...';

PHP Swift mailer: Failed to authenticate on SMTP using 2 possible authenticators

I got the same same error.

I was using gmail account and Google's SMTP server to send emails. The problem was due to SMTP server refusing to authorize as it considered my web host (through whom I sent email) as an intruder.

I followed Google's process to identify my web host as an valid entity to send email through my account and problem was solved.

Express.js - app.listen vs server.listen

The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io within the same HTTP server instance:

var express = require('express');
var app     = express();
var server  = require('http').createServer(app);
var io      = require('socket.io').listen(server);
...
server.listen(1234);

However, app.listen() also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:

var express   = require('express');
var app       = express();

// app.use/routes/etc...

var server    = app.listen(3033);
var io        = require('socket.io').listen(server);

io.sockets.on('connection', function (socket) {
  ...
});

OkHttp Post Body as JSON

In okhttp v4.* I got it working that way


// import the extensions!
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody

// ...

json : String = "..."

val JSON : MediaType = "application/json; charset=utf-8".toMediaType()
val jsonBody: RequestBody = json.toRequestBody(JSON)

// go on with Request.Builder() etc

How can I unstage my files again after making a local commit?

git reset --soft is just for that: it is like git reset --hard, but doesn't touch the files.

How to programmatically get iOS status bar height

Here is a Swift way to get screen status bar height:

var screenStatusBarHeight: CGFloat {
    return UIApplication.sharedApplication().statusBarFrame.height
}

These are included as a standard function in a project of mine: https://github.com/goktugyil/EZSwiftExtensions

Erase whole array Python

It's simple:

array = []

will set array to be an empty list. (They're called lists in Python, by the way, not arrays)

If that doesn't work for you, edit your question to include a code sample that demonstrates your problem.

Example on ToggleButton

Try this Toggle Buttons

test_activity.xml

<ToggleButton 
android:id="@+id/togglebutton" 
android:layout_width="100px" 
android:layout_height="50px" 
android:layout_centerVertical="true" 
android:layout_centerHorizontal="true"
android:onClick="toggleclick"/>

Test.java

public class Test extends Activity {

private ToggleButton togglebutton;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    togglebutton = (ToggleButton) findViewById(R.id.togglebutton);
}

public void toggleclick(View v){
    if(togglebutton.isChecked())
        Toast.makeText(TestActivity.this, "ON", Toast.LENGTH_SHORT).show();
    else
        Toast.makeText(TestActivity.this, "OFF", Toast.LENGTH_SHORT).show();
    }
}

Linux - Install redis-cli only

I made a simple pure-go solution, which is under development.

redis-cli: https://github.com/holys/redis-cli

Build once, and run everywhere. Fully portable.

Please feel free to have a try.

Export pictures from excel file into jpg using VBA

Thanks for the ideas! I used the above ideas to make a macro to do a bulk file conversion--convert every file of one format in a folder to another format.

This code requires a sheet with cells named "FilePath" (which must end in a "\"), "StartExt" (original file extension), and "EndExt" (desired file extension). Warning: it doesn't ask for confirmation before replacing existing files with the same name and extension.

Private Sub CommandButton1_Click()
    Dim path As String
    Dim pathExt As String
    Dim file As String
    Dim oldExt As String
    Dim newExt As String
    Dim newFile As String
    Dim shp As Picture
    Dim chrt As ChartObject
    Dim chrtArea As Chart

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    'Get settings entered by user
    path = Range("FilePath")
    oldExt = Range("StartExt")
    pathExt = path & "*." & oldExt
    newExt = Range("EndExt")

    file = Dir(pathExt)

    Do While Not file = "" 'cycle through all images in folder of selected format
        Set shp = ActiveSheet.Pictures.Insert(path & file) 'Import image
        newFile = Replace(file, "." & oldExt, "." & newExt) 'Determine new file name
        Set chrt = ActiveSheet.ChartObjects.Add(0, 0, shp.Width, shp.Height) 'Create blank chart for embedding image
        Set chrtArea = chrt.Chart
        shp.CopyPicture 'Copy image to clipboard
        With chrtArea 'Paste image to chart, then export
            .ChartArea.Select
            .Paste
            .Export (path & newFile)
        End With
        chrt.Delete 'Delete chart
        shp.Delete 'Delete imported image

        file = Dir 'Advance to next file
    Loop

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True


End Sub

How to generate the whole database script in MySQL Workbench?

In MySQL Workbench 6, commands have been repositioned as the "Server Administration" tab is gone.

You now find the option "Data Export" under the "Management" section when you open a standard server connection.

How to get a tab character?

Posting another alternative to be more complete. When I tried the "pre" based answers, they added extra vertical line breaks as well.

Each tab can be converted to a sequence non-breaking spaces which require no wrapping.

"&nbsp;&nbsp;&nbsp;&nbsp;" 

This is not recommended for repeated/extensive use within a page. A div margin/padding approach would appear much cleaner.

How to use unicode characters in Windows command line?

Check the language for non-Unicode programs. If you have problems with Russian in the Windows console, then you should set Russian here:

Changing language for non-Unicode programs

NLS_NUMERIC_CHARACTERS setting for decimal

To know SESSION decimal separator, you can use following SQL command:

ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';

select SUBSTR(value,1,1) as "SEPARATOR"
      ,'using NLS-PARAMETER' as "Explanation"
  from nls_session_parameters
  where parameter = 'NLS_NUMERIC_CHARACTERS'

UNION ALL

select SUBSTR(0.5,1,1) as "SEPARATOR" 
      ,'using NUMBER IMPLICIT CASTING' as "Explanation"
  from DUAL;

The first SELECT command find NLS Parameter defined in NLS_SESSION_PARAMETERS table. The decimal separator is the first character of the returned value.

The second SELECT command convert IMPLICITELY the 0.5 rational number into a String using (by default) NLS_NUMERIC_CHARACTERS defined at session level.

The both command return same value.

I have already tested the same SQL command in PL/SQL script and this is always the same value COMMA or POINT that is displayed. Decimal Separator displayed in PL/SQL script is equal to what is displayed in SQL.

To test what I say, I have used following SQL commands:

ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';

select 'DECIMAL-SEPARATOR on CLIENT: (' || TO_CHAR(.5,) || ')' from dual;

DECLARE
    S VARCHAR2(10) := '?';
BEGIN

    select .5 INTO S from dual;

    DBMS_OUTPUT.PUT_LINE('DECIMAL-SEPARATOR in PL/SQL: (' || S || ')');
END;
/

The shorter command to know decimal separator is:

SELECT .5 FROM DUAL;

That return 0,5 if decimal separator is a COMMA and 0.5 if decimal separator is a POINT.

getting the ng-object selected with ng-change

Instead of setting the ng-model to item.size.code, how about setting it to size:

<select ng-options="size as size.name for size in sizes" 
   ng-model="item" ng-change="update()"></select>

Then in your update() method, $scope.item will be set to the currently selected item.

And whatever code needed item.size.code, can get that property via $scope.item.code.

Fiddle.

Update based on more info in comments:

Use some other $scope property for your select ng-model then:

<select ng-options="size as size.name for size in sizes" 
   ng-model="selectedItem" ng-change="update()"></select>

Controller:

$scope.update = function() {
   $scope.item.size.code = $scope.selectedItem.code
   // use $scope.selectedItem.code and $scope.selectedItem.name here
   // for other stuff ...
}

PHP namespaces and "use"

If you need to order your code into namespaces, just use the keyword namespace:

file1.php

namespace foo\bar;

In file2.php

$obj = new \foo\bar\myObj();

You can also use use. If in file2 you put

use foo\bar as mypath;

you need to use mypath instead of bar anywhere in the file:

$obj  = new mypath\myObj();

Using use foo\bar; is equal to use foo\bar as bar;.

jQuery - Appending a div to body, the body is the object?

Instead use use appendTo. append or appendTo returns a jQuery object so you don't have to wrap it inside $().

var holdyDiv = $('<div />').appendTo('body');
holdyDiv.attr('id', 'holdy');

.appendTo() reference: http://api.jquery.com/appendTo/

Alernatively you can try this also.

$('<div />', { id: 'holdy' }).appendTo('body');
               ^
             (Here you can specify any attribute/value pair you want)

Error: unable to verify the first certificate in nodejs

The server you're trying to download from may be badly configured. Even if it works in your browser, it may not be including all the public certificates in the chain needed for a cache-empty client to verify.

I recommend checking the site in SSLlabs tool: https://www.ssllabs.com/ssltest/

Look for this error:

This server's certificate chain is incomplete.

And this:

Chain issues.........Incomplete

Undefined variable: $_SESSION

Turned out there was some extra code in the AppModel that was messing things up:

in beforeFind and afterFind:

App::Import("Session");
$session = new CakeSession();
$sim_id = $session->read("Simulation.id");

I don't know why, but that was what the problem was. Removing those lines fixed the issue I was having.

ClassNotFoundException com.mysql.jdbc.Driver

I experienced the same error after upgrading my java to 1.8.0_101. Try this: i. Remove the mysql.jar fro your buildpath. ii. Clean the server and project iii. Add the jar file back to the build path.

Worked for me.

Create Pandas DataFrame from a string

Simplest way is to save it to temp file and then read it:

import pandas as pd

CSV_FILE_NAME = 'temp_file.csv'  # Consider creating temp file, look URL below
with open(CSV_FILE_NAME, 'w') as outfile:
    outfile.write(TESTDATA)
df = pd.read_csv(CSV_FILE_NAME, sep=';')

Right way of creating temp file: How can I create a tmp file in Python?

Using a custom typeface in Android

It may be useful to know that starting from Android 8.0 (API level 26) you can use a custom font in XML.

Simply put, you can do it in the following way.

  1. Put the font in the folder res/font.

  2. Either use it in the attribute of a widget

<Button android:fontFamily="@font/myfont"/>

or put it in res/values/styles.xml

<style name="MyButton" parent="android:Widget.Button">
    <item name="android:fontFamily">@font/myfont</item>
</style>

and use it as a style

<Button style="@style/MyButton"/>

C# Convert List<string> to Dictionary<string, string>

EDIT

another way to deal with duplicate is you can do like this

var dic = slist.Select((element, index)=> new{element,index} )
            .ToDictionary(ele=>ele.index.ToString(), ele=>ele.element);

or


easy way to do is

var res = list.ToDictionary(str => str, str=> str); 

but make sure that there is no string is repeating...again otherewise above code will not work for you

if there is string is repeating than its better to do like this

Dictionary<string,string> dic= new Dictionary<string,string> ();

    foreach(string s in Stringlist)
    {
       if(!dic.ContainsKey(s))
       {
        //  dic.Add( value to dictionary
      }
    }

Why would you use Expression<Func<T>> rather than Func<T>?

LINQ is the canonical example (for example, talking to a database), but in truth, any time you care more about expressing what to do, rather than actually doing it. For example, I use this approach in the RPC stack of protobuf-net (to avoid code-generation etc) - so you call a method with:

string result = client.Invoke(svc => svc.SomeMethod(arg1, arg2, ...));

This deconstructs the expression tree to resolve SomeMethod (and the value of each argument), performs the RPC call, updates any ref/out args, and returns the result from the remote call. This is only possible via the expression tree. I cover this more here.

Another example is when you are building the expression trees manually for the purpose of compiling to a lambda, as done by the generic operators code.

port forwarding in windows

nginx is useful for forwarding HTTP on many platforms including Windows. It's easy to setup and extend with more advanced configuration. A basic configuration could look something like this:

events {}

http {
     server {

        listen 192.168.1.111:4422;

        location / {
            proxy_pass http://192.168.2.33:80/;
        }
     }
}

What is the difference between a var and val definition in Scala?

As so many others have said, the object assigned to a val cannot be replaced, and the object assigned to a var can. However, said object can have its internal state modified. For example:

class A(n: Int) {
  var value = n
}

class B(n: Int) {
  val value = new A(n)
}

object Test {
  def main(args: Array[String]) {
    val x = new B(5)
    x = new B(6) // Doesn't work, because I can't replace the object created on the line above with this new one.
    x.value = new A(6) // Doesn't work, because I can't replace the object assigned to B.value for a new one.
    x.value.value = 6 // Works, because A.value can receive a new object.
  }
}

So, even though we can't change the object assigned to x, we could change the state of that object. At the root of it, however, there was a var.

Now, immutability is a good thing for many reasons. First, if an object doesn't change internal state, you don't have to worry if some other part of your code is changing it. For example:

x = new B(0)
f(x)
if (x.value.value == 0)
  println("f didn't do anything to x")
else
  println("f did something to x")

This becomes particularly important with multithreaded systems. In a multithreaded system, the following can happen:

x = new B(1)
f(x)
if (x.value.value == 1) {
  print(x.value.value) // Can be different than 1!
}

If you use val exclusively, and only use immutable data structures (that is, avoid arrays, everything in scala.collection.mutable, etc.), you can rest assured this won't happen. That is, unless there's some code, perhaps even a framework, doing reflection tricks -- reflection can change "immutable" values, unfortunately.

That's one reason, but there is another reason for it. When you use var, you can be tempted into reusing the same var for multiple purposes. This has some problems:

  • It will be more difficult for people reading the code to know what is the value of a variable in a certain part of the code.
  • You may forget to re-initialize the variable in some code path, and end up passing wrong values downstream in the code.

Simply put, using val is safer and leads to more readable code.

We can, then, go the other direction. If val is that better, why have var at all? Well, some languages did take that route, but there are situations in which mutability improves performance, a lot.

For example, take an immutable Queue. When you either enqueue or dequeue things in it, you get a new Queue object. How then, would you go about processing all items in it?

I'll go through that with an example. Let's say you have a queue of digits, and you want to compose a number out of them. For example, if I have a queue with 2, 1, 3, in that order, I want to get back the number 213. Let's first solve it with a mutable.Queue:

def toNum(q: scala.collection.mutable.Queue[Int]) = {
  var num = 0
  while (!q.isEmpty) {
    num *= 10
    num += q.dequeue
  }
  num
}

This code is fast and easy to understand. Its main drawback is that the queue that is passed is modified by toNum, so you have to make a copy of it beforehand. That's the kind of object management that immutability makes you free from.

Now, let's covert it to an immutable.Queue:

def toNum(q: scala.collection.immutable.Queue[Int]) = {
  def recurse(qr: scala.collection.immutable.Queue[Int], num: Int): Int = {
    if (qr.isEmpty)
      num
    else {
      val (digit, newQ) = qr.dequeue
      recurse(newQ, num * 10 + digit)
    }
  }
  recurse(q, 0)
}

Because I can't reuse some variable to keep track of my num, like in the previous example, I need to resort to recursion. In this case, it is a tail-recursion, which has pretty good performance. But that is not always the case: sometimes there is just no good (readable, simple) tail recursion solution.

Note, however, that I can rewrite that code to use an immutable.Queue and a var at the same time! For example:

def toNum(q: scala.collection.immutable.Queue[Int]) = {
  var qr = q
  var num = 0
  while (!qr.isEmpty) {
    val (digit, newQ) = qr.dequeue
    num *= 10
    num += digit
    qr = newQ
  }
  num
}

This code is still efficient, does not require recursion, and you don't need to worry whether you have to make a copy of your queue or not before calling toNum. Naturally, I avoided reusing variables for other purposes, and no code outside this function sees them, so I don't need to worry about their values changing from one line to the next -- except when I explicitly do so.

Scala opted to let the programmer do that, if the programmer deemed it to be the best solution. Other languages have chosen to make such code difficult. The price Scala (and any language with widespread mutability) pays is that the compiler doesn't have as much leeway in optimizing the code as it could otherwise. Java's answer to that is optimizing the code based on the run-time profile. We could go on and on about pros and cons to each side.

Personally, I think Scala strikes the right balance, for now. It is not perfect, by far. I think both Clojure and Haskell have very interesting notions not adopted by Scala, but Scala has its own strengths as well. We'll see what comes up on the future.

Java HTML Parsing

HTMLUnit might be of help. It does a lot more stuff too.

http://htmlunit.sourceforge.net/1

Run-time error '1004' - Method 'Range' of object'_Global' failed

Change

Range(DataImportColumn & DataImportRow).Offset(0, 2).Value

to

Cells(DataImportRow,DataImportColumn).Value

When you just have the row and the column then you can use the cells() object. The syntax is Cells(Row,Column)

Also one more tip. You might want to fully qualify your Cells object. for example

ThisWorkbook.Sheets("WhatEver").Cells(DataImportRow,DataImportColumn).Value

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

from Jackson 2.7.x+ there is a way to annotate the member variable itself:

 @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY)
 private List<String> newsletters;

More info here: Jackson @JsonFormat

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

According to the JUnit GitHub team website (https://github.com/junit-team/junit/wiki/Download-and-Install), junit.jar and hamcrest-core.jar are both needed in the classpath when using JUnit 4.11.

Here is the Maven dependency block for including junit and hamcrest.

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.1.2</version>
    <scope>test</scope>
</dependency>
<!-- Needed by junit -->
<dependency>
    <groupId>org.hamcrest</groupId>
    <artifactId>hamcrest-all</artifactId>
    <version>1.3</version>
    <scope>test</scope>
</dependency>

Setting the zoom level for a MKMapView

For Swift 3 it's pretty fast forward:

private func setMapRegion(for location: CLLocationCoordinate2D, animated: Bool)
{
    let viewRegion = MKCoordinateRegionMakeWithDistance(location, <#T##latitudinalMeters: CLLocationDistance##CLLocationDistance#>, <#T##longitudinalMeters: CLLocationDistance##CLLocationDistance#>)
    MapView.setRegion(viewRegion, animated: animated)
}

Just define the lat-, long-Meters <CLLocationDistance> and the mapView will fit the zoom level to your values.

Header div stays at top, vertical scrolling div below with scrollbar only attached to that div

HTML:

?<div class="header">This is the header</div>
<div class="content">This is the content</div>?????????????????????????????????

CSS:

?.header
{
    height:50px;
}
.content
{
    position:absolute;
    top: 50px;
    left:0px;
    right:0px;
    bottom:0px;
    overflow-y:scroll;        
}?

Simplest way to have a configuration file in a Windows Forms C# application

You should create an App.config file (very similar to web.config).

You should right click on your project, add new item, and choose new "Application Configuration File".

Ensure that you add using System.Configuration in your project.

Then you can add values to it:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add key="setting1" value="key"/>
  </appSettings>
  <connectionStrings>
    <add name="prod" connectionString="YourConnectionString"/>
  </connectionStrings>
</configuration>

    private void Form1_Load(object sender, EventArgs e)
    {
        string setting = ConfigurationManager.AppSettings["setting1"];
        string conn = ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
    }

Just a note: According to Microsoft, you should use ConfigurationManager instead of ConfigurationSettings (see the remarks section):

"The ConfigurationSettings class provides backward compatibility only. For new applications you should use the ConfigurationManager class or WebConfigurationManager class instead. "

Remove/ truncate leading zeros by javascript/jquery

I would use the Number() function:

var str = "00001";
str = Number(str).toString();
>> "1"

Or I would multiply my string by 1

var str = "00000000002346301625363";
str = (str * 1).toString();
>> "2346301625363"

What is Type-safe?

Try this explanation on...

TypeSafe means that variables are statically checked for appropriate assignment at compile time. For example, consder a string or an integer. These two different data types cannot be cross-assigned (ie, you can't assign an integer to a string nor can you assign a string to an integer).

For non-typesafe behavior, consider this:

object x = 89;
int y;

if you attempt to do this:

y = x;

the compiler throws an error that says it can't convert a System.Object to an Integer. You need to do that explicitly. One way would be:

y = Convert.ToInt32( x );

The assignment above is not typesafe. A typesafe assignement is where the types can directly be assigned to each other.

Non typesafe collections abound in ASP.NET (eg, the application, session, and viewstate collections). The good news about these collections is that (minimizing multiple server state management considerations) you can put pretty much any data type in any of the three collections. The bad news: because these collections aren't typesafe, you'll need to cast the values appropriately when you fetch them back out.

For example:

Session[ "x" ] = 34;

works fine. But to assign the integer value back, you'll need to:

int i = Convert.ToInt32( Session[ "x" ] );

Read about generics for ways that facility helps you easily implement typesafe collections.

C# is a typesafe language but watch for articles about C# 4.0; interesting dynamic possibilities loom (is it a good thing that C# is essentially getting Option Strict: Off... we'll see).

A long bigger than Long.MAX_VALUE

You can't. If you have a method called isBiggerThanMaxLong(long) it should always return false.

If you were to increment the bits of Long.MAX_VALUE, the next value should be Long.MIN_VALUE. Read up on twos-complement and that should tell you why.

Adding a UISegmentedControl to UITableView

   self.tableView.tableHeaderView = segmentedControl; 

If you want it to obey your width and height properly though enclose your segmentedControl in a UIView first as the tableView likes to mangle your view a bit to fit the width.

enter image description here enter image description here

Smooth scrolling when clicking an anchor link

Only CSS

html {
    scroll-behavior: smooth !important;
}

All you need to add only this. Now your internal links scrolling behavior will be smooth like a stream-flow.

Programmatically: Something extra and advanced

// Scroll to specific values
// scrollTo is the same
window.scroll({
  top: 1000, 
  left: 0, 
  behavior: 'smooth'
});

// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 250, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

// Scroll to a certain element
document.getElementById('el').scrollIntoView({
  behavior: 'smooth'
})

Note: All latest browsers (Opera, Chrome, Firefox etc) supports this feature.

for detail understanding, read this article

Any free WPF themes?

Not purely themes, but MahApps.Metro provides Windows 8 Look and feel with a few variants like dark and light base themes with green,blue etc for text and others. Its pretty cool and can be used out of the box.

Copying text to the clipboard using Java

The following class allows you to copy/paste a String to/from the clipboard.

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;

import static java.awt.event.KeyEvent.*;
import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC;

public class SystemClipboard
{
    public static void copy(String text)
    {
        Clipboard clipboard = getSystemClipboard();
        clipboard.setContents(new StringSelection(text), null);
    }

    public static void paste() throws AWTException
    {
        Robot robot = new Robot();

        int controlKey = IS_OS_MAC ? VK_META : VK_CONTROL;
        robot.keyPress(controlKey);
        robot.keyPress(VK_V);
        robot.keyRelease(controlKey);
        robot.keyRelease(VK_V);
    }

    public static String get() throws Exception
    {
        Clipboard systemClipboard = getSystemClipboard();
        DataFlavor dataFlavor = DataFlavor.stringFlavor;

        if (systemClipboard.isDataFlavorAvailable(dataFlavor))
        {
            Object text = systemClipboard.getData(dataFlavor);
            return (String) text;
        }

        return null;
    }

    private static Clipboard getSystemClipboard()
    {
        Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
        return defaultToolkit.getSystemClipboard();
    }
}

How to install cron

Install cron on Linux/Unix:

apt-get install cron

Use cron on Linux/Unix

crontab -e

See the canonical answer about cron for more details: https://serverfault.com/questions/449651/why-is-my-crontab-not-working-and-how-can-i-troubleshoot-it

Get encoding of a file in Windows

If you have "git" or "Cygwin" on your Windows Machine, then go to the folder where your file is present and execute the command:

file *

This will give you the encoding details of all the files in that folder.

Why does Python code use len() function instead of a length method?

You can also say

>> x = 'test'
>> len(x)
4

Using Python 2.7.3.

How do I trim whitespace?

    something = "\t  please_     \t remove_  all_    \n\n\n\nwhitespaces\n\t  "

    something = "".join(something.split())

output:

please_remove_all_whitespaces


Adding Le Droid's comment to the answer. To separate with a space:

    something = "\t  please     \t remove  all   extra \n\n\n\nwhitespaces\n\t  "
    something = " ".join(something.split())

output:

please remove all extra whitespaces

Add shadow to custom shape on Android

For some reason shadows don't work if you set <solid> AND <stroke> on your custom background drawable. Creating a <layer-list> with separate layers for fill and borders fixes the issue:

<?xml version="1.0" encoding="utf-8"?>
<!-- Separate layers for solid and stroke, because no shadows get drawn otherwise (using elevation) -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@color/card_default" />
            <corners android:radius="@dimen/card_corner_radius" />
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <stroke android:color="@color/card_border" android:width="@dimen/card_border_width"/>
            <corners android:radius="@dimen/card_corner_radius" />
        </shape>
    </item>
</layer-list>

Background Image for Select (dropdown) does not work in Chrome

What Arne said - you can't reliably style select boxes and have them look anything like consistent across browsers.

Uniform: https://github.com/pixelmatrix/uniform is a javascript solution which gives you good graphic control over your form elements - it's still Javascript, but it's about as nice as javascript gets for solving this problem.

Import a custom class in Java

I see the picture, and all your classes are in the same package. So you don't have to import, you can create a new instance without the import sentence.

How can I style even and odd elements?

 <ul class="names" id="names_list">
          <a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="1">Ashwin Nair</li></a>
           <a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="2">Anil Reddy</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="3">Chirag</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="4">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="15">Ashwin</li></a>
            <a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="16">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="17">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="18">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="19">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">2</span><li class="part2" id="188">Anil Reddy</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="111">Bhavesh</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="122">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">0</span><li class="part1" id="133">Ashwin</li></a>
            <a href="javascript:void(0);"><span class="badge">0</span><li class="part2" id="144">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">5</span><li class="part1" id="199">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">6</span><li class="part2" id="156">Ashwin</li></a>
           <a href="javascript:void(0);"><span class="badge">1</span><li class="part1" id="174">Ashwin</li></a>

         </ul>    
$(document).ready(function(){
      var a=0;
      var ac;
      var ac2;
        $(".names li").click(function(){
           var b=0;
            if(a==0)
            {
              var accc="#"+ac2;
     if(ac=='part2')
     {
    $(accc).css({

    "background": "#322f28",
    "color":"#fff",
    });
     }
     if(ac=='part1')
     {

      $(accc).css({

      "background": "#3e3b34",
      "color":"#fff",
    });
     }

              $(this).css({
                "background":"#d3b730",
                "color":"#000",
            });
              ac=$(this).attr('class');
              ac2=$(this).attr('id');
    a=1;
            }
            else{

    var accc="#"+ac2;
    //alert(accc);
     if(ac=='part2')
     {
    $(accc).css({

    "background": "#322f28",
    "color":"#fff",
    });
     }
     if(ac=='part1')
     {

      $(accc).css({

      "background": "#3e3b34",
      "color":"#fff",
    });
     }

     a=0;
    ac=$(this).attr('class');
    ac2=$(this).attr('id');
    $(this).css({
                "background":"#d3b730",
                "color":"#000",
            });

            }

        });

linux execute command remotely

I guess ssh is the best secured way for this, for example :

ssh -OPTIONS -p SSH_PORT user@remote_server "remote_command1; remote_command2; remote_script.sh"  

where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.

Note:
If you do not want to be prompt at every ssh run, please also have a look to ssh-agent, and optionally to keychain if your system allows it. Key is... to understand the ssh keys exchange process. Please take a careful look to ssh_config (i.e. the ssh client config file) and sshd_config (i.e. the ssh server config file). Configuration filenames depend on your system, anyway you'll find them somewhere like /etc/sshd_config. Ideally, pls do not run ssh as root obviously but as a specific user on both sides, servers and client.

Some extra docs over the source project main pages :

ssh and ssh-agent
man ssh

http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring

keychain
http://www.gentoo.org/doc/en/keychain-guide.xml
an older tuto in French (by myself :-) but might be useful too :
http://hornetbzz.developpez.com/tutoriels/debian/ssh/keychain/

Import JSON file in React

Something that worked for me was to simply place the JSON file in the public folder. You can simply import in any js using

brain.loadData("exampleFile.json");

It is as simple as that I guess. Definitely worth a try :D

How do I turn off the mysql password validation?

CREATE USER 'username'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'organizer'@'localhost'  WITH GRANT OPTION;

CREATE USER 'username'@'%' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON *.* TO 'organizer'@'%' WITH GRANT OPTION;
FLUSH PRIVILEGES;

no need to stop/start mysql

How to add elements to a list in R (loop)

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

I am not sure if intercepting function keys is possible, but I would avoid using function keys all together. Function keys are used by browsers to perform a variety of tasks, some of them quite common. For example, in Firefox on Linux, at least six or seven of the function keys are reserved for use by the browser:

  • F1 (Help),
  • F3 (Search),
  • F5 (Refresh),
  • F6 (focus address bar),
  • F7 (caret browsing mode),
  • F11 (full screen mode), and
  • F12 (used by several add-ons, including Firebug)

The worst part is that different browsers on different operating systems use different keys for different things. That's a lot of differences to account for. You should stick to safer, less commonly used key combinations.

How to Free Inode Usage?

It's quite easy for a disk to have a large number of inodes used even if the disk is not very full.

An inode is allocated to a file so, if you have gazillions of files, all 1 byte each, you'll run out of inodes long before you run out of disk.

It's also possible that deleting files will not reduce the inode count if the files have multiple hard links. As I said, inodes belong to the file, not the directory entry. If a file has two directory entries linked to it, deleting one will not free the inode.

Additionally, you can delete a directory entry but, if a running process still has the file open, the inode won't be freed.

My initial advice would be to delete all the files you can, then reboot the box to ensure no processes are left holding the files open.

If you do that and you still have a problem, let us know.

By the way, if you're looking for the directories that contain lots of files, this script may help:

#!/bin/bash
# count_em - count files in all subdirectories under current directory.
echo 'echo $(ls -a "$1" | wc -l) $1' >/tmp/count_em_$$
chmod 700 /tmp/count_em_$$
find . -mount -type d -print0 | xargs -0 -n1 /tmp/count_em_$$ | sort -n
rm -f /tmp/count_em_$$

Proper MIME type for .woff2 fonts

font/woff2

For nginx add the following to the mime.types file:

font/woff2 woff2;


Old Answer

The mime type (sometime written as mimetype) for WOFF2 fonts has been proposed as application/font-woff2.

Also, if you refer to the spec (http://dev.w3.org/webfonts/WOFF2/spec/) you will see that font/woff2 is being discussed. I suspect that the filal mime type for all fonts will eventually be the more logical font/* (font/ttf, font/woff2 etc)...

N.B. WOFF2 is still in 'Working Draft' status -- not yet adopted officially.

Remove all newlines from inside a string

strip() returns the string after removing leading and trailing whitespace. see doc

In your case, you may want to try replace():

string2 = string1.replace('\n', '')

Find first element in a sequence that matches a predicate

You could use a generator expression with a default value and then next it:

next((x for x in seq if predicate(x)), None)

Although for this one-liner you need to be using Python >= 2.6.

This rather popular article further discusses this issue: Cleanest Python find-in-list function?.

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

next - it's like return, but for blocks! (So you can use this in any proc/lambda too.)

That means you can also say next n to "return" n from the block. For instance:

puts [1, 2, 3].map do |e|
  next 42 if e == 2
  e
end.inject(&:+)

This will yield 46.

Note that return always returns from the closest def, and never a block; if there's no surrounding def, returning is an error.

Using return from within a block intentionally can be confusing. For instance:

def my_fun
  [1, 2, 3].map do |e|
    return "Hello." if e == 2
    e
  end
end

my_fun will result in "Hello.", not [1, "Hello.", 2], because the return keyword pertains to the outer def, not the inner block.

Read XML Attribute using XmlDocument

I have an Xml File books.xml

<ParameterDBConfig>
    <ID Definition="1" />
</ParameterDBConfig>

Program:

XmlDocument doc = new XmlDocument();
doc.Load("D:/siva/books.xml");
XmlNodeList elemList = doc.GetElementsByTagName("ID");     
for (int i = 0; i < elemList.Count; i++)     
{
    string attrVal = elemList[i].Attributes["Definition"].Value;
}

Now, attrVal has the value of ID.

jQuery: select an element's class and id at the same time?

In the end the same rules as for css apply.

So I think this reference could be of some valuable use.

Move SQL Server 2008 database files to a new folder location

To add the privileges needed to the files add and grant right to the following local user: SQLServerMSSQLUser$COMPUTERNAME$INSTANCENAME, where COMPUTERNAME and INSTANCENAME has to be replaced with name of computer and MSSQL instance respectively.

What is meant by Ems? (Android TextView)

em is the typography unit of font width. one em in a 16-point typeface is 16 points

How can I get just the first row in a result set AFTER ordering?

In 12c, here's the new way:

select bla
  from bla
 where bla
 order by finaldate desc
 fetch first 1 rows only; 

How nice is that!

React js change child component's state from parent component

The parent component can manage child state passing a prop to child and the child convert this prop in state using componentWillReceiveProps.

class ParentComponent extends Component {
  state = { drawerOpen: false }
  toggleChildMenu = () => {
    this.setState({ drawerOpen: !this.state.drawerOpen })
  }
  render() {
    return (
      <div>
        <button onClick={this.toggleChildMenu}>Toggle Menu from Parent</button>
        <ChildComponent drawerOpen={this.state.drawerOpen} />
      </div>
    )
  }
}

class ChildComponent extends Component {
  constructor(props) {
    super(props)
    this.state = {
      open: false
    }
  }

  componentWillReceiveProps(props) {
    this.setState({ open: props.drawerOpen })
  }

  toggleMenu() {
    this.setState({
      open: !this.state.open
    })
  }

  render() {
    return <Drawer open={this.state.open} />
  }
}

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Using #!/usr/bin/env NAME makes the shell search for the first match of NAME in the $PATH environment variable. It can be useful if you aren't aware of the absolute path or don't want to search for it.

PHP Multiple Checkbox Array

Also remember you can include custom indices to the array sent to the server like this

<form method='post' id='userform' action='thisform.php'>
<tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[4]' value='Option One'>4<br>
    <input type='checkbox' name='checkboxvar[6]' value='Option Two'>6<br>
    <input type='checkbox' name='checkboxvar[9]' value='Option Three'>9
    </td>
</tr>
<input type='submit' class='buttons'>
</form>

This is particularly useful when you want to use the id of individual objects in a server array accounts (for instance) to send data back to the server and recognize same at server

<form method='post' id='userform' action='thisform.php'>
<tr>
    <td>Trouble Type</td>
    <td>
    <?php foreach($accounts as $account) { ?>
        <input type='checkbox' name='accounts[<?php echo $account->id ?>]' value='<?php echo $account->name ?>'>
        <?php echo $account->name ?>
        <br>
    <?php } ?>
    </td>
</tr>
<input type='submit' class='buttons'>
</form>

<?php 
if (isset($_POST['accounts'])) 
{
    print_r($_POST['accounts']); 
}
?>

java: ArrayList - how can I check if an index exists?

This is what you need ...

public boolean indexExists(final List list, final int index) {
    return index >= 0 && index < list.size();
}

Why not use an plain old array? Indexed access to a List is a code smell I think.

Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods

We have found that adding the Apptentive cocoa pod to an existing Xcode project may potentially not include some of our required frameworks.

Check your linker flags:

Target > Build Settings > Other Linker Flags 

You should see -lApptentiveConnect listed as a linker flag:

... -ObjC -lApptentiveConnect ... 

You should also see our required Frameworks listed:

  • Accelerate
  • CoreData
  • CoreText
  • CoreGraphics
  • CoreTelephony
  • Foundation
  • QuartzCore
  • StoreKit
  • SystemConfiguration
  • UIKit

    -ObjC -lApptentiveConnect -framework Accelerate -framework CoreData -framework CoreGraphics -framework CoreText -framework Foundation -framework QuartzCore -framework SystemConfiguration -framework UIKit -framework CoreTelephony -framework StoreKit  

Laravel Migration table already exists, but I want to add new not the older

I inherited some real bad code from someone who wasn't using migrations!?, so manually pasted the filenames into the migrations, forgetting to remove the trailing .php

So that caused the 'table exists' error despite the filename and migration matching.

2018_05_07_142737_create_users_table.php - WRONG 2018_05_07_142737_create_users_table - CORRECT

Make Bootstrap's Carousel both center AND responsive?

in bootstrap v4, i center and fill the carousel img to the screen using

<img class="d-block mx-auto" max-width="100%" max-height="100%">

pretty sure this requires parent elements' height or width to be set

html,body{height:100%;}
.carousel,.carousel-item,.active{height:100%;}
.carousel-inner{height:100%;}

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

put a int infront of the all the voxelCoord's...Like this below :

patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]

Checking if a collection is empty in Java: which is the best method?

If you have the Apache common utilities in your project rather use the first one. Because its shorter and does exactly the same as the latter one. There won't be any difference between both methods but how it looks inside the source code.

Also a empty check using

listName.size() != 0

Is discouraged because all collection implementations have the

listName.isEmpty()

function that does exactly the same.

So all in all, if you have the Apache common utils in your classpath anyway, use

if (CollectionUtils.isNotEmpty(listName)) 

in any other case use

if(listName != null && listName.isEmpty())

You will not notice any performance difference. Both lines do exactly the same.

database vs. flat files

This is an answer I've already given some time ago:

It depends entirely on the domain-specific application needs. A lot of times direct text file/binary files access can be extremely fast, efficient, as well as providing you all the file access capabilities of your OS's file system.

Furthermore, your programming language most likely already has a built-in module (or is easy to make one) for specific parsing.

If what you need is many appends (INSERTS?) and sequential/few access little/no concurrency, files are the way to go.

On the other hand, when your requirements for concurrency, non-sequential reading/writing, atomicity, atomic permissions, your data is relational by the nature etc., you will be better off with a relational or OO database.

There is a lot that can be accomplished with SQLite3, which is extremely light (under 300kb), ACID compliant, written in C/C++, and highly ubiquitous (if it isn't already included in your programming language -for example Python-, there is surely one available). It can be useful even on db files as big as 140 terabytes, or 128 tebibytes (Link to Database Size), possible more.

If your requirements where bigger, there wouldn't even be a discussion, go for a full-blown RDBMS.

As you say in a comment that "the system" is merely a bunch of scripts, then you should take a look at pgbash.

how to open Jupyter notebook in chrome on windows

Create and edit the jupyter notebook config file with the following steps:

  • Launch Anaconda Prompt
  • Type jupyter notebook --generate-config
  • Type notepad path_to_file/jupyter_notebook_config.py to open it (change path_to_file)
  • Modify #c.NotebookApp.browser = '' to c.NotebookApp.browser = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
  • Save the file and close it

Jupyter notebook will now use Chrome.

Make code in LaTeX look *nice*

For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.

How do I parse command line arguments in Java?

Someone pointed me to args4j lately which is annotation based. I really like it!

How to create JSON string in C#

If you need complex result (embedded) create your own structure:

class templateRequest
{
    public String[] registration_ids;
    public Data data;
    public class Data
    {
        public String message;
        public String tickerText;
        public String contentTitle;
        public Data(String message, String tickerText, string contentTitle)
        {
            this.message = message;
            this.tickerText = tickerText;
            this.contentTitle = contentTitle;
        }                
    };
}

and then you can obtain JSON string with calling

List<String> ids = new List<string>() { "id1", "id2" };
templateRequest request = new templeteRequest();
request.registration_ids = ids.ToArray();
request.data = new templateRequest.Data("Your message", "Your ticker", "Your content");

string json = new JavaScriptSerializer().Serialize(request);

The result will be like this:

json = "{\"registration_ids\":[\"id1\",\"id2\"],\"data\":{\"message\":\"Your message\",\"tickerText\":\"Your ticket\",\"contentTitle\":\"Your content\"}}"

Hope it helps!

What does HTTP/1.1 302 mean exactly?

  • The code 302 indicates a temporary redirection.
  • One of the most notable features that differentiate it from a 301 redirect is that, in the case of 302 redirects, the strength of the SEO is not transferred to a new URL.
  • This is because this redirection has been designed to be used when there is a need to redirect content to a page that will not be the definitive one. Thus, once the redirection is eliminated, the original page will not have lost its positioning in the Google search engine.

EXAMPLE:- Although it is not very common that we find ourselves in need of a 302 redirect, this option can be very useful in some cases. These are the most frequent cases:

  • When we realize that there is some inappropriate content on a page. While we solve the problem, we can redirect the user to another page that may be of interest.
  • In the event that an attack on our website requires the restoration of any of the pages, this redirect can help us minimize the incidence.

A redirect 302 is a code that tells visitors of a specific URL that the page has been moved temporarily, directing them directly to the new location.

  • In other words, redirect 302 is activated when Google robots or other search engines request to load a specific page. At that moment, thanks to this redirection, the server returns an automatic response indicating a new URL.

  • In this way errors and annoyances are avoided both to search engines and users, guaranteeing smooth navigation.

For More details Refer this Article.

Printing the correct number of decimal points with cout

With <iomanip>, you can use std::fixed and std::setprecision

Here is an example

#include <iostream>
#include <iomanip>

int main()
{
    double d = 122.345;

    std::cout << std::fixed;
    std::cout << std::setprecision(2);
    std::cout << d;
}

And you will get output

122.34

Is there an alternative to string.Replace that is case-insensitive?

Inspired by cfeduke's answer, I made this function which uses IndexOf to find the old value in the string and then replaces it with the new value. I used this in an SSIS script processing millions of rows, and the regex-method was way slower than this.

public static string ReplaceCaseInsensitive(this string str, string oldValue, string newValue)
{
    int prevPos = 0;
    string retval = str;
    // find the first occurence of oldValue
    int pos = retval.IndexOf(oldValue, StringComparison.InvariantCultureIgnoreCase);

    while (pos > -1)
    {
        // remove oldValue from the string
        retval = retval.Remove(pos, oldValue.Length);

        // insert newValue in it's place
        retval = retval.Insert(pos, newValue);

        // check if oldValue is found further down
        prevPos = pos + newValue.Length;
        pos = retval.IndexOf(oldValue, prevPos, StringComparison.InvariantCultureIgnoreCase);
    }

    return retval;
}

"Warning: iPhone apps should include an armv6 architecture" even with build config set

I had this problem even after following the accepted answer and found the following to work:

In your Info.plist, add an entry for Required Device Capabilities. This should be an array and will have two entries.

  • Item 0 : armv6
  • Item 1 : armv7

It will look like this:

Required device capabilities entry

What are the differences between Pandas and NumPy+SciPy in Python?

Pandas offer a great way to manipulate tables, as you can make binning easy (binning a dataframe in pandas in Python) and calculate statistics. Other thing that is great in pandas is the Panel class that you can join series of layers with different properties and combine it using groupby function.

How do you prevent install of "devDependencies" NPM modules for Node.js (package.json)?

The npm install command will install the devDependencies along other dependencies when run inside a package directory, in a development environment (the default).

Use npm install --only=prod (or --only=production) to install only dependencies, and not devDependencies,regardless of the value of the NODE_ENV environment variable.

Source: npm docs

Note: Before v3.3.0 of npm (2015-08-13), the option was called --production, i.e. npm install --production.

I get "Http failure response for (unknown url): 0 Unknown Error" instead of actual error message in Angular

In asp.net core, If your api controller doesn't have annotation called [AllowAnonymous], add it to above your controller name like

[ApiController]
    [Route("api/")]
    [AllowAnonymous]
    public class TestController : ControllerBase

Django Model() vs Model.objects.create()

UPDATE 15.3.2017:

I have opened a Django-issue on this and it seems to be preliminary accepted here: https://code.djangoproject.com/ticket/27825

My experience is that when using the Constructor (ORM) class by references with Django 1.10.5 there might be some inconsistencies in the data (i.e. the attributes of the created object may get the type of the input data instead of the casted type of the ORM object property) example:

models

class Payment(models.Model):
     amount_cash = models.DecimalField()

some_test.py - object.create

Class SomeTestCase:
    def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
        objs = []
        if not base_data:
            base_data = {'amount_case': 123.00}
        for modifier in modifiers:
            actual_data = deepcopy(base_data)
            actual_data.update(modifier)
            # Hacky fix,
            _obj = _constructor.objects.create(**actual_data)
            print(type(_obj.amount_cash)) # Decimal
            assert created
           objs.append(_obj)
        return objs

some_test.py - Constructor()

Class SomeTestCase:
    def generate_orm_obj(self, _constructor, base_data=None, modifiers=None):
        objs = []
        if not base_data:
            base_data = {'amount_case': 123.00}
        for modifier in modifiers:
            actual_data = deepcopy(base_data)
            actual_data.update(modifier)
            # Hacky fix,
            _obj = _constructor(**actual_data)
            print(type(_obj.amount_cash)) # Float
            assert created
           objs.append(_obj)
        return objs

Row count with PDO

Use parameter array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL), else show -1:

Usen parametro array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL), sin ello sale -1

example:

$res1 = $mdb2->prepare("SELECT clave FROM $tb WHERE id_usuario='$username' AND activo=1 and id_tipo_usuario='4'", array(PDO::ATTR_CURSOR => PDO::CURSOR_SCROLL));
$res1->execute();

$count=$res1->rowCount();
echo $count;

Extract time from date String

The other answers were good answers when the question was asked. Time moves on, Date and SimpleDateFormat get replaced by newer and better classes and go out of use. In 2017, use the classes in the java.time package:

    String timeString = LocalDateTime.parse(dateString, DateTimeFormatter.ofPattern("uuuu-MM-dd HH:mm:ss"))
            .format(DateTimeFormatter.ofPattern("H:mm"));

The result is the desired, 9:00.

How do I print the content of httprequest request?

In case someone also want to dump response like me. i avoided to dump response body. following code just dump the StatusCode and Headers.

static private String dumpResponse(HttpServletResponse resp){
    StringBuilder sb = new StringBuilder();

    sb.append("Response Status = [" + resp.getStatus() + "], ");
    String headers = resp.getHeaderNames().stream()
                    .map(headerName -> headerName + " : " + resp.getHeaders(headerName) )
                    .collect(Collectors.joining(", "));

    if (headers.isEmpty()) {
        sb.append("Response headers: NONE,");
    } else {
        sb.append("Response headers: "+headers+",");
    }

    return sb.toString();
}

Where is Developer Command Prompt for VS2013?

For some reason, it doesn't properly add an icon when running Windows 8+. Here's how I solved it:

Using Windows Explorer, navigate to:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Visual Studio 2013

In that folder, you'll see a shortcut named Visual Studio Tools that maps to (assuming default installation):

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\Shortcuts

Double-click the shortcut (or go to the folder above).

From that folder, copy the shortcut named Developer Command Prompt for VS2013 (and any others you find useful) to the first directory (for the Start Menu). You'll likely be prompted for administrative access (do so).

Once you've done that, you'll now have an icon available for the 2013 command prompt.

How do I configure modprobe to find my module?

You can make a symbolic link of your module to the standard path, so depmod will see it and you'll be able load it as any other module.

sudo ln -s /path/to/module.ko /lib/modules/`uname -r`
sudo depmod -a
sudo modprobe module

If you add the module name to /etc/modules it will be loaded any time you boot.

Anyway I think that the proper configuration is to copy the module to the standard paths.

What is the purpose of willSet and didSet in Swift?

My understanding is that set and get are for computed properties (no backing from stored properties)

if you are coming from an Objective-C bare in mind that the naming conventions have changed. In Swift an iVar or instance variable is named stored property

Example 1 (read only property) - with warning:

var test : Int {
    get {
        return test
    }
}

This will result in a warning because this results in a recursive function call (the getter calls itself).The warning in this case is "Attempting to modify 'test' within its own getter".

Example 2. Conditional read/write - with warning

var test : Int {
    get {
        return test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        //(prevents same value being set)
        if (aNewValue != test) {
            test = aNewValue
        }
    }
}

Similar problem - you cannot do this as it's recursively calling the setter. Also, note this code will not complain about no initialisers as there is no stored property to initialise.

Example 3. read/write computed property - with backing store

Here is a pattern that allows conditional setting of an actual stored property

//True model data
var _test : Int = 0

var test : Int {
    get {
        return _test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        if (aNewValue != test) {
            _test = aNewValue
        }
    }
}

Note The actual data is called _test (although it could be any data or combination of data) Note also the need to provide an initial value (alternatively you need to use an init method) because _test is actually an instance variable

Example 4. Using will and did set

//True model data
var _test : Int = 0 {

    //First this
    willSet {
        println("Old value is \(_test), new value is \(newValue)")
    }

    //value is set

    //Finaly this
    didSet {
        println("Old value is \(oldValue), new value is \(_test)")
    }
}

var test : Int {
    get {
        return _test
    }
    set (aNewValue) {
        //I've contrived some condition on which this property can be set
        if (aNewValue != test) {
            _test = aNewValue
        }
    }
}

Here we see willSet and didSet intercepting a change in an actual stored property. This is useful for sending notifications, synchronisation etc... (see example below)

Example 5. Concrete Example - ViewController Container

//Underlying instance variable (would ideally be private)
var _childVC : UIViewController? {
    willSet {
        //REMOVE OLD VC
        println("Property will set")
        if (_childVC != nil) {
            _childVC!.willMoveToParentViewController(nil)
            self.setOverrideTraitCollection(nil, forChildViewController: _childVC)
            _childVC!.view.removeFromSuperview()
            _childVC!.removeFromParentViewController()
        }
        if (newValue) {
            self.addChildViewController(newValue)
        }

    }

    //I can't see a way to 'stop' the value being set to the same controller - hence the computed property

    didSet {
        //ADD NEW VC
        println("Property did set")
        if (_childVC) {
//                var views  = NSDictionaryOfVariableBindings(self.view)    .. NOT YET SUPPORTED (NSDictionary bridging not yet available)

            //Add subviews + constraints
            _childVC!.view.setTranslatesAutoresizingMaskIntoConstraints(false)       //For now - until I add my own constraints
            self.view.addSubview(_childVC!.view)
            let views = ["view" : _childVC!.view] as NSMutableDictionary
            let layoutOpts = NSLayoutFormatOptions(0)
            let lc1 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("|[view]|",  options: layoutOpts, metrics: NSDictionary(), views: views)
            let lc2 : AnyObject[] = NSLayoutConstraint.constraintsWithVisualFormat("V:|[view]|", options: layoutOpts, metrics: NSDictionary(), views: views)
            self.view.addConstraints(lc1)
            self.view.addConstraints(lc2)

            //Forward messages to child
            _childVC!.didMoveToParentViewController(self)
        }
    }
}


//Computed property - this is the property that must be used to prevent setting the same value twice
//unless there is another way of doing this?
var childVC : UIViewController? {
    get {
        return _childVC
    }
    set(suggestedVC) {
        if (suggestedVC != _childVC) {
            _childVC = suggestedVC
        }
    }
}

Note the use of BOTH computed and stored properties. I've used a computed property to prevent setting the same value twice (to avoid bad things happening!); I've used willSet and didSet to forward notifications to viewControllers (see UIViewController documentation and info on viewController containers)

I hope this helps, and please someone shout if I've made a mistake anywhere here!

Set default format of datetimepicker as dd-MM-yyyy

You can set CustomFormat property to "dd-MM-yyyy" in design mode and use dateTimePicker1.Text property to fetch string in "dd/MM/yyyy" format irrespective of display format.

Android-Studio upgraded from 0.1.9 to 0.2.0 causing gradle build errors now

Gradle should be updated already, you just need to let your previous projects know gradle has been updated.

Source

Edit your build.gradle file to show this:

dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
}

This should only be required for projects created with the previous version of Android Studio. New projects you create will have that by default.

Check if textbox has empty value

$('input:text').filter(function() { return this.value.length > 0; });

Attribute Error: 'list' object has no attribute 'split'

The problem is that readlines is a list of strings, each of which is a line of filename. Perhaps you meant:

for line in readlines:
    Type = line.split(",")
    x = Type[1]
    y = Type[2]
    print(x,y)

How do you find out the type of an object (in Swift)?

Here is 2 ways I recommend doing it:

if let thisShape = aShape as? Square 

Or:

aShape.isKindOfClass(Square)

Here is a detailed example:

class Shape { }
class Square: Shape { } 
class Circle: Shape { }

var aShape = Shape()
aShape = Square()

if let thisShape = aShape as? Square {
    println("Its a square")
} else {
    println("Its not a square")
}

if aShape.isKindOfClass(Square) {
    println("Its a square")
} else {
    println("Its not a square")
}

How to select min and max values of a column in a datatable?

The most efficient way to do this (believe it or not) is to make two variables and write a for loop.

Properties file in python (similar to Java Properties)

create a dictionary in your python module and store everything into it and access it, for example:

dict = {
       'portalPath' : 'www.xyx.com',
       'elementID': 'submit'}

Now to access it you can simply do:

submitButton = driver.find_element_by_id(dict['elementID'])

C# Checking if button was clicked

button1, button2 and button3 have same even handler

private void button1_Click(Object sender, EventArgs e)
    {
        Button btnSender = (Button)sender;
        if (btnSender == button1 || btnSender == button2)
        {
            //some code here
        }
        else if (btnSender == button3)
            //some code here
    }

Visual Studio Code Search and Replace with Regular Expressions

If you want ex. change all country codes in .json file from uppercase to lowercase:

ctrl+h
alt+r
alt+c

Find: ([A-Z]{2,})
Replace: $1

alt+enter
F1
type: lower -> select toLoweCase
ctrl+alt+enter

ex file:

[
 {"id": "PL", "name": "Poland"},
 {"id": "NZ", "name": "New Zealand"},
 ...
]

Getting a File's MD5 Checksum in Java

I recently had to do this for just a dynamic string, MessageDigest can represent the hash in numerous ways. To get the signature of the file like you would get with the md5sum command I had to do something like the this:

try {
   String s = "TEST STRING";
   MessageDigest md5 = MessageDigest.getInstance("MD5");
   md5.update(s.getBytes(),0,s.length());
   String signature = new BigInteger(1,md5.digest()).toString(16);
   System.out.println("Signature: "+signature);

} catch (final NoSuchAlgorithmException e) {
   e.printStackTrace();
}

This obviously doesn't answer your question about how to do it specifically for a file, the above answer deals with that quiet nicely. I just spent a lot of time getting the sum to look like most application's display it, and thought you might run into the same trouble.

Get started with Latex on Linux

LaTeX comes with most Linux distributions in the form of the teTeX distribution. Find all packages with 'teTeX' in the name and install them.

  • Most editors such as vim or emacs come with TeX editing modes. You can also get WYSIWIG-ish front-ends (technically WYSIWYM), of which perhaps the best known is LyX.

  • The best quick intro to LaTeX is Oetiker's 'The not so short intro to LaTeX'

  • LaTeX works like a compiler. You compile the LaTeX document (which can include other files), which generates a file called a .dvi (device independent). This can be post-processed to various formats (including PDF) with various post-processors.

  • To do PDF, use dvips and use the flag -PPDF (IIRC - I don't have a makefile to hand) to produce a PS with font rendering set up for conversion to pdf. PDF conversion can then be done with ps2pdf or distiller (if you have this).

  • The best format for including graphics in this environment is eps (Encapsulated Postscript) although not all software produces well-behaved postscript. Photographs in jpeg or other formats can be included using various mechanisms.

Python Error: unsupported operand type(s) for +: 'int' and 'NoneType'

When none of the if test in number_translator() evaluate to true, the function returns None. The error message is the consequence of that.

Whenever you see an error that include 'NoneType' that means that you have an operand or an object that is None when you were expecting something else.

What is the easiest way to initialize a std::vector with hardcoded elements?

Starting with:

int a[] = {10, 20, 30}; //i'm assuming a is just a placeholder

If you don't have a C++11 compiler and you don't want to use boost:

const int a[] = {10, 20, 30};
const std::vector<int> ints(a,a+sizeof(a)/sizeof(int)); //make it const if you can

If you don't have a C++11 compiler and can use boost:

#include <boost/assign.hpp>
const std::vector<int> ints = boost::assign::list_of(10)(20)(30);

If you do have a C++11 compiler:

const std::vector<int> ints = {10,20,30};

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

Do you use the ob_start(ob_gzhandler) function? If so and If you output any content above the ob_start(ob_gzhandler) function, you'll get this error. You can don't use this function or don't output content above this function. The ob_gzhandler callback function will determine what type of content encoding the browser will accept and will return its output accordingly. So if you output content above this function, the content's encoding maybe different from the output content of ob_gzhandler and that cause this error.

Adding Google Translate to a web site

function googleTranslateElementInit() {
  new google.translate.TranslateElement(
    {pageLanguage: 'en'},
    'google_translate_element'
  );
}

Debugging Spring configuration

If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.

java -jar myapp.jar --debug

You can also specify debug=true in your application.properties.

When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.

Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html

vbscript output to console

This was found on Dragon-IT Scripts and Code Repository.

You can do this with the following and stay away from the cscript/wscript differences and allows you to get the same console output that a batch file would have. This can help if your calling VBS from a batch file and need to make it look seamless.

Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
Set stderr = fso.GetStandardStream (2)
stdout.WriteLine "This will go to standard output."
stderr.WriteLine "This will go to error output."

How can I display a tooltip message on hover using jQuery?

As recommended qTip and other projects are quite old I recommend using qTip2 as it is most up-to-date.

Connection string with relative path to the database file

I had the same issue trying to specify the relative file path for a database connected to a Windows Forms application. I was able to resolve the issue by following the directions for adding a data source to Windows Forms from Microsoft (e.g., for connecting an Access database).

By using this method, Visual Studio will set the relative file paths to your database for you instead of trying to set it manually. If your database is external to your application, it will create a copy of the database and add it to your application in the proper location. Although you can manually alter you connection string in App.config and/or Settings.settings or within one of your scripts, I've found this method to be error prone. Instead, I've found it best to follow the Microsoft instructions, in general.

LINQ: "contains" and a Lambda query

Use Any() instead of Contains():

buildingStatus.Any(item => item.GetCharValue() == v.Status)

Internet Explorer 11 detection

All of the above answers ignore the fact that you mention you have no window or navigator :-)

Then I openede developer console in IE11

and thats where it says

Object not found and needs to be re-evaluated.

and navigator, window, console, none of them exist and need to be re-evaluated. I've had that in emulation. just close and open the console a few times.

PHP display current server path

php can call command line operations so

echo exec("pwd");

no pg_hba.conf entry for host

To resolved this problem, you can try this.

first you have find out your pg_hba.conf and write :

local all all md5

after that restart pg server:

postgresql restart

or

sudo /etc/init.d/postgresql restart

Where does Chrome store extensions?

Since chrome has come up with the multiple profiles you will not get it directly in C:\Users\<Your_User_Name>\AppData\Local\Google\Chrome\User Data\Default\Extensions but you have to first type chrome://version/ in a tab and then look out for Profile path inside that and after you reach to your profile path look for Extensions folder in it and then folder with the desired extension Id

Predicate Delegates in C#

What is Predicate Delegate?

1) Predicate is a feature that returns true or false.This concept has come in .net 2.0 framework. 2) It is being used with lambda expression (=>). It takes generic type as an argument. 3) It allows a predicate function to be defined and passed as a parameter to another function. 4) It is a special case of a Func, in that it takes only a single parameter and always returns a bool.

In C# namespace:

namespace System
{   
    public delegate bool Predicate<in T>(T obj);
}

It is defined in the System namespace.

Where should we use Predicate Delegate?

We should use Predicate Delegate in the following cases:

1) For searching items in a generic collection. e.g.

var employeeDetails = employees.Where(o=>o.employeeId == 1237).FirstOrDefault();

2) Basic example that shortens the code and returns true or false:

Predicate<int> isValueOne = x => x == 1;

now, Call above predicate:

Console.WriteLine(isValueOne.Invoke(1)); // -- returns true.

3) An anonymous method can also be assigned to a Predicate delegate type as below:

Predicate<string> isUpper = delegate(string s) { return s.Equals(s.ToUpper());};
    bool result = isUpper("Hello Chap!!");

Any best practices about predicates?

Use Func, Lambda Expressions and Delegates instead of Predicates.

Why are elementwise additions much faster in separate loops than in a combined loop?

It's not because of a different code, but because of caching: RAM is slower than the CPU registers and a cache memory is inside the CPU to avoid to write the RAM every time a variable is changing. But the cache is not big as the RAM is, hence, it maps only a fraction of it.

The first code modifies distant memory addresses alternating them at each loop, thus requiring continuously to invalidate the cache.

The second code don't alternate: it just flow on adjacent addresses twice. This makes all the job to be completed in the cache, invalidating it only after the second loop starts.

XAMPP keeps showing Dashboard/Welcome Page instead of the Configuration Page

my suggestion: Choose a different version. I had the same problem you have deinstalled v5.6.11, downloaded and installed v5.6.3, works fine for me.

cheers!

Angularjs loading screen on ajax request

Also, there is a nice demo that shows how can you use Angularjs animation in your project.

The link is here (See the top left corner).

It's an open source. Here is the link to download

And here is the link for tutorial;

My point is, go ahead and download the source files and then see how they have implemented the spinner. They might have used a little better aproach. So, checkout this project.

ADB No Devices Found

Use another cable.

Just found out that one of my regular charging cables had Vcc, Gnd pairs, but no Data+, Data-.

https://en.wikipedia.org/wiki/USB#Pinouts

Bootstrap modal: close current, open new

Just copy and paste this code and you can experiment with two modals. Second modal is open after closing the first one:

<!-- Button to Open the Modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
    Open modal
</button>

<!-- The Modal -->
<div class="modal" id="myModal">
    <div class="modal-dialog">
        <div class="modal-content">

            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Modal Heading</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- Modal body -->
            <div class="modal-body">
                Modal body..
            </div>

            <!-- Modal footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>

        </div>
    </div>
</div>



<!-- The Modal 2 -->
<div class="modal" id="myModal2">
    <div class="modal-dialog">
        <div class="modal-content">

            <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Second modal</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <!-- Modal body -->
            <div class="modal-body">
                Modal body..
            </div>

            <!-- Modal footer -->
            <div class="modal-footer">
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>

        </div>
    </div>
</div>




<script>
    $('#myModal').on('hidden.bs.modal', function () {
        $('#myModal2').modal('show')
    })
</script>

Cheers!

Where to change default pdf page width and font size in jspdf.debug.js?

From the documentation page

To set the page type pass the value in constructor

jsPDF(orientation, unit, format) Creates new jsPDF document object

instance Parameters:

orientation One of "portrait" or "landscape" (or shortcuts "p" (Default), "l")

unit Measurement unit to be used when coordinates are specified. One of "pt" (points), "mm" (Default), "cm", "in"

format One of 'a3', 'a4' (Default),'a5' ,'letter' ,'legal'

To set font size

setFontSize(size)

Sets font size for upcoming text elements.

Parameters:

{Number} size Font size in points.

How to fix Git error: object file is empty?

Here is a way to solve the problem if your public repo on github.com is working, but your local repo is corrupt. Be aware that you will loose all the commits you've done in the local repo.

Alright, so I have one repo locally that is giving me this object empty error, and the same repo on github.com, but without this error. So what I simply did was to clone the repo that is working from github, and then copied everything from the corrupt repo (except the .git folder), and paste it the cloned repo that is working.

This may not be a practical solution (since you delete the local commits), however, you maintain the code and a repaired version control.

Remember to back-up before applying this approach.

java.lang.IllegalArgumentException: View not attached to window manager

The activity is declared NOT be recreated by rotation or keyboard slide.

Just got the same problem. Fix for API level 13 or higer.
From Android docs:

Note: If your application targets API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), then you should also declare the "screenSize" configuration, because it also changes when a device switches between portrait and landscape orientations.

So i've changed my manifest to this:

<activity
        android:name="MyActivity"
        android:configChanges="orientation|screenSize"
        android:label="MyActivityName" >
</activity>

And now it works fine. Activity is not recreating when i rotate the phone, progress dialog and view stay the same. No error for me.

Remove all whitespace in a string

' hello  \n\tapple'.translate({ord(c):None for c in ' \n\t\r'})

MaK already pointed out the "translate" method above. And this variation works with Python 3 (see this Q&A).

jQuery remove special characters from string and more

Since I can't comment on Jasper's answer, I'd like to point out a small bug in his solution:

str.replace(/[^a-z0-9\s]/gi, '').replace(/[_\s]/g, '-');

The problem is that first code removes all the hyphens and then tries to replace them :) You should reverse the replace calls and also add hyphen to second replace regex. Like this:

str.replace(/[_\s]/g, '-').replace(/[^a-z0-9-\s]/gi, '');

When should I use "this" in a class?

when there are two variables one instance variable and other local variable of the same name then we use this. to refer current executing object to avoid the conflict between the names.

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

configure Git to accept a particular self-signed server certificate for a particular https remote

On windows in a corporate environment where certificates are distributed from a single source, I found this answer solved the issue: https://stackoverflow.com/a/48212753/761755

Change color when hover a font awesome icon?

if you want to change only the colour of the flag on hover use this:

http://jsfiddle.net/uvamhedx/

_x000D_
_x000D_
.fa-flag:hover {_x000D_
    color: red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<i class="fa fa-flag fa-3x"></i>
_x000D_
_x000D_
_x000D_

How do I set up a simple delegate to communicate between two view controllers?

This below code just show the very basic use of delegate concept .. you name the variable and class as per your requirement.

First you need to declare a protocol:

Let's call it MyFirstControllerDelegate.h

@protocol MyFirstControllerDelegate
- (void) FunctionOne: (MyDataOne*) dataOne;
- (void) FunctionTwo: (MyDatatwo*) dataTwo;
@end

Import MyFirstControllerDelegate.h file and confirm your FirstController with protocol MyFirstControllerDelegate

#import "MyFirstControllerDelegate.h"

@interface FirstController : UIViewController<MyFirstControllerDelegate>
{

}

@end

In the implementation file, you need to implement both functions of protocol:

@implementation FirstController 


    - (void) FunctionOne: (MyDataOne*) dataOne
      {
          //Put your finction code here
      }
    - (void) FunctionTwo: (MyDatatwo*) dataTwo
      {
          //Put your finction code here
      }

     //Call below function from your code
    -(void) CreateSecondController
     {
             SecondController *mySecondController = [SecondController alloc] initWithSomeData:.];
           //..... push second controller into navigation stack 
            mySecondController.delegate = self ;
            [mySecondController release];
     }

@end

in your SecondController:

@interface SecondController:<UIViewController>
{
   id <MyFirstControllerDelegate> delegate;
}

@property (nonatomic,assign)  id <MyFirstControllerDelegate> delegate;

@end

In the implementation file of SecondController.

@implementation SecondController

@synthesize delegate;
//Call below two function on self.
-(void) SendOneDataToFirstController
{
   [delegate FunctionOne:myDataOne];
}
-(void) SendSecondDataToFirstController
{
   [delegate FunctionTwo:myDataSecond];
}

@end

Here is the wiki article on delegate.

Is there a link to the "latest" jQuery library on Google APIs?

jQuery also doesn't allow you to call their latest file over SSL, a consideration if you want to use jQuery in a shopping cart etc.

e.g.

<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>

will give you a security error.

Google's API will let you call over SSL:

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
  google.load("jquery", "1.7");
</script>

Remove '\' char from string c#

You could use:

line.Replace(@"\", "");

or

line.Replace(@"\", string.Empty);

How to change Format of a Cell to Text using VBA

Well this should change your format to text.

Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"

How to change FontSize By JavaScript?

span.style.fontSize = "25px";

use this

Setting a JPA timestamp column to be generated by the database?

If you are doing development in Java 8 and Hibernate 5 Or Spring Boot JPA then use following annotation directly in your Entity class. Hibernate gets the current timestamp from the VM and will insert date and time in database.

public class YourEntity {
 
    @Id
    @GeneratedValue
    private Long id;
 
    private String name;
 
    @CreationTimestamp
    private LocalDateTime createdDateTime;
 
    @UpdateTimestamp
    private LocalDateTime updatedDateTime;
 
    …
}

How can I debug a HTTP POST in Chrome?

The other people made very nice answers, but I would like to complete their work with an extra development tool. It is called Live HTTP Headers and you can install it into your Firefox, and in Chrome we have the same plug in like this.

Working with it is queit easy.

  1. Using your Firefox, navigate to the website which you want to get your post request to it.

  2. In your Firefox menu Tools->Live Http Headers

  3. A new window pop ups for you, and all the http method details would be saved in this window for you. You don't need to do anything in this step.

  4. In the website, do an activity(log in, submit a form, etc.)

  5. Look at your plug in window. It is all recorded.

Just remember you need to check the Capture.

enter image description here

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

Following the unobtrusive principle, it's not quite required for "_myPartial" to inject content directly into scripts section. You could add those partial view scripts into separate .js file and reference them into @scripts section from parent view.

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

Please try with the below code snippet.

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.common.min.css" rel="stylesheet" />
    <link href="http://cdn.kendostatic.com/2014.1.318/styles/kendo.default.min.css" rel="stylesheet" />
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script src="http://cdn.kendostatic.com/2014.1.318/js/kendo.all.min.js"></script>
    <script>
        function onDataBound(e) {
            var grid = $("#grid").data("kendoGrid");
            $(grid.tbody).find('tr').removeClass('k-alt');
        }

        $(document).ready(function () {
            $("#grid").kendoGrid({
                dataSource: {
                    type: "odata",
                    transport: {
                        read: "http://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
                    },
                    schema: {
                        model: {
                            fields: {
                                OrderID: { type: "number" },
                                Freight: { type: "number" },
                                ShipName: { type: "string" },
                                OrderDate: { type: "date" },
                                ShipCity: { type: "string" }
                            }
                        }
                    },
                    pageSize: 20,
                    serverPaging: true,
                    serverFiltering: true,
                    serverSorting: true
                },
                height: 430,
                filterable: true,
                dataBound: onDataBound,
                sortable: true,
                pageable: true,
                columns: [{
                    field: "OrderID",
                    filterable: false
                },
                            "Freight",
                            {
                                field: "OrderDate",
                                title: "Order Date",
                                width: 120,
                                format: "{0:MM/dd/yyyy}"
                            }, {
                                field: "ShipName",
                                title: "Ship Name",
                                width: 260
                            }, {
                                field: "ShipCity",
                                title: "Ship City",
                                width: 150
                            }
                        ]
            });
        });
    </script>
</head>
<body>
    <div id="grid">
    </div>
</body>
</html>

I have implemented same thing with different way.

Set max-height on inner div so scroll bars appear, but not on parent div

It might be easier to use JavaScript or jquery for this. Assuming that the height of the header and the footer is 200 then the code will be:

function SetHeight(){
    var h = $(window).height();
    $("#inner-right").height(h-200);    
}

$(document).ready(SetHeight);
$(window).resize(SetHeight);

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

You have to add THEN

IF EXISTS(SELECT * FROM component_psar WHERE tbl_id = '2' AND row_nr = '1') 
THEN
UPDATE component_psar SET col_1 = '1', col_2 = '1', col_3 = '1', col_4 = '1', col_5 = '1', col_6 = '1', unit = '1', add_info = '1', fsar_lock = '1' WHERE tbl_id = '2' AND row_nr = '1' 
ELSE 
INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock) VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')

VBA Excel 2-Dimensional Arrays

Here's A generic VBA Array To Range function that writes an array to the sheet in a single 'hit' to the sheet. This is much faster than writing the data into the sheet one cell at a time in loops for the rows and columns... However, there's some housekeeping to do, as you must specify the size of the target range correctly.

This 'housekeeping' looks like a lot of work and it's probably rather slow: but this is 'last mile' code to write to the sheet, and everything is faster than writing to the worksheet. Or at least, so much faster that it's effectively instantaneous, compared with a read or write to the worksheet, even in VBA, and you should do everything you possibly can in code before you hit the sheet.

A major component of this is error-trapping that I used to see turning up everywhere . I hate repetitive coding: I've coded it all here, and - hopefully - you'll never have to write it again.

A VBA 'Array to Range' function

Public Sub ArrayToRange(rngTarget As Excel.Range, InputArray As Variant)
' Write an array to an Excel range in a single 'hit' to the sheet
' InputArray must be a 2-Dimensional structure of the form Variant(Rows, Columns)

' The target range is resized automatically to the dimensions of the array, with
' the top left cell used as the start point.

' This subroutine saves repetitive coding for a common VBA and Excel task.

' If you think you won't need the code that works around common errors (long strings
' and objects in the array, etc) then feel free to comment them out.

On Error Resume Next

'
' Author: Nigel Heffernan
' HTTP://Excellerando.blogspot.com
'
' This code is in te public domain: take care to mark it clearly, and segregate
' it from proprietary code if you intend to assert intellectual property rights
' or impose commercial confidentiality restrictions on that proprietary code

Dim rngOutput As Excel.Range

Dim iRowCount   As Long
Dim iColCount   As Long
Dim iRow        As Long
Dim iCol        As Long
Dim arrTemp     As Variant
Dim iDimensions As Integer

Dim iRowOffset  As Long
Dim iColOffset  As Long
Dim iStart      As Long


Application.EnableEvents = False
If rngTarget.Cells.Count > 1 Then
    rngTarget.ClearContents
End If
Application.EnableEvents = True

If IsEmpty(InputArray) Then
    Exit Sub
End If


If TypeName(InputArray) = "Range" Then
    InputArray = InputArray.Value
End If

' Is it actually an array? IsArray is sadly broken so...
If Not InStr(TypeName(InputArray), "(") Then
    rngTarget.Cells(1, 1).Value2 = InputArray
    Exit Sub
End If


iDimensions = ArrayDimensions(InputArray)

If iDimensions < 1 Then

    rngTarget.Value = CStr(InputArray)

ElseIf iDimensions = 1 Then

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iStart = LBound(InputArray)
    iColCount = 1

    If iRowCount > (655354 - rngTarget.Row) Then
        iRowCount = 655354 + iStart - rngTarget.Row
        ReDim Preserve InputArray(iStart To iRowCount)
    End If

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iColCount = 1

    ' It's a vector. Yes, I asked for a 2-Dimensional array. But I'm feeling generous.
    ' By convention, a vector is presented in Excel as an arry of 1 to n rows and 1 column.
    ReDim arrTemp(LBound(InputArray, 1) To UBound(InputArray, 1), 1 To 1)
    For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
        arrTemp(iRow, 1) = InputArray(iRow)
    Next

    With rngTarget.Worksheet
        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount))
        rngOutput.Value2 = arrTemp
        Set rngTarget = rngOutput
    End With

    Erase arrTemp

ElseIf iDimensions = 2 Then

    iRowCount = UBound(InputArray, 1) - LBound(InputArray, 1)
    iColCount = UBound(InputArray, 2) - LBound(InputArray, 2)

    iStart = LBound(InputArray, 1)

    If iRowCount > (65534 - rngTarget.Row) Then
        iRowCount = 65534 - rngTarget.Row
        InputArray = ArrayTranspose(InputArray)
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iRowCount)
        InputArray = ArrayTranspose(InputArray)
    End If


    iStart = LBound(InputArray, 2)
    If iColCount > (254 - rngTarget.Column) Then
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iColCount)
    End If



    With rngTarget.Worksheet

        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount + 1))

        Err.Clear
        Application.EnableEvents = False
        rngOutput.Value2 = InputArray
        Application.EnableEvents = True

        If Err.Number <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        InputArray(iRow, iCol) = Trim(InputArray(iRow, iCol))
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Formula = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        If Left(InputArray(iRow, iCol), 1) = "=" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "+" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "*" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Value2 = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)

                    If IsObject(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = "[OBJECT] " & TypeName(InputArray(iRow, iCol))
                    ElseIf IsArray(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = Split(InputArray(iRow, iCol), ",")
                    ElseIf IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        If Len(InputArray(iRow, iCol)) > 255 Then
                            ' Block-write operations fail on strings exceeding 255 chars. You *have*
                            ' to go back and check, and write this masterpiece one cell at a time...
                            InputArray(iRow, iCol) = Left(Trim(InputArray(iRow, iCol)), 255)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Text = InputArray
        End If 'err<>0

        If Err <> 0 Then
            Application.ScreenUpdating = False
            Application.Calculation = xlCalculationManual
            iRowOffset = LBound(InputArray, 1) - 1
            iColOffset = LBound(InputArray, 2) - 1
            For iRow = 1 To iRowCount
                If iRow Mod 100 = 0 Then
                    Application.StatusBar = "Filling range... " & CInt(100# * iRow / iRowCount) & "%"
                End If
                For iCol = 1 To iColCount
                    rngOutput.Cells(iRow, iCol) = InputArray(iRow + iRowOffset, iCol + iColOffset)
                Next iCol
            Next iRow
            Application.StatusBar = False
            Application.ScreenUpdating = True


        End If 'err<>0


        Set rngTarget = rngOutput   ' resizes the range This is useful, *most* of the time

    End With

End If

End Sub

You will need the source for ArrayDimensions:

This API declaration is required in the module header:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
                   (Destination As Any, _
                    Source As Any, _
                    ByVal Length As Long)

...And here's the function itself:

Private Function ArrayDimensions(arr As Variant) As Integer
  '-----------------------------------------------------------------
  ' will return:
  ' -1 if not an array
  ' 0  if an un-dimmed array
  ' 1  or more indicating the number of dimensions of a dimmed array
  '-----------------------------------------------------------------


  ' Retrieved from Chris Rae's VBA Code Archive - http://chrisrae.com/vba
  ' Code written by Chris Rae, 25/5/00

  ' Originally published by R. B. Smissaert.
  ' Additional credits to Bob Phillips, Rick Rothstein, and Thomas Eyde on VB2TheMax

  Dim ptr As Long
  Dim vType As Integer

  Const VT_BYREF = &H4000&

  'get the real VarType of the argument
  'this is similar to VarType(), but returns also the VT_BYREF bit
  CopyMemory vType, arr, 2

  'exit if not an array
  If (vType And vbArray) = 0 Then
    ArrayDimensions = -1
    Exit Function
  End If

  'get the address of the SAFEARRAY descriptor
  'this is stored in the second half of the
  'Variant parameter that has received the array
  CopyMemory ptr, ByVal VarPtr(arr) + 8, 4

  'see whether the routine was passed a Variant
  'that contains an array, rather than directly an array
  'in the former case ptr already points to the SA structure.
  'Thanks to Monte Hansen for this fix

  If (vType And VT_BYREF) Then
    ' ptr is a pointer to a pointer
    CopyMemory ptr, ByVal ptr, 4
  End If

  'get the address of the SAFEARRAY structure
  'this is stored in the descriptor

  'get the first word of the SAFEARRAY structure
  'which holds the number of dimensions
  '...but first check that saAddr is non-zero, otherwise
  'this routine bombs when the array is uninitialized

  If ptr Then
    CopyMemory ArrayDimensions, ByVal ptr, 2
  End If

End Function

Also: I would advise you to keep that declaration private. If you must make it a public Sub in another module, insert the Option Private Module statement in the module header. You really don't want your users calling any function with CopyMemoryoperations and pointer arithmetic.

'module' has no attribute 'urlencode'

You use the Python 2 docs but write your program in Python 3.

How to make sure docker's time syncs with that of the host?

If you are using boot2docker and ntp doesn't work inside the docker VM (you are behind a proxy which does not forward ntp packets) but your host is time-synced, you can run the following from your host:

docker-machine ssh default "sudo date -u $(date -u +%m%d%H%M%Y)"

This way you are sending your machine's current time (in UTC timezone) as a string to set the docker VM time using date (again in UTC timezone).

NOTE: in Windows, inside a bash shell (from the msys git), use:

docker-machine.exe ssh default "sudo date -u $(date -u +%m%d%H%M%Y)"

Get integer value from string in swift

In Swift 3.0

Type 1: Convert NSString to String

    let stringNumb:NSString = "1357"
    let someNumb = Int(stringNumb as String) // 1357 as integer

Type 2: If the String has Integer only

    let stringNumb = "1357"
    let someNumb = Int(stringNumb) // 1357 as integer

Type 3: If the String has Float value

    let stringNumb = "13.57"
    if let stringToFloat = Float(stringNumb){
        let someNumb = Int(stringToFloat)// 13 as Integer
    }else{
       //do something if the stringNumb not have digit only. (i.e.,) let stringNumb = "13er4"
    }

View JSON file in Browser

Well I was searching view json file in WebBrowser in my Desktop app, when I try in IE still same problem IE was also prompt to download the file. Luckily after too much search I find the solution for it.

You need to : Open Notepad and paste the following:

    [HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
    "CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
    "Encoding"=hex:08,00,00,00
    
Save document as Json.reg and then right click on file and run as administrator.

After this You can view json file in IE and you Desktop WebBrowser enjoy :)

Css height in percent not working

height: 100% works if you give a fixed size to the parent element.

Insert line break in wrapped cell via code

Just do Ctrl + Enter inside the text box

Decreasing for loops in Python impossible?

0 is conditional value when this condition is true, loop will keep executing.10 is the initial value. 1 is the modifier where may be simple decrement.

for number in reversed(range(0,10,1)):
print number;

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

Understanding REST: Verbs, error codes, and authentication

About REST return codes: it is wrong to mix HTTP protocol codes and REST results.

However, I saw many implementations mixing them, and many developers may not agree with me.

HTTP return codes are related to the HTTP Request itself. A REST call is done using a Hypertext Transfer Protocol request and it works at a lower level than invoked REST method itself. REST is a concept/approach, and its output is a business/logical result, while HTTP result code is a transport one.

For example, returning "404 Not found" when you call /users/ is confuse, because it may mean:

  • URI is wrong (HTTP)
  • No users are found (REST)

"403 Forbidden/Access Denied" may mean:

  • Special permission needed. Browsers can handle it by asking the user/password. (HTTP)
  • Wrong access permissions configured on the server. (HTTP)
  • You need to be authenticated (REST)

And the list may continue with '500 Server error" (an Apache/Nginx HTTP thrown error or a business constraint error in REST) or other HTTP errors etc...

From the code, it's hard to understand what was the failure reason, a HTTP (transport) failure or a REST (logical) failure.

If the HTTP request physically was performed successfully it should always return 200 code, regardless is the record(s) found or not. Because URI resource is found and was handled by the http server. Yes, it may return an empty set. Is it possible to receive an empty web-page with 200 as http result, right?

Instead of this you may return 200 HTTP code and simply a JSON with an empty array/object, or to use a bool result/success flag to inform about the performed operation status.

Also, some internet providers may intercept your requests and return you a 404 http code. This does not means that your data are not found, but it's something wrong at transport level.

From Wiki:

In July 2004, the UK telecom provider BT Group deployed the Cleanfeed content blocking system, which returns a 404 error to any request for content identified as potentially illegal by the Internet Watch Foundation. Other ISPs return a HTTP 403 "forbidden" error in the same circumstances. The practice of employing fake 404 errors as a means to conceal censorship has also been reported in Thailand and Tunisia. In Tunisia, where censorship was severe before the 2011 revolution, people became aware of the nature of the fake 404 errors and created an imaginary character named "Ammar 404" who represents "the invisible censor".

How to replace spaces in file names using a bash script

I found around this script, it may be interesting :)

 IFS=$'\n';for f in `find .`; do file=$(echo $f | tr [:blank:] '_'); [ -e $f ] && [ ! -e $file ] && mv "$f" $file;done;unset IFS

Case-insensitive search in Rails model

You'll probably have to be more verbose here

name = "Blue Jeans"
model = Product.where('lower(name) = ?', name.downcase).first 
model ||= Product.create(:name => name)

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

JavaScript/jQuery - "$ is not defined- $function()" error

You must not have made jQuery available to your script.

Add this to the top of your file:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

This issue is related to the jQuery/JavaScript file not added to the PHP/JSP/ASP file properly. This goes out and gets the jQuery code from the source. You could download that and reference it locally on the server which would be faster.

Or either one can directly link it to jQuery or GoogleCDN or MicrosoftCDN.

How do add jQuery to your webpage

php create object without class

you can always use new stdClass(). Example code:

   $object = new stdClass();
   $object->property = 'Here we go';

   var_dump($object);
   /*
   outputs:

   object(stdClass)#2 (1) {
      ["property"]=>
      string(10) "Here we go"
    }
   */

Also as of PHP 5.4 you can get same output with:

$object = (object) ['property' => 'Here we go'];

How to list all installed packages and their versions in Python?

To run this in later versions of pip (tested on pip==10.0.1) use the following:

from pip._internal.operations.freeze import freeze
for requirement in freeze(local_only=True):
    print(requirement)

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

I tried running on Windows, and got this problem after an update. I tried restarting the docker service as well as my pc, but nothing worked.

When running:

curl https://registry-1.docker.io/v2/ && echo Works

I got back:

{"errors":[{"code":"UNAUTHORIZED","message":"authentication required","detail":null}]}
Works

Eventually, I tried: https://github.com/moby/moby/issues/22635#issuecomment-284956961

By changing the fixed address to 8.8.8.8: enter image description here

Which worked for me! I still got the unauthorized message for curl https://registry-1.docker.io/v2/ but I managed to pull images from docker hub.

What is the apply function in Scala?

It comes from the idea that you often want to apply something to an object. The more accurate example is the one of factories. When you have a factory, you want to apply parameter to it to create an object.

Scala guys thought that, as it occurs in many situation, it could be nice to have a shortcut to call apply. Thus when you give parameters directly to an object, it's desugared as if you pass these parameters to the apply function of that object:

class MyAdder(x: Int) {
  def apply(y: Int) = x + y
}

val adder = new MyAdder(2)
val result = adder(4) // equivalent to x.apply(4)

It's often use in companion object, to provide a nice factory method for a class or a trait, here is an example:

trait A {
  val x: Int
  def myComplexStrategy: Int
}

object A {
  def apply(x: Int): A = new MyA(x)

  private class MyA(val x: Int) extends A {
    val myComplexStrategy = 42
  }
}

From the scala standard library, you might look at how scala.collection.Seq is implemented: Seq is a trait, thus new Seq(1, 2) won't compile but thanks to companion object and apply, you can call Seq(1, 2) and the implementation is chosen by the companion object.