Programs & Examples On #Mod auth passthrough

CodeIgniter: Create new helper?

Some code that allows you to use CI instance inside the helper:

function yourHelperFunction(){
    $ci=& get_instance();
    $ci->load->database(); 

    $sql = "select * from table"; 
    $query = $ci->db->query($sql);
    $row = $query->result();
}

Can I call an overloaded constructor from another constructor of the same class in C#?

In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().

When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that

Force table column widths to always be fixed regardless of contents

Try looking into the following CSS:

word-wrap:break-word;

Web browsers should not break-up "words" by default so what you are experiencing is normal behaviour of a browser. However you can override this with the word-wrap CSS directive.

You would need to set a width on the overall table then a width on the columns. "width:100%;" should also be OK depending on your requirements.

Using word-wrap may not be what you want however it is useful for showing all of the data without deforming the layout.

How to detect DIV's dimension changed?

I found this library to work when MarcJ's solution didn't:

https://github.com/sdecima/javascript-detect-element-resize

It's very lightweight and detects even natural resizes via CSS or simply the HTML loading/rendering.

Code sample (taken from the link):

<script type="text/javascript" src="detect-element-resize.js"></script>
<script type="text/javascript">
  var resizeElement = document.getElementById('resizeElement'),
      resizeCallback = function() {
          /* do something */
      };
  addResizeListener(resizeElement, resizeCallback);
  removeResizeListener(resizeElement, resizeCallback);
</script>

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

I found that I could access the checkbox directly using Worksheets("SheetName").CB_Checkboxname.value directly without relating to additional objects.

JUNIT Test class in Eclipse - java.lang.ClassNotFoundException

A variation on Guy's answer above, involving additional builders. Say you have an Ant builder configured:

<buildSpec>
    <buildCommand>
        <name>org.eclipse.jdt.core.javabuilder</name>
        <arguments>
        </arguments>
    </buildCommand>
    <buildCommand>
        <name>org.eclipse.ui.externaltools.ExternalToolBuilder</name>
        <arguments>
            <dictionary>
                <key>LaunchConfigHandle</key>
                <value>&lt;project&gt;/.externalToolBuilders/myprojectantlaunch.launch</value>
            </dictionary>
        </arguments>
    </buildCommand>
</buildSpec>

If the Ant build and Eclipse build have differing output locations, Eclipse may not be able to locate the test class on the classpath. In the case of an Ant builder, also check the configured targets for clean, auto, manual and after-clean builds, to ensure that the target which builds the unit tests is called.

How to automatically generate a stacktrace when my program crashes

In addition to above answers, here how you make Debian Linux OS generate core dump

  1. Create a “coredumps” folder in the user's home folder
  2. Go to /etc/security/limits.conf. Below the ' ' line, type “ soft core unlimited”, and “root soft core unlimited” if enabling core dumps for root, to allow unlimited space for core dumps.
  3. NOTE: “* soft core unlimited” does not cover root, which is why root has to be specified in its own line.
  4. To check these values, log out, log back in, and type “ulimit -a”. “Core file size” should be set to unlimited.
  5. Check the .bashrc files (user, and root if applicable) to make sure that ulimit is not set there. Otherwise, the value above will be overwritten on startup.
  6. Open /etc/sysctl.conf. Enter the following at the bottom: “kernel.core_pattern = /home//coredumps/%e_%t.dump”. (%e will be the process name, and %t will be the system time)
  7. Exit and type “sysctl -p” to load the new configuration Check /proc/sys/kernel/core_pattern and verify that this matches what you just typed in.
  8. Core dumping can be tested by running a process on the command line (“ &”), and then killing it with “kill -11 ”. If core dumping is successful, you will see “(core dumped)” after the segmentation fault indication.

Ways to implement data versioning in MongoDB

There is a versioning scheme called "Vermongo" which addresses some aspects which haven't been dealt with in the other replies.

One of these issues is concurrent updates, another one is deleting documents.

Vermongo stores complete document copies in a shadow collection. For some use cases this might cause too much overhead, but I think it also simplifies many things.

https://github.com/thiloplanz/v7files/wiki/Vermongo

React Native: Possible unhandled promise rejection

You should add the catch() to the end of the Api call. When your code hits the catch() it doesn't return anything, so data is undefined when you try to use setState() on it. The error message actually tells you this too :)

How to determine a user's IP address in node

    const express = require('express')
    const app = express()
    const port = 3000

    app.get('/', (req, res) => {
    var ip = req.ip
    console.log(ip);
    res.send('Hello World!')
    })

   // Run as nodejs ip.js
    app.listen(port, () => {
    console.log(`Example app listening at http://localhost:${port}`)
    })

Case insensitive comparison of strings in shell script

For korn shell, I use typeset built-in command (-l for lower-case and -u for upper-case).

var=True
typeset -l var
if [[ $var == "true" ]]; then
    print "match"
fi

How to append to a file in Node?

Your code using createWriteStream creates a file descriptor for every write. log.end is better because it asks node to close immediately after the write.

var fs = require('fs');
var logStream = fs.createWriteStream('log.txt', {flags: 'a'});
// use {flags: 'a'} to append and {flags: 'w'} to erase and write a new file
logStream.write('Initial line...');
logStream.end('this is the end line');

How to dismiss AlertDialog in android

Here is How I close my alertDialog

lv_three.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                GetTalebeDataUser clickedObj = (GetTalebeDataUser) parent.getItemAtPosition(position);
                alertDialog.setTitle(clickedObj.getAd());
                alertDialog.setMessage("Ögrenci Bilgileri Güncelle?");
                alertDialog.setIcon(R.drawable.ic_info);
                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        // User pressed YES button. Write Logic Here
                    }
                });
                alertDialog.setNegativeButton("Iptal", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        //alertDialog.
                        alertDialog.setCancelable(true); // HERE

                    }
                });
                alertDialog.show();
                return true;
            }
        });

z-index not working with fixed positioning

When elements are positioned outside the normal flow, they can overlap other elements.

according to Overlapping Elements section on http://web.archive.org/web/20130501103219/http://w3schools.com/css/css_positioning.asp

Better solution without exluding fields from Binding

You should not use your domain models in your views. ViewModels are the correct way to do it.

You need to map your domain model's necessary fields to viewmodel and then use this viewmodel in your controllers. This way you will have the necessery abstraction in your application.

If you never heard of viewmodels, take a look at this.

adb remount permission denied, but able to access super user in shell -- android

emulator -writable-system

For people using an Emulator: Another possibility is that you need to start the emulator with -writable-system. That was the only thing that worked for me when using the standard emulator packaged with android studio with a 4.1 image. Check here: https://stackoverflow.com/a/41332316/4962858

Binary search (bisection) in Python

Simplest is to use bisect and check one position back to see if the item is there:

def binary_search(a,x,lo=0,hi=-1):
    i = bisect(a,x,lo,hi)
    if i == 0:
        return -1
    elif a[i-1] == x:
        return i-1
    else:
        return -1

How can I force clients to refresh JavaScript files?

One simple way. Edit htaccess

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} \.(jpe?g|bmp|png|gif|css|js|mp3|ogg)$ [NC]
RewriteCond %{QUERY_STRING} !^(.+?&v33|)v=33[^&]*(?:&(.*)|)$ [NC]
RewriteRule ^ %{REQUEST_URI}?v=33 [R=301,L]

SQL MERGE statement to update data

If you need just update your records in energydata based on data in temp_energydata, assuming that temp_enerydata doesn't contain any new records, then try this:

UPDATE e SET e.kWh = t.kWh
  FROM energydata e INNER JOIN 
       temp_energydata t ON e.webmeterID = t.webmeterID AND 
                            e.DateTime = t.DateTime

Here is working sqlfiddle

But if temp_energydata contains new records and you need to insert it to energydata preferably with one statement then you should definitely go with the answer that Bacon Bits gave.

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

you will also need to have a asp:ScriptManager control on every page that you want to use ajax controls on. you should be able to just drag the scriptmanager over from your toolbox one the toolkit is installed following Zack's instructions.

How to change the type of a field?

Convert String field to Integer:

db.db-name.find({field-name: {$exists: true}}).forEach(function(obj) { 
    obj.field-name = new NumberInt(obj.field-name);
    db.db-name.save(obj);
});

Convert Integer field to String:

db.db-name.find({field-name: {$exists: true}}).forEach(function(obj) {
    obj.field-name = "" + obj.field-name;
    db.db-name.save(obj);
});

Does hosts file exist on the iPhone? How to change it?

Not programming related, but I'll answer anyway. It's in /etc/hosts.

You can change it with a simple text editor such as nano.

(Obviously you would need a jailbroken iphone for this)

How to launch html using Chrome at "--allow-file-access-from-files" mode?

Depending on the file which will be put into filesystem, as long as that file is not a malware, then that would be safe.

But don't worry to write/read file(s) to File System directory, cause you can tighten that directory security (include it's inheritance) by give a proper access right and security restriction. eg: read/write/modify.

By default, File System, Local Storage, and Storage directory are located on "\Users[Current User]\AppData\Local\Google\Chrome\User Data\Default" directory.

However you can customize it by using "--user-data-dir" flag.

And this is a sample:

"C:\Program Files (x86)\Google\Application\chrome.exe" --user-data-dir="C:\Chrome_Data\OO7" --allow-file-access-from-files

Hope this helps anyone.

How can I remove space (margin) above HTML header?

It is good practice when you start creating website to reset all the margins and paddings. So I recommend on start just to simple do:

* { margin: 0, padding: 0 }

This will make margins and paddings of all elements to be 0, and then you can style them as you wish, because each browser has a different default margin and padding of the elements.

PHP CURL & HTTPS

Quick fix, add this in your options:

curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false)

Now you have no idea what host you're actually connecting to, because cURL will not verify the certificate in any way. Hope you enjoy man-in-the-middle attacks!

Or just add it to your current function:

/**
 * Get a web file (HTML, XHTML, XML, image, etc.) from a URL.  Return an
 * array containing the HTTP server response header fields and content.
 */
function get_web_page( $url )
{
    $options = array(
        CURLOPT_RETURNTRANSFER => true,     // return web page
        CURLOPT_HEADER         => false,    // don't return headers
        CURLOPT_FOLLOWLOCATION => true,     // follow redirects
        CURLOPT_ENCODING       => "",       // handle all encodings
        CURLOPT_USERAGENT      => "spider", // who am i
        CURLOPT_AUTOREFERER    => true,     // set referer on redirect
        CURLOPT_CONNECTTIMEOUT => 120,      // timeout on connect
        CURLOPT_TIMEOUT        => 120,      // timeout on response
        CURLOPT_MAXREDIRS      => 10,       // stop after 10 redirects
        CURLOPT_SSL_VERIFYPEER => false     // Disabled SSL Cert checks
    );

    $ch      = curl_init( $url );
    curl_setopt_array( $ch, $options );
    $content = curl_exec( $ch );
    $err     = curl_errno( $ch );
    $errmsg  = curl_error( $ch );
    $header  = curl_getinfo( $ch );
    curl_close( $ch );

    $header['errno']   = $err;
    $header['errmsg']  = $errmsg;
    $header['content'] = $content;
    return $header;
}

Linux cmd to search for a class file among jars irrespective of jar path

Linux, Walkthrough to find a class file among many jars.

Go to the directory that contains the jars underneath.

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ ls
blah.txt                             metrics-core-2.2.0.jar
jopt-simple-3.2.jar                  scala-library-2.10.1.jar
kafka_2.10-0.8.1.1-sources.jar       zkclient-0.3.jar
kafka_2.10-0.8.1.1-sources.jar.asc   zookeeper-3.3.4.jar
log4j-1.2.15.jar

I'm looking for which jar provides for the Producer class.

Understand how the for loop works:

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ for i in `seq 1 3`; do
> echo $i
> done
1
2
3

Understand why find this works:

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ find . -name "*.jar"
./slf4j-api-1.7.2.jar
./zookeeper-3.3.4.jar
./kafka_2.10-0.8.1.1-javadoc.jar
./slf4j-1.7.7/osgi-over-slf4j-1.7.7-sources.jar

You can pump all the jars underneath into the for loop:

eric@dev /home/el/kafka_2.10-0.8.1.1/libs $ for i in `find . -name "*.jar"`; do
> echo $i
> done

./slf4j-api-1.7.2.jar
./zookeeper-3.3.4.jar
./kafka_2.10-0.8.1.1-javadoc.jar
./kafka_2.10-0.8.1.1-sources.jar

Now we can operate on each one:

Do a jar tf on every jar and cram it into blah.txt:

for i in `find . -name "*.jar"`; do echo $i; jar tf $i; done > blah.txt

Inspect blah.txt, it's a list of all the classes in all the jars. You can search that file for the class you want, then look for the jar that came before it, that's the one you want.

How to create an Array with AngularJS's ng-model

This should work.

app = angular.module('plunker', [])

app.controller 'MainCtrl', ($scope) ->
  $scope.users = ['bob', 'sean', 'rocky', 'john']
  $scope.test = ->
    console.log $scope.users

HTML:

<input ng-repeat="user in users" ng-model="user" type="text"/>
<input type="button" value="test" ng-click="test()" />

Example plunk here

java.lang.IllegalStateException: Only fullscreen opaque activities can request orientation

I resolved this issue by removing android:screenOrientation="portrait" and added below code into my onCreate

if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}

while my theme properties are

<item name="android:windowIsTranslucent">true</item>
<item name="android:windowDisablePreview">true</item>

Change navbar color in Twitter Bootstrap

Update 2020

Changing the Navbar color is different (and a little easier) in Bootstrap 4. You can create a custom navbar class, and then reference it to change the navbar without impacting other Bootstrap navs..

<nav class="navbar navbar-custom">...</nav>

Bootstrap 4.3+

The CSS required to change the Navbar is much less in Bootstrap 4...

.navbar-custom {
    background-color: #ff5500;
}
/* change the brand and text color */
.navbar-custom .navbar-brand,
.navbar-custom .navbar-text {
    color: rgba(255,255,255,.8);
}
/* change the link color */
.navbar-custom .navbar-nav .nav-link {
    color: rgba(255,255,255,.5);
}
/* change the color of active or hovered links */
.navbar-custom .nav-item.active .nav-link,
.navbar-custom .nav-item:hover .nav-link {
    color: #ffffff;
}

Bootstrap 4 Custom Navbar Demoenter image description here

Changing the active/hover link background color also works with the same CSS, but you must adjust the padding if you want the bg color to fill the full height of the link...

py-0 to remove vertical padding from the entire navbar...

<nav class="navbar navbar-expand-sm navbar-custom py-0">..</nav>

/* change the link color and padding  */
.navbar-custom .navbar-nav .nav-link {
    color: rgba(255,255,255,.5);
    padding: .75rem 1rem;
}

/* change the color and background color of active links */
.navbar-custom .nav-item.active .nav-link,
.navbar-custom .nav-item:hover .nav-link {
    color: #ffffff;
    background-color: #333;
}

Bootstrap 4 Change Link and Background Color Demo

Also see: Bootstrap 4 Change Hamburger Toggler Color


**Bootstrap 3**
<nav class="navbar navbar-custom">
  <div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">...
    </button>
    <a class="navbar-brand" href="#">Title</a>
  </div>
   ...
</nav>


.navbar-custom {
    background-color:#229922;
    color:#ffffff;
    border-radius:0;
}
  
.navbar-custom .navbar-nav > li > a {
    color:#fff;
}

