Programs & Examples On #Use strict

How is the 'use strict' statement interpreted in Node.js?

"use strict";

Basically it enables the strict mode.

Strict Mode is a feature that allows you to place a program, or a function, in a "strict" operating context. In strict operating context, the method form binds this to the objects as before. The function form binds this to undefined, not the global set objects.

As per your comments you are telling some differences will be there. But it's your assumption. The Node.js code is nothing but your JavaScript code. All Node.js code are interpreted by the V8 JavaScript engine. The V8 JavaScript Engine is an open source JavaScript engine developed by Google for Chrome web browser.

So, there will be no major difference how "use strict"; is interpreted by the Chrome browser and Node.js.

Please read what is strict mode in JavaScript.

For more information:

  1. Strict mode
  2. ECMAScript 5 Strict mode support in browsers
  3. Strict mode is coming to town
  4. Compatibility table for strict mode
  5. Stack Overflow questions: what does 'use strict' do in JavaScript & what is the reasoning behind it


ECMAScript 6:

ECMAScript 6 Code & strict mode. Following is brief from the specification:

10.2.1 Strict Mode Code

An ECMAScript Script syntactic unit may be processed using either unrestricted or strict mode syntax and semantics. Code is interpreted as strict mode code in the following situations:

  • Global code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive (see 14.1.1).
  • Module code is always strict mode code.
  • All parts of a ClassDeclaration or a ClassExpression are strict mode code.
  • Eval code is strict mode code if it begins with a Directive Prologue that contains a Use Strict Directive or if the call to eval is a direct eval (see 12.3.4.1) that is contained in strict mode code.
  • Function code is strict mode code if the associated FunctionDeclaration, FunctionExpression, GeneratorDeclaration, GeneratorExpression, MethodDefinition, or ArrowFunction is contained in strict mode code or if the code that produces the value of the function’s [[ECMAScriptCode]] internal slot begins with a Directive Prologue that contains a Use Strict Directive.
  • Function code that is supplied as the arguments to the built-in Function and Generator constructors is strict mode code if the last argument is a String that when processed is a FunctionBody that begins with a Directive Prologue that contains a Use Strict Directive.

Additionally if you are lost on what features are supported by your current version of Node.js, this node.green can help you (leverages from the same data as kangax).

What does "use strict" do in JavaScript, and what is the reasoning behind it?

Strict mode eliminates errors that would be ignored in non-strict mode, thus making javascript “more secured”.

Is it considered among best practices?

Yes, It's considered part of the best practices while working with javascript to include Strict mode. This is done by adding the below line of code in your JS file.

'use strict';

in your code.

What does it mean to user agents?

Indicating that code should be interpreted in strict mode specifies to user agents like browsers that they should treat code literally as written, and throw an error if the code doesn't make sense.

For example: Consider in your .js file you have the following code:

Scenario 1: [NO STRICT MODE]

var city = "Chicago"
console.log(city) // Prints the city name, i.e. Chicago

Scenario 2: [NO STRICT MODE]

city = "Chicago"
console.log(city) // Prints the city name, i.e. Chicago

So why does the variable name is being printed in both cases?

Without strict mode turned on, user agents often go through a series of modifications to problematic code in an attempt to get it to make sense. On the surface, this can seem like a fine thing, and indeed, working outside of strict mode makes it possible for people to get their feet wet with JavaScript code without having all the details quite nailed down. However, as a developer, I don't want to leave a bug in my code, because I know it could come back and bite me later on, and I also just want to write good code. And that's where strict mode helps out.

Scenario 3: [STRICT MODE]

'use strict';

city = "Chicago"
console.log(city) // Reference Error: asignment is undeclared variable city.

Additional tip: To maintain code quality using strict mode, you don't need to write this over and again especially if you have multiple .js file. You can enforce this rule globally in eslint rules as follows:

Filename: .eslintrc.js

module.exports = {
    env: {
        es6: true
    },
    rules : {
        strict: ['error', 'global'],
        },
    };
    

Okay, so what is prevented in strict mode?

  • Using a variable without declaring it will throw an error in strict mode. This is to prevent unintentionally creating global variables throughout your application. The example with printing Chicago covers this in particular.

  • Deleting a variable or a function or an argument is a no-no in strict mode.

    "use strict";
     function x(p1, p2) {}; 
     delete x; // This will cause an error
    
  • Duplicating a parameter name is not allowed in strict mode.

     "use strict";
     function x(p1, p1) {};   // This will cause an error
    
  • Reserved words in the Javascript language are not allowed in strict mode. The words are implements interface, let, packages, private, protected, public. static, and yield

For a more comprehensive list check out the MDN documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode

XSL if: test with multiple test conditions

Try to use the empty() function:

<xsl:if test="empty(node/ABC/node()) and empty(node/DEF/node())">
    <xsl:text>This should work</xsl:text>
</xsl:if>

This identifies ABC and DEF as empty in the sense that they do not have any child nodes (no elements, no text nodes, no processing instructions, no comments).

But, as pointed out by @Ian, your elements might not be empty really or that might not be your actual problem - you did not show what your input XML looks like.

Another cause of error could be your relative position in the tree. This way of testing conditions only works if the surrounding template matches the parent element of node or if you iterate over the parent element of node.

Call a React component method from outside

You can just add an onClick handler to the div with the function (onClick is React's own implementation of onClick) and you can access the property within { } curly braces, and your alert message will appear.

In case you wish to define static methods that can be called on the component class - you should use statics. Although:

"Methods defined within this block are static, meaning that you can run them before any component instances are created, and the methods do not have access to the props or state of your components. If you want to check the value of props in a static method, have the caller pass in the props as an argument to the static method." (source)

Some example code:

    const Hello = React.createClass({

        /*
            The statics object allows you to define static methods that can be called on the component class. For example:
        */
        statics: {
            customMethod: function(foo) {
              return foo === 'bar';
            }
        },


        alertMessage: function() {
            alert(this.props.name);                             
        },

        render: function () {
            return (
                <div onClick={this.alertMessage}>
                Hello {this.props.name}
                </div>
            );
        }
    });

    React.render(<Hello name={'aworld'} />, document.body);

Hope this helps you a bit, because i don't know if I understood your question correctly, so correct me if i interpreted it wrong:)

How to save a new sheet in an existing excel file, using Pandas?

For creating a new file

x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)
with pd.ExcelWriter('sample.xlsx') as writer:  
    df1.to_excel(writer, sheet_name='x1')

For appending to the file, use the argument mode='a' in pd.ExcelWriter.

x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)
with pd.ExcelWriter('sample.xlsx', engine='openpyxl', mode='a') as writer:  
    df2.to_excel(writer, sheet_name='x2')

Default is mode ='w'. See documentation.

mysql update query with sub query

The main issue is that the inner query cannot be related to your where clause on the outer update statement, because the where filter applies first to the table being updated before the inner subquery even executes. The typical way to handle a situation like this is a multi-table update.

Update
  Competition as C
  inner join (
    select CompetitionId, count(*) as NumberOfTeams
    from PicksPoints as p
    where UserCompetitionID is not NULL
    group by CompetitionID
  ) as A on C.CompetitionID = A.CompetitionID
set C.NumberOfTeams = A.NumberOfTeams

Demo: http://www.sqlfiddle.com/#!2/a74f3/1

JQuery create new select option

How about

$('#county').append(
    $('<option />')
        .text('Select a city / town in Sweden')
        .val(''),
    $('<option />')
        .text('Melbourne')
        .val('Melbourne')
);

Seeing the console's output in Visual Studio 2010?

Add a Console.Read(); at the end of your program. It'll keep the application from closing, and you can see its output that way.

This is a console application I just dug up that stops after processing but before exiting:

class Program
{
    static void Main(string[] args)
    {
        DummyObjectList dol = new DummyObjectList(2);
        dol.Add(new DummyObject("test1", (Decimal)25.36));
        dol.Add(new DummyObject("test2", (Decimal)0.698));
        XmlSerializer dolxs = new XmlSerializer(typeof(DummyObjectList));
        dolxs.Serialize(Console.Out, dol);

        Console.WriteLine(string.Empty);
        Console.WriteLine(string.Empty);

        List<DummyObject> dolist = new List<DummyObject>(2);
        dolist.Add(new DummyObject("test1", (Decimal)25.36));
        dolist.Add(new DummyObject("test2", (Decimal)0.698));
        XmlSerializer dolistxs = new XmlSerializer(typeof(List<DummyObject>));
        dolistxs.Serialize(Console.Out, dolist);
        Console.Read(); //  <--- Right here
    }
}

Alternatively, you can simply add a breakpoint on the last line.

How to get my Android device Internal Download Folder path

if a device has an SD card, you use:

Environment.getExternalStorageState() 

if you don't have an SD card, you use:

Environment.getDataDirectory()

if there is no SD card, you can create your own directory on the device locally.

    //if there is no SD card, create new directory objects to make directory on device
        if (Environment.getExternalStorageState() == null) {
                        //create new file directory object
            directory = new File(Environment.getDataDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(Environment.getDataDirectory()
                    + "/Robotium-Screenshots/");
            /*
             * this checks to see if there are any previous test photo files
             * if there are any photos, they are deleted for the sake of
             * memory
             */
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length != 0) {
                    for (int ii = 0; ii <= dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                }
            }
            // if no directory exists, create new directory
            if (!directory.exists()) {
                directory.mkdir();
            }

            // if phone DOES have sd card
        } else if (Environment.getExternalStorageState() != null) {
            // search for directory on SD card
            directory = new File(Environment.getExternalStorageDirectory()
                    + "/RobotiumTestLog/");
            photoDirectory = new File(
                    Environment.getExternalStorageDirectory()
                            + "/Robotium-Screenshots/");
            if (photoDirectory.exists()) {
                File[] dirFiles = photoDirectory.listFiles();
                if (dirFiles.length > 0) {
                    for (int ii = 0; ii < dirFiles.length; ii++) {
                        dirFiles[ii].delete();
                    }
                    dirFiles = null;
                }
            }
            // if no directory exists, create new directory to store test
            // results
            if (!directory.exists()) {
                directory.mkdir();
            }
        }// end of SD card checking

add permissions on your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Happy coding..

CSS grid wrapping

You may be looking for auto-fill:

grid-template-columns: repeat(auto-fill, 186px);

Demo: http://codepen.io/alanbuchanan/pen/wJRMox

To use up the available space more efficiently, you could use minmax, and pass in auto as the second argument:

grid-template-columns: repeat(auto-fill, minmax(186px, auto));

Demo: http://codepen.io/alanbuchanan/pen/jBXWLR

If you don't want the empty columns, you could use auto-fit instead of auto-fill.

iPhone X / 8 / 8 Plus CSS media queries

If your page is missing meta[@name="viewport"] element within its DOM, then the following could be used to detect a mobile device:

@media only screen and (width: 980px), (hover: none) { … }

If you want to avoid false-positives with desktops that just magically have their viewport set to 980px like all the mobile browsers do, then a device-width test could also be added into the mix:

@media only screen and (max-device-width: 800px) and (width: 980px), (hover: none) { … }

Per the list at https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries, the new hover property would appear to be the final new way to detect that you've got yourself a mobile device that doesn't really do proper hover; it's only been introduced in 2018 with Firefox 64 (2018), although it's been supported since 2016 with Android Chrome 50 (2016), or even since 2014 with Chrome 38 (2014):

How to test an SQL Update statement before running it?

What about Transactions? They have the ROLLBACK-Feature.

@see https://dev.mysql.com/doc/refman/5.0/en/commit.html

For example:

START TRANSACTION;
SELECT * FROM nicetable WHERE somthing=1;
UPDATE nicetable SET nicefield='VALUE' WHERE somthing=1;
SELECT * FROM nicetable WHERE somthing=1; #check

COMMIT;
# or if you want to reset changes 
ROLLBACK;

SELECT * FROM nicetable WHERE somthing=1; #should be the old value

Answer on question from @rickozoe below:

In general these lines will not be executed as once. In PHP f.e. you would write something like that (perhaps a little bit cleaner, but wanted to answer quick ;-) ):

$MysqlConnection->query('START TRANSACTION;');
$erg = $MysqlConnection->query('UPDATE MyGuests SET lastname='Doe' WHERE id=2;');
if($erg)
    $MysqlConnection->query('COMMIT;');
else
    $MysqlConnection->query('ROLLBACK;');

Another way would be to use MySQL Variables (see https://dev.mysql.com/doc/refman/5.7/en/user-variables.html and https://stackoverflow.com/a/18499823/1416909 ):

# do some stuff that should be conditionally rollbacked later on

SET @v1 := UPDATE MyGuests SET lastname='Doe' WHERE id=2;
IF(v1 < 1) THEN
    ROLLBACK;
ELSE
    COMMIT;
END IF;

But I would suggest to use the language wrappers available in your favorite programming language.

Can a relative sitemap url be used in a robots.txt?

According to the official documentation on sitemaps.org it needs to be a full URL:

You can specify the location of the Sitemap using a robots.txt file. To do this, simply add the following line including the full URL to the sitemap:

Sitemap: http://www.example.com/sitemap.xml

SASS and @font-face

In case anyone was wondering - it was probably my css...

@font-face
  font-family: "bingo"
  src: url('bingo.eot')
  src: local('bingo')
  src: url('bingo.svg#bingo') format('svg')
  src: url('bingo.otf') format('opentype')

will render as

@font-face {
  font-family: "bingo";
  src: url('bingo.eot');
  src: local('bingo');
  src: url('bingo.svg#bingo') format('svg');
  src: url('bingo.otf') format('opentype'); }

which seems to be close enough... just need to check the SVG rendering

Dynamically converting java object of Object class to a given class when class name is known

If you didnt know that mojb is of type MyClass, then how can you create that variable?

If MyClass is an interface type, or a super type, then there is no need to do a cast.

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

Angular; with IDE keyCode deprecated warning

Functionally the same as rinku's answer but with IDE warning prevention

numericOnly(event): boolean {
    // noinspection JSDeprecatedSymbols
    const charCode = (event.which) ? event.which : event.key || event.keyCode;  // keyCode is deprecated but needed for some browsers
    return !(charCode === 101 || charCode === 69 || charCode === 45 || charCode === 43);
}

Renaming the current file in Vim

Another way is to just use netrw, which is a native part of vim.

:e path/to/whatever/folder/

Then there are options to delete, rename, etc.

Here's a keymap to open netrw to the folder of the file you are editing:

map <leader>e :e <C-R>=expand("%:p:h") . '/'<CR><CR>

Changing button color programmatically

Try this code You may want something like this

<button class="normal" id="myButton" 
        value="Hover" onmouseover="mouseOver()" 
        onmouseout="mouseOut()">Some text</button>

Then on your .js file enter this.Make sure your html is connected to your .js

var tag=document.getElementById("myButton");

function mouseOver() {
    tag.style.background="yellow";
};
function mouseOut() {
    tag.style.background="white";
};

Android Location Manager, Get GPS location ,if no GPS then get to Network Provider location

The recommended way to do this is to use LocationClient:

First, define location update interval values. Adjust this to your needs.

private static final int MILLISECONDS_PER_SECOND = 1000;
private static final long UPDATE_INTERVAL = MILLISECONDS_PER_SECOND * UPDATE_INTERVAL_IN_SECONDS;
private static final int FASTEST_INTERVAL_IN_SECONDS = 1;
private static final long FASTEST_INTERVAL = MILLISECONDS_PER_SECOND * FASTEST_INTERVAL_IN_SECONDS;

Have your Activity implement GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, and LocationListener.

public class LocationActivity extends Activity implements 
GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener, LocationListener {}

Then, set up a LocationClientin the onCreate() method of your Activity:

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mLocationClient = new LocationClient(this, this, this);

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(UPDATE_INTERVAL);
    mLocationRequest.setFastestInterval(FASTEST_INTERVAL);
}

