Programs & Examples On #Nopcommerce

Open source E-commerce Shopping Cart Solution based on ASP.NET MVC and Entity Framework. Notable differentiators are multi-store and multi-vendor capabilities.

Assets file project.assets.json not found. Run a NuGet package restore

Try this (It worked for me):

  • Run VS as Administrator
  • Manual update NuGet to most recent version
  • Delete all bin and obj files in the project.
  • Restart VS
  • Recompile

Could not load file or assembly 'Microsoft.Web.Infrastructure,

Experienced this issue on new Windows 10 machine on VS2015 with an existing project. Package Manager 3.4.4. Restore packages enabled.

The restore doesn't seem to work completely. Had to run the following on the Package Manager Command line

Update-Package -ProjectName "YourProjectName" -Id Microsoft.Web.Infrastructure -Reinstall

This made the following changes to my solution file which the restore did NOT do.

<Reference Include="Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
  <HintPath>..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll</HintPath>
  <Private>True</Private>
</Reference>

Just adding the above elements to the ItemGroup section in you solution file will ALSO solve the issue provided that ..\packages\Microsoft.Web.Infrastructure.1.0.0.0\lib\net40\Microsoft.Web.Infrastructure.dll exist.

Easier to just do the -Reinstall but good to understand what it does differently to the package restore.

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

Attention: The other answers only work on SQL Servers with English configuration! Use SET DATEFIRST 7 to ensure DATEPART(DW, ...) returns 1 for Sunday and 7 for Saturday.

Here's a version that is independent of the local setting and does not require to use :

CREATE FUNCTION [dbo].[fct_IsDateWeekend] ( @date DATETIME )
RETURNS BIT
AS
BEGIN
    RETURN CASE WHEN DATEPART(DW, @date + @@DATEFIRST - 1) > 5  THEN 1 ELSE 0 END;
END;

If you don't want to use the function, simply use this in your SELECT statement:

CASE WHEN DATEPART(DW, YourDateTime + @@DATEFIRST - 1) > 5  THEN 'Weekend' ELSE 'Weekday' END

How to use an image for the background in tkinter?

A simple tkinter code for Python 3 for setting background image .

from tkinter import *
from tkinter import messagebox
top = Tk()

C = Canvas(top, bg="blue", height=250, width=300)
filename = PhotoImage(file = "C:\\Users\\location\\imageName.png")
background_label = Label(top, image=filename)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

C.pack()
top.mainloop

Insert Multiple Rows Into Temp Table With SQL Server 2012

When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:

SQL Fiddle

MS SQL Server 2012 Schema Setup:

Query 1:

CREATE TABLE #Names
  ( 
    Name1 VARCHAR(100),
    Name2 VARCHAR(100)
  ) 

INSERT INTO #Names
  (Name1, Name2)
VALUES
  ('Matt', 'Matthew'),
  ('Matt', 'Marshal'),
  ('Matt', 'Mattison')

SELECT * FROM #NAMES

Results:

| NAME1 |    NAME2 |
--------------------
|  Matt |  Matthew |
|  Matt |  Marshal |
|  Matt | Mattison |

Here a SSMS 2012 screenshot: enter image description here

Android: How to open a specific folder via Intent and show its content in a file browser?

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, DocumentsContract.Document.MIME_TYPE_DIR);
startActivity(intent);

Will open files app home screen enter image description here

convert string date to java.sql.Date

This works for me without throwing an exception:

package com.sandbox;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Sandbox {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date parsed = format.parse("20110210");
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
    }


}

Add/Delete table rows dynamically using JavaScript

You can add a row to a table in the most easiest way like this :-

I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .

row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;

Here #table_body is the id of the table body tag .

python 3.x ImportError: No module named 'cStringIO'

I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.

How can I convert a timestamp from yyyy-MM-ddThh:mm:ss:SSSZ format to MM/dd/yyyy hh:mm:ss.SSS format? From ISO8601 to UTC

Hope this Helps:

public String getSystemTimeInBelowFormat() {
    String timestamp = new SimpleDateFormat("yyyy-mm-dd 'T' HH:MM:SS.mmm-HH:SS").format(new Date());
    return timestamp;
}

What is the difference between Python and IPython?

There are few differences between Python and IPython but they are only the interpretation of few syntax like the few mentioned by @Ryan Chase but deep inside the true flavor of Python is maintained even in the Ipython.

The best part of the IPython is the IPython notebook. You can put all your work into a notebook like script, image files, etc. But with base Python, you can only make the script in a file and execute it.

At start, you need to understand that the IPython is developed with the intention of supporting rich media and Python script in a single integrated container.

Show only two digit after decimal

First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.

And other aspect is providing proper result. So you want to truncate the number or round it.

So before you start you should ask your self, am i interested on the value or not.

To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

I got the same error {AttributeError: 'bytes' object has no attribute 'read'} in python3. This worked for me later without using json:

from urllib.request import urlopen
from bs4 import BeautifulSoup

url = 'https://someurl/'
page = urlopen(url)
html = page.read()
soup = BeautifulSoup(html)
print(soup.prettify('latin-1'))

jQuery textbox change event

You can achieve it:

 $(document).ready(function(){              
     $('#textBox').keyup(function () {alert('changed');});
 });

or with change (handle copy paste with right click):

 $(document).ready(function(){              
     $('#textBox2').change(function () {alert('changed');});
 });

Here is Demo

Setting value of active workbook in Excel VBA

You're probably after Set wbOOR = ThisWorkbook

Just to clarify

ThisWorkbook will always refer to the workbook the code resides in

ActiveWorkbook will refer to the workbook that is active

Be careful how you use this when dealing with multiple workbooks. It really depends on what you want to achieve as to which is the best option.

Reload an iframe with jQuery

//refresh all iframes on page

var f_list = document.getElementsByTagName('iframe');

 for (var i = 0, f; f = f_list[i]; i++) {
                            f.src = f.src;
                        }

How to convert empty spaces into null values, using SQL Server?

Maybe something like this?

UPDATE [MyTable]
SET [SomeField] = NULL
WHERE [SomeField] is not NULL
AND LEN(LTRIM(RTRIM([SomeField]))) = 0

Check if file is already open

If file is in use FileOutputStream fileOutputStream = new FileOutputStream(file); returns java.io.FileNotFoundException with 'The process cannot access the file because it is being used by another process' in the exception message.

jQuery - Redirect with post data

Similar to the above answer, but written differently.

$.extend(
{
    redirectPost: function (location, args) {
        var form = $('<form>', { action: location, method: 'post' });
        $.each(args,
            function (key, value) {
                $(form).append(
                    $('<input>', { type: 'hidden', name: key, value: value })
                );
            });
        $(form).appendTo('body').submit();
    }
});

Post-increment and pre-increment within a 'for' loop produce same output

Both i++ and ++i is executed after printf("%d", i) is executed at each time, so there's no difference.

How do I get just the date when using MSSQL GetDate()?

SELECT CONVERT(DATETIME, CONVERT(varchar(10), GETDATE(), 101))

How to clear gradle cache?

In android studio open View > Tool Windows > Terminal and execute the following commands

On Windows:

gradlew cleanBuildCache

On Mac or Linux:

./gradlew cleanBuildCache

if you want to disable the cache from your project add this into the gradle build properties

(Warning: this may slow your PC performance if there is no cache than same time will consume after every time during the run app)

android.enableBuildCache=false

Finding diff between current and last version

If you want the changes for the last n commits, you can use the following:

git diff HEAD~n

So for the last 5 commits (count including your current commit) from the current commit, it would be:

git diff HEAD~5

Recommended way to get hostname in Java

Environment variables may also provide a useful means -- COMPUTERNAME on Windows, HOSTNAME on most modern Unix/Linux shells.

See: https://stackoverflow.com/a/17956000/768795

I'm using these as "supplementary" methods to InetAddress.getLocalHost().getHostName(), since as several people point out, that function doesn't work in all environments.

Runtime.getRuntime().exec("hostname") is another possible supplement. At this stage, I haven't used it.

import java.net.InetAddress;
import java.net.UnknownHostException;

// try InetAddress.LocalHost first;
//      NOTE -- InetAddress.getLocalHost().getHostName() will not work in certain environments.
try {
    String result = InetAddress.getLocalHost().getHostName();
    if (StringUtils.isNotEmpty( result))
        return result;
} catch (UnknownHostException e) {
    // failed;  try alternate means.
}

// try environment properties.
//      
String host = System.getenv("COMPUTERNAME");
if (host != null)
    return host;
host = System.getenv("HOSTNAME");
if (host != null)
    return host;

// undetermined.
return null;

Nested rows with bootstrap grid system?

Adding to what @KyleMit said, consider using:

  • col-md-* classes for the larger outer columns
  • col-xs-* classes for the smaller inner columns

This will be useful when you view the page on different screen sizes.

On a small screen, the wrapping of larger outer columns will then happen while maintaining the smaller inner columns, if possible

How can I let a user download multiple files when a button is clicked?

I've solved this a different way by using window.location. It works in Chrome, which fortunately is the only browser I had to support. Might be useful to someone. I'd initally used Dan's answer, which also needed the timeout I've used here or it only downloaded one file.

var linkArray = [];
linkArray.push("http://example.com/downloadablefile1");
linkArray.push("http://example.com/downloadablefile2");
linkArray.push("http://example.com/downloadablefile3");    

function (linkArray) {
  for (var i = 0; i < linkArray.length; i++) { 
    setTimeout(function (path) { window.location = path; }, 200 + i * 200, linkArray[i]);
  }        
};

How to disable text selection highlighting

Add a class to your CSS that defines you cannot select or highlight an element. I have an example:

<style> 
    .no_highlighting{
        user-select: none;
    }

    .anchor_without_decoration:hover{
        text-decoration-style: none;
    }
</style>

<a href="#" class="anchor_without_decoration no_highlighting">Anchor text</a>

Vertical Text Direction

I was searching for an actual vertical text and not the rotated text in HTML as shown below. So I could achieve it by using the following method.

enter image description here HTML:-

<p class="vericaltext">
Hi This is Vertical Text!
</p>

CSS:-

.vericaltext{
    width:1px;
    word-wrap: break-word;
    font-family: monospace; /* this is just for good looks */
}

JSFiddle! Demo.

Update:- If you need the whitespaces to be displayed, then add the following property to your css.

white-space: pre;

So, the css class shall be

.vericaltext{
    width:1px;
    word-wrap: break-word;
    font-family: monospace; /* this is just for good looks */
    white-space: pre;/* this is for displaying whitespaces */
}

JSFiddle! Demo With Whitespace

Update 2 (28-JUN-2015)

Since white-space: pre; doesnt seem to work (for this specific use) on Firefox(as of now), just change that line to

white-space: pre-wrap;

So, the css class shall be

.vericaltext{
    width:1px;
    word-wrap: break-word;
    font-family: monospace; /* this is just for good looks */
    white-space:pre-wrap; /* this is for displaying whitespaces including Moz-FF.*/
}

JsFiddle Demo FF Compatible.

How to set the JSTL variable value in javascript?

one more approach to use.

first, define the following somewhere on the page:

<div id="valueHolderId">${someValue}</div>

then in JS, just do something similar to

var someValue = $('#valueHolderId').html();

it works great for the cases when all scripts are inside .js files and obviously there is no jstl available

How to redirect from one URL to another URL?

Since you tagged the question with javascript and html...

For a purely HTML solution, you can use a meta tag in the header to "refresh" the page, specifying a different URL:

<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/somepage.html">

If you can/want to use JavaScript, you can set the location.href of the window:

<script type="text/javascript">
    window.location.href = "http://www.yourdomain.com/somepage.html";
</script>

Drop multiple tables in one shot in MySQL

Example:

Let's say table A has two children B and C. Then we can use the following syntax to drop all tables.

DROP TABLE IF EXISTS B,C,A;

This can be placed in the beginning of the script instead of individually dropping each table.

How can I determine if a date is between two dates in Java?

Here you go:

public static void main(String[] args) throws ParseException {

        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

        String oeStartDateStr = "04/01/";
        String oeEndDateStr = "11/14/";

        Calendar cal = Calendar.getInstance();
        Integer year = cal.get(Calendar.YEAR);

        oeStartDateStr = oeStartDateStr.concat(year.toString());
        oeEndDateStr = oeEndDateStr.concat(year.toString());

        Date startDate = sdf.parse(oeStartDateStr);
        Date endDate = sdf.parse(oeEndDateStr);
        Date d = new Date();
        String currDt = sdf.format(d);


        if((d.after(startDate) && (d.before(endDate))) || (currDt.equals(sdf.format(startDate)) ||currDt.equals(sdf.format(endDate)))){
            System.out.println("Date is between 1st april to 14th nov...");
        }
        else{
            System.out.println("Date is not between 1st april to 14th nov...");
        }
    }

java: run a function after a specific number of seconds

public static Timer t;

public synchronized void startPollingTimer() {
        if (t == null) {
            TimerTask task = new TimerTask() {
                @Override
                public void run() {
                   //Do your work
                }
            };

            t = new Timer();
            t.scheduleAtFixedRate(task, 0, 1000);
        }
    }