.navbar-custom .navbar-nav > .active > a {
    color: #ffffff;
    background-color:transparent;
}
      
.navbar-custom .navbar-nav > li > a:hover,
.navbar-custom .navbar-nav > li > a:focus,
.navbar-custom .navbar-nav > .active > a:hover,
.navbar-custom .navbar-nav > .active > a:focus,
.navbar-custom .navbar-nav > .open >a {
    text-decoration: none;
    background-color: #33aa33;
}
     
.navbar-custom .navbar-brand {
    color:#eeeeee;
}
.navbar-custom .navbar-toggle {
    background-color:#eeeeee;
}
.navbar-custom .icon-bar {
    background-color:#33aa33;
}

Custom Navbar Demo on Bootply


If the Navbar has dropdowns, add the following to change dropdown color(s):

/* for dropdowns only */
.navbar-custom .navbar-nav .dropdown-menu  { 
  background-color: #33aa33;
}
.navbar-custom .navbar-nav .dropdown-menu>li>a  { 
  color: #fff;
}
.navbar-custom .navbar-nav .dropdown-menu>li>a:hover,.navbar-custom .navbar-nav .dropdown-menu>li>a:focus  { 
  color: #33aa33;
}

Demo with Dropdown


If you want to change the theme colors all together (beyond the navbar), see this answer

CSS hover vs. JavaScript mouseover

A very big difference is that ":hover" state is automatically deactivated when the mouse moves out of the element. As a result any styles that are applied on hover are automatically reversed. On the other hand, with the javascript approach, you would have to define both "onmouseover" and "onmouseout" events. If you only define "onmouseover" the styles that are applied "onmouseover" will persist even after you mouse out unless you have explicitly defined "onmouseout".

How can I create a two dimensional array in JavaScript?

Recursive function to create a multi-dimensional array:

var makeArray = function (dims, arr) {          
    if (dims[1] === undefined) {
        return new Array(dims[0]);
    }

    arr = new Array(dims[0]);

    for (var i=0; i<dims[0]; i++) {
        arr[i] = new Array(dims[1]);
        arr[i] = makeArray(dims.slice(1), arr[i]);
    }

    return arr;
}

Build a 2x3x4x2 4D-Array:

var array = makeArray([2, 3, 4, 2]);    

What's the difference between .NET Core, .NET Framework, and Xamarin?

Xamarin is used for phone applications (both IOS/Android). The .NET Core is used for designing Web applications that can work on both Apache and IIS.

That is the difference in two sentences.

How do I remove link underlining in my HTML email?

Code like the lines below worked for me in Gmail Web client. A non-underlined black link showed up in the email. I didn't use the nested span tag.

<table>
  <tbody>
    <tr>
        <td>
            <a href="http://hexinpeter.com" style="text-decoration: none; color: #000000 !important;">Peter Blog</a>
        </td>
    </tr>
  </tbody>
</table>

Note: Gmail will strip off any incorrect inline styles. E.g. code like the line below will have its inline styles all stripped off.

<a href="http://hexinpeter.com" style="font-family:; text-decoration: none; color: #000000 !important;">Peter Blog</a>

Save PHP array to MySQL?

You can save your array as a json.
there is documentation for json data type: https://dev.mysql.com/doc/refman/5.7/en/json.html
I think this is the best solution, and will help you maintain your code more readable by avoiding crazy functions.
I expect this is helpful for you.

Call Class Method From Another Class

You can call a function from within a class with:

A().method1()

How to loop through array in jQuery?

Try this:

$.grep(array, function(element) {

})

Adding a column after another column within SQL

In a Firebird database the AFTER myOtherColumn does not work but you can try re-positioning the column using:

ALTER TABLE name ALTER column POSITION new_position

I guess it may work in other cases as well.

How to replace ${} placeholders in a text file?

It can be done in bash itself if you have control of the configuration file format. You just need to source (".") the configuration file rather than subshell it. That ensures the variables are created in the context of the current shell (and continue to exist) rather than the subshell (where the variable disappear when the subshell exits).

$ cat config.data
    export parm_jdbc=jdbc:db2://box7.co.uk:5000/INSTA
    export parm_user=pax
    export parm_pwd=never_you_mind

$ cat go.bash
    . config.data
    echo "JDBC string is " $parm_jdbc
    echo "Username is    " $parm_user
    echo "Password is    " $parm_pwd

$ bash go.bash
    JDBC string is  jdbc:db2://box7.co.uk:5000/INSTA
    Username is     pax
    Password is     never_you_mind

If your config file cannot be a shell script, you can just 'compile' it before executing thus (the compilation depends on your input format).

$ cat config.data
    parm_jdbc=jdbc:db2://box7.co.uk:5000/INSTA # JDBC URL
    parm_user=pax                              # user name
    parm_pwd=never_you_mind                    # password

$ cat go.bash
    cat config.data
        | sed 's/#.*$//'
        | sed 's/[ \t]*$//'
        | sed 's/^[ \t]*//'
        | grep -v '^$'
        | sed 's/^/export '
        >config.data-compiled
    . config.data-compiled
    echo "JDBC string is " $parm_jdbc
    echo "Username is    " $parm_user
    echo "Password is    " $parm_pwd

$ bash go.bash
    JDBC string is  jdbc:db2://box7.co.uk:5000/INSTA
    Username is     pax
    Password is     never_you_mind

In your specific case, you could use something like:

$ cat config.data
    export p_p1=val1
    export p_p2=val2
$ cat go.bash
    . ./config.data
    echo "select * from dbtable where p1 = '$p_p1' and p2 like '$p_p2%' order by p1"
$ bash go.bash
    select * from dbtable where p1 = 'val1' and p2 like 'val2%' order by p1

Then pipe the output of go.bash into MySQL and voila, hopefully you won't destroy your database :-).

Jetty: HTTP ERROR: 503/ Service Unavailable

Actually, I solved the problem. I run it by eclipse jetty plugin.

  1. I didn't have the JDK lib in my eclipse, that's why the message keep showing that I need the full JDK installed, that's the main reason.

  2. I installed two versions of jetty plugin, wich is jetty7 and jetty8. I think they conflict with each other or something, so I removed the jetty7, and it works!

Scroll to the top of the page after render in react.js

You can do this in the router like that:

ReactDOM.render((
<Router onUpdate={() => window.scrollTo(0, 0)} history={browserHistory}>
     <Route path='/' component={App}>
        <IndexRoute component={Home}></IndexRoute>
        <Route path="/about" component={About}/>
        <Route path="/work">
            <IndexRoute component={Work}></IndexRoute>
            <Route path=":id" component={ProjectFull}></Route>
        </Route>
        <Route path="/blog" component={Blog}/>
    </Route>
 </Router>
), document.getElementById('root'));

The onUpdate={() => window.scrollTo(0, 0)} put the scroll top. For more information check: codepen link

How do I debug error ECONNRESET in Node.js?

Another possible case (but rare) could be if you have server to server communications and have set server.maxConnections to a very low value.

In node's core lib net.js it will call clientHandle.close() which will also cause error ECONNRESET:

if (self.maxConnections && self._connections >= self.maxConnections) {
  clientHandle.close(); // causes ECONNRESET on the other end
  return;
}

How do I use hexadecimal color strings in Flutter?

As the Color constructor does not support hexadecimal string, so we should find other alternatives.

There are several possibilities :

1- The first one is to create a small function that will allow you to convert a color hex-string to a Color object.

Code :

   Color colorFromHex(String hexColor) {
   final hexCode = hexColor.replaceAll('#', '');
   if (hexColor.length == 6) {
    hexColor = 'FF' + hexColor; // FF as the opacity value if you don't add it.
   }
  return Color(int.parse('FF$hexCode', radix: 16));
}

Usage :

 Container(
          color: colorFromHex('abcdff'),
          child: Text(
            'Never stop learning',
            style: TextStyle(color: colorFromHex('bbffffcc')),
          ),
        )

2- The second possibility is to use the supercharged package. Supercharged brings all the comfort features from languages like Kotlin to all Flutter developers.

Add the dependency supercharged: ^1.X.X (find recent version) to your project and start using Supercharged everywhere:

import 'package:supercharged/supercharged.dart';

Now ,transform any String to colors

Code :

"#ff00ff".toColor(); // painless hex to color
"red".toColor(); // supports all web color names

You can also use the hexcolor package which is also great .

Best way to implement multi-language/globalization in large .NET project

Use a separate project with Resources

I can tell this from out experience, having a current solution with 12 24 projects that includes API, MVC, Project Libraries (Core functionalities), WPF, UWP and Xamarin. It is worth reading this long post as I think it is the best way to do so. With the help of VS tools easily exportable and importable to sent to translation agencies or review by other people.

EDIT 02/2018: Still going strong, converting it to a .NET Standard library makes it possible to even use it across .NET Framework and NET Core. I added an extra section for converting it to JSON so for example angular can use it.

EDIT 2019: Going forward with Xamarin, this still works across all platforms. E.g. Xamarin.Forms advices to use resx files as well. (I did not develop an app in Xamarin.Forms yet, but the documentation, that is way to detailed to just get started, covers it: Xamarin.Forms Documentation). Just like converting it to JSON we can also convert it to a .xml file for Xamarin.Android.

EDIT 2019 (2): While upgrading to UWP from WPF, I encountered that in UWP they prefer to use another filetype .resw, which is is in terms of content identical but the usage is different. I found a different way of doing this which, in my opinion, works better then the default solution.

EDIT 2020: Updated some suggestions for larger (modulair) projects that might require multiple language projects.

So, lets get to it.

Pro's

  • Strongly typed almost everywhere.
  • In WPF you don't have to deal with ResourceDirectories.
  • Supported for ASP.NET, Class Libraries, WPF, Xamarin, .NET Core, .NET Standard as far as I have tested.
  • No extra third-party libraries needed.
  • Supports culture fallback: en-US -> en.
  • Not only back-end, works also in XAML for WPF and Xamarin.Forms, in .cshtml for MVC.
  • Easily manipulate the language by changing the Thread.CurrentThread.CurrentCulture
  • Search engines can Crawl in different languages and user can send or save language-specific urls.

Con's

  • WPF XAML is sometimes buggy, newly added strings don't show up directly. Rebuild is the temp fix (vs2015).
  • UWP XAML does not show intellisense suggestions and does not show the text while designing.
  • Tell me.

Setup

Create language project in your solution, give it a name like MyProject.Language. Add a folder to it called Resources, and in that folder, create two Resources files (.resx). One called Resources.resx and another called Resources.en.resx (or .en-GB.resx for specific). In my implementation, I have NL (Dutch) language as the default language, so that goes in my first file, and English goes in my second file.

Setup should look like this:

language setup project

The properties for Resources.resx must be: properties

Make sure that the custom tool namespace is set to your project namespace. Reason for this is that in WPF, you cannot reference to Resources inside XAML.

And inside the resource file, set the access modifier to Public:

access modifier

If you have such a large application (let's say different modules) you can consider creating multiple projects like above. In that case you could prefix your Keys and resource classes with the particular Module. Use the best language editor there is for Visual Studio to combine all files into a single overview.

Using in another project

Reference to your project: Right click on References -> Add Reference -> Prjects\Solutions.

Use namespace in a file: using MyProject.Language;

Use it like so in back-end: string someText = Resources.orderGeneralError; If there is something else called Resources, then just put in the entire namespace.

Using in MVC

In MVC you can do however you like to set the language, but I used parameterized url's, which can be setup like so:

RouteConfig.cs Below the other mappings

routes.MapRoute(
    name: "Locolized",
    url: "{lang}/{controller}/{action}/{id}",
    constraints: new { lang = @"(\w{2})|(\w{2}-\w{2})" },   // en or en-US
    defaults: new { controller = "shop", action = "index", id = UrlParameter.Optional }
);

FilterConfig.cs (might need to be added, if so, add FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); to the Application_start() method in Global.asax

public class FilterConfig
{
    public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {
        filters.Add(new ErrorHandler.AiHandleErrorAttribute());
        //filters.Add(new HandleErrorAttribute());
        filters.Add(new LocalizationAttribute("nl-NL"), 0);
    }
}

LocalizationAttribute

public class LocalizationAttribute : ActionFilterAttribute
{
    private string _DefaultLanguage = "nl-NL";
    private string[] allowedLanguages = { "nl", "en" };

    public LocalizationAttribute(string defaultLanguage)
    {
        _DefaultLanguage = defaultLanguage;
    }

    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        string lang = (string) filterContext.RouteData.Values["lang"] ?? _DefaultLanguage;
        LanguageHelper.SetLanguage(lang);
    }
}

LanguageHelper just sets the Culture info.

//fixed number and date format for now, this can be improved.
public static void SetLanguage(LanguageEnum language)
{
    string lang = "";
    switch (language)
    {
        case LanguageEnum.NL:
            lang = "nl-NL";
            break;
        case LanguageEnum.EN:
            lang = "en-GB";
            break;
        case LanguageEnum.DE:
            lang = "de-DE";
            break;
    }
    try
    {
        NumberFormatInfo numberInfo = CultureInfo.CreateSpecificCulture("nl-NL").NumberFormat;
        CultureInfo info = new CultureInfo(lang);
        info.NumberFormat = numberInfo;
        //later, we will if-else the language here
        info.DateTimeFormat.DateSeparator = "/";
        info.DateTimeFormat.ShortDatePattern = "dd/MM/yyyy";
        Thread.CurrentThread.CurrentUICulture = info;
        Thread.CurrentThread.CurrentCulture = info;
    }
    catch (Exception)
    {

    }
}

Usage in .cshtml

@using MyProject.Language;
<h3>@Resources.w_home_header</h3>

or if you don't want to define usings then just fill in the entire namespace OR you can define the namespace under /Views/web.config:

<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
    ...
    <add namespace="MyProject.Language" />
  </namespaces>
</pages>
</system.web.webPages.razor>

This mvc implementation source tutorial: Awesome tutorial blog

Using in class libraries for models

Back-end using is the same, but just an example for using in attributes

using MyProject.Language;
namespace MyProject.Core.Models
{
    public class RegisterViewModel
    {
        [Required(ErrorMessageResourceName = "accountEmailRequired", ErrorMessageResourceType = typeof(Resources))]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }
    }
}

If you have reshaper it will automatically check if the given resource name exists. If you prefer type safety you can use T4 templates to generate an enum

Using in WPF.

Ofcourse add a reference to your MyProject.Language namespace, we know how to use it in back-end.

In XAML, inside the header of a Window or UserControl, add a namespace reference called lang like so:

<UserControl x:Class="Babywatcher.App.Windows.Views.LoginView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:MyProject.App.Windows.Views"
              xmlns:lang="clr-namespace:MyProject.Language;assembly=MyProject.Language" <!--this one-->
             mc:Ignorable="d" 
            d:DesignHeight="210" d:DesignWidth="300">

Then, inside a label:

    <Label x:Name="lblHeader" Content="{x:Static lang:Resources.w_home_header}" TextBlock.FontSize="20" HorizontalAlignment="Center"/>

Since it is strongly typed you are sure the resource string exists. You might need to recompile the project sometimes during setup, WPF is sometimes buggy with new namespaces.

One more thing for WPF, set the language inside the App.xaml.cs. You can do your own implementation (choose during installation) or let the system decide.

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        SetLanguageDictionary();
    }

    private void SetLanguageDictionary()
    {
        switch (Thread.CurrentThread.CurrentCulture.ToString())
        {
            case "nl-NL":
                MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo("nl-NL");
                break;
            case "en-GB":
                MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo("en-GB");
                break;
            default://default english because there can be so many different system language, we rather fallback on english in this case.
                MyProject.Language.Resources.Culture = new System.Globalization.CultureInfo("en-GB");
                break;
        }
       
    }
}

