Programs & Examples On #Rubiks cube

Rubik's Cube is a 3-D combination puzzle invented in 1974 by Hungarian sculptor and professor of architecture Ernő Rubik.

Creating a byte array from a stream

While Jon's answer is correct, he is rewriting code that already exists in CopyTo. So for .Net 4 use Sandip's solution, but for previous version of .Net use Jon's answer. Sandip's code would be improved by use of "using" as exceptions in CopyTo are, in many situations, quite likely and would leave the MemoryStream not disposed.

public static byte[] ReadFully(Stream input)
{
    using (MemoryStream ms = new MemoryStream())
    {
        input.CopyTo(ms);
        return ms.ToArray();
    }
}

How to make phpstorm display line numbers by default?

just double tap 'Shift'
and search for 'Line Numbers'
and there you will see a toggle option on or off

WAMP won't turn green. And the VCRUNTIME140.dll error

As Oriol said, you need the following redistributables before installing WAMP.

From the readme.txt

BEFORE proceeding with the installation of Wampserver, you must ensure that certain elements are installed on your system, otherwise Wampserver will absolutely not run, and in addition, the installation will be faulty and you need to remove Wampserver BEFORE installing the elements that were missing.

Make sure you are "up to date" in the redistributable packages VC9, VC10, VC11, VC13 and VC14 Even if you think you are up to date, install each package as administrator and if message "Already installed", validate Repair.

The following packages (VC9, VC10, VC11) are imperatively required to Wampserver 2.4, 2.5 and 3.0, even if you use only Apache and PHP versions VC11 and VC14 is required for PHP 7 and Apache 2.4.17

https://support.microsoft.com/en-us/help/2977003/the-latest-supported-visual-c-downloads

Finding element's position relative to the document

You can traverse the offsetParent up to the top level of the DOM.

function getOffsetLeft( elem )
{
    var offsetLeft = 0;
    do {
      if ( !isNaN( elem.offsetLeft ) )
      {
          offsetLeft += elem.offsetLeft;
      }
    } while( elem = elem.offsetParent );
    return offsetLeft;
}

omp parallel vs. omp parallel for

I don't think there is any difference, one is a shortcut for the other. Although your exact implementation might deal with them differently.

The combined parallel worksharing constructs are a shortcut for specifying a parallel construct containing one worksharing construct and no other statements. Permitted clauses are the union of the clauses allowed for the parallel and worksharing contructs.

Taken from http://www.openmp.org/mp-documents/OpenMP3.0-SummarySpec.pdf

The specs for OpenMP are here:

https://openmp.org/specifications/

How to replace a set of tokens in a Java String?

In the past, I've solved this kind of problem with StringTemplate and Groovy Templates.

Ultimately, the decision of using a templating engine or not should be based on the following factors:

  • Will you have many of these templates in the application?
  • Do you need the ability to modify the templates without restarting the application?
  • Who will be maintaining these templates? A Java programmer or a business analyst involved on the project?
  • Will you need to the ability to put logic in your templates, like conditional text based on values in the variables?
  • Will you need the ability to include other templates in a template?

If any of the above applies to your project, I would consider using a templating engine, most of which provide this functionality, and more.

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Acked Unseen sample

Hi guys! Just some observations from what I just found in my capture:

On many occasions, the packet capture reports “ACKed segment that wasn't captured” on the client side, which alerts of the condition that the client PC has sent a data packet, the server acknowledges receipt of that packet, but the packet capture made on the client does not include the packet sent by the client

Initially, I thought it indicates a failure of the PC to record into the capture a packet it sends because “e.g., machine which is running Wireshark is slow” (https://osqa-ask.wireshark.org/questions/25593/tcp-previous-segment-not-captured-is-that-a-connectivity-issue)
However, then I noticed every time I see this “ACKed segment that wasn't captured” alert I can see a record of an “invalid” packet sent by the client PC

  • In the capture example above, frame 67795 sends an ACK for 10384

  • Even though wireshark reports Bogus IP length (0), frame 67795 is reported to have length 13194

  • Frame 67800 sends an ACK for 23524
  • 10384+13194 = 23578
  • 23578 – 23524 = 54
  • 54 is in fact length of the Ethernet / IP / TCP headers (14 for Ethernt, 20 for IP, 20 for TCP)
  • So in fact, the frame 67796 does represent a large TCP packets (13194 bytes) which operating system tried to put on the wore
    • NIC driver will fragment it into smaller 1500 bytes pieces in order to transmit over the network
    • But Wireshark running on my PC fails to understand it is a valid packet and parse it. I believe Wireshark running on 2012 Windows server reads these captures correctly
  • So after all, these “Bogus IP length” and “ACKed segment that wasn't captured” alerts were in fact false positives in my case

Tomcat 7 "SEVERE: A child container failed during start"

This is what i have been facing for long time.

This happened last time and figured out that one case could be a bad war deployment, which came after i update library/maven dependencies on pom and re installed it.

SOLUTION:

right click on the server >  remove the war and 
right click on the server again > clean
make sure the maven dependencies are added to deployment assembly
right click on the project > Run As > maven clean
right click on the project again > Run As > maven install 
and finally deploy the project on to the server. This helped me to solve the issue  

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

I just had this issue after installing and removing some npm packages and spent almost 5 hours to figure out what was going on.

What I did is basically copied my src/components in a different directory, then removed all the node modules and package-lock.json (if you are running your app in the Docker container, remove images and rebuild it just to be safe); then reset it to my last commit and then put back my src/components then ran npm i.

I hope it helps.

csv.Error: iterator should return strings, not bytes

In Python3, csv.reader expects, that passed iterable returns strings, not bytes. Here is one more solution to this problem, that uses codecs module:

import csv
import codecs
ifile  = open('sample.csv', "rb")
read = csv.reader(codecs.iterdecode(ifile, 'utf-8'))
for row in read :
    print (row) 

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

How to get current screen width in CSS?

Use the CSS3 Viewport-percentage feature.

Viewport-Percentage Explanation

Assuming you want the body width size to be a ratio of the browser's view port. I added a border so you can see the body resize as you change your browser width or height. I used a ratio of 90% of the view-port size.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <title>Styles</title>_x000D_
_x000D_
    <style>_x000D_
        @media screen and (min-width: 480px) {_x000D_
            body {_x000D_
                background-color: skyblue;_x000D_
                width: 90vw;_x000D_
                height: 90vh;_x000D_
                border: groove black;_x000D_
            }_x000D_
_x000D_
            div#main {_x000D_
                font-size: 3vw;_x000D_
            }_x000D_
        }_x000D_
    </style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
    <div id="main">_x000D_
        Viewport-Percentage Test_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

File.Move Does Not Work - File Already Exists

Try Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True). The last parameter is Overwrite switch, which System.IO.File.Move doesn't have.

How to set opacity in parent div and not affect in child div?

I had the same problem and I fixed by setting transparent png image as background for the parent tag.

This is the 1px x 1px PNG Image that I have created with 60% Opacity of black background !

How to include CSS file in Symfony 2 and Twig?

In case you are using Silex add the Symfony Asset as a dependency:

composer require symfony/asset

Then you may register Asset Service Provider:

$app->register(new Silex\Provider\AssetServiceProvider(), array(
    'assets.version' => 'v1',
    'assets.version_format' => '%s?version=%s',
    'assets.named_packages' => array(
        'css' => array(
            'version' => 'css2',
            'base_path' => __DIR__.'/../public_html/resources/css'
        ),
        'images' => array(
            'base_urls' => array(
                'https://img.example.com'
            )
        ),
    ),
));

Then in your Twig template file in head section:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    {% block head %}
    <link rel="stylesheet" href="{{ asset('style.css') }}" />
    {% endblock %}
</head>
<body>

</body>
</html>

Unable instantiate android.gms.maps.MapFragment

Maybe You must highlight this :

Note: Google Play services is not supported on the Android emulator — to develop using the APIs, you need to provide a development device such as an Android phone or tablet.

http://developer.android.com/google/play-services/setup.html

You must provide a physical development device on which you can run and debug your app. Do not use emulator. Will not working.

How to connect from windows command prompt to mysql command line

To make it easier to invoke MySQL programs, you can add the path name of the MySQL bin directory to your Windows system PATH environment variable:

On the Windows desktop, right-click the My Computer icon, and select Properties.

Next select the Advanced tab from the System Properties menu that appears, and click the Environment Variables button.

Under System Variables, select Path, and then click the Edit button. The Edit System Variable dialogue should appear.

Place your cursor at the end of the text appearing in the space marked Variable Value. (Use the End key to ensure that your cursor is positioned at the very end of the text in this space.) Then enter the complete path name of your MySQL bin directory (for example, C:\Program Files\MySQL\MySQL Server 8.0\bin).

Open a different terminal and if you are using root as user run mysql -u root -p else use the a different username you created.

Get value of input field inside an iframe

<iframe id="upload_target" name="upload_target">
    <textarea rows="20" cols="100" name="result" id="result" ></textarea>
    <input type="text" id="txt1" />
</iframe>

You can Get value by JQuery

$(document).ready(function(){
  alert($('#upload_target').contents().find('#result').html());
  alert($('#upload_target').contents().find('#txt1').val());
});

work on only same domain link

What is wrong with this code that uses the mysql extension to fetch data from a database in PHP?

  1. Select a database with identifier mysql_select_db("form1",$connect);

  2. Are you getting syntax error? If please put a ; next to $comment = $rows['Comment'].

  3. Also the variables should be case sensitive here

If REST applications are supposed to be stateless, how do you manage sessions?

Stateless here means that state or meta data of request is not maintained on server side. By maintaining each request or user's state on server, it would lead to performance bottlenecks. Server is just requested with required attributes to perform any specific operations.

Coming to managing sessions, or giving customize experience to users, it requires to maintain some meta data or state of user likely user's preferences, past request history. This can be done by maintaining cookies, hidden attributes or into session object.

This can maintain or keep track of user's state in the application.

Hope this helps!

Adjust plot title (main) position

To summarize and explain visually how it works. Code construction is as follows:

par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)

explanation:

par(mar = c(low, left, top, right)) - margins of the graph area.

title("text" - title text
      adj  = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
      line = positive values move title text up, negative - down)

enter image description here

I have created a table in hive, I would like to know which directory my table is created in?

in hive 0.1 you can use SHOW CREATE TABLE to find the path where hive store data.

in other versions, there is no good way to do this.

upadted:

thanks Joe K

use DESCRIBE FORMATTED <table> to show table information.

ps: database.tablename is not supported here.

Is there a free GUI management tool for Oracle Database Express?

You could try this: it's a very good tool, very fast and effective.

http://code.google.com/p/oracle-gui/

Best data type for storing currency values in a MySQL database

Something like Decimal(19,4) usually works pretty well in most cases. You can adjust the scale and precision to fit the needs of the numbers you need to store. Even in SQL Server, I tend not to use "money" as it's non-standard.

Recommended SQL database design for tags or tagging

I've always kept the tags in a separate table and then had a mapping table. Of course I've never done anything on a really large scale either.

Having a "tags" table and a map table makes it pretty trivial to generate tag clouds & such since you can easily put together SQL to get a list of tags with counts of how often each tag is used.

Installation Issue with matplotlib Python

Problem Cause

In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.

Solution

  • I assume you have installed the pip matplotlib, there is a directory in your root called ~/.matplotlib.
  • Create a file ~/.matplotlib/matplotlibrc there and add the following code: backend: TkAgg

From this link you can try different diagrams.

Eclipse: All my projects disappeared from Project Explorer

I tried differently for the same issue and worked .

Go to your project location in hard drive. ex: /home/user/workspace/project/settings and Delete this file org.eclipse.core.resources.prefs

For full details check out bellow link

http://errorkode.com/viewtopic.php?f=20&t=8&sid=40cff1661bf0ace12878d6d6fb7e75ac

update one table with data from another

Oracle 11g R2:

create table table1 (
  id number,
  name varchar2(10),
  desc_ varchar2(10)
);

create table table2 (
  id number,
  name varchar2(10),
  desc_ varchar2(10)
);

insert into table1 values(1, 'a', 'abc');
insert into table1 values(2, 'b', 'def');
insert into table1 values(3, 'c', 'ghi');

insert into table2 values(1, 'x', '123');
insert into table2 values(2, 'y', '456');

merge into table1 t1
using (select * from table2) t2
on (t1.id = t2.id)
when matched then update set t1.name = t2.name, t1.desc_ = t2.desc_;

select * from table1;

        ID NAME       DESC_
---------- ---------- ----------
         1 x          123
         2 y          456
         3 c          ghi

See also Oracle - Update statement with inner join.

C# Version Of SQL LIKE

Simply .Contains() would do the work for you.

"Example String".Contains("amp");   //like '%amp%'

This would return true, and performing a select on it would return the desired output.

Why can't I find SQL Server Management Studio after installation?

It appears that SQL Server 2008 R2 can be downloaded with or without the management tools. I honestly have NO IDEA why someone would not want the management tools. But either way, the options are here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

and the one for 64 bit WITH the management tools (management studio) is here:

http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

From the first link I presented, the 3rd and 4th include the management studio for 32 and 64 bit respectively.

macro run-time error '9': subscript out of range

Why are you using a macro? Excel has Password Protection built-in. When you select File/Save As... there should be a Tools button by the Save button, click it then "General Options" where you can enter a "Password to Open" and a "Password to Modify".

How Best to Compare Two Collections in Java and Act on Them?

For a set that small is generally not worth it to convert from an Array to a HashMap/set. In fact, you're probably best off keeping them in an array and then sorting them by key and iterating over both lists simultaneously to do the comparison.