How to write a simple Html.DropDownListFor()?

See this MSDN article and an example usage here on Stack Overflow.

Let's say that you have the following Linq/POCO class:

public class Color
{
    public int ColorId { get; set; }
    public string Name { get; set; }
}

And let's say that you have the following model:

public class PageModel 
{
   public int MyColorId { get; set; }
}

And, finally, let's say that you have the following list of colors. They could come from a Linq query, from a static list, etc.:

public static IEnumerable<Color> Colors = new List<Color> { 
    new Color {
        ColorId = 1,
        Name = "Red"
    },
    new Color {
        ColorId = 2,
        Name = "Blue"
    }
};

In your view, you can create a drop down list like so:

<%= Html.DropDownListFor(n => n.MyColorId, 
                         new SelectList(Colors, "ColorId", "Name")) %>

Upload artifacts to Nexus, without Maven

You can use curl instead.

version=1.2.3
artifact="artifact"
repoId=repositoryId
groupId=org/myorg
REPO_URL=http://localhost:8081/nexus

curl -u username:password --upload-file filename.tgz $REPO_URL/content/repositories/$repoId/$groupId/$artefact/$version/$artifact-$version.tgz

How to declare a inline object with inline variables without a parent class

You can also declare 'x' with the keyword var:

var x = new
{
  driver = new
  {
    firstName = "john",
    lastName = "walter"
  },
  car = new
  {
    brand = "BMW"
  }
};

This will allow you to declare your x object inline, but you will have to name your 2 anonymous objects, in order to access them. You can have an array of "x" :

x.driver.firstName // "john"
x.car.brand // "BMW"

var y = new[] { x, x, x, x };
y[1].car.brand; // "BMW"

How to compare only date components from DateTime in EF?

You can also use this:

DbFunctions.DiffDays(date1, date2) == 0

How do I minimize the command prompt from my bat file

One option is to find one of the various utilities that can change the window state of the currently running console window and make a call to it from within the batch script.

You can run it as the first thing in your batch script. Here are two such tools:

min.exe http://www.paulsadowski.com/wsh/cmdprogs.htm

cmdow http://www.commandline.co.uk/cmdow/index.html

Java Error: "Your security settings have blocked a local application from running"

My problem case was to run portecle.jnlp file locally using Java8.

What worked for me was

  1. Start Programs --> Java --> Configure Java...
  2. Go to Security --> Edit Site List...
  3. Add http://portecle.sourceforce.net
  4. Start javaws portecle.jnlp in CMD prompt

On step 3, you might try also to add file:///c:/path/portecle.jnlp, but this addition didn't help with my case.

Want to upgrade project from Angular v5 to Angular v6

I had to re-run ng update @angular/cli for angular-cli.json to be changed to angular.json

Finding element in XDocument?

The problem is that Elements only takes the direct child elements of whatever you call it on. If you want all descendants, use the Descendants method:

var query = from c in xmlFile.Descendants("Band")

How to select data from 30 days?

You should be using DATEADD is Sql server so if try this simple select you will see the affect

Select DATEADD(Month, -1, getdate())

Result

2013-04-20 14:08:07.177

in your case try this query

SELECT name
FROM (
SELECT name FROM 
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM 
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name

Object cannot be cast from DBNull to other types

I suspect that the line

DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));

is causing the problem. Is it possible that the op_Id value is being set to null by the stored procedure?

To Guard against it use the Convert.IsDBNull method. For example:

if (!Convert.IsDBNull(dataAccCom.GetParameterValue(IDbCmd, "op_Id"))
{
 DataTO.Id = Convert.ToInt64(dataAccCom.GetParameterValue(IDbCmd, "op_Id"));
}
else 
{
 DataTO.Id = ...some default value or perform some error case management
}

What is the difference between the kernel space and the user space?

The really simplified answer is that the kernel runs in kernel space, and normal programs run in user space. User space is basically a form of sand-boxing -- it restricts user programs so they can't mess with memory (and other resources) owned by other programs or by the OS kernel. This limits (but usually doesn't entirely eliminate) their ability to do bad things like crashing the machine.

The kernel is the core of the operating system. It normally has full access to all memory and machine hardware (and everything else on the machine). To keep the machine as stable as possible, you normally want only the most trusted, well-tested code to run in kernel mode/kernel space.

The stack is just another part of memory, so naturally it's segregated right along with the rest of memory.

What does "pending" mean for request in Chrome Developer Window?

I also get this when using the HTTPS everywhere plugin. This plugin has a list of sites that also have https instead of http. So I assume before the actual request is made it is already being cancelled somehow.

So for example when I go to http://stackexchange.com, in Developer I first see a request with status (terminated). This request has some headers, but only the GET, User-Agent, and Accept. No response as well.

Then there is request to https://stackexchange.com with full headers etc.

So I assume it is used for requests that aren't sent.

ModelState.IsValid == false, why?

Paste the below code in the ActionResult of your controller and place the debugger at this point.

var errors = ModelState
    .Where(x => x.Value.Errors.Count > 0)
    .Select(x => new { x.Key, x.Value.Errors })
    .ToArray();

Convert file path to a file URI?

The System.Uri constructor has the ability to parse full file paths and turn them into URI style paths. So you can just do the following:

var uri = new System.Uri("c:\\foo");
var converted = uri.AbsoluteUri;

Delete a row in DataGridView Control in VB.NET

Assuming you are using Windows forms, you could allow the user to select a row and in the delete key click event. It is recommended that you allow the user to select 1 row only and not a group of rows (myDataGridView.MultiSelect = false)

Private Sub pbtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If myDataGridView.SelectedRows.Count > 0 Then
            'you may want to add a confirmation message, and if the user confirms delete
            myDataGridView.Rows.Remove(myDataGridView.SelectedRows(0))
        Else
            MessageBox.Show("Select 1 row before you hit Delete")
        End If

    End Sub

Note that this will not delete the row form the database until you perform the delete in the database.

Reset ID autoincrement ? phpmyadmin

I agree with rpd, this is the answer and can be done on a regular basis to clean up your id column that is getting bigger with only a few hundred rows of data, but maybe an id of 34444543!, as the data is deleted out regularly but id is incremented automatically.

ALTER TABLE users DROP id

The above sql can be run via sql query or as php. This will delete the id column.

Then re add it again, via the code below:

ALTER TABLE  `users` ADD `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST

Place this in a piece of code that may get run maybe in an admin panel, so when anyone enters that page it will run this script that auto cleans your database, and tidys it.

Return only string message from Spring MVC 3 Controller

@ResponseBody
@RequestMapping(value="/get-text", produces="text/plain")
public String myMethod() {
     return "Response!";
}
  • You see that @ResponseBody ?

It's telling that the method returns some text and not to interpret it as a view etc.

  • You see that produces="text/plain" ?

It's just a good practice as it tells what will be returned from the method :)

Download files from server php

To read directory contents you can use readdir() and use a script, in my example download.php, to download files

if ($handle = opendir('/path/to/your/dir/')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<a href='download.php?file=".$entry."'>".$entry."</a>\n";
        }
    }
    closedir($handle);
}

In download.php you can force browser to send download data, and use basename() to make sure client does not pass other file name like ../config.php

$file = basename($_GET['file']);
$file = '/path/to/your/dir/'.$file;

if(!file_exists($file)){ // file does not exist
    die('file not found');
} else {
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: application/zip");
    header("Content-Transfer-Encoding: binary");

    // read the file from disk
    readfile($file);
}

java : non-static variable cannot be referenced from a static context Error

The simplest change would be something like this:

public static void main (String[] args) throws Exception {
  testconnect obj = new testconnect();
  obj.con2 = DriverManager.getConnection(obj.getConnectionUrl2());
  obj.con2.close();
}

Switch case: can I use a range instead of a one number

You can use if-else statements with || operators (or-operator) like:

if(case1 == true || case2 == true || case3 == true)
   {
    Do this!... 
   }
else if(case4 == true || case5 == true || case6 == true)
   {
    Do this!... 
   }
else if(case7 == true || case8 == true || case9 == true)
   {
    Do this!... 
   }

How to construct a set out of list items in python?

If you have a list of hashable objects (filenames would probably be strings, so they should count):

lst = ['foo.py', 'bar.py', 'baz.py', 'qux.py', Ellipsis]

you can construct the set directly:

s = set(lst)

In fact, set will work this way with any iterable object! (Isn't duck typing great?)


If you want to do it iteratively:

s = set()
for item in iterable:
    s.add(item)

But there's rarely a need to do it this way. I only mention it because the set.add method is quite useful.

In android how to set navigation drawer header image and name programmatically in class file?

Here is the method you can use to get header view and set data accourdingly

val headerView: View? = navigationView.getHeaderView(0) // Index of the added headerView  

// Now you can access child views of the header view
val titleTextView: TextView? = headerView?.findViewById(R.id.titleTextView)

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

Go to the Design, right click on your Widget, Constraint Layout >> Infer Constraints. You can observe that some code has been automatically added to your Text.

Invalid postback or callback argument. Event validation is enabled using '<pages enableEventValidation="true"/>'

I was using datalist and I was getting the same error for my push button. I just use IsPostBack to check and fill my controls and the problem is solved! Great!!!

Why and when to use angular.copy? (Deep Copy)

I am just sharing my experience here, I used angular.copy() for comparing two objects properties. I was working on a number of inputs without form element, I was wondering how to compare two objects properties and based on result I have to enable and disable the save button. So I used as below.

I assigned an original server object user values to my dummy object to say userCopy and used watch to check changes to the user object.

My server API which gets me data from the server:

var req = {
    method: 'GET',
    url: 'user/profile/' + id,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}
$http(req).success(function(data) {
    $scope.user = data;
    $scope.userCopy = angular.copy($scope.user);
    $scope.btnSts=true;
}).error(function(data) {
    $ionicLoading.hide();
});

//initially my save button is disabled because objects are same, once something 
//changes I am activating save button

$scope.btnSts = true;
$scope.$watch('user', function(newVal, oldVal) {
    console.log($scope.userCopy.name);

    if ($scope.userCopy.name !== $scope.user.name || $scope.userCopy.email !== $scope.user.email) {
        console.log('Changed');
        $scope.btnSts = false;
    } else {
        console.log('Unchanged');
        $scope.btnSts = true;
    }    
}, true);

I am not sure but comparing two objects was really headache for me always but with angular.copy() it went smoothly.

How to combine multiple inline style objects?

    const style1 = {
        backgroundColor: "#2196F3", 
    }
    
    const style2 = {
        color: "white", 
    }

    const someComponent = () => {
        return <div style={{ ...style1, ...style2 }}>This has 2 separate styles</div> 
    }
    

Note the double curly brackets. The spread operator is your friend.

How to get tf.exe (TFS command line client)?

You need to install Team Explorer, it's best to install the version of Team Explorer that matches the version of TFS you are using e.g. if you're using TFS 2010 then install Team Explorer 2010.

2012 version http://www.microsoft.com/en-gb/download/details.aspx?id=30656

2013 version http://www.microsoft.com/en-us/download/details.aspx?id=40776

2019 version https://visualstudio.microsoft.com/thank-you-downloading-visual-studio/?sku=TeamExplorer&rel=16

You also might be interested in the TFS power tools. They add some extra command line features (using tfpt.exe) and also add some extra IDE features.

Getting Integer value from a String using javascript/jquery

just do this , you need to remove char other than "numeric" and "." form your string will do work for you

yourString = yourString.replace ( /[^\d.]/g, '' );

your final code will be

  str1 = "test123.00".replace ( /[^\d.]/g, '' );
  str2 = "yes50.00".replace ( /[^\d.]/g, '' );
  total = parseInt(str1, 10) + parseInt(str2, 10);
  alert(total);

Demo

Horizontal scroll css?

I figured it this way:

* { padding: 0; margin: 0 }
body { height: 100%; white-space: nowrap }
html { height: 100% }

.red { background: red }
.blue { background: blue }
.yellow { background: yellow }

.header { width: 100%; height: 10%; position: fixed }
.wrapper { width: 1000%; height: 100%; background: green }
.page { width: 10%; height: 100%; float: left }

<div class="header red"></div>
<div class="wrapper">
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
</div>

I have the wrapper at 1000% and ten pages at 10% each. I set mine up to still have "pages" with each being 100% of the window (color coded). You can do eight pages with an 800% wrapper. I guess you can leave out the colors and have on continues page. I also set up a fixed header, but that's not necessary. Hope this helps.

415 Unsupported Media Type - POST json to OData service in lightswitch 2012

It looks like this issue has to do with the difference between the Content-Type and Accept headers. In HTTP, Content-Type is used in request and response payloads to convey the media type of the current payload. Accept is used in request payloads to say what media types the server may use in the response payload.

So, having a Content-Type in a request without a body (like your GET request) has no meaning. When you do a POST request, you are sending a message body, so the Content-Type does matter.

If a server is not able to process the Content-Type of the request, it will return a 415 HTTP error. (If a server is not able to satisfy any of the media types in the request Accept header, it will return a 406 error.)

In OData v3, the media type "application/json" is interpreted to mean the new JSON format ("JSON light"). If the server does not support reading JSON light, it will throw a 415 error when it sees that the incoming request is JSON light. In your payload, your request body is verbose JSON, not JSON light, so the server should be able to process your request. It just doesn't because it sees the JSON light content type.

You could fix this in one of two ways:

  1. Make the Content-Type "application/json;odata=verbose" in your POST request, or
  2. Include the DataServiceVersion header in the request and set it be less than v3. For example:

    DataServiceVersion: 2.0;
    

(Option 2 assumes that you aren't using any v3 features in your request payload.)

How to debug .htaccess RewriteRule not working

Why not put some junk in your .htaccess file and try to reload apache. If apache fails to start you know its working. Remove the junk then reload apache if it loads congrats you configured .htaccess correctly.

Is there a command to restart computer into safe mode?

In the command prompt, type the command below and press Enter.

bcdedit /enum

Under the Windows Boot Loader sections, make note of the identifier value.

To start in safe mode from command prompt :

bcdedit /set {identifier} safeboot minimal 

Then enter the command line to reboot your computer.

React PropTypes : Allow different types of PropTypes for one prop

For documentation purpose, it's better to list the string values that are legal:

size: PropTypes.oneOfType([
    PropTypes.number,
    PropTypes.oneOf([ 'SMALL', 'LARGE' ]),
]),

YAML: Do I need quotes for strings in YAML?

After a brief review of the YAML cookbook cited in the question and some testing, here's my interpretation:

  • In general, you don't need quotes.
  • Use quotes to force a string, e.g. if your key or value is 10 but you want it to return a String and not a Fixnum, write '10' or "10".
  • Use quotes if your value includes special characters, (e.g. :, {, }, [, ], ,, &, *, #, ?, |, -, <, >, =, !, %, @, \).
  • Single quotes let you put almost any character in your string, and won't try to parse escape codes. '\n' would be returned as the string \n.
  • Double quotes parse escape codes. "\n" would be returned as a line feed character.
  • The exclamation mark introduces a method, e.g. !ruby/sym to return a Ruby symbol.

Seems to me that the best approach would be to not use quotes unless you have to, and then to use single quotes unless you specifically want to process escape codes.

Update

"Yes" and "No" should be enclosed in quotes (single or double) or else they will be interpreted as TrueClass and FalseClass values:

en:
  yesno:
    'yes': 'Yes'
    'no': 'No'

How to set python variables to true or false?

match_var = a==b

that should more than suffice

you cant use a - in a variable name as it thinks that is match (minus) var

match=1
var=2

print match-var  #prints -1

Printing a 2D array in C

First you need to input the two numbers say num_rows and num_columns perhaps using argc and argv then do a for loop to print the dots.

int j=0;
int k=0;
for (k=0;k<num_columns;k++){
   for (j=0;j<num_rows;j++){
       printf(".");
   }
 printf("\n");
 }

you'd have to replace the dot with something else later.

How to check for registry value using VbScript

Try something like this:

Dim windowsShell
Dim regValue
Set windowsShell = CreateObject("WScript.Shell")
regValue = windowsShell.RegRead("someRegKey")

Uploading Images to Server android

Try this method for uploading Image file from camera

package com.example.imageupload;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.message.BasicHeader;

public class MultipartEntity implements HttpEntity {

private String boundary = null;

ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;

public MultipartEntity() {
    this.boundary = System.currentTimeMillis() + "";
}

public void writeFirstBoundaryIfNeeds() {
    if (!isSetFirst) {
        try {
            out.write(("--" + boundary + "\r\n").getBytes());
        } catch (final IOException e) {

        }
    }
    isSetFirst = true;
}

public void writeLastBoundaryIfNeeds() {
    if (isSetLast) {
        return;
    }
    try {
        out.write(("\r\n--" + boundary + "--\r\n").getBytes());
    } catch (final IOException e) {

    }
    isSetLast = true;
}

public void addPart(final String key, final String value) {
    writeFirstBoundaryIfNeeds();
    try {
        out.write(("Content-Disposition: form-data; name=\"" + key + "\"\r\n")
                .getBytes());
        out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
        out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
        out.write(value.getBytes());
        out.write(("\r\n--" + boundary + "\r\n").getBytes());
    } catch (final IOException e) {

    }
}

public void addPart(final String key, final String fileName,
        final InputStream fin) {
    addPart(key, fileName, fin, "application/octet-stream");
}

public void addPart(final String key, final String fileName,
        final InputStream fin, String type) {
    writeFirstBoundaryIfNeeds();
    try {
        type = "Content-Type: " + type + "\r\n";
        out.write(("Content-Disposition: form-data; name=\"" + key
                + "\"; filename=\"" + fileName + "\"\r\n").getBytes());
        out.write(type.getBytes());
        out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());

        final byte[] tmp = new byte[4096];
        int l = 0;
        while ((l = fin.read(tmp)) != -1) {
            out.write(tmp, 0, l);
        }
        out.flush();
    } catch (final IOException e) {

    } finally {
        try {
            fin.close();
        } catch (final IOException e) {

        }
    }
}

public void addPart(final String key, final File value) {
    try {
        addPart(key, value.getName(), new FileInputStream(value));
    } catch (final FileNotFoundException e) {

    }
}

public long getContentLength() {
    writeLastBoundaryIfNeeds();
    return out.toByteArray().length;
}

public Header getContentType() {
    return new BasicHeader("Content-Type", "multipart/form-data; boundary="
            + boundary);
}

public boolean isChunked() {
    return false;
}

public boolean isRepeatable() {
    return false;
}

public boolean isStreaming() {
    return false;
}

public void writeTo(final OutputStream outstream) throws IOException {
    outstream.write(out.toByteArray());
}

public Header getContentEncoding() {
    return null;
}

public void consumeContent() throws IOException,
        UnsupportedOperationException {
    if (isStreaming()) {
        throw new UnsupportedOperationException(
                "Streaming entity does not implement #consumeContent()");
    }
}

public InputStream getContent() throws IOException,
        UnsupportedOperationException {
    return new ByteArrayInputStream(out.toByteArray());
}

}

Use of class for uploading

private void doFileUpload(File file_path) {

    Log.d("Uri", "Do file path" + file_path);

    try {

        HttpClient client = new DefaultHttpClient();
        //use your server path of php file
        HttpPost post = new HttpPost(ServerUploadPath);

        Log.d("ServerPath", "Path" + ServerUploadPath);

        FileBody bin1 = new FileBody(file_path);
        Log.d("Enter", "Filebody complete " + bin1);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("uploaded_file", bin1);
        reqEntity.addPart("email", new StringBody(useremail));

        post.setEntity(reqEntity);
        Log.d("Enter", "Image send complete");

        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        Log.d("Enter", "Get Response");
        try {

            final String response_str = EntityUtils.toString(resEntity);
            if (resEntity != null) {
                Log.i("RESPONSE", response_str);
                JSONObject jobj = new JSONObject(response_str);
                result = jobj.getString("ResponseCode");
                Log.e("Result", "...." + result);

            }
        } catch (Exception ex) {
            Log.e("Debug", "error: " + ex.getMessage(), ex);
        }
    } catch (Exception e) {
        Log.e("Upload Exception", "");
        e.printStackTrace();
    }
}

Service for uploading

   <?php
$image_name = $_FILES["uploaded_file"]["name"]; 
$tmp_arr = explode(".",$image_name);
$img_extn = end($tmp_arr);
$new_image_name = 'image_'. uniqid() .'.'.$img_extn;    
$flag=0;                 

if (file_exists("Images/".$new_image_name))
{
           $msg=$new_image_name . " already exists."
           header('Content-type: application/json');        
           echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=>$msg));        
}else{  
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],"Images/". $new_image_name);
                   $flag = 1;
}   

if($flag == 1){                    
            require 'db.php';   
            $static_url =$new_image_name;
            $conn=mysql_connect($db_host,$db_username,$db_password) or die("unable to connect localhost".mysql_error());
            $db=mysql_select_db($db_database,$conn) or die("unable to select message_app"); 
            $email = "";
            if((isset($_REQUEST['email'])))
            {
                     $email = $_REQUEST['email'];
            }

    $sql ="insert into alert(images) values('$static_url')";

     $result=mysql_query($sql);

     if($result){
    echo json_encode(array("ResponseCode"=>"1","ResponseMsg"=> "Insert data successfully.","Result"=>"True","ImageName"=>$static_url,"email"=>$email));
       } else
       {

         echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Could not insert data.","Result"=>"False","email"=>$email));
        }
}
    else{
    echo json_encode(array("ResponseCode"=>"2","ResponseMsg"=> "Erroe While Inserting Image.","Result"=>"False"));
    }
    ?>

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

Remove all subviews?

Try this way swift 2.0

view.subviews.forEach { $0.removeFromSuperview() }

Pandas read_csv from url

As I commented you need to use a StringIO object and decode i.e c=pd.read_csv(io.StringIO(s.decode("utf-8"))) if using requests, you need to decode as .content returns bytes if you used .text you would just need to pass s as is s = requests.get(url).text c = pd.read_csv(StringIO(s)).

A simpler approach is to pass the correct url of the raw data directly to read_csv, you don't have to pass a file like object, you can pass a url so you don't need requests at all:

c = pd.read_csv("https://raw.githubusercontent.com/cs109/2014_data/master/countries.csv")

print(c)

Output:

                              Country         Region
0                             Algeria         AFRICA
1                              Angola         AFRICA
2                               Benin         AFRICA
3                            Botswana         AFRICA
4                             Burkina         AFRICA
5                             Burundi         AFRICA
6                            Cameroon         AFRICA
..................................

From the docs:

filepath_or_buffer :

string or file handle / StringIO The string could be a URL. Valid URL schemes include http, ftp, s3, and file. For file URLs, a host is expected. For instance, a local file could be file ://localhost/path/to/table.csv

How to destroy a JavaScript object?

Structure your code so that all your temporary objects are located inside closures instead of global namespace / global object properties and go out of scope when you've done with them. GC will take care of the rest.

How to correctly assign a new string value?

The two structs are different. When you initialize the first struct, about 40 bytes of memory are allocated. When you initialize the second struct, about 10 bytesof memory are allocated. (Actual amount is architecture dependent)

You can use the string literals (string constants) to initalize character arrays. This is why

person p = {"John", "Doe",30};

works in the first example.

You cannot assign (in the conventional sense) a string in C.

The string literals you have ("John") are loaded into memory when your code executes. When you initialize an array with one of these literals, then the string is copied into a new memory location. In your second example, you are merely copying the pointer to (location of) the string literal. Doing something like:

char* string = "Hello";
*string = 'C'

might cause compile or runtime errors (I am not sure.) It is a bad idea because you are modifying the literal string "Hello" which, for example on a microcontroler, could be located in read-only memory.

Clear input fields on form submit

You can access the form over the event:

e.target.reset();

How to load all modules in a folder?

Add the __all__ Variable to __init__.py containing:

__all__ = ["bar", "spam", "eggs"]

See also http://docs.python.org/tutorial/modules.html

How to run an awk commands in Windows?

If you want to avoid including the full path to awk, you need to update your PATH variable to include the path to the directory where awk is located, then you can just type

awk

to run your programs.

Go to Control Panel->System->Advanced and set your PATH environment variable to include "C:\Program Files (x86)\GnuWin32\bin" at the end (separated by a semi-colon) from previous entry. enter image description here

parent & child with position fixed, parent overflow:hidden bug

I had a similar, quite complex problem with a fluid layout, where the right column had a fixed width and the left one had a flexible width. My fixed container should have the same width as the flexible column. Here is my solution:

HTML

<div id="wrapper">
    <div id="col1">
    <div id="fixed-outer">
        <div id="fixed-inner">inner</div>
    </div>
    COL1<br />Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
    </div>
    <div id="col2">COL2</div>
</div>

CSS

    #wrapper {
    padding-left: 20px;
}

#col1 {
    background-color: grey;
    float: left;
    margin-right: -200px; /* #col2 width */
    width: 100%;
}

#col2 {
    background-color: #ddd;
    float: left;
    height: 400px;
    width: 200px;
}

#fixed-outer {
    background: yellow;
    border-right: 2px solid red;
    height: 30px;
    margin-left: -420px; /* 2x #col2 width + #wrapper padding-left */
    overflow: hidden;
    padding-right: 200px; /* #col2 width */
    position: fixed;
    width: 100%;
}

#fixed-inner {
    background: orange;
    border-left: 2px solid blue;
    border-top: 2px solid blue;
    height: 30px;
    margin-left: 420px; /* 2x #col2 width + #wrapper padding-left */
    position: absolute;
    width: 100%;
}

Live Demo: http://jsfiddle.net/hWCub/

Running multiple commands with xargs

This is just another approach without xargs nor cat:

while read stuff; do
  command1 "$stuff"
  command2 "$stuff"
  ...
done < a.txt

Equivalent of .bat in mac os

The common convention would be to put it in a .sh file that looks like this -

#!/bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;... etc

Note that '\' become '/'.

You could execute as

sh myfile.sh

or set the x bit on the file

chmod +x myfile.sh

and then just call

myfile.sh

Update Git submodule to latest commit on origin

Your main project points to a particular commit that the submodule should be at. git submodule update tries to check out that commit in each submodule that has been initialized. The submodule is really an independent repository - just creating a new commit in the submodule and pushing that isn't enough. You also need to explicitly add the new version of the submodule in the main project.

So, in your case, you should find the right commit in the submodule - let's assume that's the tip of master:

cd mod
git checkout master
git pull origin master

Now go back to the main project, stage the submodule and commit that:

cd ..
git add mod
git commit -m "Updating the submodule 'mod' to the latest version"

Now push your new version of the main project:

git push origin master

From this point on, if anyone else updates their main project, then git submodule update for them will update the submodule, assuming it's been initialized.

How to do sed like text replace with python?

If I want something like sed, then I usually just call sed itself using the sh library.

from sh import sed

sed(['-i', 's/^# deb/deb/', '/etc/apt/sources.list'])

Sure, there are downsides. Like maybe the locally installed version of sed isn't the same as the one you tested with. In my cases, this kind of thing can be easily handled at another layer (like by examining the target environment beforehand, or deploying in a docker image with a known version of sed).

Checking if output of a command contains a certain string in a shell script

A clean if/else conditional shell script:

if ./somecommand | grep -q 'some_string'; then
  echo "exists"
else
  echo "doesn't exist"
fi

TSQL Default Minimum DateTime

I think this would work...

create table atable
(
  atableID int IDENTITY(1, 1) PRIMARY KEY CLUSTERED,
  Modified datetime DEFAULT ((0))
)

Edit: This is wrong...The minimum SQL DateTime Value is 1/1/1753. My solution provides a datetime = 1/1/1900 00:00:00. Other answers have the correct minimum date...

Java: Convert String to TimeStamp

The easy way to convert String to java.sql.Timestamp:

Timestamp t = new Timestamp(DateUtil.provideDateFormat().parse("2019-01-14T12:00:00.000Z").getTime());

DateUtil.java:

import java.text.SimpleDateFormat;
import java.util.TimeZone;

public interface DateUtil {

  String ISO_DATE_FORMAT_ZERO_OFFSET = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'";
  String UTC_TIMEZONE_NAME = "UTC";

  static SimpleDateFormat provideDateFormat() {
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat(ISO_DATE_FORMAT_ZERO_OFFSET);
    simpleDateFormat.setTimeZone(TimeZone.getTimeZone(UTC_TIMEZONE_NAME));
    return simpleDateFormat;
  }
}

while-else-loop

Am I missing something?

Doesn't this hypothetical code

while(rowIndex >= dataColLinker.size()) {
    dataColLinker.add(value);
} else {
    dataColLinker.set(rowIndex, value);
}

mean the same thing as this?

while(rowIndex >= dataColLinker.size()) {
    dataColLinker.add(value);
}
dataColLinker.set(rowIndex, value);

or this?

if (rowIndex >= dataColLinker.size()) {
    do {
        dataColLinker.add(value);
    } while(rowIndex >= dataColLinker.size());
} else {
    dataColLinker.set(rowIndex, value);
}

(The latter makes more sense ... I guess). Either way, it is obvious that you can rewrite the loop so that the "else test" is not repeated inside the loop ... as I have just done.


FWIW, this is most likely a case of premature optimization. That is, you are probably wasting your time optimizing code that doesn't need to be optimized:

  • For all you know, the JIT compiler's optimizer may have already moved the code around so that the "else" part is no longer in the loop.

  • Even if it hasn't, the chances are that the particular thing you are trying to optimize is not a significant bottleneck ... even if it might be executed 600,000 times.

My advice is to forget this problem for now. Get the program working. When it is working, decide if it runs fast enough. If it doesn't then profile it, and use the profiler output to decide where it is worth spending your time optimizing.

Execute a stored procedure in another stored procedure in SQL server

Procedure example:

Create  PROCEDURE SP_Name
     @UserName nvarchar(200),
     @Password nvarchar(200)
AS
BEGIN
    DECLARE  @loginID  int

    --Statements for this Store Proc
  --
  -- 
  --

  --execute second store procedure
  --below line calling sencond Store Procedure Exec is used for execute Store Procedure.
    **Exec SP_Name_2 @params** (if any) 


END

Efficient Algorithm for Bit Reversal (from MSB->LSB to LSB->MSB) in C

I know it isn't C but asm:

var1 dw 0f0f0
clc
     push ax
     push cx
     mov cx 16
loop1:
     shl var1
     shr ax
loop loop1
     pop ax
     pop cx

This works with the carry bit, so you may save flags too

Page unload event in asp.net

There is an event Page.Unload. At that moment page is already rendered in HTML and HTML can't be modified. Still, all page objects are available.

Cancel a vanilla ECMAScript 6 Promise chain

Here's our implementation https://github.com/permettez-moi-de-construire/cancellable-promise

Used like

const {
  cancellablePromise,
  CancelToken,
  CancelError
} = require('@permettezmoideconstruire/cancellable-promise')

const cancelToken = new CancelToken()

const initialPromise = SOMETHING_ASYNC()
const wrappedPromise = cancellablePromise(initialPromise, cancelToken)


// Somewhere, cancel the promise...
cancelToken.cancel()


//Then catch it
wrappedPromise
.then((res) => {
  //Actual, usual fulfill
})
.catch((err) => {
  if(err instanceOf CancelError) {
    //Handle cancel error
  }

  //Handle actual, usual error
})

which :

  • Doesn't touch Promise API
  • Let us make further cancellation inside catch call
  • Rely on cancellation being rejected instead of resolved unlike any other proposal or implementation

Pulls and comments welcome

Escape text for HTML

using System.Web;

var encoded = HttpUtility.HtmlEncode(unencoded);

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

code:

// Create Directory if not exist then Copy a file.


public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {

    Path FROM = Paths.get(origin);
    Path TO = Paths.get(destination);
    File directory = new File(String.valueOf(destDir));

    if (!directory.exists()) {
        directory.mkdir();
    }
        //overwrite the destination file if it exists, and copy
        // the file attributes, including the rwx permissions
     CopyOption[] options = new CopyOption[]{
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES

        };
        Files.copy(FROM, TO, options);


}

How to convert integer timestamp to Python datetime

datetime.datetime.fromtimestamp() is correct, except you are probably having timestamp in miliseconds (like in JavaScript), but fromtimestamp() expects Unix timestamp, in seconds.

Do it like that:

>>> import datetime
>>> your_timestamp = 1331856000000
>>> date = datetime.datetime.fromtimestamp(your_timestamp / 1e3)

and the result is:

>>> date
datetime.datetime(2012, 3, 16, 1, 0)

Does it answer your question?

EDIT: J.F. Sebastian correctly suggested to use true division by 1e3 (float 1000). The difference is significant, if you would like to get precise results, thus I changed my answer. The difference results from the default behaviour of Python 2.x, which always returns int when dividing (using / operator) int by int (this is called floor division). By replacing the divisor 1000 (being an int) with the 1e3 divisor (being representation of 1000 as float) or with float(1000) (or 1000. etc.), the division becomes true division. Python 2.x returns float when dividing int by float, float by int, float by float etc. And when there is some fractional part in the timestamp passed to fromtimestamp() method, this method's result also contains information about that fractional part (as the number of microseconds).

Call js-function using JQuery timer

Might want to check out jQuery Timer to manage one or multiple timers.

http://code.google.com/p/jquery-timer/

var timer = $.timer(yourfunction, 10000);

function yourfunction() { alert('test'); }

Then you can control it with:

timer.play();
timer.pause();
timer.toggle();
timer.once();
etc...

Locate current file in IntelliJ

And make it autoscrollable from source without hitting shortcuts every time How to make Scroll From Source feature always enabled?

Resize svg when window is resized in d3.js

Use window.onresize:

function updateWindow(){
    x = w.innerWidth || e.clientWidth || g.clientWidth;
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;

    svg.attr("width", x).attr("height", y);
}
d3.select(window).on('resize.updatesvg', updateWindow);

http://jsfiddle.net/Zb85u/1/

JavaScript single line 'if' statement - best syntax, this alternative?

// Another simple example

 var a = 11;
 a == 10 ? alert("true") : alert("false");

How do I vertically align text in a div?

The correct way to do this in modern browsers is to use Flexbox.

See this answer for details.

See below for some older ways that work in older browsers.


Vertical Centering in CSS
http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

Article summary:

For a CSS 2 browser, one can use display:table/display:table-cell to center content.

A sample is also available at JSFiddle:

_x000D_
_x000D_
div { border:1px solid green;}
_x000D_
<div style="display: table; height: 400px; overflow: hidden;">
  <div style="display: table-cell; vertical-align: middle;">
    <div>
      everything is vertically centered in modern IE8+ and others.
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

It is possible to merge hacks for old browsers (Internet Explorer 6/7) into styles with using # to hide styles from newer browsers:

_x000D_
_x000D_
div { border:1px solid green;}
_x000D_
<div style="display: table; height: 400px; #position: relative; overflow: hidden;">
  <div style=
    "#position: absolute; #top: 50%;display: table-cell; vertical-align: middle;">
    <div style=" #position: relative; #top: -50%">
      everything is vertically centered
    </div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

HTML5 record audio to file

The code shown below is copyrighted to Matt Diamond and available for use under MIT license. The original files are here:

Save this files and use

_x000D_
_x000D_
(function(window){_x000D_
_x000D_
      var WORKER_PATH = 'recorderWorker.js';_x000D_
      var Recorder = function(source, cfg){_x000D_
        var config = cfg || {};_x000D_
        var bufferLen = config.bufferLen || 4096;_x000D_
        this.context = source.context;_x000D_
        this.node = this.context.createScriptProcessor(bufferLen, 2, 2);_x000D_
        var worker = new Worker(config.workerPath || WORKER_PATH);_x000D_
        worker.postMessage({_x000D_
          command: 'init',_x000D_
          config: {_x000D_
            sampleRate: this.context.sampleRate_x000D_
          }_x000D_
        });_x000D_
        var recording = false,_x000D_
          currCallback;_x000D_
_x000D_
        this.node.onaudioprocess = function(e){_x000D_
          if (!recording) return;_x000D_
          worker.postMessage({_x000D_
            command: 'record',_x000D_
            buffer: [_x000D_
              e.inputBuffer.getChannelData(0),_x000D_
              e.inputBuffer.getChannelData(1)_x000D_
            ]_x000D_
          });_x000D_
        }_x000D_
_x000D_
        this.configure = function(cfg){_x000D_
          for (var prop in cfg){_x000D_
            if (cfg.hasOwnProperty(prop)){_x000D_
              config[prop] = cfg[prop];_x000D_
            }_x000D_
          }_x000D_
        }_x000D_
_x000D_
        this.record = function(){_x000D_
       _x000D_
          recording = true;_x000D_
        }_x000D_
_x000D_
        this.stop = function(){_x000D_
        _x000D_
          recording = false;_x000D_
        }_x000D_
_x000D_
        this.clear = function(){_x000D_
          worker.postMessage({ command: 'clear' });_x000D_
        }_x000D_
_x000D_
        this.getBuffer = function(cb) {_x000D_
          currCallback = cb || config.callback;_x000D_
          worker.postMessage({ command: 'getBuffer' })_x000D_
        }_x000D_
_x000D_
        this.exportWAV = function(cb, type){_x000D_
          currCallback = cb || config.callback;_x000D_
          type = type || config.type || 'audio/wav';_x000D_
          if (!currCallback) throw new Error('Callback not set');_x000D_
          worker.postMessage({_x000D_
            command: 'exportWAV',_x000D_
            type: type_x000D_
          });_x000D_
        }_x000D_
_x000D_
        worker.onmessage = function(e){_x000D_
          var blob = e.data;_x000D_
          currCallback(blob);_x000D_
        }_x000D_
_x000D_
        source.connect(this.node);_x000D_
        this.node.connect(this.context.destination);    //this should not be necessary_x000D_
      };_x000D_
_x000D_
      Recorder.forceDownload = function(blob, filename){_x000D_
        var url = (window.URL || window.webkitURL).createObjectURL(blob);_x000D_
        var link = window.document.createElement('a');_x000D_
        link.href = url;_x000D_
        link.download = filename || 'output.wav';_x000D_
        var click = document.createEvent("Event");_x000D_
        click.initEvent("click", true, true);_x000D_
        link.dispatchEvent(click);_x000D_
      }_x000D_
_x000D_
      window.Recorder = Recorder;_x000D_
_x000D_
    })(window);_x000D_
_x000D_
    //ADDITIONAL JS recorderWorker.js_x000D_
    var recLength = 0,_x000D_
      recBuffersL = [],_x000D_
      recBuffersR = [],_x000D_
      sampleRate;_x000D_
    this.onmessage = function(e){_x000D_
      switch(e.data.command){_x000D_
        case 'init':_x000D_
          init(e.data.config);_x000D_
          break;_x000D_
        case 'record':_x000D_
          record(e.data.buffer);_x000D_
          break;_x000D_
        case 'exportWAV':_x000D_
          exportWAV(e.data.type);_x000D_
          break;_x000D_
        case 'getBuffer':_x000D_
          getBuffer();_x000D_
          break;_x000D_
        case 'clear':_x000D_
          clear();_x000D_
          break;_x000D_
      }_x000D_
    };_x000D_
_x000D_
    function init(config){_x000D_
      sampleRate = config.sampleRate;_x000D_
    }_x000D_
_x000D_
    function record(inputBuffer){_x000D_
_x000D_
      recBuffersL.push(inputBuffer[0]);_x000D_
      recBuffersR.push(inputBuffer[1]);_x000D_
      recLength += inputBuffer[0].length;_x000D_
    }_x000D_
_x000D_
    function exportWAV(type){_x000D_
      var bufferL = mergeBuffers(recBuffersL, recLength);_x000D_
      var bufferR = mergeBuffers(recBuffersR, recLength);_x000D_
      var interleaved = interleave(bufferL, bufferR);_x000D_
      var dataview = encodeWAV(interleaved);_x000D_
      var audioBlob = new Blob([dataview], { type: type });_x000D_
_x000D_
      this.postMessage(audioBlob);_x000D_
    }_x000D_
_x000D_
    function getBuffer() {_x000D_
      var buffers = [];_x000D_
      buffers.push( mergeBuffers(recBuffersL, recLength) );_x000D_
      buffers.push( mergeBuffers(recBuffersR, recLength) );_x000D_
      this.postMessage(buffers);_x000D_
    }_x000D_
_x000D_
    function clear(){_x000D_
      recLength = 0;_x000D_
      recBuffersL = [];_x000D_
      recBuffersR = [];_x000D_
    }_x000D_
_x000D_
    function mergeBuffers(recBuffers, recLength){_x000D_
      var result = new Float32Array(recLength);_x000D_
      var offset = 0;_x000D_
      for (var i = 0; i < recBuffers.length; i++){_x000D_
        result.set(recBuffers[i], offset);_x000D_
        offset += recBuffers[i].length;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function interleave(inputL, inputR){_x000D_
      var length = inputL.length + inputR.length;_x000D_
      var result = new Float32Array(length);_x000D_
_x000D_
      var index = 0,_x000D_
        inputIndex = 0;_x000D_
_x000D_
      while (index < length){_x000D_
        result[index++] = inputL[inputIndex];_x000D_
        result[index++] = inputR[inputIndex];_x000D_
        inputIndex++;_x000D_
      }_x000D_
      return result;_x000D_
    }_x000D_
_x000D_
    function floatTo16BitPCM(output, offset, input){_x000D_
      for (var i = 0; i < input.length; i++, offset+=2){_x000D_
        var s = Math.max(-1, Math.min(1, input[i]));_x000D_
        output.setInt16(offset, s < 0 ? s * 0x8000 : s * 0x7FFF, true);_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function writeString(view, offset, string){_x000D_
      for (var i = 0; i < string.length; i++){_x000D_
        view.setUint8(offset + i, string.charCodeAt(i));_x000D_
      }_x000D_
    }_x000D_
_x000D_
    function encodeWAV(samples){_x000D_
      var buffer = new ArrayBuffer(44 + samples.length * 2);_x000D_
      var view = new DataView(buffer);_x000D_
_x000D_
      /* RIFF identifier */_x000D_
      writeString(view, 0, 'RIFF');_x000D_
      /* file length */_x000D_
      view.setUint32(4, 32 + samples.length * 2, true);_x000D_
      /* RIFF type */_x000D_
      writeString(view, 8, 'WAVE');_x000D_
      /* format chunk identifier */_x000D_
      writeString(view, 12, 'fmt ');_x000D_
      /* format chunk length */_x000D_
      view.setUint32(16, 16, true);_x000D_
      /* sample format (raw) */_x000D_
      view.setUint16(20, 1, true);_x000D_
      /* channel count */_x000D_
      view.setUint16(22, 2, true);_x000D_
      /* sample rate */_x000D_
      view.setUint32(24, sampleRate, true);_x000D_
      /* byte rate (sample rate * block align) */_x000D_
      view.setUint32(28, sampleRate * 4, true);_x000D_
      /* block align (channel count * bytes per sample) */_x000D_
      view.setUint16(32, 4, true);_x000D_
      /* bits per sample */_x000D_
      view.setUint16(34, 16, true);_x000D_
      /* data chunk identifier */_x000D_
      writeString(view, 36, 'data');_x000D_
      /* data chunk length */_x000D_
      view.setUint32(40, samples.length * 2, true);_x000D_
_x000D_
      floatTo16BitPCM(view, 44, samples);_x000D_
_x000D_
      return view;_x000D_
    }
_x000D_
<html>_x000D_
     <body>_x000D_
      <audio controls autoplay></audio>_x000D_
      <script type="text/javascript" src="recorder.js"> </script>_x000D_
                    <fieldset><legend>RECORD AUDIO</legend>_x000D_
      <input onclick="startRecording()" type="button" value="start recording" />_x000D_
      <input onclick="stopRecording()" type="button" value="stop recording and play" />_x000D_
                    </fieldset>_x000D_
      <script>_x000D_
       var onFail = function(e) {_x000D_
        console.log('Rejected!', e);_x000D_
       };_x000D_
_x000D_
       var onSuccess = function(s) {_x000D_
        var context = new webkitAudioContext();_x000D_
        var mediaStreamSource = context.createMediaStreamSource(s);_x000D_
        recorder = new Recorder(mediaStreamSource);_x000D_
        recorder.record();_x000D_
_x000D_
        // audio loopback_x000D_
        // mediaStreamSource.connect(context.destination);_x000D_
       }_x000D_
_x000D_
       window.URL = window.URL || window.webkitURL;_x000D_
       navigator.getUserMedia  = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;_x000D_
_x000D_
       var recorder;_x000D_
       var audio = document.querySelector('audio');_x000D_
_x000D_
       function startRecording() {_x000D_
        if (navigator.getUserMedia) {_x000D_
         navigator.getUserMedia({audio: true}, onSuccess, onFail);_x000D_
        } else {_x000D_
         console.log('navigator.getUserMedia not present');_x000D_
        }_x000D_
       }_x000D_
_x000D_
       function stopRecording() {_x000D_
        recorder.stop();_x000D_
        recorder.exportWAV(function(s) {_x000D_
                                _x000D_
                                  audio.src = window.URL.createObjectURL(s);_x000D_
        });_x000D_
       }_x000D_
      </script>_x000D_
     </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Create a new workspace in Eclipse

I use File -> Switch Workspace -> Other... and type in my new workspace name.

New workspace composite screenshot (EDIT: Added the composite screen shot.)

Once in the new workspace, File -> Import... and under General choose "Existing Projects into Workspace. Press the Next button and then Browse for the old projects you would like to import. Check "Copy projects into workspace" to make a copy.

When should an IllegalArgumentException be thrown?

As specified in oracle official tutorial , it states that:

If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

If I have an Application interacting with database using JDBC , And I have a method that takes the argument as the int item and double price. The price for corresponding item is read from database table. I simply multiply the total number of item purchased with the price value and return the result. Although I am always sure at my end(Application end) that price field value in the table could never be negative .But what if the price value comes out negative? It shows that there is a serious issue with the database side. Perhaps wrong price entry by the operator. This is the kind of issue that the other part of application calling that method can't anticipate and can't recover from it. It is a BUG in your database. So , and IllegalArguementException() should be thrown in this case which would state that the price can't be negative.
I hope that I have expressed my point clearly..

How do I modify a MySQL column to allow NULL?

My solution is the same as @Krishnrohit:

ALTER TABLE `table` CHANGE `column_current_name` `new_column_name` DATETIME NULL;

I actually had the column set as NOT NULL but with the above query it was changed to NULL.

P.S. I know this an old thread but nobody seems to acknowledge that CHANGE is also correct.

Rename multiple files in a directory in Python

Use os.rename(src, dst) to rename or move a file or a directory.

$ ls
cheese_cheese_type.bar  cheese_cheese_type.foo
$ python
>>> import os
>>> for filename in os.listdir("."):
...  if filename.startswith("cheese_"):
...    os.rename(filename, filename[7:])
... 
>>> 
$ ls
cheese_type.bar  cheese_type.foo

Changing button color programmatically

If you assign it to a class it should work:

<script>
  function changeClass(){
    document.getElementById('myButton').className = 'formatForButton';
  }
</script>

<style>
  .formatForButton {
    background-color:pink;
   }
</style>

<body>
  <input id='myButton' type=button class=none value='Change Color to pink' onclick='changeClass()'>
</body>

What is stdClass in PHP?

Also worth noting, an stdClass object can be created from the use of json_decode() as well.

Run Command Prompt Commands

if you want to run the command in async mode - and print the results. you can you this class:

    public static class ExecuteCmd
{
    /// <summary>
    /// Executes a shell command synchronously.
    /// </summary>
    /// <param name="command">string command</param>
    /// <returns>string, as output of the command.</returns>
    public static void ExecuteCommandSync(object command)
    {
        try
        {
            // create the ProcessStartInfo using "cmd" as the program to be run, and "/c " as the parameters.
            // Incidentally, /c tells cmd that we want it to execute the command that follows, and then exit.
            System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
            // The following commands are needed to redirect the standard output. 
            //This means that it will be redirected to the Process.StandardOutput StreamReader.
            procStartInfo.RedirectStandardOutput =  true;
            procStartInfo.UseShellExecute = false;
            // Do not create the black window.
            procStartInfo.CreateNoWindow = true;
            // Now we create a process, assign its ProcessStartInfo and start it
            System.Diagnostics.Process proc = new System.Diagnostics.Process();
            proc.StartInfo = procStartInfo;
            proc.Start();

            // Get the output into a string
            string result = proc.StandardOutput.ReadToEnd();

            // Display the command output.
            Console.WriteLine(result);
        }
        catch (Exception objException)
        {
            // Log the exception
            Console.WriteLine("ExecuteCommandSync failed" + objException.Message);
        }
    }

    /// <summary>
    /// Execute the command Asynchronously.
    /// </summary>
    /// <param name="command">string command.</param>
    public static void ExecuteCommandAsync(string command)
    {
        try
        {
            //Asynchronously start the Thread to process the Execute command request.
            Thread objThread = new Thread(new ParameterizedThreadStart(ExecuteCommandSync));
            //Make the thread as background thread.
            objThread.IsBackground = true;
            //Set the Priority of the thread.
            objThread.Priority = ThreadPriority.AboveNormal;
            //Start the thread.
            objThread.Start(command);
        }
        catch (ThreadStartException )
        {
            // Log the exception
        }
        catch (ThreadAbortException )
        {
            // Log the exception
        }
        catch (Exception )
        {
            // Log the exception
        }
    }

}

Running a CMD or BAT in silent mode

Use Bat To Exe Converter to do this

http://download.cnet.com/Bat-To-Exe-Converter/3000-2069_4-10555897.html
(Choose Direct Download Link)

1 - Open Bat to Exe Converter, select your Bat file.
2 - In Option menu select "Invisible Application", then press compile button.

Done!

Debian 8 (Live-CD) what is the standard login and password?

Although this is an old question, I had the same question when using the Standard console version. The answer can be found in the Debian Live manual under the section 10.1 Customizing the live user. It says:

It is also possible to change the default username "user" and the default password "live".

I tried the username user and password live and it did work. If you want to run commands as root you can preface each command with sudo

How to resolve javax.mail.AuthenticationFailedException issue?

Just wanted to share with you:
I happened to get this error after changing Digital Ocean machine (IP address). Apparently Gmail recognized it as a hacking attack. After following their directions, and approving the new IP address the code is back and running.

Chrome Extension - Get DOM content

The terms "background page", "popup", "content script" are still confusing you; I strongly suggest a more in-depth look at the Google Chrome Extensions Documentation.

Regarding your question if content scripts or background pages are the way to go:

Content scripts: Definitely
Content scripts are the only component of an extension that has access to the web-page's DOM.

Background page / Popup: Maybe (probably max. 1 of the two)
You may need to have the content script pass the DOM content to either a background page or the popup for further processing.


Let me repeat that I strongly recommend a more careful study of the available documentation!
That said, here is a sample extension that retrieves the DOM content on StackOverflow pages and sends it to the background page, which in turn prints it in the console:

background.js:

// Regex-pattern to check URLs against. 
// It matches URLs like: http[s]://[...]stackoverflow.com[...]
var urlRegex = /^https?:\/\/(?:[^./?#]+\.)?stackoverflow\.com/;

// A function to use as callback
function doStuffWithDom(domContent) {
    console.log('I received the following DOM content:\n' + domContent);
}

// When the browser-action button is clicked...
chrome.browserAction.onClicked.addListener(function (tab) {
    // ...check the URL of the active tab against our pattern and...
    if (urlRegex.test(tab.url)) {
        // ...if it matches, send a message specifying a callback too
        chrome.tabs.sendMessage(tab.id, {text: 'report_back'}, doStuffWithDom);
    }
});

content.js:

// Listen for messages
chrome.runtime.onMessage.addListener(function (msg, sender, sendResponse) {
    // If the received message has the expected format...
    if (msg.text === 'report_back') {
        // Call the specified callback, passing
        // the web-page's DOM content as argument
        sendResponse(document.all[0].outerHTML);
    }
});

manifest.json:

{
  "manifest_version": 2,
  "name": "Test Extension",
  "version": "0.0",
  ...

  "background": {
    "persistent": false,
    "scripts": ["background.js"]
  },
  "content_scripts": [{
    "matches": ["*://*.stackoverflow.com/*"],
    "js": ["content.js"]
  }],
  "browser_action": {
    "default_title": "Test Extension"
  },

  "permissions": ["activeTab"]
}

How to specify multiple return types using type-hints

The statement def foo(client_id: str) -> list or bool: when evaluated is equivalent to def foo(client_id: str) -> list: and will therefore not do what you want.

The native way to describe a "either A or B" type hint is Union (thanks to Bhargav Rao):

def foo(client_id: str) -> Union[list, bool]:

I do not want to be the "Why do you want to do this anyway" guy, but maybe having 2 return types isn't what you want:

If you want to return a bool to indicate some type of special error-case, consider using Exceptions instead. If you want to return a bool as some special value, maybe an empty list would be a good representation. You can also indicate that None could be returned with Optional[list]

How To Check If A Key in **kwargs Exists?

You can discover those things easily by yourself:

def hello(*args, **kwargs):
    print kwargs
    print type(kwargs)
    print dir(kwargs)

hello(what="world")

How to send value attribute from radio button in PHP

Check whether you have put name="your_radio" where you have inserted radio tag

if you have done this then check your php code. Use isset()

e.g.

   if(isset($_POST['submit']))
   {
    /*other variables*/
    $radio_value = $_POST["your_radio"];
   }

If you have done this as well then we need to look through your codes

Check, using jQuery, if an element is 'display:none' or block on click

There are two methods in jQuery to check for visibility:

$("#selector").is(":visible")

and

$("#selector").is(":hidden")

You can also execute commands based on visibility in the selector;

$("#selector:visible").hide()

or

$("#selector:hidden").show()

Convert pandas DataFrame into list of lists

EDIT: as_matrix is deprecated since version 0.23.0

You can use the built in values or to_numpy (recommended option) method on the dataframe:

In [8]:
df.to_numpy()

Out[8]:
array([[  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.9,   7. ,   5.2, ...,  13.3,  13.5,   8.9],
   [  0.8,   6.1,   5.4, ...,  15.9,  14.4,   8.6],
   ..., 
   [  0.2,   1.3,   2.3, ...,  16.1,  16.1,  10.8],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4],
   [  0.2,   1.3,   2.4, ...,  16.5,  15.9,  11.4]])

If you explicitly want lists and not a numpy array add .tolist():

df.to_numpy().tolist()

String concatenation in Ruby

Concatenation you say? How about #concat method then?

a = 'foo'
a.object_id #=> some number
a.concat 'bar' #=> foobar
a.object_id #=> same as before -- string a remains the same object

In all fairness, concat is aliased as <<.

How to reference a method in javadoc?

you can use @see to do that:

sample:

interface View {
        /**
         * @return true: have read contact and call log permissions, else otherwise
         * @see #requestReadContactAndCallLogPermissions()
         */
        boolean haveReadContactAndCallLogPermissions();

        /**
         * if not have permissions, request to user for allow
         * @see #haveReadContactAndCallLogPermissions()
         */
        void requestReadContactAndCallLogPermissions();
    }

How can I access a hover state in reactjs?

React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter and onMouseLeave. You then attach them to handlers in your component like so:

<ReactComponent
    onMouseEnter={() => this.someHandler}
    onMouseLeave={() => this.someOtherHandler}
/>

You'll then use some combination of state/props to pass changed state or properties down to your child React components.

How to count the occurrence of certain item in an ndarray?

You can use dictionary comprehension to create a neat one-liner. More about dictionary comprehension can be found here

>>>counts = {int(value): list(y).count(value) for value in set(y)}
>>>print(counts)
{0: 8, 1: 4}

This will create a dictionary with the values in your ndarray as keys, and the counts of the values as the values for the keys respectively.

This will work whenever you want to count occurences of a value in arrays of this format.

What is the meaning of CTOR?

To expand a little more, there are two kinds of constructors: instance initializers (.ctor), type initializers (.cctor). Build the code below, and explore the IL code in ildasm.exe. You will notice that the static field 'b' will be initialized through .cctor() whereas the instance field will be initialized through .ctor()

internal sealed class CtorExplorer
{
   protected int a = 0;
   protected static int b = 0;
}

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

I had the same problem, What helped me was:

  1. Right click on the project.
  2. Click 'Properties'
  3. Go to 'Java Build Path'
  4. And then: 'Libraries'
  5. In there, Click: Add External Jars
  6. Add: ''Path/To/Tomcat/Bin/tomcat-juli.jar

Done .

Excel column number from column name

Write and run the following code in the Immediate Window

?cells(,"type the column name here").column

For example ?cells(,"BYL").column will return 2014. The code is case-insensitive, hence you may write ?cells(,"byl").column and the output will still be the same.

How to iterate std::set?

Another example for the C++11 standard:

set<int> data;
data.insert(4);
data.insert(5);

for (const int &number : data)
  cout << number;

Convert Int to String in Swift

Convert Unicode Int to String

For those who want to convert an Int to a Unicode string, you can do the following:

let myInteger: Int = 97

// convert Int to a valid UnicodeScalar
guard let myUnicodeScalar = UnicodeScalar(myInteger) else {
    return ""
}

// convert UnicodeScalar to String
let myString = String(myUnicodeScalar)

// results
print(myString) // a

Or alternatively:

let myInteger: Int = 97
if let myUnicodeScalar = UnicodeScalar(myInteger) {
    let myString = String(myUnicodeScalar)
}

Importing class from another file

Your problem is basically that you never specified the right path to the file.

Try instead, from your main script:

from folder.file import Klasa

Or, with from folder import file:

from folder import file
k = file.Klasa()

Or again:

import folder.file as myModule
k = myModule.Klasa()

How do I parse a YAML file in Ruby?

I had the same problem but also wanted to get the content of the file (after the YAML front-matter).

This is the best solution I have found:

if (md = contents.match(/^(?<metadata>---\s*\n.*?\n?)^(---\s*$\n?)/m))
  self.contents = md.post_match
  self.metadata = YAML.load(md[:metadata])
end

Source and discussion: https://practicingruby.com/articles/tricks-for-working-with-text-and-files

How to compile a static library in Linux?

Generate the object files with gcc, then use ar to bundle them into a static library.

How can I directly view blobs in MySQL Workbench

SELECT *, CONVERT( UNCOMPRESS(column) USING "utf8" ) AS column FROM table_name

How to disable Compatibility View in IE

In JSF I used:

<h:head>
    <f:facet name="first">
        <meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
    </f:facet>

    <!-- ... other meta tags ... -->

</h:head>

Adding :default => true to boolean in existing Rails column

I'm not sure when this was written, but currently to add or remove a default from a column in a migration, you can use the following:

change_column_null :products, :name, false

Rails 5:

change_column_default :products, :approved, from: true, to: false

http://edgeguides.rubyonrails.org/active_record_migrations.html#changing-columns

Rails 4.2:

change_column_default :products, :approved, false

http://guides.rubyonrails.org/v4.2/active_record_migrations.html#changing-columns

Which is a neat way of avoiding looking through your migrations or schema for the column specifications.

Return multiple fields as a record in PostgreSQL with PL/pgSQL

You need to define a new type and define your function to return that type.

CREATE TYPE my_type AS (f1 varchar(10), f2 varchar(10) /* , ... */ );

CREATE OR REPLACE FUNCTION get_object_fields(name text) 
RETURNS my_type 
AS 
$$

DECLARE
  result_record my_type;

BEGIN
  SELECT f1, f2, f3
  INTO result_record.f1, result_record.f2, result_record.f3
  FROM table1
  WHERE pk_col = 42;

  SELECT f3 
  INTO result_record.f3
  FROM table2
  WHERE pk_col = 24;

  RETURN result_record;

END
$$ LANGUAGE plpgsql; 

If you want to return more than one record you need to define the function as returns setof my_type


Update

Another option is to use RETURNS TABLE() instead of creating a TYPE which was introduced in Postgres 8.4

CREATE OR REPLACE FUNCTION get_object_fields(name text) 
  RETURNS TABLE (f1 varchar(10), f2 varchar(10) /* , ... */ )
...

Switch android x86 screen resolution

Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.

VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"

With the following appended to android kernel cmd:

UVESA_MODE=440x680 DPI=120

Simplest way to wait some asynchronous tasks complete, in Javascript?

Expanding upon @freakish answer, async also offers a each method, which seems especially suited for your case:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    conn.collection(name).drop( callback );
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

IMHO, this makes the code both more efficient and more legible. I've taken the liberty of removing the console.log('dropped') - if you want it, use this instead:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    // if you really want the console.log( 'dropped' ),
    // replace the 'callback' here with an anonymous function
    conn.collection(name).drop( function(err) {
        if( err ) { return callback(err); }
        console.log('dropped');
        callback()
    });
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

How to make an ng-click event conditional?

You could try to use ng-class.
Here is my simple example:
http://plnkr.co/edit/wS3QkQ5dvHNdc6Lb8ZSF?p=preview

<div ng-repeat="object in objects">
  <span ng-class="{'disabled': object.status}" ng-click="disableIt(object)">
    {{object.value}}
  </span>
</div>

The status is a custom attribute of object, you could name it whatever you want.
The disabled in ng-class is a CSS class name, the object.status should be true or false

You could change every object's status in function disableIt.
In your Controller, you could do this:

$scope.disableIt = function(obj) {
  obj.status = !obj.status
}

How to get HTTP Response Code using Selenium WebDriver

Not sure this is what you're looking for, but I had a bit different goal is to check if remote image exists and I will not have 403 error, so you could use something like below:

public static boolean linkExists(String URLName){
    try {
        HttpURLConnection.setFollowRedirects(false);
        HttpURLConnection con = (HttpURLConnection) new URL(URLName).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpURLConnection.HTTP_OK);
    }
    catch (Exception e) {
        e.printStackTrace();
        return false;
    }
}

Removing Spaces from a String in C?

if you are still interested, this function removes spaces from the beginning of the string, and I just had it working in my code:

void removeSpaces(char *str1)  
{
    char *str2; 
    str2=str1;  
    while (*str2==' ') str2++;  
    if (str2!=str1) memmove(str1,str2,strlen(str2)+1);  
}

KERNELBASE.dll Exception 0xe0434352 offset 0x000000000000a49d

0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.

There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.

I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException and Application.ThreadException, as appropriate.

Laravel Eloquent inner join with multiple conditions

//You may use this example. Might be help you...

$user = User::select("users.*","items.id as itemId","jobs.id as jobId")
        ->join("items","items.user_id","=","users.id")
        ->join("jobs",function($join){
            $join->on("jobs.user_id","=","users.id")
                ->on("jobs.item_id","=","items.id");
        })
        ->get();
print_r($user);

UIButton Image + Text IOS

You should create custom imageview for image and custom label for text and you add to your button as subviews. That's it.

UIButton *yourButton = [UIButton buttonWithType:UIButtonTypeCustom];
yourButton.backgroundColor = [UIColor greenColor];
yourButton.frame = CGRectMake(140, 40, 175, 30);     
[yourButton addTarget:self action:@selector(yourButtonSelected:) forControlEvents:UIControlEventTouchUpInside]; 
[self.view addSubview:yourButton];

UIImageView *imageView1 = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, yourButton.frame.size.width, yourButton.frame.size.height/2)];
imageView1.image =[UIImage imageNamed:@"images.jpg"];
[yourButton addSubview:imageView1];

UILabel *label=[[UILabel alloc] initWithFrame:CGRectMake(0, yourButton.frame.size.height/2, yourButton.frame.size.width, yourButton.frame.size.height/2)];
label.backgroundColor = [UIColor greenColor];
label.textAlignment= UITextAlignmentCenter;
label.text = @"ButtonTitle";
[yourButton addSubview:label];

For testing purpose, use yourButtonSelected: method

-(void)yourButtonSelected:(id)sender{
    NSLog(@"Your Button Selected");

}

I think it will be helpful to you.

Setting Java heap space under Maven 2 on Windows

On windows:

Add an environmental variable (in both system and user's variables, I have some weird problem, that it gets the var from various places, so I add them in both of them).

Name it MAVEN_OPTS.

Value will be: -Xms1024m -Xmx3000m -XX:MaxPermSize=1024m -XX:+CMSClassUnloadingEnabled

The numbers can be different, make them relative to your mem size.

I had that problem and this fixed it, nothing else!

Which sort algorithm works best on mostly sorted data?

If elements are already sorted or there are only few elements, it would be a perfect use case for Insertion Sort!

A function to convert null to string

Its possible to make this even shorter with C# 6:

public string NullToString(string Value)
{
    return value?.ToString() ?? "";
}

Pass parameter from a batch file to a PowerShell script

When a script is loaded, any parameters that are passed are automatically loaded into a special variables $args. You can reference that in your script without first declaring it.

As an example, create a file called test.ps1 and simply have the variable $args on a line by itself. Invoking the script like this, generates the following output:

PowerShell.exe -File test.ps1 a b c "Easy as one, two, three"
a
b
c
Easy as one, two, three

As a general recommendation, when invoking a script by calling PowerShell directly I would suggest using the -File option rather than implicitly invoking it with the & - it can make the command line a bit cleaner, particularly if you need to deal with nested quotes.

Visual Studio Copy Project

If you want a copy, the fastest way of doing this would be to save the project. Then make a copy of the entire thing on the File System. Go back into Visual Studio and open the copy. From there, I would most likely recommend re-naming the project/solution so that you don't have two of the same name, but that is the fastest way to make a copy.

Is there a way to check for both `null` and `undefined`?

Since TypeScript is a typed superset of ES6 JavaScript. And lodash are a library of javascript.

Using lodash to checks if value is null or undefined can be done using _.isNil().

_.isNil(value)

Arguments

value (*): The value to check.

Returns

(boolean): Returns true if value is nullish, else false.

Example

_.isNil(null);
// => true

_.isNil(void 0);
// => true

_.isNil(NaN);
// => false

Link

Lodash Docs

How to view query error in PDO PHP

I'm guessing that your complaint is that the exception is not firing. PDO is most likely configured to not throw exceptions. Enable them with this:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 

Math constant PI value in C

anyway you have not a unlimited accuracy so C define a constant in this way:

#define PI 3.14159265358979323846

import math.h to use this

Random / noise functions for GLSL

It occurs to me that you could use a simple integer hash function and insert the result into a float's mantissa. IIRC the GLSL spec guarantees 32-bit unsigned integers and IEEE binary32 float representation so it should be perfectly portable.

I gave this a try just now. The results are very good: it looks exactly like static with every input I tried, no visible patterns at all. In contrast the popular sin/fract snippet has fairly pronounced diagonal lines on my GPU given the same inputs.

One disadvantage is that it requires GLSL v3.30. And although it seems fast enough, I haven't empirically quantified its performance. AMD's Shader Analyzer claims 13.33 pixels per clock for the vec2 version on a HD5870. Contrast with 16 pixels per clock for the sin/fract snippet. So it is certainly a little slower.

Here's my implementation. I left it in various permutations of the idea to make it easier to derive your own functions from.

/*
    static.frag
    by Spatial
    05 July 2013
*/

#version 330 core

uniform float time;
out vec4 fragment;



// A single iteration of Bob Jenkins' One-At-A-Time hashing algorithm.
uint hash( uint x ) {
    x += ( x << 10u );
    x ^= ( x >>  6u );
    x += ( x <<  3u );
    x ^= ( x >> 11u );
    x += ( x << 15u );
    return x;
}



// Compound versions of the hashing algorithm I whipped together.
uint hash( uvec2 v ) { return hash( v.x ^ hash(v.y)                         ); }
uint hash( uvec3 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z)             ); }
uint hash( uvec4 v ) { return hash( v.x ^ hash(v.y) ^ hash(v.z) ^ hash(v.w) ); }



// Construct a float with half-open range [0:1] using low 23 bits.
// All zeroes yields 0.0, all ones yields the next smallest representable value below 1.0.
float floatConstruct( uint m ) {
    const uint ieeeMantissa = 0x007FFFFFu; // binary32 mantissa bitmask
    const uint ieeeOne      = 0x3F800000u; // 1.0 in IEEE binary32

    m &= ieeeMantissa;                     // Keep only mantissa bits (fractional part)
    m |= ieeeOne;                          // Add fractional part to 1.0

    float  f = uintBitsToFloat( m );       // Range [1:2]
    return f - 1.0;                        // Range [0:1]
}



// Pseudo-random value in half-open range [0:1].
float random( float x ) { return floatConstruct(hash(floatBitsToUint(x))); }
float random( vec2  v ) { return floatConstruct(hash(floatBitsToUint(v))); }
float random( vec3  v ) { return floatConstruct(hash(floatBitsToUint(v))); }
float random( vec4  v ) { return floatConstruct(hash(floatBitsToUint(v))); }





void main()
{
    vec3  inputs = vec3( gl_FragCoord.xy, time ); // Spatial and temporal inputs
    float rand   = random( inputs );              // Random per-pixel value
    vec3  luma   = vec3( rand );                  // Expand to RGB

    fragment = vec4( luma, 1.0 );
}

Screenshot:

Output of random(vec3) in static.frag

I inspected the screenshot in an image editing program. There are 256 colours and the average value is 127, meaning the distribution is uniform and covers the expected range.

How to disable sort in DataGridView?

private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
      for (int i = 0; i < dataGridView1.Columns.Count; i++)
      {
           dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
      }
}

$(document).ready shorthand

This is not a shorthand for $(document).ready().

The code you posted boxes the inside code and makes jQuery available as $ without polluting the global namespace. This can be used when you want to use both prototype and jQuery on one page.

Documented here: http://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/#use-an-immediately-invoked-function-expression

SQL Server: use CASE with LIKE

Add an END at last before alias name.

CASE WHEN countries LIKE '%'+@selCountry+'%' 
     THEN 'national' ELSE 'regional' 
END AS validity

For example:

SELECT CASE WHEN countries LIKE '%'+@selCountry+'%' 
       THEN 'national' ELSE 'regional' 
       END AS validity
FROM TableName

Tomcat - maxThreads vs maxConnections

Tomcat can work in 2 modes:

  • BIO – blocking I/O (one thread per connection)
  • NIOnon-blocking I/O (many more connections than threads)

Tomcat 7 is BIO by default, although consensus seems to be "don't use Bio because Nio is better in every way". You set this using the protocol parameter in the server.xml file.

  • BIO will be HTTP/1.1 or org.apache.coyote.http11.Http11Protocol
  • NIO will be org.apache.coyote.http11.Http11NioProtocol

If you're using BIO then I believe they should be more or less the same.

If you're using NIO then actually "maxConnections=1000" and "maxThreads=10" might even be reasonable. The defaults are maxConnections=10,000 and maxThreads=200. With NIO, each thread can serve any number of connections, switching back and forth but retaining the connection so you don't need to do all the usual handshaking which is especially time-consuming with HTTPS but even an issue with HTTP. You can adjust the "keepAlive" parameter to keep connections around for longer and this should speed everything up.

What is an MDF file?

SQL Server databases use two files - an MDF file, known as the primary database file, which contains the schema and data, and a LDF file, which contains the logs. See wikipedia. A database may also use secondary database file, which normally uses a .ndf extension.

As John S. indicates, these file extensions are purely convention - you can use whatever you want, although I can't think of a good reason to do that.

More info on MSDN here and in Beginning SQL Server 2005 Administation (Google Books) here.

How to view/delete local storage in Firefox?

Try this, it works for me:

var storage = null;
setLocalStorage();

function setLocalStorage() {
    storage = (localStorage ? localStorage : (window.content.localStorage ? window.content.localStorage : null));

    try {
        storage.setItem('test_key', 'test_value');//verify if posible saving in the current storage
    }
    catch (e) {
        if (e.name == "NS_ERROR_FILE_CORRUPTED") {
            storage = sessionStorage ? sessionStorage : null;//set the new storage if fails
        }
    }
}

Comparing strings, c++

Regarding the question,

can someone explain why the compare() function exists if a comparison can be made using simple operands?

Relative to < and ==, the compare function is conceptually simpler and in practice it can be more efficient since it avoids two comparisons per item for ordinary ordering of items.


As an example of simplicity, for small integer values you can write a compare function like this:

auto compare( int a, int b ) -> int { return a - b; }

which is highly efficient.

Now for a structure

struct Foo
{
    int a;
    int b;
    int c;
};

auto compare( Foo const& x, Foo const& y )
    -> int
{
    if( int const r = compare( x.a, y.a ) ) { return r; }
    if( int const r = compare( x.b, y.b ) ) { return r; }
    return compare( x.c, y.c );
}

Trying to express this lexicographic compare directly in terms of < you wind up with horrendous complexity and inefficiency, relatively speaking.


With C++11, for the simplicity alone ordinary less-than comparison based lexicographic compare can be very simply implemented in terms of tuple comparison.

What is the difference between \r and \n?

\r is Carriage Return; \n is New Line (Line Feed) ... depends on the OS as to what each means. Read this article for more on the difference between '\n' and '\r\n' ... in C.

Dynamically allocating an array of objects

Why not have a setSize method.

A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
    arrayOfAs[i].SetSize(3);
}

I like the "copy" but in this case the default constructor isn't really doing anything. The SetSize could copy the data out of the original m_array (if it exists).. You'd have to store the size of the array within the class to do that.
OR
The SetSize could delete the original m_array.

void SetSize(unsigned int p_newSize)
{
    //I don't care if it's null because delete is smart enough to deal with that.
    delete myArray;
    myArray = new int[p_newSize];
    ASSERT(myArray);
}

How do I find the length/number of items present for an array?

I'm not sure that i know exactly what you mean.

But to get the length of an initialized array,

doesn't strlen(string) work ??

What is WEB-INF used for in a Java EE web application?

The Servlet 2.4 specification says this about WEB-INF (page 70):

A special directory exists within the application hierarchy named WEB-INF. This directory contains all things related to the application that aren’t in the document root of the application. The WEB-INF node is not part of the public document tree of the application. No file contained in the WEB-INF directory may be served directly to a client by the container. However, the contents of the WEB-INF directory are visible to servlet code using the getResource and getResourceAsStream method calls on the ServletContext, and may be exposed using the RequestDispatcher calls.

This means that WEB-INF resources are accessible to the resource loader of your Web-Application and not directly visible for the public.

This is why a lot of projects put their resources like JSP files, JARs/libraries and their own class files or property files or any other sensitive information in the WEB-INF folder. Otherwise they would be accessible by using a simple static URL (usefull to load CSS or Javascript for instance).

Your JSP files can be anywhere though from a technical perspective. For instance in Spring you can configure them to be in WEB-INF explicitly:

<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
    p:prefix="/WEB-INF/jsp/" 
    p:suffix=".jsp" >
</bean>

The WEB-INF/classes and WEB-INF/lib folders mentioned in Wikipedia's WAR files article are examples of folders required by the Servlet specification at runtime.

It is important to make the difference between the structure of a project and the structure of the resulting WAR file.

The structure of the project will in some cases partially reflect the structure of the WAR file (for static resources such as JSP files or HTML and JavaScript files, but this is not always the case.

The transition from the project structure into the resulting WAR file is done by a build process.

While you are usually free to design your own build process, nowadays most people will use a standardized approach such as Apache Maven. Among other things Maven defines defaults for which resources in the project structure map to what resources in the resulting artifact (the resulting artifact is the WAR file in this case). In some cases the mapping consists of a plain copy process in other cases the mapping process includes a transformation, such as filtering or compiling and others.

One example: The WEB-INF/classes folder will later contain all compiled java classes and resources (src/main/java and src/main/resources) that need to be loaded by the Classloader to start the application.

Another example: The WEB-INF/lib folder will later contain all jar files needed by the application. In a maven project the dependencies are managed for you and maven automatically copies the needed jar files to the WEB-INF/lib folder for you. That explains why you don't have a lib folder in a maven project.

Install MySQL on Ubuntu without a password prompt

sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server

For specific versions, such as mysql-server-5.6, you'll need to specify the version in like this:

sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password password your_password'
sudo debconf-set-selections <<< 'mysql-server-5.6 mysql-server/root_password_again password your_password'
sudo apt-get -y install mysql-server-5.6

For mysql-community-server, the keys are slightly different:

sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/root-pass password your_password'
sudo debconf-set-selections <<< 'mysql-community-server mysql-community-server/re-root-pass password your_password'
sudo apt-get -y install mysql-community-server

Replace your_password with the desired root password. (it seems your_password can also be left blank for a blank root password.)

If your shell doesn't support here-strings (zsh, ksh93 and bash support them), use:

echo ... | sudo debconf-set-selections 

Can't push image to Amazon ECR - fails with "no basic auth credentials"

On Windows in PowerShell, use:

Invoke-Expression $(aws ecr get-login --no-include-email)

Reliable way to convert a file to a byte[]

byte[] bytes = File.ReadAllBytes(filename) 

or ...

var bytes = File.ReadAllBytes(filename) 

MySQL Workbench: How to keep the connection alive

If you are using a "Standard TCP/IP over SSH" type of connection, under "Preferences"->"Others" there is "SSH KeepAlive" field. It took me quite a while to find it :(

How to make a PHP SOAP call using the SoapClient class

There is an option to generate php5 objects with WsdlInterpreter class. See more here: https://github.com/gkwelding/WSDLInterpreter

for example:

require_once 'WSDLInterpreter-v1.0.0/WSDLInterpreter.php';
$wsdlLocation = '<your wsdl url>?wsdl';
$wsdlInterpreter = new WSDLInterpreter($wsdlLocation);
$wsdlInterpreter->savePHP('.');

Shift column in pandas dataframe up by one?

In [44]: df['gdp'] = df['gdp'].shift(-1)

In [45]: df
Out[45]: 
   y  gdp  cap
0  1    3    5
1  2    7    9
2  8    4    2
3  3    7    7
4  6  NaN    7

In [46]: df[:-1]                                                                                                                                                                                                                                                                                                               
Out[46]: 
   y  gdp  cap
0  1    3    5
1  2    7    9
2  8    4    2
3  3    7    7

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

What determines the monitor my app runs on?

It's not exactly the answer to this question but I dealt with this problem with the Shift + Win + [left,right] arrow keys shortcut. You can move the currently active window to another monitor with it.

How to add facebook share button on my website?

For Facebook share with an image without an API and using a # to deep link into a sub page, the trick was to share the image as picture=

The variable mainUrl would be http://yoururl.com/

var d1 = $('.targ .t1').text();
var d2 = $('.targ .t2').text();
var d3 = $('.targ .t3').text();
var d4 = $('.targ .t4').text();
var descript_ = d1 + ' ' + d2 + ' ' + d3 + ' ' + d4;
var descript = encodeURIComponent(descript_);

var imgUrl_ = 'path/to/mypic_'+id+'.jpg';
var imgUrl = mainUrl + encodeURIComponent(imgUrl_);

var shareLink = mainUrl + encodeURIComponent('mypage.html#' + id);

var fbShareLink = shareLink + '&picture=' + imgUrl + '&description=' + descript;
var twShareLink = 'text=' + descript + '&url=' + shareLink;

// facebook
$(".my-btn .facebook").off("tap click").on("tap click",function(){
  var fbpopup = window.open("https://www.facebook.com/sharer/sharer.php?u=" + fbShareLink, "pop", "width=600, height=400, scrollbars=no");
  return false;
});

// twitter
$(".my-btn .twitter").off("tap click").on("tap click",function(){
  var twpopup = window.open("http://twitter.com/intent/tweet?" + twShareLink , "pop", "width=600, height=400, scrollbars=no");
  return false;
});

First Heroku deploy failed `error code=H10`

I had a typo

const PORT = process.env.PORT||'8080';

used to be

const PORT = process.env.port||'8080';

Replace preg_replace() e modifier with preg_replace_callback

In a regular expression, you can "capture" parts of the matched string with (brackets); in this case, you are capturing the (^|_) and ([a-z]) parts of the match. These are numbered starting at 1, so you have back-references 1 and 2. Match 0 is the whole matched string.

The /e modifier takes a replacement string, and substitutes backslash followed by a number (e.g. \1) with the appropriate back-reference - but because you're inside a string, you need to escape the backslash, so you get '\\1'. It then (effectively) runs eval to run the resulting string as though it was PHP code (which is why it's being deprecated, because it's easy to use eval in an insecure way).

The preg_replace_callback function instead takes a callback function and passes it an array containing the matched back-references. So where you would have written '\\1', you instead access element 1 of that parameter - e.g. if you have an anonymous function of the form function($matches) { ... }, the first back-reference is $matches[1] inside that function.

So a /e argument of

'do_stuff(\\1) . "and" . do_stuff(\\2)'

could become a callback of

function($m) { return do_stuff($m[1]) . "and" . do_stuff($m[2]); }

Or in your case

'strtoupper("\\2")'

could become

function($m) { return strtoupper($m[2]); }

Note that $m and $matches are not magic names, they're just the parameter name I gave when declaring my callback functions. Also, you don't have to pass an anonymous function, it could be a function name as a string, or something of the form array($object, $method), as with any callback in PHP, e.g.

function stuffy_callback($things) {
    return do_stuff($things[1]) . "and" . do_stuff($things[2]);
}
$foo = preg_replace_callback('/([a-z]+) and ([a-z]+)/', 'stuffy_callback', 'fish and chips');

As with any function, you can't access variables outside your callback (from the surrounding scope) by default. When using an anonymous function, you can use the use keyword to import the variables you need to access, as discussed in the PHP manual. e.g. if the old argument was

'do_stuff(\\1, $foo)'

then the new callback might look like

function($m) use ($foo) { return do_stuff($m[1], $foo); }

Gotchas

  • Use of preg_replace_callback is instead of the /e modifier on the regex, so you need to remove that flag from your "pattern" argument. So a pattern like /blah(.*)blah/mei would become /blah(.*)blah/mi.
  • The /e modifier used a variant of addslashes() internally on the arguments, so some replacements used stripslashes() to remove it; in most cases, you probably want to remove the call to stripslashes from your new callback.

SQL Server AS statement aliased column within WHERE statement

I am not sure why you cannot use "lat" but, if you must you can rename the columns in a derived table.

select a.latitude from (SELECT lat AS latitude FROM poi_table) a where latitude < 500

What are the possible values of the Hibernate hbm2ddl.auto configuration and what do they do

If you don't want to use Strings in your app and are looking for predefined constants have a look at org.hibernate.cfg.AvailableSettings class included in the Hibernate JAR, where you'll find a constant for all possible settings. In your case for example:

/**
 * Auto export/update schema using hbm2ddl tool. Valid values are <tt>update</tt>,
 * <tt>create</tt>, <tt>create-drop</tt> and <tt>validate</tt>.
 */
String HBM2DDL_AUTO = "hibernate.hbm2ddl.auto";

Convert an integer to an array of digits

Use:

int count = 0;
String newString = n + "";
char [] stringArray = newString.toCharArray();
int [] intArray = new int[stringArray.length];
for (char i : stringArray) {
  int m = Character.getNumericValue(i);
  intArray[count] = m;
  count += 1;
}
return intArray;

You'll have to put this into a method.

Node.js connect only works on localhost

To gain access for other users to your local machine, i usually use ngrok. Ngrok exposes your localhost to the web, and has an NPM wrapper that is simple to install and start:

$ npm install ngrok -g
$ ngrok http 3000

See this example usage:

enter image description here

In the above example, the locally running instance of sails at: localhost:3000 is now available on the Internet served at: http://69f8f0ee.ngrok.io or https://69f8f0ee.ngrok.io

How to format a float in javascript?

var x = 0.3445434
x = Math.round (x*100) / 100 // this will make nice rounding

Insert data using Entity Framework model

[HttpPost] // it use when you write logic on button click event

public ActionResult DemoInsert(EmployeeModel emp)
{
    Employee emptbl = new Employee();    // make object of table
    emptbl.EmpName = emp.EmpName;
    emptbl.EmpAddress = emp.EmpAddress;  // add if any field you want insert
    dbc.Employees.Add(emptbl);           // pass the table object 
    dbc.SaveChanges();

    return View();
}

Rename a table in MySQL

For Mysql 5.6.18 use the following command

ALTER TABLE `old_table` RENAME TO `new_table`

Also if there is an error saying ".... near RENAME TO ..." try removing the tick `