Using in UWP

In UWP, Microsoft uses this solution, meaning you will need to create new resource files. Plus you can not re-use the text either because they want you to set the x:Uid of your control in XAML to a key in your resources. And in your resources you have to do Example.Text to fill a TextBlock's text. I didn't like that solution at all because I want to re-use my resource files. Eventually I came up with the following solution. I just found this out today (2019-09-26) so I might come back with something else if it turns out this doesn't work as desired.

Add this to your project:

using Windows.UI.Xaml.Resources;

public class MyXamlResourceLoader : CustomXamlResourceLoader
{
    protected override object GetResource(string resourceId, string objectType, string propertyName, string propertyType)
    {
        return MyProject.Language.Resources.ResourceManager.GetString(resourceId);
    }
}

Add this to App.xaml.cs in the constructor:

CustomXamlResourceLoader.Current = new MyXamlResourceLoader();

Where ever you want to in your app, use this to change the language:

ApplicationLanguages.PrimaryLanguageOverride = "nl";
Frame.Navigate(this.GetType());

The last line is needed to refresh the UI. While I am still working on this project I noticed that I needed to do this 2 times. I might end up with a language selection at the first time the user is starting. But since this will be distributed via Windows Store, the language is usually equal to the system language.

Then use in XAML:

<TextBlock Text="{CustomResource ExampleResourceKey}"></TextBlock>

Using it in Angular (convert to JSON)

Now days it is more common to have a framework like Angular in combination with components, so without cshtml. Translations are stored in json files, I am not going to cover how that works, I would just highly recommend ngx-translate instead of the angular multi-translation. So if you want to convert translations to a JSON file, it is pretty easy, I use a T4 template script that converts the Resources file to a json file. I recommend installing T4 editor to read the syntax and use it correctly because you need to do some modifications.

Only 1 thing to note: It is not possible to generate the data, copy it, clean the data and generate it for another language. So you have to copy below code as many times as languages you have and change the entry before '//choose language here'. Currently no time to fix this but probably will update later (if interested).

Path: MyProject.Language/T4/CreateLocalizationEN.tt

<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Resources" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.ComponentModel.Design" #>
<#@ output extension=".json" #>
<#


var fileNameNl = "../Resources/Resources.resx";
var fileNameEn = "../Resources/Resources.en.resx";
var fileNameDe = "../Resources/Resources.de.resx";
var fileNameTr = "../Resources/Resources.tr.resx";

var fileResultName = "../T4/CreateLocalizationEN.json";//choose language here
var fileResultPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", fileResultName);
//var fileDestinationPath = "../../MyProject.Web/ClientApp/app/i18n/";

var fileNameDestNl = "nl.json";
var fileNameDestEn = "en.json";
var fileNameDestDe = "de.json";
var fileNameDestTr = "tr.json";

var pathBaseDestination = Directory.GetParent(Directory.GetParent(this.Host.ResolvePath("")).ToString()).ToString();

string[] fileNamesResx = new string[] {fileNameEn }; //choose language here
string[] fileNamesDest = new string[] {fileNameDestEn }; //choose language here

for(int x = 0; x < fileNamesResx.Length; x++)
{
    var currentFileNameResx = fileNamesResx[x];
    var currentFileNameDest = fileNamesDest[x];
    var currentPathResx = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", currentFileNameResx);
    var currentPathDest =pathBaseDestination + "/MyProject.Web/ClientApp/app/i18n/" + currentFileNameDest;
    using(var reader = new ResXResourceReader(currentPathResx))
    {
        reader.UseResXDataNodes = true;
#>
        {
<#
            foreach(DictionaryEntry entry in reader)
            {
                var name = entry.Key;
                var node = (ResXDataNode)entry.Value;
                var value = node.GetValue((ITypeResolutionService) null); 
                 if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\n", "");
                 if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\r", "");
#>
            "<#=name#>": "<#=value#>",
<#

    
            }
#>
        "WEBSHOP_LASTELEMENT": "just ignore this, for testing purpose"
        }
<#
    }
    File.Copy(fileResultPath, currentPathDest, true);
}


#>

If you have a modulair application and you followed my suggestion to create multiple language projects, then you will have to create a T4 file for each of them. Make sure the json files are logically defined, it doesn't have to be en.json, it can also be example-en.json. To combine multiple json files for using with ngx-translate, follow the instructions here

Use in Xamarin.Android

As explained above in the updates, I use the same method as I have done with Angular/JSON. But Android uses XML files, so I wrote a T4 file that generates those XML files.

Path: MyProject.Language/T4/CreateAppLocalizationEN.tt

#@ template debug="false" hostspecific="true" language="C#" #>
<#@ assembly name="System.Core" #>
<#@ assembly name="System.Windows.Forms" #>
<#@ import namespace="System.Linq" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.Resources" #>
<#@ import namespace="System.Collections" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.ComponentModel.Design" #>
<#@ output extension=".xml" #>
<#
var fileName = "../Resources/Resources.en.resx";
var fileResultName = "../T4/CreateAppLocalizationEN.xml";
var fileResultRexPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", fileName);
var fileResultPath = Path.Combine(Path.GetDirectoryName(this.Host.ResolvePath("")), "MyProject.Language", fileResultName);

    var fileNameDest = "strings.xml";

    var pathBaseDestination = Directory.GetParent(Directory.GetParent(this.Host.ResolvePath("")).ToString()).ToString();

    var currentPathDest =pathBaseDestination + "/MyProject.App.AndroidApp/Resources/values-en/" + fileNameDest;

    using(var reader = new ResXResourceReader(fileResultRexPath))
    {
        reader.UseResXDataNodes = true;
        #>
        <resources>
        <#

                foreach(DictionaryEntry entry in reader)
                {
                    var name = entry.Key;
                    //if(!name.ToString().Contains("WEBSHOP_") && !name.ToString().Contains("DASHBOARD_"))//only include keys with these prefixes, or the country ones.
                    //{
                    //  if(name.ToString().Length != 2)
                    //  {
                    //      continue;
                    //  }
                    //}
                    var node = (ResXDataNode)entry.Value;
                    var value = node.GetValue((ITypeResolutionService) null); 
                     if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\n", "");
                     if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("\r", "");
                     if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("&", "&amp;");
                     if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("<<", "");
                     //if (!String.IsNullOrEmpty(value.ToString())) value = value.ToString().Replace("'", "\'");
#>
              <string name="<#=name#>">"<#=value#>"</string>
<#      
                }
#>
            <string name="WEBSHOP_LASTELEMENT">just ignore this</string>
<#
        #>
        </resources>
        <#
        File.Copy(fileResultPath, currentPathDest, true);
    }

#>

Android works with values-xx folders, so above is for English for in the values-en folder. But you also have to generate a default which goes into the values folder. Just copy above T4 template and change the folder in the above code.

There you go, you can now use one single resource file for all your projects. This makes it very easy exporting everything to an excl document and let someone translate it and import it again.

Special thanks to this amazing VS extension which works awesome with resx files. Consider donating to him for his awesome work (I have nothing to do with that, I just love the extension).

DLL References in Visual C++

You mention adding the additional include directory (C/C++|General) and additional lib dependency (Linker|Input), but have you also added the additional library directory (Linker|General)?

Including a sample error message might also help people answer the question since it's not even clear if the error is during compilation or linking.

Intellij reformat on file save

I thought there was something like that in IntelliJ, but I can't find it. The only clean-up that happens at save is that white space at the ends of lines is removed. I thought I had to specify that behavior at one point, but I don't see anything related at this point.

How does setTimeout work in Node.JS?

The idea of non-blocking is that the loop iterations are quick. So to iterate for each tick should take short enough a time that the setTimeout will be accurate to within reasonable precision (off by maybe <100 ms or so).

In theory though you're right. If I write an application and block the tick, then setTimeouts will be delayed. So to answer you're question, who can assure setTimeouts execute on time? You, by writing non-blocking code, can control the degree of accuracy up to almost any reasonable degree of accuracy.

As long as javascript is "single-threaded" in terms of code execution (excluding web-workers and the like), that will always happen. The single-threaded nature is a huge simplification in most cases, but requires the non-blocking idiom to be successful.

Try this code out either in your browser or in node, and you'll see that there is no guarantee of accuracy, on the contrary, the setTimeout will be very late:

var start = Date.now();

// expecting something close to 500
setTimeout(function(){ console.log(Date.now() - start); }, 500);

// fiddle with the number of iterations depending on how quick your machine is
for(var i=0; i<5000000; ++i){}

Unless the interpreter optimises the loop away (which it doesn't on chrome), you'll get something in the thousands. Remove the loop and you'll see it's 500 on the nose...

How to declare a Fixed length Array in TypeScript

The Tuple approach :

This solution provides a strict FixedLengthArray (ak.a. SealedArray) type signature based in Tuples.

Syntax example :

// Array containing 3 strings
let foo : FixedLengthArray<[string, string, string]> 

This is the safest approach, considering it prevents accessing indexes out of the boundaries.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number
type ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never
type FixedLengthArray<T extends any[]> =
  Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>
  & { [Symbol.iterator]: () => IterableIterator< ArrayItems<T> > }

Tests :

var myFixedLengthArray: FixedLengthArray< [string, string, string]>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? INVALID INDEX ERROR

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? INVALID INDEX ERROR

(*) This solution requires the noImplicitAny typescript configuration directive to be enabled in order to work (commonly recommended practice)


The Array(ish) approach :

This solution behaves as an augmentation of the Array type, accepting an additional second parameter(Array length). Is not as strict and safe as the Tuple based solution.

Syntax example :

let foo: FixedLengthArray<string, 3> 

Keep in mind that this approach will not prevent you from accessing an index out of the declared boundaries and set a value on it.

Implementation :

type ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' |  'unshift'
type FixedLengthArray<T, L extends number, TObj = [T, ...Array<T>]> =
  Pick<TObj, Exclude<keyof TObj, ArrayLengthMutationKeys>>
  & {
    readonly length: L 
    [ I : number ] : T
    [Symbol.iterator]: () => IterableIterator<T>   
  }

Tests :

var myFixedLengthArray: FixedLengthArray<string,3>

// Array declaration tests
myFixedLengthArray = [ 'a', 'b', 'c' ]  // ? OK
myFixedLengthArray = [ 'a', 'b', 123 ]  // ? TYPE ERROR
myFixedLengthArray = [ 'a' ]            // ? LENGTH ERROR
myFixedLengthArray = [ 'a', 'b' ]       // ? LENGTH ERROR

// Index assignment tests 
myFixedLengthArray[1] = 'foo'           // ? OK
myFixedLengthArray[1000] = 'foo'        // ? SHOULD FAIL

// Methods that mutate array length
myFixedLengthArray.push('foo')          // ? MISSING METHOD ERROR
myFixedLengthArray.pop()                // ? MISSING METHOD ERROR

// Direct length manipulation
myFixedLengthArray.length = 123         // ? READ-ONLY ERROR

// Destructuring
var [ a ] = myFixedLengthArray          // ? OK
var [ a, b ] = myFixedLengthArray       // ? OK
var [ a, b, c ] = myFixedLengthArray    // ? OK
var [ a, b, c, d ] = myFixedLengthArray // ? SHOULD FAIL

How to find index of all occurrences of element in array?

Another alternative solution is to use Array.prototype.reduce():

["Nano","Volvo","BMW","Nano","VW","Nano"].reduce(function(a, e, i) {
    if (e === 'Nano')
        a.push(i);
    return a;
}, []);   // [0, 3, 5]

N.B.: Check the browser compatibility for reduce method and use polyfill if required.

Find out which remote branch a local branch is tracking

If you are using Gradle,

def gitHash = new ByteArrayOutputStream()
    project.exec {
        commandLine 'git', 'rev-parse', '--short', 'HEAD'
        standardOutput = gitHash
    }

def gitBranch = new ByteArrayOutputStream()
    project.exec {
        def gitCmd = "git symbolic-ref --short -q HEAD || git branch -rq --contains "+getGitHash()+" | sed -e '2,\$d'  -e 's/\\(.*\\)\\/\\(.*\\)\$/\\2/' || echo 'master'"
        commandLine "bash", "-c", "${gitCmd}"
        standardOutput = gitBranch
    }

How to throw a C++ exception

Simple:

#include <stdexcept>

int compare( int a, int b ) {
    if ( a < 0 || b < 0 ) {
        throw std::invalid_argument( "received negative value" );
    }
}

The Standard Library comes with a nice collection of built-in exception objects you can throw. Keep in mind that you should always throw by value and catch by reference:

try {
    compare( -1, 3 );
}
catch( const std::invalid_argument& e ) {
    // do stuff with exception... 
}

You can have multiple catch() statements after each try, so you can handle different exception types separately if you want.

You can also re-throw exceptions:

catch( const std::invalid_argument& e ) {
    // do something

    // let someone higher up the call stack handle it if they want
    throw;
}

And to catch exceptions regardless of type:

catch( ... ) { };

How to trim a string after a specific character in java

You could use result = result.replaceAll("\n",""); or

 String[] split = result.split("\n");

How do you test a public/private DSA keypair?

For DSA keys, use

 openssl dsa -pubin -in dsa.pub -modulus -noout

to print the public keys, then

 openssl dsa -in dsa.key -modulus -noout

to display the public keys corresponding to a private key, then compare them.

what is the most efficient way of counting occurrences in pandas?

I think df['word'].value_counts() should serve. By skipping the groupby machinery, you'll save some time. I'm not sure why count should be much slower than max. Both take some time to avoid missing values. (Compare with size.)

In any case, value_counts has been specifically optimized to handle object type, like your words, so I doubt you'll do much better than that.

show distinct column values in pyspark dataframe: python

Run this first

df.createOrReplaceTempView('df')

Then run

spark.sql("""
    SELECT distinct
        column name
    FROM
        df
    """).show()

Python write line by line to a text file

You may want to look into os dependent line separators, e.g.:

import os

with open('./output.txt', 'a') as f1:
    f1.write(content + os.linesep)

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

Html ordered list 1.1, 1.2 (Nested counters and scope) not working

Moshe's solution is great but the problem may still exist if you need to put the list inside a div. (read: CSS counter-reset on nested list)

This style could prevent that issue:

_x000D_
_x000D_
ol > li {_x000D_
    counter-increment: item;_x000D_
}_x000D_
_x000D_
ol > li:first-child {_x000D_
  counter-reset: item;_x000D_
}_x000D_
_x000D_
ol ol > li {_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
ol ol > li:before {_x000D_
    content: counters(item, ".") ". ";_x000D_
    margin-left: -20px;_x000D_
}
_x000D_
<ol>_x000D_
  <li>list not nested in div</li>_x000D_
</ol>_x000D_
_x000D_
<hr>_x000D_
_x000D_
<div>_x000D_
  <ol>_x000D_
  <li>nested in div</li>_x000D_
  <li>two_x000D_
    <ol>_x000D_
      <li>two.one</li>_x000D_
      <li>two.two</li>_x000D_
      <li>two.three</li>_x000D_
    </ol>_x000D_
  </li>_x000D_
  <li>three_x000D_
    <ol>_x000D_
      <li>three.one</li>_x000D_
      <li>three.two_x000D_
        <ol>_x000D_
          <li>three.two.one</li>_x000D_
          <li>three.two.two</li>_x000D_
        </ol>_x000D_
      </li>_x000D_
    </ol>_x000D_
  </li>_x000D_
  <li>four</li>_x000D_
  </ol>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can also set the counter-reset on li:before.

React.createElement: type is invalid -- expected a string

In my case I forgot to import and export my (new) elements called by the render in the index.js file.

Calling one method from another within same class in Python

To call the method, you need to qualify function with self.. In addition to that, if you want to pass a filename, add a filename parameter (or other name you want).

class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        srcpath = event.src_path
        print (srcpath, 'has been ',event.event_type)
        print (datetime.datetime.now())
        filename = srcpath[12:]
        self.dropbox_fn(filename) # <----

    def dropbox_fn(self, filename):  # <-----
        print('In dropbox_fn:', filename)

Big O, how do you calculate/approximate it?

Small reminder: the big O notation is used to denote asymptotic complexity (that is, when the size of the problem grows to infinity), and it hides a constant.

This means that between an algorithm in O(n) and one in O(n2), the fastest is not always the first one (though there always exists a value of n such that for problems of size >n, the first algorithm is the fastest).

Note that the hidden constant very much depends on the implementation!

Also, in some cases, the runtime is not a deterministic function of the size n of the input. Take sorting using quick sort for example: the time needed to sort an array of n elements is not a constant but depends on the starting configuration of the array.

There are different time complexities:

  • Worst case (usually the simplest to figure out, though not always very meaningful)
  • Average case (usually much harder to figure out...)

  • ...

A good introduction is An Introduction to the Analysis of Algorithms by R. Sedgewick and P. Flajolet.

As you say, premature optimisation is the root of all evil, and (if possible) profiling really should always be used when optimising code. It can even help you determine the complexity of your algorithms.

Git checkout: updating paths is incompatible with switching branches

I believe this occurs when you are trying to checkout a remote branch that your local git repo is not aware of yet. Try:

git remote show origin

If the remote branch you want to checkout is under "New remote branches" and not "Tracked remote branches" then you need to fetch them first:

git remote update
git fetch

Now it should work:

git checkout -b local-name origin/remote-name

How to write the Fibonacci Sequence?

Fibonacci series in python,by creating null list:

                   inp=int(input())     #size of the series example it is 7
                   n=0
                   n1=1
                   x=[]                 #blank list
                   x.insert(0,0)    #initially insert 0th position 0 element
                   for i in range(0,inp-1):
                    nth=n+n1
                    n=n1                  #swapping the value
                    n1=nth
                    x.append(n)          #append all the values to null list
                   for i in x:        #run this loop so ans is 0 1 1 2 3 5 8
                    print(i,end=" ")

$(document).click() not working correctly on iPhone. jquery

CSS Cursor:Pointer; is a great solution. FastClick https://github.com/ftlabs/fastclick is another solution which doesn't require you to change css if you didn't want Cursor:Pointer; on an element for some reason. I use fastclick now anyway to eliminate the 300ms delay on iOS devices.

anaconda update all possible packages?

if working in MS windows, you can use Anaconda navigator. click on the environment, in the drop-down box, it's "installed" by default. You can select "updatable" and start from there

Python: Best way to add to sys.path relative to the current running script

If you don't want to edit each file

  • Install you library like a normal python libray
    or
  • Set PYTHONPATH to your lib

or if you are willing to add a single line to each file, add a import statement at top e.g.

import import_my_lib

keep import_my_lib.py in bin and import_my_lib can correctly set the python path to whatever lib you want

Rails has_many with alias name

Give this a shot:

has_many :jobs, foreign_key: "user_id", class_name: "Task"

Note, that :as is used for polymorphic associations.

Hour from DateTime? in 24 hours format

Try this, if your input is string 
For example 

string input= "13:01";
string[] arry = input.Split(':');                  
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)

 {

DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)), 
int.Parse(timeinput.Substring(2, 2)), 0); 
return startTime.ToString("hh:mm tt");

}
out put: 01:01