How to save a pandas DataFrame table as a png

I had the same requirement for a project I am doing. But none of the answers came elegant to my requirement. Here is something which finally helped me, and might be useful for this case:

from bokeh.io import export_png, export_svgs
from bokeh.models import ColumnDataSource, DataTable, TableColumn

def save_df_as_image(df, path):
    source = ColumnDataSource(df)
    df_columns = [df.index.name]
    df_columns.extend(df.columns.values)
    columns_for_table=[]
    for column in df_columns:
        columns_for_table.append(TableColumn(field=column, title=column))

    data_table = DataTable(source=source, columns=columns_for_table,height_policy="auto",width_policy="auto",index_position=None)
    export_png(data_table, filename = path)

enter image description here

Exception.Message vs Exception.ToString()

Converting the WHOLE Exception To a String

Calling Exception.ToString() gives you more information than just using the Exception.Message property. However, even this still leaves out lots of information, including:

  1. The Data collection property found on all exceptions.
  2. Any other custom properties added to the exception.

There are times when you want to capture this extra information. The code below handles the above scenarios. It also writes out the properties of the exceptions in a nice order. It's using C# 7 but should be very easy for you to convert to older versions if necessary. See also this related answer.

public static class ExceptionExtensions
{
    public static string ToDetailedString(this Exception exception) =>
        ToDetailedString(exception, ExceptionOptions.Default);

    public static string ToDetailedString(this Exception exception, ExceptionOptions options)
    {
        if (exception == null)
        {
            throw new ArgumentNullException(nameof(exception));
        } 

        var stringBuilder = new StringBuilder();

        AppendValue(stringBuilder, "Type", exception.GetType().FullName, options);

        foreach (PropertyInfo property in exception
            .GetType()
            .GetProperties()
            .OrderByDescending(x => string.Equals(x.Name, nameof(exception.Message), StringComparison.Ordinal))
            .ThenByDescending(x => string.Equals(x.Name, nameof(exception.Source), StringComparison.Ordinal))
            .ThenBy(x => string.Equals(x.Name, nameof(exception.InnerException), StringComparison.Ordinal))
            .ThenBy(x => string.Equals(x.Name, nameof(AggregateException.InnerExceptions), StringComparison.Ordinal)))
        {
            var value = property.GetValue(exception, null);
            if (value == null && options.OmitNullProperties)
            {
                if (options.OmitNullProperties)
                {
                    continue;
                }
                else
                {
                    value = string.Empty;
                }
            }

            AppendValue(stringBuilder, property.Name, value, options);
        }

        return stringBuilder.ToString().TrimEnd('\r', '\n');
    }

    private static void AppendCollection(
        StringBuilder stringBuilder,
        string propertyName,
        IEnumerable collection,
        ExceptionOptions options)
        {
            stringBuilder.AppendLine($"{options.Indent}{propertyName} =");

            var innerOptions = new ExceptionOptions(options, options.CurrentIndentLevel + 1);

            var i = 0;
            foreach (var item in collection)
            {
                var innerPropertyName = $"[{i}]";

                if (item is Exception)
                {
                    var innerException = (Exception)item;
                    AppendException(
                        stringBuilder,
                        innerPropertyName,
                        innerException,
                        innerOptions);
                }
                else
                {
                    AppendValue(
                        stringBuilder,
                        innerPropertyName,
                        item,
                        innerOptions);
                }

                ++i;
            }
        }

    private static void AppendException(
        StringBuilder stringBuilder,
        string propertyName,
        Exception exception,
        ExceptionOptions options)
    {
        var innerExceptionString = ToDetailedString(
            exception, 
            new ExceptionOptions(options, options.CurrentIndentLevel + 1));

        stringBuilder.AppendLine($"{options.Indent}{propertyName} =");
        stringBuilder.AppendLine(innerExceptionString);
    }

    private static string IndentString(string value, ExceptionOptions options)
    {
        return value.Replace(Environment.NewLine, Environment.NewLine + options.Indent);
    }

    private static void AppendValue(
        StringBuilder stringBuilder,
        string propertyName,
        object value,
        ExceptionOptions options)
    {
        if (value is DictionaryEntry)
        {
            DictionaryEntry dictionaryEntry = (DictionaryEntry)value;
            stringBuilder.AppendLine($"{options.Indent}{propertyName} = {dictionaryEntry.Key} : {dictionaryEntry.Value}");
        }
        else if (value is Exception)
        {
            var innerException = (Exception)value;
            AppendException(
                stringBuilder,
                propertyName,
                innerException,
                options);
        }
        else if (value is IEnumerable && !(value is string))
        {
            var collection = (IEnumerable)value;
            if (collection.GetEnumerator().MoveNext())
            {
                AppendCollection(
                    stringBuilder,
                    propertyName,
                    collection,
                    options);
            }
        }
        else
        {
            stringBuilder.AppendLine($"{options.Indent}{propertyName} = {value}");
        }
    }
}

public struct ExceptionOptions
{
    public static readonly ExceptionOptions Default = new ExceptionOptions()
    {
        CurrentIndentLevel = 0,
        IndentSpaces = 4,
        OmitNullProperties = true
    };

    internal ExceptionOptions(ExceptionOptions options, int currentIndent)
    {
        this.CurrentIndentLevel = currentIndent;
        this.IndentSpaces = options.IndentSpaces;
        this.OmitNullProperties = options.OmitNullProperties;
    }

    internal string Indent { get { return new string(' ', this.IndentSpaces * this.CurrentIndentLevel); } }

    internal int CurrentIndentLevel { get; set; }

    public int IndentSpaces { get; set; }

    public bool OmitNullProperties { get; set; }
}

Top Tip - Logging Exceptions

Most people will be using this code for logging. Consider using Serilog with my Serilog.Exceptions NuGet package which also logs all properties of an exception but does it faster and without reflection in the majority of cases. Serilog is a very advanced logging framework which is all the rage at the time of writing.

Top Tip - Human Readable Stack Traces

You can use the Ben.Demystifier NuGet package to get human readable stack traces for your exceptions or the serilog-enrichers-demystify NuGet package if you are using Serilog.

$_SERVER['HTTP_REFERER'] missing

You can and should never assume that $_SERVER['HTTP_REFERER'] will be present.

If you control the previous page, you can pass the URL as a parameter "site.com/page2.php?prevUrl=".urlencode("site.com/page1.php").

If you don't control the page, then there is nothing you can do.

CORS with spring-boot and angularjs not working

This is what has worked for me in order to disable CORS between Spring boot and React

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    /**
     * Overriding the CORS configuration to exposed required header for ussd to work
     *
     * @param registry CorsRegistry
     */

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("*")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(4800);
    }
}

I had to modify the Security configuration also like below:

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                    .cors().configurationSource(new CorsConfigurationSource() {

                @Override
                public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
                    CorsConfiguration config = new CorsConfiguration();
                    config.setAllowedHeaders(Collections.singletonList("*"));
                    config.setAllowedMethods(Collections.singletonList("*"));
                    config.addAllowedOrigin("*");
                    config.setAllowCredentials(true);
                    return config;
                }
            }).and()
                    .antMatcher("/api/**")
                    .authorizeRequests()
                    .anyRequest().authenticated()
                    .and().httpBasic()
                    .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and().exceptionHandling().accessDeniedHandler(apiAccessDeniedHandler());
        }

Getting Google+ profile picture url with user_id

UPDATE: The method below DOES NOT WORK since 2015

It is possible to get the profile picture, and you can even set the size of it:

https://plus.google.com/s2/photos/profile/<user_id>?sz=<your_desired_size>

Example: My profile picture, with size set to 100 pixels:

https://plus.google.com/s2/photos/profile/116018066779980863044?sz=100

Usage with an image tag:

<img src="https://plus.google.com/s2/photos/profile/116018066779980863044?sz=100" width="100" height="100">

Hope you get it working!

Eclipse Bug: Unhandled event loop exception No more handles

I found now 2 ways to work with eclipse without getting “SWTError: No more handles” on my Dell ProBook 6550b Windows 7 64 bit but none of them is really satisfying: I can start windows in “secure mode” or I can downgrade to “eclipse-jee-indigo-SR2-win32-x86_64”. I will now try to kill one process after the other until kepler starts working respective until I arrive in secure mode.

... and then a few hours later ...

Finally (for now) I could solve the issue (at least on my laptop: Dell ProBook 6550b Windows 7 64). I “just” had to kill the processes: “DPAgent.exe*32” (DigitalPersona Local Agent) & “DPAgent.exe” (DigitalPersona 64-bit Helper Process) which were luckily running under my user (and not SYSTEM which might have made it impossible to kill depending on your rights). Nevertheless I don't understand how these processes can interfere with SWT handles in eclipse ....

More information on this issue can as well be found here: https://bugs.eclipse.org/bugs/show_bug.cgi?id=402983

Cannot find name 'require' after upgrading to Angular4

Still not sure the answer, but a possible workaround is

import * as Chart from 'chart.js';

How to turn IDENTITY_INSERT on and off using SQL Server 2008?

Another option is where you have tables like 'type' or 'status', for example, OrderStatus, where you always want to control the Id value, create the Id (Primary Key) column without it being an Identity column is the first place.

How to [recursively] Zip a directory in PHP?

Great solution but for my Windows I need make a modifications. Below the modify code

function Zip($source, $destination){

if (!extension_loaded('zip') || !file_exists($source)) {
    return false;
}

$zip = new ZipArchive();
if (!$zip->open($destination, ZIPARCHIVE::CREATE)) {
    return false;
}

$source = str_replace('\\', '/', realpath($source));

if (is_dir($source) === true)
{
    $files = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($source), RecursiveIteratorIterator::SELF_FIRST);

    foreach ($files as $file)
    {
        $file = str_replace('\\', '/', $file);

        // Ignore "." and ".." folders
        if( in_array(substr($file, strrpos($file, '/')+1), array('.', '..')) )
            continue;

        if (is_dir($file) === true)
        {
            $zip->addEmptyDir(str_replace($source . '/', '', $file));
        }
        else if (is_file($file) === true)
        {

            $str1 = str_replace($source . '/', '', '/'.$file);
            $zip->addFromString($str1, file_get_contents($file));

        }
    }
}
else if (is_file($source) === true)
{
    $zip->addFromString(basename($source), file_get_contents($source));
}

return $zip->close();
}

Loaded nib but the 'view' outlet was not set

In my case , the designated initializer - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil in ***ViewController class was implemented so even if when I call other initializer to initialize the object ,the designated initializer will be called .

So to resolve this problem checking wether the - (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil is also a proper way.

How to generate the whole database script in MySQL Workbench?

Try the export function of phpMyAdmin.

I think there is also a possibility to copy the database files from one server to another, but I do not have a server available at the moment so I can't test it.

PowerShell Remoting giving "Access is Denied" error

Running the command prompt or Powershell ISE as an administrator fixed this for me.

How do I configure php to enable pdo and include mysqli on CentOS?

You might just have to install the packages.

yum install php-pdo php-mysqli

After they're installed, restart Apache.

httpd restart

or

apachectl restart

How do I get current URL in Selenium Webdriver 2 Python?

Another way to do it would be to inspect the url bar in chrome to find the id of the element, have your WebDriver click that element, and then send the keys you use to copy and paste using the keys common function from selenium, and then printing it out or storing it as a variable, etc.

"Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo." when using GCC

You don't need to fiddle around with any command :)

Once the XCode is updated, open the Xcode IDE program. Please accept terms and conditions.

You are all set to go :))

Javascript: formatting a rounded number to N decimals

I think that there is a more simple approach to all given here, and is the method Number.toFixed() already implemented in JavaScript.

simply write:

var myNumber = 2;

myNumber.toFixed(2); //returns "2.00"
myNumber.toFixed(1); //returns "2.0"

etc...

Convert UTF-8 with BOM to UTF-8 with no BOM in Python

import codecs
import shutil
import sys

s = sys.stdin.read(3)
if s != codecs.BOM_UTF8:
    sys.stdout.write(s)

shutil.copyfileobj(sys.stdin, sys.stdout)

How to use the toString method in Java?

Whenever you access an Object (not being a String) in a String context then the toString() is called under the covers by the compiler.

This is why

Map map = new HashMap();
System.out.println("map=" + map);

works, and by overriding the standard toString() from Object in your own classes, you can make your objects useful in String contexts too.

(and consider it a black box! Never, ever use the contents for anything else than presenting to a human)

Where to put a textfile I want to use in eclipse?

Just create a folder Files under src and put your file there. This will look like src/Files/myFile.txt

Note: In your code you need to specify like this Files/myFile.txt e.g.

getResource("Files/myFile.txt");

So when you build your project and run the .jar file this should be able to work.

Is it possible to use if...else... statement in React render function?

I used ternary operator and it's working fine for me.

> {item.lotNum == null ? ('PDF'):(item.lotNum)}

How to write JUnit test with Spring Autowire?

A JUnit4 test with Autowired and bean mocking (Mockito):

// JUnit starts spring context
@RunWith(SpringRunner.class)
// spring load context configuration from AppConfig class
@ContextConfiguration(classes = AppConfig.class)
// overriding some properties with test values if you need
@TestPropertySource(properties = {
        "spring.someConfigValue=your-test-value",
})
public class PersonServiceTest {

    @MockBean
    private PersonRepository repository;

    @Autowired
    private PersonService personService; // uses PersonRepository    

    @Test
    public void testSomething() {
        // using Mockito
        when(repository.findByName(any())).thenReturn(Collection.emptyList());
        Person person = new Person();
        person.setName(null);

        // when
        boolean found = personService.checkSomething(person);

        // then
        assertTrue(found, "Something is wrong");
    }
}

