Programs & Examples On #Decomposition

How to display an unordered list in two columns?

Modern Browsers

leverage the css3 columns module to support what you are looking for.

http://www.w3schools.com/cssref/css3_pr_columns.asp

CSS:

ul {
  columns: 2;
  -webkit-columns: 2;
  -moz-columns: 2;
}

http://jsfiddle.net/HP85j/8/

Legacy Browsers

Unfortunately for IE support you will need a code solution that involves JavaScript and dom manipulation. This means that anytime the contents of the list changes you will need to perform the operation for reordering the list into columns and reprinting. The solution below uses jQuery for brevity.

http://jsfiddle.net/HP85j/19/

HTML:

<div>
    <ul class="columns" data-columns="2">
        <li>A</li>
        <li>B</li>
        <li>C</li>
        <li>D</li>
        <li>E</li>
        <li>F</li>
        <li>G</li>
    </ul>
</div>

JavaScript:

(function($){
    var initialContainer = $('.columns'),
        columnItems = $('.columns li'),
        columns = null,
        column = 1; // account for initial column
    function updateColumns(){
        column = 0;
        columnItems.each(function(idx, el){
            if (idx !== 0 && idx > (columnItems.length / columns.length) + (column * idx)){
                column += 1;
            }
            $(columns.get(column)).append(el);
        });
    }
    function setupColumns(){
        columnItems.detach();
        while (column++ < initialContainer.data('columns')){
            initialContainer.clone().insertBefore(initialContainer);
            column++;
        }
        columns = $('.columns');
    }

    $(function(){
        setupColumns();
        updateColumns();
    });
})(jQuery);

CSS:

.columns{
    float: left;
    position: relative;
    margin-right: 20px;
}

EDIT:

As pointed out below this will order the columns as follows:

A  E
B  F
C  G
D

while the OP asked for a variant matching the following:

A  B
C  D
E  F
G

To accomplish the variant you simply change the code to the following:

function updateColumns(){
    column = 0;
    columnItems.each(function(idx, el){
        if (column > columns.length){
            column = 0;
        }
        $(columns.get(column)).append(el);
        column += 1;
    });
}

Check if a div does NOT exist with javascript

All these answers do NOT take into account that you asked specifically about a DIV element.

document.querySelector("div#the-div-id")

@see https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

What is a 'workspace' in Visual Studio Code?

Although the question is asking "what is a workspace?", I feel that the source of confusion is the expectation that workspaces should behave more like "projects" in other editors.

So, I to help all the people landing here because of this confusion, I wanted to post the following plugin for VS Code (not mine), "Project Manager": https://marketplace.visualstudio.com/items?itemName=alefragnani.project-manager

It has a nice UI for managing (saving and opening) single-folder projects:

Save Projects:

enter image description here

Open projects with the palette:

enter image description here

See the current project in the status bar (click to open project palette):

enter image description here

Access projects in the sidebar:

enter image description here

Best PHP IDE for Mac? (Preferably free!)

Here's the lowdown on Mac IDE's for PHP

NetBeans Free! Plus, the best functionality of all offerings. Includes inline database connections, code completion, syntax checking, color coding, split views etc. Downside: It's a memory hog on the Mac. Be prepared to allow half a gig of memory then you'll need to shut down and restart.

Komodo A step above a Text Editor. Does not support database connections or split views. Color coding and syntax checking are there to an extent. The project control on Komodo is very unwieldy and strange compared to the other IDEs.

Aptana The perfect solution. Eclipsed based and uses the Aptana PHP plug in. Real time syntax checking, word wrap, drag and drop split views, database connections and a slew of other excellent features. Downside: Not a supported product any more. Aptana Studio 2.0+ uses PDT which is a watered down, under-developed (at present) php plug in.

Zend Studio - Almost identical to Aptana, except no word wrap and you can't change alot of the php configuration on the MAC apparently due to bugs.

Coda Created by Panic, Coda has nice integration with source control and their popular FTP client, transmit. They also have a collaboration feature which is cool for pair-programming.

PhpEd with Parallels or Wine. The best IDE for Windows has all the feature you could need and is worth the effort to pass it through either Parallels or Wine.

Dreamweaver Good for Javascript/HTML/CSS, but only marginal for PHP. There is some color coding, but no syntax checking or code completion native to the package. Database connections are supported, and so are split views.

I'm using NetBeans, which is free, and feature rich. I can deal with the memory issues for a while, but it could be slow coming to the MAC.

Cheers! Korky Kathman Senior Partner Entropy Dynamics, LLC

How do I move files in node.js?

Use the mv node module which will first try to do an fs.rename and then fallback to copying and then unlinking.

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

This error happens because of your Jre version of Eclipse and Tomcat are mismatched ..either change eclipse one to tomcat one or ViceVersa..

Both should be same ..Java version mismatched ..Check it

Padding is invalid and cannot be removed?

I came across this error while attempting to pass an un-encrypted file path to the Decrypt method.The solution was to check if the passed file is encrypted first before attempting to decrypt

if (Sec.IsFileEncrypted(e.File.FullName))
{
    var stream = Sec.Decrypt(e.File.FullName);
} 
else
{
    // non-encrypted scenario  
}

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

How to set tbody height with overflow scroll

Another approach is to wrap your table in a scrollable element and set the header cells to stick to the top.

The advantage of this approach is that you don't have to change the display on tbody and you can leave it to the browser to calculate column width while keeping the header cell widths in line with the data cell column widths.

_x000D_
_x000D_
/* Set a fixed scrollable wrapper */_x000D_
.tableWrap {_x000D_
  height: 200px;_x000D_
  border: 2px solid black;_x000D_
  overflow: auto;_x000D_
}_x000D_
/* Set header to stick to the top of the container. */_x000D_
thead tr th {_x000D_
  position: sticky;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
/* If we use border,_x000D_
we must use table-collapse to avoid_x000D_
a slight movement of the header row */_x000D_
table {_x000D_
 border-collapse: collapse;_x000D_
}_x000D_
_x000D_
/* Because we must set sticky on th,_x000D_
 we have to apply background styles here_x000D_
 rather than on thead */_x000D_
th {_x000D_
  padding: 16px;_x000D_
  padding-left: 15px;_x000D_
  border-left: 1px dotted rgba(200, 209, 224, 0.6);_x000D_
  border-bottom: 1px solid #e8e8e8;_x000D_
  background: #ffc491;_x000D_
  text-align: left;_x000D_
  /* With border-collapse, we must use box-shadow or psuedo elements_x000D_
  for the header borders */_x000D_
  box-shadow: 0px 0px 0 2px #e8e8e8;_x000D_
}_x000D_
_x000D_
/* Basic Demo styling */_x000D_
table {_x000D_
  width: 100%;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
table td {_x000D_
  padding: 16px;_x000D_
}_x000D_
tbody tr {_x000D_
  border-bottom: 2px solid #e8e8e8;_x000D_
}_x000D_
thead {_x000D_
  font-weight: 500;_x000D_
  color: rgba(0, 0, 0, 0.85);_x000D_
}_x000D_
tbody tr:hover {_x000D_
  background: #e6f7ff;_x000D_
}
_x000D_
<div class="tableWrap">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th><span>Month</span></th>_x000D_
        <th>_x000D_
          <span>Event</span>_x000D_
        </th>_x000D_
        <th><span>Action</span></th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>January</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>February. An extra long string.</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>March</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>April</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>May</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>June</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>July</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>August</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>September</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>October</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>November</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>December</td>_x000D_
        <td>AAA</td>_x000D_
        <td><span>Invite | Delete</span></td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why does Git tell me "No such remote 'origin'" when I try to push to origin?

Two problems:

1 - You never told Git to start tracking any file

You write that you ran

git init
git commit -m "first commit"

and that, at that stage, you got

nothing added to commit but untracked files present (use "git add" to track).

Git is telling you that you never told it to start tracking any files in the first place, and it has nothing to take a snapshot of. Therefore, Git creates no commit. Before attempting to commit, you should tell Git (for instance):

Hey Git, you see that README.md file idly sitting in my working directory, there? Could you put it under version control for me? I'd like it to go in my first commit/snapshot/revision...

For that you need to stage the files of interest, using

git add README.md

before running

git commit -m "some descriptive message"

2 - You haven't set up the remote repository

You then ran

git remote add origin https://github.com/VijayNew/NewExample.git

After that, your local repository should be able to communicate with the remote repository that resides at the specified URL (https://github.com/VijayNew/NewExample.git)... provided that remote repo actually exists! However, it seems that you never created that remote repo on GitHub in the first place: at the time of writing this answer, if I try to visit the correponding URL, I get

enter image description here

Before attempting to push to that remote repository, you need to make sure that the latter actually exists. So go to GitHub and create the remote repo in question. Then and only then will you be able to successfully push with

git push -u origin master

Xcode build failure "Undefined symbols for architecture x86_64"

In my case problem was compiled framework architecture.
I'm running Xcode 11 and using Swift 5.1

  • I had 3 target like:
    • MyApp
    • MyAppTests
    • MyAppFrameWork

I was tried to run tests but MyAppFrameWork product was compiled for Generic iOS Devices and the Test target needed an arm x86-64, So I rebuilt Framework for iOS Simulators and test cases successfuly start running.

Remove duplicates in the list using linq

var distinctItems = items.Distinct();

To match on only some of the properties, create a custom equality comparer, e.g.:

class DistinctItemComparer : IEqualityComparer<Item> {

    public bool Equals(Item x, Item y) {
        return x.Id == y.Id &&
            x.Name == y.Name &&
            x.Code == y.Code &&
            x.Price == y.Price;
    }

    public int GetHashCode(Item obj) {
        return obj.Id.GetHashCode() ^
            obj.Name.GetHashCode() ^
            obj.Code.GetHashCode() ^
            obj.Price.GetHashCode();
    }
}

Then use it like this:

var distinctItems = items.Distinct(new DistinctItemComparer());

How to check if "Radiobutton" is checked?

If you need for espresso test the solutions is like this :

onView(withId(id)).check(matches(isChecked()));

Bye,

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

Access a global variable in a PHP function

<?php

    $data = 'My data';

    $menugen = function() use ($data) {

        echo "[ $data ]";
    };

    $menugen();
?>

You can also simplify

echo "[" . $data . "]"

to

echo "[$data]"

Find the most popular element in int[] array

This is the wrong syntax. When you create an anonymous array you MUST NOT give its size.

When you write the following code :

    new int[] {1,23,4,4,5,5,5};

You are here creating an anonymous int array whose size will be determined by the number of values that you provide in the curly braces.

You can assign this a reference as you have done, but this will be the correct syntax for the same :-

    int[] a = new int[]{1,2,3,4,5,6,7,7,7,7};

Now, just Sysout with proper index position:

    System.out.println(a[7]);

C# equivalent of C++ map<string,double>

Dictionary is the most common, but you can use other types of collections, e.g. System.Collections.Generic.SynchronizedKeyedCollection, System.Collections.Hashtable, or any KeyValuePair collection

Procedure or function !!! has too many arguments specified

In addition to all the answers provided so far, another reason for causing this exception can happen when you are saving data from list to database using ADO.Net.

Many developers will mistakenly use for loop or foreach and leave the SqlCommand to execute outside the loop, to avoid that make sure that you have like this code sample for example:

public static void Save(List<myClass> listMyClass)
    {
        using (var Scope = new System.Transactions.TransactionScope())
        {
            if (listMyClass.Count > 0)
            {
                for (int i = 0; i < listMyClass.Count; i++)
                {
                    SqlCommand cmd = new SqlCommand("dbo.SP_SaveChanges", myConnection);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Clear();

                    cmd.Parameters.AddWithValue("@ID", listMyClass[i].ID);
                    cmd.Parameters.AddWithValue("@FirstName", listMyClass[i].FirstName);
                    cmd.Parameters.AddWithValue("@LastName", listMyClass[i].LastName);

                    try
                    {
                        myConnection.Open();
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqe)
                    {
                        throw new Exception(sqe.Message);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        myConnection.Close();
                    }
                }
            }
            else
            {
                throw new Exception("List is empty");
            }

            Scope.Complete();
        }
    }

How to compile multiple java source files in command line

Try the following:

javac file1.java file2.java

What's the difference between subprocess Popen and call (how can I use them)?

The other answer is very complete, but here is a rule of thumb:

  • call is blocking:

    call('notepad.exe')
    print('hello')  # only executed when notepad is closed
    
  • Popen is non-blocking:

    Popen('notepad.exe')
    print('hello')  # immediately executed
    

How to instantiate a javascript class in another js file?

Possible Suggestions to make it work:

Some modifications (U forgot to include a semicolon in the statement this.getName=function(){...} it should be this.getName=function(){...};)

function Customer(){
this.name="Jhon";
this.getName=function(){
return this.name;
};
}

(This might be one of the problem.)

and

Make sure U Link the JS files in the correct order

<script src="file1.js" type="text/javascript"></script>
<script src="file2.js" type="text/javascript"></script>

PHP GuzzleHttp. How to make a post request with params?

Note in Guzzle V6.0+, another source of getting the following error may be incorrect use of JSON as an array:

Passing in the "body" request option as an array to send a POST request has been deprecated. Please use the "form_params" request option to send a application/x-www-form-urlencoded request, or a the "multipart" request option to send a multipart/form-data request.

Incorrect:

$response = $client->post('http://example.com/api', [
    'body' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'json' => [
        'name' => 'Example name',
    ]
])

Correct:

$response = $client->post('http://example.com/api', [
    'headers' => ['Content-Type' => 'application/json'],
    'body' => json_encode([
        'name' => 'Example name',
    ])
])

Hide vertical scrollbar in <select> element

I worked out Arraxas solution to:

  • expand the box to include all elements

  • change background & color on hover

  • get and alert value on click

  • do not keep highlighting selection after clicking

_x000D_
_x000D_
let selElem=document.getElementById('myselect').children[0];_x000D_
selElem.size=selElem.length;_x000D_
selElem.value=-1;_x000D_
_x000D_
selElem.addEventListener('change', e => {_x000D_
  alert(e.target.value);_x000D_
  e.target.value=-1;_x000D_
});
_x000D_
#myselect {_x000D_
  display:inline-block; overflow:hidden; border:solid black 1px;_x000D_
}_x000D_
_x000D_
#myselect > select {_x000D_
  padding:10px; margin:-5px -20px -5px -5px;";_x000D_
}_x000D_
_x000D_
#myselect > select > option:hover {_x000D_
  box-shadow: 0 0 10px 100px #4A8CF7 inset; color: white;_x000D_
}
_x000D_
<div id="myselect">_x000D_
  <select>_x000D_
    <option value="2010">2010</option>_x000D_
    <option value="2011">2011</option>_x000D_
    <option value="2012">2012</option>_x000D_
    <option value="2013">2013</option>_x000D_
    <option value="2014">2014</option>_x000D_
    <option value="2015">2015</option>_x000D_
    <option value="2016">2016</option>_x000D_
   </select>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to loop through Excel files and load them into a database using SSIS package?

Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx

Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\