Add the required methods to your Activity; onConnected() is the method that is called when the LocationClientconnects. onLocationChanged() is where you'll retrieve the most up-to-date location.

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
    Log.w(TAG, "Location client connection failed");
}

@Override
public void onConnected(Bundle dataBundle) {
    Log.d(TAG, "Location client connected");
    mLocationClient.requestLocationUpdates(mLocationRequest, this); 
}

@Override
public void onDisconnected() {
    Log.d(TAG, "Location client disconnected");
}

@Override
public void onLocationChanged(Location location) {
    if (location != null) {
        Log.d(TAG, "Updated Location: " + Double.toString(location.getLatitude()) + "," + Double.toString(location.getLongitude()));
    } else {
        Log.d(TAG, "Updated location NULL");
    } 
}     

Be sure to connect/disconnect the LocationClient so it's only using extra battery when absolutely necessary and so the GPS doesn't run indefinitely. The LocationClient must be connected in order to get data from it.

public void onResume() {
    super.onResume();
    mLocationClient.connect();
}

public void onStop() {
    if (mLocationClient.isConnected()) {
        mLocationClient.removeLocationUpdates(this);
    }
    mLocationClient.disconnect();
    super.onStop();
}

Get the user's location. First try using the LocationClient; if that fails, fall back to the LocationManager.

public Location getLocation() {
    if (mLocationClient != null && mLocationClient.isConnected()) {
        return mLocationClient.getLastLocation();
    } else {
        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        if (locationManager != null) {
            Location lastKnownLocationGPS = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            if (lastKnownLocationGPS != null) {
                return lastKnownLocationGPS;
            } else {
                return locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            }
        } else {
            return null;
        }
    }
}

Convert normal date to unix timestamp

You should check out the moment.js api, it is very easy to use and has lots of built in features.

I think for your problem, you could use something like this:

var unixTimestamp = moment('2012.08.10', 'YYYY.MM.DD').unix();

JavaScript regex for alphanumeric string with length of 3-5 chars

add {3,5} to your expression which means length between 3 to 5

/^([a-zA-Z0-9_-]){3,5}$/

Is there a way to do repetitive tasks at intervals?

A broader answer to this question might consider the Lego brick approach often used in Occam, and offered to the Java community via JCSP. There is a very good presentation by Peter Welch on this idea.

This plug-and-play approach translates directly to Go, because Go uses the same Communicating Sequential Process fundamentals as does Occam.

So, when it comes to designing repetitive tasks, you can build your system as a dataflow network of simple components (as goroutines) that exchange events (i.e. messages or signals) via channels.

This approach is compositional: each group of small components can itself behave as a larger component, ad infinitum. This can be very powerful because complex concurrent systems are made from easy to understand bricks.

Footnote: in Welch's presentation, he uses the Occam syntax for channels, which is ! and ? and these directly correspond to ch<- and <-ch in Go.

Adding a css class to select using @Html.DropDownList()

As the signature from the error message implies, the second argument must be an IEnumerable, more specifically, an IEnumerable of SelectListItem. It is the list of choices. You can use the SelectList type, which is a IEnumerable of SelectListItem. For a list with no choices:

@Html.DropDownList("PriorityID", new List<SelectListItem>(), new {@class="textbox"} )

For a list with a few choices:

@Html.DropDownList(
    "PriorityID", 
    new List<SelectListItem> 
    { 
        new SelectListItem { Text = "High", Value = 1 }, 
        new SelectListItem { Text = "Low",  Value = 0 },
    }, 
    new {@class="textbox"})

Maybe this tutorial can be of help: How to create a DropDownList with ASP.NET MVC

Convert pyspark string to date format

Try this:

df = spark.createDataFrame([('2018-07-27 10:30:00',)], ['Date_col'])
df.select(from_unixtime(unix_timestamp(df.Date_col, 'yyyy-MM-dd HH:mm:ss')).alias('dt_col'))
df.show()
+-------------------+  
|           Date_col|  
+-------------------+  
|2018-07-27 10:30:00|  
+-------------------+  

How can I make an "are you sure" prompt in a Windows batchfile?

Here is a simple example which I use in a backup (.bat / batch) script on Windows 10, which allows me to have different options when making backups.

...

:choice
set /P c=Do you want to rsync the archives to someHost[Y/N]?
if /I "%c%" EQU "Y" goto :syncthefiles
if /I "%c%" EQU "N" goto :doonotsyncthefiles
goto :choice

:syncthefiles
echo rsync files to somewhere ...
bash -c "rsync -vaz /mnt/d/Archive/Backup/ user@host:/home/user/Backup/blabla/"
echo done

:doonotsyncthefiles
echo Backup Complete!

...

You can have as many as you need of these blocks.

How to get a jqGrid cell value when editing

You can use getCol to get the column values as an array then index into it by the row you are interested in.

var col = $('#grid').jqGrid('getCol', 'Sales', false);

var val = col[row];

read complete file without using loop in java

If you are using Java 5/6, you can use Apache Commons IO for read file to string. The class org.apache.commons.io.FileUtils contais several method for read files.

e.g. using the method FileUtils#readFileToString:

File file = new File("abc.txt");
String content = FileUtils.readFileToString(file);

Count unique values with pandas per groups

df.domain.value_counts()

>>> df.domain.value_counts()

vk.com          5

twitter.com     2

google.com      1

facebook.com    1

Name: domain, dtype: int64

Get only specific attributes with from Laravel Collection

use User::get(['id', 'name', 'email']), it will return you a collection with the specified columns and if you want to make it an array, just use toArray() after the get() method like so:

User::get(['id', 'name', 'email'])->toArray()

Most of the times, you won't need to convert the collection to an array because collections are actually arrays on steroids and you have easy-to-use methods to manipulate the collection.

Make a link use POST instead of GET

You can use this jQuery function

function makePostRequest(url, data) {
    var jForm = $('<form></form>');
    jForm.attr('action', url);
    jForm.attr('method', 'post');
    for (name in data) {
        var jInput = $("<input>");
        jInput.attr('name', name);
        jInput.attr('value', data[name]);
        jForm.append(jInput);
    }
    jForm.submit();
}

Here is an example in jsFiddle (http://jsfiddle.net/S7zUm/)

How to get the type of T from a member of a generic class or method?

If I understand correctly, your list has the same type parameter as the container class itself. If this is the case, then:

Type typeParameterType = typeof(T);

If you are in the lucky situation of having object as a type parameter, see Marc's answer.

Is there Selected Tab Changed Event in the standard WPF Tab Control

This code seems to work:

    private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        TabItem selectedTab = e.AddedItems[0] as TabItem;  // Gets selected tab

        if (selectedTab.Name == "Tab1")
        {
            // Do work Tab1
        }
        else if (selectedTab.Name == "Tab2")
        {
            // Do work Tab2
        }
    }

How to choose the id generation strategy when using JPA and Hibernate


A while ago i wrote a detailed article about Hibernate key generators: http://blog.eyallupu.com/2011/01/hibernatejpa-identity-generators.html

Choosing the correct generator is a complicated task but it is important to try and get it right as soon as possible - a late migration might be a nightmare.

A little off topic but a good chance to raise a point usually overlooked which is sharing keys between applications (via API). Personally I always prefer surrogate keys and if I need to communicate my objects with other systems I don't expose my key (even though it is a surrogate one) – I use an additional ‘external key’. As a consultant I have seen more than once 'great' system integrations using object keys (the 'it is there let's just use it' approach) just to find a year or two later that one side has issues with the key range or something of the kind requiring a deep migration on the system exposing its internal keys. Exposing your key means exposing a fundamental aspect of your code to external constrains shouldn’t really be exposed to.

Difference between a View's Padding and Margin

Margin refers to the extra space outside of an element. Padding refers to the extra space within an element. The margin is the extra space around the control. The padding is extra space inside the control.

It's hard to see the difference with margin and padding with a white fill, but with a colored fill you can see it fine.

File count from a folder

Reading PDF files from a directory:

var list = Directory.GetFiles(@"C:\ScanPDF", "*.pdf");
if (list.Length > 0)
{

}

ESLint Parsing error: Unexpected token

I solved this issue by First, installing babel-eslint using npm

npm install babel-eslint --save-dev

Secondly, add this configuration in .eslintrc file

{
   "parser":"babel-eslint"
}

How can one check to see if a remote file exists using PHP?

This can be done by obtaining the HTTP Status code (404 = not found) which is possible with file_get_contentsDocs making use of context options. The following code takes redirects into account and will return the status code of the final destination (Demo):

$url = 'http://example.com/';
$code = FALSE;

$options['http'] = array(
    'method' => "HEAD",
    'ignore_errors' => 1
);

$body = file_get_contents($url, NULL, stream_context_create($options));

foreach($http_response_header as $header)
    sscanf($header, 'HTTP/%*d.%*d %d', $code);

echo "Status code: $code";

If you don't want to follow redirects, you can do it similar (Demo):

$url = 'http://example.com/';
$code = FALSE;

$options['http'] = array(
    'method' => "HEAD",
    'ignore_errors' => 1,
    'max_redirects' => 0
);

$body = file_get_contents($url, NULL, stream_context_create($options));

sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);

echo "Status code: $code";

Some of the functions, options and variables in use are explained with more detail on a blog post I've written: HEAD first with PHP Streams.

Is it possible to set UIView border properties from interface builder?

while this might set the properties, it doesnt actually reflect in IB. So if you're essentially writing code in IB, you might as well then do it in your source code

String's Maximum length in Java - calling length() method

java.io.DataInput.readUTF() and java.io.DataOutput.writeUTF(String) say that a String object is represented by two bytes of length information and the modified UTF-8 representation of every character in the string. This concludes that the length of String is limited by the number of bytes of the modified UTF-8 representation of the string when used with DataInput and DataOutput.

In addition, The specification of CONSTANT_Utf8_info found in the Java virtual machine specification defines the structure as follows.

CONSTANT_Utf8_info {
    u1 tag;
    u2 length;
    u1 bytes[length];
}

You can find that the size of 'length' is two bytes.

That the return type of a certain method (e.g. String.length()) is int does not always mean that its allowed maximum value is Integer.MAX_VALUE. Instead, in most cases, int is chosen just for performance reasons. The Java language specification says that integers whose size is smaller than that of int are converted to int before calculation (if my memory serves me correctly) and it is one reason to choose int when there is no special reason.

The maximum length at compilation time is at most 65536. Note again that the length is the number of bytes of the modified UTF-8 representation, not the number of characters in a String object.

String objects may be able to have much more characters at runtime. However, if you want to use String objects with DataInput and DataOutput interfaces, it is better to avoid using too long String objects. I found this limitation when I implemented Objective-C equivalents of DataInput.readUTF() and DataOutput.writeUTF(String).

Capture HTML Canvas as gif/jpg/png/pdf?

I would use "wkhtmltopdf". It just work great. It uses webkit engine (used in Chrome, Safari, etc.), and it is very easy to use:

wkhtmltopdf stackoverflow.com/questions/923885/ this_question.pdf

That's it!

Try it

How to insert the current timestamp into MySQL database using a PHP insert query

Instead of NOW() you can use UNIX_TIMESTAMP() also:

$update_query = "UPDATE db.tablename 
                 SET insert_time=UNIX_TIMESTAMP()
                 WHERE username='$somename'";

Difference between UNIX_TIMESTAMP and NOW() in MySQL

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList(); 

C# Test if user has write access to a folder

I faced the same problem: how to verify if I can read/write in a particular directory. I ended up with the easy solution to...actually test it. Here is my simple though effective solution.

 class Program
{

    /// <summary>
    /// Tests if can read files and if any are present
    /// </summary>
    /// <param name="dirPath"></param>
    /// <returns></returns>
    private genericResponse check_canRead(string dirPath)
    {
        try
        {
            IEnumerable<string> files = Directory.EnumerateFiles(dirPath);
            if (files.Count().Equals(0))
                return new genericResponse() { status = true, idMsg = genericResponseType.NothingToRead };

            return new genericResponse() { status = true, idMsg = genericResponseType.OK };
        }
        catch (DirectoryNotFoundException ex)
        {

            return new genericResponse() { status = false, idMsg = genericResponseType.ItemNotFound };

        }
        catch (UnauthorizedAccessException ex)
        {

            return new genericResponse() { status = false, idMsg = genericResponseType.CannotRead };

        }

    }

    /// <summary>
    /// Tests if can wirte both files or Directory
    /// </summary>
    /// <param name="dirPath"></param>
    /// <returns></returns>
    private genericResponse check_canWrite(string dirPath)
    {

        try
        {
            string testDir = "__TESTDIR__";
            Directory.CreateDirectory(string.Join("/", dirPath, testDir));

            Directory.Delete(string.Join("/", dirPath, testDir));


            string testFile = "__TESTFILE__.txt";
            try
            {
                TextWriter tw = new StreamWriter(string.Join("/", dirPath, testFile), false);
                tw.WriteLine(testFile);
                tw.Close();
                File.Delete(string.Join("/", dirPath, testFile));

                return new genericResponse() { status = true, idMsg = genericResponseType.OK };
            }
            catch (UnauthorizedAccessException ex)
            {

                return new genericResponse() { status = false, idMsg = genericResponseType.CannotWriteFile };

            }


        }
        catch (UnauthorizedAccessException ex)
        {

            return new genericResponse() { status = false, idMsg = genericResponseType.CannotWriteDir };

        }
    }


}

public class genericResponse
{

    public bool status { get; set; }
    public genericResponseType idMsg { get; set; }
    public string msg { get; set; }

}

public enum genericResponseType
{

    NothingToRead = 1,
    OK = 0,
    CannotRead = -1,
    CannotWriteDir = -2,
    CannotWriteFile = -3,
    ItemNotFound = -4

}

Hope it helps !

How to calculate percentage when old value is ZERO

When both values are zero, then the change is zero.

If one of the values is zero, it's infinite (ambiguous), but I would set it to 100%.

Here is a C++ code (where v1 is the previous value (old), and v2 is new):

double result = 0;
if (v1 != 0 && v2 != 0) {
  // If values are non-zero, use the standard formula.
  result = (v2 / v1) - 1;
} else if (v1 == 0 || v2 == 0) {
  // Change is zero when both values are zeros, otherwise it's 100%.
  result = v1 == 0 && v2 == 0 ? 0 : 1;
}
result = v2 > v1 ? abs(result) : -abs(result);
// Note: To have format in hundreds, multiply the result by 100.

Markdown `native` text alignment

I was trying to center an image and none of the techniques suggested in answers here worked. A regular HTML <img> with inline CSS worked for me...

<img style="display: block; margin: auto;" alt="photo" src="{{ site.baseurl }}/images/image.jpg">

This is for a Jekyll blog hosted on GitHub

How to modify existing, unpushed commit messages?

For anyone looking for a Windows/Mac GUI to help with editing older messages (i.e. not just the latest message), I'd recommend Sourcetree. The steps to follow are below the image.

Sourcetree interactive rebase

For commits that haven't been pushed to a remote yet:

  1. Make sure you've committed or stashed all current changes (i.e., so there are no files listed in the "File Status" tab) - it won't work otherwise.
  2. In the "Log / History" tab, right click on the entry with an adjoining line in the graph one below the commit(s) you wish to edit and select "Rebase children of <commit ref> interactively..."
  3. Select the whole row for a commit message you wish to change (click on the "Message" column).
  4. Click the "Edit Message" button.
  5. Edit the message as desired in the dialog that comes up and then click OK.
  6. Repeat steps 3-4 if there are other commit messages to change.
  7. Click OK: Rebasing will commence. If all is well, the output will end "Completed successfully". NOTE: I've sometimes seen this fail with Unable to create 'project_path/.git/index.lock': File exists. when trying to modify multiple commit messages at the same time. Not sure exactly what the issue is, or whether it will be fixed in a future version of Sourcetree, but if this happens would recommend rebasing them one at a time (slower but seems more reliable).