How to verify element present or visible in selenium 2 (Selenium WebDriver)

To check if element is visible we need to use element.isDisplayed(); But if we need to check for presence of element anywhere in Dom we can use following method

public boolean isElementPresentCheckUsingJavaScriptExecutor(WebElement element) {
        JavascriptExecutor jse=(JavascriptExecutor) driver;
        try {
            Object obj = jse.execute("return typeof(arguments[0]) != 'undefined' && arguments[0] != null;",
                    element);
            if (obj.toString().contains("true")) {
                System.out.println("isElementPresentCheckUsingJavaScriptExecutor: SUCCESS");
                return true;
            } else {
                System.out.println("isElementPresentCheckUsingJavaScriptExecutor: FAIL");
            }

        } catch (NoSuchElementException e) {
            System.out.println("isElementPresentCheckUsingJavaScriptExecutor: FAIL");
        }
        return false;
    }

Are there constants in JavaScript?

Clearly this shows the need for a standardized cross-browser const keyword.

But for now:

var myconst = value;

or

Object['myconst'] = value;

Both seem sufficient and anything else is like shooting a fly with a bazooka.

Finding all objects that have a given property inside a collection

I have been using Google Collections (now called Guava) for this kind of problem. There is a class called Iterables that can take an interface called Predicate as a parameter of a method that is really helpful.

Cat theOne = Iterables.find(cats, new Predicate<Cat>() {
    public boolean apply(Cat arg) { return arg.age() == 3; }
});

Check it here!

getting the table row values with jquery

$(document).ready(function () {
        $("#tbl_Customer tbody tr .companyname").click(function () {

            var comapnyname = $(this).closest(".trclass").find(".companyname").text();
            var CompanyAddress = $(this).closest(".trclass").find(".CompanyAddress").text();
            var CompanyEmail = $(this).closest(".trclass").find(".CompanyEmail").text();
            var CompanyContactNumber = $(this).closest(".trclass").find(".CompanyContactNumber").text();
            var CompanyContactPerson = $(this).closest(".trclass").find(".CompanyContactPerson").text();
           // var clickedCell = $(this);
            alert(comapnyname);
            alert(CompanyAddress);
            alert(CompanyEmail);
            alert(CompanyContactNumber);
            alert(CompanyContactPerson);

            //alert(clickedCell.text());
        });
    });

SQL Server FOR EACH Loop

SQL is primarily a set-orientated language - it's generally a bad idea to use a loop in it.

In this case, a similar result could be achieved using a recursive CTE:

with cte as
(select 1 i union all
 select i+1 i from cte where i < 5)
select dateadd(d, i-1, '2010-01-01') from cte

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

In these two lines:

mask = cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)

frame = cv2.circle(frame,(a, b),5,color[i].tolist(),-1)

try instead:

cv2.line(mask, (a,b),(c,d), color[i].tolist(), 2)

cv2.circle(frame,(a, b),5,color[i].tolist(),-1)

I had the same problem and the variables were being returned empty

How to get time (hour, minute, second) in Swift 3 using NSDate?

let hours = time / 3600
let minutes = (time / 60) % 60
let seconds = time % 60
return String(format: "%0.2d:%0.2d:%0.2d", hours, minutes, seconds)

DateTime fields from SQL Server display incorrectly in Excel

I had the same problem as Andre. There does not seem to be a direct solution, but a CAST in the query that generates the data fixes the problem as long as you can live within the restrictions of SMALLDATETIME. In the following query, the first column does not format correctly in Excel, the second does.

SELECT GETDATE(), CAST(GETDATE() AS SMALLDATETIME)

Perhaps the fractional part of the seconds in DATETIME and DATETIME2 confuses Excel.

How do I read a date in Excel format in Python?

For quick and dirty:

year, month, day, hour, minute, second = xlrd.xldate_as_tuple(excelDate, wb.datemode)
whatYouWant = str(month)+'/'+str(day)+'/'+str(year)

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

I have found this page

http://schemas.xmlsoap.org/wsdl/soap12/soap12WSDL.htm

which says that Soap 1.2 uses the new namespace http://schemas.xmlsoap.org/wsdl/soap12/

It is in the 'WSDL 1.1 Binding extension for SOAP 1.1'.

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

TIP:

comment out pid and socket file, if you can't connect to server.. mysql could be connecting with incorrect pid and/or socket file, so when you try to connect to server trough command-line it "looks" at the incorrect pid/socket file...

### comment out pid and socket file, if you can't connect to server..
#pid-file=/var/run/mysql/mysqld.pid #socket=/var/lib/mysql/mysql.sock

Writing handler for UIAlertAction

Functions are first-class objects in Swift. So if you don't want to use a closure, you can also just define a function with the appropriate signature and then pass it as the handler argument. Observe:

func someHandler(alert: UIAlertAction!) {
    // Do something...
}

alert.addAction(UIAlertAction(title: "Okay",
                              style: UIAlertActionStyle.Default,
                              handler: someHandler))

Java: Convert String to TimeStamp

can you try it once...

String dob="your date String";
String dobis=null;
final DateFormat df = new SimpleDateFormat("yyyy-MMM-dd");
final Calendar c = Calendar.getInstance();
try {
    if(dob!=null && !dob.isEmpty() && dob != "")
    {
    c.setTime(df.parse(dob));
    int month=c.get(Calendar.MONTH);
    month=month+1;
    dobis=c.get(Calendar.YEAR)+"-"+month+"-"+c.get(Calendar.DAY_OF_MONTH);
    }

}

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

Clearing the contents of storage/framework/cache did the trick for me. Nothing else worked...

In excel how do I reference the current row but a specific column?

To static either a row or a column, put a $ sign in front of it. So if you were to use the formula =AVERAGE($A1,$C1) and drag it down the entire sheet, A and C would remain static while the 1 would change to the current row

If you're on Windows, you can achieve the same thing by repeatedly pressing F4 while in the formula editing bar. The first F4 press will static both (it will turn A1 into $A$1), then just the row (A$1) then just the column ($A1)

Although technically with the formulas that you have, dragging down for the entirety of the column shouldn't be a problem without putting a $ sign in front of the column. Setting the column as static would only come into play if you're dragging ACROSS columns and want to keep using the same column, and setting the row as static would be for dragging down rows but wanting to use the same row.

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

According to documentation: to verify host or peer certificate you need to specify alternate certificates with the CURLOPT_CAINFO option or a certificate directory can be specified with the CURLOPT_CAPATH option.

Also look at CURLOPT_SSL_VERIFYHOST:

  • 1 to check the existence of a common name in the SSL peer certificate.
  • 2 to check the existence of a common name and also verify that it matches the hostname provided.

curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);

Windows 8.1 gets Error 720 on connect VPN

I had the same problem. Most posted solutions would not work. I ran sfc /scannow and it reported that some errors could not be fixed. To address that problem I ran the command

Dism /Online /Cleanup-Image /RestoreHealth

Ironically, I later found the WAN errors had gone away, the 720 VPN error went away and my VPN worked.

Hard to believe that the WAN errors were corrected by this rather esoteric command, but it's worth a try.

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

How to add external JS scripts to VueJS Components

mounted() {
    if (document.getElementById('myScript')) { return }
    let src = 'your script source'
    let script = document.createElement('script')
    script.setAttribute('src', src)
    script.setAttribute('type', 'text/javascript')
    script.setAttribute('id', 'myScript')
    document.head.appendChild(script)
}


beforeDestroy() {
    let el = document.getElementById('myScript')
    if (el) { el.remove() }
}

pandas get rows which are NOT in other dataframe

The currently selected solution produces incorrect results. To correctly solve this problem, we can perform a left-join from df1 to df2, making sure to first get just the unique rows for df2.

First, we need to modify the original DataFrame to add the row with data [3, 10].

df1 = pd.DataFrame(data = {'col1' : [1, 2, 3, 4, 5, 3], 
                           'col2' : [10, 11, 12, 13, 14, 10]}) 
df2 = pd.DataFrame(data = {'col1' : [1, 2, 3],
                           'col2' : [10, 11, 12]})

df1

   col1  col2
0     1    10
1     2    11
2     3    12
3     4    13
4     5    14
5     3    10

df2

   col1  col2
0     1    10
1     2    11
2     3    12

Perform a left-join, eliminating duplicates in df2 so that each row of df1 joins with exactly 1 row of df2. Use the parameter indicator to return an extra column indicating which table the row was from.

df_all = df1.merge(df2.drop_duplicates(), on=['col1','col2'], 
                   how='left', indicator=True)
df_all

   col1  col2     _merge
0     1    10       both
1     2    11       both
2     3    12       both
3     4    13  left_only
4     5    14  left_only
5     3    10  left_only

Create a boolean condition:

df_all['_merge'] == 'left_only'

0    False
1    False
2    False
3     True
4     True
5     True
Name: _merge, dtype: bool

Why other solutions are wrong

A few solutions make the same mistake - they only check that each value is independently in each column, not together in the same row. Adding the last row, which is unique but has the values from both columns from df2 exposes the mistake:

common = df1.merge(df2,on=['col1','col2'])
(~df1.col1.isin(common.col1))&(~df1.col2.isin(common.col2))
0    False
1    False
2    False
3     True
4     True
5    False
dtype: bool

This solution gets the same wrong result:

df1.isin(df2.to_dict('l')).all(1)

Watch multiple $scope attributes

Beginning with AngularJS 1.1.4 you can use $watchCollection:

$scope.$watchCollection('[item1, item2]', function(newValues, oldValues){
    // do stuff here
    // newValues and oldValues contain the new and respectively old value
    // of the observed collection array
});

Plunker example here

Documentation here

Undefined reference to main - collect2: ld returned 1 exit status

Executable file needs a main function. See below hello world demo.

#include <stdio.h>
int main(void)
{
        printf("Hello world!\n");
        return 0;
}

As you can see there is a main function. if you don't have this main function, ld will report "undefined reference to main' "

check my result:

$ cat es3.c
#include <stdio.h>
int main(void)
{
    printf("Hello world!\n");
    return 0;
}
$ gcc -Wall -g -c es3.c
$ gcc -Wall -g es3.o -o es3
~$ ./es3
Hello world! 

please use $ objdump -t es3.o to check if there is a main symbol. Below is my result.

$ objdump -t es3.o

es3.o:     file format elf32-i386

SYMBOL TABLE:
00000000 l    df *ABS*  00000000 es3.c
00000000 l    d  .text  00000000 .text
00000000 l    d  .data  00000000 .data
00000000 l    d  .bss   00000000 .bss
00000000 l    d  .debug_abbrev  00000000 .debug_abbrev
00000000 l    d  .debug_info    00000000 .debug_info
00000000 l    d  .debug_line    00000000 .debug_line
00000000 l    d  .rodata        00000000 .rodata
00000000 l    d  .debug_frame   00000000 .debug_frame
00000000 l    d  .debug_loc     00000000 .debug_loc
00000000 l    d  .debug_pubnames        00000000 .debug_pubnames
00000000 l    d  .debug_aranges 00000000 .debug_aranges
00000000 l    d  .debug_str     00000000 .debug_str
00000000 l    d  .note.GNU-stack        00000000 .note.GNU-stack
00000000 l    d  .comment       00000000 .comment
00000000 g     F .text  0000002b main
00000000         *UND*  00000000 puts

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

In some cases data was not encoded into JSON format, so you need to encode it first e.g

 json_encode($data);

Later you will use json Parse in your JS, like

JSON.parse(data);

Mac install and open mysql using terminal

  1. install homebrew via terminal

  2. brew install mysql

How to increase heap size of an android application?

Use second process. Declare at AndroidManifest new Service with

android:process=":second"

Exchange between first and second process over BroadcastReceiver

Java heap terminology: young, old and permanent generations?

The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

center image in div with overflow hidden

Found this nice solution by MELISSA PENTA (https://www.localwisdom.com/)

HTML

<div class="wrapper">
   <img src="image.jpg" />
</div>

CSS

div.wrapper {
  height:200px;
  line-height:200px;
  overflow:hidden;
  text-align:center;
  width:200px;
}
div.wrapper img {
  margin:-100%;
}

Center any size image in div
Used with rounded wrapper and different sized images.

CSS

.item-image {
    border: 5px solid #ccc;
    border-radius: 100%;
    margin: 0 auto;
    height: 200px;
    width: 200px;
    overflow: hidden;
    text-align: center;
}
.item-image img {
    height: 200px;    
    margin: -100%;
    max-width: none;
    width: auto;    
}

Working example here codepen

Flask - Calling python function on button OnClick event

index.html (index.html should be in templates folder)

<!doctype html>
<html>

<head>
    <title>The jQuery Example</title>

    <h2>jQuery-AJAX in FLASK. Execute function on button click</h2>  

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
    <script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { },
    function(data) { }); return false; }); }); </script> 
</head>

<body>        
        <input type = "button" id = "mybutton" value = "Click Here" />
</body>    

</html>

test.py

from flask import Flask, jsonify, render_template, request
app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/SomeFunction')
def SomeFunction():
    print('In SomeFunction')
    return "Nothing"



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

Run Executable from Powershell script with parameters

Just adding an example that worked fine for me:

$sqldb = [string]($sqldir) + '\bin\MySQLInstanceConfig.exe'
$myarg = '-i ConnectionUsage=DSS Port=3311 ServiceName=MySQL RootPassword= ' + $rootpw
Start-Process $sqldb -ArgumentList $myarg

Spring Boot War deployed to Tomcat

Solution for people using Gradle

Add plugin to build.gradle

apply plugin: 'war'

Add provided dependency to tomcat

dependencies {
    // other dependencies
    providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
}