In the folder path F:\Temp\, create an Excel 2007 spreadsheet file named States_1.xlsx with two worksheets.

Sheet 1 of States_1.xlsx contained the following data

States_1_Sheet_1

Sheet 2 of States_1.xlsx contained the following data

States_1_Sheet_2

In the folder path F:\Temp\, create another Excel 2007 spreadsheet file named States_2.xlsx with two worksheets.

Sheet 1 of States_2.xlsx contained the following data

States_2_Sheet_1

Sheet 2 of States_2.xlsx contained the following data

States_2_Sheet_2

Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.

CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [State] [nvarchar](255) NULL,
    [Country] [nvarchar](255) NULL,
    [FilePath] [nvarchar](255) NULL,
    [SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

The table is currently empty.

Empty table

Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$ to avoid design time error.

Variables

In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.

Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx

ExcelSchema 1

Click on the All section on the left side and set the property Extended Properties to Excel 12.0 to denote the version of Excel. Here in this case 12.0 denotes Excel 2007. Click on the Test Connection to make sure that the connection succeeds.

ExcelSchema 2

Create an Excel connection manager named Excel as shown below.

Excel

Create an OLE DB Connection SQL Server named SQLServer. So, we should have three connections on the package as shown below.

Connections

We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.

On the connection ExcelSchema, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

ExcelSchema ServerName

Similarly on the connection Excel, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

Excel ServerName

On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container named Loop files will loop through the files. The second Foreach Loop container will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL

Control Flow

Configure the first Foreach loop container named Loop files as shown below:

Foreach Loop 1 Collection

Foreach Loop 1 Variable Mappings

Configure the first Foreach loop container named Loop sheets as shown below:

Foreach Loop 2 Collection

Foreach Loop 2 Variable Mappings

Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:

Data Flow Task

Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.

Excel Source Connection Manager

Excel Source Columns

Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.

Derived column

Configure the OLE DB destination to insert the data into the SQL table.

OLE DB Destination Connection Manager

OLE DB Destination Columns

Below screenshot shows successful execution of the package.

Execution successful

Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.

SQL table

Hope that helps.

Bootstrap modal link

Please remove . from your target it should be a id

<a href="#bannerformmodal" data-toggle="modal" data-target="#bannerformmodal">Load me</a>

Also you have to give your modal id like below

<div class="modal fade bannerformmodal" tabindex="-1" role="dialog" aria-labelledby="bannerformmodal" aria-hidden="true" id="bannerformmodal">

Here is the solution in a fiddle.

python date of the previous month

Just for fun, a pure math answer using divmod. Pretty inneficient because of the multiplication, could do just as well a simple check on the number of month (if equal to 12, increase year, etc)

year = today.year
month = today.month

nm = list(divmod(year * 12 + month + 1, 12))
if nm[1] == 0:
    nm[1] = 12
    nm[0] -= 1
pm = list(divmod(year * 12 + month - 1, 12))
if pm[1] == 0:
    pm[1] = 12
    pm[0] -= 1

next_month = nm
previous_month = pm

Validate Dynamically Added Input fields

Try using input arrays:

<form action="try.php" method="post">
    <div id="events_wrapper">
        <div id="sub_events">
            <input type="text" name="firstname[]" />                                       
        </div>
    </div>
    <input type="button" id="add_another_event" name="add_another_event" value="Add Another" />
    <input type="submit" name="submit" value="submit" />
</form>

and add this script and jQuery, using foreach() to retrieve the data being $_POST'ed:

<script>                                                                                    
    $(document).ready(function(){
        $("#add_another_event").click(function(){
        var $address = $('#sub_events');
        var num = $('.clonedAddress').length; // there are 5 children inside each address so the prevCloned address * 5 + original
        var newNum = num + 1;
        var newElem = $address.clone().attr('id', 'address' + newNum).addClass('clonedAddress');

        //set all div id's and the input id's
        newElem.children('div').each (function (i) {
            this.id = 'input' + (newNum*5 + i);
        });

        newElem.find('input').each (function () {
            this.id = this.id + newNum;
            this.name = this.name + newNum;
        });

        if (num > 0) {
            $('.clonedAddress:last').after(newElem);
        } else {
            $address.after(newElem);
        }

        $('#btnDel').removeAttr('disabled');
        });

        $("#remove").click(function(){

        });

    });
</script>

Eclipse jump to closing brace

Place the cursor next to an opening or closing brace and punch Ctrl + Shift + P to find the matching brace. If Eclipse can't find one you'll get a "No matching bracket found" message.

edit: as mentioned by Romaintaz below, you can also get Eclipse to auto-select all of the code between two curly braces simply by double-clicking to the immediate right of a opening brace.

Multiple inputs with same name through POST in php

Eric answer is correct, but the problem is the fields are not grouped. Imagine you have multiple streets and cities which belong together:

<h1>First Address</h1>
<input name="street[]" value="Hauptstr" />
<input name="city[]" value="Berlin"  />

<h2>Second Address</h2>
<input name="street[]" value="Wallstreet" />
<input name="city[]" value="New York" />

The outcome would be

$POST = [ 'street' => [ 'Hauptstr', 'Wallstreet'], 
          'city' => [ 'Berlin' , 'New York'] ];

To group them by address, I would rather recommend to use what Eric also mentioned in the comment section:

<h1>First Address</h1>
<input name="address[1][street]" value="Hauptstr" />
<input name="address[1][city]" value="Berlin"  />

<h2>Second Address</h2>
<input name="address[2][street]" value="Wallstreet" />
<input name="address[2][city]" value="New York" />

The outcome would be

$POST = [ 'address' => [ 
                 1 => ['street' => 'Hauptstr', 'city' => 'Berlin'],
                 2 => ['street' => 'Wallstreet', 'city' => 'New York'],
              ]
        ]

how to open a page in new tab on button click in asp.net?

You could do this on the ASPX HTML front end to make the button go to a new tab to show page in your ASP.NET site dynamically:

        <asp:Button ID="btnNewEntry" CssClass="button"  OnClientClick="window.open('https://website','_blank'); return false;" text="WebsiteName"  runat="server" />

Adding an onclick event to a div element

I think You are using //--style="display:none"--// for hiding the div.

Use this code:

<script>
    function klikaj(i) {
        document.getElementById(i).style.display = 'block';
    }
</script>
<div id="thumb0" class="thumbs" onclick="klikaj('rad1')">Click Me..!</div>
<div id="rad1" class="thumbs" style="display:none">Helloooooo</div>

How can you get the first digit in an int (C#)?

Using all the examples below to get this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace Benfords
{
    class Program
    {
        static int FirstDigit1(int value)
        {
            return Convert.ToInt32(value.ToString().Substring(0, 1));
        }

        static int FirstDigit2(int value)
        {
            while (value >= 10) value /= 10;
            return value;
        }


        static int FirstDigit3(int value)
        {
            return (int)(value.ToString()[0]) - 48;
        }

        static int FirstDigit4(int value)
        {
            return (int)(value / Math.Pow(10, (int)Math.Floor(Math.Log10(value))));
        }

        static int FirstDigit5(int value)
        {
            if (value < 10) return value;
            if (value < 100) return value / 10;
            if (value < 1000) return value / 100;
            if (value < 10000) return value / 1000;
            if (value < 100000) return value / 10000;
            if (value < 1000000) return value / 100000;
            if (value < 10000000) return value / 1000000;
            if (value < 100000000) return value / 10000000;
            if (value < 1000000000) return value / 100000000;
            return value / 1000000000;
        }

        static int FirstDigit6(int value)
        {
            if (value >= 100000000) value /= 100000000;
            if (value >= 10000) value /= 10000;
            if (value >= 100) value /= 100;
            if (value >= 10) value /= 10;
            return value;
        }

        const int mcTests = 1000000;

        static void Main(string[] args)
        {
            Stopwatch lswWatch = new Stopwatch();
            Random lrRandom = new Random();

            int liCounter;

            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit1(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 1, lswWatch.ElapsedTicks);

            lswWatch.Reset();
            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit2(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 2, lswWatch.ElapsedTicks);

            lswWatch.Reset();
            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit3(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 3, lswWatch.ElapsedTicks);

            lswWatch.Reset();
            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit4(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 4, lswWatch.ElapsedTicks);

            lswWatch.Reset();
            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit5(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 5, lswWatch.ElapsedTicks);

            lswWatch.Reset();
            lswWatch.Start();
            for (liCounter = 0; liCounter < mcTests; liCounter++)
                FirstDigit6(lrRandom.Next());
            lswWatch.Stop();
            Console.WriteLine("Test {0} = {1} ticks", 6, lswWatch.ElapsedTicks);

            Console.ReadLine();
        }
    }
}

I get these results on an AMD Ahtlon 64 X2 Dual Core 4200+ (2.2 GHz):

Test 1 = 2352048 ticks
Test 2 = 614550 ticks
Test 3 = 1354784 ticks
Test 4 = 844519 ticks
Test 5 = 150021 ticks
Test 6 = 192303 ticks

But get these on a AMD FX 8350 Eight Core (4.00 GHz)

Test 1 = 3917354 ticks
Test 2 = 811727 ticks
Test 3 = 2187388 ticks
Test 4 = 1790292 ticks
Test 5 = 241150 ticks
Test 6 = 227738 ticks

So whether or not method 5 or 6 is faster depends on the CPU, I can only surmise this is because the branch prediction in the command processor of the CPU is smarter on the new processor, but I'm not really sure.

I dont have any Intel CPUs, maybe someone could test it for us?

Hibernate-sequence doesn't exist

When you use

@GeneratedValue(strategy=GenerationType.AUTO)

or

@GeneratedValue which is short hand way of the above, Hibernate starts to decide the best generation strategy for you, in this case it has selected

GenerationType.SEQUENCE as the strategy and that is why it is looking for

schemaName.hibernate_sequence which is a table, for sequence based id generation.

When you use GenerationType.SEQUENCE as the strategy you need to provide the @TableGenerator as follows.

     @Id
     @GeneratedValue(strategy = GenerationType.TABLE, generator = "user_table_generator")
     @TableGenerator(name = "user_table_generator",
                table = "user_keys", pkColumnName = "PK_NAME", valueColumnName = "PK_VALUE")
     @Column(name = "USER_ID")
     private long userId;

When you set the strategy it the to

@GeneratedValue(strategy = GenerationType.IDENTITY) .

original issue get resolved because then Hibernate stop looking for sequence table.

Problem with converting int to string in Linq to entities

My understanding is that you have to create a partial class to "extend" your model and add a property that is readonly that can utilize the rest of the class's properties.

public partial class Contact{

   public string ContactIdString
   {
      get{ 
            return this.ContactId.ToString();
      }
   } 
}

Then

var items = from c in contacts
select new ListItem
{
    Value = c.ContactIdString, 
    Text = c.Name
};

Using std::max_element on a vector<double>

min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:

cLower = *min_element(C.begin(), C.end());

How to force a UIViewController to Portrait orientation in iOS 6

Just go to project.plist then add Supported interface orientation and then add only Portrait (bottom home button) and Portrait (top home button).

You can add or remove there orientation as per your project requirement .

Thanks

Angular 2 - Setting selected value on dropdown list

If your values are coming from the database, show selected values in that way.

<div class="form-group">
    <label for="status">Status</label>
    <select class="form-control" name="status" [(ngModel)]="category.status">
       <option [value]="1" [selected]="category.status ==1">Active</option>
       <option [value]="0" [selected]="category.status ==0">In Active</option>
    </select>
</div>

Get Selected value from dropdown using JavaScript

Try

var e = document.getElementById("mySelect");
var selectedOp = e.options[e.selectedIndex].text;

ListAGG in SQLSERVER

MySQL

SELECT FieldA
     , GROUP_CONCAT(FieldB ORDER BY FieldB SEPARATOR ',') AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

Oracle & DB2

SELECT FieldA
     , LISTAGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

PostgreSQL

SELECT FieldA
     , STRING_AGG(FieldB, ',' ORDER BY FieldB) AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

SQL Server

SQL Server ≥ 2017 & Azure SQL

SELECT FieldA
     , STRING_AGG(FieldB, ',') WITHIN GROUP (ORDER BY FieldB) AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

SQL Server ≤ 2016 (CTE included to encourage the DRY principle)

  WITH CTE_TableName AS (
       SELECT FieldA, FieldB
         FROM TableName)
SELECT t0.FieldA
     , STUFF((
       SELECT ',' + t1.FieldB
         FROM CTE_TableName t1
        WHERE t1.FieldA = t0.FieldA
        ORDER BY t1.FieldB
          FOR XML PATH('')), 1, LEN(','), '') AS FieldBs
  FROM CTE_TableName t0
 GROUP BY t0.FieldA
 ORDER BY FieldA;

SQLite

Ordering requires a CTE or subquery

  WITH CTE_TableName AS (
       SELECT FieldA, FieldB
         FROM TableName
        ORDER BY FieldA, FieldB)
SELECT FieldA
     , GROUP_CONCAT(FieldB, ',') AS FieldBs
  FROM CTE_TableName
 GROUP BY FieldA
 ORDER BY FieldA;

Without ordering

SELECT FieldA
     , GROUP_CONCAT(FieldB, ',') AS FieldBs
  FROM TableName
 GROUP BY FieldA
 ORDER BY FieldA;

Artificially create a connection timeout error

There are a couple of tactics I've used in the past to simulate networking issues;

  1. Pull out the network cable
  2. Switch off the switch (ideally with the switch that the computer is plugged into still being powered so the machine maintains it's "network connection") between your machine and the "target" machine
  3. Run firewall software on the target machine that silently drops received data

One of these ideas might give you some means of artifically generating the scenario you need

Getting year in moment.js

_x000D_
_x000D_
var year1 = moment().format('YYYY');_x000D_
var year2 = moment().year();_x000D_
_x000D_
console.log('using format("YYYY") : ',year1);_x000D_
console.log('using year(): ',year2);_x000D_
_x000D_
// using javascript _x000D_
_x000D_
var year3 = new Date().getFullYear();_x000D_
console.log('using javascript :',year3);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Parsing json and searching through it

Seems there's a typo (missing colon) in the JSON dict provided by jro.

The correct syntax would be:

jdata = json.load('{"uri": "http:", "foo": "bar"}')

This cleared it up for me when playing with the code.

GDB: break if variable equal value

in addition to a watchpoint nested inside a breakpoint you can also set a single breakpoint on the 'filename:line_number' and use a condition. I find it sometimes easier.

(gdb) break iter.c:6 if i == 5
Breakpoint 2 at 0x4004dc: file iter.c, line 6.
(gdb) c
Continuing.
0
1
2
3
4

Breakpoint 2, main () at iter.c:6
6           printf("%d\n", i);

If like me you get tired of line numbers changing, you can add a label then set the breakpoint on the label like so:

#include <stdio.h>
main()
{ 
     int i = 0;
     for(i=0;i<7;++i) {
       looping:
        printf("%d\n", i);
     }
     return 0;
}

(gdb) break main:looping if i == 5

What's the most efficient way to check if a record exists in Oracle?

select count(1) into existence 
   from sales where sales_type = 'Accessories' and rownum=1;

Oracle plan says that it costs 1 if seles_type column is indexed.

Multiple conditions in WHILE loop

If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

ng-change not working on a text input

I've got the same issue, my model is binding from another form, I've added ng-change and ng-model and it still doesn't work:

<input type="hidden" id="pdf-url" class="form-control" ng-model="pdfUrl"/>

<ng-dropzone
  dropzone="dropzone"
  dropzone-config="dropzoneButtonCfg"
  model="pdfUrl">
</ng-dropzone>

An input #pdf-url gets data from dropzone (two ways binding), however, ng-change doesn't work in this case. $scope.$watch is a solution for me:

$scope.$watch('pdfUrl', function updatePdfUrl(newPdfUrl, oldPdfUrl) {
  if (newPdfUrl !== oldPdfUrl) {
    // It's updated - Do something you want here.
  }
});

Hope this help.

SQL: Two select statements in one query

You can do something like this:

 (SELECT
    name, games, goals
    FROM tblMadrid WHERE name = 'ronaldo')
 UNION
 (SELECT
    name, games, goals
    FROM tblBarcelona WHERE name = 'messi')
ORDER BY goals;

See, for example: https://dev.mysql.com/doc/refman/5.0/en/union.html

Vertical Menu in Bootstrap

here is vertical menu base on Bootstrap http://www.okvee.net/articles/okvee-bootstrap-sidebar-menu it is also support responsive design.

How to call one shell script from another shell script?

Check this out.

#!/bin/bash
echo "This script is about to run another script."
sh ./script.sh
echo "This script has just run another script."

LINQ Group By into a Dictionary Object

I cannot comment on @Michael Blackburn, but I guess you got the downvote because the GroupBy is not necessary in this case.

Use it like:

var lookupOfCustomObjects = listOfCustomObjects.ToLookup(o=>o.PropertyName);
var listWithAllCustomObjectsWithPropertyName = lookupOfCustomObjects[propertyName]

Additionally, I've seen this perform way better than when using GroupBy().ToDictionary().

How can I make my own event in C#?

to do it we have to know the three components

  1. the place responsible for firing the Event
  2. the place responsible for responding to the Event
  3. the Event itself

    a. Event

    b .EventArgs

    c. EventArgs enumeration

now lets create Event that fired when a function is called

but I my order of solving this problem like this: I'm using the class before I create it

  1. the place responsible for responding to the Event

    NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) 
    {
            // when the Event Happened I want to Update the UI
            // this is WPF Window (WPF Project)  
            this.Dispatcher.Invoke(() =>
            {
                LabelFileName.Content = args.ItemUri;
                LabelOperation.Content = args.Operation;
                LabelStatus.Content = args.Status;
            });
    };
    

NetLog is a static class I will Explain it later

the next step is

  1. the place responsible for firing the Event

    //this is the sender object, MessageEventArgs Is a class I want to create it  and Operation and Status are Event enums
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
    downloadFile = service.DownloadFile(item.Uri);
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
    

the third step

  1. the Event itself

I warped The Event within a class called NetLog

public sealed class NetLog
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs args);

    public static event MessageEventHandler OnMessageFired;
    public static void FireMessage(Object obj,MessageEventArgs eventArgs)
    {
        if (OnMessageFired != null)
        {
            OnMessageFired(obj, eventArgs);
        }
    }
}