How to access a dictionary key value present inside a list?

To get all the values from a list of dictionaries, use the following code :

list = [{'text': 1, 'b': 2}, {'text': 3, 'd': 4}, {'text': 5, 'f': 6}]
subtitle=[]
for value in list:
   subtitle.append(value['text'])

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

Method Call Chaining; returning a pointer vs a reference?

The difference between pointers and references is quite simple: a pointer can be null, a reference can not.

Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).

Here it looks like references are more appropriate.

how do you pass images (bitmaps) between android activities using bundles?

You can pass image in short without using bundle like this This is the code of sender .class file

Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher;
Intent intent = new Intent();
Intent.setClass(<Sender_Activity>.this, <Receiver_Activity.class);
Intent.putExtra("Bitmap", bitmap);
startActivity(intent);

and this is receiver class file code.

Bitmap bitmap = (Bitmap)this.getIntent().getParcelableExtra("Bitmap");
ImageView viewBitmap = (ImageView)findViewById(R.id.bitmapview);
viewBitmap.setImageBitmap(bitmap);

No need to compress. that's it

Difference between logger.info and logger.debug

Just a clarification about the set of all possible levels, that are:

ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF

ListView inside ScrollView is not scrolling on Android

Above solution given by @Shailesh Rohit works perfectly fine. Some tricks has to be done.

  1. If you are putting helper class inside the same class( main class) then make Helper class as static and getListViewSize() not be static.

  2. Most important, write "Helper.getListViewSize(listView);" statement after setting adapter for the first time like "listView.setAdapter(myAdapter);" as well as when ever you are using "myAdapter.notifyDataSetChanged();"

  3. Usage is shown below.

    listView = (ListView) findViewById(R.id.listView); myAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1, listValues); listView .setAdapter(myAdapter); Helper.getListViewSizelistView(listView);

    myAdapter.notifyDataSetChanged(); Helper.getListViewSizelistView(listView);