Exercises to improve my Java programming skills

Go and buy the book titled "Java examples in a nutshell". In the book you will find most of practical examples.

How to compile without warnings being treated as errors?

Solution:

CFLAGS=-Wno-error ./configure

Uninitialized Constant MessagesController

Your model is @Messages, change it to @message.

To change it like you should use migration:

def change   rename_table :old_table_name, :new_table_name end 

Of course do not create that file by hand but use rails generator:

rails g migration ChangeMessagesToMessage 

That will generate new file with proper timestamp in name in 'db dir. Then run:

rake db:migrate 

And your app should be fine since then.

Hunk #1 FAILED at 1. What's that mean?

It is an error generated by patch. If you would open the .patch file, you'd see that it's organized in a bunch of segments, so-called "hunks". Every hunk identifies corresponding pieces of code (by line numbers) in the old and new version, the differences between those pieces of code, and similarities between them (the "context").

A hunk might fail if the similarities of a hunk don't match what's in the original file. When you see this error, it is almost always because you're using a patch for the wrong version of the code you're patching. There are a few ways to work around this:

  • Get an updated version of libdvdnav that already includes the patch (best option).
  • Get a .patch file for the version of libdvdnav you're patching.
  • Patch manually. For every hunk in the patch, try to locate the corresponding file and lines in libdvdnav, and correct them according to the instructions in the patch.
  • Take the version of libdvdnav that's closer to whatever version the .patch file was intended for (probably a bad idea).

How to get C# Enum description from value?

You can't easily do this in a generic way: you can only convert an integer to a specific type of enum. As Nicholas has shown, this is a trivial cast if you only care about one kind of enum, but if you want to write a generic method that can handle different kinds of enums, things get a bit more complicated. You want a method along the lines of:

public static string GetEnumDescription<TEnum>(int value)
{
  return GetEnumDescription((Enum)((TEnum)value));  // error!
}

but this results in a compiler error that "int can't be converted to TEnum" (and if you work around this, that "TEnum can't be converted to Enum"). So you need to fool the compiler by inserting casts to object:

public static string GetEnumDescription<TEnum>(int value)
{
  return GetEnumDescription((Enum)(object)((TEnum)(object)value));  // ugly, but works
}

You can now call this to get a description for whatever type of enum is at hand:

GetEnumDescription<MyEnum>(1);
GetEnumDescription<YourEnum>(2);

Bootstrap center heading

just use class='text-center' in element for center heading.

<h2 class="text-center">sample center heading</h2>

use class='text-left' in element for left heading, and use class='text-right' in element for right heading.

Excel VBA Automation Error: The object invoked has disconnected from its clients

I had this same problem in a large Excel 2000 spreadsheet with hundreds of lines of code. My solution was to make the Worksheet active at the beginning of the Class. I.E. ThisWorkbook.Worksheets("WorkSheetName").Activate This was finally discovered when I noticed that if "WorkSheetName" was active when starting the operation (the code) the error didn't occur. Drove me crazy for quite awhile.

TypeError: argument of type 'NoneType' is not iterable

If a function does not return anything, e.g.:

def test():
    pass

it has an implicit return value of None.

Thus, as your pick* methods do not return anything, e.g.:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")

the lines that call them, e.g.:

word = pickEasy()

set word to None, so wordInput in getInput is None. This means that:

if guess in wordInput:

is the equivalent of:

if guess in None:

and None is an instance of NoneType which does not provide iterator/iteration functionality, so you get that type error.

The fix is to add the return type:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

Can you hide the controls of a YouTube embed without enabling autoplay?

To remove you tube controls and title you can do something like this

_x000D_
_x000D_
<iframe width="560" height="315" src="https://www.youtube.com/embed/zP0Wnb9RI9Q?autoplay=1&showinfo=0&controls=0" frameborder="0" allowfullscreen ></iframe>
_x000D_
_x000D_
_x000D_

code with output

showinfo=0 is used to remove title and &controls=0 is used for remove controls like volume,play,pause,expend.

Getting time and date from timestamp with php

$timestamp='2014-11-21 16:38:00';

list($date,$time)=explode(' ',$timestamp);

// just time

preg_match("/ (\d\d:\d\d):\d\d$/",$timestamp,$match);
echo "\n<br>".$match[1];

Connecting to MySQL from Android with JDBC

public void testDB() {
        TextView tv = (TextView) this.findViewById(R.id.tv_data);
        try {

            Class.forName("com.mysql.jdbc.Driver");

            // perfect

            // localhost

            /*
             * Connection con = DriverManager .getConnection(
             * "jdbc:mysql://192.168.1.5:3306/databasename?user=root&password=123"
             * );
             */

            // online testing

            Connection con = DriverManager
                    .getConnection("jdbc:mysql://173.5.128.104:3306/vokyak_heyou?user=viowryk_hiweser&password=123");

            String result = "Database connection success\n";
            Statement st = con.createStatement();

            ResultSet rs = st.executeQuery("select * from tablename ");
            ResultSetMetaData rsmd = rs.getMetaData();

            while (rs.next()) {

                result += rsmd.getColumnName(1) + ": " + rs.getString(1) + "\n";

            }
            tv.setText(result);
        } catch (Exception e) {
            e.printStackTrace();
            tv.setText(e.toString());
        }

    }

Java - checking if parseInt throws exception

Check if it is integer parseable

public boolean isInteger(String string) {
    try {
        Integer.valueOf(string);
        return true;
    } catch (NumberFormatException e) {
        return false;
    }
}

or use Scanner

Scanner scanner = new Scanner("Test string: 12.3 dog 12345 cat 1.2E-3");

while (scanner.hasNext()) {
    if (scanner.hasNextDouble()) {
        Double doubleValue = scanner.nextDouble();
    } else {
        String stringValue = scanner.next();
    }
}

or use Regular Expression like

private static Pattern doublePattern = Pattern.compile("-?\\d+(\\.\\d*)?");

public boolean isDouble(String string) {
    return doublePattern.matcher(string).matches();
}

How do I get the dialer to open with phone number displayed?

Pretty late on the answer, but if you have a TextView that you're showing the phone number in, then you don't need to deal with intents at all, you can just use the XML attribute android:autoLink="phone" and the OS will automatically initiate an ACTION_DIAL Intent.

How do you do a limit query in JPQL or HQL?