public class MessageEventArgs : EventArgs
{
    public string ItemUri { get; private set; }
    public Operation Operation { get; private set; }
    public Status Status { get; private set; }

    public MessageEventArgs(string itemUri, Operation operation, Status status)
    {
        ItemUri = itemUri;
        Operation = operation;
        Status = status;
    }
}

public enum Operation
{
    Upload,Download
}

public enum Status
{
    Started,Finished
}

this class now contain the Event, EventArgs and EventArgs Enums and the function responsible for firing the event

sorry for this long answer

How to force addition instead of concatenation in javascript

The following statement appends the value to the element with the id of response

$('#response').append(total);

This makes it look like you are concatenating the strings, but you aren't, you're actually appending them to the element

change that to

$('#response').text(total);

You need to change the drop event so that it replaces the value of the element with the total, you also need to keep track of what the total is, I suggest something like the following

$(function() {
    var data = [];
    var total = 0;

    $( "#draggable1" ).draggable();
    $( "#draggable2" ).draggable();
    $( "#draggable3" ).draggable();

    $("#droppable_box").droppable({
        drop: function(event, ui) {
        var currentId = $(ui.draggable).attr('id');
        data.push($(ui.draggable).attr('id'));

        if(currentId == "draggable1"){
            var myInt1 = parseFloat($('#MealplanCalsPerServing1').val());
        }
        if(currentId == "draggable2"){
            var myInt2 = parseFloat($('#MealplanCalsPerServing2').val());
        }
        if(currentId == "draggable3"){
            var myInt3 = parseFloat($('#MealplanCalsPerServing3').val());
        }
        if ( typeof myInt1 === 'undefined' || !myInt1 ) {
            myInt1 = parseInt(0);
        }
        if ( typeof myInt2 === 'undefined' || !myInt2){
            myInt2 = parseInt(0);
        }
        if ( typeof myInt3 === 'undefined' || !myInt3){
        myInt3 = parseInt(0);
        }
        total += parseFloat(myInt1 + myInt2 + myInt3);
        $('#response').text(total);
        }
    });

    $('#myId').click(function(event) {
        $.post("process.php", ({ id: data }), function(return_data, status) {
            alert(data);
            //alert(total);
        });
    });
});

I moved the var total = 0; statement out of the drop event and changed the assignment statment from this

total = parseFloat(myInt1 + myInt2 + myInt3);

to this

total += parseFloat(myInt1 + myInt2 + myInt3);

Here is a working example http://jsfiddle.net/axrwkr/RCzGn/

Copying a local file from Windows to a remote server using scp

Drive letter can be used in the source like

scp /c/path/to/file.txt user@server:/dir1/file.txt

Check if XML Element exists

Following is a simple function to check if a particular node is present or not in the xml file.

public boolean envParamExists(String xmlFilePath, String paramName){
    try{
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(xmlFilePath));
        doc.getDocumentElement().normalize();
        if(doc.getElementsByTagName(paramName).getLength()>0)
            return true;
        else
            return false;
    }catch (Exception e) {
        //error handling
    }
    return false;
}

CodeIgniter - How to return Json response from controller

return $this->output
            ->set_content_type('application/json')
            ->set_status_header(500)
            ->set_output(json_encode(array(
                    'text' => 'Error 500',
                    'type' => 'danger'
            )));

Oracle - Best SELECT statement for getting the difference in minutes between two DateTime columns?

SELECT date1 - date2
  FROM some_table

returns a difference in days. Multiply by 24 to get a difference in hours and 24*60 to get minutes. So

SELECT (date1 - date2) * 24 * 60 difference_in_minutes
  FROM some_table

should be what you're looking for

Importing larger sql files into MySQL

Use this from mysql command window:

mysql> use db_name;
mysql> source backup-file.sql;

How can I select item with class within a DIV?

You'll do it the same way you would apply a css selector. For instanse you can do

$("#mydiv > .myclass")

or

$("#mydiv .myclass")

The last one will match every myclass inside myDiv, including myclass inside myclass.

Redirect echo output in shell script to logfile

You can easily redirect different parts of your shell script to a file (or several files) using sub-shells:

{
  command1
  command2
  command3
  command4
} > file1
{
  command5
  command6
  command7
  command8
} > file2

Best way to get user GPS location in background in Android

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.hardware.GeomagneticField;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.widget.Toast;


public class LocationService extends Service {
    private static final int MINUTES = 1000 * 60 * 2;
    public LocationManager locationManager;
    public MyLocationListener listener;
    public Location previousBestLocation = null;
    Context mContext;
    private boolean isGpsEnabled = false;
    private boolean isNetworkEnabled = false;

    private GeomagneticField geoField;
    private double latitude = 0.0;
    private double longitude = 0.0;


    @Override
    public void onCreate() {
        super.onCreate();
        mContext = getApplicationContext();
        if (locationManager == null) {
            locationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE);
        }
        getCurrentLocation();
    }

    private void getCurrentLocation() {
        try {
            assert locationManager != null;
            isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
            isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (!isGpsEnabled && !isNetworkEnabled) {
            showSettingsAlert();
        }
        listener = new MyLocationListener();

        try {
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 0, listener);
            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000, 0, listener);
        } catch (SecurityException e) {
            e.printStackTrace();
        }
    }

    private void showSettingsAlert() {
        Toast.makeText(mContext, "GPS is disabled in your device. Please Enable it ?", Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mContext.startActivity(intent);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    protected boolean isBetterLocation(Location location, Location currentBestLocation) {
        if (currentBestLocation == null) {
            return true;
        }
        long timeDelta = location.getTime() - currentBestLocation.getTime();
        boolean isSignificantlyNewer = timeDelta > MINUTES;
        boolean isSignificantlyOlder = timeDelta < -MINUTES;
        boolean isNewer = timeDelta > 0;

        if (isSignificantlyNewer) {
            return true;
        } else if (isSignificantlyOlder) {
            return false;
        }

        int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
        boolean isLessAccurate = accuracyDelta > 0;
        boolean isMoreAccurate = accuracyDelta < 0;
        boolean isSignificantlyLessAccurate = accuracyDelta > 200;
        boolean isFromSameProvider = isSameProvider(location.getProvider(), currentBestLocation.getProvider());
        if (isMoreAccurate) {
            return true;
        } else if (isNewer && !isLessAccurate) {
            return true;
        } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
            return true;
        }
        return false;
    }


    private boolean isSameProvider(String provider1, String provider2) {
        if (provider1 == null) {
            return provider2 == null;
        }
        return provider1.equals(provider2);
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        locationManager.removeUpdates(listener);
    }

    private void setupFinalLocationData(Location mLocation) {
        if (mLocation != null) {
            geoField = new GeomagneticField(
                    Double.valueOf(mLocation.getLatitude()).floatValue(),
                    Double.valueOf(mLocation.getLongitude()).floatValue(),
                    Double.valueOf(mLocation.getAltitude()).floatValue(),
                    System.currentTimeMillis()
            );

            latitude = mLocation.getLatitude();
            longitude = mLocation.getLongitude();
            //Update latitude and longtitude in SharedPreference...
        }
    }

    public class MyLocationListener implements LocationListener {
        public void onLocationChanged(final Location loc) {
            if (isBetterLocation(loc, previousBestLocation)) {
                setupFinalLocationData(loc);
            }
        }

        public void onProviderDisabled(String provider) {
        }

        public void onProviderEnabled(String provider) {
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
    }
}

Make virtualenv inherit specific packages from your global site-packages

Create the environment with virtualenv --system-site-packages . Then, activate the virtualenv and when you want things installed in the virtualenv rather than the system python, use pip install --ignore-installed or pip install -I . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.

How to determine if Javascript array contains an object with an attribute that equals a given value?

Correct me if i'm wrong.. i could have used forEach method like this,

var found=false;
vendors.forEach(function(item){
   if(item.name === "name"){
       found=true;

   }
});

Nowadays i'm used to it ,because of it simplicity and self explanatory word. Thank you.

Resolve Javascript Promise outside function scope

Just another solution to resolve Promise from the outside

 class Lock {
        #lock;  // Promise to be resolved (on  release)
        release;  // Release lock
        id;  // Id of lock
        constructor(id) {
            this.id = id
            this.#lock = new Promise((resolve) => {
                this.release = () => {
                    if (resolve) {
                        resolve()
                    } else {
                        Promise.resolve()
                    }
                }
            })
        }
        get() { return this.#lock }
    }

Usage

let lock = new Lock(... some id ...);
...
lock.get().then(()=>{console.log('resolved/released')})
lock.release()  // Excpected 'resolved/released'

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

Whenever you will face below error just follow it.

org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here at org.springframework.orm.hibernate3.SpringSessionContext.currentSession(SpringSessionContext.java:63)

Put a @Transactional annotation for each method of implementing classes.

What is the difference between a Relational and Non-Relational Database?

The relational database uses a formal system of predicates to address data. The underlying physical implementation is of no substance and can vary to optimize for certain operations, but it must always assume the relational model. In layman's terms, that's just saying I know exactly how many values (attributes) each row (tuple) in my table (relation) has and now I want to exploit the fact accordingly, thoroughly and to it's extreme. That's the true nature of the beast. 

Since we're obviously the generation that has had a relational upbringing, if you look at NoSQL database models from the perspective of the relational model, again in layman's terms, the first obvious difference is that no assumptions about the number of values a row can contain is ever made. This is really oversimplifying the matter and does not cleanly apply to the intricacies of the physical models of every NoSQL database, but it's the pinnacle of the relational model and the first assumption we have to leave behind or, if you'd rather, the biggest leap we have to make.

We can agree to two things that are true for every DBMS: it can store any kind of data and has enough mathematical underpinnings to make it possible to manage the data in any way imaginable. The reality is that you'll never want to make the mistake of putting any of the two points to the test, but rather just stick with what the actual DBMS was really made for. In layman's terms: respect the beast within!