...Or... for commits that have already been pushed:

Follow the steps in this answer, which are similar to above, but require a further command to be run from the command line (git push origin <branch> -f) to force-push the branch. I'd recommend reading it all and applying the necessary caution!

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

This works for me:

android {
   packagingOptions {
       exclude 'LICENSE.txt'
   }
}

convert string to date in sql server

This will do the trick:

SELECT CONVERT(char(10), GetDate(),126)

No value accessor for form control

In my case, I used Angular forms with contenteditable elements like div and had similar problems before.

I wrote ng-contenteditable module to resolve this problem.

How to add an item to an ArrayList in Kotlin?

If you want to specifically use java ArrayList then you can do something like this:

fun initList(){
    val list: ArrayList<String> = ArrayList()
    list.add("text")
    println(list)
}

Otherwise @guenhter answer is the one you are looking for.

Xcode/Simulator: How to run older iOS version?

If you have iAds in your binary you will not be able to run it on anything before iOS 4.0 and it will be rejected if you try and submit a binary like this.

You can still run the simulator from 3.2 onwards after upgrading.

In the iPhone Simulator try selecting Hardware -> Version -> 3.2

How to change column datatype in SQL database without losing data

I can modify the table field's datatype, with these following query: and also in the Oracle DB,

ALTER TABLE table_name
MODIFY column_name datatype;

Is there a way to only install the mysql client (Linux)?

When I now just use the command: mysql

I get: Command 'mysql' not found, but can be installed with:

sudo apt install mysql-client-core-8.0 # version 8.0.22-0ubuntu0.20.04.2, or sudo apt install mariadb-client-core-10.3 # version 1:10.3.25-0ubuntu0.20.04.1

Very helpfull.

How do I convert a double into a string in C++?

Use to_string().
example :

#include <iostream>   
#include <string>  

using namespace std;
int main ()
{
    string pi = "pi is " + to_string(3.1415926);
    cout<< "pi = "<< pi << endl;

  return 0;
}

run it yourself : http://ideone.com/7ejfaU
These are available as well :

string to_string (int val);
string to_string (long val);
string to_string (long long val);
string to_string (unsigned val);
string to_string (unsigned long val);
string to_string (unsigned long long val);
string to_string (float val);
string to_string (double val);
string to_string (long double val);

Android new Bottom Navigation bar or BottomNavigationView

You can create the layouts according to the above-mentioned answers If anyone wants to use this in kotlin:-

 private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
    when (item.itemId) {
        R.id.images -> {
          // do your work....
            return@OnNavigationItemSelectedListener true
        }
       R.id.videos ->
         {
          // do your work....
            return@OnNavigationItemSelectedListener true
        }
    }
    false
}

then in oncreate you can set the above listener to your view

   mDataBinding?.navigation?.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener)

Absolute vs relative URLs

In most instances relative URLs are the way to go, they are portable by nature, which means if you wanted to lift your site and put it someone where else it would work instantly, reducing possibly hours of debugging.

There is a pretty decent article on absolute vs relative URLs, check it out.

How to recursively find and list the latest modified files in a directory with subdirectories and times

This is what I'm using (very efficient):

function find_last () { find "${1:-.}" -type f -printf '%TY-%Tm-%Td %TH:%TM %P\n' 2>/dev/null | sort | tail -n "${2:-10}"; }

PROS:

  • it spawns only 3 processes

USAGE:

find_last [dir [number]]

where:

  • dir - a directory to be searched [current dir]
  • number - number of newest files to display [10]

Output for find_last /etc 4 looks like this:

2019-07-09 12:12 cups/printers.conf
2019-07-09 14:20 salt/minion.d/_schedule.conf
2019-07-09 14:31 network/interfaces
2019-07-09 14:41 environment

How to load data from a text file in a PostgreSQL database?

The slightly modified version of COPY below worked better for me, where I specify the CSV format. This format treats backslash characters in text without any fuss. The default format is the somewhat quirky TEXT.

COPY myTable FROM '/path/to/file/on/server' ( FORMAT CSV, DELIMITER('|') );

How to programmatically connect a client to a WCF service?

You'll have to use the ChannelFactory class.

Here's an example:

var myBinding = new BasicHttpBinding();
var myEndpoint = new EndpointAddress("http://localhost/myservice");
using (var myChannelFactory = new ChannelFactory<IMyService>(myBinding, myEndpoint))
{
    IMyService client = null;

    try
    {
        client = myChannelFactory.CreateChannel();
        client.MyServiceOperation();
        ((ICommunicationObject)client).Close();
        myChannelFactory.Close();
    }
    catch
    {
        (client as ICommunicationObject)?.Abort();
    }
}

Related resources:

UTF-8 output from PowerShell

This is a bug in .NET. When PowerShell launches, it caches the output handle (Console.Out). The Encoding property of that text writer does not pick up the value StandardOutputEncoding property.

When you change it from within PowerShell, the Encoding property of the cached output writer returns the cached value, so the output is still encoded with the default encoding.

As a workaround, I would suggest not changing the encoding. It will be returned to you as a Unicode string, at which point you can manage the encoding yourself.

Caching example:

102 [C:\Users\leeholm]
>> $r1 = [Console]::Out

103 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US



104 [C:\Users\leeholm]
>> [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

105 [C:\Users\leeholm]
>> $r1

Encoding                                          FormatProvider
--------                                          --------------
System.Text.SBCSCodePageEncoding                  en-US

Is there any difference between a GUID and a UUID?

Not really. GUID is more Microsoft-centric whereas UUID is used more widely (e.g., as in the urn:uuid: URN scheme, and in CORBA).

MISCONF Redis is configured to save RDB snapshots

There might be errors during the bgsave process due to low memory. Try this (from redis background save FAQ)

echo 'vm.overcommit_memory = 1' >> /etc/sysctl.conf
sysctl vm.overcommit_memory=1

Redirect form to different URL based on select option element

This can be archived by adding code on the onchange event of the select control.

For Example:

<select onchange="this.options[this.selectedIndex].value && (window.location = this.options[this.selectedIndex].value);">
    <option value="http://gmail.com">Gmail</option>
    <option value="http://youtube.com">Youtube</option>
</select>

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

What are the obj and bin folders (created by Visual Studio) used for?

The obj directory is for intermediate object files and other transient data files that are generated by the compiler or build system during a build. The bin directory is the directory that final output binaries (and any dependencies or other deployable files) will be written to.

You can change the actual directories used for both purposes within the project settings, if you like.

Uncaught TypeError: Cannot read property 'toLowerCase' of undefined

It causes the error when you access $(this).val() when it called by change event this points to the invoker i.e. CourseSelect so it is working and and will get the value of CourseSelect. but when you manually call it this points to document. so either you will have to pass the CourseSelect object or access directly like $("#CourseSelect").val() instead of $(this).val().

Is it possible to clone html element objects in JavaScript / JQuery?

Yes, you can copy children of one element and paste them into the other element:

var foo1 = jQuery('#foo1');
var foo2 = jQuery('#foo2');

foo1.html(foo2.children().clone());

Proof: http://jsfiddle.net/de9kc/

Git with SSH on Windows

I was trying to solve my issue with some of the answers above and for some reason it didn't work. I did switch to use the git extensions and this are the steps I did follow.

  1. I went to Tools -> Settings -> SSH -> Other ssh client
  2. Set this value to C:\Program Files\Git\usr\bin\ssh.exe
  3. Apply

I guess that this steps are just the same explained above. The only difference is that I used the Git Extensions User Interface instead of the terminal. Hope this help.

Root element is missing

I had the same problem when i have trying to read xml that was extracted from archive to memory stream.

 MemoryStream SubSetupStream = new MemoryStream();
        using (ZipFile archive = ZipFile.Read(zipPath))
        {
            archive.Password = "SomePass";
            foreach  (ZipEntry file in archive)
            {
                file.Extract(SubSetupStream);
            }
        }

Problem was in these lines:

XmlDocument doc = new XmlDocument();
    doc.Load(SubSetupStream);

And solution is (Thanks to @Phil):

        if (SubSetupStream.Position>0)
        {
            SubSetupStream.Position = 0;
        }

Changing Java Date one hour back

To subtract hours, you need to use the HOUR_OF_DAY constant. Within that, include the number with the negative sign. This would be the hours you want to reduce. All this is done under the Calendar add() method.

The following is an example:

import java.util.Calendar;
public class Example {
  public static void main(String[] args) {
   Calendar c = Calendar.getInstance();
     System.out.println("Date : " + c.getTime());
       // 2 hours subtracted
   c.add(Calendar.HOUR_OF_DAY, -2);
   System.out.println("After subtracting 2 hrs : " + c.getTime());
 }
}

Here is the output:

Date : Sun Dec 16 16:28:53 UTC 2018
After subtracting 2 hrs : Sun Dec 16 14:28:53 UTC 2018

Detect If Browser Tab Has Focus

Cross Browser jQuery Solution! Raw available at GitHub

Fun & Easy to Use!

The following plugin will go through your standard test for various versions of IE, Chrome, Firefox, Safari, etc.. and establish your declared methods accordingly. It also deals with issues such as:

  • onblur|.blur/onfocus|.focus "duplicate" calls
  • window losing focus through selection of alternate app, like word
    • This tends to be undesirable simply because, if you have a bank page open, and it's onblur event tells it to mask the page, then if you open calculator, you can't see the page anymore!
  • Not triggering on page load

Use is as simple as: Scroll Down to 'Run Snippet'

$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);
});

//  OR Pass False boolean, and it will not trigger on load,
//  Instead, it will first trigger on first blur of current tab_window
$.winFocus(function(event, isVisible) {
    console.log("Combo\t\t", event, isVisible);
}, false);

//  OR Establish an object having methods "blur" & "focus", and/or "blurFocus"
//  (yes, you can set all 3, tho blurFocus is the only one with an 'isVisible' param)
$.winFocus({
    blur: function(event) {
        console.log("Blur\t\t", event);
    },
    focus: function(event) {
        console.log("Focus\t\t", event);
    }
});

//  OR First method becoms a "blur", second method becoms "focus"!
$.winFocus(function(event) {
    console.log("Blur\t\t", event);
},
function(event) {
    console.log("Focus\t\t", event);
});