My observation is that even you have limit in the HQL (hibernate 3.x), it will be either causing parsing error or just ignored. (if you have order by + desc/asc before limit, it will be ignored, if you don't have desc/asc before limit, it will cause parsing error)

How to hide element using Twitter Bootstrap and show it using jQuery?

?? The righter answer

In Bootstrap 4 you hide the element:

<p id="insufficient-balance-warning" class="d-none alert alert-danger">Pay me</p>

Then, sure, you could literally show it with:

if (pizzaFundsAreLow) {
  $('#insufficient-balance-warning').removeClass('d-none');
}

But if you do it the semantic way, by transferring responsibility from Bootstrap to jQuery, then you can use other jQuery niceties like fading:

if (pizzaFundsAreLow) {
  $('#insufficient-balance-warning').hide().removeClass('d-none').fadeIn();
}

How to create an array for JSON using PHP?

I created a crude and simple jsonOBJ class to use for my code. PHP does not include json functions like JavaScript/Node do. You have to iterate differently, but may be helpful.

<?php

// define a JSON Object class
class jsonOBJ {
    private $_arr;
    private $_arrName;

    function __construct($arrName){
        $this->_arrName = $arrName;
        $this->_arr[$this->_arrName] = array();

    }

    function toArray(){return $this->_arr;}
    function toString(){return json_encode($this->_arr);}

    function push($newObjectElement){
        $this->_arr[$this->_arrName][] = $newObjectElement; // array[$key]=$val;
    }

    function add($key,$val){
        $this->_arr[$this->_arrName][] = array($key=>$val);
    }
}

// create an instance of the object
$jsonObj = new jsonOBJ("locations");

// add items using one of two methods
$jsonObj->push(json_decode("{\"location\":\"TestLoc1\"}",true)); // from a JSON String
$jsonObj->push(json_decode("{\"location\":\"TestLoc2\"}",true));

$jsonObj->add("location","TestLoc3"); // from key:val pairs

echo "<pre>" . print_r($jsonObj->toArray(),1) . "</pre>";
echo "<br />" . $jsonObj->toString();
?>

Will output:

Array
(
    [locations] => Array
        (
            [0] => Array
                (
                    [location] => TestLoc1
                )

            [1] => Array
                (
                    [location] => TestLoc2
                )

            [2] => Array
                (
                    [location] => TestLoc3
                )

        )

)


{"locations":[{"location":"TestLoc1"},{"location":"TestLoc2"},{"location":"TestLoc3"}]}

To iterate, convert to a normal object:

$myObj = $jsonObj->toArray();

Then:

foreach($myObj["locations"] as $locationObj){
    echo $locationObj["location"] ."<br />";
}

Outputs:

TestLoc1
TestLoc2
TestLoc3

Access direct:

$location = $myObj["locations"][0]["location"];
$location = $myObj["locations"][1]["location"];

A practical example:

// return a JSON Object (jsonOBJ) from the rows
    function ParseRowsAsJSONObject($arrName, $rowRS){
        $jsonArr = new jsonOBJ($arrName); // name of the json array

        $rows = mysqli_num_rows($rowRS);
        if($rows > 0){
            while($rows > 0){
                $rd = mysqli_fetch_assoc($rowRS);
                $jsonArr->push($rd);
                $rows--;
            }
            mysqli_free_result($rowRS);
        }
        return $jsonArr->toArray();
    }

AngularJS: How to make angular load script inside ng-include?

I tried using Google reCAPTCHA explicitly. Here is the example:

// put somewhere in your index.html
<script type="text/javascript">
var onloadCallback = function() {
  grecaptcha.render('your-recaptcha-element', {
    'sitekey' : '6Ldcfv8SAAAAAB1DwJTM6T7qcJhVqhqtss_HzS3z'
  });
};

//link function of Angularjs directive
link: function (scope, element, attrs) {
  ...
  var domElem = '<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit" async defer></script>';
  $('#your-recaptcha-element').append($compile(domElem)(scope));
}

Forward declaration of a typedef in C++

To "fwd declare a typedef" you need to fwd declare a class or a struct and then you can typedef declared type. Multiple identical typedefs are acceptable by compiler.

long form:

class MyClass;
typedef MyClass myclass_t;

short form:

typedef class MyClass myclass_t;

How to execute a shell script on a remote server using Ansible?

you can use script module

Example

- name: Transfer and execute a script.
  hosts: all
  tasks:

     - name: Copy and Execute the script 
       script: /home/user/userScript.sh

jquery: animate scrollLeft

You'll want something like this:


$("#next").click(function(){
      var currentElement = currentElement.next();
      $('html, body').animate({scrollLeft: $(currentElement).offset().left}, 800);
      return false;
   }); 
I believe this should work, it's adopted from a scrollTop function.

How do I keep two side-by-side divs the same height?

I was having the same problem so i created this small function using jquery as jquery is part of every web application nowadays.

function fEqualizeHeight(sSelector) {
    var sObjects = $(sSelector);

    var iCount = sObjects.length;

    var iHeights = [];

    if (iCount > 0) {
        $(sObjects).each(function () {
            var sHeight = $(this).css('height');
            var iHeight = parseInt(sHeight.replace(/px/i,''));
            iHeights.push(iHeight);
        });

        iHeights.sort(function (a, b) {
            return a - b
        });

        var iMaxHeight = iHeights.pop();

        $(sSelector).each(function () {
            $(this).css({
                'height': iMaxHeight + 'px'
            });
        });
    }
}

You can call this function on page ready event

$(document).ready(function(){
   fEqualizeHeight('.columns');
});

I hope this works for you.

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

JavaScript is object-oriented, but it's radically different than other OOP languages like Java, C# or C++. Don't try to understand it like that. Throw that old knowledge out and start anew. JavaScript needs a different thinking.

I'd suggest to get a good manual or something on the subject. I myself found ExtJS Tutorials the best for me, although I haven't used the framework before or after reading it. But it does give a good explanation about what is what in JavaScript world. Sorry, it seems that that content has been removed. Here's a link to archive.org copy instead. Works today. :P

How to merge two arrays in JavaScript and de-duplicate items

If you do not want duplicates of a specific property (for example the ID)

let noDuplicate = array1.filter ( i => array2.findIndex(a => i.id==a.id)==-1 );
let result = [...noDuplicate, ...array2];

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

Before and After Suite execution hook in jUnit 4.x

Yes, it is possible to reliably run set up and tear down methods before and after any tests in a test suite. Let me demonstrate in code:

package com.test;

import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;

@RunWith(Suite.class)
@SuiteClasses({Test1.class, Test2.class})
public class TestSuite {

    @BeforeClass
    public static void setUp() {
        System.out.println("setting up");
    }

    @AfterClass
    public static void tearDown() {
        System.out.println("tearing down");
    }

}

So your Test1 class would look something like:

package com.test;

import org.junit.Test;


public class Test1 {
    @Test
    public void test1() {
        System.out.println("test1");
    }

}

...and you can imagine that Test2 looks similar. If you ran TestSuite, you would get:

setting up
test1
test2
tearing down

So you can see that the set up/tear down only run before and after all tests, respectively.

The catch: this only works if you're running the test suite, and not running Test1 and Test2 as individual JUnit tests. You mentioned you're using maven, and the maven surefire plugin likes to run tests individually, and not part of a suite. In this case, I would recommend creating a superclass that each test class extends. The superclass then contains the annotated @BeforeClass and @AfterClass methods. Although not quite as clean as the above method, I think it will work for you.

As for the problem with failed tests, you can set maven.test.error.ignore so that the build continues on failed tests. This is not recommended as a continuing practice, but it should get you functioning until all of your tests pass. For more detail, see the maven surefire documentation.

Javascript can't find element by id?

How will the browser know when to run the code inside script tag? So, to make the code run after the window is loaded completely,

window.onload = doStuff;

function doStuff() {
    var e = document.getElementById("db_info");
    e.innerHTML='Found you';
}

The other alternative is to keep your <script...</script> just before the closing </body> tag.

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

It appears that iOS 9.0.2 breaks requests to valid HTTPS endpoints. My current suspicion is that it is requiring SHA-256 certs or it fails with this error.

To reproduce, inspect your UIWebView with safari, and try navigating to an arbitrary HTTPS endpoint:

location.href = "https://d37gvrvc0wt4s1.cloudfront.net/js/v1.4/rollbar.min.js"
// [Error] Failed to load resource: An SSL error has occurred and a secure connection to the server cannot be made. (rollbar.min.js, line 0)

Now try going to google (because of course they have a SHA-256 cert):

location.href = "https://google.com"
// no problemo

Adding an exception to transport security (as outlined by @stéphane-bruckert's answer above) works to fix this. I also assume that completely disabling NSAppTransportSecurity would work too, though I've read that completely disabling it can jeopardize your app review.

[EDIT] I've found that simply enumerating the domains I'm connecting to in the NSExceptionDomains dict fixes this problem, even when leaving NSExceptionAllowsInsecureHTTPLoads set to true. :\

MySQL Multiple Joins in one query?

You can simply add another join like this:

SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data 
    INNER JOIN dashboard_messages 
        ON dashboard_message_id = dashboard_messages.id
    INNER JOIN images
        ON dashboard_messages.image_id = images.image_id 

However be aware that, because it is an INNER JOIN, if you have a message without an image, the entire row will be skipped. If this is a possibility, you may want to do a LEFT OUTER JOIN which will return all your dashboard messages and an image_filename only if one exists (otherwise you'll get a null)

SELECT dashboard_data.headline, dashboard_data.message, dashboard_messages.image_id, images.filename
FROM dashboard_data 
    INNER JOIN dashboard_messages 
        ON dashboard_message_id = dashboard_messages.id
    LEFT OUTER JOIN images
        ON dashboard_messages.image_id = images.image_id 

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

json.dumps vs flask.jsonify

consider

data={'fld':'hello'}

now

jsonify(data)

will yield {'fld':'hello'} and

json.dumps(data)

gives

"<html><body><p>{'fld':'hello'}</p></body></html>"

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

Check if Variable is Empty - Angular 2

if( myVariable ) 
{ 
    //mayVariable is not : 
    //null 
    //undefined 
    //NaN 
    //empty string ("") 
    //0 
    //false 
}

"Could not find acceptable representation" using spring-boot-starter-web

accepted answer is not right with Spring 5. try changing your URL of your web service to .json! that is the right fix. great details here http://stick2code.blogspot.com/2014/03/solved-orgspringframeworkwebhttpmediaty.html

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

Josh says: "....Something to keep in mind when you are using Unicode although you can store different languages in a single column you can only sort using a single collation. There are some languages that use latin characters but do not sort like other latin languages. Accents is a good example of this, I can't remeber the example but there was a eastern european language whose Y didn't sort like the English Y. Then there is the spanish ch which spanish users expet to be sorted after h."

I'm a native Spanish Speaker and "ch" is not a letter but two "c" and "h" and the Spanish alphabet is like: abcdefghijklmn ñ opqrstuvwxyz We don't expect "ch" after "h" but "i" The alphabet is the same as in English except for the ñ or in HTML "&ntilde ;"

Alex

Jquery Ajax Loading image

Description

You should do this using jQuery.ajaxStart and jQuery.ajaxStop.

  1. Create a div with your image
  2. Make it visible in jQuery.ajaxStart
  3. Hide it in jQuery.ajaxStop

Sample

<div id="loading" style="display:none">Your Image</div>

<script src="../../Scripts/jquery-1.5.1.min.js" type="text/javascript"></script>
<script>
    $(function () {
        var loading = $("#loading");
        $(document).ajaxStart(function () {
            loading.show();
        });

        $(document).ajaxStop(function () {
            loading.hide();
        });

        $("#startAjaxRequest").click(function () {
            $.ajax({
                url: "http://www.google.com",
                // ... 
            });
        });
    });
</script>

<button id="startAjaxRequest">Start</button>

More Information

How is a non-breaking space represented in a JavaScript string?

Remember that .text() strips out markup, thus I don't believe you're going to find &nbsp; in a non-markup result.

Made in to an answer....

var p = $('<p>').html('&nbsp;');
if (p.text() == String.fromCharCode(160) && p.text() == '\xA0')
    alert('Character 160');

Shows an alert, as the ASCII equivalent of the markup is returned instead.

How to install and use "make" in Windows?

  1. Install Msys2 http://www.msys2.org
  2. Follow installation instructions
  3. Install make with $ pacman -S make gettext base-devel
  4. Add C:\msys64\usr\bin\ to your path

Bad Request - Invalid Hostname IIS7

For Visual Studio 2017 and Visual Studio 2015, IIS Express settings is stored in the hidden .vs directory and the path is something like this .vs\config\applicationhost.config, add binding like below will work

<bindings>
    <binding protocol="http" bindingInformation="*:8802:localhost" />
    <binding protocol="http" bindingInformation="*:8802:127.0.0.1" />
</bindings>

Syntax: https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.administration.binding.bindinginformation?view=iis-dotnet

How can I read numeric strings in Excel cells as string (not numbers)?

This worked perfect for me.

Double legacyRow = row.getCell(col).getNumericCellValue();
String legacyRowStr = legacyRow.toString();
if(legacyRowStr.contains(".0")){
    legacyRowStr = legacyRowStr.substring(0, legacyRowStr.length()-2);
}

How to modify values of JsonObject / JsonArray directly?

Strangely, the answer is to keep adding back the property. I was half expecting a setter method. :S

System.out.println("Before: " + obj.get("DebugLogId")); // original "02352"

obj.addProperty("DebugLogId", "YYY");

System.out.println("After: " + obj.get("DebugLogId")); // now "YYY"

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

To produce the same results:

MessageDigest sha1 = MessageDigest.getInstance("SHA1", BOUNCY_CASTLE_PROVIDER);
byte[] digest = sha1.digest(content);
DERObjectIdentifier sha1oid_ = new DERObjectIdentifier("1.3.14.3.2.26");

AlgorithmIdentifier sha1aid_ = new AlgorithmIdentifier(sha1oid_, null);
DigestInfo di = new DigestInfo(sha1aid_, digest);

byte[] plainSig = di.getDEREncoded();
Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding", BOUNCY_CASTLE_PROVIDER);
cipher.init(Cipher.ENCRYPT_MODE, privateKey);
byte[] signature = cipher.doFinal(plainSig);

SQL How to Select the most recent date item

Select Top 1* FROM test_table WHERE user_id = value order by Date_Added Desc

Reset push notification settings for app

I have wondered about this in the past and came to the conclusion that it was not actually a valid test case for my code. I don't think your application code can actually tell the difference between somebody declining notifications the first time or later disabling it from the iPhone notification settings. It is true that the user experience is different but that is hidden inside the call to registerForRemoteNotificationTypes.

Calling unregisterForRemoteNotifications does not completely remove the application from the notifications settings - though it does remove the contents of the settings for that application. So this still will not cause the dialog to be presented a second time to the user the next time the app runs (at least not on v3.1.3 that I am currently testing with). But as I say above you probably should not be worrying about that.

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

Use next:

(1..10).each do |a|
  next if a.even?
  puts a
end

prints:

1
3   
5
7
9

For additional coolness check out also redo and retry.

Works also for friends like times, upto, downto, each_with_index, select, map and other iterators (and more generally blocks).

For more info see http://ruby-doc.org/docs/ProgrammingRuby/html/tut_expressions.html#UL.

How to retrieve field names from temporary table (SQL Server 2008)

you can do it by following way too ..

create table #test (a int, b char(1))

select * From #test

exec tempdb..sp_columns '#test'

Storing and Retrieving ArrayList values from hashmap

You can use like this(Though the random number generator logic is not upto the mark)

public class WorkSheet {
    HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();

public static void main(String args[]) {
    WorkSheet test = new WorkSheet();
    test.inputData("mango", 5);
    test.inputData("apple", 2);
    test.inputData("grapes", 2);
    test.inputData("peach", 3);
    test.displayData();

}
public void displayData(){
    for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
        System.out.print(entry.getKey()+" | ");
        for(int fruitNo : entry.getValue()){
            System.out.print(fruitNo+" ");
        }
        System.out.println();
    }
}
public void inputData(String name ,int number) {
    Random rndData = new Random();
    ArrayList<Integer> fruit = new ArrayList<Integer>();
    for(int i=0 ; i<number ; i++){
        fruit.add(rndData.nextInt(10));
    }
    map.put(name, fruit);
}
}

OUTPUT

grapes | 7 5 
apple | 9 5 
peach | 5 5 8 
mango | 4 7 1 5 5 

Postgresql - select something where date = "01/01/11"

With PostgreSQL there are a number of date/time functions available, see here.

In your example, you could use:

SELECT * FROM myTable WHERE date_trunc('day', dt) = 'YYYY-MM-DD';

If you are running this query regularly, it is possible to create an index using the date_trunc function as well:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt) );

One advantage of this is there is some more flexibility with timezones if required, for example:

CREATE INDEX date_trunc_dt_idx ON myTable ( date_trunc('day', dt at time zone 'Australia/Sydney') );
SELECT * FROM myTable WHERE date_trunc('day', dt at time zone 'Australia/Sydney') = 'YYYY-MM-DD';

How can I remove an SSH key?

I can confirm that this bug is still present in Ubuntu 19.04 (Disco Dingo). The workaround suggested by VonC worked perfectly, summarizing for my version:

  • Click on Activities tab on top left corner
  • On the search box that comes up, begin typing "startup applications"
  • Click on the "Startup Applications" icon
  • On the box that pops up, select the gnome key ring manager application (can't remember the exact name on the GUI but it is distinctive enough) and remove it.

Next, I tried ssh-add -D again, and after reboot ssh-add -l told me The agent has no identities. I confirmed that I still had the ssh-agent daemon running with ps aux | grep agent. So I added the key I most frequently used with GitHub (ssh-add ~/.ssh/id_ecdsa) and all was good!

Now I can do the normal operations with my most frequently used repository, and if I occasionally require access to the other repository which uses the RSA key, I just dedicate one terminal for it with export GIT_SSH_COMMAND="ssh -i /home/me/.ssh/id_rsa.pub". Solved! Credit goes to VonC for pointing out the bug and the solution.

javascript: get a function's variable's value within another function

Your nameContent scope is only inside first function. You'll never get it's value that way.

var nameContent; // now it's global!
function first(){
    nameContent = document.getElementById('full_name').value;
}

function second() {
    first(); 
    y=nameContent; 
    alert(y);
}
second();

how to install apk application from my pc to my mobile android

C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>adb install com.lge.filemanager-15052-v3.1.15052.apk
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
2683 KB/s (3159508 bytes in 1.150s)
pkg: /data/local/tmp/com.lge.filemanager-15052-v3.1.15052.apk
Success

C:\Program Files (x86)\LG Electronics\LG PC Suite\adb>

We can use the adb.exe which is there in PC suit, it worked for me. Thanks Chethan

how to use "tab space" while writing in text file

Use "\t". That's the tab space character.

You can find a list of many of the Java escape characters here: http://java.sun.com/docs/books/tutorial/java/data/characters.html

What does $1 [QSA,L] mean in my .htaccess file?

Not the place to give a complete tutorial, but here it is in short;

RewriteCond basically means "execute the next RewriteRule only if this is true". The !-l path is the condition that the request is not for a link (! means not, -l means link)

The RewriteRule basically means that if the request is done that matches ^(.+)$ (matches any URL except the server root), it will be rewritten as index.php?url=$1 which means a request for ollewill be rewritten as index.php?url=olle).

QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1 will be rewritten as index.php?url=olle&p=1.

L means if the rule matches, don't process any more RewriteRules below this one.

For more complete info on this, follow the links above. The rewrite support can be a bit hard to grasp, but there are quite a few examples on stackoverflow to learn from.

python: creating list from string

If you need to convert some of them to numbers and don't know in advance which ones, some additional code will be needed. Try something like this:

b = []
for x in a:
    temp = []
    items = x.split(",")
    for item in items:
        try:
            n = int(item)
        except ValueError:
            temp.append(item)
        else:
            temp.append(n)
    b.append(temp)

This is longer than the other answers, but it's more versatile.

How to set a radio button in Android

If you want to do it in code, you can call the check member of RadioGroup:

radioGroup.check(R.id.radioButtonId);

This will check the button you specify and uncheck the others.

Command-line Unix ASCII-based charting / plotting tool

Here is my patch for eplot that adds a -T option for terminal output:

--- eplot       2008-07-09 16:50:04.000000000 -0400
+++ eplot+      2017-02-02 13:20:23.551353793 -0500
@@ -172,7 +172,10 @@
                                        com=com+"set terminal postscript color;\n"
                                        @o["DoPDF"]=true