(Please note that I've avoided comparing the (obviously) well founded standards revolving around the relational model against the many flavors provided by NoSQL databases. If you'd like, consider NoSQL databases as an umbrella term for any DBMS that does not completely assume the relational model, in exclusion to everything else. The differences are too many, but that's the principal difference and the one I think would be of most use to you to understand the two.)

Error: 0xC0202009 at Data Flow Task, OLE DB Destination [43]: SSIS Error Code DTS_E_OLEDBERROR. An OLE DB error has occurred. Error code: 0x80040E21

In my case the underlying system account through which the package was running was locked out. Once we got the system account unlocked and reran the package, it executed successfully. The developer said that he got to know of this while debugging wherein he directly tried to connect to the server and check the status of the connection.

How do I convert ticks to minutes?

TimeSpan.FromTicks(28000000000).TotalMinutes;

initialize a const array in a class initializer in C++

interestingly, in C# you have the keyword const that translates to C++'s static const, as opposed to readonly which can be only set at constructors and initializations, even by non-constants, ex:

readonly DateTime a = DateTime.Now;

I agree, if you have a const pre-defined array you might as well make it static. At that point you can use this interesting syntax:

//in header file
class a{
    static const int SIZE;
    static const char array[][10];
};
//in cpp file:
const int a::SIZE = 5;
const char array[SIZE][10] = {"hello", "cruel","world","goodbye", "!"};

however, I did not find a way around the constant '10'. The reason is clear though, it needs it to know how to perform accessing to the array. A possible alternative is to use #define, but I dislike that method and I #undef at the end of the header, with a comment to edit there at CPP as well in case if a change.

T-SQL Format integer to 2-digit string

SELECT
replace(str(month(DATEADD(month, -1, '2012-02-29')), 2),' ' , '0')

Can I use a binary literal in C or C++?

The smallest unit you can work with is a byte (which is of char type). You can work with bits though by using bitwise operators.

As for integer literals, you can only work with decimal (base 10), octal (base 8) or hexadecimal (base 16) numbers. There are no binary (base 2) literals in C nor C++.

Octal numbers are prefixed with 0 and hexadecimal numbers are prefixed with 0x. Decimal numbers have no prefix.

In C++0x you'll be able to do what you want by the way via user defined literals.

Can I use tcpdump to get HTTP requests, response header and response body?

I would recommend using Wireshark, which has a "Follow TCP Stream" option that makes it very easy to see the full requests and responses for a particular TCP connection. If you would prefer to use the command line, you can try tcpflow, a tool dedicated to capturing and reconstructing the contents of TCP streams.

Other options would be using an HTTP debugging proxy, like Charles or Fiddler as EricLaw suggests. These have the advantage of having specific support for HTTP to make it easier to deal with various sorts of encodings, and other features like saving requests to replay them or editing requests.

You could also use a tool like Firebug (Firefox), Web Inspector (Safari, Chrome, and other WebKit-based browsers), or Opera Dragonfly, all of which provide some ability to view the request and response headers and bodies (though most of them don't allow you to see the exact byte stream, but instead how the browsers parsed the requests).

And finally, you can always construct requests by hand, using something like telnet, netcat, or socat to connect to port 80 and type the request in manually, or a tool like htty to help easily construct a request and inspect the response.

JavaScript pattern for multiple constructors

Going further with eruciform's answer, you can chain your new call into your init method.

function Foo () {
    this.bar = 'baz';
}

Foo.prototype.init_1 = function (bar) {
    this.bar = bar;
    return this;
};

Foo.prototype.init_2 = function (baz) {
    this.bar = 'something to do with '+baz;
    return this;
};

var a = new Foo().init_1('constructor 1');
var b = new Foo().init_2('constructor 2');

ImportError: No module named _ssl

Since --with-ssl is not recognized anymore I just installed the libssl-dev. For debian based systems:

sudo apt-get install libssl-dev 

For CentOS and RHEL

sudo yum install openssl-devel

To restart the make first clean up by:

make clean

Then start again and execute the following commands one after the other:

./configure
make
make test
make install

For further information on OpenSSL visit the Ubuntu Help Page on OpenSSL.

What is the difference between localStorage, sessionStorage, session and cookies?

The Web Storage API provides mechanisms by which browsers can securely store key/value pairs, in a much more intuitive fashion than using cookies. The Web Storage API extends the Window object with two new properties — Window.sessionStorage and Window.localStorage. — invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorage and localStorage for each origin (domain).

Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads.

localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting', '#a4509b');

The keys and the values are always strings. To store any type convert it to String and then store it. It's always recommended to use Storage interface methods.

var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('Converting String to Object: ', JSON.parse(retrievedObject));

The two mechanisms within Web Storage are as follows:

  • sessionStorage maintains a separate storage area for each given originSame-origin policy that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
  • localStorage does the same thing, but persists even when the browser is closed and reopened.

Storage « Local storage writes the data to the disk, while session storage writes the data to the memory only. Any data written to the session storage is purged when your app exits.

The maximum storage available is different per browser, but most browsers have implemented at least the w3c recommended maximum storage limit of 5MB.

+----------------+--------+---------+-----------+--------+
|                | Chrome | Firefox | Safari    |  IE    |
+----------------+--------+---------+-----------+--------+
| LocalStorage   | 10MB   | 10MB    | 5MB       | 10MB   |
+----------------+--------+---------+-----------+--------+
| SessionStorage | 10MB   | 10MB    | Unlimited | 10MB   |
+----------------+--------+---------+-----------+--------+

Always catch LocalStorage security and quota exceeded errors

StorageEvent « The storage event is fired on a document's Window object when a storage area changes. When a user agent is to send a storage notification for a Document, the user agent must queue a task to fire an event named storage at the Document object's Window object, using StorageEvent.

Note: For a real world example, see Web Storage Demo. check out the source code

Listen to the storage event on dom/Window to catch changes in the storage. fiddle.


Cookies (web cookie, browser cookie) Cookies are data, stored in small text files as name-value pairs, on your computer.

JavaScript access using Document.cookie

New cookies can also be created via JavaScript using the Document.cookie property, and if the HttpOnly flag is not set, existing cookies can be accessed from JavaScript as well.

document.cookie = "yummy_cookie=choco"; 
document.cookie = "tasty_cookie=strawberry"; 
console.log(document.cookie); 
// logs "yummy_cookie=choco; tasty_cookie=strawberry"

Secure and HttpOnly cookies HTTP State Management Mechanism

Cookies are often used in web application to identify a user and their authenticated session

When receiving an HTTP request, a server can send a Set-Cookie header with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header.

Set-Cookie: <cookie-name>=<cookie-value> 
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>

Session cookies will get removed when the client is shut down. They don't specify the Expires or Max-Age directives.

Set-Cookie: sessionid=38afes7a8; HttpOnly; Path=/

Permanent cookies expire at a specific date (Expires) or after a specific length of time (Max-Age).

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly

The Cookie HTTP request header contains stored HTTP cookies previously sent by the server with the Set-Cookie header. HTTP-only cookies aren't accessible via JavaScript through the Document.cookie property, the XMLHttpRequest and Request APIs to mitigate attacks against cross-site scripting (XSS).

Cookies are mainly used for three purposes:

  • Session management « Logins, shopping carts, game scores, or anything else the server should remember
  • Personalization « User preferences, themes, and other settings
  • Tracking (Recording and analyzing user behavior) « Cookies have a domain associated to them. If this domain is the same as the domain of the page you are on, the cookies is said to be a first-party cookie. If the domain is different, it is said to be a third-party cookie. While first-party cookies are sent only to the server setting them, a web page may contain images or other components stored on servers in other domains (like ad banners). Cookies that are sent through these third-party components are called third-party cookies and are mainly used for advertising and tracking across the web.

Cookies were invented to solve the problem "how to remember information about the user":

  • When a user visits a web page, his name can be stored in a cookie.
  • Next time the user visits the page, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

GitHubGist Example


As summary,

  • localStorage persists over different tabs or windows, and even if we close the browser, accordingly with the domain security policy and user choices about quota limit.
  • sessionStorage object does not persist if we close the tab (top-level browsing context) as it does not exists if we surf via another tab or window.
  • Web Storage (session, local) allows us to save a large amount of key/value pairs and lots of text, something impossible to do via cookie.
  • Cookies that are used for sensitive actions should have a short lifetime only.
  • Cookies mainly used for advertising and tracking across the web. See for example the types of cookies used by Google.
  • Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web storage API (localStorage and sessionStorage) and IndexedDB.

Transfer data between databases with PostgreSQL

From: hxxp://dbaspot.c om/postgresql/348627-pg_dump-t-give-where-condition.html (NOTE: the link is now broken)

# create temp table with the data
psql mydb
CREATE TABLE temp1 (LIKE mytable);
INSERT INTO temp1 SELECT * FROM mytable WHERE myconditions;
\q

# export the data to a sql file
pg_dump --data-only --column-inserts -t temp1 mtdb > out.sql
psql mydb
DROP TABLE temp1;
\q

# import temp1 rows in another database
cat out.sql | psql -d [other_db]
psql other_db
INSERT INTO mytable (SELECT * FROM temp1);
DROP TABLE temp1;

Another method useful in remotes

  # export a table csv and import in another database
  psql-remote> COPY elements TO '/tmp/elements.csv' DELIMITER ',' CSV HEADER;
  $ scp host.com:/tmp/elements.csv /tmp/elements.csv
  psql-local> COPY elements FROM '/tmp/elements.csv' DELIMITER ',' CSV;

Accurate way to measure execution times of php scripts

$start = microtime(true);
for ($i = 0; $i < 10000; ++$i) {
    // do something
}
$total = microtime(true) - $start;
echo $total;

How to check if a user likes my Facebook Page or URL using Facebook's API

I tore my hair out over this one too. Your code only works if the user has granted an extended permission for that which is not ideal.

Here's another approach.

In a nutshell, if you turn on the OAuth 2.0 for Canvas advanced option, Facebook will send a $_REQUEST['signed_request'] along with every page requested within your tab app. If you parse that signed_request you can get some info about the user including if they've liked the page or not.

function parsePageSignedRequest() {
    if (isset($_REQUEST['signed_request'])) {
      $encoded_sig = null;
      $payload = null;
      list($encoded_sig, $payload) = explode('.', $_REQUEST['signed_request'], 2);
      $sig = base64_decode(strtr($encoded_sig, '-_', '+/'));
      $data = json_decode(base64_decode(strtr($payload, '-_', '+/'), true));
      return $data;
    }
    return false;
  }
  if($signed_request = parsePageSignedRequest()) {
    if($signed_request->page->liked) {
      echo "This content is for Fans only!";
    } else {
      echo "Please click on the Like button to view this tab!";
    }
  }

How to create json by JavaScript for loop?

If you want a single JavaScript object such as the following:

{ uniqueIDofSelect: "uniqueID", optionValue: "2" }

(where option 2, "Absent", is the current selection) then the following code should produce it:

  var jsObj = null;
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsObj = { uniqueIDofSelect: status.id, optionValue: options[i].value };
        break;
     }
  }

If you want an array of all such objects (not just the selected one), use michael's code but swap out status.options[i].text for status.id.

If you want a string that contains a JSON representation of the selected object, use this instead:

  var jsonStr = "";
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsonStr = '{ '
                  + '"uniqueIDofSelect" : '
                  + '"' + status.id + '"'
                  + ", "
                  + '"optionValue" : '
                  + '"'+ options[i].value + '"'
                  + ' }';
        break;
     }
  }

How to fix "unable to write 'random state' " in openssl

just enter this line in the command line :

set RANDFILE=.rnd

An error occurred while collecting items to be installed (Access is denied)

None of the above worked for me.

Instead, I tried installing the plugins I needed via the Eclipse Market Place, and that worked without issue.

  1. Click "Help" Menu.
  2. Click "Eclipse Marketplace..." menu item.
  3. Enter the name of the plugin you want.
  4. Click "Install" when the plugin appears in the Marketplace List.
  5. Restart Eclipse.

How to setup virtual environment for Python in VS Code?

  1. If your using vs code on mac, it's important to have your venv installed in the same directory as your workspace.

  2. In my case my venv was in a different directory( not in my project workspace) so a simple cut/copy-paste of my venv to the project workspace did the trick.

  3. As soon as your venv is copied to the project workspace, your vs code will pick that up and show a notification giving you an option to select venv as an interpreter.

Can I change the color of Font Awesome's icon color?

For me the only thing that worked is inline css + overriding

<i class="fas fa-ellipsis-v fa-2x" style="color:red !important"></i>

Securely storing passwords for use in python script

Know the master key yourself. Don't hard code it.

Use py-bcrypt (bcrypt), powerful hashing technique to generate a password yourself.

Basically you can do this (an idea...)

import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)

save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.

This is basically how login should work these days.

Difference between Eclipse Europa, Helios, Galileo

The Eclipse releases are named after the moons of Jupiter, and each denotes a successive release.

Helios is the current release you can download eclipse as your programming needs http://www.eclipse.org/downloads/

Scaling an image to fit on canvas

Provide the source image (img) size as the first rectangle:

ctx.drawImage(img, 0, 0, img.width,    img.height,     // source rectangle
                   0, 0, canvas.width, canvas.height); // destination rectangle

The second rectangle will be the destination size (what source rectangle will be scaled to).

Update 2016/6: For aspect ratio and positioning (ala CSS' "cover" method), check out:
Simulation background-size: cover in canvas

Java : Cannot format given Object as a Date

DateFormat.format only works on Date values.

You should use two SimpleDateFormat objects: one for parsing, and one for formatting. For example:

// Note, MM is months, not mm
DateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US);
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);

String inputText = "2012-11-17T00:00:00.000-05:00";
Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);

EDIT: Note that you may well want to specify the time zone and/or locale in your formats, and you should also consider using Joda Time instead of all of this to start with - it's a much better date/time API.

Convert HTML5 into standalone Android App

You could use PhoneGap.

http://phonegap.com/

http://docs.phonegap.com/en/2.1.0/guide_getting-started_android_index.md.html#Getting%20Started%20with%20Android

This has the benefit of being a cross-platform solution. Be warned though that you may need to pay subscription fees. The simplest solution is to just embed a WebView as detailed in @Enigma's answer.

"make clean" results in "No rule to make target `clean'"

I suppose you have figured it out by now. The answer is hidden in your first mail itself.

The make command by default looks for makefile, Makefile, and GNUMakefile as the input file and you are having Makefile.txt in your folder. Just remove the file extension (.txt) and it should work.

How can I rename a field for all documents in MongoDB?

If you are using MongoMapper, this works:

Access.collection.update( {}, { '$rename' => { 'location' => 'location_info' } }, :multi => true )

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

Are you running Android M? If so, this is because it's not enough to declare permissions in the manifest. For some permissions, you have to explicitly ask user in the runtime: http://developer.android.com/training/permissions/requesting.html

How do you grep a file and get the next 5 lines

Here is a sed solution:

sed '/19:55/{
N
N
N
N
N
s/\n/ /g
}' file.txt

What is the best way to test for an empty string with jquery-out-of-the-box?

Based on David's answer I personally like to check the given object first if it is a string at all. Otherwise calling .trim() on a not existing object would throw an exception:

function isEmpty(value) {
  return typeof value == 'string' && !value.trim() || typeof value == 'undefined' || value === null;
}

Usage:

isEmpty(undefined); // true
isEmpty(null); // true
isEmpty(''); // true
isEmpty('foo'); // false
isEmpty(1); // false
isEmpty(0); // false

Most efficient way to reverse a numpy array

Expanding on what others have said I will give a short example.

If you have a 1D array ...

>>> import numpy as np
>>> x = np.arange(4) # array([0, 1, 2, 3])
>>> x[::-1] # returns a view
Out[1]: 
array([3, 2, 1, 0])

But if you are working with a 2D array ...

>>> x = np.arange(10).reshape(2, 5)
>>> x
Out[2]:
array([[0, 1, 2, 3, 4],
       [5, 6, 7, 8, 9]])

>>> x[::-1] # returns a view:
Out[3]: array([[5, 6, 7, 8, 9],
               [0, 1, 2, 3, 4]])

This does not actually reverse the Matrix.

Should use np.flip to actually reverse the elements

>>> np.flip(x)
Out[4]: array([[9, 8, 7, 6, 5],
               [4, 3, 2, 1, 0]])

If you want to print the elements of a matrix one-by-one use flat along with flip

>>> for el in np.flip(x).flat:
>>>     print(el, end = ' ')
9 8 7 6 5 4 3 2 1 0

How to print multiple variable lines in Java

You can do it with 1 printf:

System.out.printf("First Name: %s\nLast Name: %s",firstname, lastname);

How to write a stored procedure using phpmyadmin and how to use it through php?

I got it to work in phpAdmin , but only when I removed the "Number of records " phrase.

In my version of phpAdmin I could see the box for changing the delimiters.

Also to see the procedure in the database i went to the phpAdmin home, then information_schema database and then the routines table.

Which language uses .pde extension?

Bad news I'm afraid (or maybe great news?) : it isn't C code, it's an example of "Processing" - an open source language aimed at programming images. Take a look here

Looks very cool.

Implementing SearchView in action bar


For Searchview use these code

  1. For XML

    <android.support.v7.widget.SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/searchView">
    
    </android.support.v7.widget.SearchView>
    

  2. In your Fragment or Activity

    package com.example.user.salaryin;
    
    import android.app.ProgressDialog;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v4.view.MenuItemCompat;
    import android.support.v7.widget.GridLayoutManager;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.SearchView;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuInflater;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Toast;
    import com.example.user.salaryin.Adapter.BusinessModuleAdapter;
    import com.example.user.salaryin.Network.ApiClient;
    import com.example.user.salaryin.POJO.ProductDetailPojo;
    import com.example.user.salaryin.Service.ServiceAPI;
    import java.util.ArrayList;
    import java.util.List;
    import retrofit2.Call;
    import retrofit2.Callback;
    import retrofit2.Response;
    
    
    public class OneFragment extends Fragment implements SearchView.OnQueryTextListener {
    
    RecyclerView recyclerView;
    RecyclerView.LayoutManager layoutManager;
    ArrayList<ProductDetailPojo> arrayList;
    BusinessModuleAdapter adapter;
    private ProgressDialog pDialog;
    GridLayoutManager gridLayoutManager;
    SearchView searchView;
    
    public OneFragment() {
        // Required empty public constructor
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }
    
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    
        View rootView = inflater.inflate(R.layout.one_fragment,container,false);
    
        pDialog = new ProgressDialog(getActivity());
        pDialog.setMessage("Please wait...");
    
    
        searchView=(SearchView)rootView.findViewById(R.id.searchView);
        searchView.setQueryHint("Search BY Brand");
        searchView.setOnQueryTextListener(this);
    
        recyclerView = (RecyclerView) rootView.findViewById(R.id.recyclerView);
        layoutManager = new LinearLayoutManager(this.getActivity());
        recyclerView.setLayoutManager(layoutManager);
        gridLayoutManager = new GridLayoutManager(this.getActivity().getApplicationContext(), 2);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setHasFixedSize(true);
        getImageData();
    
    
        // Inflate the layout for this fragment
        //return inflater.inflate(R.layout.one_fragment, container, false);
        return rootView;
    }
    
    
    private void getImageData() {
        pDialog.show();
        ServiceAPI service = ApiClient.getRetrofit().create(ServiceAPI.class);
        Call<List<ProductDetailPojo>> call = service.getBusinessImage();
    
        call.enqueue(new Callback<List<ProductDetailPojo>>() {
            @Override
            public void onResponse(Call<List<ProductDetailPojo>> call, Response<List<ProductDetailPojo>> response) {
                if (response.isSuccessful()) {
                    arrayList = (ArrayList<ProductDetailPojo>) response.body();
                    adapter = new BusinessModuleAdapter(arrayList, getActivity());
                    recyclerView.setAdapter(adapter);
                    pDialog.dismiss();
                } else if (response.code() == 401) {
                    pDialog.dismiss();
                    Toast.makeText(getActivity(), "Data is not found", Toast.LENGTH_SHORT).show();
                }
    
            }
    
            @Override
            public void onFailure(Call<List<ProductDetailPojo>> call, Throwable t) {
                Toast.makeText(getActivity(), t.getMessage(), Toast.LENGTH_SHORT).show();
                pDialog.dismiss();
    
            }
        });
    }
    
       /* @Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.menu_search, menu);
        MenuItem menuItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) MenuItemCompat.getActionView(menuItem);
        searchView.setQueryHint("Search Product");
        searchView.setOnQueryTextListener(this);
    }*/
    
    @Override
    public boolean onQueryTextSubmit(String query) {
        return false;
    }
    
    @Override
    public boolean onQueryTextChange(String newText) {
        newText = newText.toLowerCase();
        ArrayList<ProductDetailPojo> newList = new ArrayList<>();
        for (ProductDetailPojo productDetailPojo : arrayList) {
            String name = productDetailPojo.getDetails().toLowerCase();
    
            if (name.contains(newText) )
                newList.add(productDetailPojo);
            }
        adapter.setFilter(newList);
        return true;
       }
    }
    
  3. In adapter class

     public void setFilter(List<ProductDetailPojo> newList){
        arrayList=new ArrayList<>();
        arrayList.addAll(newList);
        notifyDataSetChanged();
    }
    

Datatable select with multiple conditions

    protected void FindCsv()
    {
        string strToFind = "2";

        importFolder = @"C:\Documents and Settings\gmendez\Desktop\";

        fileName = "CSVFile.csv";

        connectionString= @"Driver={Microsoft Text Driver (*.txt; *.csv)};Dbq="+importFolder+";Extended Properties=Text;HDR=No;FMT=Delimited";
        conn = new OdbcConnection(connectionString);

        System.Data.Odbc.OdbcDataAdapter  da = new OdbcDataAdapter("select * from [" + fileName + "]", conn);
        DataTable dt = new DataTable();
        da.Fill(dt);

        dt.Columns[0].ColumnName = "id";

        DataRow[] dr = dt.Select("id=" + strToFind);

        Response.Write(dr[0][0].ToString() + dr[0][1].ToString() + dr[0][2].ToString() + dr[0][3].ToString() + dr[0][4].ToString() + dr[0][5].ToString());
    }

TypeError: can only concatenate list (not "str") to list

You can use:

newinv=inventory+[add]

but using append is better since it doesn't create a new list:

inventory.append(add)

Java multiline string

It sounds like you want to do a multiline literal, which does not exist in Java.

Your best alternative is going to be strings that are just +'d together. Some other options people have mentioned (StringBuilder, String.format, String.join) would only be preferable if you started with an array of strings.

Consider this:

String s = "It was the best of times, it was the worst of times,\n"
         + "it was the age of wisdom, it was the age of foolishness,\n"
         + "it was the epoch of belief, it was the epoch of incredulity,\n"
         + "it was the season of Light, it was the season of Darkness,\n"
         + "it was the spring of hope, it was the winter of despair,\n"
         + "we had everything before us, we had nothing before us";

Versus StringBuilder:

String s = new StringBuilder()
           .append("It was the best of times, it was the worst of times,\n")
           .append("it was the age of wisdom, it was the age of foolishness,\n")
           .append("it was the epoch of belief, it was the epoch of incredulity,\n")
           .append("it was the season of Light, it was the season of Darkness,\n")
           .append("it was the spring of hope, it was the winter of despair,\n")
           .append("we had everything before us, we had nothing before us")
           .toString();

Versus String.format():

String s = String.format("%s\n%s\n%s\n%s\n%s\n%s"
         , "It was the best of times, it was the worst of times,"
         , "it was the age of wisdom, it was the age of foolishness,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"
);

Versus Java8 String.join():

String s = String.join("\n"
         , "It was the best of times, it was the worst of times,"
         , "it was the age of wisdom, it was the age of foolishness,"
         , "it was the epoch of belief, it was the epoch of incredulity,"
         , "it was the season of Light, it was the season of Darkness,"
         , "it was the spring of hope, it was the winter of despair,"
         , "we had everything before us, we had nothing before us"
);

If you want the newline for your particular system, you either need to use System.lineSeparator(), or you can use %n in String.format.

Another option is to put the resource in a text file, and just read the contents of that file. This would be preferable for very large strings to avoid unnecessarily bloating your class files.

How to thoroughly purge and reinstall postgresql on ubuntu?

I was facing same problem in my ubuntu 16.04

but i fixed that problem and it's very simple just follow these step and you will be able to install postgresql 10 in your system :

Add this to your sources.list:

sudo vim /etc/apt/sources.list

deb http://ftp.de.debian.org/debian/ wheezy main non-free contrib

deb-src http://ftp.de.debian.org/debian/ wheezy main non-free contrib

after that add these link to your pgdg.list file if it's not there you have to create && add link && save it.

sudo vim /etc/apt/sources.list.d/pgdg.list

deb http://apt.postgresql.org/pub/repos/apt/ xenial-pgdg main

deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main

then update your system

sudo apt-get update

sudo apt-get upgrade

and install that unmet dependencies :

apt-get install ssl-cert

that's it. now Install postgresql using these command

sudo apt-get install postgresql-10

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

socket.error: [Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

Got this with flask :

Means that the port you're trying to bind to, is already in used by another service or process : got a hint on this in my code developed on Eclipse / windows :

if __name__ == "__main__":
     # Check the System Type before to decide to bind
     # If the system is a Linux machine -:) 
     if platform.system() == "Linux":
        app.run(host='0.0.0.0',port=5000, debug=True)
     # If the system is a windows /!\ Change  /!\ the   /!\ Port
     elif platform.system() == "Windows":
        app.run(host='0.0.0.0',port=50000, debug=True)

Ifelse statement in R with multiple conditions

Based on suggestions from @jaimedash and @Old_Mortality I found a solution:

DF$Den <- ifelse(DF$Denial1 < 1 & !is.na(DF$Denial1) | DF$Denial2 < 1 &  
!is.na(DF$Denial2) | DF$Denial3 < 1 & !is.na(DF$Denial3), "0", "1")

Then to ensure a value of NA if all values of the conditional variables are NA:

DF$Den <- ifelse(is.na(DF$Denial1) & is.na(DF$Denial2) & is.na(DF$Denial3), 
NA, DF$Den)

The model backing the 'ApplicationDbContext' context has changed since the database was created

This worked for me - no other changes required.

DELETE FROM [dbo].[__MigrationHistory]

How to add Headers on RESTful call using Jersey Client API

If you want to add a header to all Jersey responses, you could also use a ContainerResponseFilter, from Jersey's filter documentation :

import java.io.IOException;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.Response;

@Provider
public class PoweredByResponseFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
        throws IOException {

            responseContext.getHeaders().add("X-Powered-By", "Jersey :-)");
    }
}

Make sure that you initialize it correctly in your project using the @Provider annotation or through traditional ways with web.xml.

How to crop a CvMat in OpenCV?

To get better results and robustness against differents types of matrices, you can do this in addition to the first answer, that copy the data :

cv::Mat source = getYourSource();

// Setup a rectangle to define your region of interest
cv::Rect myROI(10, 10, 100, 100);

// Crop the full image to that image contained by the rectangle myROI
// Note that this doesn't copy the data
cv::Mat croppedRef(source, myROI);

cv::Mat cropped;
// Copy the data into new matrix
croppedRef.copyTo(cropped);

Best way to restrict a text field to numbers only?

this will enable the numpad inputs also.

.keydown(function(event){                                     
    if(event.keyCode == 8 || event.keyCode == 46)             
        return true;                                         
    if(event.keyCode >= 96 && event.keyCode <= 105)           
        return true;                                          
    if(isNaN(parseInt(String.fromCharCode(event.keyCode),10)))
       return false;                                          
}); 

Plot 3D data in R

I use the lattice package for almost everything I plot in R and it has a corresponing plot to persp called wireframe. Let data be the way Sven defined it.

wireframe(z ~ x * y, data=data)

wireframe plot