"undefined" function declared in another file?

If your source folder is structured /go/src/blog (assuming the name of your source folder is blog).

  1. cd /go/src/blog ... (cd inside the folder that has your package)
  2. go install
  3. blog

That should run all of your files at the same time, instead of you having to list the files manually or "bashing" a method on the command line.

How to limit depth for recursive file list?

Checkout the -maxdepth flag of find

find . -maxdepth 1 -type d -exec ls -ld "{}" \;

Here I used 1 as max level depth, -type d means find only directories, which then ls -ld lists contents of, in long format.

How do I add a resources folder to my Java project in Eclipse

When at the "Add resource folder", Build Path -> Configure Build Path -> Source (Tab) -> Add Folder -> Create new Folder enter image description here

add "my-resource.txt" file inside the new folder. Then in your code:

    InputStream res =
    Main.class.getResourceAsStream("/my-resource.txt");

    BufferedReader reader =
        new BufferedReader(new InputStreamReader(res));
    String line = null;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
    reader.close();

TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:

x = ["0", "1", "2"] 
y = int(x[0]) #accessing the zeroth element

If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:

x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)

If your list elements are not strings, you'll have to convert them to strings before using str.join:

x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)

Also, as stated above, make sure that you're not returning a nested list.

ASP.net vs PHP (What to choose)

This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.

Difference between two lists

If both your lists implement IEnumerable interface you can achieve this using LINQ.

list3 = list1.where(i => !list2.contains(i));

How to get HTTP Response Code using Selenium WebDriver

You can use BrowserMob proxy to capture the requests and responses with a HttpRequestInterceptor. Here is an example in Java:

// Start the BrowserMob proxy
ProxyServer server = new ProxyServer(9978);
server.start();

server.addResponseInterceptor(new HttpResponseInterceptor()
{
    @Override
    public void process(HttpResponse response, HttpContext context)
        throws HttpException, IOException
    {
        System.out.println(response.getStatusLine());
    }
});

// Get selenium proxy
Proxy proxy = server.seleniumProxy();

// Configure desired capability for using proxy server with WebDriver
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.PROXY, proxy);

// Set up driver
WebDriver driver = new FirefoxDriver(capabilities);

driver.get("http://stackoverflow.com/questions/6509628/webdriver-get-http-response-code");

// Close the browser
driver.quit();

base64 encode in MySQL

For those interested, these are the only alternatives so far:

1) Using these Functions:

http://wi-fizzle.com/downloads/base64.sql

2) If you already have the sys_eval UDF, (Linux) you can do this:

sys_eval(CONCAT("echo '",myField,"' | base64"));

The first method is known to be slow. The problem with the second one, is that the encoding is actually happening "outside" MySQL, which can have encoding problems (besides the security risks that you are adding with sys_* functions).

Unfortunately there is no UDF compiled version (which should be faster) nor a native support in MySQL (Posgresql supports it!).

It seems that the MySQL development team are not interested in implement it as this function already exists in other languages, which seems pretty silly to me.

Edit and replay XHR chrome/firefox etc?

5 years have passed and this essential requirement didn't get ignored by the Chrome devs.
While they offer no method to edit the data like in Firefox, they offer a full XHR replay.
This allows to debug ajax calls.
enter image description here
"Replay XHR" will repeat the entire transmission.

How to cast int to enum in C++?

int i = 1;
Test val = static_cast<Test>(i);

Accessing post variables using Java Servlets

The previous answers are correct but remember to use the name attribute in the input fields (html form) or you won't get anything. Example:

<input type="text" id="username" /> <!-- won't work --> <input type="text" name="username" /> <!-- will work --> <input type="text" name="username" id="username" /> <!-- will work too -->

All this code is HTML valid, but using getParameter(java.lang.String) you will need the name attribute been set in all parameters you want to receive.

Android Get Application's 'Home' Data Directory

You can try Context.getApplicationInfo().dataDir if you want the package's persistent data folder.

getFilesDir() returns a subroot of this.

.htaccess file to allow access to images folder to view pictures?

<Directory /uploads>
   Options +Indexes
</Directory>

Getting the index of a particular item in array

FindIndex Extension

static class ArrayExtensions
{
    public static int FindIndex<T>(this T[] array, Predicate<T> match)
    {
        return Array.FindIndex(array, match);
    }
}

Usage

int[] array = { 9,8,7,6,5 };

var index = array.FindIndex(i => i == 7);

Console.WriteLine(index); // Prints "2"

Here's a fiddle with it.


Bonus: IndexOf Extension

I wrote this first not reading the question properly...

static class ArrayExtensions
{
    public static int IndexOf<T>(this T[] array, T value)
    {
        return Array.IndexOf(array, value);
    }   
}

Usage

int[] array = { 9,8,7,6,5 };

var index = array.IndexOf(7);

Console.WriteLine(index); // Prints "2"

Here's a fiddle with it.

Count words in a string method?

A string phrase normaly has words separated by space. Well you can split the phrase using the spaces as separating characters and count them as follows.

import java.util.HashMap;

import java.util.Map;

public class WordCountMethod {

    public static void main (String [] args){

        Map<String, Integer>m = new HashMap<String, Integer>();
        String phrase = "hello my name is John I repeat John";
        String [] array = phrase.split(" ");

        for(int i =0; i < array.length; i++){
            String word_i = array[i];
            Integer ci = m.get(word_i);
            if(ci == null){
                m.put(word_i, 1);
            }
            else m.put(word_i, ci+1);
        }

        for(String s : m.keySet()){
            System.out.println(s+" repeats "+m.get(s));
        }
    }

} 

pip cannot install anything

On Virtualenv try editing the pip file, like so:

vi <your_virtualenv_folder>/bin/pip

look at the first line and check if it corresponds to the project folder, if not just change it.

#!/<your_path>/<project_folder>/<your_virtualenv_folder>/bin/python

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

This esc behavior is IE only by the way. Instead of using jQuery use good old javascript for creating the element and it works.

var element = document.createElement('input');
element.type = 'text';
element.value = 100;
document.getElementsByTagName('body')[0].appendChild(element);

http://jsfiddle.net/gGrf9/

If you want to extend this functionality to other browsers then I would use jQuery's data object to store the default. Then set it when user presses escape.

//store default value for all elements on page. set new default on blur
$('input').each( function() {
    $(this).data('default', $(this).val());
    $(this).blur( function() { $(this).data('default', $(this).val()); });
});

$('input').keyup( function(e) {
    if (e.keyCode == 27) { $(this).val($(this).data('default')); }
});

Javascript Get Element by Id and set the value

For each element type, you can use specific attribute to set value. E.g.:

<div id="theValue1"></div>
window.document.getElementById("theValue1").innerText = "value div";

<input id="theValue2"></input>
window.document.getElementById("theValue2").value = "value input";

You can try example here!

Why is there no Char.Empty like String.Empty?

A char, unlike a string, is a discrete thing with a fixed size. A string is really a container of chars.

So, Char.Empty doesn't really make sense in that context. If you have a char, it's not empty.

What is the standard way to add N seconds to datetime.time in Python?

For completeness' sake, here's the way to do it with arrow (better dates and times for Python):

sometime = arrow.now()
abitlater = sometime.shift(seconds=3)

How to start and stop android service from a adb shell?

You should set the android:exported attribute of the service to "true", in order to allow other components to invoke it. In the AndroidManifest.xml file, add the following attribute:

<service android:exported="true" ></service>

Then, you should be able to start the service via adb:

adb shell am startservice com.package.name/.YourServiceName

For more info about the android:exported attribute see this page.

Resource leak: 'in' is never closed

If you are using JDK7 or 8, you can use try-catch with resources.This will automatically close the scanner.

try ( Scanner scanner = new Scanner(System.in); )
  {
    System.out.println("Enter the width of the Rectangle: ");
    width = scanner.nextDouble();
    System.out.println("Enter the height of the Rectangle: ");
    height = scanner.nextDouble();
  }
catch(Exception ex)
{
    //exception handling...do something (e.g., print the error message)
    ex.printStackTrace();
}

How to set underline text on textview?

Need not to use HTML properties, let's focus on java xD I had the same problem, i found the way to do it in java:

String text="Hide post";
TextView tvHide=(TextView)findViewById(R.id.text);
SpannableString spanString = new SpannableString(text);
spanString.setSpan(new UnderlineSpan(), 0, spanString.length(), 0);
tvHide.setText(spanString );

Git: How to remove proxy

git config --global --unset http.proxy
git config --unset http.proxy
http_proxy=""

How to margin the body of the page (html)?

Yeah a CSS primer will not hurt here so you can do two things: 1 - within the tags of your html you can open a style tag like this:

<style type="text/css">
  body {
   margin: 0px;
  }
  /*
   * this is the same as writing
   * body { margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px;}
   * I'm adding px here for clarity sake but the unit is not really needed if you have 0
   * look into em, pt and % for other unit types 
   * the rules are always clockwise: top, right, bottom, left
  */
</style>

2- the above though will only work on the page you have this code embeded, so if if you wanted to reuse this in 10 files, then you will have to copy it over on all 10 files, and if you wanted to make a change let's say have a margin of 5px instead, you would have to open all those files and make the edit. That's why using an external style sheet is a golden rule in front end coding. So save the body declaration in a separate file named style.css for example and from your add this to your html instead:

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

Now you can put this in the of all pages that will benefit from these styles and whenever needed to change them you will only need to do so in one place. Hope it helps. Cheers

string.Replace in AngularJs

In Javascript method names are camel case, so it's replace, not Replace:

$scope.newString = oldString.replace("stackover","NO");

Note that contrary to how the .NET Replace method works, the Javascript replace method replaces only the first occurrence if you are using a string as first parameter. If you want to replace all occurrences you need to use a regular expression so that you can specify the global (g) flag:

$scope.newString = oldString.replace(/stackover/g,"NO");

See this example.

Select and display only duplicate records in MySQL

SELECT * FROM `table` t1 join `table` t2 WHERE (t1.name=t2.name) && (t1.id!=t2.id)

#include errors detected in vscode

For Windows:

  1. Please add this directory to your environment variable(Path):

C:\mingw-w64\x86_64-8.1.0-win32-seh-rt_v6-rev0\mingw64\bin\

  1. For Include errors detected, mention the path of your include folder into

"includePath": [ "C:/mingw-w64/x86_64-8.1.0-win32-seh-rt_v6-rev0/mingw64/include/" ]

, as this is the path from where the compiler fetches the library to be included in your program.

Using jQuery, Restricting File Size Before Uploading

It's not possible to verify the image size, width or height on the client side. You need to have this file uploaded on the server and use PHP to verify all this info. PHP has special functions like: getimagesize()

list($width, $height, $type, $attr) = getimagesize("img/flag.jpg");
echo "<img src=\"img/flag.jpg\" $attr alt=\"getimagesize() example\" />";

Setting Windows PATH for Postgres tools

In order to connect my git bash to the postgreSQL, I had to add at least 4 environment variables to the windows. Git, Node.js, System 32 and postgreSQL. This is what I set as the value for the Path variable: C:\Windows\System32;C:\Program Files\Git\cmd;C:\Program Files\nodejs;C:\Program Files\PostgreSQL\12\bin; and It works perfectly.

How to delete a column from a table in MySQL

If you are running MySQL 5.6 onwards, you can make this operation online, allowing other sessions to read and write to your table while the operation is been performed:

ALTER TABLE tbl_Country DROP COLUMN IsDeleted, ALGORITHM=INPLACE, LOCK=NONE;

How to compile c# in Microsoft's new Visual Studio Code?

Intellisense does work for C# 6, and it's great.

For running console apps you should set up some additional tools:

  • ASP.NET 5; in Powershell: &{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}
  • Node.js including package manager npm.
  • The rest of required tools including Yeoman yo: npm install -g yo grunt-cli generator-aspnet bower
  • You should also invoke .NET Version Manager: c:\Users\Username\.dnx\bin\dnvm.cmd upgrade -u

Then you can use yo as wizard for Console Application: yo aspnet Choose name and project type. After that go to created folder cd ./MyNewConsoleApp/ and run dnu restore

To execute your program just type >run in Command Palette (Ctrl+Shift+P), or execute dnx . run in shell from the directory of your project.

Increment counter with loop

The varStatus references to LoopTagStatus which has a getIndex() method.

So:

<c:forEach var="tableEntity" items='${requestScope.tables}' varStatus="outer">
   <c:forEach var="rowEntity" items='${tableEntity.rows}' varStatus="inner">            
        <c:out value="${(outer.index * fn:length(tableEntity.rows)) + inner.index}" />
    </c:forEach>
</c:forEach>

See also:

HTML: How to limit file upload to be only images?

Edited

If things were as they SHOULD be, you could do this via the "Accept" attribute.

http://www.webmasterworld.com/forum21/6310.htm

However, browsers pretty much ignore this, so this is irrelavant. The short answer is, i don't think there is a way to do it in HTML. You'd have to check it server-side instead.

The following older post has some information that could help you with alternatives.

File input 'accept' attribute - is it useful?

How to center a checkbox in a table cell?

If you don't support legacy browsers, I'd use flexbox because it's well supported and will simply solve most of your layout problems.

#table-id td:nth-child(1) { 
    /* nth-child(1) is the first column, change to fit your needs */
    display: flex;
    justify-content: center;
}

This centers all content in the first <td> of every row.

Remove commas from the string using JavaScript

Related answer, but if you want to run clean up a user inputting values into a form, here's what you can do:

const numFormatter = new Intl.NumberFormat('en-US', {
  style: "decimal",
  maximumFractionDigits: 2
})