-                               # ---- Specify a custom output file
+                               when /^-T$|^--terminal$/
+                                       com=com+"set terminal dumb;\n"
+
+                                # ---- Specify a custom output file
                                when /^-o$|^--output$/
                                        @o["OutputFileSpecified"]=checkOptArg(xargv,i)
                                        i=i+1

                                    i=i+1

Using this you can run it as eplot -T to get ASCII-graphics result instead of a gnuplot window.

Creating a div element in jQuery

You can use append (to add at last position of parent) or prepend (to add at fist position of parent):

$('#parent').append('<div>hello</div>');    
// or
$('<div>hello</div>').appendTo('#parent');

Alternatively, you can use the .html() or .add() as mentioned in a different answer.

Invalid date in safari

The same problem facing in Safari and it was solved by inserting this in web page

 <script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=Intl.~locale.en"></script> 

Hope it will work also your case too

Thanks

How do I update a model value in JavaScript in a Razor view?

The model (@Model) only exists while the page is being constructed. Once the page is rendered in the browser, all that exists is HTML, JavaScript and CSS.

What you will want to do is put the PostID in a hidden field. As the PostID value is fixed, there actually is no need for JavaScript. A simple @HtmlHiddenFor will suffice.

However, you will want to change your foreach loop to a for loop. The final solution will look something like this:

for (int i = 0 ; i < Model.Post; i++)
{
    <br/>
    <b>Posted by :</b> @Model.Post[i].Username <br/>
    <span>@Model.Post[i].Content</span> <br/>
    if(Model.loginuser == Model.username)
    {
        @Html.HiddenFor(model => model.Post[i].PostID)
        @Html.TextAreaFor(model => model.addcomment.Content)
        <button type="submit">Add Comment</button>
    }
}

How do I compute the intersection point of two lines?

If your lines are multiple points instead, you can use this version.

enter image description here

import numpy as np
import matplotlib.pyplot as plt
"""
Sukhbinder
5 April 2017
Based on:    
"""

def _rect_inter_inner(x1,x2):
    n1=x1.shape[0]-1
    n2=x2.shape[0]-1
    X1=np.c_[x1[:-1],x1[1:]]
    X2=np.c_[x2[:-1],x2[1:]]    
    S1=np.tile(X1.min(axis=1),(n2,1)).T
    S2=np.tile(X2.max(axis=1),(n1,1))
    S3=np.tile(X1.max(axis=1),(n2,1)).T
    S4=np.tile(X2.min(axis=1),(n1,1))
    return S1,S2,S3,S4

def _rectangle_intersection_(x1,y1,x2,y2):
    S1,S2,S3,S4=_rect_inter_inner(x1,x2)
    S5,S6,S7,S8=_rect_inter_inner(y1,y2)

    C1=np.less_equal(S1,S2)
    C2=np.greater_equal(S3,S4)
    C3=np.less_equal(S5,S6)
    C4=np.greater_equal(S7,S8)

    ii,jj=np.nonzero(C1 & C2 & C3 & C4)
    return ii,jj

def intersection(x1,y1,x2,y2):
    """
INTERSECTIONS Intersections of curves.
   Computes the (x,y) locations where two curves intersect.  The curves
   can be broken with NaNs or have vertical segments.
usage:
x,y=intersection(x1,y1,x2,y2)
    Example:
    a, b = 1, 2
    phi = np.linspace(3, 10, 100)
    x1 = a*phi - b*np.sin(phi)
    y1 = a - b*np.cos(phi)
    x2=phi    
    y2=np.sin(phi)+2
    x,y=intersection(x1,y1,x2,y2)
    plt.plot(x1,y1,c='r')
    plt.plot(x2,y2,c='g')
    plt.plot(x,y,'*k')
    plt.show()
    """
    ii,jj=_rectangle_intersection_(x1,y1,x2,y2)
    n=len(ii)

    dxy1=np.diff(np.c_[x1,y1],axis=0)
    dxy2=np.diff(np.c_[x2,y2],axis=0)

    T=np.zeros((4,n))
    AA=np.zeros((4,4,n))
    AA[0:2,2,:]=-1
    AA[2:4,3,:]=-1
    AA[0::2,0,:]=dxy1[ii,:].T
    AA[1::2,1,:]=dxy2[jj,:].T

    BB=np.zeros((4,n))
    BB[0,:]=-x1[ii].ravel()
    BB[1,:]=-x2[jj].ravel()
    BB[2,:]=-y1[ii].ravel()
    BB[3,:]=-y2[jj].ravel()

    for i in range(n):
        try:
            T[:,i]=np.linalg.solve(AA[:,:,i],BB[:,i])
        except:
            T[:,i]=np.NaN


    in_range= (T[0,:] >=0) & (T[1,:] >=0) & (T[0,:] <=1) & (T[1,:] <=1)

    xy0=T[2:,in_range]
    xy0=xy0.T
    return xy0[:,0],xy0[:,1]


if __name__ == '__main__':

    # a piece of a prolate cycloid, and am going to find
    a, b = 1, 2
    phi = np.linspace(3, 10, 100)
    x1 = a*phi - b*np.sin(phi)
    y1 = a - b*np.cos(phi)

    x2=phi
    y2=np.sin(phi)+2
    x,y=intersection(x1,y1,x2,y2)
    plt.plot(x1,y1,c='r')
    plt.plot(x2,y2,c='g')
    plt.plot(x,y,'*k')
    plt.show()

Is it correct to use alt tag for an anchor link?

"title" is widely implemented in browsers. Try:

<a href="#" title="hello">asf</a>

Beginner question: returning a boolean value from a function in Python

Ignoring the refactoring issues, you need to understand functions and return values. You don't need a global at all. Ever. You can do this:

def rps():
    # Code to determine if player wins
    if player_wins:
        return True

    return False

Then, just assign a value to the variable outside this function like so:

player_wins = rps()

It will be assigned the return value (either True or False) of the function you just called.


After the comments, I decided to add that idiomatically, this would be better expressed thus:

 def rps(): 
     # Code to determine if player wins, assigning a boolean value (True or False)
     # to the variable player_wins.

     return player_wins

 pw = rps()

This assigns the boolean value of player_wins (inside the function) to the pw variable outside the function.

Handling NULL values in Hive

I use below sql to exclude the null string and empty string lines.

select * from table where length(nvl(column1,0))>0

Because, the length of empty string is 0.

select length('');
+-----------+--+
| length()  |
+-----------+--+
| 0         |
+-----------+--+

What is the difference between a JavaBean and a POJO?

All JavaBeans are POJOs but not all POJOs are JavaBeans.

A JavaBean is a Java object that satisfies certain programming conventions:

  • the JavaBean class must implement either Serializable or Externalizable;
  • the JavaBean class must have a public no-arg constructor;
  • all JavaBean properties must have public setter and getter methods (as appropriate);
  • all JavaBean instance variables should be private.

How do I Merge two Arrays in VBA?

To join Array1 and Array2, create a new array say JointArray

Dim JointArray As Variant
ReDim JointArray(UBound(Array1) + UBound(Array2) + 1) As Variant
For i = 0 To UBound(JointArray)
    If i <= UBound(Array1) Then
    JointArray(i) = Array1(i)
    Else
    JointArray(i) = Array2(i - UBound(Array1) - 1)
    End If
Next

Convert python datetime to timestamp in milliseconds

For Python2.7

You can format it into seconds and then multiply by 1000 to convert to millisecond.

from datetime import datetime