Or how about this (modification of fig 6.3 in Deepanyan Sarkar's book):

p <- wireframe(z ~ x * y, data=data)
npanel <- c(4, 2)
rotx <- c(-50, -80)
rotz <- seq(30, 300, length = npanel[1]+1)
update(p[rep(1, prod(npanel))], layout = npanel,
    panel = function(..., screen) {
        panel.wireframe(..., screen = list(z = rotz[current.column()],
                                           x = rotx[current.row()]))
    })

Multiple wireframe plots using panel and update

Update: Plotting surfaces with OpenGL

Since this post continues to draw attention I want to add the OpenGL way to make 3-d plots too (as suggested by @tucson below). First we need to reformat the dataset from xyz-tripplets to axis vectors x and y and a matrix z.

x <- 1:5/10
y <- 1:5
z <- x %o% y
z <- z + .2*z*runif(25) - .1*z

library(rgl)
persp3d(x, y, z, col="skyblue")

rgl::persp3d

This image can be freely rotated and scaled using the mouse, or modified with additional commands, and when you are happy with it you save it using rgl.snapshot.

rgl.snapshot("myplot.png")

Android 6.0 multiple permissions

Simple way to ask multiple permission,

https://github.com/sachinvarma/EasyPermission

How to add :

repositories {
        maven { url "https://jitpack.io" }
    }

implementation 'com.github.sachinvarma:EasyPermission:1.0.1'

How to ask permission:

 List<String> permission = new ArrayList<>();
 permission.add(EasyPermissionList.READ_EXTERNAL_STORAGE);
 permission.add(EasyPermissionList.ACCESS_FINE_LOCATION);

 new EasyPermissionInit(MainActivity.this, permission);

For more Details - >

https://github.com/sachinvarma/EasyPermission/blob/master/app/src/main/java/com/sachinvarma/easypermissionsample/MainActivity.java

It may help someone in future.

How to override application.properties during production in Spring-Boot?

I know you asked how to do this, but the answer is you should not do this.

Instead, have a application.properties, application-default.properties application-dev.properties etc., and switch profiles via args to the JVM: e.g. -Dspring.profiles.active=dev

You can also override some things at test time using @TestPropertySource

Ideally everything should be in source control so that there are no surprises e.g. How do you know what properties are sitting there in your server location, and which ones are missing? What happens if developers introduce new things?

Spring Boot is already giving you enough ways to do this right.

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

Permutation of array

Do like this...

import java.util.ArrayList;
import java.util.Arrays;

public class rohit {

    public static void main(String[] args) {
        ArrayList<Integer> a=new ArrayList<Integer>();
        ArrayList<Integer> b=new ArrayList<Integer>();
        b.add(1);
        b.add(2);
        b.add(3);
        permu(a,b);
    }

    public static void permu(ArrayList<Integer> prefix,ArrayList<Integer> value) {
        if(value.size()==0) {
            System.out.println(prefix);
        } else {
            for(int i=0;i<value.size();i++) {
                ArrayList<Integer> a=new ArrayList<Integer>();
                a.addAll(prefix);
                a.add(value.get(i));

                ArrayList<Integer> b=new ArrayList<Integer>();

                b.addAll(value.subList(0, i));
                b.addAll(value.subList(i+1, value.size()));

                permu(a,b);
            }
        }
    }

}

[] and {} vs list() and dict(), which is better?

In terms of speed, it's no competition for empty lists/dicts:

>>> from timeit import timeit
>>> timeit("[]")
0.040084982867934334
>>> timeit("list()")
0.17704233359267718
>>> timeit("{}")
0.033620194745424214
>>> timeit("dict()")
0.1821558326547077

and for non-empty:

>>> timeit("[1,2,3]")
0.24316302770330367
>>> timeit("list((1,2,3))")
0.44744206316727286
>>> timeit("list(foo)", setup="foo=(1,2,3)")
0.446036018543964
>>> timeit("{'a':1, 'b':2, 'c':3}")
0.20868602015059423
>>> timeit("dict(a=1, b=2, c=3)")
0.47635635255323905
>>> timeit("dict(bar)", setup="bar=[('a', 1), ('b', 2), ('c', 3)]")
0.9028228448029267

Also, using the bracket notation lets you use list and dictionary comprehensions, which may be reason enough.

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

You can see some reports in SSMS:

Right-click the instance name / reports / standard / top sessions

You can see top CPU consuming sessions. This may shed some light on what SQL processes are using resources. There are a few other CPU related reports if you look around. I was going to point to some more DMVs but if you've looked into that already I'll skip it.

You can use sp_BlitzCache to find the top CPU consuming queries. You can also sort by IO and other things as well. This is using DMV info which accumulates between restarts.

This article looks promising.

Some stackoverflow goodness from Mr. Ozar.

edit: A little more advice... A query running for 'only' 5 seconds can be a problem. It could be using all your cores and really running 8 cores times 5 seconds - 40 seconds of 'virtual' time. I like to use some DMVs to see how many executions have happened for that code to see what that 5 seconds adds up to.

How do I address unchecked cast warnings?

In this particular case, I would not store Maps into the HttpSession directly, but instead an instance of my own class, which in turn contains a Map (an implementation detail of the class). Then you can be sure that the elements in the map are of the right type.

But if you anyways want to check that the contents of the Map are of right type, you could use a code like this:

public static void main(String[] args) {
    Map<String, Integer> map = new HashMap<String, Integer>();
    map.put("a", 1);
    map.put("b", 2);
    Object obj = map;

    Map<String, Integer> ok = safeCastMap(obj, String.class, Integer.class);
    Map<String, String> error = safeCastMap(obj, String.class, String.class);
}

@SuppressWarnings({"unchecked"})
public static <K, V> Map<K, V> safeCastMap(Object map, Class<K> keyType, Class<V> valueType) {
    checkMap(map);
    checkMapContents(keyType, valueType, (Map<?, ?>) map);
    return (Map<K, V>) map;
}

private static void checkMap(Object map) {
    checkType(Map.class, map);
}

private static <K, V> void checkMapContents(Class<K> keyType, Class<V> valueType, Map<?, ?> map) {
    for (Map.Entry<?, ?> entry : map.entrySet()) {
        checkType(keyType, entry.getKey());
        checkType(valueType, entry.getValue());
    }
}

private static <K> void checkType(Class<K> expectedType, Object obj) {
    if (!expectedType.isInstance(obj)) {
        throw new IllegalArgumentException("Expected " + expectedType + " but was " + obj.getClass() + ": " + obj);
    }
}

jQuery - find child with a specific class

I'm not sure if I understand your question properly, but it shouldn't matter if this div is a child of some other div. You can simply get text from all divs with class bgHeaderH2 by using following code:

$(".bgHeaderH2").text();

Converting a string to an integer on Android

You can use the following to parse a string to an integer:

int value=Integer.parseInt(textView.getText().toString());

(1) input: 12 then it will work.. because textview has taken this 12 number as "12" string.

(2) input: "abdul" then it will throw an exception that is NumberFormatException. So to solve this we need to use try catch as I have mention below:

  int tax_amount=20;
  EditText edit=(EditText)findViewById(R.id.editText1);
     try
       {

        int value=Integer.parseInt(edit.getText().toString());
        value=value+tax_amount;
        edit.setText(String.valueOf(value));// to convert integer to string 

       }catch(NumberFormatException ee){
       Log.e(ee.toString());
       }

You may also want to refer to the following link for more information: http://developer.android.com/reference/java/lang/Integer.html

How to Parse JSON Array with Gson

[
      {
           id : '1',
           title: 'sample title',
           ....
      },
      {
           id : '2',
           title: 'sample title',
           ....
     },
      ...
 ]

Check Easy code for this output

 Gson gson=new GsonBuilder().create();
                List<Post> list= Arrays.asList(gson.fromJson(yourResponse.toString,Post[].class));

Anaconda / Python: Change Anaconda Prompt User Path

Just Type the Drive Location you want to work with: This worked for me! For example you want to change to D drive in windows:

D:\

If you want to change to particular folder in the drive:

cd D:\Newfolder

How to loop in excel without VBA or macros?

Add more columns when you have variable loops that repeat at different rates. I'm not sure explicitly what you're trying to do, but I think I've done something that could apply.

Creating a single loop in Excel is prettty simple. It actually does the work for you. Try this on a new workbook

  1. Enter "1" in A1
  2. Enter "=A1+1" in A2

A3 will automatically be "=A2+1" as you drag down. The first steps don't have to be that explicit. Excel will automatically recognize the pattern and count if you just put "2" in A2, but if we want B1-B5 to be "100" and B5-B10 to be "200" (counting up the same way) you can see why knowing how to do it explicitly matters. In this scenario, You just enter:

  1. "100" in B1, drag through to B5 and
  2. "=B1+100" in B6

B7 will automatically be "=B2+100" etc. as you drag down, so basically it increases every 5 rows infinitely. To make a loop of numbers 1-5 in column A:

  1. Enter "=A1" in cell A6. As you drag down, it will automatically be "=A2" in cell A7, etc. because of the way that Excel does things.

So, now we have column A repeating numbers 1-5 while column B is increasing by 100 every 5 cells.You could make column B repeat, for instance, the numbers 100-900 in using the same method as you did with column A as a way to produce, for instance, each possible combination with multiple variables. Drag down the columns and they'll do it infinitely. I'm not explicitly addressing the scenario given, but if you follow the steps and understand them, the concept should give you an answer to the problem that involves adding more columns and concactinating or using them as your variables.

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

Try granting permission to the NETWORK SERVICE user.

What is the different between RESTful and RESTless

'RESTless' is a term not often used.

You can define 'RESTless' as any system that is not RESTful. For that it is enough to not have one characteristic that is required for a RESTful system.

Most systems are RESTless by this definition because they don't implement HATEOAS.

HTML5 best practices; section/header/aside/article elements

According to Nathan's answer, this makes perfect sense (for red and orange parts, maybe you could use div's and/or header and footer respectively):

enter image description here

How to determine the encoding of text?

Another option for working out the encoding is to use libmagic (which is the code behind the file command). There are a profusion of python bindings available.

The python bindings that live in the file source tree are available as the python-magic (or python3-magic) debian package. It can determine the encoding of a file by doing:

import magic

blob = open('unknown-file', 'rb').read()
m = magic.open(magic.MAGIC_MIME_ENCODING)
m.load()
encoding = m.buffer(blob)  # "utf-8" "us-ascii" etc

There is an identically named, but incompatible, python-magic pip package on pypi that also uses libmagic. It can also get the encoding, by doing:

import magic

blob = open('unknown-file', 'rb').read()
m = magic.Magic(mime_encoding=True)
encoding = m.from_buffer(blob)

join list of lists in python

Or a recursive operation:

def flatten(input):
    ret = []
    if not isinstance(input, (list, tuple)):
        return [input]
    for i in input:
        if isinstance(i, (list, tuple)):
            ret.extend(flatten(i))
        else:
            ret.append(i)
    return ret

How can I remove the search bar and footer added by the jQuery DataTables plugin?

Just a reminder you can't initialise DataTable on the same <table> element twice.

If you encounter same issue then you can set searching and paging false while initializing DataTable on your HTML <table> like this

 $('#tbl').DataTable({
    searching: false, 
    paging: false,
    dom: 'Bfrtip',
    buttons: [
       'copy', 'csv', 'excel', 'pdf', 'print'
    ]
 });

HTML5 Form Input Pattern Currency Format

Use this pattern "^\d*(\.\d{2}$)?"

How to pass variable from jade template file to a script file?

If you're like me and you use this method of passing variables a lot, here's a write-less-code solution.

In your node.js route, pass the variables in an object called window, like this:

router.get('/', function (req, res, next) {
    res.render('index', {
        window: {
            instance: instance
        }
    });
});

Then in your pug/jade layout file (just before the block content), you get them out like this:

if window
    each object, key in window
        script.
            window.!{key} = !{JSON.stringify(object)};

As my layout.pug file gets loaded with each pug file, I don't need to 'import' my variables over and over.

This way all variables/objects passed to window 'magically' end up in the real window object of your browser where you can use them in Reactjs, Angular, ... or vanilla javascript.

Bootstrap 3: How do you align column content to bottom of row

When working with bootsrap usually face three main problems:

  1. How to place the content of the column to the bottom?
  2. How to create a multi-row gallery of columns of equal height in one .row?
  3. How to center columns horizontally if their total width is less than 12 and the remaining width is odd?

To solve first two problems download this small plugin https://github.com/codekipple/conformity

The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns

Common code

<style>
    [class*=col-] {position: relative}
    .row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
    .row-centered {text-align:center}   
    .row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top} 
</style>

<script src="assets/conformity/conformity.js"></script>
<script>
    $(document).ready(function () {
        $('.row-conformity > [class*=col-]').conformity();
        $(window).on('resize', function() {
            $('.row-conformity > [class*=col-]').conformity();
        });
    });
</script>

1. Aligning content of the column to the bottom

<div class="row row-conformity">
    <div class="col-sm-3">
        I<br>create<br>highest<br>column
    </div>
    <div class="col-sm-3">
        <div class="to-bottom">
            I am on the bottom
        </div>
    </div>
</div>

2. Gallery of columns of equal height

<div class="row row-conformity">
    <div class="col-sm-4">We all have equal height</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
</div>

3. Horizontal alignment of columns to the center (less than 12 col units)

<div class="row row-centered">
    <div class="col-sm-3">...</div>
    <div class="col-sm-4">...</div>
</div>

All classes can work together

<div class="row row-conformity row-centered">
    ...
</div>

Threading Example in Android

Here is a simple threading example for Android. It's very basic but it should help you to get a perspective.

Android code - Main.java

package test12.tt;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Test12Activity extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        final TextView txt1 = (TextView) findViewById(R.id.sm);

        new Thread(new Runnable() { 
            public void run(){        
            txt1.setText("Thread!!");
            }
        }).start();

    }    
}

Android application xml - main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <TextView  
    android:id = "@+id/sm"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"/>

</LinearLayout>

SELECT last id, without INSERT

You could descendingly order the tabele by id and limit the number of results to one:

SELECT id FROM tablename ORDER BY id DESC LIMIT 1

BUT: ORDER BY rearranges the entire table for this request. So if you have a lot of data and you need to repeat this operation several times, I would not recommend this solution.

Turning off eslint rule for a specific file

Simply create an empty file .eslintignore in your project root the type the path to the file you want it to be ignore.

Source: https://eslint.org/docs/2.13.1/user-guide/configuring#:~:text=To%20disable%20rule%20warnings%20in,*%2F%20alert('foo')%3B

Line Ignoring Files and Directories

Order columns through Bootstrap4

This can also be achieved with the CSS "Order" property and a media query.

Something like this:

@media only screen and (max-width: 768px) {
    #first {
        order: 2;
    }
    #second {
        order: 4;
    }
    #third {
        order: 1;
    }
    #fourth {
        order: 3;
    }
}

CodePen Link: https://codepen.io/preston206/pen/EwrXqm

Removing MySQL 5.7 Completely

First of all, do a backup of your needed databases with mysqldump

Note: If you want to restore later, just backup your relevant databases, and not the WHOLE, because the whole database might actually be the reason you need to purge and reinstall).

In total, do this:

sudo service mysql stop  #or mysqld
sudo killall -9 mysql
sudo killall -9 mysqld
sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean
sudo deluser -f mysql
sudo rm -rf /var/lib/mysql
sudo apt-get purge mysql-server-core-5.7
sudo apt-get purge mysql-client-core-5.7
sudo rm -rf /var/log/mysql
sudo rm -rf /etc/mysql

All above commands in single line (just copy and paste):

sudo service mysql stop && sudo killall -9 mysql && sudo killall -9 mysqld && sudo apt-get remove --purge mysql-server mysql-client mysql-common && sudo apt-get autoremove && sudo apt-get autoclean && sudo deluser mysql && sudo rm -rf /var/lib/mysql && sudo apt-get purge mysql-server-core-5.7 && sudo apt-get purge mysql-client-core-5.7 && sudo rm -rf /var/log/mysql && sudo rm -rf /etc/mysql

How to properly create composite primary keys - MYSQL

CREATE  TABLE `mom`.`sec_subsection` (

  `idsec_sub` INT(11) NOT NULL ,

  `idSubSections` INT(11) NOT NULL ,

  PRIMARY KEY (`idsec_sub`, `idSubSections`) 

);

Searching word in vim?

If you are working in Ubuntu,follow the steps:

  1. Press / and type word to search
  2. To search in forward press 'SHIFT' key with * key
  3. To search in backward press 'SHIFT' key with # key

Does document.body.innerHTML = "" clear the web page?