Validating email addresses using jQuery and regex

Javascript:

var pattern = new RegExp("^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
var result = pattern .test(str);


The regex is not allowed for:

[email protected]
[email protected]..


Allowed for:

[email protected]
[email protected]

Source: http://www.mkyong.com/regular-expressions/10-java-regular-expression-examples-you-should-know/

How do I apply a diff patch on Windows?

It appears that TortoiseSVN (TortoiseMerge) requires the line Index: foobar.py in the diff/patch file. This is what I needed to do to make a non-TortoiseSVN patch file work with TortoiseSVN's right-click Apply Patch command.

Before:

--- foobar.py.org   Sat May 08 16:00:56 2010
+++ foobar.py   Sat May 08 15:47:48 2010

After:

Index: foobar.py
===================================================================
--- foobar.py
+++ foobar.py   (working copy)

Or if you know the specific revision your contributor was working from:

Index: foobar.py
===================================================================
--- foobar.py   (revision 1157)
+++ foobar.py   (working copy)

JSON and escaping characters

hmm, well here's a workaround anyway:

function JSON_stringify(s, emit_unicode)
{
   var json = JSON.stringify(s);
   return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
      function(c) { 
        return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
      }
   );
}

test case:

js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"

How to get nth jQuery element

If I understand your question correctly, you can always just wrap the get function like so:

var $someJqueryEl = $($('.myJqueryEls').get(3));

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

If you're seeing this error message when attempting to connect using SSMS, add TrustServerCertificate=True to the Additional Connection Parameters.

How can I run another application within a panel of my C# program?

If you want to run notepad inside your app you would probably be better of with a text editor component. There's obviously a basic text box that comes with WinForms, but I suspect more advanced components that offer Notepad functionality (or better) can be found on the interweb.

Unable to update the EntitySet - because it has a DefiningQuery and no <UpdateFunction> element exist

I had this issue come up and believe it was caused because I had deleted the Index on my tables primary key and replaced it with an index on some of the other fields in the table.

After I deleted the primary key index and refreshed the edmx, inserts stopped working.

I refreshed the table to the older version, refreshed the edmx and everything works again.

I should note that when I opened the EDMX to troubleshoot this issue, checking to see if there was a primary key defined, there was. So none of the above suggestions were helping me. But refreshing the index on the primary key seemed to work.

Abstract methods in Python

Abstract base classes are deep magic. Periodically I implement something using them and am amazed at my own cleverness, very shortly afterwards I find myself completely confused by my own cleverness (this may well just be a personal limitation though).

Another way of doing this (should be in the python std libs if you ask me) is to make a decorator.

def abstractmethod(method):
    """
    An @abstractmethod member fn decorator.
    (put this in some library somewhere for reuse).

    """
    def default_abstract_method(*args, **kwargs):
        raise NotImplementedError('call to abstract method ' 
                                  + repr(method))
    default_abstract_method.__name__ = method.__name__    
    return default_abstract_method