_x000D_
_x000D_
/*    Begin Plugin    */_x000D_
;;(function($){$.winFocus||($.extend({winFocus:function(){var a=!0,b=[];$(document).data("winFocus")||$(document).data("winFocus",$.winFocus.init());for(x in arguments)"object"==typeof arguments[x]?(arguments[x].blur&&$.winFocus.methods.blur.push(arguments[x].blur),arguments[x].focus&&$.winFocus.methods.focus.push(arguments[x].focus),arguments[x].blurFocus&&$.winFocus.methods.blurFocus.push(arguments[x].blurFocus),arguments[x].initRun&&(a=arguments[x].initRun)):"function"==typeof arguments[x]?b.push(arguments[x]):_x000D_
"boolean"==typeof arguments[x]&&(a=arguments[x]);b&&(1==b.length?$.winFocus.methods.blurFocus.push(b[0]):($.winFocus.methods.blur.push(b[0]),$.winFocus.methods.focus.push(b[1])));if(a)$.winFocus.methods.onChange()}}),$.winFocus.init=function(){$.winFocus.props.hidden in document?document.addEventListener("visibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="mozHidden")in document?document.addEventListener("mozvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden=_x000D_
"webkitHidden")in document?document.addEventListener("webkitvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="msHidden")in document?document.addEventListener("msvisibilitychange",$.winFocus.methods.onChange):($.winFocus.props.hidden="onfocusin")in document?document.onfocusin=document.onfocusout=$.winFocus.methods.onChange:window.onpageshow=window.onpagehide=window.onfocus=window.onblur=$.winFocus.methods.onChange;return $.winFocus},$.winFocus.methods={blurFocus:[],blur:[],focus:[],_x000D_
exeCB:function(a){$.winFocus.methods.blurFocus&&$.each($.winFocus.methods.blurFocus,function(b,c){this.apply($.winFocus,[a,!a.hidden])});a.hidden&&$.winFocus.methods.blur&&$.each($.winFocus.methods.blur,function(b,c){this.apply($.winFocus,[a])});!a.hidden&&$.winFocus.methods.focus&&$.each($.winFocus.methods.focus,function(b,c){this.apply($.winFocus,[a])})},onChange:function(a){var b={focus:!1,focusin:!1,pageshow:!1,blur:!0,focusout:!0,pagehide:!0};if(a=a||window.event)a.hidden=a.type in b?b[a.type]:_x000D_
document[$.winFocus.props.hidden],$(window).data("visible",!a.hidden),$.winFocus.methods.exeCB(a);else try{$.winFocus.methods.onChange.call(document,new Event("visibilitychange"))}catch(c){}}},$.winFocus.props={hidden:"hidden"})})(jQuery);_x000D_
/*    End Plugin      */_x000D_
_x000D_
// Simple example_x000D_
$(function() {_x000D_
 $.winFocus(function(event, isVisible) {_x000D_
  $('td tbody').empty();_x000D_
  $.each(event, function(i) {_x000D_
   $('td tbody').append(_x000D_
    $('<tr />').append(_x000D_
     $('<th />', { text: i }),_x000D_
     $('<td />', { text: this.toString() })_x000D_
    )_x000D_
   )_x000D_
  });_x000D_
  if (isVisible) _x000D_
   $("#isVisible").stop().delay(100).fadeOut('fast', function(e) {_x000D_
    $('body').addClass('visible');_x000D_
    $(this).stop().text('TRUE').fadeIn('slow');_x000D_
   });_x000D_
  else {_x000D_
   $('body').removeClass('visible');_x000D_
   $("#isVisible").text('FALSE');_x000D_
  }_x000D_
 });_x000D_
})
_x000D_
body { background: #AAF; }_x000D_
table { width: 100%; }_x000D_
table table { border-collapse: collapse; margin: 0 auto; width: auto; }_x000D_
tbody > tr > th { text-align: right; }_x000D_
td { width: 50%; }_x000D_
th, td { padding: .1em .5em; }_x000D_
td th, td td { border: 1px solid; }_x000D_
.visible { background: #FFA; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<h3>See Console for Event Object Returned</h3>_x000D_
<table>_x000D_
    <tr>_x000D_
        <th><p>Is Visible?</p></th>_x000D_
        <td><p id="isVisible">TRUE</p></td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
        <td colspan="2">_x000D_
            <table>_x000D_
                <thead>_x000D_
                    <tr>_x000D_
                        <th colspan="2">Event Data <span style="font-size: .8em;">{ See Console for More Details }</span></th>_x000D_
                    </tr>_x000D_
                </thead>_x000D_
                <tbody></tbody>_x000D_
            </table>_x000D_
        </td>_x000D_
    </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How can I check if a file exists in Perl?

Test whether something exists at given path using the -e file-test operator.

print "$base_path exists!\n" if -e $base_path;

However, this test is probably broader than you intend. The code above will generate output if a plain file exists at that path, but it will also fire for a directory, a named pipe, a symlink, or a more exotic possibility. See the documentation for details.

Given the extension of .TGZ in your question, it seems that you expect a plain file rather than the alternatives. The -f file-test operator asks whether a path leads to a plain file.

print "$base_path is a plain file!\n" if -f $base_path;

The perlfunc documentation covers the long list of Perl's file-test operators that covers many situations you will encounter in practice.

  • -r
    File is readable by effective uid/gid.
  • -w
    File is writable by effective uid/gid.
  • -x
    File is executable by effective uid/gid.
  • -o
    File is owned by effective uid.
  • -R
    File is readable by real uid/gid.
  • -W
    File is writable by real uid/gid.
  • -X
    File is executable by real uid/gid.
  • -O
    File is owned by real uid.
  • -e
    File exists.
  • -z
    File has zero size (is empty).
  • -s
    File has nonzero size (returns size in bytes).
  • -f
    File is a plain file.
  • -d
    File is a directory.
  • -l
    File is a symbolic link (false if symlinks aren’t supported by the file system).
  • -p
    File is a named pipe (FIFO), or Filehandle is a pipe.
  • -S
    File is a socket.
  • -b
    File is a block special file.
  • -c
    File is a character special file.
  • -t
    Filehandle is opened to a tty.
  • -u
    File has setuid bit set.
  • -g
    File has setgid bit set.
  • -k
    File has sticky bit set.
  • -T
    File is an ASCII or UTF-8 text file (heuristic guess).
  • -B
    File is a “binary” file (opposite of -T).
  • -M
    Script start time minus file modification time, in days.
  • -A
    Same for access time.
  • -C
    Same for inode change time (Unix, may differ for other platforms)

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

In [9]: pd.Series(df.Letter.values,index=df.Position).to_dict()
Out[9]: {1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}

Speed comparion (using Wouter's method)

In [6]: df = pd.DataFrame(randint(0,10,10000).reshape(5000,2),columns=list('AB'))

In [7]: %timeit dict(zip(df.A,df.B))
1000 loops, best of 3: 1.27 ms per loop

In [8]: %timeit pd.Series(df.A.values,index=df.B).to_dict()
1000 loops, best of 3: 987 us per loop

Terminal Multiplexer for Microsoft Windows - Installers for GNU Screen or tmux

As an alternative SuperPutty has tabs and the option to run the same command across many terminals... might be what someone is looking for.

https://code.google.com/p/superputty/

It imports your PuTTY sessions too.

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

How can I find the first and last date in a month using PHP?

If you want to find the first day and last day from the specified date variable then you can do this like below:

$date    =    '2012-02-12';//your given date

$first_date_find = strtotime(date("Y-m-d", strtotime($date)) . ", first day of this month");
echo $first_date = date("Y-m-d",$first_date_find);

$last_date_find = strtotime(date("Y-m-d", strtotime($date)) . ", last day of this month");
echo $last_date = date("Y-m-d",$last_date_find);

For the current date just simple use this

$first_date = date('Y-m-d',strtotime('first day of this month'));
$last_date = date('Y-m-d',strtotime('last day of this month'));

Saving Excel workbook to constant path with filename from two fields

try

Sub save()
ActiveWorkbook.SaveAS Filename:="C:\-docs\cmat\Desktop\New folder\" & Range("C5").Text & chr(32) & Range("C8").Text &".xls", FileFormat:= _
  xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
 , CreateBackup:=False
End Sub

If you want to save the workbook with the macros use the below code

Sub save()
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xlsm", FileFormat:= _
    xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
    ReadOnlyRecommended:=False, CreateBackup:=False
End Sub

if you want to save workbook with no macros and no pop-up use this

Sub save()
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xls", _
    FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    Application.DisplayAlerts = True
End Sub

std::enable_if to conditionally compile a member function

For those late-comers that are looking for a solution that "just works":

#include <utility>
#include <iostream>

template< typename T >
class Y {

    template< bool cond, typename U >
    using resolvedType  = typename std::enable_if< cond, U >::type; 

    public:
        template< typename U = T > 
        resolvedType< true, U > foo() {
            return 11;
        }
        template< typename U = T >
        resolvedType< false, U > foo() {
            return 12;
        }

};


int main() {
    Y< double > y;

    std::cout << y.foo() << std::endl;
}

Compile with:

g++ -std=gnu++14 test.cpp 

Running gives:

./a.out 
11

How to create/make rounded corner buttons in WPF?

Well the best way to get round corners fast and with standard animation is to create a copy of the control template with Blend. Once you get a copy set the corner radius on the Grid tag and you should be able to have your control with full animation functionality and applyable to any button control. look this is the code:

<ControlTemplate x:Key="ButtonControlTemplate" TargetType="Button">        
    <Grid x:Name="RootGrid" Background="{TemplateBinding Background}"
          CornerRadius="8,8,8,8">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal">
                    <Storyboard>
                        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="PointerOver">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundPointerOver}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPointerOver}" />
                        </ObjectAnimationUsingKeyFrames>
                        <PointerUpThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Pressed">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundPressed}" />
                        </ObjectAnimationUsingKeyFrames>
                        <PointerDownThemeAnimation Storyboard.TargetName="RootGrid" />
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="Disabled">
                    <Storyboard>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="RootGrid" Storyboard.TargetProperty="Background">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBackgroundDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="BorderBrush">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonBorderBrushDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ContentPresenter" Storyboard.TargetProperty="Foreground">
                            <DiscreteObjectKeyFrame KeyTime="0" Value="{ThemeResource ButtonForegroundDisabled}" />
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        <!--<Border CornerRadius="8,8,8,8"
                        Background="#002060"
                        BorderBrush="Red"
                        BorderThickness="2">-->
            <ContentPresenter x:Name="ContentPresenter"
                              BorderBrush="{TemplateBinding BorderBrush}"
                              BorderThickness="{TemplateBinding BorderThickness}"
                              Content="{TemplateBinding Content}"
                              ContentTransitions="{TemplateBinding ContentTransitions}"
                              ContentTemplate="{TemplateBinding ContentTemplate}"
                              Padding="{TemplateBinding Padding}"
                              HorizontalContentAlignment="{TemplateBinding HorizontalContentAlignment}"
                              VerticalContentAlignment="{TemplateBinding VerticalContentAlignment}"
                              AutomationProperties.AccessibilityView="Raw"/>
        <!--</Border>-->
    </Grid>        
</ControlTemplate>

I also edited the VisualState="PointerOver" specifically at Storyboard.TargetName="BorderBrush", because its ThemeResource get squared corners whenever PointerOver triggers.

Then you should be able to apply it to your control style like this:

<Style TargetType="ContentControl" x:Key="ButtonLoginStyle"
       BasedOn="{StaticResource CommonLoginStyleMobile}">
    <Setter Property="FontWeight" Value="Bold"/>
    <Setter Property="Background" Value="#002060"/>
    <Setter Property="Template" Value="{StaticResource ButtonControlTemplate}"/>        
</Style>

So you can apply your styles to any Button.

ActiveRecord OR query

in Rails 3, it should be

Model.where("column = ? or other_column = ?", value, other_value)

This also includes raw sql but I dont think there is a way in ActiveRecord to do OR operation. Your question is not a noob question.

How to disable XDebug

Apache/2.4.33 (Win64) PHP/7.2.4 myHomeBrew stack

At end of php.ini I use the following to manage Xdebug for use with PhpStorm

; jch ~ Sweet analizer at https://xdebug.org/wizard.php for matching xdebug to php version.
; jch ~ When upgrading php versions check if newer xdebug.dll is needed in ext directory.
; jch Renamed... zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug-2.6.0-7.2-vc15-x86_64.dll

zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug.dll

; jch !!!! Added the following for Xdebug with PhpStorm

[Xdebug]
; zend_extension=<full_path_to_xdebug_extension>
; xdebug.remote_host=<the host where PhpStorm is running (e.g. localhost)>
; xdebug.remote_port=<the port to which Xdebug tries to connect on the host where PhpStorm is running (default 9000)>

xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000

xdebug.profiler_enable=1
xdebug.profiler_output_dir="E:\x64Stack\Xdebug_profiler_output"
xdebug.idekey=PHPSTORM
xdebug.remote_autostart=1

; jch ~~~~~~~~~To turn Xdebug off(disable) uncomment the following 3 lines restart Apache~~~~~~~~~ 
;xdebug.remote_autostart=0  
;xdebug.remote_enable=0
;xdebug.profiler_enable=0

; !!! Might get a little more speed by also commenting out this line above... 
;;; zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug.dll
; so that Xdebug is both disabled AND not loaded

Odd behavior when Java converts int to byte?

  1. In java int takes 4 bytes=4x8=32 bits
  2. byte = 8 bits range=-128 to 127

converting 'int' into 'byte' is like fitting big object into small box

if sign in -ve takes 2's complement

example 1: let number be 130

step 1:130 interms of bits =1000 0010

step 2:condider 1st 7 bits and 8th bit is sign(1=-ve and =+ve)

step 3:convert 1st 7 bits to 2's compliment

            000 0010   
          -------------
            111 1101
       add         1
          -------------
            111 1110 =126

step 4:8th bit is "1" hence the sign is -ve

step 5:byte of 130=-126

Example2: let number be 500

step 1:500 interms of bits 0001 1111 0100

step 2:consider 1st 7 bits =111 0100

step 3: the remained bits are '11' gives -ve sign

step 4: take 2's compliment

        111 0100
      -------------
        000 1011 
    add        1
      -------------
        000 1100 =12

step 5:byte of 500=-12

example 3: number=300

 300=1 0010 1100

 1st 7 bits =010 1100

 remaining bit is '0' sign =+ve need not take 2's compliment for +ve sign

 hence 010 1100 =44

 byte(300) =44

How to handle change text of span

Span does not have 'change' event by default. But you can add this event manually.

Listen to the change event of span.

$("#span1").on('change',function(){
     //Do calculation and change value of other span2,span3 here
     $("#span2").text('calculated value');
});

And wherever you change the text in span1. Trigger the change event manually.

$("#span1").text('test').trigger('change'); 

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

Same issue i faced , when copy the project from another system. In my case i fixed this issue:

delete everythings from inside Bin folder. Clean & Rebuild the app again

Hope this will help.

How can I list all of the files in a directory with Perl?

Or File::Find

use File::Find;
finddepth(\&wanted, '/some/path/to/dir');
sub wanted { print };

It'll go through subdirectories if they exist.

How to run an EXE file in PowerShell with parameters with spaces and quotes

You can use:

Start-Process -FilePath "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe" -ArgumentList "-verb:sync -source:dbfullsql="Data Source=mysource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;" -dest:dbfullsql="Data Source=.\mydestsource;Integrated Security=false;User ID=sa;Pwd=sapass!;Database=mydb;",computername=10.10.10.10,username=administrator,password=adminpass"

The key thing to note here is that FilePath must be in position 0, according to the Help Guide. To invoke the Help guide for a commandlet, just type in Get-Help <Commandlet-name> -Detailed . In this case, it is Get-Help Start-Process -Detailed.

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

How to change font size in html?

You can do this by setting a style in your paragraph tag. For example if you wanted to change the font size to 28px.

<p style="font-size: 28px;"> Hello, World! </p>

You can also set the color by setting:

<p style="color: blue;"> Hello, World! </p>

However, if you want to preview font sizes and colors (which I recommend doing) before you add them to your website and use them. I recommend testing them out beforehand so you pick a good font size and color that contrasts well with the background. I recommend using this site if you wish to do so, couldn't find anything else: http://fontpreview.herokuapp.com/

DateTime format to SQL format using C#

Using the standard datetime format "s" will also ensure internationalization compatibility (MM/dd versus dd/MM):

myDateTime.ToString("s");

=> 2013-12-31T00:00:00

Complete Options: (code: sample result)

d: 6/15/2008 
D: Sunday, June 15, 2008 
f: Sunday, June 15, 2008 9:15 PM 
F: Sunday, June 15, 2008 9:15:07 PM 
g: 6/15/2008 9:15 PM 
G: 6/15/2008 9:15:07 PM 
m: June 15 
o: 2008-06-15T21:15:07.0000000 
R: Sun, 15 Jun 2008 21:15:07 GMT 
s: 2008-06-15T21:15:07 
t: 9:15 PM 
T: 9:15:07 PM 
u: 2008-06-15 21:15:07Z 
U: Monday, June 16, 2008 4:15:07 AM 
y: June, 2008 

'h:mm:ss.ff t': 9:15:07.00 P 
'd MMM yyyy': 15 Jun 2008 
'HH:mm:ss.f': 21:15:07.0 
'dd MMM HH:mm:ss': 15 Jun 21:15:07 
'\Mon\t\h\: M': Month: 6 
'HH:mm:ss.ffffzzz': 21:15:07.0000-07:00

Supported in .NET Framework: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0
Reference: DateTime.ToString Method

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

I had this same error showing. When I replaced jQuery selector with normal JavaScript, the error was fixed.

var this_id = $(this).attr('id');

Replace:

getComputedStyle( $('#'+this_id)[0], "")

With:

getComputedStyle( document.getElementById(this_id), "")

Create a string and append text to it

Use the string concatenation operator:

Dim str As String = New String("") & "some other string"

Strings in .NET are immutable and thus there exist no concept of appending strings. All string modifications causes a new string to be created and returned.

This obviously cause a terrible performance. In common everyday code this isn't an issue, but if you're doing intensive string operations in which time is of the essence then you will benefit from looking into the StringBuilder class. It allow you to queue appends. Once you're done appending you can ask it to actually perform all the queued operations.

See "How to: Concatenate Multiple Strings" for more information on both methods.

Maven: The packaging for this project did not assign a file to the build artifact

While @A_Di-Matteo answer does work for non multimodule I have a solution for multimodules.

The solution is to override every plugin configuration so that it binds to the phase of none with the exception of the jar/war/ear plugin and of course the deploy plugin. Even if you do have a single module my rudimentary tests show this to be a little faster (for reasons I don't know) performance wise.

Thus the trick is to make a profile that does the above that is activated when you only want to deploy.

Below is an example from one of my projects which uses the shade plugin and thus I had to re-override the jar plugin not to overwrite:

    <profile>
      <id>deploy</id>
      <activation>
        <property>
          <name>buildStep</name>
          <value>deploy</value>
        </property>
      </activation>
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <executions>
              <execution>
                <id>default-compile</id>
                <phase>none</phase>
              </execution>
              <execution>
                <id>default-testCompile</id>
                <phase>none</phase>
              </execution>
              <execution>
                <id>test-compile</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <executions>
              <execution>
                <id>default-test</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-install-plugin</artifactId>
            <executions>
              <execution>
                <id>default-install</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-resources-plugin</artifactId>
            <executions>
              <execution>
                <id>default-resources</id>
                <phase>none</phase>
              </execution>
              <execution>
                <id>default-testResources</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <executions>
              <execution>
                <id>default</id>
                <phase>none</phase>
              </execution>
            </executions>
          </plugin>
          <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <executions>
              <execution>
                <id>default-jar</id>
                <configuration>
                  <forceCreation>false</forceCreation>
                </configuration>
              </execution>
            </executions>
          </plugin>
        </plugins>
      </build>
    </profile>

Now if I run mvn deploy -Pdeploy it will only run the jar and deploy plugins.

How you can figure out which plugins you need to override is to run deploy and look at the log to see which plugins are running. Make sure to keep track of the id of the plugin configuration which is parens after the name of the plugin.

Parse DateTime string in JavaScript

We use this code to check if the string is a valid date

var dt = new Date(txtDate.value)
if (isNaN(dt))

jquery (or pure js) simulate enter key pressed for testing

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

How to put/get multiple JSONObjects to JSONArray?

From android API Level 19, when I want to instance JSONArray object I put JSONObject directly as parameter like below:

JSONArray jsonArray=new JSONArray(jsonObject);

JSONArray has constructor to accept object.

What is the difference between git clone and checkout?

One thing to notice is the lack of any "Copyout" within git. That's because you already have a full copy in your local repo - your local repo being a clone of your chosen upstream repo. So you have effectively a personal checkout of everything, without putting some 'lock' on those files in the reference repo.

Git provides the SHA1 hash values as the mechanism for verifying that the copy you have of a file / directory tree / commit / repo is exactly the same as that used by whoever is able to declare things as "Master" within the hierarchy of trust. This avoids all those 'locks' that cause most SCM systems to choke (with the usual problems of private copies, big merges, and no real control or management of source code ;-) !

How to use C++ in Go

You can't quite yet from what I read in the FAQ:

Do Go programs link with C/C++ programs?

There are two Go compiler implementations, gc (the 6g program and friends) and gccgo. Gc uses a different calling convention and linker and can therefore only be linked with C programs using the same convention. There is such a C compiler but no C++ compiler. Gccgo is a GCC front-end that can, with care, be linked with GCC-compiled C or C++ programs.

The cgo program provides the mechanism for a “foreign function interface” to allow safe calling of C libraries from Go code. SWIG extends this capability to C++ libraries.

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

POST request with a simple string in body with Alamofire

func paramsFromJSON(json: String) -> [String : AnyObject]?
{
    let objectData: NSData = (json.dataUsingEncoding(NSUTF8StringEncoding))!
    var jsonDict: [ String : AnyObject]!
    do {
        jsonDict = try NSJSONSerialization.JSONObjectWithData(objectData, options: .MutableContainers) as! [ String : AnyObject]
        return jsonDict
    } catch {
        print("JSON serialization failed:  \(error)")
        return nil
    }
}

let json = Mapper().toJSONString(loginJSON, prettyPrint: false)

Alamofire.request(.POST, url + "/login", parameters: paramsFromJSON(json!), encoding: .JSON)

File being used by another process after using File.Create()

I know this is an old question, but I just want to throw this out there that you can still use File.Create("filename")", just add .Dispose() to it.

File.Create("filename").Dispose();

This way it creates and closes the file for the next process to use it.

How do I supply an initial value to a text field?

class _YourClassState extends State<YourClass> {
  TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    _controller.text = 'Your message';
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      child: TextFormField(
        controller: _controller,
        decoration: InputDecoration(labelText: 'Send message...'),
      ),
    );
  }
}

How to make shadow on border-bottom?

New method for an old question

enter image description here

It seems like in the answers provided the issue was always how the box border would either be visible on the left and right of the object or you'd have to inset it so far that it didn't shadow the whole length of the container properly.

This example uses the :after pseudo element along with a linear gradient with transparency in order to put a drop shadow on a container that extends exactly to the sides of the element you wish to shadow.

Worth noting with this solution is that if you use padding on the element that you wish to drop shadow, it won't display correctly. This is because the after pseudo element appends it's content directly after the elements inner content. So if you have padding, the shadow will appear inside the box. This can be overcome by eliminating padding on outer container (where the shadow applies) and using an inner container where you apply needed padding.

Example with padding and background color on the shadowed div:

enter image description here

If you want to change the depth of the shadow, simply increase the height style in the after pseudo element. You can also obviously darken, lighten, or change colors in the linear gradient styles.

_x000D_
_x000D_
body {_x000D_
  background: #eee;_x000D_
}_x000D_
_x000D_
.bottom-shadow {_x000D_
  width: 80%;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
.bottom-shadow:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  height: 8px;_x000D_
  background: transparent;_x000D_
  background: -moz-linear-gradient(top, rgba(0,0,0,0.4) 0%, rgba(0,0,0,0) 100%); /* FF3.6-15 */_x000D_
  background: -webkit-linear-gradient(top, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* Chrome10-25,Safari5.1-6 */_x000D_
  background: linear-gradient(to bottom, rgba(0,0,0,0.4) 0%,rgba(0,0,0,0) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */_x000D_
  filter: progid:DXImageTransform.Microsoft.gradient(   startColorstr='#a6000000', endColorstr='#00000000',GradientType=0 ); /* IE6-9 */_x000D_
}_x000D_
_x000D_
.bottom-shadow div {_x000D_
  padding: 18px;_x000D_
  background: #fff;_x000D_
}
_x000D_
<div class="bottom-shadow">_x000D_
  <div>_x000D_
    Shadows, FTW!_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Maintain the aspect ratio of a div with CSS

As @web-tiki already show a way to use vh/vw, I also need a way to center in the screen, here is a snippet code for 9:16 portrait.

.container {
  width: 100vw;
  height: calc(100vw * 16 / 9);
  transform: translateY(calc((100vw * 16 / 9 - 100vh) / -2));
}

translateY will keep this center in the screen. calc(100vw * 16 / 9) is expected height for 9/16.(100vw * 16 / 9 - 100vh) is overflow height, so, pull up overflow height/2 will keep it center on screen.

For landscape, and keep 16:9, you show use

.container {
  width: 100vw;
  height: calc(100vw * 9 / 16);
  transform: translateY(calc((100vw * 9 / 16 - 100vh) / -2));
}

The ratio 9/16 is ease to change, no need to predefined 100:56.25 or 100:75.If you want to ensure height first, you should switch width and height, e.g. height:100vh;width: calc(100vh * 9 / 16) for 9:16 portrait.

If you want to adapted for different screen size, you may also interest

  • background-size cover/contain
    • Above style is similar to contain, depends on width:height ratio.
  • object-fit
    • cover/contain for img/video tag
  • @media (orientation: portrait)/@media (orientation: landscape)
    • Media query for portrait/landscape to change the ratio.

Class 'DOMDocument' not found

For PHP 7.4 Install the DOM extension.

Debian / Ubuntu:

sudo apt-get update
sudo apt-get install php7.4-xml
sudo service apache2 restart

Centos / Fedora / Red Hat:

yum update
yum install php74w-xml
systemctl restart httpd

For previous PHP releases, replace with your version.

Git - deleted some files locally, how do I get them from a remote repository

If you deleted multiple files locally and did not commit the changes, go to your local repository path, open the git shell and type.

$ git checkout HEAD .

All the deleted files before the last commit will be recovered.

Adding "." will recover all the deleted the files in the current repository, to their respective paths.

For more details checkout the documentation.

jQuery count child elements

fastest one:

$("div#selected ul li").length

Using Python 3 in virtualenv

In addition to the other answers, I recommend checking what instance of virtualenv you are executing:

which virtualenv

If this turns up something in /usr/local/bin, then it is possible - even likely - that you installed virtualenv (possibly using an instance of easy_tools or pip) without using your system's package manager (brew in OP's case). This was my problem.

Years ago - when I was even more ignorant - I had installed virtualenv and it was masking my system's package-provided virtualenv.

After removing this old, broken virtualenv, my problems went away.

Should I use pt or px?

Have a look at this excellent article at CSS-Tricks:

Taken from the article:


pt

The final unit of measurement that it is possible to declare font sizes in is point values (pt). Point values are only for print CSS! A point is a unit of measurement used for real-life ink-on-paper typography. 72pts = one inch. One inch = one real-life inch like-on-a-ruler. Not an inch on a screen, which is totally arbitrary based on resolution.

Just like how pixels are dead-accurate on monitors for font-sizing, point sizes are dead-accurate on paper. For the best cross-browser and cross-platform results while printing pages, set up a print stylesheet and size all fonts with point sizes.

For good measure, the reason we don't use point sizes for screen display (other than it being absurd), is that the cross-browser results are drastically different:

px

If you need fine-grained control, sizing fonts in pixel values (px) is an excellent choice (it's my favorite). On a computer screen, it doesn't get any more accurate than a single pixel. With sizing fonts in pixels, you are literally telling browsers to render the letters exactly that number of pixels in height:

Windows, Mac, aliased, anti-aliased, cross-browsers, doesn't matter, a font set at 14px will be 14px tall. But that isn't to say there won't still be some variation. In a quick test below, the results were slightly more consistent than with keywords but not identical:

Due to the nature of pixel values, they do not cascade. If a parent element has an 18px pixel size and the child is 16px, the child will be 16px. However, font-sizing settings can be using in combination. For example, if the parent was set to 16px and the child was set to larger, the child would indeed come out larger than the parent. A quick test showed me this:

"Larger" bumped the 16px of the parent into 20px, a 25% increase.

Pixels have gotten a bad wrap in the past for accessibility and usability concerns. In IE 6 and below, font-sizes set in pixels cannot be resized by the user. That means that us hip young healthy designers can set type in 12px and read it on the screen just fine, but when folks a little longer in the tooth go to bump up the size so they can read it, they are unable to. This is really IE 6's fault, not ours, but we gots what we gots and we have to deal with it.

Setting font-size in pixels is the most accurate (and I find the most satisfying) method, but do take into consideration the number of visitors still using IE 6 on your site and their accessibility needs. We are right on the bleeding edge of not needing to care about this anymore.


Get file path of image on Android

I am doing this on click of Button.

private static final int CAMERA_PIC_REQUEST = 1;

private View.OnClickListener  OpenCamera=new View.OnClickListener() {

            @Override
            public void onClick(View paramView) {
                // TODO Auto-generated method stub

                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);

                NewSelectedImageURL=null;
                //outfile where we are thinking of saving it
                Date date = new Date();
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

                String newPicFile = RecipeName+ df.format(date) + ".png";


                String outPath =Environment.getExternalStorageDirectory() + "/myFolderName/"+ newPicFile ;
                File outFile = new File(outPath);               

                CapturedImageURL=outFile.toString();
                Uri outuri = Uri.fromFile(outFile);
                cameraIntent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, outuri);            
                startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);  

            }
        };