document.body.innerHTML = ''; does clear the body, yeah. But it clears the innerHTML as it is at the moment the code is ran. As you run the code before the images and the script are actually in the body, it tries to clear the body, but there's nothing to clear.

If you want to clear the body, you have to run the code after the body has been filled with content. You can do this by either placing the <script> block as the last child of body, so everything is loaded before the code is ran, or you have to use some way to listen to the dom:loaded event.

How to find elements by class

Try to check if the div has a class attribute first, like this:

soup = BeautifulSoup(sdata)
mydivs = soup.findAll('div')
for div in mydivs:
    if "class" in div:
        if (div["class"]=="stylelistrow"):
            print div

What's the best UML diagramming tool?

I have been working on UML standards since 1999 and may tell you that Sparx Enterprise Architect should not be considered as a UML tool as it does not follow UML 2 specification. Its diagrams look as UML but names of the properties and the way as they specified are not following UML standard. MagicDraw and IBM RSA are the true UML tool on the market so far.

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

The example in the question is a simpler case where the property names matched exactly in json and in code. If the property names do not exactly match, e.g. property in json is "first_name": "Mark" and the property in code is FirstName then use the Select method as follows

List<SelectableEnumItem> items = ((JArray)array).Select(x => new SelectableEnumItem
{
    FirstName = (string)x["first_name"],
    Selected = (bool)x["selected"]
}).ToList();

Java - How to convert type collection into ArrayList?

public <E> List<E> collectionToList(Collection<E> collection)
{
    return (collection instanceof List) ? (List<E>) collection : new ArrayList<E>(collection);
}

Use the above method for converting the collection to list

MySQL Check if username and password matches in Database

1.) Storage of database passwords Use some kind of hash with a salt and then alter the hash, obfuscate it, for example add a distinct value for each byte. That way your passwords a super secured against dictionary attacks and rainbow tables.

2.) To check if the password matches, create your hash for the password the user put in. Then perform a query against the database for the username and just check if the two password hashes are identical. If they are, give the user an authentication token.

The query should then look like this:

select hashedPassword from users where username=?

Then compare the password to the input.

Further questions?

Git pushing to remote branch

You can push your local branch to a new remote branch like so:

git push origin master:test

(Assuming origin is your remote, master is your local branch name and test is the name of the new remote branch, you wish to create.)

If at the same time you want to set up your local branch to track the newly created remote branch, you can do so with -u (on newer versions of Git) or --set-upstream, so:

git push -u origin master:test

or

git push --set-upstream origin master:test

...will create a new remote branch, named test, in remote repository origin, based on your local master, and setup your local master to track it.

Strangest language feature

In C#, the following code generates compiler error "Cannot convert from method group to Delegate". Though the logic behind is reasonable, it still feels strange to me.

control.BeginInvoke(delegate { DoSomething(); });

What exactly is Apache Camel?

Here is another attempt at it.

You know how there are/were things like Webmethods, ICAN Seebeyond, Tibco BW, IBM Broker. They all did help with integration solutions in the enterprise. These tools are commonly known by the name Enterprise Application Integration (EAI) tools.

There were mostly drag drop tools built around these technologies and in parts you would have to write adapters in Java. These adapter code were either untested or had poor tooling/automation around testing.

Just like with design patterns in programming, you have Enterprise Integration patterns for common integration solutions. They were made famous by a book of the same name by Gregor Hohpe and Bobby Woolf.

Although it is quite possible to implement integration solutions which use one or many EIP, Camel is an attempt at doing this within your code base using one of XML, Java, Groovy or Scala.

Camel supports all Enterprise Integration Patterns listed in the book via its rich DSL and routing mechanism.

So Camel is a competing technoloy to other EAI tools with better support for testing your integration code. The code is concise because of the Domain Specific Languages (DSLs). It is readable by even business users and it is free and makes you productive.

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

Convert form data to JavaScript object with jQuery

[UPDATE 2020]

With a simple oneliner in vanilla js that leverages fromEntries (as always, check browser support):

Object.fromEntries(new FormData(form))

Remove all non-"word characters" from a String in Java, leaving accented characters?

You might want to remove the accents and diacritic signs first, then on each character position check if the "simplified" string is an ascii letter - if it is, the original position shall contain word characters, if not, it can be removed.

PHP 5.4 Call-time pass-by-reference - Easy fix available?

PHP and references are somewhat unintuitive. If used appropriately references in the right places can provide large performance improvements or avoid very ugly workarounds and unusual code.

The following will produce an error:

 function f(&$v){$v = true;}
 f(&$v);

 function f($v){$v = true;}
 f(&$v);

None of these have to fail as they could follow the rules below but have no doubt been removed or disabled to prevent a lot of legacy confusion.

If they did work, both involve a redundant conversion to reference and the second also involves a redundant conversion back to a scoped contained variable.

The second one used to be possible allowing a reference to be passed to code that wasn't intended to work with references. This is extremely ugly for maintainability.

This will do nothing:

 function f($v){$v = true;}
 $r = &$v;
 f($r);

More specifically, it turns the reference back into a normal variable as you have not asked for a reference.

This will work:

 function f(&$v){$v = true;}
 f($v);

This sees that you are passing a non-reference but want a reference so turns it into a reference.

What this means is that you can't pass a reference to a function where a reference is not explicitly asked for making it one of the few areas where PHP is strict on passing types or in this case more of a meta type.

If you need more dynamic behaviour this will work:

 function f(&$v){$v = true;}
 $v = array(false,false,false);
 $r = &$v[1];
 f($r);

Here it sees that you want a reference and already have a reference so leaves it alone. It may also chain the reference but I doubt this.

Ant is using wrong java version

If you run Ant from eclipse, the eclipse will use jdk or jre that is configured in the class-path(build path).

How to apply slide animation between two activities in Android?

Hopefully, it will work for you.

startActivityForResult( intent, 1 , ActivityOptions.makeCustomAnimation(getActivity(),R.anim.slide_out_bottom,R.anim.slide_in_bottom).toBundle());

What are the differences between a pointer variable and a reference variable in C++?

A reference to a pointer is possible in C++, but the reverse is not possible means a pointer to a reference isn't possible. A reference to a pointer provides a cleaner syntax to modify the pointer. Look at this example:

#include<iostream>
using namespace std;

void swap(char * &str1, char * &str2)
{
  char *temp = str1;
  str1 = str2;
  str2 = temp;
}

int main()
{
  char *str1 = "Hi";
  char *str2 = "Hello";
  swap(str1, str2);
  cout<<"str1 is "<<str1<<endl;
  cout<<"str2 is "<<str2<<endl;
  return 0;
}

And consider the C version of the above program. In C you have to use pointer to pointer (multiple indirection), and it leads to confusion and the program may look complicated.

#include<stdio.h>
/* Swaps strings by swapping pointers */
void swap1(char **str1_ptr, char **str2_ptr)
{
  char *temp = *str1_ptr;
  *str1_ptr = *str2_ptr;
  *str2_ptr = temp;
}

int main()
{
  char *str1 = "Hi";
  char *str2 = "Hello";
  swap1(&str1, &str2);
  printf("str1 is %s, str2 is %s", str1, str2);
  return 0;
}

Visit the following for more information about reference to pointer:

As I said, a pointer to a reference isn't possible. Try the following program:

#include <iostream>
using namespace std;

int main()
{
   int x = 10;
   int *ptr = &x;
   int &*ptr1 = ptr;
}

Receive JSON POST with PHP

Try;

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
echo $data["operacion"];

From your json and your code, it looks like you have spelled the word operation correctly on your end, but it isn't in the json.

EDIT

Maybe also worth trying to echo the json string from php://input.

echo file_get_contents('php://input');

Twitter Bootstrap 3: how to use media queries?

These are the values from Bootstrap3:

/* Extra Small */
@media(max-width:767px){}

/* Small */
@media(min-width:768px) and (max-width:991px){}

/* Medium */
@media(min-width:992px) and (max-width:1199px){}

/* Large */
@media(min-width:1200px){}

How to use if-else logic in Java 8 stream forEach

The problem by using stream().forEach(..) with a call to add or put inside the forEach (so you mutate the external myMap or myList instance) is that you can run easily into concurrency issues if someone turns the stream in parallel and the collection you are modifying is not thread safe.

One approach you can take is to first partition the entries in the original map. Once you have that, grab the corresponding list of entries and collect them in the appropriate map and list.

Map<Boolean, List<Map.Entry<K, V>>> partitions =
    animalMap.entrySet()
             .stream()
             .collect(partitioningBy(e -> e.getValue() == null));

Map<K, V> myMap = 
    partitions.get(false)
              .stream()
              .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));

List<K> myList =
    partitions.get(true)
              .stream()
              .map(Map.Entry::getKey) 
              .collect(toList());

... or if you want to do it in one pass, implement a custom collector (assuming a Tuple2<E1, E2> class exists, you can create your own), e.g:

public static <K,V> Collector<Map.Entry<K, V>, ?, Tuple2<Map<K, V>, List<K>>> customCollector() {
    return Collector.of(
            () -> new Tuple2<>(new HashMap<>(), new ArrayList<>()),
            (pair, entry) -> {
                if(entry.getValue() == null) {
                    pair._2.add(entry.getKey());
                } else {
                    pair._1.put(entry.getKey(), entry.getValue());
                }
            },
            (p1, p2) -> {
                p1._1.putAll(p2._1);
                p1._2.addAll(p2._2);
                return p1;
            });
}

with its usage:

Tuple2<Map<K, V>, List<K>> pair = 
    animalMap.entrySet().parallelStream().collect(customCollector());

You can tune it more if you want, for example by providing a predicate as parameter.

Property 'value' does not exist on type 'Readonly<{}>'

I suggest to use

for string only state values

export default class Home extends React.Component<{}, { [key: string]: string }> { }

for string key and any type of state values

export default class Home extends React.Component<{}, { [key: string]: any}> { }

for any key / any values

export default class Home extends React.Component<{}, { [key: any]: any}> {}

setting request headers in selenium

I had the same issue. I solved it downloading modify-headers firefox add-on and activate it with selenium.

The code in python is the following

fp = webdriver.FirefoxProfile()
path_modify_header = 'C:/xxxxxxx/modify_headers-0.7.1.1-fx.xpi'
fp.add_extension(path_modify_header)

fp.set_preference("modifyheaders.headers.count", 1)
fp.set_preference("modifyheaders.headers.action0", "Add")
fp.set_preference("modifyheaders.headers.name0", "Name_of_header") # Set here the name of the header
fp.set_preference("modifyheaders.headers.value0", "value_of_header") # Set here the value of the header
fp.set_preference("modifyheaders.headers.enabled0", True)
fp.set_preference("modifyheaders.config.active", True)
fp.set_preference("modifyheaders.config.alwaysOn", True)

driver = webdriver.Firefox(firefox_profile=fp)

How can I configure Logback to log different levels for a logger to different destinations?

The simplest solution is to use ThresholdFilter on the appenders:

    <appender name="..." class="...">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>

Full example:

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d %-5level: %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
        <target>System.err</target>
        <encoder>
            <pattern>%d %-5level: %msg%n</pattern>
        </encoder>
    </appender>

    <root>
        <appender-ref ref="STDOUT" />
        <appender-ref ref="STDERR" />
    </root>
</configuration>

Update: As Mike pointed out in the comment, messages with ERROR level are printed here both to STDOUT and STDERR. Not sure what was the OP's intent, though. You can try Mike's answer if this is not what you wanted.

Laravel - Forbidden You don't have permission to access / on this server

On public/.htaccess edit to

<IfModule mod_rewrite.c>
 <IfModule mod_negotiation.c>
              Options -MultiViews
          </IfModule>

          RewriteEngine On

          # Redirect Trailing Slashes If Not A Folder...
          RewriteCond %{REQUEST_FILENAME} !-d
          RewriteCond %{REQUEST_URI} (.+)/$
          RewriteRule ^ %1 [L,R=301]

          # Handle Front Controller...
          RewriteCond %{REQUEST_FILENAME} !-d
          RewriteCond %{REQUEST_FILENAME} !-f
          RewriteRule ^ index.php [L]

          # Handle Authorization Header
          RewriteCond %{HTTP:Authorization} .
          RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
</IfModule>

In the root of the project add file

Procfile

File content

web: vendor/bin/heroku-php-apache2 public/

Reload the project to Heroku

bash
heroku login
cd my-project/
git init
heroku git:remote -a my project
git add .
git commit -am "make it better"
git push heroku master
heroku open

How to check for valid email address?

Found this to be a practical implementation:

[^@\s]+@[^@\s]+\.[^@\s]+

How can I get the selected VALUE out of a QCombobox?

The question is old, but maybe, somebody need an actual answer.

In the QGIS 3.4 you can get the value from the QComboBox with the method currentData().

Example: comboBox.currentData()

Link: https://doc.qt.io/qt-5/qcombobox.html#currentData-prop

Failed to Connect to MySQL at localhost:3306 with user root

Steps:

1 - Right click on your task bar -->Start Task Manager

2 - Click on Services button (at bottom).

3 - Search for MYSQL57

4 - Right Click on MYSQL57 --> Start

Now again start your mysql-cmd-prompt or MYSQL WorkBench

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

I just ran into this and found that changing this in the .env file from 127.0.0.1 to localhost fixed it.

DB_HOST=localhost

How to use git merge --squash?

if you get error: Committing is not possible because you have unmerged files.

git checkout master
git merge --squash bugfix
git add .
git commit -m "Message"

fixed all the Conflict files

git add . 

you could also use

git add [filename]

SOAP Action WSDL

If its a SOAP 1.1 service then you will also need to include a SOAPAction HTTP header field:

http://www.w3.org/TR/2000/NOTE-SOAP-20000508/#_Toc478383528

curl.h no such file or directory

sudo apt-get install curl-devel

sudo apt-get install libcurl-dev

(will install the default alternative)

OR

sudo apt-get install libcurl4-openssl-dev

(the OpenSSL variant)

OR

sudo apt-get install libcurl4-gnutls-dev

(the gnutls variant)

Cannot import keras after installation

Diagnose

If you have pip installed (you should have it until you use Python 3.5), list the installed Python packages, like this:

$ pip list | grep -i keras
Keras (1.1.0)

If you don’t see Keras, it means that the previous installation failed or is incomplete (this lib has this dependancies: numpy (1.11.2), PyYAML (3.12), scipy (0.18.1), six (1.10.0), and Theano (0.8.2).)

Consult the pip.log to see what’s wrong.

You can also display your Python path like this:

$ python3 -c 'import sys, pprint; pprint.pprint(sys.path)'
['',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python35.zip',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/plat-darwin',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/lib-dynload',
 '/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages']