// Good Inputs
parseFloat(numFormatter.format('1234').replace(/,/g,"")) // 1234
parseFloat(numFormatter.format('123').replace(/,/g,"")) // 123

// 3rd decimal place rounds to nearest
parseFloat(numFormatter.format('1234.233').replace(/,/g,"")); // 1234.23
parseFloat(numFormatter.format('1234.239').replace(/,/g,"")); // 1234.24

// Bad Inputs
parseFloat(numFormatter.format('1234.233a').replace(/,/g,"")); // NaN
parseFloat(numFormatter.format('$1234.23').replace(/,/g,"")); // NaN

// Edge Cases
parseFloat(numFormatter.format(true).replace(/,/g,"")) // 1
parseFloat(numFormatter.format(false).replace(/,/g,"")) // 0
parseFloat(numFormatter.format(NaN).replace(/,/g,"")) // NaN

Use the international date local via format. This cleans up any bad inputs, if there is one it returns a string of NaN you can check for. There's no way currently of removing commas as part of the locale (as of 10/12/19), so you can use a regex command to remove commas using replace.

ParseFloat converts the this type definition from string to number

If you use React, this is what your calculate function could look like:

updateCalculationInput = (e) => {
    let value;
    value = numFormatter.format(e.target.value); // 123,456.78 - 3rd decimal rounds to nearest number as expected
    if(value === 'NaN') return; // locale returns string of NaN if fail
    value = value.replace(/,/g, ""); // remove commas
    value = parseFloat(value); // now parse to float should always be clean input

    // Do the actual math and setState calls here
}

Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?

If you have not committed:

git stash
git checkout some-branch
git stash pop

If you have committed and have not changed anything since:

git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}

If you have committed and then done extra work:

git stash
git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}
git stash pop

Open new popup window without address bars in firefox & IE

check this if it works it works fine for me

<script>
  var windowObjectReference;
  var strWindowFeatures = "menubar=no,location=no,resizable=no,scrollbars=no,status=yes,width=400,height=350";

     function openRequestedPopup() {
      windowObjectReference = window.open("http://www.flyingedge.in/", "CNN_WindowName", strWindowFeatures);
     }
</script>

How to align a div to the top of its parent but keeping its inline-block behaviour?

As others have said, vertical-align: top is your friend.

As a bonus here is a forked fiddle with added enhancements that make it work in Internet Explorer 6 and Internet Explorer 7 too ;)

Example: here

SQL Server: Multiple table joins with a WHERE clause

You need to do a LEFT JOIN.

SELECT Computer.ComputerName, Application.Name, Software.Version
FROM Computer
JOIN dbo.Software_Computer
    ON Computer.ID = Software_Computer.ComputerID
LEFT JOIN dbo.Software
    ON Software_Computer.SoftwareID = Software.ID
RIGHT JOIN dbo.Application
    ON Application.ID = Software.ApplicationID
WHERE Computer.ID = 1 

Here is the explanation:

The result of a left outer join (or simply left join) for table A and B always contains all records of the "left" table (A), even if the join-condition does not find any matching record in the "right" table (B). This means that if the ON clause matches 0 (zero) records in B, the join will still return a row in the result—but with NULL in each column from B. This means that a left outer join returns all the values from the left table, plus matched values from the right table (or NULL in case of no matching join predicate). If the right table returns one row and the left table returns more than one matching row for it, the values in the right table will be repeated for each distinct row on the left table. From Oracle 9i onwards the LEFT OUTER JOIN statement can be used as well as (+).

How to adjust an UIButton's imageSize?

Swift 3

I set myButton width and height to 40 and my padding from EdgeInsetsMake is 15 all sides. I suggest to add a background color to your button to see the actual padding.

myButton.backgroundColor = UIColor.gray // sample color to check padding
myButton.imageView?.contentMode = .scaleAspectFit
myButton.imageEdgeInsets = UIEdgeInsetsMake(15, 15, 15, 15)

Find max and second max salary for a employee table MySQL

You can write 2 subqueries like this example

SELECT (select max(Salary) from Employee) as max_id, 
     (select Salary from Employee order by Salary desc limit 1,1) as max_2nd 

Android: disabling highlight on listView click

The orange highlight effect is a style on the ListView. This article gives a good overview of how to override the listView style.

Essentially, you have a selector that specifies different style elements based on the current state.

see this for short and quick solution https://stackoverflow.com/a/12242564/185022

Copying from one text file to another using Python

f=open('list1.txt')  
f1=open('output.txt','a')
for x in f.readlines():
    f1.write(x)
f.close()
f1.close()

this will work 100% try this once

"Failed to install the following Android SDK packages as some licences have not been accepted" error

In Android Studio go to Tools -> SDK Manager.

Go to SDK Tools tab.

Select the Android SDK Command-line Tools (latest) and download by pressing Apply.

enter image description here

On Windows, you can find the sdkmanager.bat at

C:\Users\[your_user]\AppData\Local\Android\Sdk\cmdline-tools\latest\bin

enter image description here

Calling Javascript from a html form

Everything seems to be perfect in your code except the fact that handleClick() isn't working because this function lacks a parameter in its function call invocation(but the function definition within has an argument which makes a function mismatch to occur).

The following is a sample working code for calculating all semester's total marks and corresponding grade. It demonstrates the use of a JavaScript function(call) within a html file and also solves the problem you are facing.

<!DOCTYPE html>
<html>
<head>
    <title> Semester Results </title>
</head>
<body>
    <h1> Semester Marks </h1> <br> 
    <script type = "text/javascript">
        function checkMarks(total)
        {
            document.write("<h1> Final Result !!! </h1><br>");
            document.write("Total Marks = " + total + "<br><br>");
            var avg = total / 6.0;
            document.write("CGPA = " + (avg / 10.0).toFixed(2) + "<br><br>");
            if(avg >= 90)
                document.write("Grade = A");
            else if(avg >= 80)
                document.write("Grade = B");
            else if(avg >= 70)
                document.write("Grade = C");
            else if(avg >= 60)
                document.write("Grade = D");
            else if(avg >= 50)
                document.write("Grade = Pass");
            else
                document.write("Grade = Fail");
       }
    </script>
    <form name = "myform" action = "javascript:checkMarks(Number(s1.value) + Number(s2.value) + Number(s3.value) + Number(s4.value) + Number(s5.value) + Number(s6.value))"/>
        Semester 1:  <input type = "text" id = "s1"/> <br><br>
        Semester 2:  <input type = "text" id = "s2"/> <br><br>
        Semester 3:  <input type = "text" id = "s3"/> <br><br>
        Semester 4:  <input type = "text" id = "s4"/> <br><br>
        Semester 5:  <input type = "text" id = "s5"/> <br><br>
        Semester 6:  <input type = "text" id = "s6"/> <br><br><br>
        <input type = "submit" value = "Submit"/>
    </form>
</body>
</html>

Favicon: .ico or .png / correct tags?

See here: Cross Browser favicon

Thats the way to go:

<link rel="icon" type="image/png" href="http://www.example.com/image.png"><!-- Major Browsers -->
<!--[if IE]><link rel="SHORTCUT ICON" href="http://www.example.com/alternateimage.ico"/><![endif]--><!-- Internet Explorer-->

How to automatically update your docker containers, if base-images are updated

Above Answers are also correct

There are two Approach

  1. Use webhooks
  2. Run script for every specific minute to get fresh pull of docker images

I am just sharing script may be it will helpful for you! You can use it with cronjob, I tried succesfully on OSX

#!/bin/bash
##You can use below commented line for setting cron tab for running cron job and to store its O/P in one .txt file  
#* * * * * /usr/bin/sudo -u admin -i bash -c /Users/Swapnil/Documents/checkimg.sh > /Users/Swapnil/Documents/cron_output.log 2>&1
# Example for the Docker Hub V2 API
# Returns all images and tags associated with a Docker Hub organization account.
# Requires 'jq': https://stedolan.github.io/jq/

# set username, password, and organization
# Filepath where your docker-compose file is present
FILEPATH="/Users/Swapnil/Documents/lamp-alpine"
# Your Docker hub user name
UNAME="ur username"
# Your Docker hub user password
UPASS="ur pwd"
# e.g organisation_name/image_name:image_tag
ORG="ur org name"
IMGNAME="ur img name"
IMGTAG="ur img tag"
# Container name
CONTNAME="ur container name"
# Expected built mins
BUILDMINS="5"
#Generally cronjob frequency
CHECKTIME="5"
NETWORKNAME="${IMGNAME}_private-network"
#After Image pulling, need to bring up all docker services?
DO_DOCKER_COMPOSE_UP=true
# -------
echo "Eecuting Script @ date and time in YmdHMS: $(date +%Y%m%d%H%M%S)"
set -e
PIDFILE=/Users/Swapnil/Documents/$IMGNAME/forever.pid
if [ -f $PIDFILE ]
then
  PID=$(cat $PIDFILE)
  ps -p $PID > /dev/null 2>&1
  if [ $? -eq 0 ]
  then
    echo "Process already running"
    exit 1
  else
    ## Process not found assume not running
    echo $$
    echo $$ > $PIDFILE
    if [ $? -ne 0 ]
    then
      echo "Could not create PID file"
      exit 1
    fi
  fi
else
  echo $$ > $PIDFILE
  if [ $? -ne 0 ]
  then
    echo "Could not create PID file"
    exit 1
  fi
fi

# Check Docker is running or not; If not runing then exit
if docker info|grep Containers ; then
    echo "Docker is running"
else
    echo "Docker is not running"
    rm $PIDFILE
    exit 1
fi

# Check Container is running or not; and set variable
CONT_INFO=$(docker ps -f "name=$CONTNAME" --format "{{.Names}}")
if [ "$CONT_INFO" = "$CONTNAME" ]; then
    echo "Container is running"
    IS_CONTAINER_RUNNING=true
else
    echo "Container is not running"
    IS_CONTAINER_RUNNING=false
fi


# get token
echo "Retrieving token ..."
TOKEN=$(curl -s -H "Content-Type: application/json" -X POST -d '{"username": "'${UNAME}'", "password": "'${UPASS}'"}' https://hub.docker.com/v2/users/login/ | jq -r .token)

# get list of repositories
echo "Retrieving repository list ..."
REPO_LIST=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/?page_size=100 | jq -r '.results|.[]|.name')

# output images & tags
echo "Images and tags for organization: ${ORG}"
echo
for i in ${REPO_LIST}
do
  echo "${i}:"
  # tags
  IMAGE_TAGS=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/${i}/tags/?page_size=100 | jq -r '.results|.[]|.name')
  for j in ${IMAGE_TAGS}
  do
    echo "  - ${j}"
  done
  #echo
done