You can get the URL of the recently Captured Image from variable CapturedImageURL

protected void onActivityResult(int requestCode, int resultCode, Intent data) {  


    //////////////////////////////////////
    if (requestCode == CAMERA_PIC_REQUEST) {  
        // do something  

         if (resultCode == RESULT_OK) 
         {
             Uri uri = null;

             if (data != null) 
             {
                 uri = data.getData();
             }
             if (uri == null && CapturedImageURL != null) 
             {
                 uri = Uri.fromFile(new File(CapturedImageURL));
             }
             File file = new File(CapturedImageURL);
             if (!file.exists()) {
                file.mkdir();
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"+Environment.getExternalStorageDirectory())));
            }




         }


    }

How to use ConfigurationManager

I found some answers, but I don't know if it is the right way.This is my solution for now. Fortunatelly it didn´t broke my design mode.

    `
    /// <summary>
    /// set config, if key is not in file, create
    /// </summary>
    /// <param name="key">Nome do parâmetro</param>
    /// <param name="value">Valor do parâmetro</param>
    public static void SetConfig(string key, string value)
    {
        var configFile = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
        var settings = configFile.AppSettings.Settings;
        if (settings[key] == null)
        {
            settings.Add(key, value);
        }
        else
        {
            settings[key].Value = value;
        }
        configFile.Save(ConfigurationSaveMode.Modified);
        ConfigurationManager.RefreshSection(configFile.AppSettings.SectionInformation.Name);
    }

    /// <summary>
    /// Get key value, if not found, return null
    /// </summary>
    /// <param name="key"></param>
    /// <returns>null if key is not found, else string with value</returns>
    public static string GetConfig(string key)
    {
        return ConfigurationManager.AppSettings[key];
    }`

how to set radio button checked in edit mode in MVC razor view

Add checked to both of your radio button. And then show/hide your desired one on document ready.

<div class="form-group">
    <div class="mt-radio-inline" style="padding-left:15px;">
        <label class="mt-radio mt-radio-outline">
            Full Edition
            <input type="radio" value="@((int)SelectEditionTypeEnum.FullEdition)" asp-for="SelectEditionType" checked>
            <span></span>
        </label>
        <label class="mt-radio mt-radio-outline">
            Select Modules
            <input type="radio" value="@((int)SelectEditionTypeEnum.CustomEdition)" asp-for="SelectEditionType" checked>
            <span></span>
        </label>
    </div>
</div>

Regex remove all special characters except numbers?

This should work as well

text = 'the car? was big and* red!'

newtext = re.sub( '[^a-z0-9]', ' ', text)

print(newtext)

the car was big and red

Can git undo a checkout of unstaged files

I just had that happen to me, I checked out an entire folder containing hours of work! Fortunately I found out that my IDE Netbeans keeps an history of each file, that allowed me to recuperate 99% of the stuff even though I needed to fix a few things manually.

How to search through all Git and Mercurial commits in the repository for a certain string?

Don't know about git, but in Mercurial I'd just pipe the output of hg log to some sed/perl/whatever script to search for whatever it is you're looking for. You can customize the output of hg log using a template or a style to make it easier to search on, if you wish.

This will include all named branches in the repo. Mercurial does not have something like dangling blobs afaik.

How I can delete in VIM all text from current line to end of file?

:.,$d

This will delete all content from current line to end of the file. This is very useful when you're dealing with test vector generation or stripping.

HashMap get/put complexity

In practice, it is O(1), but this actually is a terrible and mathematically non-sense simplification. The O() notation says how the algorithm behaves when the size of the problem tends to infinity. Hashmap get/put works like an O(1) algorithm for a limited size. The limit is fairly large from the computer memory and from the addressing point of view, but far from infinity.

When one says that hashmap get/put is O(1) it should really say that the time needed for the get/put is more or less constant and does not depend on the number of elements in the hashmap so far as the hashmap can be presented on the actual computing system. If the problem goes beyond that size and we need larger hashmaps then, after a while, certainly the number of the bits describing one element will also increase as we run out of the possible describable different elements. For example, if we used a hashmap to store 32bit numbers and later we increase the problem size so that we will have more than 2^32 bit elements in the hashmap, then the individual elements will be described with more than 32bits.

The number of the bits needed to describe the individual elements is log(N), where N is the maximum number of elements, therefore get and put are really O(log N).

If you compare it with a tree set, which is O(log n) then hash set is O(long(max(n)) and we simply feel that this is O(1), because on a certain implementation max(n) is fixed, does not change (the size of the objects we store measured in bits) and the algorithm calculating the hash code is fast.

Finally, if finding an element in any data structure were O(1) we would create information out of thin air. Having a data structure of n element I can select one element in n different way. With that, I can encode log(n) bit information. If I can encode that in zero bit (that is what O(1) means) then I created an infinitely compressing ZIP algorithm.

Create file path from variables

You want the path.join() function from os.path.

>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'

This builds your path with os.sep (instead of the less portable '/') and does it more efficiently (in general) than using +.

However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:

start_path = '/my/root/directory'
final_path = os.join(start_path, *list_of_vars)
if not os.path.isdir(final_path):
    os.makedirs (final_path)

Intellij idea subversion checkout error: `Cannot run program "svn"`

Check my solution, It will work.

Solutions:

First Download Subversion 1.8.13 ( 1.8 ) Download link ( https://www.visualsvn.com/downloads/ )

enter image description here

Then unzipped in a folder. There will have one folder "bin".

Then

Go to settings - > Version control -> Subversion

Copy the url of your downloaded svn.exe that is in bin folder that you have downloaded.

follow the pic:

enter image description here

Don't forget to give the end name like svn.exe last as per image.

Apply -> Ok

Restart your android studio now.

Happy Coding!

How to cancel an $http request in AngularJS?

Cancelling Angular $http Ajax with the timeout property doesn't work in Angular 1.3.15. For those that cannot wait for this to be fixed I'm sharing a jQuery Ajax solution wrapped in Angular.

The solution involves two services:

  • HttpService (a wrapper around the jQuery Ajax function);
  • PendingRequestsService (tracks the pending/open Ajax requests)

Here goes the PendingRequestsService service:

    (function (angular) {
    'use strict';
    var app = angular.module('app');
    app.service('PendingRequestsService', ["$log", function ($log) {            
        var $this = this;
        var pending = [];
        $this.add = function (request) {
            pending.push(request);
        };
        $this.remove = function (request) {
            pending = _.filter(pending, function (p) {
                return p.url !== request;
            });
        };
        $this.cancelAll = function () {
            angular.forEach(pending, function (p) {
                p.xhr.abort();
                p.deferred.reject();
            });
            pending.length = 0;
        };
    }]);})(window.angular);

The HttpService service:

     (function (angular) {
        'use strict';
        var app = angular.module('app');
        app.service('HttpService', ['$http', '$q', "$log", 'PendingRequestsService', function ($http, $q, $log, pendingRequests) {
            this.post = function (url, params) {
                var deferred = $q.defer();
                var xhr = $.ASI.callMethod({
                    url: url,
                    data: params,
                    error: function() {
                        $log.log("ajax error");
                    }
                });
                pendingRequests.add({
                    url: url,
                    xhr: xhr,
                    deferred: deferred
                });            
                xhr.done(function (data, textStatus, jqXhr) {                                    
                        deferred.resolve(data);
                    })
                    .fail(function (jqXhr, textStatus, errorThrown) {
                        deferred.reject(errorThrown);
                    }).always(function (dataOrjqXhr, textStatus, jqXhrErrorThrown) {
                        //Once a request has failed or succeeded, remove it from the pending list
                        pendingRequests.remove(url);
                    });
                return deferred.promise;
            }
        }]);
    })(window.angular);

Later in your service when you are loading data you would use the HttpService instead of $http:

(function (angular) {

    angular.module('app').service('dataService', ["HttpService", function (httpService) {

        this.getResources = function (params) {

            return httpService.post('/serverMethod', { param: params });

        };
    }]);

})(window.angular);

Later in your code you would like to load the data:

(function (angular) {

var app = angular.module('app');

app.controller('YourController', ["DataService", "PendingRequestsService", function (httpService, pendingRequestsService) {

    dataService
    .getResources(params)
    .then(function (data) {    
    // do stuff    
    });    

    ...

    // later that day cancel requests    
    pendingRequestsService.cancelAll();
}]);

})(window.angular);

string encoding and decoding?

Aside from getting decode and encode backwards, I think part of the answer here is actually don't use the ascii encoding. It's probably not what you want.

To begin with, think of str like you would a plain text file. It's just a bunch of bytes with no encoding actually attached to it. How it's interpreted is up to whatever piece of code is reading it. If you don't know what this paragraph is talking about, go read Joel's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets right now before you go any further.

Naturally, we're all aware of the mess that created. The answer is to, at least within memory, have a standard encoding for all strings. That's where unicode comes in. I'm having trouble tracking down exactly what encoding Python uses internally for sure, but it doesn't really matter just for this. The point is that you know it's a sequence of bytes that are interpreted a certain way. So you only need to think about the characters themselves, and not the bytes.

The problem is that in practice, you run into both. Some libraries give you a str, and some expect a str. Certainly that makes sense whenever you're streaming a series of bytes (such as to or from disk or over a web request). So you need to be able to translate back and forth.

Enter codecs: it's the translation library between these two data types. You use encode to generate a sequence of bytes (str) from a text string (unicode), and you use decode to get a text string (unicode) from a sequence of bytes (str).

For example:

>>> s = "I look like a string, but I'm actually a sequence of bytes. \xe2\x9d\xa4"
>>> codecs.decode(s, 'utf-8')
u"I look like a string, but I'm actually a sequence of bytes. \u2764"

What happened here? I gave Python a sequence of bytes, and then I told it, "Give me the unicode version of this, given that this sequence of bytes is in 'utf-8'." It did as I asked, and those bytes (a heart character) are now treated as a whole, represented by their Unicode codepoint.

Let's go the other way around:

>>> u = u"I'm a string! Really! \u2764"
>>> codecs.encode(u, 'utf-8')
"I'm a string! Really! \xe2\x9d\xa4"

I gave Python a Unicode string, and I asked it to translate the string into a sequence of bytes using the 'utf-8' encoding. So it did, and now the heart is just a bunch of bytes it can't print as ASCII; so it shows me the hexadecimal instead.

We can work with other encodings, too, of course:

>>> s = "I have a section \xa7"
>>> codecs.decode(s, 'latin1')
u'I have a section \xa7'
>>> codecs.decode(s, 'latin1')[-1] == u'\u00A7'
True

>>> u = u"I have a section \u00a7"
>>> u
u'I have a section \xa7'
>>> codecs.encode(u, 'latin1')
'I have a section \xa7'

('\xa7' is the section character, in both Unicode and Latin-1.)

So for your question, you first need to figure out what encoding your str is in.

  • Did it come from a file? From a web request? From your database? Then the source determines the encoding. Find out the encoding of the source and use that to translate it into a unicode.

    s = [get from external source]
    u = codecs.decode(s, 'utf-8') # Replace utf-8 with the actual input encoding
    
  • Or maybe you're trying to write it out somewhere. What encoding does the destination expect? Use that to translate it into a str. UTF-8 is a good choice for plain text documents; most things can read it.

    u = u'My string'
    s = codecs.encode(u, 'utf-8') # Replace utf-8 with the actual output encoding
    [Write s out somewhere]
    
  • Are you just translating back and forth in memory for interoperability or something? Then just pick an encoding and stick with it; 'utf-8' is probably the best choice for that:

    u = u'My string'
    s = codecs.encode(u, 'utf-8')
    newu = codecs.decode(s, 'utf-8')
    

In modern programming, you probably never want to use the 'ascii' encoding for any of this. It's an extremely small subset of all possible characters, and no system I know of uses it by default or anything.

Python 3 does its best to make this immensely clearer simply by changing the names. In Python 3, str was replaced with bytes, and unicode was replaced with str.

HTML character codes for this ? or this ?

Check this page http://www.alanwood.net/unicode/geometric_shapes.html, first is "9650 ? 25B2 BLACK UP-POINTING TRIANGLE (present in WGL4)" and 2nd "9660 ? 25BC BLACK DOWN-POINTING TRIANGLE (present in WGL4)".

What is the purpose of the HTML "no-js" class?

When Modernizr runs, it removes the "no-js" class and replaces it with "js". This is a way to apply different CSS rules depending on whether or not Javascript support is enabled.

See Modernizer's source code.

Comparing two maps

As long as you override equals() on each key and value contained in the map, then m1.equals(m2) should be reliable to check for maps equality.

The same result can be obtained also by comparing toString() of each map as you suggested, but using equals() is a more intuitive approach.

May not be your specific situation, but if you store arrays in the map, may be a little tricky, because they must be compared value by value, or using Arrays.equals(). More details about this see here.

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

I was also facing the same issue. First I generated build using V2 and installed that in mobile devices running on OS 5.1 and I got the same issue. But build was working fine on Tablet running on OS 7.0. So I generated build with V1 Jar signature and it was working fine on both the devices.

Conclusion: If you are supporting the device below android OS 7.0. Use V1 jar signature to generate the build.

How can I get name of element with jQuery?

You should use attr('name') like this

 $('#yourid').attr('name')

you should use an id selector, if you use a class selector you encounter problems because a collection is returned

Is there a way to reduce the size of the git folder?

I'm not sure what you want. First of all, of course each time you commit/push the directory is going to get a little larger, since it has to store each of those additional commits.

However, probably you want git gc which will "cleanup unnecessary files and optimize the local repository" (manual page).

Another possibly relevant command is git clean which will delete untracked files from your tree (manual page).

What is the difference between a data flow diagram and a flow chart?

Data flow diagram: A modeling notation that represents a functional decomposition of a system.

Flow chart: Step by step flow of a programe.

Passing data to components in vue.js

-------------Following is applicable only to Vue 1 --------------

Passing data can be done in multiple ways. The method depends on the type of use.


If you want to pass data from your html while you add a new component. That is done using props.

<my-component prop-name="value"></my-component>

This prop value will be available to your component only if you add the prop name prop-name to your props attribute.


When data is passed from a component to another component because of some dynamic or static event. That is done by using event dispatchers and broadcasters. So for example if you have a component structure like this:

<my-parent>
    <my-child-A></my-child-A>
    <my-child-B></my-child-B>
</my-parent>

And you want to send data from <my-child-A> to <my-child-B> then in <my-child-A> you will have to dispatch an event:

this.$dispatch('event_name', data);

This event will travel all the way up the parent chain. And from whichever parent you have a branch toward <my-child-B> you broadcast the event along with the data. So in the parent:

events:{
    'event_name' : function(data){
        this.$broadcast('event_name', data);
    },

Now this broadcast will travel down the child chain. And at whichever child you want to grab the event, in our case <my-child-B> we will add another event:

events: {
    'event_name' : function(data){
        // Your code. 
    },
},

The third way to pass data is through parameters in v-links. This method is used when components chains are completely destroyed or in cases when the URI changes. And i can see you already understand them.


Decide what type of data communication you want, and choose appropriately.

How to combine multiple inline style objects?

Actually, there is a formal way to combine and it is like below:

<View style={[style01, style02]} />

But, there is a small issue, if one of them is passed by the parent component and it was created by a combined formal way we have a big problem:

// The passing style02 from props: [parentStyle01, parentStyle02]

// Now:
<View style={[style01, [parentStyle01, parentStyle02]]} />

And this last line causes to have UI bug, surly, React Native cannot deal with a deep array inside an array. So I create my helper function:

import { StyleSheet } from 'react-native';

const styleJoiner = (...arg) => StyleSheet.flatten(arg);

By using my styleJoiner anywhere you can combine any type of style and combine styles. even undefined or other useless types don't cause to break the styling.

Use :hover to modify the css of another class?

It's not possible in CSS at the moment, unless you want to select a child or sibling element (trivial and described in other answers here).

For all other cases you'll need JavaScript. jQuery and frameworks like Angular can tackle this problem with relative ease.

[Edit]

With the new CSS (4) selector :has(), you'll be able to target parent elements/classes, making a CSS-Only solution viable in the near future!

I got error "The DELETE statement conflicted with the REFERENCE constraint"

You are trying to delete a row that is referenced by another row (possibly in another table).

You need to delete that row first (or at least re-set its foreign key to something else), otherwise you’d end up with a row that references a non-existing row. The database forbids that.

What is the difference between Numpy's array() and asarray() functions?

asarray(x) is like array(x, copy=False)

Use asarray(x) when you want to ensure that x will be an array before any other operations are done. If x is already an array then no copy would be done. It would not cause a redundant performance hit.

Here is an example of a function that ensure x is converted into an array first.

def mysum(x):
    return np.asarray(x).sum()

OSX - How to auto Close Terminal window after the "exit" command executed.

I tried several variations of the answers here. No matter what I try, I can always find a use case where the user is prompted to close Terminal.

Since my script is a simple (drutil -drive 2 tray open -- to open a specific DVD drive), the user does not need to see the Terminal window while the script runs.

My solution was to turn the script into an app, which runs the script without displaying a Terminal window. The added benefit is that any terminal windows that are already open stay open, and if none are open, then Terminal doesn't stay resident after the script ends. It doesn't seem to launch Terminal at all to run the bash script.

I followed these instructions to turn my script into an app: https://superuser.com/a/1354541/162011

Spring Data JPA and Exists query

Spring Data JPA 1.11 now supports the exists projection in repository query derivation.

See documentation here.

In your case the following will work:

public interface MyEntityRepository extends CrudRepository<MyEntity, String> {  
    boolean existsByFoo(String foo);
}

How to add a vertical Separator?

In the past I've used the style found here

<Style x:Key="VerticalSeparatorStyle" 
       TargetType="{x:Type Separator}"
       BasedOn="{StaticResource {x:Type Separator}}">
    <Setter Property="Margin" Value="6,0,6,0"/>
    <Setter Property="LayoutTransform">
        <Setter.Value>
            <TransformGroup>
                <TransformGroup.Children>
                    <TransformCollection>
                        <RotateTransform Angle="90"/>
                    </TransformCollection>
                </TransformGroup.Children>
            </TransformGroup>
        </Setter.Value>
    </Setter>
</Style>

<Separator Style="{DynamicResource VerticalSeparatorStyle}" />

You need to set the transformation in LayoutTransform instead of RenderTransform so the transformation occurs during the Layout pass, not during the Render pass. The Layout pass occurs when WPF is trying to layout controls and figure out how much space each control takes up, while the Render pass occurs after the layout pass when WPF is trying to render controls.

You can read more about the difference between LayoutTransform and RenderTransform here or here

Android Eclipse - Could not find *.apk

SHA1's answer did it for me: after updating to the latest sdk/adt, my project refused to build an apk; unchecking the option resolved the issue.

I don't know if the update checked this, or if it was checked before but the new adt screwed things up, but things work again now :)

MAX() and MAX() OVER PARTITION BY produces error 3504 in Teradata Query

SELECT employee_number, course_code, MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code

How do I display an alert dialog on Android?

You can create Activity and extends AppCompatActivity. Then in the Manifest put next style:

<activity android:name=".YourCustomDialog"
            android:theme="Theme.AppCompat.Light.Dialog">
</activity>

Inflate it by Buttons and TextViews

Then use this like a dialog.

For example, in the linearLayout I fill next parameters:

android:layout_width="300dp"
android:layout_height="wrap_content"

What is the path that Django uses for locating and loading templates?

basically BASE_DIR is your django project directory, same dir where manage.py is.

    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]

Can RDP clients launch remote applications and not desktops

At least on 2008R2 if the accounts are only used for RDP and not for local logins then you can set this on a per-account basis. That should work for thin clients. If the accounts are also used on local desktops then this would also affect those logins.

In ADUsers&Computers, open the properties for the account and go to the Environment tab. On that tab, check "Start the following program at logon" and specify the path and executable for the program.

Permanently adding a file path to sys.path in Python

There are a few ways. One of the simplest is to create a my-paths.pth file (as described here). This is just a file with the extension .pth that you put into your system site-packages directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/ and it will add that directory to the path.

You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path. See the documentation.

Note that no matter what you do, sys.path contains directories not files. You can't "add a file to sys.path". You always add its directory and then you can import the file.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

This fixed my issue when I restarted the mysql service. Just run:

brew services start mysql

'DataFrame' object has no attribute 'sort'

Pandas Sorting 101

sort has been replaced in v0.20 by DataFrame.sort_values and DataFrame.sort_index. Aside from this, we also have argsort.

Here are some common use cases in sorting, and how to solve them using the sorting functions in the current API. First, the setup.

# Setup
np.random.seed(0)
df = pd.DataFrame({'A': list('accab'), 'B': np.random.choice(10, 5)})    
df                                                                                                                                        
   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

Sort by Single Column

For example, to sort df by column "A", use sort_values with a single column name:

df.sort_values(by='A')

   A  B
0  a  7
3  a  5
4  b  2
1  c  9
2  c  3

If you need a fresh RangeIndex, use DataFrame.reset_index.

Sort by Multiple Columns

For example, to sort by both col "A" and "B" in df, you can pass a list to sort_values:

df.sort_values(by=['A', 'B'])

   A  B
3  a  5
0  a  7
4  b  2
2  c  3
1  c  9

Sort By DataFrame Index

df2 = df.sample(frac=1)
df2

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

You can do this using sort_index:

df2.sort_index()

   A  B
0  a  7
1  c  9
2  c  3
3  a  5
4  b  2

df.equals(df2)                                                                                                                            
# False
df.equals(df2.sort_index())                                                                                                               
# True

Here are some comparable methods with their performance:

%timeit df2.sort_index()                                                                                                                  
%timeit df2.iloc[df2.index.argsort()]                                                                                                     
%timeit df2.reindex(np.sort(df2.index))                                                                                                   

605 µs ± 13.6 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
610 µs ± 24.2 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
581 µs ± 7.63 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Sort by List of Indices

For example,

idx = df2.index.argsort()
idx
# array([0, 7, 2, 3, 9, 4, 5, 6, 8, 1])

This "sorting" problem is actually a simple indexing problem. Just passing integer labels to iloc will do.

df.iloc[idx]

   A  B
1  c  9
0  a  7
2  c  3
3  a  5
4  b  2

Setting an HTML text input box's "default" value. Revert the value when clicking ESC

You might looking for the placeholder attribute which will display a grey text in the input field while empty.

From Mozilla Developer Network:

A hint to the user of what can be entered in the control . The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored.

However as it's a fairly 'new' tag (from the HTML5 specification afaik) you might want to to browser testing to make sure your target audience is fine with this solution.
(If not tell tell them to upgrade browser 'cause this tag works like a charm ;o) )

And finally a mini-fiddle to see it directly in action: http://jsfiddle.net/LnU9t/

Edit: Here is a plain jQuery solution which will also clear the input field if an escape keystroke is detected: http://jsfiddle.net/3GLwE/

What is the purpose of the return statement?

return means, "output this value from this function".

print means, "send this value to (generally) stdout"

In the Python REPL, a function return will be output to the screen by default (this isn't quite the same as print).

This is an example of print:

>>> n = "foo\nbar" #just assigning a variable. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>

This is an example of return:

>>> def getN():
...    return "foo\nbar"
...
>>> getN() #When this isn't assigned to something, it is just output
'foo\nbar'
>>> n = getN() # assigning a variable to the return value. No output
>>> n #the value is output, but it is in a "raw form"
'foo\nbar'
>>> print n #the \n is now a newline
foo
bar
>>>

Couldn't load memtrack module Logcat Error

do you called the ViewTreeObserver and not remove it.

    mEtEnterlive.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
         // do nothing here can cause such problem
    });

Import/Index a JSON file into Elasticsearch

I wrote some code to expose the Elasticsearch API via a Filesystem API.

It is good idea for clear export/import of data for example.

I created prototype elasticdriver. It is based on FUSE

demo

How do you save/store objects in SharedPreferences on Android?

You can use gson.jar to store class objects into SharedPreferences. You can download this jar from google-gson

Or add the GSON dependency in your Gradle file:

implementation 'com.google.code.gson:gson:2.8.5'

Creating a shared preference:

SharedPreferences  mPrefs = getPreferences(MODE_PRIVATE);

To save:

MyObject myObject = new MyObject;
//set variables of 'myObject', etc.

Editor prefsEditor = mPrefs.edit();
Gson gson = new Gson();
String json = gson.toJson(myObject);
prefsEditor.putString("MyObject", json);
prefsEditor.commit();

To retrieve:

Gson gson = new Gson();
String json = mPrefs.getString("MyObject", "");
MyObject obj = gson.fromJson(json, MyObject.class);

Use a loop to plot n charts Python

We can create a for loop and pass all the numeric columns into it. The loop will plot the graphs one by one in separate pane as we are including plt.figure() into it.

import pandas as pd
import seaborn as sns
import numpy as np

numeric_features=[x for x in data.columns if data[x].dtype!="object"]
#taking only the numeric columns from the dataframe.

for i in data[numeric_features].columns:
    plt.figure(figsize=(12,5))
    plt.title(i)
    sns.boxplot(data=data[i])

How to output to the console in C++/Windows

You don't necessarily need to make any changes to your code (nor to change the SUBSYSTEM type). If you wish, you also could simply pipe stdout and stderr to a console application (a Windows version of cat works well).

Multiple inheritance for an anonymous class

An anonymous class is extending or implementing while creating its object For example :

Interface in = new InterFace()
{

..............

}

Here anonymous class is implementing Interface.

Class cl = new Class(){

.................

}

here anonymous Class is extending a abstract Class.

correct configuration for nginx to localhost?

Fundamentally you hadn't declare location which is what nginx uses to bind URL with resources.

 server {
            listen       80;
            server_name  localhost;

            access_log  logs/localhost.access.log  main;

            location / {
                root /var/www/board/public;
                index index.html index.htm index.php;
            }
       }

Logging with Retrofit 2

You can also add Facebook's Stetho and look at the network traces in Chrome: http://facebook.github.io/stetho/

final OkHttpClient.Builder builder = new OkHttpClient.Builder();
if (BuildConfig.DEBUG) {
    builder.networkInterceptors().add(new StethoInterceptor());
}

Then open "chrome://inspect" in Chrome...

How to suppress scientific notation when printing float values?

Using 3.6.4, I was having a similar problem that randomly, a number in the output file would be formatted with scientific notation when using this:

fout.write('someFloats: {0:0.8},{1:0.8},{2:0.8}'.format(someFloat[0], someFloat[1], someFloat[2]))

All that I had to do to fix it was to add 'f':

fout.write('someFloats: {0:0.8f},{1:0.8f},{2:0.8f}'.format(someFloat[0], someFloat[1], someFloat[2]))

Print the address or pointer for value in C

I believe this would be most correct.

printf("%p", (void *)emp1);
printf("%p", (void *)*emp1);

printf() is a variadic function and must be passed arguments of the right types. The standard says %p takes void *.

Java simple code: java.net.SocketException: Unexpected end of file from server

Summary

This exception is encountered when you are expecting a response, but the socket has been abruptly closed.

Detailed Explanation

Java's HTTPClient, found here, throws a SocketException with message "Unexpected end of file from server" in a very specific circumstance.

After making a request, HTTPClient gets an InputStream tied to the socket associated with the request. It then polls that InputStream repeatedly until it either:

  1. Finds the string "HTTP/1."
  2. The end of the InputStream is reached before 8 characters are read
  3. Finds a string other than "HTTP/1."

In case of number 2, HTTPClient will throw this SocketException if any of the following are true:

  • The HTTP method is CONNECT
  • The HTTP method is POST and the client is set to streaming mode

Why would this happen

This indicates that the TCP socket has been closed before the server was able to send a response. This could happen for any number of reasons, but some possibilities are:

  • Network connection was lost
  • The server decided to close the connection
  • Something in between the client and the server (nginx, router, etc) terminated the request

Note: When Nginx reloads its config, it forcefully closes any in-flight HTTP Keep-Alive connections (even POSTs), causing this exact error.

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

Just install php5-cgi in debian

sudo apt-get install php5-cgi

in Centos

sudo yum install php5-cgi

jQuery preventDefault() not triggered

Try this one:

   $("div.subtab_left li.notebook a").click(function(e) {
    e.preventDefault();
    return false;   
    });

How do I get the XML root node with C#?

I got the same question here. If the document is huge, it is not a good idea to use XmlDocument. The fact is that the first element is the root element, based on which XmlReader can be used to get the root element. Using XmlReader will be much more efficient than using XmlDocument as it doesn't require load the whole document into memory.

  using (XmlReader reader = XmlReader.Create(<your_xml_file>)) {
    while (reader.Read()) {
      // first element is the root element
      if (reader.NodeType == XmlNodeType.Element) {
        System.Console.WriteLine(reader.Name);
        break;
      }
    }
  }

Python conversion between coordinates

You can use the cmath module.

If the number is converted to a complex format, then it becomes easier to just call the polar method on the number.

import cmath
input_num = complex(1, 2) # stored as 1+2j
r, phi = cmath.polar(input_num)

Convert number to varchar in SQL with formatting

RIGHT('00' + CONVERT(VARCHAR, MyNumber), 2)

Be warned that this will cripple numbers > 99. You might want to factor in that possibility.

How to use pip on windows behind an authenticating proxy

It took me a couple hours to figure this out but I finally got it to work using CNTLM and afterwards got it to work with just a pip config file. Here is how I got it work with the pip config file...

Solution:

1. In Windows navigate to your user profile directory (Ex. C:\Users\Sync) and create a folder named "pip"

2. Create a file named "pip.ini" in this directory (Ex. C:\Users\Sync\pip\pip.ini) and enter the following into it:

    [global]
    trusted-host = pypi.python.org
                   pypi.org
                   files.pythonhosted.org
    proxy = http://[domain name]%5C[username]:[password]@[proxy address]:[proxy port]

Replace [domain name], [username], [password], [proxy address] and [proxy port] with your own information.

Note, if your [domain name], [username] or [password] has special characters, you have to percent-encode | encode them.

3. At this point I was able to run "pip install" without any issues.

Hopefully this works for others too!

P.S.: This may pose a security concern because of having your password stored in plain text. If this is an issue, consider setting up CNTLM using this article (allows using hashed password instead of plain text). Afterwards set proxy = 127.0.0.1:3128in the "pip.ini" file mentioned above.

what's the differences between r and rb in fopen

On Linux, and Unix in general, "r" and "rb" are the same. More specifically, a FILE pointer obtained by fopen()ing a file in in text mode and in binary mode behaves the same way on Unixes. On windows, and in general, on systems that use more than one character to represent "newlines", a file opened in text mode behaves as if all those characters are just one character, '\n'.

If you want to portably read/write text files on any system, use "r", and "w" in fopen(). That will guarantee that the files are written and read properly. If you are opening a binary file, use "rb" and "wb", so that an unfortunate newline-translation doesn't mess your data.

Note that a consequence of the underlying system doing the newline translation for you is that you can't determine the number of bytes you can read from a file using fseek(file, 0, SEEK_END).

Finally, see What's the difference between text and binary I/O? on comp.lang.c FAQs.

What does CultureInfo.InvariantCulture mean?

When numbers, dates and times are formatted into strings or parsed from strings a culture is used to determine how it is done. E.g. in the dominant en-US culture you have these string representations:

  • 1,000,000.00 - one million with a two digit fraction
  • 1/29/2013 - date of this posting

In my culture (da-DK) the values have this string representation:

  • 1.000.000,00 - one million with a two digit fraction
  • 29-01-2013 - date of this posting

In the Windows operating system the user may even customize how numbers and date/times are formatted and may also choose another culture than the culture of his operating system. The formatting used is the choice of the user which is how it should be.

So when you format a value to be displayed to the user using for instance ToString or String.Format or parsed from a string using DateTime.Parse or Decimal.Parse the default is to use the CultureInfo.CurrentCulture. This allows the user to control the formatting.

However, a lot of string formatting and parsing is actually not strings exchanged between the application and the user but between the application and some data format (e.g. an XML or CSV file). In that case you don't want to use CultureInfo.CurrentCulture because if formatting and parsing is done with different cultures it can break. In that case you want to use CultureInfo.InvariantCulture (which is based on the en-US culture). This ensures that the values can roundtrip without problems.

The reason that ReSharper gives you the warning is that some application writers are unaware of this distinction which may lead to unintended results but they never discover this because their CultureInfo.CurrentCulture is en-US which has the same behavior as CultureInfo.InvariantCulture. However, as soon as the application is used in another culture where there is a chance of using one culture for formatting and another for parsing the application may break.

So to sum it up:

  • Use CultureInfo.CurrentCulture (the default) if you are formatting or parsing a user string.
  • Use CultureInfo.InvariantCulture if you are formatting or parsing a string that should be parseable by a piece of software.
  • Rarely use a specific national culture because the user is unable to control how formatting and parsing is done.

CSS3 background image transition

You can use pseudo element to get the effect you want like I did in that Fiddle.

CSS:

.title a {
    display: block;
    width: 340px;
    height: 338px;
    color: black;
    position: relative;
}
.title a:after {
    background: url(https://lh3.googleusercontent.com/-p1nr1fkWKUo/T0zUp5CLO3I/AAAAAAAAAWg/jDiQ0cUBuKA/s800/red-pattern.png) repeat;
    content: "";
    opacity: 0;
    width: inherit;
    height: inherit;
    position: absolute;
    top: 0;
    left: 0;
    /* TRANSISITION */
    transition: opacity 1s ease-in-out;
    -webkit-transition: opacity 1s ease-in-out;
    -moz-transition: opacity 1s ease-in-out;
    -o-transition: opacity 1s ease-in-out;
}
.title a:hover:after{   
    opacity: 1;
}

HTML:

<div class="title">
    <a href="#">HYPERLINK</a>
</div>

How do I display images from Google Drive on a website?

<img src="https://drive.google.com/uc?export=view&id=Your_Image_ID" alt="">

I use on my wordpress site as storing image files on local host takes up to much space and slows down my site

I use textmate as it is easy to edit multiple URLs at same time using the 'alt/option' button

What is the current directory in a batch file?

It is the directory from where you start the batch file. E.g. if your batch is in c:\dir1\dir2 and you do cd c:\dir3, then run the batch, the current directory will be c:\dir3.

Create a directory if it does not exist and then create the files in that directory as well

This code checks for the existence of the directory first and creates it if not, and creates the file afterwards. Please note that I couldn't verify some of your method calls as I don't have your complete code, so I'm assuming the calls to things like getTimeStamp() and getClassName() will work. You should also do something with the possible IOException that can be thrown when using any of the java.io.* classes - either your function that writes the files should throw this exception (and it be handled elsewhere), or you should do it in the method directly. Also, I assumed that id is of type String - I don't know as your code doesn't explicitly define it. If it is something else like an int, you should probably cast it to a String before using it in the fileName as I have done here.

Also, I replaced your append calls with concat or + as I saw appropriate.

public void writeFile(String value){
    String PATH = "/remote/dir/server/";
    String directoryName = PATH.concat(this.getClassName());
    String fileName = id + getTimeStamp() + ".txt";

    File directory = new File(directoryName);
    if (! directory.exists()){
        directory.mkdir();
        // If you require it to make the entire directory path including parents,
        // use directory.mkdirs(); here instead.
    }

    File file = new File(directoryName + "/" + fileName);
    try{
        FileWriter fw = new FileWriter(file.getAbsoluteFile());
        BufferedWriter bw = new BufferedWriter(fw);
        bw.write(value);
        bw.close();
    }
    catch (IOException e){
        e.printStackTrace();
        System.exit(-1);
    }
}

You should probably not use bare path names like this if you want to run the code on Microsoft Windows - I'm not sure what it will do with the / in the filenames. For full portability, you should probably use something like File.separator to construct your paths.

Edit: According to a comment by JosefScript below, it's not necessary to test for directory existence. The directory.mkdir() call will return true if it created a directory, and false if it didn't, including the case when the directory already existed.

How can I completely uninstall nodejs, npm and node in Ubuntu

I was crazy to delete node and npm and nodejs from my Ubuntu 14.04 but with this steps you will remove it:

sudo apt-get uninstall nodejs npm node
sudo apt-get remove nodejs npm node

If you uninstall correctly and it is still there, check these links:

You can also try using find:

find / -name "node"

Although since that is likely to take a long time and return a lot of confusing false positives, you may want to search only PATH locations:

find $(echo $PATH | sed 's/:/ /g') -name "node"

It would probably be in /usr/bin/node or /usr/local/bin. After finding it, you can delete it using the correct path, eg:

sudo rm /usr/bin/node

How can I draw vertical text with CSS cross-browser?

If you use Bootstrap 3, you can use one of it's mixins:

.rotate(degrees);

Example:

.rotate(-90deg);

Telnet is not recognized as internal or external command

You can also try dism /online /Enable-Feature /FeatureName:TelnetClient

Run this command with "Run as an administrator"

Reference

How to perform Join between multiple tables in LINQ lambda

take look at this sample code from my project

public static IList<Letter> GetDepartmentLettersLinq(int departmentId)
{
    IEnumerable<Letter> allDepartmentLetters =
        from allLetter in LetterService.GetAllLetters()
        join allUser in UserService.GetAllUsers() on allLetter.EmployeeID equals allUser.ID into usersGroup
        from user in usersGroup.DefaultIfEmpty()// here is the tricky part
        join allDepartment in DepartmentService.GetAllDepartments() on user.DepartmentID equals allDepartment.ID
        where allDepartment.ID == departmentId
        select allLetter;

    return allDepartmentLetters.ToArray();
}

in this code I joined 3 tables and I spited join condition from where clause

note: the Services classes are just warped(encapsulate) the database operations

How do I prevent the error "Index signature of object type implicitly has an 'any' type" when compiling typescript with noImplicitAny flag enabled?

The 'keyof' solution mentioned above works. But if the variable is used only once e.g looping through an object etc, you can also typecast it.

for (const key in someObject) {
    sampleObject[key] = someObject[key as keyof ISomeObject];
}

How to set zoom level in google map

Here is a function I use:

var map =  new google.maps.Map(document.getElementById('map'), {
            center: new google.maps.LatLng(52.2, 5),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            zoom: 7
        });

function zoomTo(level) {
        google.maps.event.addListener(map, 'zoom_changed', function () {
            zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function (event) {
                if (this.getZoom() > level && this.initialZoom == true) {
                    this.setZoom(level);
                    this.initialZoom = false;
                }
                google.maps.event.removeListener(zoomChangeBoundsListener);
            });
        });
    }

Printing prime numbers from 1 through 100

A simple program to print "N" prime numbers. You can use N value as 100.

    #include  <iostream >
    using  namespace  std;

    int  main()
    {
        int  N;
        cin  >>  N;
        for (int  i =  2;  N > 0;  ++i)
        {
            bool  isPrime  =  true ;
            for (int  j =  2;  j < i;  ++j)
            {
                if (i  % j ==  0)
                {
                    isPrime  =  false ;
                    break ;
                }
            }
            if (isPrime)
            {
                --N;
                cout  <<  i  <<  "\n";
            }
        }
        return  0;
    }

orderBy multiple fields in Angular

There are 2 ways of doing AngularJs filters, one in the HTML using {{}} and one in actual JS files...

You can solve you problem by using :

{{ Expression | orderBy : expression : reverse}}

if you use it in the HTML or use something like:

$filter('orderBy')(yourArray, yourExpression, reverse)

The reverse is optional at the end, it accepts a boolean and if it's true, it will reverse the Array for you, very handy way to reverse your Array...

How to SELECT based on value of another SELECT

You can calculate the total (and from that the desired percentage) by using a subquery in the FROM clause:

SELECT Name,
       SUM(Value) AS "SUM(VALUE)",
       SUM(Value) / totals.total AS "% of Total"
FROM   table1,
       (
           SELECT Name,
                  SUM(Value) AS total
           FROM   table1
           GROUP BY Name
       ) AS totals
WHERE  table1.Name = totals.Name
AND    Year BETWEEN 2000 AND 2001
GROUP BY Name;

Note that the subquery does not have the WHERE clause filtering the years.

Difference between window.location.href, window.location.replace and window.location.assign

The part about not being able to use the Back button is a common misinterpretation. window.location.replace(URL) throws out the top ONE entry from the page history list, by overwriting it with the new entry, so the user can't easily go Back to that ONE particular webpage. The function does NOT wipe out the entire page history list, nor does it make the Back button completely non-functional.

(NO function nor combination of parameters that I know of can change or overwrite history list entries that you don't own absolutely for certain - browsers generally impelement this security limitation by simply not even defining any operation that might at all affect any entry other than the top one in the page history list. I shudder to think what sorts of dastardly things malware might do if such a function existed.)

If you really want to make the Back button non-functional (probably not "user friendly": think again if that's really what you want to do), "open" a brand new window. (You can "open" a popup that doesn't even have a "Back" button too ...but popups aren't very popular these days:-) If you want to keep your page showing no matter what the user does (again the "user friendliness" is questionable), set up a window.onunload handler that just reloads your page all over again clear from the very beginning every time.

Is it possible to make desktop GUI application in .NET Core?

It will be available using .NET 6: https://devblogs.microsoft.com/dotnet/announcing-net-6-preview-1/

But you can already create WinForms applications using netcore 3.1 and net 5 (at least in Visual Studio 2019 16.8.4+).

Create winforms app sample

UI Constructor available

How to ping a server only once from within a batch file?

The only thing you need to think about in this case is, in which directory you are on your computer. Your command line window shows C:\users\rei0d\desktop\ as your current directory.

So the only thing you really need to do is:
Remove the desktop by "going up" with the command cd ...

So the complete command would be:

cd ..
ping XXX.XXX.XXX.XXX -t

Calling a java method from c++ in Android

If it's an object method, you need to pass the object to CallObjectMethod:

jobject result = env->CallObjectMethod(obj, messageMe, jstr);

What you were doing was the equivalent of jstr.messageMe().

Since your is a void method, you should call:

env->CallVoidMethod(obj, messageMe, jstr);

If you want to return a result, you need to change your JNI signature (the ()V means a method of void return type) and also the return type in your Java code.

what exactly is device pixel ratio?

Short answer

The device pixel ratio is the ratio between physical pixels and logical pixels. For instance, the iPhone 4 and iPhone 4S report a device pixel ratio of 2, because the physical linear resolution is double the logical linear resolution.

  • Physical resolution: 960 x 640
  • Logical resolution: 480 x 320

The formula is:

linres_p/linres_l

Where:

linres_p is the physical linear resolution

and:

linres_l is the logical linear resolution

Other devices report different device pixel ratios, including non-integer ones. For example, the Nokia Lumia 1020 reports 1.6667, the Samsumg Galaxy S4 reports 3, and the Apple iPhone 6 Plus reports 2.46 (source: dpilove). But this does not change anything in principle, as you should never design for any one specific device.

Discussion

The CSS "pixel" is not even defined as "one picture element on some screen", but rather as a non-linear angular measurement of 0.0213° viewing angle, which is approximately 1/96 of an inch at arm's length. Source: CSS Absolute Lengths

This has lots of implications when it comes to web design, such as preparing high-definition image resources and carefully applying different images at different device pixel ratios. You wouldn't want to force a low-end device to download a very high resolution image, only to downscale it locally. You also don't want high-end devices to upscale low resolution images for a blurry user experience.

If you are stuck with bitmap images, to accommodate for many different device pixel ratios, you should use CSS Media Queries to provide different sets of resources for different groups of devices. Combine this with nice tricks like background-size: cover or explicitly set the background-size to percentage values.

Example

#element { background-image: url('lores.png'); }

@media only screen and (min-device-pixel-ratio: 2) {
    #element { background-image: url('hires.png'); }
}

@media only screen and (min-device-pixel-ratio: 3) {
    #element { background-image: url('superhires.png'); }
}

This way, each device type only loads the correct image resource. Also keep in mind that the px unit in CSS always operates on logical pixels.

A case for vector graphics

As more and more device types appear, it gets trickier to provide all of them with adequate bitmap resources. In CSS, media queries is currently the only way, and in HTML5, the picture element lets you use different sources for different media queries, but the support is still not 100 % since most web developers still have to support IE11 for a while more (source: caniuse).

If you need crisp images for icons, line-art, design elements that are not photos, you need to start thinking about SVG, which scales beautifully to all resolutions.

jQuery table sort

We just started using this slick tool: https://plugins.jquery.com/tablesorter/

There is a video on its use at: http://www.highoncoding.com/Articles/695_Sorting_GridView_Using_JQuery_TableSorter_Plug_in.aspx

    $('#tableRoster').tablesorter({
        headers: {
            0: { sorter: false },
            4: { sorter: false }
        }
    });

With a simple table

<table id="tableRoster">
        <thead> 
                  <tr>
                    <th><input type="checkbox" class="rCheckBox" value="all" id="rAll" ></th>
                    <th>User</th>
                    <th>Verified</th>
                    <th>Recently Accessed</th>
                    <th>&nbsp;</th>
                  </tr>
        </thead>

How to leave/exit/deactivate a Python virtualenv

I use zsh-autoenv which is based off autoenv.

zsh-autoenv automatically sources (known/whitelisted) .autoenv.zsh files, typically used in project root directories. It handles "enter" and leave" events, nesting, and stashing of variables (overwriting and restoring).

Here is an example:

; cd dtree 
Switching to virtual environment: Development tree utiles
;dtree(feature/task24|?); cat .autoenv.zsh       
# Autoenv.
echo -n "Switching to virtual environment: "
printf "\e[38;5;93m%s\e[0m\n" "Development tree utiles"
workon dtree
# eof
dtree(feature/task24|?); cat .autoenv_leave.zsh 
deactivate

So when I leave the dtree directory, the virtual environment is automatically exited.

"Development tree utiles" is just a name… No hidden mean linking to the Illuminati in here.

Call apply-like function on each row of dataframe with multiple arguments from each row

Use mapply

> df <- data.frame(x=c(1,2), y=c(3,4), z=c(5,6))
> df
  x y z
1 1 3 5
2 2 4 6
> mapply(function(x,y) x+y, df$x, df$z)
[1] 6 8

> cbind(df,f = mapply(function(x,y) x+y, df$x, df$z) )
  x y z f
1 1 3 5 6
2 2 4 6 8

How to add app icon within phonegap projects?

Fortunately there is a little bit in the docs about the splash images, which put me on the road to getting the right location for the icon images as well. So here it goes.

Where the files are placed Once you have built your project using command-line interface "cordova build ios" you should have a complete file structure for your iOS app in the platforms/ios/ folder.

Inside that folder is a folder with the name of your app. Which in turn contains a resources/ directory where you will find the icons/ and splashscreen/ folders.

In the icons folder you will find four icon files (for 57px and 72 px, each in regular and @2x version). These are the Phonegap placeholder icons you've been seeing so far.

What to do

All you have to do is save the icon files in this folder. So that's:

YourPhonegapProject/Platforms/ios/YourAppName/Resources/icons

Same for splashscreen files.

Notes

  1. After placing the files there, rebuild the project using cordova build ios AND use xCode's 'Clean product' menu command. Without this, you'll still be seeing the Phonegap placeholders.

  2. It's wisest to rename your files the iOS/Apple way (i.e. [email protected] etc) instead of editing the names in the info.plist or config.xml. At least that worked for me.

  3. And by the way, ignore the weird path and the weird filename given for the icons in config.xml (i.e. <icon gap:platform="ios" height="114" src="res/icon/ios/icon-57-2x.png" width="114" />). I just left those definitions there, and the icons showed up just fine even though my 114px icon was named [email protected] instead of icon-57-2x.png.

  4. Don't use config.xml to prevent Apple's gloss effect on the icon. Instead, tick the box in xCode (click the project title in the left navigation column, select your app under the Target header, and scroll down to the icons section).

Laravel blank white screen

This changes works for my localhost Ubuntu server 14.xx setting

# Apply all permission to the laravel 5.x site folders     
$ sudo chmod -R 777 mysite

Also made changes on site-available httpd setting Apache2 settings

Add settings:

Options +Indexes +FollowSymLinks +MultiViews
Require all granted

A potentially dangerous Request.Form value was detected from the client

If you are on .NET 4.0 make sure you add this in your web.config file inside the <system.web> tags:

<httpRuntime requestValidationMode="2.0" />

In .NET 2.0, request validation only applied to aspx requests. In .NET 4.0 this was expanded to include all requests. You can revert to only performing XSS validation when processing .aspx by specifying:

requestValidationMode="2.0"

You can disable request validate entirely by specifying:

validateRequest="false"

How to store decimal values in SQL Server?

You can try this

decimal(18,1)

The length of numbers should be totally 18. The length of numbers after the decimal point should be 1 only and not more than that.

Viewing all defined variables

keep in mind dir() will return all current imports, AND variables.

if you just want your variables, I would suggest a naming scheme that is easy to extract from dir, such as varScore, varNames, etc.

that way, you can simply do this:

for vars in dir():
 if vars.startswith("var"):
   print vars

Edit

if you want to list all variables, but exclude imported modules and variables such as:

__builtins__

you can use something like so:

import os
import re

x = 11
imports = "os","re"

for vars in dir():
    if vars.startswith("__") == 0 and vars not in imports:
        print vars

as you can see, it will show the variable "imports" though, because it is a variable (well, a tuple). A quick workaround is to add the word "imports" into the imports tuple itself!

Shortcut for changing font size

Use : Tools in Menu -> Options -> Environment -> Fonts and Colors

Android Pop-up message

You can use Dialog to create this easily

create a Dialog instance using the context

Dialog dialog = new Dialog(contex);

You can design your layout as you like.

You can add this layout to your dialog by dialog.setContentView(R.layout.popupview);//popup view is the layout you created

then you can access its content (textviews, etc.) by using findViewById method

TextView txt = (TextView)dialog.findViewById(R.id.textbox);

you can add any text here. the text can be stored in the String.xml file in res\values.

txt.setText(getString(R.string.message));

then finally show the pop up menu

dialog.show();

more information http://developer.android.com/guide/topics/ui/dialogs.html

http://developer.android.com/reference/android/app/Dialog.html

How to get the difference between two arrays of objects in JavaScript

In addition, say two object array with different key value

// Array Object 1
const arrayObjOne = [
    { userId: "1", display: "Jamsheer" },
    { userId: "2", display: "Muhammed" },
    { userId: "3", display: "Ravi" },
    { userId: "4", display: "Ajmal" },
    { userId: "5", display: "Ryan" }
]

// Array Object 2
const arrayObjTwo =[
    { empId: "1", display: "Jamsheer", designation:"Jr. Officer" },
    { empId: "2", display: "Muhammed", designation:"Jr. Officer" },
    { empId: "3", display: "Ravi", designation:"Sr. Officer" },
    { empId: "4", display: "Ajmal", designation:"Ast. Manager" },
]

You can use filter in es5 or native js to substract two array object.

//Find data that are in arrayObjOne but not in arrayObjTwo
var uniqueResultArrayObjOne = arrayObjOne.filter(function(objOne) {
    return !arrayObjTwo.some(function(objTwo) {
        return objOne.userId == objTwo.empId;
    });
});

In ES6 you can use Arrow function with Object destructuring of ES6.

const ResultArrayObjOne = arrayObjOne.filter(({ userId: userId }) => !arrayObjTwo.some(({ empId: empId }) => empId === userId));

console.log(ResultArrayObjOne);

How to create the pom.xml for a Java project with Eclipse

If you have plugin for Maven in Eclipse, you can do following:

  • right click on your project -> Maven -> Enable Dependency Management

This will convert your project to Maven and creates a pom.xml. Fast and simple...

Change background color of edittext in android

This is my working solution

View view = new View(getApplicationContext());
view.setBackgroundResource(R.color.background);
myEditText.setBackground(view.getBackground());

Convert datatable to JSON in C#

public static string ConvertIntoJson(DataTable dt)
{
    var jsonString = new StringBuilder();
    if (dt.Rows.Count > 0)
    {
        jsonString.Append("[");
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            jsonString.Append("{");
            for (int j = 0; j < dt.Columns.Count; j++)
                jsonString.Append("\"" + dt.Columns[j].ColumnName + "\":\"" 
                    + dt.Rows[i][j].ToString().Replace('"','\"') + (j < dt.Columns.Count - 1 ? "\"," : "\""));

            jsonString.Append(i < dt.Rows.Count - 1 ? "}," : "}");
        }
        return jsonString.Append("]").ToString();
    }
    else
    {
        return "[]";
    }
}
public static string ConvertIntoJson(DataSet ds)
{
    var jsonString = new StringBuilder();
    jsonString.Append("{");
    for (int i = 0; i < ds.Tables.Count; i++)
    {
        jsonString.Append("\"" + ds.Tables[i].TableName + "\":");
        jsonString.Append(ConvertIntoJson(ds.Tables[i]));
        if (i < ds.Tables.Count - 1)
            jsonString.Append(",");
    }
    jsonString.Append("}");
    return jsonString.ToString();
}

Adding new column to existing DataFrame in Python pandas

Let me just add that, just like for hum3, .loc didn't solve the SettingWithCopyWarning and I had to resort to df.insert(). In my case false positive was generated by "fake" chain indexing dict['a']['e'], where 'e' is the new column, and dict['a'] is a DataFrame coming from dictionary.

Also note that if you know what you are doing, you can switch of the warning using pd.options.mode.chained_assignment = None and than use one of the other solutions given here.

Using getline() in C++

I know I'm late but I hope this is useful. Logic is for taking one line at a time if the user wants to enter many lines

int main() 
{ 
int t;                    // no of lines user wants to enter
cin>>t;
string str;
cin.ignore();            // for clearing newline in cin
while(t--)
{
    getline(cin,str);    // accepting one line, getline is teminated when newline is found 
    cout<<str<<endl; 
}
return 0; 
} 

input :

3

Government collage Berhampore

Serampore textile collage

Berhampore Serampore

output :

Government collage Berhampore

Serampore textile collage

Berhampore Serampore