Make sure the Keras library appears in the /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages path (the path is different on Ubuntu).

If not, try do uninstall it, and retry installation:

$ pip uninstall Keras

Use a virtualenv

It’s a bad idea to use and pollute your system-wide Python. I recommend using a virtualenv (see this guide).

The best usage is to create a virtualenv directory (in your home, for instance), and store your virtualenvs in:

cd virtualenv/
virtualenv -p python3.5 py-keras
source py-keras/bin/activate
pip install -q -U pip setuptools wheel

Then install Keras:

pip install keras

You get:

$ pip list
Keras (1.1.0)
numpy (1.11.2)
pip (8.1.2)
PyYAML (3.12)
scipy (0.18.1)
setuptools (28.3.0)
six (1.10.0)
Theano (0.8.2)
wheel (0.30.0a0)

But, you also need to install extra libraries, like Tensorflow:

$ python -c "import keras"
Using TensorFlow backend.
Traceback (most recent call last):
  ...
ImportError: No module named 'tensorflow'

The installation guide of TesnsorFlow is here: https://www.tensorflow.org/versions/r0.11/get_started/os_setup.html#pip-installation

How To fix white screen on app Start up?

This solved the problem :

Edit your styles.xml file :


Paste the code below :

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="android:windowFullscreen">true</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:windowIsTranslucent">true</item>
    </style>

</resources>

And don't forget to make the modifications in the AndroidManifest.xml file. (theme's name)

Be careful about the declaration order of the activities in this file.

How to encode a URL in Swift

In my case where the last component was non latin characters I did the following in Swift 2.2:

extension String {
 func encodeUTF8() -> String? {
//If I can create an NSURL out of the string nothing is wrong with it
if let _ = NSURL(string: self) {

    return self
}

//Get the last component from the string this will return subSequence
let optionalLastComponent = self.characters.split { $0 == "/" }.last


if let lastComponent = optionalLastComponent {

    //Get the string from the sub sequence by mapping the characters to [String] then reduce the array to String
    let lastComponentAsString = lastComponent.map { String($0) }.reduce("", combine: +)


    //Get the range of the last component
    if let rangeOfLastComponent = self.rangeOfString(lastComponentAsString) {
        //Get the string without its last component
        let stringWithoutLastComponent = self.substringToIndex(rangeOfLastComponent.startIndex)


        //Encode the last component
        if let lastComponentEncoded = lastComponentAsString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.alphanumericCharacterSet()) {


        //Finally append the original string (without its last component) to the encoded part (encoded last component)
        let encodedString = stringWithoutLastComponent + lastComponentEncoded

            //Return the string (original string/encoded string)
            return encodedString
        }
    }
}

return nil;
}
}

What do "branch", "tag" and "trunk" mean in Subversion repositories?

Tag = a defined slice in time, usually used for releases

I think this is what one typically means by "tag". But in Subversion:

They don't really have any formal meaning. A folder is a folder to SVN.

which I find rather confusing: a revision control system that knows nothing about branches or tags. From an implementation point of view, I think the Subversion way of creating "copies" is very clever, but me having to know about it is what I'd call a leaky abstraction.

Or perhaps I've just been using CVS far too long.

How to use a dot "." to access members of dictionary?

If you want to pickle your modified dictionary, you need to add few state methods to above answers:

class DotDict(dict):
    """dot.notation access to dictionary attributes"""
    def __getattr__(self, attr):
        return self.get(attr)
    __setattr__= dict.__setitem__
    __delattr__= dict.__delitem__

    def __getstate__(self):
        return self

    def __setstate__(self, state):
        self.update(state)
        self.__dict__ = self

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

Hey, we just did a global find-replace, changing Required=" to jRequired=". Then you just change it in the jquery code as well (jquery_helper.js -> Function ValidateControls). Now our validation continues as before and Chrome leaves us alone! :)

How to Set Selected value in Multi-Value Select in Jquery-Select2.?

To Select all

 $('select[name=eventsFilter]').find('option').attr('selected', true);
$('select[name=eventsFilter]').select2();

To UnSellect all

$('select[name=eventsFilter]').find('option').attr('selected', false);
  $('select[name=eventsFilter]').select2("");

How to remove the border highlight on an input text element

try this css, it work for me

textarea:focus, input:focus{ border: none; }

Excel formula to get cell color

No, you can only get to the interior color of a cell by using a Macro. I am afraid. It's really easy to do (cell.interior.color) so unless you have a requirement that restricts you from using VBA, I say go for it.

How to send a PUT/DELETE request in jQuery?

You should be able to use jQuery.ajax :

Load a remote page using an HTTP request.


And you can specify which method should be used, with the type option :

The type of request to make ("POST" or "GET"), default is "GET".
Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.

How to set standard encoding in Visual Studio

The Problem is Windows and Microsoft applications put byte order marks at the beginning of all your files so other applications often break or don't read these UTF-8 encoding marks. I perfect example of this problem was triggering quirsksmode in old IE web browsers when encoding in UTF-8 as browsers often display web pages based on what encoding falls at the start of the page. It makes a mess when other applications view those UTF-8 Visual Studio pages.

I usually do not recommend Visual Studio Extensions, but I do this one to fix that issue:

Fix File Encoding: https://vlasovstudio.com/fix-file-encoding/

The FixFileEncoding above install REMOVES the byte order mark and forces VS to save ALL FILES without signature in UTF-8. After installing go to Tools > Option then choose "FixFileEncoding". It should allow you to set all saves as UTF-8 . Add "cshtml to the list of files to always save in UTF-8 without the byte order mark as so: ".(htm|html|cshtml)$)".

Now open one of your files in Visual Studio. To verify its saving as UTF-8 go to File > Save As, then under the Save button choose "Save With Encoding". It should choose "UNICODE (Save without Signature)" by default from the list of encodings. Now when you save that page it should always save as UTF-8 without byte order mark at the beginning of the file when saving in Visual Studio.

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

Use request.args.get(param), for example:

http://10.1.1.1:5000/login?username=alex&password=pw1
@app.route('/login', methods=['GET', 'POST'])
def login():
    username = request.args.get('username')
    print(username)
    password = request.args.get('password')
    print(password)

Here is the referenced link to the code.

How to set app icon for Electron / Atom Shell App

Below is the solution that i have :

mainWindow = new BrowserWindow({width: 800, height: 600,icon: __dirname + '/Bluetooth.ico'});

Is it possible to hide/encode/encrypt php source code and let others have the system?

You could just split the frontend and backend. The frontend is hosted on the customers server with an API that makes calls to the backend on your server. This keeps all of the proprietary code proprietary and forces users to sign up / pay for subscriptions.

There is no argument given that corresponds to the required formal parameter - .NET Error

I received this same error in the following Linq statement regarding DailyReport. The problem was that DailyReport had no default constructor. Apparently, it instantiates the object before populating the properties.

var sums = reports
    .GroupBy(r => r.CountryRegion)
    .Select(cr => new DailyReport
    {
        CountryRegion = cr.Key,
        ProvinceState = "All",
        RecordDate = cr.First().RecordDate,
        Confirmed = cr.Sum(c => c.Confirmed),
        Recovered = cr.Sum(c => c.Recovered),
        Deaths = cr.Sum(c => c.Deaths)
    });

How do you replace double quotes with a blank space in Java?

Strings are immutable, so you need to say

sInputString = sInputString("\"","");

not just the right side of the =

"Cannot allocate an object of abstract type" error

In C++ a class with at least one pure virtual function is called abstract class. You can not create objects of that class, but may only have pointers or references to it.

If you are deriving from an abstract class, then make sure you override and define all pure virtual functions for your class.

From your snippet Your class AliceUniversity seems to be an abstract class. It needs to override and define all the pure virtual functions of the classes Graduate and UniversityGraduate.

Pure virtual functions are the ones with = 0; at the end of declaration.

Example: virtual void doSomething() = 0;

For a specific answer, you will need to post the definition of the class for which you get the error and the classes from which that class is deriving.

How to display loading image while actual image is downloading

Just add a background image to all images using css:

img {
  background: url('loading.gif') no-repeat;
}

How to get VM arguments from inside of Java application?

At startup pass this -Dname=value

and then in your code you should use

value=System.getProperty("name");

to get that value

cordova Android requirements failed: "Could not find an installed version of Gradle"

same problem but very simple on Mac with brew:

  • brew update
  • brew install gradle

What can MATLAB do that R cannot do?

As a user of both MATLAB and R, I think they are very different applications. I myself have a background in computer science, etc. and I can't help thinking that R is by statisticians for statisticians whereas MATLAB is by programmers for programmers.

R makes it very easy to visualize and compute all sorts of statistical stuff but I wouldn't use it to implement anything signal processing related if it was up to me.

To sum up, if you want to do statistics, use R. If you want to program, use MATLAB or some programming language.

Angular cli generate a service and include the provider in one step

Specify paths

--app
  --one
    one.module.ts
    --services

  --two
    two.module.ts
    --services

Create Service with new folder in module ONE

ng g service one/services/myNewServiceFolderName/serviceOne --module one/one

--one
  one.module.ts // service imported and added to providers.
  --services
    --myNewServiceFolderName
      serviceOne.service.ts
      serviceOne.service.spec.ts

Undefined symbols for architecture armv7

Probably some classes are missing from your target. This usually happens when you rename/remove/add new classes files to your project. To fix add the newly added classes to some targets.

Select the class in the Project Navigator (right sidebar) , open the Utilities sidebar (right sidebar), from the Utilities select the File Inspector (file like icon), under the Target Membership tab tick your targets. This is all to avoid the "Remove reference" and add again with ticking "Add to targets" trick.

So: Select Class -> Utilities (File Inspector) -> Target Membership -> Tick the targets you want.

How can I get the Windows last reboot reason

This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:

  1. Press the Windows + R keys to open the Run dialog, type eventvwr.msc, and press Enter.

  2. If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).

  3. In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.

  4. Do either step 5 or 6 below for what shutdown events you would like to see.

  5. To See the Dates and Times of All User Shut Downs of the Computer

    A) In Event sources, click/tap on the drop down arrow and check the USER32 box.

    B) In the All Event IDs field, type 1074, then click/tap on OK.

    C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.

    D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.

    E) Go to step 7.

  6. To See the Dates and Times of All Unexpected Shut Downs of the Computer

    A) In the All Event IDs field, type 6008, then click/tap on OK.

    B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.

Why do we not have a virtual constructor in C++?

If you think logically about how constructors work and what the meaning/usage of a virtual function is in C++ then you will realise that a virtual constructor would be meaningless in C++. Declaring something virtual in C++ means that it can be overridden by a sub-class of the current class, however the constructor is called when the objected is created, at that time you cannot be creating a sub-class of the class, you must be creating the class so there would never be any need to declare a constructor virtual.

And another reason is, the constructors have the same name as its class name and if we declare constructor as virtual, then it should be redefined in its derived class with the same name, but you can not have the same name of two classes. So it is not possible to have a virtual constructor.

Output Django queryset as JSON

To return the queryset you retrieved with queryset = Users.objects.all(), you first need to serialize them.

Serialization is the process of converting one data structure to another. Using Class-Based Views, you could return JSON like this.

from django.core.serializers import serialize
from django.http import JsonResponse
from django.views.generic import View

class JSONListView(View):
    def get(self, request, *args, **kwargs):
        qs = User.objects.all()
        data = serialize("json", qs)
        return JsonResponse(data)

This will output a list of JSON. For more detail on how this works, check out my blog article How to return a JSON Response with Django. It goes into more detail on how you would go about this.

How do I read any request header in PHP

PHP 7: Null Coalesce Operator

//$http = 'SCRIPT_NAME';
$http = 'X_REQUESTED_WITH';
$http = strtoupper($http);
$header = $_SERVER['HTTP_'.$http] ?? $_SERVER[$http] ?? NULL;

if(is_null($header)){
    die($http. ' Not Found');
}
echo $header;

Angular 2 filter/search list

data

names = ['Prashobh','Abraham','Anil','Sam','Natasha','Marry','Zian','karan']

You can achieve this by creating a simple pipe

<input type="text" [(ngModel)]="queryString" id="search" placeholder="Search to type">

Pipe

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'FilterPipe',
})
export class FilterPipe implements PipeTransform {
    transform(value: any, input: string) {
        if (input) {
            input = input.toLowerCase();
            return value.filter(function (el: any) {
                return el.toLowerCase().indexOf(input) > -1;
            })
        }
        return value;
    }
}

This will filter the result based on the search term

More Info

How to get the type of a variable in MATLAB?

class() function is the equivalent of typeof()

You can also use isa() to check if a variable is of a particular type. If you want to be even more specific, you can use ischar(), isfloat(), iscell(), etc.

Split list into smaller lists (split in half)

f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)]
f(A)

n - the predefined length of result arrays

TortoiseGit-git did not exit cleanly (exit code 1)

Actually, this error message just says that there is some problem but no specifications of the problem. So, in my case, it was a pending pull request. I pulled the changes into my repo, and then pushed it again and it worked. Moreover, if there is an error on tortoisegit, I prefer to do the same on console. Console gives more detail error message

Setting the default active profile in Spring-boot

One can have separate application properties files according to the environment, if Spring Boot application is being created. For example - properties file for dev environment, application-dev.properties:

spring.hivedatasource.url=<hive dev data source url>
spring.hivedatasource.username=dev
spring.hivedatasource.password=dev
spring.hivedatasource.driver-class-name=org.apache.hive.jdbc.HiveDriver

application-test.properties:

spring.hivedatasource.url=<hive dev data source url>
spring.hivedatasource.username=test
spring.hivedatasource.password=test
spring.hivedatasource.driver-class-name=org.apache.hive.jdbc.HiveDriver

And a primary application.properties file to select the profile:

application.properties:

spring.profiles.active=dev
server.tomcat.max-threads = 10
spring.application.name=sampleApp

Define the DB Configuration as below:

@Configuration
@ConfigurationProperties(prefix="spring.hivedatasource")
public class DBConfig {

    @Profile("dev")
    @Qualifier("hivedatasource")
    @Primary
    @Bean
    public DataSource devHiveDataSource() {
        System.out.println("DataSource bean created for Dev");
        return new BasicDataSource();
    }

    @Profile("test")
    @Qualifier("hivedatasource")
    @Primary
    @Bean
    public DataSource testHiveDataSource() {
        System.out.println("DataSource bean created for Test");
        return new BasicDataSource();
    }

This will automatically create the BasicDataSource bean according to the active profile set in application.properties file. Run the Spring-boot application and test.

Note that this will create an empty bean initially until getConnection() is called. Once the connection is available you can get the url, driver-class, etc. using that DataSource bean.