# Check Perticular image is the latest or not
#imm=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/${IMGNAME}/tags/?page_size=100)
echo "-----------------"
echo "Last built date details about Image ${IMGNAME} : ${IMGTAG} for organization: ${ORG}"
IMAGE_UPDATED_DATE=$(curl -s -H "Authorization: JWT ${TOKEN}" https://hub.docker.com/v2/repositories/${ORG}/${IMGNAME}/tags/?page_size=100 | jq -r '.results|.[]|select(.name | contains("'${IMGTAG}'")).last_updated')
echo "On Docker Hub IMAGE_UPDATED_DATE---$IMAGE_UPDATED_DATE"
echo "-----------------"

IMAGE_CREATED_DATE=$(docker image inspect ${ORG}/${IMGNAME}:${IMGTAG} | jq -r '.[]|.Created')
echo "Locally IMAGE_CREATED_DATE---$IMAGE_CREATED_DATE"

updatedDate=$(date -jf '%Y-%m-%dT%H:%M' "${IMAGE_UPDATED_DATE:0:16}" +%Y%m%d%H%M%S) 
createdDate=$(date -jf '%Y-%m-%dT%H:%M' "${IMAGE_CREATED_DATE:0:16}" +%Y%m%d%H%M%S)
currentDate=$(date +%Y%m%d%H%M%S)

start_date=$(date -jf "%Y%m%d%H%M%S" "$currentDate" "+%s")
end_date=$(date -jf "%Y%m%d%H%M%S" "$updatedDate" "+%s")
updiffMins=$(( ($start_date - $end_date) / (60) ))
if [[ "$updiffMins" -lt $(($CHECKTIME+1)) ]]; then
        if [ ! -d "${FILEPATH}" ]; then
            mkdir "${FILEPATH}";
        fi
        cd "${FILEPATH}"
        pwd
        echo "updatedDate---$updatedDate" > "ScriptOutput_${currentDate}.txt"
        echo "createdDate---$createdDate" >> "ScriptOutput_${currentDate}.txt"
        echo "currentDate---$currentDate" >> "ScriptOutput_${currentDate}.txt"
        echo "Found after regular checking time -> Docker hub's latest updated image is new; Diff ${updiffMins} mins" >> "ScriptOutput_${currentDate}.txt"
        echo "Script is checking for latest updates after every ${CHECKTIME} mins" >> "ScriptOutput_${currentDate}.txt"
        echo "Fetching all new"
        echo "---------------------------"
        if $IS_CONTAINER_RUNNING ; then
            echo "Container is running"         
        else
            docker-compose down
            echo "Container stopped and removed; Network removed" >> "ScriptOutput_${currentDate}.txt"
        fi
        echo "Image_Created_Date=$currentDate" > ".env"
        echo "ORG=$ORG" >> ".env"
        echo "IMGNAME=$IMGNAME" >> ".env"
        echo "IMGTAG=$IMGTAG" >> ".env"
        echo "CONTNAME=$CONTNAME" >> ".env"
        echo "NETWORKNAME=$NETWORKNAME" >> ".env"
        docker-compose build --no-cache
        echo "Docker Compose built" >> "ScriptOutput_${currentDate}.txt"
        if $DO_DOCKER_COMPOSE_UP ; then
            docker-compose up -d
            echo "Docker services are up now, checked in" >> "ScriptOutput_${currentDate}.txt"  
        else
            echo "Docker services are down, checked in" >> "ScriptOutput_${currentDate}.txt"
        fi
elif [[ "$updatedDate" -gt "$createdDate" ]]; then 
    echo "Updated is latest"
    start_date=$(date -jf "%Y%m%d%H%M%S" "$updatedDate" "+%s")
    end_date=$(date -jf "%Y%m%d%H%M%S" "$createdDate" "+%s")
    diffMins=$(( ($start_date - $end_date) / (60) ))
    if [[ "$BUILDMINS" -lt "$diffMins" ]]; then
        if [ ! -d "${FILEPATH}" ]; then
            mkdir "${FILEPATH}";
        fi
        cd "${FILEPATH}"
        pwd
        echo "updatedDate---$updatedDate" > "ScriptOutput_${currentDate}.txt"
        echo "createdDate---$createdDate" >> "ScriptOutput_${currentDate}.txt"
        echo "currentDate---$currentDate" >> "ScriptOutput_${currentDate}.txt"
        echo "Found after comparing times -> Docker hub's latest updated image is new; Diff ${diffMins} mins" >> "ScriptOutput_${currentDate}.txt"
        echo "Actual image built time is less i.e. ${diffMins} mins than MAX expexted BUILD TIME i.e. ${BUILDMINS} mins" >> "ScriptOutput_${currentDate}.txt"
        echo "Fetching all new" >> "ScriptOutput_${currentDate}.txt"
        echo "-----------------------------"
        if $IS_CONTAINER_RUNNING ; then
            echo "Container is running"         
        else
            docker-compose down
            echo "Container stopped and removed; Network removed" >> "ScriptOutput_${currentDate}.txt"
        fi
        echo "Image_Created_Date=$currentDate" > ".env"
        echo "ORG=$ORG" >> ".env"
        echo "IMGNAME=$IMGNAME" >> ".env"
        echo "IMGTAG=$IMGTAG" >> ".env"
        echo "CONTNAME=$CONTNAME" >> ".env"
        echo "NETWORKNAME=$NETWORKNAME" >> ".env"
        docker-compose build --no-cache
        echo "Docker Compose built" >> "ScriptOutput_${currentDate}.txt"
        if $DO_DOCKER_COMPOSE_UP ; then
            docker-compose up -d
            echo "Docker services are up now" >> "ScriptOutput_${currentDate}.txt"  
        else
            echo "Docker services are down" >> "ScriptOutput_${currentDate}.txt"
        fi
    elif [[ "$BUILDMINS" -gt "$diffMins" ]]; then
        echo "Docker hub's latest updated image is NOT new; Diff ${diffMins} mins"
        echo "Docker images not fetched"
    else
        echo "Docker hub's latest updated image is NOT new; Diff ${diffMins} mins"
        echo "Docker images not fetched"
    fi
elif [[ "$createdDate" -gt "$updatedDate" ]]; then 
    echo "Created is latest"
    start_date=$(date -jf "%Y%m%d%H%M%S" "$createdDate" "+%s")
    end_date=$(date -jf "%Y%m%d%H%M%S" "$updatedDate" "+%s")
    echo "Docker hub has older docker image than local; Older than $(( ($start_date - $end_date) / (60) ))mins"
fi
echo 
echo "------------end---------------"
rm $PIDFILE

Here is my docker-compose file

version:  "3.2"
services:
  lamp-alpine:
    build:
      context: .
    container_name: "${CONTNAME}"
    image: "${ORG}/${IMGNAME}:${IMGTAG}"
    ports:
      - "127.0.0.1:80:80"
    networks:
      - private-network 

networks:
  private-network:
    driver: bridge

How can I count the number of elements with same class?

$('#maindivid').find('input .inputclass').length

Eclipse error "Could not find or load main class"

I was using eclipse oxygen and the problem persists everytime. Later i found that if your Eclipse workspace is under the directory with non ascii characters then somehow javaw.exe couldn't reach the bin directory. Suppose your directory name is Work_Hello the remove underscore sign and clean the project and run configurations. This worked for me. Reference: https://www.eclipse.org/forums/index.php/t/1093209/

Java Reflection: How to get the name of a variable?

update @Marcel Jackwerth's answer for general.

and only working with class attribute, not working with method variable.

    /**
     * get variable name as string
     * only work with class attributes
     * not work with method variable
     *
     * @param headClass variable name space
     * @param vars      object variable
     * @throws IllegalAccessException
     */
    public static void printFieldNames(Object headClass, Object... vars) throws IllegalAccessException {
        List<Object> fooList = Arrays.asList(vars);
        for (Field field : headClass.getClass().getFields()) {
            if (fooList.contains(field.get(headClass))) {
                System.out.println(field.getGenericType() + " " + field.getName() + " = " + field.get(headClass));
            }
        }
    }

IF... OR IF... in a windows batch file

A much faster alternative I usually use is as follows, as I can "or" an arbitrary number of conditions that can fit in variable space

@(
  Echo off
  Set "_Match= 1 2 3 "
)

Set /a "var=3"

Echo:%_Match%|Find " %var% ">nul || (
  REM Code for a false condition goes here
) && (
  REM code for a true condition goes here.
)

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

Passing $_POST values with cURL

Should work fine.

$data = array('name' => 'Ross', 'php_master' => true);

// You can POST a file by prefixing with an @ (for <input type="file"> fields)
$data['file'] = '@/home/user/world.jpg';

$handle = curl_init($url);
curl_setopt($handle, CURLOPT_POST, true);
curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
curl_exec($handle);
curl_close($handle)

We have two options here, CURLOPT_POST which turns HTTP POST on, and CURLOPT_POSTFIELDS which contains an array of our post data to submit. This can be used to submit data to POST <form>s.


It is important to note that curl_setopt($handle, CURLOPT_POSTFIELDS, $data); takes the $data in two formats, and that this determines how the post data will be encoded.

  1. $data as an array(): The data will be sent as multipart/form-data which is not always accepted by the server.

    $data = array('name' => 'Ross', 'php_master' => true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, $data);
    
  2. $data as url encoded string: The data will be sent as application/x-www-form-urlencoded, which is the default encoding for submitted html form data.

    $data = array('name' => 'Ross', 'php_master' => true);
    curl_setopt($handle, CURLOPT_POSTFIELDS, http_build_query($data));
    

I hope this will help others save their time.

See:

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

In the build.gradle file for your app module, add this to the defaultConfig section (under the android section). This will write out the schema to a schemas subfolder of your project folder.

javaCompileOptions {
    annotationProcessorOptions {
        arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
    }
}

Like this:

// ...

android {
    
    // ... (compileSdkVersion, buildToolsVersion, etc)

    defaultConfig {

        // ... (applicationId, miSdkVersion, etc)
        
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }
   
    // ... (buildTypes, compileOptions, etc)

}

// ...

Node.js https pem error: routines:PEM_read_bio:no start line

I guess this is because your nodejs cert has expired. Type this line :
npm set registry http://registry.npmjs.org/
and after that try again with npm install . This actually solved my problem.

How to use SQL Select statement with IF EXISTS sub query?

Use CASE:

SELECT 
  TABEL1.Id, 
  CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1

If TABLE2.ID is Unique or a Primary Key, you could also use this:

SELECT 
  TABEL1.Id, 
  CASE WHEN TABLE2.ID IS NOT NULL
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1
  LEFT JOIN Table2
    ON TABLE2.ID = TABLE1.ID

How to iterate over arguments in a Bash script

Note that Robert's answer is correct, and it works in sh as well. You can (portably) simplify it even further:

for i in "$@"

is equivalent to:

for i

I.e., you don't need anything!

Testing ($ is command prompt):

$ set a b "spaces here" d
$ for i; do echo "$i"; done
a
b
spaces here
d
$ for i in "$@"; do echo "$i"; done
a
b
spaces here
d

I first read about this in Unix Programming Environment by Kernighan and Pike.

In bash, help for documents this:

for NAME [in WORDS ... ;] do COMMANDS; done

If 'in WORDS ...;' is not present, then 'in "$@"' is assumed.

AngularJS resource promise

If you want to use asynchronous method you need to use callback function by $promise, here is example:

var Regions = $resource('mocks/regions.json');

$scope.regions = Regions.query();
$scope.regions.$promise.then(function (result) {
    $scope.regions = result;
});

How to plot all the columns of a data frame in R

You can jump through hoops and convert your solution to a lapply, sapply or apply call. (I see @jonw shows one way to do this.) Other than that what you have already is perfectly acceptable code.

If these are all a time series or similar then the following might be a suitable alternative, which plots each series in it's own panel on a single plotting region. We use the zoo package as it handles ordered data like this very well indeed.

require(zoo)
set.seed(1)
## example data
dat <- data.frame(X = cumsum(rnorm(100)), Y = cumsum(rnorm(100)),
                  Z = cumsum(rnorm(100)))
## convert to multivariate zoo object
datz <- zoo(dat)
## plot it
plot(datz)

Which gives: Example of zoo plotting capabilities

Javascript : array.length returns undefined

One option is:

Object.keys(myObject).length

Sadly it not works under older IE versions (under 9).

If you need that compatibility, use the painful version:

var key, count = 0;
for(key in myObject) {
  if(myObject.hasOwnProperty(key)) {
    count++;
  }
}

JavaScript window resize event

The resize event should never be used directly as it is fired continuously as we resize.

Use a debounce function to mitigate the excess calls.

window.addEventListener('resize',debounce(handler, delay, immediate),false);

Here's a common debounce floating around the net, though do look for more advanced ones as featuerd in lodash.

const debounce = (func, wait, immediate) => {
    var timeout;
    return () => {
        const context = this, args = arguments;
        const later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

This can be used like so...

window.addEventListener('resize', debounce(() => console.log('hello'),
200, false), false);

It will never fire more than once every 200ms.

For mobile orientation changes use:

window.addEventListener('orientationchange', () => console.log('hello'), false);

Here's a small library I put together to take care of this neatly.

Windows Batch: How to add Host-Entries?

Here is my modification of @rashy above. The script does the following:

  • it verifies you have access, if not, requests it
  • allows you to enter in multiple hosts in a list
  • loops through the list
  • It finds the line containing the the domain name and removes it, then re-adds it (incase the ip has changed since the last time the script was run).
  • if the domain isn't there, it just adds it.

This is the script:

@echo off
TITLE Modifying your HOSTS file
COLOR F0
ECHO.


:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"="
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"

IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%

ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop


:REJECTED
ECHO Your HOSTS file was left unchanged>>%systemroot%\Temp\hostFileUpdate.log
ECHO Finished.
GOTO END


:ACCEPTED
setlocal enabledelayedexpansion
::Create your list of host domains
set LIST=(diqc.oca wiki.oca)
::Set the ip of the domains you set in the list above
set diqc.oca=192.168.111.6
set wiki.oca=192.168.111.4
:: deletes the parentheses from LIST
set _list=%LIST:~1,-1%
::ECHO %WINDIR%\System32\drivers\etc\hosts > tmp.txt
for  %%G in (%_list%) do (
    set  _name=%%G
    set  _value=!%%G!
    SET NEWLINE=^& echo.
    ECHO Carrying out requested modifications to your HOSTS file
    ::strip out this specific line and store in tmp file
    type %WINDIR%\System32\drivers\etc\hosts | findstr /v !_name! > tmp.txt
    ::re-add the line to it
    ECHO %NEWLINE%^!_value! !_name!>>tmp.txt
    ::overwrite host file
    copy /b/v/y tmp.txt %WINDIR%\System32\drivers\etc\hosts
    del tmp.txt
)
ipconfig /flushdns
ECHO.
ECHO.
ECHO Finished, you may close this window now.
ECHO You should now open Chrome and go to "chrome://net-internals/#dns" (without quotes)
ECHO     then click the "clear host cache" button
GOTO END

:END
ECHO.
ping -n 11 192.0.2.2 > nul
EXIT

SQL Query To Obtain Value that Occurs more than once

SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
ORDER BY COUNT(*) DESC

Where is SQL Server Management Studio 2012?

For separate modules (x86 and x64), if you want a customized installation without downloading loads of crap, see Servers Microsoft® SQL Server® 2012 Express.

Working with select using AngularJS's ng-options

If you need a custom title for each option, ng-options is not applicable. Instead use ng-repeat with options:

<select ng-model="myVariable">
  <option ng-repeat="item in items"
          value="{{item.ID}}"
          title="Custom title: {{item.Title}} [{{item.ID}}]">
       {{item.Title}}
  </option>
</select>

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

Center Align on a Absolutely Positioned Div

If it is necessary for you to have a relative width (in percentage), you could wrap your div in a absolute positioned one:

div#wrapper {
    position: absolute;
    width: 100%;
    text-align: center;
}

Remember that in order to position an element absolutely, the parent element must be positioned relatively.

How can I get argv[] as int?

Basic usage

The "string to long" (strtol) function is standard for this ("long" can hold numbers much larger than "int"). This is how to use it:

#include <stdlib.h>

long arg = strtol(argv[1], NULL, 10);
// string to long(string, endpointer, base)

Since we use the decimal system, base is 10. The endpointer argument will be set to the "first invalid character", i.e. the first non-digit. If you don't care, set the argument to NULL instead of passing a pointer, as shown.

Error checking (1)

If you don't want non-digits to occur, you should make sure it's set to the "null terminator", since a \0 is always the last character of a string in C:

#include <stdlib.h>

char* p;
long arg = strtol(argv[1], &p, 10);
if (*p != '\0') // an invalid character was found before the end of the string

Error checking (2)

As the man page mentions, you can use errno to check that no errors occurred (in this case overflows or underflows).

#include <stdlib.h>
#include <errno.h>

char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
    return 1; // In main(), returning non-zero means failure
}

// Everything went well, print it as 'long decimal'
printf("%ld", arg);

Convert to integer

So now we are stuck with this long, but we often want to work with integers. To convert a long into an int, we should first check that the number is within the limited capacity of an int. To do this, we add a second if-statement, and if it matches, we can just cast it.

#include <stdlib.h>
#include <errno.h>
#include <limits.h>

char* p;
errno = 0; // not 'int errno', because the '#include' already defined it
long arg = strtol(argv[1], &p, 10);
if (*p != '\0' || errno != 0) {
    return 1; // In main(), returning non-zero means failure
}

if (arg < INT_MIN || arg > INT_MAX) {
    return 1;
}
int arg_int = arg;

// Everything went well, print it as a regular number
printf("%d", arg_int);

To see what happens if you don't do this check, test the code without the INT_MIN/MAX if-statement. You'll see that if you pass a number larger than 2147483647 (231), it will overflow and become negative. Or if you pass a number smaller than -2147483648 (-231-1), it will underflow and become positive. Values beyond those limits are too large to fit in an integer.

Full example

#include <stdio.h>  // for printf()
#include <stdlib.h> // for strtol()
#include <errno.h>  // for errno
#include <limits.h> // for INT_MIN and INT_MAX

int main(int argc, char** argv) {
    char* p;
    errno = 0; // not 'int errno', because the '#include' already defined it
    long arg = strtol(argv[1], &p, 10);
    if (*p != '\0' || errno != 0) {
        return 1; // In main(), returning non-zero means failure
    }

    if (arg < INT_MIN || arg > INT_MAX) {
        return 1;
    }
    int arg_int = arg;

    // Everything went well, print it as a regular number plus a newline
    printf("Your value was: %d\n", arg_int);
    return 0;
}

In Bash, you can test this with:

cc code.c -o example  # Compile, output to 'example'
./example $((2**31-1))  # Run it
echo "exit status: $?"  # Show the return value, also called 'exit status'

Using 2**31-1, it should print the number and 0, because 231-1 is just in range. If you pass 2**31 instead (without -1), it will not print the number and the exit status will be 1.

Beyond this, you can implement custom checks: test whether the user passed an argument at all (check argc), test whether the number is in the range that you want, etc.

Do I need to pass the full path of a file in another directory to open()?

Yes, you need the full path.

log = open(os.path.join(root, f), 'r')

Is the quick fix. As the comment pointed out, os.walk decends into subdirs so you do need to use the current directory root rather than indir as the base for the path join.

python pandas dataframe columns convert to dict key and value

You can also do this if you want to play around with pandas. However, I like punchagan's way.

# replicating your dataframe
lake = pd.DataFrame({'co tp': ['DE Lake', 'Forest', 'FR Lake', 'Forest'], 
                 'area': [10, 20, 30, 40], 
                 'count': [7, 5, 2, 3]})
lake.set_index('co tp', inplace=True)

# to get key value using pandas
area_dict = lake.set_index('area').T.to_dict('records')[0]
print(area_dict)

output: {10: 7, 20: 5, 30: 2, 40: 3}

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

I had this problem and

dumpbin /exports mydll.dll

and

depends mydll.dll

showed 'DllRegisterServer'.

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

Invalid use side-effecting operator Insert within a function

You can't use a function to insert data into a base table. Functions return data. This is listed as the very first limitation in the documentation:

User-defined functions cannot be used to perform actions that modify the database state.

"Modify the database state" includes changing any data in the database (though a table variable is an obvious exception the OP wouldn't have cared about 3 years ago - this table variable only lives for the duration of the function call and does not affect the underlying tables in any way).

You should be using a stored procedure, not a function.

Angular 2 'component' is not a known element

I had the same problem with Angular CLI: 10.1.5 The code works fine, but the error was shown in the VScode v1.50

Resolved by killing the terminal (ng serve) and restarting VScode.

Calculate difference in keys contained in two Python dictionaries

what about standart (compare FULL Object)

PyDev->new PyDev Module->Module: unittest

import unittest


class Test(unittest.TestCase):


    def testName(self):
        obj1 = {1:1, 2:2}
        obj2 = {1:1, 2:2}
        self.maxDiff = None # sometimes is usefull
        self.assertDictEqual(d1, d2)

if __name__ == "__main__":
    #import sys;sys.argv = ['', 'Test.testName']

    unittest.main()

XPath test if node value is number

Test the value against NaN:

<xsl:if test="string(number(myNode)) != 'NaN'">
    <!-- myNode is a number -->
</xsl:if>

This is a shorter version (thanks @Alejandro):

<xsl:if test="number(myNode) = myNode">
    <!-- myNode is a number -->
</xsl:if>

font-weight is not working properly?

Its because the font size (9px) is too small to display bold. Try 11px or more and it works fine.

VBScript How can I Format Date?

Although answer is provided I found simpler solution:

Date:

01/20/2017

By doing replace

CurrentDate = replace(date, "/", "-")

It will output:

01-20-2017

How do I check to see if a value is an integer in MySQL?

Here is the simple solution for it assuming the data type is varchar

select * from calender where year > 0

It will return true if the year is numeric else false

endsWith in JavaScript

From developer.mozilla.org String.prototype.endsWith()

Summary

The endsWith() method determines whether a string ends with the characters of another string, returning true or false as appropriate.

Syntax

str.endsWith(searchString [, position]);

Parameters

  • searchString : The characters to be searched for at the end of this string.

  • position : Search within this string as if this string were only this long; defaults to this string's actual length, clamped within the range established by this string's length.

Description

This method lets you determine whether or not a string ends with another string.

Examples

var str = "To be, or not to be, that is the question.";

alert( str.endsWith("question.") );  // true
alert( str.endsWith("to be") );      // false
alert( str.endsWith("to be", 19) );  // true

Specifications

ECMAScript Language Specification 6th Edition (ECMA-262)

Browser compatibility

Browser compatibility

Select rows which are not present in other table

this can also be tried...

SELECT l.ip, tbl2.ip as ip2, tbl2.hostname
FROM   login_log l 
LEFT   JOIN (SELECT ip_location.ip, ip_location.hostname
             FROM ip_location
             WHERE ip_location.ip is null)tbl2

C# : Out of Memory exception

While the GC compacts the small object heap as part of an optimization strategy to eliminate memory holes, the GC never compacts the large object heap for performance reasons**(the cost of compaction is too high for large objects (greater than 85KB in size))**. Hence if you are running a program that uses many large objects in an x86 system, you might encounter OutOfMemory exceptions. If you are running that program in an x64 system, you might have a fragmented heap.

When creating a service with sc.exe how to pass in context parameters?

This command works:

sc create startSvn binPath= "\"C:\Subversion\bin\svnserve.exe\" --service -r \"C:\SVN_Repository\"" displayname= "MyServer" depend= tcpip start= auto

Purpose of a constructor in Java?

Let us consider we are storing the student details of 3 students. These 3 students are having different values for sno, sname and sage, but all 3 students belongs to same department CSE. So it is better to initialize "dept" variable inside a constructor so that this value can be taken by all the 3 student objects.

To understand clearly, see the below simple example:

class Student
{
    int sno,sage;
    String sname,dept;
    Student()
    {
        dept="CSE";
    }
    public static void main(String a[])
    {
        Student s1=new Student();
        s1.sno=101;
        s1.sage=33;
        s1.sname="John";

        Student s2=new Student();
        s2.sno=102;
        s2.sage=99;
        s2.sname="Peter";


        Student s3=new Student();
        s3.sno=102;
        s3.sage=99;
        s3.sname="Peter";
        System.out.println("The details of student1 are");
        System.out.println("The student no is:"+s1.sno);
        System.out.println("The student age is:"+s1.sage);
        System.out.println("The student name is:"+s1.sname);
        System.out.println("The student dept is:"+s1.dept);


        System.out.println("The details of student2 are");`enter code here`
        System.out.println("The student no is:"+s2.sno);
        System.out.println("The student age is:"+s2.sage);
        System.out.println("The student name is:"+s2.sname);
        System.out.println("The student dept is:"+s2.dept);

        System.out.println("The details of student2 are");
        System.out.println("The student no is:"+s3.sno);
        System.out.println("The student age is:"+s3.sage);
        System.out.println("The student name is:"+s3.sname);
        System.out.println("The student dept is:"+s3.dept);
    }
}

Output:

The details of student1 are
The student no is:101
The student age is:33
The student name is:John
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE
The details of student2 are
The student no is:102
The student age is:99
The student name is:Peter
The student dept is:CSE

When to use margin vs padding in CSS

Here is some HTML that demonstrates how padding and margin affect clickability, and background filling. An object receives clicks to its padding, but clicks on an objects margin'd area go to its parent.

_x000D_
_x000D_
$(".outer").click(function(e) {_x000D_
  console.log("outer");_x000D_
  e.stopPropagation();_x000D_
});_x000D_
_x000D_
$(".inner").click(function(e) {_x000D_
  console.log("inner");_x000D_
  e.stopPropagation();_x000D_
});
_x000D_
.outer {_x000D_
  padding: 10px;_x000D_
  background: red;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  margin: 10px;_x000D_
  padding: 10px;_x000D_
  background: blue;_x000D_
  border: solid white 1px;_x000D_
}
_x000D_
<script src="http://code.jquery.com/jquery-latest.js"></script>_x000D_
_x000D_
<div class="outer">_x000D_
  <div class="inner" style="position:relative; height:0px; width:0px">_x000D_
_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get list of JSON objects with Spring RestTemplate

i actually deveopped something functional for one of my projects before and here is the code :

/**
 * @param url             is the URI address of the WebService
 * @param parameterObject the object where all parameters are passed.
 * @param returnType      the return type you are expecting. Exemple : someClass.class
 */

public static <T> T getObject(String url, Object parameterObject, Class<T> returnType) {
    try {
        ResponseEntity<T> res;
        ObjectMapper mapper = new ObjectMapper();
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(2000);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<T> entity = new HttpEntity<T>((T) parameterObject, headers);
        String json = mapper.writeValueAsString(restTemplate.exchange(url, org.springframework.http.HttpMethod.POST, entity, returnType).getBody());
        return new Gson().fromJson(json, returnType);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

/**
 * @param url             is the URI address of the WebService
 * @param parameterObject the object where all parameters are passed.
 * @param returnType      the type of the returned object. Must be an array. Exemple : someClass[].class
 */
public static <T> List<T> getListOfObjects(String url, Object parameterObject, Class<T[]> returnType) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
        restTemplate.getMessageConverters().add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
        ((SimpleClientHttpRequestFactory) restTemplate.getRequestFactory()).setConnectTimeout(2000);
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<T> entity = new HttpEntity<T>((T) parameterObject, headers);
        ResponseEntity<Object[]> results = restTemplate.exchange(url, org.springframework.http.HttpMethod.POST, entity, Object[].class);
        String json = mapper.writeValueAsString(results.getBody());
        T[] arr = new Gson().fromJson(json, returnType);
        return Arrays.asList(arr);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

I hope that this will help somebody !

What port is a given program using?

most decent firewall programs should allow you to access this information. I know that Agnitum OutpostPro Firewall does.

How to provide user name and password when connecting to a network share

You should be looking at adding a like like this:

<identity impersonate="true" userName="domain\user" password="****" />

Into your web.config.

More Information.

How to make this Header/Content/Footer layout using CSS?

After fiddling around a while I found a solution that works in >IE7, Chrome, Firefox:

http://jsfiddle.net/xfXaw/

* {
    margin:0;
    padding:0;
}

html, body {
    height:100%;
}

#wrap {
    min-height:100%;

}

#header {
    background: red;
}

#content {
    padding-bottom: 50px;
}

#footer {
    height:50px;
    margin-top:-50px;
    background: green;
}