class Shape(object):

    def __init__(self, shape_name):
       self.shape = shape_name

    @abstractmethod
    def foo(self):
        print "bar"
        return

class Rectangle(Shape):
    # note you don't need to do the constructor twice either
    pass  

r = Rectangle("x")
r.foo()

I didn't write the decorator. It just occurred to me someone would have. You can find it here: http://code.activestate.com/recipes/577666-abstract-method-decorator/ Good one jimmy2times. Note the discussion at the bottom of that page r.e. type safety of the decorator. (That could be fixed with the inspect module if anyone was so inclined).

Bring element to front using CSS

In my case i had to move the html code of the element i wanted at the front at the end of the html file, because if one element has z-index and the other doesn't have z index it doesn't work.

Debugging iframes with Chrome developer tools

When the iFrame points to your site like this:

<html>
  <head>
    <script type="text/javascript" src="/jquery.js"></script>
  </head>
  <body>
    <iframe id="my_frame" src="/wherev"></iframe>
  </body>
</html>

You can access iFrame DOM through this kind of thing.

var iframeBody = $(window.my_frame.document.getElementsByTagName("body")[0]);
iframeBody.append($("<h1/>").html("Hello world!"));

Array of char* should end at '\0' or "\0"?

Well, technically '\0' is a character while "\0" is a string, so if you're checking for the null termination character the former is correct. However, as Chris Lutz points out in his answer, your comparison won't work in it's current form.

Set a thin border using .css() in javascript

Maybe just "border-width" instead of "border-weight"? There is no "border-weight" and this property is just ignored and default width is used instead.