d = datetime.strptime("20.12.2016 09:38:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s')
d_in_ms = int(d)*1000
print(d_in_ms)

print(datetime.fromtimestamp(float(d)))

Output:

1482206922000
2016-12-20 09:38:42

Eclipse keyboard shortcut to indent source code to the left?

On Mac (on french keyboard its) cmd + shift + F

LaTeX: remove blank page after a \part or \chapter

You don't say what class you are using, but I'm guessing it is the standard book. In which case the page clearing is a feature of he class which you can override as Mica suggests, or solve by switching to another class. The standard report class is similar to book, or the memoir class is an improved book and is very flexible indeed.

How can I get the named parameters from a URL using Flask?

Use request.args to get parsed contents of query string:

from flask import request

@app.route(...)
def login():
    username = request.args.get('username')
    password = request.args.get('password')

Java maximum memory on Windows XP

I think it has more to do with how Windows is configured as hinted by this response: Java -Xmx Option

Some more testing: I was able to allocate 1300MB on an old Windows XP machine with only 768MB physical RAM (plus virtual memory). On my 2GB RAM machine I can only get 1220MB. On various other corporate machines (with older Windows XP) I was able to get 1400MB. The machine with a 1220MB limit is pretty new (just purchased from Dell), so maybe it has newer (and more bloated) Windows and DLLs (it's running Window XP Pro Version 2002 SP2).

what happens when you type in a URL in browser

Attention: this is an extremely rough and oversimplified sketch, assuming the simplest possible HTTP request (no HTTPS, no HTTP2, no extras), simplest possible DNS, no proxies, single-stack IPv4, one HTTP request only, a simple HTTP server on the other end, and no problems in any step. This is, for most contemporary intents and purposes, an unrealistic scenario; all of these are far more complex in actual use, and the tech stack has become an order of magnitude more complicated since this was written. With this in mind, the following timeline is still somewhat valid:

  1. browser checks cache; if requested object is in cache and is fresh, skip to #9
  2. browser asks OS for server's IP address
  3. OS makes a DNS lookup and replies the IP address to the browser
  4. browser opens a TCP connection to server (this step is much more complex with HTTPS)
  5. browser sends the HTTP request through TCP connection
  6. browser receives HTTP response and may close the TCP connection, or reuse it for another request
  7. browser checks if the response is a redirect or a conditional response (3xx result status codes), authorization request (401), error (4xx and 5xx), etc.; these are handled differently from normal responses (2xx)
  8. if cacheable, response is stored in cache
  9. browser decodes response (e.g. if it's gzipped)
  10. browser determines what to do with response (e.g. is it a HTML page, is it an image, is it a sound clip?)
  11. browser renders response, or offers a download dialog for unrecognized types

Again, discussion of each of these points have filled countless pages; take this only as a summary, abridged for the sake of clarity. Also, there are many other things happening in parallel to this (processing typed-in address, speculative prefetching, adding page to browser history, displaying progress to user, notifying plugins and extensions, rendering the page while it's downloading, pipelining, connection tracking for keep-alive, cookie management, checking for malicious content etc.) - and the whole operation gets an order of magnitude more complex with HTTPS (certificates and ciphers and pinning, oh my!).

string comparison in batch file

Just put quotes around the Environment variable (as you have done) :
if "%DevEnvDir%" == "C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\"
but it's the way you put opening bracket without a space that is confusing it.

Works for me...

C:\if "%gtk_basepath%" == "C:\Program Files\GtkSharp\2.12\" (echo yes)
yes

How do I assert equality on two classes without an equals method?

You can use reflection to "automate" the full equality testing. you can implement the equality "tracking" code you wrote for a single field, then use reflection to run that test on all fields in the object.

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

In addition to the answers above, you can check the type of object using type(plt.subplots()) which returns a tuple, on the other hand, type(plt.subplot()) returns matplotlib.axes._subplots.AxesSubplot which you can't unpack.

Restore a postgres backup file using the command line?

If you have a backup SQL file then you can easily Restore it. Just follow the instructions, given in the below

1. At first, create a database using pgAdmin or whatever you want (for example my_db is our created db name)
2. Now Open command line window
3. Go to Postgres bin folder. For example:  cd "C:\ProgramFiles\PostgreSQL\pg10\bin"
4. Enter the following command to restore your database: psql.exe -U postgres -d my_db -f D:\Backup\backup_file_name.sql 

Type password for your postgres user if needed and let Postgres to do its work. Then you can check the restore process.

Show a div as a modal pop up

A simple modal pop up div or dialog box can be done by CSS properties and little bit of jQuery.The basic idea is simple:

  • 1. Create a div with semi transparent background & show it on top of your content page on click.
  • 2. Show your pop up div or alert div on top of the semi transparent dimming/hiding div.
  • So we need three divs:

  • content(main content of the site).
  • hider(To dim the content).
  • popup_box(the modal div to display).

    First let us define the CSS:

        #hider
        {
            position:absolute;
            top: 0%;
            left: 0%;
            width:1600px;
            height:2000px;
            margin-top: -800px; /*set to a negative number 1/2 of your height*/
            margin-left: -500px; /*set to a negative number 1/2 of your width*/
            /*
            z- index must be lower than pop up box
           */
            z-index: 99;
           background-color:Black;
           //for transparency
           opacity:0.6;
        }
    
        #popup_box  
        {
    
        position:absolute;
            top: 50%;
            left: 50%;
            width:10em;
            height:10em;
            margin-top: -5em; /*set to a negative number 1/2 of your height*/
            margin-left: -5em; /*set to a negative number 1/2 of your width*/
            border: 1px solid #ccc;
            border:  2px solid black;
            z-index:100; 
    
        }
    

    It is important that we set our hider div's z-index lower than pop_up box as we want to show popup_box on top.
    Here comes the java Script:

            $(document).ready(function () {
            //hide hider and popup_box
            $("#hider").hide();
            $("#popup_box").hide();
    
            //on click show the hider div and the message
            $("#showpopup").click(function () {
                $("#hider").fadeIn("slow");
                $('#popup_box').fadeIn("slow");
            });
            //on click hide the message and the
            $("#buttonClose").click(function () {
    
                $("#hider").fadeOut("slow");
                $('#popup_box').fadeOut("slow");
            });
    
            });
    

    And finally the HTML:

    <div id="hider"></div>
    <div id="popup_box">
        Message<br />
        <a id="buttonClose">Close</a>
    </div>    
    <div id="content">
        Page's main content.<br />
        <a id="showpopup">ClickMe</a>
    </div>
    

    I have used jquery-1.4.1.min.js www.jquery.com/download and tested the code in Firefox. Hope this helps.

  • scp copy directory to another server with private key auth

    or you can also do ( for pem file )

     scp -r -i file.pem [email protected]:/home/backup /home/user/Desktop/
    

    Access mysql remote database from command line

    Try this command mysql -uuser -hhostname -PPORT -ppassword.

    I faced a similar situation and later when mysql port for host was entered with the command, it was solved.

    How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

    I'm not sure why you're avoiding the AND clause. It is the simplest solution.

    Otherwise, you would need to do an INTERSECT of multiple queries:

    SELECT word FROM table WHERE word NOT LIKE '%a%'
    INTERSECT
    SELECT word FROM table WHERE word NOT LIKE '%b%'
    INTERSECT
    SELECT word FROM table WHERE word NOT LIKE '%c%';
    

    Alternatively, you can use a regular expression if your version of SQL supports it.

    Excluding Maven dependencies

    Global exclusions look like they're being worked on, but until then...

    From the Sonatype maven reference (bottom of the page):

    Dependency management in a top-level POM is different from just defining a dependency on a widely shared parent POM. For starters, all dependencies are inherited. If mysql-connector-java were listed as a dependency of the top-level parent project, every single project in the hierarchy would have a reference to this dependency. Instead of adding in unnecessary dependencies, using dependencyManagement allows you to consolidate and centralize the management of dependency versions without adding dependencies which are inherited by all children. In other words, the dependencyManagement element is equivalent to an environment variable which allows you to declare a dependency anywhere below a project without specifying a version number.

    As an example:

      <dependencies>
        <dependency>
          <groupId>commons-httpclient</groupId>
          <artifactId>commons-httpclient</artifactId>
          <version>3.1</version>
        </dependency>
        <dependency>
          <groupId>org.springframework</groupId>
          <artifactId>spring-beans</artifactId>
          <version>3.0.5.RELEASE</version>
        </dependency>
      </dependencies>
      <dependencyManagement>
        <dependencies>
          <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <exclusions>
              <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
              </exclusion>
            </exclusions>
          </dependency>
          <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <exclusions>
              <exclusion>
                <groupId>commons-logging</groupId>
                <artifactId>commons-logging</artifactId>
              </exclusion>
            </exclusions>
          </dependency>
        </dependencies>
      </dependencyManagement>
    

    It doesn't make the code less verbose overall, but it does make it less verbose where it counts. If you still want it less verbose you can follow these tips also from the Sonatype reference.

    How to convert an ASCII character into an int in C

    It is not possible with the C99 standard library, unless you manually write a map from character constants to the corresponding ASCII int value.

    Character constants in C like 'a' are not guaranteed to be ASCII.

    C99 only makes some guarantees about those constants, e.g. that digits be contiguous.

    The word ASCII only appears on the C99 N1256 standard draft in footer notes, and footer note 173) says:

    In an implementation that uses the seven-bit US ASCII character set, the printing characters are those whose values lie from 0x20 (space) through 0x7E (tilde); the control characters are those whose values lie from 0 (NUL) through 0x1F (US), and the character 0x7F (DEL).

    implying that ASCII is not the only possibility

    jquery input select all on focus

    This would do the work and avoid the issue that you can no longer select part of the text by mouse.

    $("input[type=text]").click(function() {
        if(!$(this).hasClass("selected")) {
            $(this).select();
            $(this).addClass("selected");
        }
    });
    $("input[type=text]").blur(function() {
        if($(this).hasClass("selected")) {
            $(this).removeClass("selected");
        }
    });
    

    How can I escape square brackets in a LIKE clause?

    Here is what I actually used:

    like 'WC![R]S123456' ESCAPE '!'
    

    What is the difference between partitioning and bucketing a table in Hive ?

    I think I am late in answering this question, but it keep coming up in my feed.

    Navneet has provided excellent answer. Adding to it visually.

    Partitioning helps in elimination of data, if used in WHERE clause, where as bucketing helps in organizing data in each partition into multiple files, so as same set of data is always written in same bucket. Helps a lot in joining of columns.

    Suppose, you have a table with five columns, name, server_date, some_col3, some_col4 and some_col5. Suppose, you have partitioned the table on server_date and bucketed on name column in 10 buckets, your file structure will look something like below.

    1. server_date=xyz
      • 00000_0
      • 00001_0
      • 00002_0
      • ........
      • 00010_0

    Here server_date=xyz is the partition and 000 files are the buckets in each partition. Buckets are calculated based on some hash functions, so rows with name=Sandy will always go in same bucket.

    print arraylist element?

    You should override toString() method in your Dog class. which will be called when you use this object in sysout.

    VBA for clear value in specific range of cell and protected cell from being wash away formula

    Try this

    Sheets("your sheetname").range("A5:X50").Value = ""
    

    You can also use

    ActiveSheet.range
    

    Apache error: _default_ virtualhost overlap on port 443

    I ran into this problem because I had multiple wildcard entries for the same ports. You can easily check this by executing apache2ctl -S:

    # apache2ctl -S
    [Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 30000, the first has precedence
    [Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 20001, the first has precedence
    VirtualHost configuration:
    11.22.33.44:80       is a NameVirtualHost
             default server xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
             port 80 namevhost xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
             [...]
    11.22.33.44:443      is a NameVirtualHost
             default server yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
             port 443 namevhost yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
    wildcard NameVirtualHosts and _default_ servers:
    *:80                   hostname.com (/etc/apache2/sites-enabled/000-default:1)
    *:20001                hostname.com (/etc/apache2/sites-enabled/000-default:33)
    *:30000                hostname.com (/etc/apache2/sites-enabled/000-default:57)
    _default_:443          hostname.com (/etc/apache2/sites-enabled/default-ssl:2)
    *:20001                hostname.com (/etc/apache2/sites-enabled/default-ssl:163)
    *:30000                hostname.com (/etc/apache2/sites-enabled/default-ssl:178)
    Syntax OK
    

    Notice how at the beginning of the output are a couple of warning lines. These will indicate which ports are creating the problems (however you probably already knew that).

    Next, look at the end of the output and you can see exactly which files and lines the virtualhosts are defined that are creating the problem. In the above example, port 20001 is assigned both in /etc/apache2/sites-enabled/000-default on line 33 and /etc/apache2/sites-enabled/default-ssl on line 163. Likewise *:30000 is listed in 2 places. The solution (in my case) was simply to delete one of the entries.

    How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

    I do the "in clause" query with spring jdbc like this:

    String sql = "SELECT bg.goodsid FROM beiker_goods bg WHERE bg.goodsid IN (:goodsid)";
    
    List ids = Arrays.asList(new Integer[]{12496,12497,12498,12499});
    Map<String, List> paramMap = Collections.singletonMap("goodsid", ids);
    NamedParameterJdbcTemplate template = 
        new NamedParameterJdbcTemplate(getJdbcTemplate().getDataSource());
    
    List<Long> list = template.queryForList(sql, paramMap, Long.class);
    

    When to encode space to plus (+) or %20?

    Its better to always encode spaces as %20, not as "+".

    It was RFC-1866 (HTML 2.0 specification), which specified that space characters should be encoded as "+" in "application/x-www-form-urlencoded" content-type key-value pairs. (see paragraph 8.2.1. subparagraph 1.). This way of encoding form data is also given in later HTML specifications, look for relevant paragraphs about application/x-www-form-urlencoded.

    Here is an example of such a string in URL where RFC-1866 allows encoding spaces as pluses: "http://example.com/over/there?name=foo+bar". So, only after "?", spaces can be replaced by pluses, according to RFC-1866. In other cases, spaces should be encoded to %20. But since it's hard to determine the context, it's the best practice to never encode spaces as "+".

    I would recommend to percent-encode all character except "unreserved" defined in RFC-3986, p.2.3

    unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
    

    Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

    After some research I understand - I have very similar, but different root project locations and its cached in /bootstrap/cache. After cache clearing project started.

    Split string with PowerShell and do something with each token

    To complement Justus Thane's helpful answer:

    • As Joey notes in a comment, PowerShell has a powerful, regex-based -split operator.

      • In its unary form (-split '...'), -split behaves like awk's default field splitting, which means that:
        • Leading and trailing whitespace is ignored.
        • Any run of whitespace (e.g., multiple adjacent spaces) is treated as a single separator.
    • In PowerShell v4+ an expression-based - and therefore faster - alternative to the ForEach-Object cmdlet became available: the .ForEach() array (collection) method, as described in this blog post (alongside the .Where() method, a more powerful, expression-based alternative to Where-Object).

    Here's a solution based on these features:

    PS> (-split '   One      for the money   ').ForEach({ "token: [$_]" })
    token: [One]
    token: [for]
    token: [the]
    token: [money]
    

    Note that the leading and trailing whitespace was ignored, and that the multiple spaces between One and for were treated as a single separator.

    Android: Access child views from a ListView

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, final View view, int position, long id) {
            View v;
            int count = parent.getChildCount();
            v = parent.getChildAt(position);
            parent.requestChildFocus(v, view);
            v.setBackground(res.getDrawable(R.drawable.transparent_button));
            for (int i = 0; i < count; i++) {
                if (i != position) {
                    v = parent.getChildAt(i);
                    v.setBackground(res.getDrawable(R.drawable.not_clicked));
                }
            }
        }
    });
    

    Basically, create two Drawables - one that is transparent, and another that is the desired color. Request focus at the clicked position (int position as defined) and change the color of the said row. Then walk through the parent ListView, and change all other rows accordingly. This accounts for when a user clicks on the listview multiple times. This is done with a custom layout for each row in the ListView. (Very simple, just create a new layout file with a TextView - do not set focusable or clickable!).

    No custom adapter required - use ArrayAdapter

    How can I set a dynamic model name in AngularJS?

    Or you can use

    <select [(ngModel)]="Answers[''+question.Name+'']" ng-options="option for option in question.Options">
            </select>
    

    Trouble using ROW_NUMBER() OVER (PARTITION BY ...)

    I would do something like this:

    ;WITH x 
     AS (SELECT *, 
                Row_number() 
                  OVER( 
                    partition BY employeeid 
                    ORDER BY datestart) rn 
         FROM   employeehistory) 
    SELECT * 
    FROM   x x1 
       LEFT OUTER JOIN x x2 
                    ON x1.rn = x2.rn + 1 
    

    Or maybe it would be x2.rn - 1. You'll have to see. In any case, you get the idea. Once you have the table joined on itself, you can filter, group, sort, etc. to get what you need.

    Unsupported major.minor version 52.0 in my app

    Check that you have the latest version of the SDK installed in either C:\Program Files\Java or C:\Program Files (x86)\Java

    Then go to VS2015 and follow the path tools - options - Xamarin - Android settings and in the section JDK location select change and go to look for the version you have either x64 or x32.

    How to playback MKV video in web browser?

    To use video extensions that are MKV. You should use video, not source

    For example :

    _x000D_
    _x000D_
      <!-- mkv -->
      <video width="320" height="240" controls src="assets/animation.mkv"></video>
    <!-- mp4 -->
      <video width="320" height="240" controls>
        <source src="assets/animation.mp4" type="video/mp4" />
      </video>
    _x000D_
    _x000D_
    _x000D_ My answer may be incomprehensible to you, so if you do not understand, click on this

    How to make ConstraintLayout work with percentage values?

    Simply, just replace , in your guideline tag

    app:layout_constraintGuide_begin="291dp"
    

    with

    app:layout_constraintGuide_percent="0.7"
    

    where 0.7 means 70%.

    Also if you now try to drag guidelines, the dragged value will now show up in %age.

    Is it possible to style a mouseover on an image map using CSS?

    You can do this by just changing the html. Here's an example:

    <hmtl>
      <head>
        <title>Some title</title>
      </head>
      <body> 
      <map name="navigatemap">
        <area shape="rect"  
              coords="166,4,319,41" 
              href="WII.htm"  
              onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'" 
              onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverWII).png'" 
        />
        <area shape="rect"
              coords="330,4,483,41" 
              href="OT.htm"  
              onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'" 
              onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverOT).png'" 
        />
    
        <area shape="rect" 
              coords="491,3,645,41" 
              href="OP.htm"  
              onMouseOut="navbar.src='Assets/NavigationBar(OnHome).png'" 
              onMouseOver="navbar.src='Assets/NavigationBar(OnHome,MouseOverOP).png'" 
       />
      </map> 
    
      <img src="Assets/NavigationBar(OnHome).png" 
         name="navbar" 
         usemap="#navigatemap" />
      </body>
    </html>
    

    How do I compile with -Xlint:unchecked?

    In gradle project, You can added this compile parameter in the following way:

    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xlint:unchecked"
        }
    }
    

    How to kill all processes with a given partial name?

    If you judge pkill -f PATTERN a bit too dangerous, I wrote ezkill a bash script that prompt you to choose which processes amongst those that match the PATTERN you want to kill.

    Adding integers to an int array

    You cannot use the add method on an array in Java.

    To add things to the array do it like this

    public static void main(String[] args) {
    int[] num = new int[args.length];
    for (int i = 0; i < args.length; i++){
        int neki = Integer.parseInt(s);
        num[i] = neki;
    
    }
    

    If you really want to use an add() method, then consider using an ArrayList<Integer> instead. This has several advantages - for instance it isn't restricted to a maximum size set upon creation. You can keep adding elements indefinitely. However it isn't quite as fast as an array, so if you really want performance stick with the array. Also it requires you to use Integer object instead of primitive int types, which can cause problems.

    ArrayList Example

    public static void main(String[] args) {
        ArrayList<Integer> num = new ArrayList<Integer>();
        for (String s : args){
            Integer neki = new Integer(Integer.parseInt(s));
            num.add(s);
    }
    

    mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

    You are single quoting your SQL statement which is making the variables text instead of variables.

    $sql = "SELECT * 
        FROM $usertable 
        WHERE PartNumber = $partid";
    

    Submitting a multidimensional array via POST with php

    On submitting, you would get an array as if created like this:

    $_POST['topdiameter'] = array( 'first value', 'second value' );
    $_POST['bottomdiameter'] = array( 'first value', 'second value' );
    

    However, I would suggest changing your form names to this format instead:

    name="diameters[0][top]"
    name="diameters[0][bottom]"
    name="diameters[1][top]"
    name="diameters[1][bottom]"
    ...
    

    Using that format, it's much easier to loop through the values.

    if ( isset( $_POST['diameters'] ) )
    {
        echo '<table>';
        foreach ( $_POST['diameters'] as $diam )
        {
            // here you have access to $diam['top'] and $diam['bottom']
            echo '<tr>';
            echo '  <td>', $diam['top'], '</td>';
            echo '  <td>', $diam['bottom'], '</td>';
            echo '</tr>';
        }
        echo '</table>';
    }
    

    What is the runtime performance cost of a Docker container?

    Docker isn't virtualization, as such -- instead, it's an abstraction on top of the kernel's support for different process namespaces, device namespaces, etc.; one namespace isn't inherently more expensive or inefficient than another, so what actually makes Docker have a performance impact is a matter of what's actually in those namespaces.


    Docker's choices in terms of how it configures namespaces for its containers have costs, but those costs are all directly associated with benefits -- you can give them up, but in doing so you also give up the associated benefit:

    • Layered filesystems are expensive -- exactly what the costs are vary with each one (and Docker supports multiple backends), and with your usage patterns (merging multiple large directories, or merging a very deep set of filesystems will be particularly expensive), but they're not free. On the other hand, a great deal of Docker's functionality -- being able to build guests off other guests in a copy-on-write manner, and getting the storage advantages implicit in same -- ride on paying this cost.
    • DNAT gets expensive at scale -- but gives you the benefit of being able to configure your guest's networking independently of your host's and have a convenient interface for forwarding only the ports you want between them. You can replace this with a bridge to a physical interface, but again, lose the benefit.
    • Being able to run each software stack with its dependencies installed in the most convenient manner -- independent of the host's distro, libc, and other library versions -- is a great benefit, but needing to load shared libraries more than once (when their versions differ) has the cost you'd expect.

    And so forth. How much these costs actually impact you in your environment -- with your network access patterns, your memory constraints, etc -- is an item for which it's difficult to provide a generic answer.

    Not receiving Google OAuth refresh token

    This has caused me some confusion so I thought I'd share what I've come to learn the hard way:

    When you request access using the access_type=offline and approval_prompt=force parameters you should receive both an access token and a refresh token. The access token expires soon after you receive it and you will need to refresh it.

    You correctly made the request to get a new access token and received the response that has your new access token. I was also confused by the fact that I didn't get a new refresh token. However, this is how it is meant to be since you can use the same refresh token over and over again.

    I think some of the other answers assume that you wanted to get yourself a new refresh token for some reason and sugggested that you re-authorize the user but in actual fact, you don't need to since the refresh token you have will work until revoked by the user.

    add Shadow on UIView using swift 3

    Very simple and few lines of code:

    let viewShadow = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
    viewShadow.center = self.view.center
    viewShadow.backgroundColor = UIColor.yellow
    viewShadow.layer.shadowColor = UIColor.red.cgColor
    viewShadow.layer.shadowOpacity = 1
    viewShadow.layer.shadowOffset = CGSize.zero
    viewShadow.layer.shadowRadius = 5
    self.view.addSubview(viewShadow)
    

    Look like : enter image description here

    How to display scroll bar onto a html table

    If you get to the point where all the mentioned solutions don't work (as it got for me), do this:

    • Create two tables. One for the header and another for the body
    • Give the two tables different parent containers/divs
    • Style the second table's div to allow vertical scroll of its contents.

    Like this, in your HTML

    <div class="table-header-class">
        <table>
           <thead>
              <tr>
                <th>Ava</th>
                <th>Alexis</th>
                <th>Mcclure</th>
              </tr>
           </thead>
        </table>
    </div>
    <div class="table-content-class">
       <table>
           <tbody>
              <tr>
                <td>I am the boss</td>
                <td>No, da-da is not the boss!</td>
                <td>Alexis, I am the boss, right?</td>
              </tr>
           </tbody>
        </table>
    </div>
    

    Then style the second table's parent to allow vertical scroll, in your CSS

        .table-content-class {
            overflow-y: scroll;    // use auto; or scroll; to allow vertical scrolling; 
            overflow-x: hidden;    // disable horizontal scroll 
        }
    

    Unable to compile class for JSP

    Try adding this to your web.xml:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/your-servlet-name.xml
        </param-value>
    

    Android - R cannot be resolved to a variable

    Agree it is probably due to a problem in resources that is preventing build of R.Java in gen. In my case a cut n paste had given a duplicate app name in string. Sort the fault, delete gen directory and clean.

    The backend version is not supported to design database diagrams or tables

    I ran into this problem when SQL Server 2014 standard was installed on a server where SQL Server Express was also installed. I had opened SSMS from a desktop shortcut, not realizing right away that it was SSMS for SQL Server Express, not for 2014. SSMS for Express returned the error, but SQL Server 2014 did not.

    Is there a JavaScript function that can pad a string to get to a determined length?

    String.prototype.padLeft = function(pad) {
            var s = Array.apply(null, Array(pad)).map(function() { return "0"; }).join('') + this;
            return s.slice(-1 * Math.max(this.length, pad));
        };
    

    usage:

    1. "123".padLeft(2) returns: "123"
    2. "12".padLeft(2) returns: "12"
    3. "1".padLeft(2) returns: "01"

    Python TypeError must be str not int

    print("the furnace is now " + str(temperature) + "degrees!")

    cast it to str

    Table Naming Dilemma: Singular vs. Plural Names

    If you use Object Relational Mapping tools or will in the future I suggest Singular.

    Some tools like LLBLGen can automatically correct plural names like Users to User without changing the table name itself. Why does this matter? Because when it's mapped you want it to look like User.Name instead of Users.Name or worse from some of my old databases tables naming tblUsers.strName which is just confusing in code.

    My new rule of thumb is to judge how it will look once it's been converted into an object.

    one table I've found that does not fit the new naming I use is UsersInRoles. But there will always be those few exceptions and even in this case it looks fine as UsersInRoles.Username.

    What's the difference between Html.Label, Html.LabelFor and Html.LabelForModel

    Html.Label - Just creates a label tag with whatever the string passed into the constructor is

    Html.LabelFor - Creates a label for that specific property. This is strongly typed. By default, this will just do the name of the property (in the below example, it'll output MyProperty if that Display attribute wasn't there). Another benefit of this is you can set the display property in your model and that's what will be put here:

    public class MyModel
    {
        [Display(Name="My property title")
        public class MyProperty{get;set;}
    }
    

    In your view:

    Html.LabelFor(x => x.MyProperty) //Outputs My property title
    

    In the above, LabelFor will display <label for="MyProperty">My property title</label>. This works nicely so you can define in one place what the label for that property will be and have it show everywhere.

    How can I search sub-folders using glob.glob module?

    (The first options are of course mentioned in other answers, here the goal is to show that glob uses os.scandir internally, and provide a direct answer with this).


    Using glob

    As explained before, with Python 3.5+, it's easy:

    import glob
    for f in glob.glob('d:/temp/**/*', recursive=True):
        print(f)
    
    #d:\temp\New folder
    #d:\temp\New Text Document - Copy.txt
    #d:\temp\New folder\New Text Document - Copy.txt
    #d:\temp\New folder\New Text Document.txt
    

    Using pathlib

    from pathlib import Path
    for f in Path('d:/temp').glob('**/*'):
        print(f)
    

    Using os.scandir

    os.scandir is what glob does internally. So here is how to do it directly, with a use of yield:

    def listpath(path):
        for f in os.scandir(path):
            f2 = os.path.join(path, f)
            if os.path.isdir(f):
                yield f2
                yield from listpath(f2)
            else:
                yield f2
    
    for f in listpath('d:\\temp'):
        print(f)
    

    How do I pass the this context to a function?

    Javascripts .call() and .apply() methods allow you to set the context for a function.

    var myfunc = function(){
        alert(this.name);
    };
    
    var obj_a = {
        name:  "FOO"
    };
    
    var obj_b = {
        name:  "BAR!!"
    };
    

    Now you can call:

    myfunc.call(obj_a);
    

    Which would alert FOO. The other way around, passing obj_b would alert BAR!!. The difference between .call() and .apply() is that .call() takes a comma separated list if you're passing arguments to your function and .apply() needs an array.

    myfunc.call(obj_a, 1, 2, 3);
    myfunc.apply(obj_a, [1, 2, 3]);
    

    Therefore, you can easily write a function hook by using the apply() method. For instance, we want to add a feature to jQuerys .css() method. We can store the original function reference, overwrite the function with custom code and call the stored function.

    var _css = $.fn.css;
    $.fn.css = function(){
       alert('hooked!');
       _css.apply(this, arguments);
    };
    

    Since the magic arguments object is an array like object, we can just pass it to apply(). That way we guarantee, that all parameters are passed through to the original function.

    How do I install Python packages on Windows?

    I had problems in installing packages on Windows. Found the solution. It works in Windows7+. Mainly anything with Windows Powershell should be able to make it work. This can help you get started with it.

    • Firstly, you'll need to add python installation to your PATH variable. This should help.
    • You need to download the package in zip format that you are trying to install and unzip it. If it is some odd zip format use 7Zip and it should be extracted.
    • Navigate to the directory extracted with setup.py using Windows Powershell (Use link for it if you have problems)
    • Run the command python setup.py install

    That worked for me when nothing else was making any sense. I use Python 2.7 but the documentation suggests that same would work for Python 3.x also.

    How to select a dropdown value in Selenium WebDriver using Java

    WebDriver driver = new FirefoxDriver();
    WebElement identifier = driver.findElement(By.id("periodId"));
    Select select = new Select(identifier);
    select.selectByVisibleText("Last 52 Weeks"); 
    

    WordPress Get the Page ID outside the loop

    If you're using pretty permalinks, get_query_var('page_id') won't work.

    Instead, get the queried object ID from the global $wp_query:

    // Since 3.1 - recommended!
    $page_object = get_queried_object();
    $page_id     = get_queried_object_id();
    
    
    // "Dirty" pre 3.1
    global $wp_query;
    
    $page_object = $wp_query->get_queried_object();
    $page_id     = $wp_query->get_queried_object_id();
    

    How to compare oldValues and newValues on React Hooks useEffect?

    If you prefer a useEffect replacement approach:

    const usePreviousEffect = (fn, inputs = []) => {
      const previousInputsRef = useRef([...inputs])
    
      useEffect(() => {
        fn(previousInputsRef.current)
        previousInputsRef.current = [...inputs]
      }, inputs)
    }
    

    And use it like this:

    usePreviousEffect(
      ([prevReceiveAmount, prevSendAmount]) => {
        if (prevReceiveAmount !== receiveAmount) // side effect here
        if (prevSendAmount !== sendAmount) // side effect here
      },
      [receiveAmount, sendAmount]
    )
    

    Note that the first time the effect executes, the previous values passed to your fn will be the same as your initial input values. This would only matter to you if you wanted to do something when a value did not change.

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

    take a look at the jQuery Tooltip plugin. You can pass in an options object for different options.

    There are also other alternative tooltip plugins available, of which a few are

    Take look at the demos and documentation and please update your question if you have specific questions about how to use them in your code.

    JSON.parse vs. eval()

    All JSON.parse implementations most likely use eval()

    JSON.parse is based on Douglas Crockford's solution, which uses eval() right there on line 497.

    // In the third stage we use the eval function to compile the text into a
    // JavaScript structure. The '{' operator is subject to a syntactic ambiguity
    // in JavaScript: it can begin a block or an object literal. We wrap the text
    // in parens to eliminate the ambiguity.
    
    j = eval('(' + text + ')');
    

    The advantage of JSON.parse is that it verifies the argument is correct JSON syntax.

    python-How to set global variables in Flask?

    With:

    global index_add_counter
    

    You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

    index_add_counter = 0
    

    Now you can import it with:

    from app import index_add_counter
    

    The construction:

    global index_add_counter
    

    is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

    index_add_counter = 0
    def test():
      global index_add_counter # means: in this scope, use the global name
      print(index_add_counter)
    

    How to log as much information as possible for a Java Exception?

    Something that I do is to have a static method that handles all exceptions and I add the log to a JOptionPane to show it to the user, but you could write the result to a file in FileWriter wraped in a BufeeredWriter. For the main static method, to catch the Uncaught Exceptions I do:

    SwingUtilities.invokeLater( new Runnable() {
        @Override
        public void run() {
            //Initializations...
        }
    });
    
    
    Thread.setDefaultUncaughtExceptionHandler( 
        new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException( Thread t, Throwable ex ) {
                handleExceptions( ex, true );
            }
        }
    );
    

    And as for the method:

    public static void handleExceptions( Throwable ex, boolean shutDown ) {
        JOptionPane.showMessageDialog( null,
            "A CRITICAL ERROR APPENED!\n",
            "SYSTEM FAIL",
            JOptionPane.ERROR_MESSAGE );
    
        StringBuilder sb = new StringBuilder(ex.toString());
        for (StackTraceElement ste : ex.getStackTrace()) {
            sb.append("\n\tat ").append(ste);
        }
    
    
        while( (ex = ex.getCause()) != null ) {
            sb.append("\n");
            for (StackTraceElement ste : ex.getStackTrace()) {
                sb.append("\n\tat ").append(ste);
            }
        }
    
        String trace = sb.toString();
    
        JOptionPane.showMessageDialog( null,
            "PLEASE SEND ME THIS ERROR SO THAT I CAN FIX IT. \n\n" + trace,
            "SYSTEM FAIL",
            JOptionPane.ERROR_MESSAGE);
    
        if( shutDown ) {
            Runtime.getRuntime().exit( 0 );
        }
    }
    

    In you case, instead of "screaming" to the user, you could write a log like I told you before:

    String trace = sb.toString();
    
    File file = new File("mylog.txt");
    FileWriter myFileWriter = null;
    BufferedWriter myBufferedWriter = null;
    
    try {
        //with FileWriter(File file, boolean append) you can writer to 
        //the end of the file
        myFileWriter = new FileWriter( file, true );
        myBufferedWriter = new BufferedWriter( myFileWriter );
    
        myBufferedWriter.write( trace );
    }
    catch ( IOException ex1 ) {
        //Do as you want. Do you want to use recursive to handle 
        //this exception? I don't advise that. Trust me...
    }
    finally {
        try {
            myBufferedWriter.close();
        }
        catch ( IOException ex1 ) {
            //Idem...
        }
    
        try {
            myFileWriter.close();
        }
        catch ( IOException ex1 ) {
            //Idem...
        }
    }
    

    I hope I have helped.

    Have a nice day. :)

    batch file - counting number of files in folder and storing in a variable

    I have used a temporary file to do this in the past, like this below.

    DIR /B *.DAT | FIND.EXE /C /V "" > COUNT.TXT
    
    FOR /F "tokens=1" %%f IN (COUNT.TXT) DO (
    IF NOT %%f==6 SET _MSG=File count is %%f, and 6 were expected. & DEL COUNT.TXT & ECHO #### ERROR - FILE COUNT WAS %%f AND 6 WERE EXPECTED. #### >> %_LOGFILE% & GOTO SENDMAIL
    )
    

    How to display a date as iso 8601 format with PHP

    Here is the good function for pre PHP 5: I added GMT difference at the end, it's not hardcoded.

    function iso8601($time=false) {
        if ($time === false) $time = time();
        $date = date('Y-m-d\TH:i:sO', $time);
        return (substr($date, 0, strlen($date)-2).':'.substr($date, -2));
    }
    

    Return from a promise then()

    When you return something from a then() callback, it's a bit magic. If you return a value, the next then() is called with that value. However, if you return something promise-like, the next then() waits on it, and is only called when that promise settles (succeeds/fails).

    Source: https://web.dev/promises/#queuing-asynchronous-actions

    Change IPython/Jupyter notebook working directory

    To do the same trick described below for Windows in OS X, create this shell script

    #!/bin/bash
    cd $(dirname "$0") && pwd
    ipython notebook
    

    Call it ipython-notebook.command and make it executable.

    Put it in the directory you want to work in, then double-click it.

    Replace all elements of Python NumPy Array that are greater than some value

    Another way is to use np.place which does in-place replacement and works with multidimentional arrays:

    import numpy as np
    
    # create 2x3 array with numbers 0..5
    arr = np.arange(6).reshape(2, 3)
    
    # replace 0 with -10
    np.place(arr, arr == 0, -10)
    

    New self vs. new static

    In addition to others' answers :

    static:: will be computed using runtime information.

    That means you can't use static:: in a class property because properties values :

    Must be able to be evaluated at compile time and must not depend on run-time information.

    class Foo {
        public $name = static::class;
    
    }
    
    $Foo = new Foo;
    echo $Foo->name; // Fatal error
    

    Using self::

    class Foo {
        public $name = self::class;
    
    }
    $Foo = new Foo;
    echo $Foo->name; // Foo
    

    Please note that the Fatal error comment in the code i made doesn't indicate where the error happened, the error happened earlier before the object was instantiated as @Grapestain mentioned in the comments

    What is the theoretical maximum number of open TCP connections that a modern Linux box can have

    If you used a raw socket (SOCK_RAW) and re-implemented TCP in userland, I think the answer is limited in this case only by the number of (local address, source port, destination address, destination port) tuples (~2^64 per local address).

    It would of course take a lot of memory to keep the state of all those connections, and I think you would have to set up some iptables rules to keep the kernel TCP stack from getting upset &/or responding on your behalf.

    How to get current date in jquery?

    Date() is not part of jQuery, it is one of JavaScript's features.

    See the documentation on Date object.

    You can do it like that:

    var d = new Date();
    
    var month = d.getMonth()+1;
    var day = d.getDate();
    
    var output = d.getFullYear() + '/' +
        (month<10 ? '0' : '') + month + '/' +
        (day<10 ? '0' : '') + day;
    

    See this jsfiddle for a proof.

    The code may look like a complex one, because it must deal with months & days being represented by numbers less than 10 (meaning the strings will have one char instead of two). See this jsfiddle for comparison.

    How to browse for a file in java swing library?

    I ended up using this quick piece of code that did exactly what I needed:

    final JFileChooser fc = new JFileChooser();
    fc.showOpenDialog(this);
    
    try {
        // Open an input stream
        Scanner reader = new Scanner(fc.getSelectedFile());
    }