HTML:

<div id="wrap">
    <div id="header">header</div>
    <div id="content">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. </div>
</div>
<div id="footer">footer</div>

Python string to unicode

Unicode escapes only work in unicode strings, so this

 a="\u2026"

is actually a string of 6 characters: '\', 'u', '2', '0', '2', '6'.

To make unicode out of this, use decode('unicode-escape'):

a="\u2026"
print repr(a)
print repr(a.decode('unicode-escape'))

## '\\u2026'
## u'\u2026'

Explanation of JSONB introduced by PostgreSQL

Peeyush:

The short answer is:

  • If you are doing a lot of JSON manipulation inside PostgreSQL, such as sorting, slicing, splicing, etc., you should use JSONB for speed reasons.
  • If you need indexed lookups for arbitrary key searches on JSON, then you should use JSONB.
  • If you are doing neither of the above, you should probably use JSON.
  • If you need to preserve key ordering, whitespace, and duplicate keys, you should use JSON.

For a longer answer, you'll need to wait for me to do a full "HowTo" writeup closer to the 9.4 release.

How to print values separated by spaces instead of new lines in Python 2.7

This does almost everything you want:

f = open('data.txt', 'rb')

while True:
    char = f.read(1)
    if not char: break
    print "{:02x}".format(ord(char)),

With data.txt created like this:

f = open('data.txt', 'wb')
f.write("ab\r\ncd")
f.close()

I get the following output:

61 62 0d 0a 63 64

tl;dr -- 1. You are using poor variable names. 2. You are slicing your hex strings incorrectly. 3. Your code is never going to replace any newlines. You may just want to forget about that feature. You do not quite yet understand the difference between a character, its integer code, and the hex string that represents the integer. They are all different: two are strings and one is an integer, and none of them are equal to each other. 4. For some files, you shouldn't remove newlines.

===

1. Your variable names are horrendous.

That's fine if you never want to ask anybody questions. But since every one needs to ask questions, you need to use descriptive variable names that anyone can understand. Your variable names are only slightly better than these:

fname = 'data.txt'
f = open(fname, 'rb')
xxxyxx = f.read()

xxyxxx = len(xxxyxx)
print "Length of file is", xxyxxx, "bytes. "
yxxxxx = 0

while yxxxxx < xxyxxx:
    xyxxxx = hex(ord(xxxyxx[yxxxxx]))
    xyxxxx = xyxxxx[-2:]
    yxxxxx = yxxxxx + 1
    xxxxxy = chr(13) + chr(10)
    xxxxyx = str(xxxxxy)
    xyxxxxx = str(xyxxxx)
    xyxxxxx.replace(xxxxyx, ' ')
    print xyxxxxx

That program runs fine, but it is impossible to understand.

2. The hex() function produces strings of different lengths.

For instance,

print hex(61)
print hex(15)

--output:--
0x3d
0xf

And taking the slice [-2:] for each of those strings gives you:

3d
xf

See how you got the 'x' in the second one? The slice:

[-2:] 

says to go to the end of the string and back up two characters, then grab the rest of the string. Instead of doing that, take the slice starting 3 characters in from the beginning:

[2:]  

3. Your code will never replace any newlines.

Suppose your file has these two consecutive characters:

"\r\n"

Now you read in the first character, "\r", and convert it to an integer, ord("\r"), giving you the integer 13. Now you convert that to a string, hex(13), which gives you the string "0xd", and you slice off the first two characters giving you:

"d"

Next, this line in your code:

bndtx.replace(entx, ' ')

tries to find every occurrence of the string "\r\n" in the string "d" and replace it. There is never going to be any replacement because the replacement string is two characters long and the string "d" is one character long.

The replacement won't work for "\r\n" and "0d" either. But at least now there is a possibility it could work because both strings have two characters. Let's reduce both strings to a common denominator: ascii codes. The ascii code for "\r" is 13, and the ascii code for "\n" is 10. Now what about the string "0d"? The ascii code for the character "0" is 48, and the ascii code for the character "d" is 100. Those strings do not have a single character in common. Even this doesn't work:

 x = '0d' + '0a'
 x.replace("\r\n", " ")
 print x

 --output:--
 '0d0a'

Nor will this:

x = 'd' + 'a'
x.replace("\r\n", " ")
print x

--output:--
da

The bottom line is: converting a character to an integer then to a hex string does not end up giving you the original character--they are just different strings. So if you do this:

char = "a"
code = ord(char)
hex_str = hex(code)

print char.replace(hex_str, " ")

...you can't expect "a" to be replaced by a space. If you examine the output here:

char = "a"
print repr(char)

code = ord(char)
print repr(code)

hex_str = hex(code)
print repr(hex_str)

print repr(
    char.replace(hex_str, " ")
)

--output:--
'a'
97
'0x61'
'a'

You can see that 'a' is a string with one character in it, and '0x61' is a string with 4 characters in it: '0', 'x', '6', and '1', and you can never find a four character string inside a one character string.

4) Removing newlines can corrupt the data.

For some files, you do not want to replace newlines. For instance, if you were reading in a .jpg file, which is a file that contains a bunch of integers representing colors in an image, and some colors in the image happened to be represented by the number 13 followed by the number 10, your code would eliminate those colors from the output.

However, if you are writing a program to read only text files, then replacing newlines is fine. But then, different operating systems use different newlines. You are trying to replace Windows newlines(\r\n), which means your program won't work on files created by a Mac or Linux computer, which use \n for newlines. There are easy ways to solve that, but maybe you don't want to worry about that just yet.

I hope all that's not too confusing.

when I try to open an HTML file through `http://localhost/xampp/htdocs/index.html` it says unable to connect to localhost

All created by user files saved in C:\xampp\htdocs directory by default, so no need to type the default path in a browser window, just type http://localhost/yourfilename.php or http://localhost/yourfoldername/yourfilename.php this will show you the content of your new page.

TypeError: 'DataFrame' object is not callable

It seems you need DataFrame.var:

Normalized by N-1 by default. This can be changed using the ddof argument

var1 = credit_card.var()

Sample:

#random dataframe
np.random.seed(100)
credit_card = pd.DataFrame(np.random.randint(10, size=(5,5)), columns=list('ABCDE'))
print (credit_card)
   A  B  C  D  E
0  8  8  3  7  7
1  0  4  2  5  2
2  2  2  1  0  8
3  4  0  9  6  2
4  4  1  5  3  4

var1 = credit_card.var()
print (var1)
A     8.8
B    10.0
C    10.0
D     7.7
E     7.8
dtype: float64

var2 = credit_card.var(axis=1)
print (var2)
0     4.3
1     3.8
2     9.8
3    12.2
4     2.3
dtype: float64

If need numpy solutions with numpy.var:

print (np.var(credit_card.values, axis=0))
[ 7.04  8.    8.    6.16  6.24]

print (np.var(credit_card.values, axis=1))
[ 3.44  3.04  7.84  9.76  1.84]

Differences are because by default ddof=1 in pandas, but you can change it to 0:

var1 = credit_card.var(ddof=0)
print (var1)
A    7.04
B    8.00
C    8.00
D    6.16
E    6.24
dtype: float64

var2 = credit_card.var(ddof=0, axis=1)
print (var2)
0    3.44
1    3.04
2    7.84
3    9.76
4    1.84
dtype: float64

How do I import material design library to Android Studio?

If you migrated to AndroidX you should add the dependency in graddle like this:

com.google.android.material:material:1.0.0-rc01

'Java' is not recognized as an internal or external command

In my case, PATH was properly SET but PATHEXT has been cleared by me by mistake with .exe extension. That why window can't find java or anything .exe application from command prompt. Hope it can help someone.

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

jquery UI dialog: how to initialize without a title bar?

Actually there's yet another way to do it, using the dialog widget directly:

You can get the Dialog Widget thus

$("#example").dialog(dialogOpts);
$dlgWidget = $('#example').dialog('widget');

and then do

$dlgWidget.find(".ui-dialog-titlebar").hide();

to hide the titlebar within that dialog only

and in a single line of code (I like chaining):

$('#example').dialog('widget').find(".ui-dialog-titlebar").hide();

No need to add an extra class to the dialog this way, just go at it directly. Workss fine for me.

Good Java graph algorithm library?

JDSL (Data Structures Library in Java) should be good enough if you're into graph algorithms - http://www.cs.brown.edu/cgc/jdsl/

convert string to specific datetime format?

  <%= string_to_datetime("2011-05-19 10:30:14") %>

  def string_to_datetime(string,format="%Y-%m-%d %H:%M:%S")
    DateTime.strptime(string, format).to_time unless string.blank?
  end

Page redirect with successful Ajax request

// Create lag time before redirecting 
setTimeout(function() {
  window.location.href = "thankyou.php";
}, 2000);

$errors=null; 

if ( ($name == "Name") ) {
    $errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
    $errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
    $errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
    $errors .= $spamError; // spam error
}

if ( !($errors) ) {
    mail ($to, $subject, $message, $headers);
    echo "Your message was successfully sent!";
    //instead of echoing this message, I want a page redirect to thankyou.html
    // redirect
    setTimeout();
} else {
    echo "<p id='errors'>";
    echo $errors;
    echo "</p>";
}

Git on Mac OS X v10.7 (Lion)

It's part of Xcode. You'll need to reinstall the developer tools.

Fast way of finding lines in one file that are not in another?

If you're short of "fancy tools", e.g. in some minimal Linux distribution, there is a solution with just cat, sort and uniq:

cat includes.txt excludes.txt excludes.txt | sort | uniq --unique

Test:

seq 1 1 7 | sort --random-sort > includes.txt
seq 3 1 9 | sort --random-sort > excludes.txt
cat includes.txt excludes.txt excludes.txt | sort | uniq --unique

# Output:
1
2    

This is also relatively fast, compared to grep.

Mock HttpContext.Current in Test Init Method

I know this is an older subject, however Mocking a MVC application for unit tests is something we do on very regular basis.

I just wanted to add my experiences Mocking a MVC 3 application using Moq 4 after upgrading to Visual Studio 2013. None of the unit tests were working in debug mode and the HttpContext was showing "could not evaluate expression" when trying to peek at the variables.

Turns out visual studio 2013 has issues evaluating some objects. To get debugging mocked web applications working again, I had to check the "Use Managed Compatibility Mode" in Tools=>Options=>Debugging=>General settings.

I generally do something like this:

public static class FakeHttpContext
{
    public static void SetFakeContext(this Controller controller)
    {

        var httpContext = MakeFakeContext();
        ControllerContext context =
        new ControllerContext(
        new RequestContext(httpContext,
        new RouteData()), controller);
        controller.ControllerContext = context;
    }


    private static HttpContextBase MakeFakeContext()
    {
        var context = new Mock<HttpContextBase>();
        var request = new Mock<HttpRequestBase>();
        var response = new Mock<HttpResponseBase>();
        var session = new Mock<HttpSessionStateBase>();
        var server = new Mock<HttpServerUtilityBase>();
        var user = new Mock<IPrincipal>();
        var identity = new Mock<IIdentity>();

        context.Setup(c=> c.Request).Returns(request.Object);
        context.Setup(c=> c.Response).Returns(response.Object);
        context.Setup(c=> c.Session).Returns(session.Object);
        context.Setup(c=> c.Server).Returns(server.Object);
        context.Setup(c=> c.User).Returns(user.Object);
        user.Setup(c=> c.Identity).Returns(identity.Object);
        identity.Setup(i => i.IsAuthenticated).Returns(true);
        identity.Setup(i => i.Name).Returns("admin");

        return context.Object;
    }


}

And initiating the context like this

FakeHttpContext.SetFakeContext(moController);

And calling the Method in the controller straight forward

long lReportStatusID = -1;
var result = moController.CancelReport(lReportStatusID);

How do I Merge two Arrays in VBA?

I tried the code provided above, but it gave an error 9 for me. I made this code, and it worked fine for my purposes. I hope others find it useful as well.

Function mergeArrays(ByRef arr1() As Variant, arr2() As Variant) As Variant

    Dim returnThis() As Variant
    Dim len1 As Integer, len2 As Integer, lenRe As Integer, counter As Integer
    len1 = UBound(arr1)
    len2 = UBound(arr2)
    lenRe = len1 + len2
    ReDim returnThis(1 To lenRe)
    counter = 1

    Do While counter <= len1 'get first array in returnThis
        returnThis(counter) = arr1(counter)
        counter = counter + 1
    Loop
    Do While counter <= lenRe 'get the second array in returnThis
        returnThis(counter) = arr2(counter - len1)
        counter = counter + 1
    Loop

mergeArrays = returnThis
End Function

android layout with visibility GONE

Done by having it like that:

view = inflater.inflate(R.layout.entry_detail, container, false);
TextView tp1= (TextView) view.findViewById(R.id.tp1);
LinearLayout layone= (LinearLayout) view.findViewById(R.id.layone);
tp1.setVisibility(View.VISIBLE);
layone.setVisibility(View.VISIBLE);

Reactjs convert html string to jsx

There are now safer methods to accomplish this. The docs have been updated with these methods.

Other Methods

  1. Easiest - Use Unicode, save the file as UTF-8 and set the charset to UTF-8.

    <div>{'First · Second'}</div>

  2. Safer - Use the Unicode number for the entity inside a Javascript string.

    <div>{'First \u00b7 Second'}</div>

    or

    <div>{'First ' + String.fromCharCode(183) + ' Second'}</div>

  3. Or a mixed array with strings and JSX elements.

    <div>{['First ', <span>&middot;</span>, ' Second']}</div>

  4. Last Resort - Insert raw HTML using dangerouslySetInnerHTML.

    <div dangerouslySetInnerHTML={{__html: 'First &middot; Second'}} />

Fastest way to determine if record exists

You can also use

 If EXISTS (SELECT 1 FROM dbo.T1 WHERE T1.Name='Scot')
    BEGIN
         --<Do something>
    END 

ELSE    
     BEGIN
       --<Do something>
     END

How to center HTML5 Videos?

I found this page while trying to center align a pair of videos. So, if I enclose both videos in a center div (which I've called central), the margin trick works, but the width is important (2 videos at 400 + padding etc)

<div class=central>
    <video id="vid1" width="400" controls>
        <source src="Carnival01.mp4" type="video/mp4">
    </video> 

    <video id="vid2" width="400" controls>
        <source src="Carnival02.mp4" type="video/mp4">
    </video>
</div>

<style>
div.central { 
  margin: 0 auto;
  width: 880px; <!--this value must be larger than both videos + padding etc-->
}
</style>

Worked for me!

How to export a table dataframe in PySpark to csv?

For Apache Spark 2+, in order to save dataframe into single csv file. Use following command

query.repartition(1).write.csv("cc_out.csv", sep='|')

Here 1 indicate that I need one partition of csv only. you can change it according to your requirements.

Create a directory if it doesn't exist

Use CreateDirectory (char *DirName, SECURITY_ATTRIBUTES Attribs);

If the function succeeds it returns non-zero otherwise NULL.

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

You can either wrap the argument in your own class, or wrap the method call in a method that doesn't need to be passed in the primitive type. Then call that method after your delay, and within that method perform the selector you wish to perform.