Programs & Examples On #Tel

'tel' is a URI scheme specification for telephone numbers, which describes resources for telephone numbers linked to within documents.

href="tel:" and mobile numbers

I know the OP is asking about international country codes but for North America, you could use the following:

_x000D_
_x000D_
<a href="tel:+1-847-555-5555">1-847-555-5555</a>

<a href="tel:+18475555555">Click Here To Call Support 1-847-555-5555</a>
_x000D_
_x000D_
_x000D_

This might help you.

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

MySQl Error #1064

maybe you forgot to add ";" after this line of code:

`quantity` INT NOT NULL)

Spring Security with roles and permissions

Just for sake of completeness (maybe someone else won't have to implement it from scratch):

We've implemented our own small library, as everyone else. It's supposed to make things easier, so that our developers don't have to reimplement it each time. It would be great if spring security would provide support of rbac out of the box, as this approach is much better than the default permission based one.

Have a look at Github (OSS, MIT license) to see if it suits your needs. It's basically only addressing the role <-> privileges mapping. The missing piece, you'll have to provide on your own is basically the user <-> roles mapping, e.g. by mapping groups (racf/ad groups) to roles (1:1) or by implementing an additional mapping. That one's different in each project, so it doesn't make sense to provide some implementation.

We've basically used this internally, so that we can start with rbac from the beginning. We can still replace it with some other implementation later on, if the application is growing, but it's important for us to get the setup right at the beginning.

If you don't use rbac, there's a good chance, that the permissions are scattered throughout the codebase and you'll have a hard time to extract/group those (into roles) later on. The generated graphs do also help to reason about it/restructure it later on.

How to click a href link using Selenium

 webDriver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();

The above line works fine. Please remove the space after href.

Is that element is visible in the page, if the element is not visible please scroll down the page then perform click action.

How can I check whether a numpy array is empty or not?

Why would we want to check if an array is empty? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append is a frequent novice error.

Using a list in if alist: hinges on its boolean value:

In [102]: bool([])                                                                       
Out[102]: False
In [103]: bool([1])                                                                      
Out[103]: True

But trying to do the same with an array produces (in version 1.18):

In [104]: bool(np.array([]))                                                             
/usr/local/bin/ipython3:1: DeprecationWarning: The truth value 
   of an empty array is ambiguous. Returning False, but in 
   future this will result in an error. Use `array.size > 0` to 
   check that an array is not empty.
  #!/usr/bin/python3
Out[104]: False

In [105]: bool(np.array([1]))                                                            
Out[105]: True

and bool(np.array([1,2]) produces the infamous ambiguity error.

edit

The accepted answer suggests size:

In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0

But I (and most others) check the shape more than the size:

In [13]: x.shape
Out[13]: (0,)

Another thing in its favor is that it 'maps' on to an empty list:

In [14]: x.tolist()
Out[14]: []

But there are other other arrays with 0 size, that aren't 'empty' in that last sense:

In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True

np.array([[],[]]) is also size 0, but shape (2,0) and len 2.

While the concept of an empty list is well defined, an empty array is not well defined. One empty list is equal to another. The same can't be said for a size 0 array.

The answer really depends on

  • what do you mean by 'empty'?
  • what are you really test for?

How do I make a text input non-editable?

Add readonly:

<input type="text" value="3" class="field left" readonly>

If you want the value to be not submitted in a form, instead add the disabled attribute.

<input type="text" value="3" class="field left" disabled>

There is no way to use CSS that always works to do this.

Why? CSS can't "disable" anything. You can still turn off display or visibility and use pointer-events: none but pointer-events doesn't work on versions of IE that came out earlier than IE 11.

How do the likely/unlikely macros in the Linux kernel work and what is their benefit?

They cause the compiler to emit the appropriate branch hints where the hardware supports them. This usually just means twiddling a few bits in the instruction opcode, so code size will not change. The CPU will start fetching instructions from the predicted location, and flush the pipeline and start over if that turns out to be wrong when the branch is reached; in the case where the hint is correct, this will make the branch much faster - precisely how much faster will depend on the hardware; and how much this affects the performance of the code will depend on what proportion of the time hint is correct.

For instance, on a PowerPC CPU an unhinted branch might take 16 cycles, a correctly hinted one 8 and an incorrectly hinted one 24. In innermost loops good hinting can make an enormous difference.

Portability isn't really an issue - presumably the definition is in a per-platform header; you can simply define "likely" and "unlikely" to nothing for platforms that do not support static branch hints.

How to capitalize the first character of each word in a string

Using org.apache.commons.lang.StringUtils makes it very simple.

capitalizeStr = StringUtils.capitalize(str);

PHPMyAdmin Default login password

Default is:

Username: root

Password: [null]

The Password is set to 'password' in some versions.

How to find third or n?? maximum salary from salary table?

For n-th highest value

select min(salary) 
from (select salary from(select salary from employee order by salary desc)where rownum<=n);

When is the @JsonProperty property used and what is it used for?

From JsonProperty javadoc,

Defines name of the logical property, i.e. JSON object field name to use for the property. If value is empty String (which is the default), will try to use name of the field that is annotated.

What is the best way to trigger onchange event in react js

Expanding on the answer from Grin/Dan Abramov, this works across multiple input types. Tested in React >= 15.5

const inputTypes = [
    window.HTMLInputElement,
    window.HTMLSelectElement,
    window.HTMLTextAreaElement,
];

export const triggerInputChange = (node, value = '') => {

    // only process the change on elements we know have a value setter in their constructor
    if ( inputTypes.indexOf(node.__proto__.constructor) >-1 ) {

        const setValue = Object.getOwnPropertyDescriptor(node.__proto__, 'value').set;
        const event = new Event('input', { bubbles: true });

        setValue.call(node, value);
        node.dispatchEvent(event);

    }

};

linux script to kill java process

You can simply use pkill -f like this:

pkill -f 'java -jar'

EDIT: To kill a particular java process running your specific jar use this regex based pkill command:

pkill -f 'java.*lnwskInterface'

How do I make a matrix from a list of vectors in R?

Not straightforward, but it works:

> t(sapply(a, unlist))
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

Best practice for localization and globalization of strings and labels

When you’re faced with a problem to solve (and frankly, who isn’t these days?), the basic strategy usually taken by we computer people is called “divide and conquer.” It goes like this:

  • Conceptualize the specific problem as a set of smaller sub-problems.
  • Solve each smaller problem.
  • Combine the results into a solution of the specific problem.

But “divide and conquer” is not the only possible strategy. We can also take a more generalist approach:

  • Conceptualize the specific problem as a special case of a more general problem.
  • Somehow solve the general problem.
  • Adapt the solution of the general problem to the specific problem.

- Eric Lippert

I believe many solutions already exist for this problem in server-side languages such as ASP.Net/C#.

I've outlined some of the major aspects of the problem

  • Issue: We need to load data only for the desired language

    Solution: For this purpose we save data to a separate files for each language

ex. res.de.js, res.fr.js, res.en.js, res.js(for default language)

  • Issue: Resource files for each page should be separated so we only get the data we need

    Solution: We can use some tools that already exist like https://github.com/rgrove/lazyload

  • Issue: We need a key/value pair structure to save our data

    Solution: I suggest a javascript object instead of string/string air. We can benefit from the intellisense from an IDE

  • Issue: General members should be stored in a public file and all pages should access them

    Solution: For this purpose I make a folder in the root of web application called Global_Resources and a folder to store global file for each sub folders we named it 'Local_Resources'

  • Issue: Each subsystems/subfolders/modules member should override the Global_Resources members on their scope

    Solution: I considered a file for each

Application Structure

root/
    Global_Resources/
        default.js
        default.fr.js
    UserManagementSystem/
        Local_Resources/
            default.js
            default.fr.js
            createUser.js
        Login.htm
        CreateUser.htm

The corresponding code for the files:

Global_Resources/default.js

var res = {
    Create : "Create",
    Update : "Save Changes",
    Delete : "Delete"
};

Global_Resources/default.fr.js

var res = {
    Create : "créer",
    Update : "Enregistrer les modifications",
    Delete : "effacer"
};

The resource file for the desired language should be loaded on the page selected from Global_Resource - This should be the first file that is loaded on all the pages.

UserManagementSystem/Local_Resources/default.js

res.Name = "Name";
res.UserName = "UserName";
res.Password = "Password";

UserManagementSystem/Local_Resources/default.fr.js

res.Name = "nom";
res.UserName = "Nom d'utilisateur";
res.Password = "Mot de passe";

UserManagementSystem/Local_Resources/createUser.js

// Override res.Create on Global_Resources/default.js
res.Create = "Create User"; 

UserManagementSystem/Local_Resources/createUser.fr.js

// Override Global_Resources/default.fr.js
res.Create = "Créer un utilisateur";

manager.js file (this file should be load last)

res.lang = "fr";

var globalResourcePath = "Global_Resources";
var resourceFiles = [];

var currentFile = globalResourcePath + "\\default" + res.lang + ".js" ;

if(!IsFileExist(currentFile))
    currentFile = globalResourcePath + "\\default.js" ;
if(!IsFileExist(currentFile)) throw new Exception("File Not Found");

resourceFiles.push(currentFile);

// Push parent folder on folder into folder
foreach(var folder in parent folder of current page)
{
    currentFile = folder + "\\Local_Resource\\default." + res.lang + ".js";

    if(!IsExist(currentFile))
        currentFile = folder + "\\Local_Resource\\default.js";
    if(!IsExist(currentFile)) throw new Exception("File Not Found");

    resourceFiles.push(currentFile);
}

for(int i = 0; i < resourceFiles.length; i++) { Load.js(resourceFiles[i]); }

// Get current page name
var pageNameWithoutExtension = "SomePage";

currentFile = currentPageFolderPath + pageNameWithoutExtension + res.lang + ".js" ;

if(!IsExist(currentFile))
    currentFile = currentPageFolderPath + pageNameWithoutExtension + ".js" ;
if(!IsExist(currentFile)) throw new Exception("File Not Found");

Hope it helps :)

How can I pad an integer with zeros on the left?

int x = 1;
System.out.format("%05d",x);

if you want to print the formatted text directly onto the screen.

How to count rows with SELECT COUNT(*) with SQLAlchemy?

If you are using the SQL Expression Style approach there is another way to construct the count statement if you already have your table object.

Preparations to get the table object. There are also different ways.

import sqlalchemy

database_engine = sqlalchemy.create_engine("connection string")

# Populate existing database via reflection into sqlalchemy objects
database_metadata = sqlalchemy.MetaData()
database_metadata.reflect(bind=database_engine)

table_object = database_metadata.tables.get("table_name") # This is just for illustration how to get the table_object                    

Issuing the count query on the table_object

query = table_object.count()
# This will produce something like, where id is a primary key column in "table_name" automatically selected by sqlalchemy
# 'SELECT count(table_name.id) AS tbl_row_count FROM table_name'

count_result = database_engine.scalar(query)

Google Drive as FTP Server

I couldn't find a direct GDrive/DropBox solution. I'm also surprised there's no lazy solution for a free ftp host. Windows azure offers a ftp server "FTP connector" that's fairly easy to turn on at: https://portal.azure.com

You can get a free 1 GB account by selecting "View All" machine types during your deployment.

MySQL: ERROR 1227 (42000): Access denied - Cannot CREATE USER

First thing to do is run this:

SHOW GRANTS;

You will quickly see you were assigned the anonymous user to authenticate into mysql.

Instead of logging into mysql with

mysql

login like this:

mysql -uroot

By default, root@localhost has all rights and no password.

If you cannot login as root without a password, do the following:

Step 01) Add the two options in the mysqld section of my.ini:

[mysqld]
skip-grant-tables
skip-networking

Step 02) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 03) Connect to mysql

mysql

Step 04) Create a password from root@localhost

UPDATE mysql.user SET password=password('whateverpasswordyoulike')
WHERE user='root' AND host='localhost';
exit

Step 05) Restart mysql

net stop mysql
<wait 10 seconds>
net start mysql

Step 06) Login as root with password

mysql -u root -p

You should be good from there.

CAVEAT: Please remove anonymous users !!!

How can I check Drupal log files?

Make sure drush is installed (you may also need to make sure the dblog module is enabled) and use:

drush watchdog-show --tail

Available in drush v8 and below.

This will give you a live look at the logs from your console.

Define preprocessor macro through CMake?

The other solution proposed on this page are useful some versions of Cmake < 3.3.2. Here the solution for the version I am using (i.e., 3.3.2). Check the version of your Cmake by using $ cmake --version and pick the solution that fits with your needs. The cmake documentation can be found on the official page.

With CMake version 3.3.2, in order to create

#define foo

I needed to use:

add_definitions(-Dfoo)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

and, in order to have a preprocessor macro definition like this other one:

#define foo=5

the line is so modified:

add_definitions(-Dfoo=5)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

What is the right way to populate a DropDownList from a database?

public void getClientNameDropDowndata()
{
    getConnection = Connection.SetConnection(); // to connect with data base Configure manager
    string ClientName = "Select  ClientName from Client ";
    SqlCommand ClientNameCommand = new SqlCommand(ClientName, getConnection);
    ClientNameCommand.CommandType = CommandType.Text;
    SqlDataReader ClientNameData;
    ClientNameData = ClientNameCommand.ExecuteReader();
    if (ClientNameData.HasRows)
    {
        DropDownList_ClientName.DataSource = ClientNameData;
        DropDownList_ClientName.DataValueField = "ClientName";
        DropDownList_ClientName.DataTextField="ClientName";
        DropDownList_ClientName.DataBind();
    }
    else
    {
        MessageBox.Show("No is found");
        CloseConnection = new Connection();
        CloseConnection.closeConnection(); // close the connection 
    }
}

LocalDate to java.util.Date and vice versa simplest conversion?

Actually there is. There is a static method valueOf in the java.sql.Date object which does exactly that. So we have

java.util.Date date = java.sql.Date.valueOf(localDate);

and that's it. No explicit setting of time zones because the local time zone is taken implicitly.

From docs:

The provided LocalDate is interpreted as the local date in the local time zone.

The java.sql.Date subclasses java.util.Date so the result is a java.util.Date also.

And for the reverse operation there is a toLocalDate method in the java.sql.Date class. So we have:

LocalDate ld = new java.sql.Date(date.getTime()).toLocalDate();

Play sound on button click android

public class MainActivity extends AppCompatActivity {

    public void clickMe (View view) {

        MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);
        mp.start();

    }

create a button with a method could be called when the button pressed (onCreate),

then create a variable for (MediaPlayer) class with the path of your file

MediaPlayer mp = MediaPlayer.create(this, R.raw.xxx);

finally run start method in that class

mp.start();

the file will run when the button pressed, hope this was helpful!

How to create a shortcut using PowerShell

Beginning PowerShell 5.0 New-Item, Remove-Item, and Get-ChildItem have been enhanced to support creating and managing symbolic links. The ItemType parameter for New-Item accepts a new value, SymbolicLink. Now you can create symbolic links in a single line by running the New-Item cmdlet.

New-Item -ItemType SymbolicLink -Path "C:\temp" -Name "calc.lnk" -Value "c:\windows\system32\calc.exe"

Be Carefull a SymbolicLink is different from a Shortcut, shortcuts are just a file. They have a size (A small one, that just references where they point) and they require an application to support that filetype in order to be used. A symbolic link is filesystem level, and everything sees it as the original file. An application needs no special support to use a symbolic link.

Anyway if you want to create a Run As Administrator shortcut using Powershell you can use

$file="c:\temp\calc.lnk"
$bytes = [System.IO.File]::ReadAllBytes($file)
$bytes[0x15] = $bytes[0x15] -bor 0x20 #set byte 21 (0x15) bit 6 (0x20) ON (Use –bor to set RunAsAdministrator option and –bxor to unset)
[System.IO.File]::WriteAllBytes($file, $bytes)

If anybody want to change something else in a .LNK file you can refer to official Microsoft documentation.

Jquery UI tooltip does not support html content

another solution will be to grab the text inside the title tag & then use .html() method of jQuery to construct the content of the tooltip.

$(function() {
  $(document).tooltip({
    position: {
      using: function(position, feedback) {
        $(this).css(position);
        var txt = $(this).text();
        $(this).html(txt);
        $("<div>")
          .addClass("arrow")
          .addClass(feedback.vertical)
          .addClass(feedback.horizontal)
          .appendTo(this);
      }
    }
  });
});

Example: http://jsfiddle.net/hamzeen/0qwxfgjo/

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

Just what is an IntPtr exactly?

What is a Pointer?

In all languages, a pointer is a type of variable that stores a memory address, and you can either ask them to tell you the address they are pointing at or the value at the address they are pointing at.

A pointer can be thought of as a sort-of book mark. Except, instead of being used to jump quickly to a page in a book, a pointer is used to keep track of or map blocks of memory.

Imagine your program's memory precisely like one big array of 65535 bytes.

Pointers point obediently

Pointers remember one memory address each, and therefore they each point to a single address in memory.

As a group, pointers remember and recall memory addresses, obeying your every command ad nauseum.

You are their king.

Pointers in C#

Specifically in C#, a pointer is an integer variable that stores a memory address between 0 and 65534.

Also specific to C#, pointers are of type int and therefore signed.

You can't use negatively numbered addresses though, neither can you access an address above 65534. Any attempt to do so will throw a System.AccessViolationException.

A pointer called MyPointer is declared like so:

int *MyPointer;

A pointer in C# is an int, but memory addresses in C# begin at 0 and extend as far as 65534.

Pointy things should be handled with extra special care

The word unsafe is intended to scare you, and for a very good reason: Pointers are pointy things, and pointy things e.g. swords, axes, pointers, etc. should be handled with extra special care.

Pointers give the programmer tight control of a system. Therefore mistakes made are likely to have more serious consequences.

In order to use pointers, unsafe code has to be enabled in your program's properties, and pointers have to be used exclusively in methods or blocks marked as unsafe.

Example of an unsafe block

unsafe
{
    // Place code carefully and responsibly here.

}

How to use Pointers

When variables or objects are declared or instantiated, they are stored in memory.

  • Declare a pointer by using the * symbol prefix.

int *MyPointer;

  • To get the address of a variable, you use the & symbol prefix.

MyPointer = &MyVariable;

Once an address is assigned to a pointer, the following applies:

  • Without * prefix to refer to the memory address being pointed to as an int.

MyPointer = &MyVariable; // Set MyPointer to point at MyVariable

  • With * prefix to get the value stored at the memory address being pointed to.

"MyPointer is pointing at " + *MyPointer;

Since a pointer is a variable that holds a memory address, this memory address can be stored in a pointer variable.

Example of pointers being used carefully and responsibly

    public unsafe void PointerTest()
    {
        int x = 100; // Create a variable named x

        int *MyPointer = &x; // Store the address of variable named x into the pointer named MyPointer

        textBox1.Text = ((int)MyPointer).ToString(); // Displays the memory address stored in pointer named MyPointer

        textBox2.Text = (*MyPointer).ToString(); // Displays the value of the variable named x via the pointer named MyPointer.

    }

Notice the type of the pointer is an int. This is because C# interprets memory addresses as integer numbers (int).

Why is it int instead of uint?

There is no good reason.

Why use pointers?

Pointers are a lot of fun. With so much of the computer being controlled by memory, pointers empower a programmer with more control of their program's memory.

Memory monitoring.

Use pointers to read blocks of memory and monitor how the values being pointed at change over time.

Change these values responsibly and keep track of how your changes affect your computer.

Custom HTTP Authorization Header

Old question I know, but for the curious:

Believe it or not, this issue was solved ~2 decades ago with HTTP BASIC, which passes the value as base64 encoded username:password. (See http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side)

You could do the same, so that the example above would become:

Authorization: FIRE-TOKEN MFBONUoxN0hCR1pIVDdKSjNYODI6ZnJKSVVOOERZcEtEdE9MQ3dvLy95bGxxRHpnPQ==

Selecting empty text input using jQuery

Building on @James Wiseman's answer, I am using this:

$.extend($.expr[':'],{
    blank: function(el){
        return $(el).val().match(/^\s*$/);
    }
});

This will catch inputs which contain only whitespace in addition to those which are 'truly' empty.

Example: http://jsfiddle.net/e9btdbyn/

How to make a flex item not fill the height of the flex container?

The align-items, or respectively align-content attribute controls this behaviour.

align-items defines the items' positioning perpendicularly to flex-direction.

The default flex-direction is row, therfore vertical placement can be controlled with align-items.

There is also the align-self attribute to control the alignment on a per item basis.

_x000D_
_x000D_
#a {_x000D_
  display:flex;_x000D_
_x000D_
  align-items:flex-start;_x000D_
  align-content:flex-start;_x000D_
  }_x000D_
_x000D_
#a > div {_x000D_
  _x000D_
  background-color:red;_x000D_
  padding:5px;_x000D_
  margin:2px;_x000D_
  }_x000D_
 #a > #c {_x000D_
  align-self:stretch;_x000D_
 }
_x000D_
<div id="a">_x000D_
  _x000D_
  <div id="b">left</div>_x000D_
  <div id="c">middle</div>_x000D_
  <div>right<br>right<br>right<br>right<br>right<br></div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

css-tricks has an excellent article on the topic. I recommend reading it a couple of times.

How to make the first option of <select> selected with jQuery

For me it only worked when I added the following code:

.change();

For me it only worked when I added the following code: As I wanted to "reset" the form, that is, select all the first options of all the selects of the form, I used the following code:

$('form').find('select').each(function(){ $(this).val($("select option:first").val()); $(this).change(); });

Firefox "ssl_error_no_cypher_overlap" error

"Error code: ssl_error_no_cypher_overlap" error message after login, when Welcome screen expected--using Firefox browser

Solution

Enable support for 40-bit RSA encryption in the Firefox Browser: 1: enter 'about:config' in Browser Address bar 2: find/select "security.ssl3.rsa_rc4_40_md5" 3: set boolean to TRUE

Git push failed, "Non-fast forward updates were rejected"

This is what worked for me. It can be found in git documentation here

If you are on your desired branch you can do this:

git fetch origin
# Fetches updates made to an online repository
git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work

How to exclude subdirectories in the destination while using /mir /xd switch in robocopy

Rather than creating empty directories in source to exclude, you can supply the full destination path to the /XD switch to have the destination directories untouched

robocopy "%SOURCE_PATH%" "%DEST_PATH%" /MIR /XD "%DEST_PATH%"\hq04s2dba301

Is it possible to deserialize XML into List<T>?

I think I have found a better way. You don't have to put attributes into your classes. I've made two methods for serialization and deserialization which take generic list as parameter.

Take a look (it works for me):

private void SerializeParams<T>(XDocument doc, List<T> paramList)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(paramList.GetType());

        System.Xml.XmlWriter writer = doc.CreateWriter();

        serializer.Serialize(writer, paramList);

        writer.Close();           
    }

private List<T> DeserializeParams<T>(XDocument doc)
    {
        System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<T>));

        System.Xml.XmlReader reader = doc.CreateReader();

        List<T> result = (List<T>)serializer.Deserialize(reader);
        reader.Close();

        return result;
    }

So you can serialize whatever list you want! You don't need to specify the list type every time.

        List<AssemblyBO> list = new List<AssemblyBO>();
        list.Add(new AssemblyBO());
        list.Add(new AssemblyBO() { DisplayName = "Try", Identifier = "243242" });
        XDocument doc = new XDocument();
        SerializeParams<T>(doc, list);
        List<AssemblyBO> newList = DeserializeParams<AssemblyBO>(doc);

ImportError: No module named google.protobuf

This solved my problem with google.protobuf import in Tensorflow and Python 3.7.5 that i had yesterday.

Check where is protobuf

pip show protobuf

If it is installed you will get something like this

Name: protobuf
Version: 3.6.1
Summary: Protocol Buffers
Home-page: https://developers.google.com/protocol-buffers/
Author: None
Author-email: None
License: 3-Clause BSD License
Location: /usr/lib/python3/dist-packages
Requires: 
Required-by: tensorflow, tensorboard

(If not, run pip install protobuf )

Now move into the location folder.

cd /usr/lib/python3/dist-packages

Now run

touch google/__init__.py

How do I get unique elements in this array?

You can just use the method uniq. Assuming your array is ary, call:

ary.uniq{|x| x.user_id}

and this will return a set with unique user_ids.

How to determine total number of open/active connections in ms sql server 2005

Use this to get an accurate count for each connection pool (assuming each user/host process uses the same connection string)

SELECT 
DB_NAME(dbid) as DBName, 
COUNT(dbid) as NumberOfConnections,
loginame as LoginName, hostname, hostprocess
FROM
sys.sysprocesses with (nolock)
WHERE 
dbid > 0
GROUP BY 
dbid, loginame, hostname, hostprocess

Java: Replace all ' in a string with \'

You can use apache's commons-text library (instead of commons-lang):

Example code:

org.apache.commons.text.StringEscapeUtils.escapeJava(escapedString);

Dependency:

compile 'org.apache.commons:commons-text:1.8'

OR

<dependency>
   <groupId>org.apache.commons</groupId>
   <artifactId>commons-text</artifactId>
   <version>1.8</version>
</dependency>

How can I limit ngFor repeat to some number of items in Angular?

This works very well:

<template *ngFor="let item of items; let i=index" >
 <ion-slide *ngIf="i<5" >
  <img [src]="item.ItemPic">
 </ion-slide>
</template>

How to redirect stderr and stdout to different files in the same line in script?

Just add them in one line command 2>> error 1>> output

However, note that >> is for appending if the file already has data. Whereas, > will overwrite any existing data in the file.

So, command 2> error 1> output if you do not want to append.

Just for completion's sake, you can write 1> as just > since the default file descriptor is the output. so 1> and > is the same thing.

So, command 2> error 1> output becomes, command 2> error > output

setting global sql_mode in mysql

In my case i have to change file /etc/mysql/mysql.conf.d/mysqld.cnf change this under [mysqld]

Paste this line on [mysqld] portion

sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Getting indices of True values in a boolean list

Use dictionary comprehension way,

x = {k:v for k,v in enumerate(states) if v == True}

Input:

states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]

Output:

{4: True, 5: True, 7: True}

varbinary to string on SQL Server

The following expression worked for me:

SELECT CONVERT(VARCHAR(1000), varbinary_value, 2);

Here are more details on the choice of style (the third parameter).

Error: Cannot pull with rebase: You have unstaged changes

First start with a git status

See if you have any pending changes. To discard them, run

git reset --hard

Serializing an object as UTF-8 XML in .NET

I found this blog post which explains the problem very well, and defines a few different solutions:

(dead link removed)

I've settled for the idea that the best way to do it is to completely omit the XML declaration when in memory. It actually is UTF-16 at that point anyway, but the XML declaration doesn't seem meaningful until it has been written to a file with a particular encoding; and even then the declaration is not required. It doesn't seem to break deserialization, at least.

As @Jon Hanna mentions, this can be done with an XmlWriter created like this:

XmlWriter writer = XmlWriter.Create (output, new XmlWriterSettings() { OmitXmlDeclaration = true });

Setting default value for TypeScript object passed as argument

No, TypeScript doesn't have a natural way of setting defaults for properties of an object defined like that where one has a default and the other does not. You could define a richer structure:

class Name {
    constructor(public first : string, 
        public last: string = "Smith") {

    }
}

And use that in place of the inline type definition.

function sayName(name: Name) {
    alert(name.first + " " + name.last);
}

You can't do something like this unfortunately:

function sayName(name : { first: string; last?:string } 
       /* and then assign a default object matching the signature */  
       = { first: null, last: 'Smith' }) {

} 

As it would only set the default if name was undefined.

Create nice column output in python

Transposing the columns like that is a job for zip:

>>> a = [['a', 'b', 'c'], ['aaaaaaaaaa', 'b', 'c'], ['a', 'bbbbbbbbbb', 'c']]
>>> list(zip(*a))
[('a', 'aaaaaaaaaa', 'a'), ('b', 'b', 'bbbbbbbbbb'), ('c', 'c', 'c')]

To find the required length of each column, you can use max:

>>> trans_a = zip(*a)
>>> [max(len(c) for c in b) for b in trans_a]
[10, 10, 1]

Which you can use, with suitable padding, to construct strings to pass to print:

>>> col_lenghts = [max(len(c) for c in b) for b in trans_a]
>>> padding = ' ' # You might want more
>>> padding.join(s.ljust(l) for s,l in zip(a[0], col_lenghts))
'a          b          c'

anchor jumping by using javascript

Because when you do

window.location.href = "#"+anchor;

You load a new page, you can do:

<a href="#" onclick="jumpTo('one');">One</a>
<a href="#" id="one"></a>

<script>

    function getPosition(element){
        var e = document.getElementById(element);
        var left = 0;
        var top = 0;

        do{
            left += e.offsetLeft;
            top += e.offsetTop;
        }while(e = e.offsetParent);

        return [left, top];
    }

    function jumpTo(id){    
        window.scrollTo(getPosition(id));
    }

</script>

Sorting dictionary keys in python

>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']

How can I extract a predetermined range of lines from a text file on Unix?

Just benchmarking 3 solutions given above, that works to me:

  • awk
  • sed
  • "head+tail"

Credits on the 3 solutions goes to:

  • @boxxar
  • @avandeursen
  • @wds
  • @manveru
  • @sibaz
  • @SOFe
  • @fedorqui 'SO stop harming'
  • @Robin A. Meade

I'm using a huge file I find in my server:

# wc fo2debug.1.log
   10421186    19448208 38795491134 fo2debug.1.log

38 Gb in 10.4 million lines.

And yes, I have a logrotate problem. : ))


Make your bets!


Getting 256 lines from the beginning of the file.

# time sed -n '1001,1256p;1256q' fo2debug.1.log | wc -l
256

real    0m0,003s
user    0m0,000s
sys     0m0,004s

# time head -1256 fo2debug.1.log | tail -n +1001 | wc -l
256

real    0m0,003s
user    0m0,006s
sys     0m0,000s

# time awk 'NR==1001, NR==1256; NR==1256 {exit}' fo2debug.1.log | wc -l
256

real    0m0,002s
user    0m0,004s
sys     0m0,000s

Awk won. Technical tie in second place between sed and "head+tail".


Getting 256 lines at the end of the first third of the file.

# time sed -n '3473001,3473256p;3473256q' fo2debug.1.log | wc -l
256

real    0m0,265s
user    0m0,242s
sys     0m0,024s

# time head -3473256 fo2debug.1.log | tail -n +3473001 | wc -l
256

real    0m0,308s
user    0m0,313s
sys     0m0,145s

# time awk 'NR==3473001, NR==3473256; NR==3473256 {exit}' fo2debug.1.log | wc -l
256

real    0m0,393s
user    0m0,326s
sys     0m0,068s

Sed won. Followed by "head+tail" and, finally, awk.


Getting 256 lines at the end of the second third of the file.

# time sed -n '6947001,6947256p;6947256q' fo2debug.1.log | wc -l
A256

real    0m0,525s
user    0m0,462s
sys     0m0,064s

# time head -6947256 fo2debug.1.log | tail -n +6947001 | wc -l
256

real    0m0,615s
user    0m0,488s
sys     0m0,423s

# time awk 'NR==6947001, NR==6947256; NR==6947256 {exit}' fo2debug.1.log | wc -l
256

real    0m0,779s
user    0m0,650s
sys     0m0,130s

Same results.

Sed won. Followed by "head+tail" and, finally, awk.


Getting 256 lines near the end of the file.

# time sed -n '10420001,10420256p;10420256q' fo2debug.1.log | wc -l
256

real    1m50,017s
user    0m12,735s
sys     0m22,926s

# time head -10420256 fo2debug.1.log | tail -n +10420001 | wc -l
256

real    1m48,269s
user    0m42,404s
sys     0m51,015s

# time awk 'NR==10420001, NR==10420256; NR==10420256 {exit}' fo2debug.1.log | wc -l
256

real    1m49,106s
user    0m12,322s
sys     0m18,576s

And suddenly, a twist!

"Head+tail" won. Followed by awk and, finally, sed.


(some hours later...)

Sorry guys!

My analysis above ends up being an example of a basic flaw in doing an analysis.

The flaw is not knowing in depth the resources used for the analysis.

In this case, I used a log file to analyze the performance of a search for a certain number of lines within it.

Using 3 different techniques, searches were made at different points in the file, comparing the performance of the techniques at each point and checking whether the results varied depending on the point in the file where the search was made.

My mistake was to assume that there was a certain homogeneity of content in the log file.

The reality is that long lines appear more frequently at the end of the file.

Thus, the apparent conclusion that longer searches (closer to the end of the file) are better with a given technique, may be biased. In fact, this technique may be better when dealing with longer lines. What remains to be confirmed.

FirstOrDefault: Default value other than null

You can also do this

    Band[] objects = { new Band { Name = "Iron Maiden" } };
    first = objects.Where(o => o.Name == "Slayer")
        .DefaultIfEmpty(new Band { Name = "Black Sabbath" })
        .FirstOrDefault();   // returns "Black Sabbath" 

This uses only linq - yipee!

How do I view the SSIS packages in SQL Server Management Studio?

Came across SSIS package that schedule to run as sql job, you can identify where the SSIS package located by looking at the sql job properties; SQL job -> properties -> Steps (from select a page on left side) -> select job (from job list) -> edit -> job step properties shows up this got all the configuration for SSIS package, including its original path, in my case its under “MSDB”

Now connect to sql integration services; - open sql management studio - select server type to “integration services” - enter server name - you will see your SSIS package under “stored packages”

to edit the package right click and export to “file system” you’ll get file with extension .dtx it can be open in visual studio, I used the version visual studio 2012

How to POST JSON data with Python Requests?

The better way is:

url = "http://xxx.xxxx.xx"
data = {
    "cardno": "6248889874650987",
    "systemIdentify": "s08",
    "sourceChannel": 12
}
resp = requests.post(url, json=data)

How to add a new audio (not mixing) into a video using ffmpeg?

Replace audio

diagram of audio stream replacement

ffmpeg -i video.mp4 -i audio.wav -map 0:v -map 1:a -c:v copy -shortest output.mp4
  • The -map option allows you to manually select streams / tracks. See FFmpeg Wiki: Map for more info.
  • This example uses -c:v copy to stream copy (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
    • If your input audio format is compatible with the output format then change -c:v copy to -c copy to stream copy both the video and audio.
    • If you want to re-encode video and audio then remove -c:v copy / -c copy.
  • The -shortest option will make the output the same duration as the shortest input.

Add audio

diagram of audio stream addition

ffmpeg -i video.mkv -i audio.mp3 -map 0 -map 1:a -c:v copy -shortest output.mkv
  • The -map option allows you to manually select streams / tracks. See FFmpeg Wiki: Map for more info.
  • This example uses -c:v copy to stream copy (mux) the video. No re-encoding of the video occurs. Quality is preserved and the process is fast.
    • If your input audio format is compatible with the output format then change -c:v copy to -c copy to stream copy both the video and audio.
    • If you want to re-encode video and audio then remove -c:v copy / -c copy.
  • The -shortest option will make the output the same duration as the shortest input.

Mixing/combining two audio inputs into one

diagram of audio downmix

Use video from video.mkv. Mix audio from video.mkv and audio.m4a using the amerge filter:

ffmpeg -i video.mkv -i audio.m4a -filter_complex "[0:a][1:a]amerge=inputs=2[a]" -map 0:v -map "[a]" -c:v copy -ac 2 -shortest output.mkv

See FFmpeg Wiki: Audio Channels for more info.

Generate silent audio

You can use the anullsrc filter to make a silent audio stream. The filter allows you to choose the desired channel layout (mono, stereo, 5.1, etc) and the sample rate.

ffmpeg -i video.mp4 -f lavfi -i anullsrc=channel_layout=stereo:sample_rate=44100 \
-c:v copy -shortest output.mp4

Also see

Using the grep and cut delimiter command (in bash shell scripting UNIX) - and kind of "reversing" it?

You don't need to change the delimiter to display the right part of the string with cut.

The -f switch of the cut command is the n-TH element separated by your delimiter : :, so you can just type :

 grep puddle2_1557936 | cut -d ":" -f2

Another solutions (adapt it a bit) if you want fun :

Using :

grep -oP 'puddle2_1557936:\K.*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                        
/home/rogers.williams/folderz/puddle2

or still with look around

grep -oP '(?<=puddle2_1557936:).*' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                                    
/home/rogers.williams/folderz/puddle2

or with :

perl -lne '/puddle2_1557936:(.*)/ and print $1' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'                                                      
/home/rogers.williams/folderz/puddle2

or using (thanks to glenn jackman)

ruby -F: -ane '/puddle2_1557936/ and puts $F[1]' <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

awk -F'puddle2_1557936:' '{print $2}'  <<< 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or with :

python -c 'import sys; print(sys.argv[1].split("puddle2_1557936:")[1])' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
/home/rogers.williams/folderz/puddle2

or using only :

IFS=: read _ a <<< "puddle2_1557936:/home/rogers.williams/folderz/puddle2"
echo "$a"
/home/rogers.williams/folderz/puddle2

or using in a :

js<<EOF
var x = 'puddle2_1557936:/home/rogers.williams/folderz/puddle2'
print(x.substr(x.indexOf(":")+1))
EOF
/home/rogers.williams/folderz/puddle2

or using in a :

php -r 'preg_match("/puddle2_1557936:(.*)/", $argv[1], $m); echo "$m[1]\n";' 'puddle2_1557936:/home/rogers.williams/folderz/puddle2' 
/home/rogers.williams/folderz/puddle2

How to force a component's re-rendering in Angular 2?

Rendering happens after change detection. To force change detection, so that component property values that have changed get propagated to the DOM (and then the browser will render those changes in the view), here are some options:

  • ApplicationRef.tick() - similar to Angular 1's $rootScope.$digest() -- i.e., check the full component tree
  • NgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular 2 zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.
  • ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

You will need to import and then inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

For your particular scenario, I would recommend the last option if only a single component has changed.

How to enable file sharing for my app?

You just have to set UIFileSharingEnabled (Application Supports iTunes file sharing) key in the info plist of your app. Here's a link for the documentation. Scroll down to the file sharing support part.

In the past, it was also necessary to define CFBundleDisplayName (Bundle Display Name), if it wasn't already there. More details here.

How to SUM parts of a column which have same text value in different column in the same row

A PivotTable might suit, though I am not quite certain of the layout of your data:

SO19669814 example

The bold numbers (one of each pair of duplicates) need not be shown as the field does not have to be subtotalled eg:

SO19669814 second example

DynamoDB vs MongoDB NoSQL

Short answer: Start with SQL and add NoSQL only when/if needed. (unless you don't need anything beyond very simple queries)

My personal experience: I haven't used MongoDB for queries but as of April 2015 DynamoDB is still very crippled when it comes to anything beyond the most basic key/value queries. I love it for the basic stuff but if you want query language then look to a real SQL database solution.

In DynamoDB you can query on a hash or on a hash and range key, and you can have multiple secondary global indexes. I'm doing queries on a single table with 4 possible filter parameters and sorting the results, this is supported (barely) through the use of the global secondary indexes with filter expressions. The problem comes in when you try to get the total results matching the filter, you can't just search for the first 10 items matching the filter, but rather it checks 10 items and you may get 0 valid results forcing you to keep re-scanning from the continue key - pain in the neck and consumes too much of your table read quota for a simple scenario.

To be specific about the limit problem with filters in the query, this is from the docs (http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/QueryAndScan.html#ScanQueryLimit):

In a response, DynamoDB returns all the matching results within
the scope of the Limit value. For example, if you issue a Query 
or a Scan request with a Limit value of 6 and without a filter
expression, the operation returns the first six items in the 
table that match the request parameters. If you also supply a
FilterExpression, the operation returns the items within the 
first six items in the table that match the filter requirements.

My conclusion is that queries involving FilterExpressions are only usable on very rare occasions and are not scalable because each query can easily read most or all of your of your table which consumes far too many DynamoDB read units. Once you use too many read units you'll get throttled and see poor performance.

Expert opinion: In the AWS summit on Apr 9, 2015 Brett Hollman, Manager, Solutions Architecture, AWS in his talk on scalling to your first 10 million users advocates starting with a SQL database and then using NoSQL only when and if it makes sense. Because sooner or later you'll probably need a SQL server somewhere in your stack. His slides are here: http://www.slideshare.net/AmazonWebServices/deep-dive-scaling-up-to-your-first-10-million-users See slide 28.

Purpose of __repr__ method?

When we create new types by defining classes, we can take advantage of certain features of Python to make the new classes convenient to use. One of these features is "special methods", also referred to as "magic methods".

Special methods have names that begin and end with two underscores. We define them, but do not usually call them directly by name. Instead, they execute automatically under under specific circumstances.

It is convenient to be able to output the value of an instance of an object by using a print statement. When we do this, we would like the value to be represented in the output in some understandable unambiguous format. The repr special method can be used to arrange for this to happen. If we define this method, it can get called automatically when we print the value of an instance of a class for which we defined this method. It should be mentioned, though, that there is also a str special method, used for a similar, but not identical purpose, that may get precedence, if we have also defined it.

If we have not defined, the repr method for the Point3D class, and have instantiated my_point as an instance of Point3D, and then we do this ...

print my_point ... we may see this as the output ...

Not very nice, eh?

So, we define the repr or str special method, or both, to get better output.

**class Point3D(object):
    def __init__(self,a,b,c):
        self.x = a
        self.y = b
        self.z = c
    def __repr__(self):
        return "Point3D(%d, %d, %d)" % (self.x, self.y, self.z)
    def __str__(self):
        return "(%d, %d, %d)" % (self.x, self.y, self.z)
my_point = Point3D(1, 2, 3)
print my_point # __repr__ gets called automatically
print my_point # __str__ gets called automatically**

Output ...

(1, 2, 3) (1, 2, 3)

how do I get eclipse to use a different compiler version for Java?

Eclipse uses it's own internal compiler that can compile to several Java versions.

From Eclipse Help > Java development user guide > Concepts > Java Builder

The Java builder builds Java programs using its own compiler (the Eclipse Compiler for Java) that implements the Java Language Specification.

For Eclipse Mars.1 Release (4.5.1), this can target 1.3 to 1.8 inclusive.

When you configure a project:

[project-name] > Properties > Java Compiler > Compiler compliance level

This configures the Eclipse Java compiler to compile code to the specified Java version, typically 1.8 today.

Host environment variables, eg JAVA_HOME etc, are not used.

The Oracle/Sun JDK compiler is not used.

try/catch with InputMismatchException creates infinite loop

@Limp, your answer is right, just use .nextLine() while reading the input. Sample code:

    do {
        try {
            System.out.println("Enter first num: ");
            n1 = Integer.parseInt(input.nextLine());
            System.out.println("Enter second num: ");
            n2 = Integer.parseInt(input.nextLine());
            nQuotient = n1 / n2;
            bError = false;
        } catch (Exception e) {
            System.out.println("Error!");
        }
    } while (bError);

    System.out.printf("%d/%d = %d", n1, n2, nQuotient);

Read the description of why this problem was caused in the link below. Look for the answer I posted for the detail in this thread. Java Homework user input issue

Ok, I will briefly describe it. When you read input using nextInt(), you just read the number part but the ENDLINE character was still on the stream. That was the main cause. Now look at the code above, all I did is read the whole line and parse it , it still throws the exception and work the way you were expecting it to work. Rest of your code works fine.

regular expression for anything but an empty string

^(?!\s*$).+

will match any string that contains at least one non-space character.

So

if (Regex.IsMatch(subjectString, @"^(?!\s*$).+")) {
    // Successful match
} else {
    // Match attempt failed
}

should do this for you.

^ anchors the search at the start of the string.

(?!\s*$), a so-called negative lookahead, asserts that it's impossible to match only whitespace characters until the end of the string.

.+ will then actually do the match. It will match anything (except newline) up to the end of the string. If you want to allow newlines, you'll have to set the RegexOptions.Singleline option.


Left over from the previous version of your question:

^\s*$

matches strings that contain only whitespace (or are empty).

The exact opposite:

^\S+$

matches only strings that consist of only non-whitespace characters, one character minimum.

Git: "Corrupt loose object"

Your best bet is probably to simply re-clone from the remote repo (ie. Github or other). Unfortunately you will lose any unpushed commits and stashed changes, however your working copy should remain intact.

First make a backup copy of your local files. Then do this from the root of your working tree:

rm -fr .git
git init
git remote add origin [your-git-remote-url]
git fetch
git reset --mixed origin/master
git branch --set-upstream-to=origin/master master  

Then commit any changed files as necessary.

The APK file does not exist on disk

I got it to work by:

  1. Closing the project
  2. From the Android Studio Welcome Window (or File > New), click on Import Project.

I guess that forced it to reinstall the APK, and now everything is running fine.

Print the contents of a DIV

I authored a plugin to address this scenario. I was unhappy with the plugins out there, and set out to make something more extensive/configurable.

https://github.com/jasonday/printThis

Get my phone number in android

Robi Code is work for me, just put if !null so that if phone number is null, user can fill the phone number by him/her self.

editTextPhoneNumber = (EditText) findViewById(R.id.editTextPhoneNumber);
TelephonyManager tMgr;
tMgr= (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();
if (mPhoneNumber != null){
editTextPhoneNumber.setText(mPhoneNumber);
}

Selecting a row in DataGridView programmatically

You can use the Select method if you have a datasource: http://msdn.microsoft.com/en-us/library/b51xae2y%28v=vs.71%29.aspx

Or use linq if you have objects in you datasource

How can I access "static" class variables within class methods in Python?

bar is your static variable and you can access it using Foo.bar.

Basically, you need to qualify your static variable with Class name.

Is it possible to register a http+domain-based URL Scheme for iPhone apps, like YouTube and Maps?

It also possible to check tab activity by document.hidden property

Possible solution

document.location = 'app://deep-link';

setInterval( function(){
  if (!document.hidden) {
    document.location = 'https://app.store.link';
  }
}, 1000);

But seems like this not works in Safari

height style property doesn't work in div elements

Position absolute fixes it for me. I suggest also adding a semi-colon if you haven't already.

.container {
    width: 22.5%;
    size: 22.5% 22.5%;
    margin-top: 0%;
    border-radius: 10px;
    background-color: floralwhite;
    display:inline-block;
    min-height: 20%;
    position: absolute;
    height: 50%;
}

How can you have SharePoint Link Lists default to opening in a new window?

You can edit the page in SharePoint designer, convert the List View web part to an XSLT Data View. (by right click + "Convert to XSLT Data View").
Then you can edit the XSLT - find the A tag and add an attribute target="_blank"

How do you validate a URL with a regular expression in Python?

urlparse quite happily takes invalid URLs, it is more a string string-splitting library than any kind of validator. For example:

from urlparse import urlparse
urlparse('http://----')
# returns: ParseResult(scheme='http', netloc='----', path='', params='', query='', fragment='')

Depending on the situation, this might be fine..

If you mostly trust the data, and just want to verify the protocol is HTTP, then urlparse is perfect.

If you want to make the URL is actually a legal URL, use the ridiculous regex

If you want to make sure it's a real web address,

import urllib
try:
    urllib.urlopen(url)
except IOError:
    print "Not a real URL"

RecyclerView and java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder in Samsung devices

I had the same problem. It was caused because I delayed notification for adapter about item insert.

But ViewHolder tried to redraw some data in it's view and it started the RecyclerView measuring and recounting children count - at that moment it crashed (items list and it's size was already updated, but the adapter was not notified yet).

What's HTML character code 8203?

The ZERO WIDTH SPACE character is inserted when you use jQuery to add elements using DOM manipulation functions like .before() and .after()

I've run into this when adding hidden modal dialog frames at the end of my document and then finding that the ZERO WIDTH SPACE screws up the layout down there, adding unwanted space.

The quick fix was to insert it before the footer, not after it. Its hidden anyway.

I can't find anything in jQuery that does this:

https://github.com/jquery/jquery/blob/master/src/manipulation.js

So it might be the browser that adds it.

How to unescape a Java string literal in Java?

I came across the same problem, but I wasn't enamoured by any of the solutions I found here. So, I wrote one that iterates over the characters of the string using a matcher to find and replace the escape sequences. This solution assumes properly formatted input. That is, it happily skips over nonsensical escapes, and it decodes Unicode escapes for line feed and carriage return (which otherwise cannot appear in a character literal or a string literal, due to the definition of such literals and the order of translation phases for Java source). Apologies, the code is a bit packed for brevity.

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Decoder {

    // The encoded character of each character escape.
    // This array functions as the keys of a sorted map, from encoded characters to decoded characters.
    static final char[] ENCODED_ESCAPES = { '\"', '\'', '\\',  'b',  'f',  'n',  'r',  't' };

    // The decoded character of each character escape.
    // This array functions as the values of a sorted map, from encoded characters to decoded characters.
    static final char[] DECODED_ESCAPES = { '\"', '\'', '\\', '\b', '\f', '\n', '\r', '\t' };

    // A pattern that matches an escape.
    // What follows the escape indicator is captured by group 1=character 2=octal 3=Unicode.
    static final Pattern PATTERN = Pattern.compile("\\\\(?:(b|t|n|f|r|\\\"|\\\'|\\\\)|((?:[0-3]?[0-7])?[0-7])|u+(\\p{XDigit}{4}))");

    public static CharSequence decodeString(CharSequence encodedString) {
        Matcher matcher = PATTERN.matcher(encodedString);
        StringBuffer decodedString = new StringBuffer();
        // Find each escape of the encoded string in succession.
        while (matcher.find()) {
            char ch;
            if (matcher.start(1) >= 0) {
                // Decode a character escape.
                ch = DECODED_ESCAPES[Arrays.binarySearch(ENCODED_ESCAPES, matcher.group(1).charAt(0))];
            } else if (matcher.start(2) >= 0) {
                // Decode an octal escape.
                ch = (char)(Integer.parseInt(matcher.group(2), 8));
            } else /* if (matcher.start(3) >= 0) */ {
                // Decode a Unicode escape.
                ch = (char)(Integer.parseInt(matcher.group(3), 16));
            }
            // Replace the escape with the decoded character.
            matcher.appendReplacement(decodedString, Matcher.quoteReplacement(String.valueOf(ch)));
        }
        // Append the remainder of the encoded string to the decoded string.
        // The remainder is the longest suffix of the encoded string such that the suffix contains no escapes.
        matcher.appendTail(decodedString);
        return decodedString;
    }

    public static void main(String... args) {
        System.out.println(decodeString(args[0]));
    }
}

I should note that Apache Commons Lang3 doesn't seem to suffer the weaknesses indicated in the accepted solution. That is, StringEscapeUtils seems to handle octal escapes and multiple u characters of Unicode escapes. That means unless you have some burning reason to avoid Apache Commons, you should probably use it rather than my solution (or any other solution here).

Connection refused on docker container

You need to publish the exposed ports by using the following options:

-P (upper case) or --publish-all that will tell Docker to use random ports from your host and map them to the exposed container's ports.

-p (lower case) or --publish=[] that will tell Docker to use ports you manually set and map them to the exposed container's ports.

The second option is preferred because you already know which ports are mapped. If you use the first option then you will need to call docker inspect demo and check which random ports are being used from your host at the Ports section.

Just run the following command:

docker run -it -p 8080:8080 demo

After that your url will work.

Get folder name of the file in Python

You can use dirname:

os.path.dirname(path)

Return the directory name of pathname path. This is the first element of the pair returned by passing path to the function split().

And given the full path, then you can split normally to get the last portion of the path. For example, by using basename:

os.path.basename(path)

Return the base name of pathname path. This is the second element of the pair returned by passing path to the function split(). Note that the result of this function is different from the Unix basename program; where basename for '/foo/bar/' returns 'bar', the basename() function returns an empty string ('').


All together:

>>> import os
>>> path=os.path.dirname("C:/folder1/folder2/filename.xml")
>>> path
'C:/folder1/folder2'
>>> os.path.basename(path)
'folder2'

Regular expression to match exact number of characters?

What you have is correct, but this is more consice:

^[A-Z]{3}$

How to SUM and SUBTRACT using SQL?

I think this is what you're looking for. NEW_BAL is the sum of QTYs subtracted from the balance:

SELECT   master_table.ORDERNO,
         master_table.ITEM,
         SUM(master_table.QTY),
         stock_bal.BAL_QTY,
         (stock_bal.BAL_QTY - SUM(master_table.QTY)) AS NEW_BAL
FROM     master_table INNER JOIN
         stock_bal ON master_bal.ITEM = stock_bal.ITEM
GROUP BY master_table.ORDERNO,
         master_table.ITEM

If you want to update the item balance with the new balance, use the following:

UPDATE stock_bal
SET    BAL_QTY = BAL_QTY - (SELECT   SUM(QTY)
                            FROM     master_table
                            GROUP BY master_table.ORDERNO,
                                     master_table.ITEM)

This assumes you posted the subtraction backward; it subtracts the quantities in the order from the balance, which makes the most sense without knowing more about your tables. Just swap those two to change it if I was wrong:

(SUM(master_table.QTY) - stock_bal.BAL_QTY) AS NEW_BAL

How do I call a Django function on button click?

There are 2 possible solutions that I personally use

1.without using form

 <button type="submit" value={{excel_path}} onclick="location.href='{% url 'downloadexcel' %}'" name='mybtn2'>Download Excel file</button>

2.Using Form

<form action="{% url 'downloadexcel' %}" method="post">
{% csrf_token %}


 <button type="submit" name='mybtn2' value={{excel_path}}>Download results in Excel</button>
 </form>

Where urls.py should have this

path('excel/',views1.downloadexcel,name="downloadexcel"),

Query to get all rows from previous month

Alternative with single condition

SELECT * FROM table
WHERE YEAR(date_created) * 12 + MONTH(date_created)
    = YEAR(CURRENT_DATE) * 12 + MONTH(CURRENT_DATE) - 1

Tesseract running error

I'm using windows OS, I tried all solutions above and none of them work.

Finally, I install Tesseract-OCR on D drive(Where I run my python script from) instead of C drive and it works.

So, if you are using windows, run your python script in the same drive as your Tesseract-OCR.

Loop through list with both content and index

Like everyone else:

for i, val in enumerate(data):
    print i, val

but also

for i, val in enumerate(data, 1):
    print i, val

In other words, you can specify as starting value for the index/count generated by enumerate() which comes in handy if you don't want your index to start with the default value of zero.

I was printing out lines in a file the other day and specified the starting value as 1 for enumerate(), which made more sense than 0 when displaying information about a specific line to the user.

How to Convert a Text File into a List in Python

This looks like a CSV file, so you could use the python csv module to read it. For example:

import csv

crimefile = open(fileName, 'r')
reader = csv.reader(crimefile)
allRows = [row for row in reader]

Using the csv module allows you to specify how things like quotes and newlines are handled. See the documentation I linked to above.

Java maximum memory on Windows XP

Here is how to increase the Paging size

  1. right click on mycomputer--->properties--->Advanced
  2. in the performance section click settings
  3. click Advanced tab
  4. in Virtual memory section, click change. It will show ur current paging size.
  5. Select Drive where HDD space is available.
  6. Provide initial size and max size ...e.g. initial size 0 MB and max size 4000 MB. (As much as you will require)

jQuery: select an element's class and id at the same time?

Just to add that the answer that Alex provided worked for me, and not the one that is highlighted as an answer.

This one didn't work for me

$('#country.save') 

But this one did:

$('#country .save') 

so my conclusion is to use the space. Now I don't know if it's to the new version of jQuery that I'm using (1.5.1), but anyway hope this helps to anyone with similar problem that I've had.

edit: Full credit for explanation (in the comment to Alex's answer) goes to Felix Kling who says:

The space is the descendant selector, i.e. A B means "Match all elements that match B which are a descendant of elements matching A". AB means "select all element that match A and B". So it really depends on what you want to achieve. #country.save and #country .save are not equivalent.

How to center an element in the middle of the browser window?

you can center any object in viewport, here is an example using jquery

$(document).ready(function()
{


posicionar("#midiv");
$(window).on("resize", function() {
    posicionar("#midiv");   
});

function posicionar(elemento){
    var altoDocumento = $(window).height();//alto
    var anchoDocumento = $(window).width();
    //console.log(altoDocumento);
    //console.log(anchoDocumento);
    var centroXDocumento = anchoDocumento / 2;
    var centroYDocumento = altoDocumento / 2;
    //console.log(centroXDocumemnto,centroYDocumento);
    var altoElemento = $(elemento).outerHeight(true);//ancho real del elemento
    var anchoElemento = $(elemento).outerWidth(true);//alto 

    var centroXElemento = anchoElemento / 2;// centro x del elemento
    var centroYElemento = altoElemento / 2; // centro y del elemento

    var posicionXElemento = centroXDocumento - centroXElemento;
    var posicionYElemento = centroYDocumento - centroYElemento;

    $(elemento).css("position","absolute");
    $(elemento).css("top", posicionYElemento);
    $(elemento).css("left", posicionXElemento);
}
});

the html

<div id="midiv"></div>

Note: you must execute the function onDomReady and when the window resizes.

here is de jsfiddle http://jsfiddle.net/geomorillo/v82x6/

UITableView, Separator color where to set?

- (void)viewDidLoad
{
   [self.tableView setSeparatorColor:[UIColor myColor]];
}

I hope that helps - you'll need the self. to access it, remember.

Swift 4.2

tableView.separatorColor = UIColor.red

force line break in html table cell

I think what you're trying to do is wrap loooooooooooooong words or URLs so they don't push the size of the table out. (I've just been trying to do the same thing!)

You can do this easily with a DIV by giving it the style word-wrap: break-word (and you may need to set its width, too).

div {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
    width: 100%;
}

However, for tables, you must either wrap the content in a DIV (or other block tag) or apply: table-layout: fixed. This means the columns widths are no longer fluid, but are defined based on the widths of the columns in the first row only (or via specified widths). Read more here.

Sample code:

table {
    table-layout: fixed;
    width: 100%;
}

table td {
    word-wrap: break-word;         /* All browsers since IE 5.5+ */
    overflow-wrap: break-word;     /* Renamed property in CSS3 draft spec */
}

Hope that helps somebody.

How to call two methods on button's onclick method in HTML or JavaScript?

As stated by Harry Joy, you can do it on the onclick attr like so:

<input type="button" onclick="func1();func2();" value="Call2Functions" />

Or, in your JS like so:

document.getElementById( 'Call2Functions' ).onclick = function()
{
    func1();
    func2();
};

Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):

var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
    func1 = Call2FunctionsEle.onclick;

Call2FunctionsEle.onclick = function()
{
    if( typeof func1 === 'function' )
    {
        func1();
    }
    func2();
};

If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:

document.getElementById( 'Call2Functions' ).onclick = function()
{
    func1.apply( this, arguments );
    func2.apply( this, arguments );
};

Convert UTC datetime string to local datetime

Here is a quick and dirty version that uses the local systems settings to work out the time difference. NOTE: This will not work if you need to convert to a timezone that your current system is not running in. I have tested this with UK settings under BST timezone

from datetime import datetime
def ConvertP4DateTimeToLocal(timestampValue):
   assert isinstance(timestampValue, int)

   # get the UTC time from the timestamp integer value.
   d = datetime.utcfromtimestamp( timestampValue )

   # calculate time difference from utcnow and the local system time reported by OS
   offset = datetime.now() - datetime.utcnow()

   # Add offset to UTC time and return it
   return d + offset

Convert decimal to hexadecimal in UNIX shell script

Hexidecimal to decimal:

$ echo $((0xfee10000))
4276158464

Decimal to hexadecimal:

$ printf '%x\n' 26
1a

Subset of rows containing NA (missing) values in a chosen column of a data frame

complete.cases gives TRUE when all values in a row are not NA

DF[!complete.cases(DF), ]

How can I perform a str_replace in JavaScript, replacing text in JavaScript?

You should write something like that :

var text = "this is some sample text that i want to replace";
var new_text = text.replace("want", "dont want");
document.write(new_text);

Confused by python file mode "w+"

The file is truncated, so you can call read() (no exceptions raised, unlike when opened using 'w') but you'll get an empty string.

Android emulator-5554 offline

Ensure that your enable ADB integration is marked; go to Tools>Android>Enable ADB integration .

if doesn't checked , check this option and close your virtual device and re-open it . this worked for me.. good luck!!

Fastest check if row exists in PostgreSQL

I would like to propose another thought to specifically address your sentence: "So I want to check if a single row from the batch exists in the table because then I know they all were inserted."

You are making things efficient by inserting in "batches" but then doing existence checks one record at a time? This seems counter intuitive to me. So when you say "inserts are always done in batches" I take it you mean you are inserting multiple records with one insert statement. You need to realize that Postgres is ACID compliant. If you are inserting multiple records (a batch of data) with one insert statement, there is no need to check if some were inserted or not. The statement either passes or it will fail. All records will be inserted or none.

On the other hand, if your C# code is simply doing a "set" separate insert statements, for example, in a loop, and in your mind, this is a "batch" .. then you should not in fact describe it as "inserts are always done in batches". The fact that you expect that part of what you call a "batch", may actually not be inserted, and hence feel the need for a check, strongly suggests this is the case, in which case you have a more fundamental problem. You need change your paradigm to actually insert multiple records with one insert, and forego checking if the individual records made it.

Consider this example:

CREATE TABLE temp_test (
    id SERIAL PRIMARY KEY,
    sometext TEXT,
    userid INT,
    somethingtomakeitfail INT unique
)
-- insert a batch of 3 rows
;;
INSERT INTO temp_test (sometext, userid, somethingtomakeitfail) VALUES
('foo', 1, 1),
('bar', 2, 2),
('baz', 3, 3)
;;
-- inspect the data of what we inserted
SELECT * FROM temp_test
;;
-- this entire statement will fail .. no need to check which one made it
INSERT INTO temp_test (sometext, userid, somethingtomakeitfail) VALUES
('foo', 2, 4),
('bar', 2, 5),
('baz', 3, 3)  -- <<--(deliberately simulate a failure)
;;
-- check it ... everything is the same from the last successful insert ..
-- no need to check which records from the 2nd insert may have made it in
SELECT * FROM temp_test

This is in fact the paradigm for any ACID compliant DB .. not just Postgresql. In other words you are better off if you fix your "batch" concept and avoid having to do any row by row checks in the first place.

Setting equal heights for div's with jQuery

You can reach each separate container using .parent() API.

Like,

var highestBox = 0;
        $('.container .column').each(function(){  
                if($(this).parent().height() > highestBox){  
                highestBox = $(this).height();  
        }
    }); 

Updating the value of data attribute using jQuery

$('.toggle img').each(function(index) { 
    if($(this).attr('data-id') == '4')
    {
        $(this).attr('data-block', 'something');
        $(this).attr('src', 'something.jpg');
    }
});

or

$('.toggle img[data-id="4"]').attr('data-block', 'something');
$('.toggle img[data-id="4"]').attr('src', 'something.jpg');

How to add elements of a Java8 stream into an existing List

The short answer is no (or should be no). EDIT: yeah, it's possible (see assylias' answer below), but keep reading. EDIT2: but see Stuart Marks' answer for yet another reason why you still shouldn't do it!

The longer answer:

The purpose of these constructs in Java 8 is to introduce some concepts of Functional Programming to the language; in Functional Programming, data structures are not typically modified, instead, new ones are created out of old ones by means of transformations such as map, filter, fold/reduce and many others.

If you must modify the old list, simply collect the mapped items into a fresh list:

final List<Integer> newList = list.stream()
                                  .filter(n -> n % 2 == 0)
                                  .collect(Collectors.toList());

and then do list.addAll(newList) — again: if you really must.

(or construct a new list concatenating the old one and the new one, and assign it back to the list variable—this is a little bit more in the spirit of FP than addAll)

As to the API: even though the API allows it (again, see assylias' answer) you should try to avoid doing that regardless, at least in general. It's best not to fight the paradigm (FP) and try to learn it rather than fight it (even though Java generally isn't a FP language), and only resort to "dirtier" tactics if absolutely needed.

The really long answer: (i.e. if you include the effort of actually finding and reading an FP intro/book as suggested)

To find out why modifying existing lists is in general a bad idea and leads to less maintainable code—unless you're modifying a local variable and your algorithm is short and/or trivial, which is out of the scope of the question of code maintainability—find a good introduction to Functional Programming (there are hundreds) and start reading. A "preview" explanation would be something like: it's more mathematically sound and easier to reason about to not modify data (in most parts of your program) and leads to higher level and less technical (as well as more human friendly, once your brain transitions away from the old-style imperative thinking) definitions of program logic.

Action Bar's onClick listener for the Home button

if anyone else need the solution

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();

    if (id == android.R.id.home) {
        onBackPressed();  return true;
    }

    return super.onOptionsItemSelected(item);
}

How do I add a margin between bootstrap columns without wrapping

Change the number of @grid-columns. Then use -offset. Changing the number of columns will allow you to control the amount of space between columns. E.g.

variables.less (approx line 294).

@grid-columns:              20;

someName.html

<div class="row">
  <div class="col-md-4 col-md-offset-1">First column</div>
  <div class="col-md-13 col-md-offset-1">Second column</div>
</div>

Getting started with Haskell

These are my favorite

Haskell: Functional Programming with Types

Joeri van Eekelen, et al. | Wikibooks
       Published in 2012, 597 pages

Real World Haskell

   B. O'Sullivan, J. Goerzen, D. Stewart | OReilly Media, Inc.
   Published in 2008, 710 pages

How to reset sequence in postgres and fill id column with new data?

If you don't want to retain the ordering of ids, then you can

ALTER SEQUENCE seq RESTART WITH 1;
UPDATE t SET idcolumn=nextval('seq');

I doubt there's an easy way to do that in the order of your choice without recreating the whole table.

How to allow Cross domain request in apache2

I had a lot of trouble getting this to work. Dummy me, don't forget that old page - even for sub-requests - gets cached in your browser. Maybe obvious, but clear your browsers cache. After that, one can also use Header set Cache-Control "no-store" This was helpful to me while testing.

Difference between Constructor and ngOnInit

The Constructor is a default method of the class that is executed when the class is instantiated and ensures proper initialisation of fields in the class and its subclasses. Angular, or better Dependency Injector (DI), analyses the constructor parameters and when it creates a new instance by calling new MyClass() it tries to find providers that match the types of the constructor parameters, resolves them and passes them to the constructor like

new MyClass(someArg);

ngOnInit is a life cycle hook called by Angular to indicate that Angular is done creating the component.

We have to import OnInit like this in order to use it (actually implementing OnInit is not mandatory but considered good practice):

import { Component, OnInit } from '@angular/core';

then to make use of the method OnInit, we have to implement the class like this:

export class App implements OnInit {
  constructor() {
     // Called first time before the ngOnInit()
  }

  ngOnInit() {
     // Called after the constructor and called  after the first ngOnChanges() 
  }
}

Implement this interface to execute custom initialization logic after your directive's data-bound properties have been initialized. ngOnInit is called right after the directive's data-bound properties have been checked for the first time, and before any of its children have been checked. It is invoked only once when the directive is instantiated.

Mostly we use ngOnInit for all the initialization/declaration and avoid stuff to work in the constructor. The constructor should only be used to initialize class members but shouldn't do actual "work".

So you should use constructor() to setup Dependency Injection and not much else. ngOnInit() is better place to "start" - it's where/when components' bindings are resolved.

For more information refer here:

How can I check for IsPostBack in JavaScript?

There is an even easier way that does not involve writing anything in the code behind: Just add this line to your javascript:

if(<%=(Not Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}

or

if(<%=(Page.IsPostBack).ToString().ToLower()%>){//Your JavaScript goodies here}

How to debug Angular JavaScript Code

Unfortunately most of add-ons and browser extensions are just showing the values to you but they don't let you to edit scope variables or run angular functions. If you wanna change the $scope variables in browser console (in all browsers) then you can use jquery. If you load jQuery before AngularJS, angular.element can be passed a jQuery selector. So you could inspect the scope of a controller with

angular.element('[ng-controller="name of your controller"]').scope()

Example: You need to change value of $scope variable and see the result in the browser then just type in the browser console:

angular.element('[ng-controller="mycontroller"]').scope().var1 = "New Value";
angular.element('[ng-controller="mycontroller"]').scope().$apply();

You can see the changes in your browser immediately. The reason we used $apply() is: any scope variable updated from outside angular context won't update it binding, You need to run digest cycle after updating values of scope using scope.$apply() .

For observing a $scope variable value, you just need to call that variable.

Example: You wanna see the value of $scope.var1 in the web console in Chrome or Firefox just type:

angular.element('[ng-controller="mycontroller"]').scope().var1;

The result will be shown in the console immediately.

JSONP call showing "Uncaught SyntaxError: Unexpected token : "

I run this

var data = '{"rut" : "' + $('#cb_rut').val() + '" , "email" : "' + $('#email').val() + '" }';
var data = JSON.parse(data);

$.ajax({
    type: 'GET',
    url: 'linkserverApi',
    success: function(success) {
        console.log('Success!');
        console.log(success);
    },
    error: function() {
        console.log('Uh Oh!');
    },
    jsonp: 'jsonp'

});

And edit header in the response

'Access-Control-Allow-Methods' , 'GET, POST, PUT, DELETE'

'Access-Control-Max-Age' , '3628800'

'Access-Control-Allow-Origin', 'websiteresponseUrl'

'Content-Type', 'text/javascript; charset=utf8'

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

Hibernate Error: a different object with the same identifier value was already associated with the session

You only need to do one thing. Run session_object.clear() and then save the new object. This will clear the session (as aptly named) and remove the offending duplicate object from your session.

Permission denied (publickey,gssapi-keyex,gssapi-with-mic)

I just experienced a similar message [ mine was "Permission denied (publickey)"] after connecting to a compute engine VM which I just created. After reading this post, I decided to try it again.

That time it worked. So i see 3 possible reasons for it working the second time,

  • connecting the second time resolves the problem (after the ssh key was created the first time), or
  • perhaps trying to connect to a compute engine immediately after it was created could also cause a problem which resolves itself after a while, or
  • merely reading this post resolves the problem

I suspect the last is unlikely :)

How to delete an instantiated object Python?

object.__del__(self) is called when the instance is about to be destroyed.

>>> class Test:
...     def __del__(self):
...         print "deleted"
... 
>>> test = Test()
>>> del test
deleted

Object is not deleted unless all of its references are removed(As quoted by ethan)

Also, From Python official doc reference:

del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero

How to handle invalid SSL certificates with Apache HttpClient?

For a way to easily add hosts you trust at runtime without throwing out all checks, try the code here: http://code.google.com/p/self-signed-cert-trust-manager/.

How to extend / inherit components?

Components can be extended as same as a typescript class inheritance, just that you have to override the selector with a new name. All Input() and Output() Properties from the Parent Component works as normal

Update

@Component is a decorator,

Decorators are applied during the declaration of class not on objects.

Basically, decorators add some metadata to the class object and that cannot be accessed via inheritance.

If you want to achieve the Decorator Inheritance I would Suggest writing a custom decorator. Something like below example.

export function CustomComponent(annotation: any) {
    return function (target: Function) {
    var parentTarget = Object.getPrototypeOf(target.prototype).constructor;

    var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
    var parentParamTypes = Reflect.getMetadata('design:paramtypes', parentTarget);
    var parentPropMetadata = Reflect.getMetadata('propMetadata', parentTarget);
    var parentParameters = Reflect.getMetadata('parameters', parentTarget);

    var parentAnnotation = parentAnnotations[0];

    Object.keys(parentAnnotation).forEach(key => {
    if (isPresent(parentAnnotation[key])) {
        if (!isPresent(annotation[key])) {
        annotation[key] = parentAnnotation[key];
        }
    }
    });
    // Same for the other metadata
    var metadata = new ComponentMetadata(annotation);

    Reflect.defineMetadata('annotations', [ metadata ], target);
    };
};

Refer: https://medium.com/@ttemplier/angular2-decorators-and-class-inheritance-905921dbd1b7

Changing SQL Server collation to case insensitive from case sensitive?

You basically need to run the installation again to rebuild the master database with the new collation. You cannot change the entire server's collation any other way.

See:

Update: if you want to change the collation of a database, you can get the current collation using this snippet of T-SQL:

SELECT name, collation_name 
FROM sys.databases
WHERE name = 'test2'   -- put your database name here

This will yield a value something like:

Latin1_General_CI_AS

The _CI means "case insensitive" - if you want case-sensitive, use _CS in its place:

Latin1_General_CS_AS

So your T-SQL command would be:

ALTER DATABASE test2 -- put your database name here
   COLLATE Latin1_General_CS_AS   -- replace with whatever collation you need

You can get a list of all available collations on the server using:

SELECT * FROM ::fn_helpcollations()

You can see the server's current collation using:

SELECT SERVERPROPERTY ('Collation')

Playing .mp3 and .wav in Java?

I would recommend using the BasicPlayerAPI. It's open source, very simple and it doesn't require JavaFX. http://www.javazoom.net/jlgui/api.html

After downloading and extracting the zip-file one should add the following jar-files to the build path of the project:

  • basicplayer3.0.jar
  • all the jars from the lib directory (inside BasicPlayer3.0)

Here is a minimalistic usage example:

String songName = "HungryKidsofHungary-ScatteredDiamonds.mp3";
String pathToMp3 = System.getProperty("user.dir") +"/"+ songName;
BasicPlayer player = new BasicPlayer();
try {
    player.open(new URL("file:///" + pathToMp3));
    player.play();
} catch (BasicPlayerException | MalformedURLException e) {
    e.printStackTrace();
}

Required imports:

import java.net.MalformedURLException;
import java.net.URL;
import javazoom.jlgui.basicplayer.BasicPlayer;
import javazoom.jlgui.basicplayer.BasicPlayerException;

That's all you need to start playing music. The Player is starting and managing his own playback thread and provides play, pause, resume, stop and seek functionality.

For a more advanced usage you may take a look at the jlGui Music Player. It's an open source WinAmp clone: http://www.javazoom.net/jlgui/jlgui.html

The first class to look at would be PlayerUI (inside the package javazoom.jlgui.player.amp). It demonstrates the advanced features of the BasicPlayer pretty well.

Check if not nil and not empty in Rails shortcut?

There's a method that does this for you:

def show
  @city = @user.city.present?
end

The present? method tests for not-nil plus has content. Empty strings, strings consisting of spaces or tabs, are considered not present.

Since this pattern is so common there's even a shortcut in ActiveRecord:

def show
  @city = @user.city?
end

This is roughly equivalent.

As a note, testing vs nil is almost always redundant. There are only two logically false values in Ruby: nil and false. Unless it's possible for a variable to be literal false, this would be sufficient:

if (variable)
  # ...
end

This is preferable to the usual if (!variable.nil?) or if (variable != nil) stuff that shows up occasionally. Ruby tends to wards a more reductionist type of expression.

One reason you'd want to compare vs. nil is if you have a tri-state variable that can be true, false or nil and you need to distinguish between the last two states.

How to change JDK version for an Eclipse project

See the page Set Up JDK in Eclipse. From the add button you can add a different version of the JDK...

JavaScript: SyntaxError: missing ) after argument list

just posting in case anyone else has the same error...

I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.

The solution was to make the function asynchronous

function functionName(args) {}

becomes

async function functionName(args) {}

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

JAVA How to remove trailing zeros from a double

Use DecimalFormat

  double answer = 5.0;
   DecimalFormat df = new DecimalFormat("###.#");
  System.out.println(df.format(answer));

How do I connect to a terminal to a serial-to-USB device on Ubuntu 10.10 (Maverick Meerkat)?

Putty on ubuntu There is no need to install the driver for PL2303 So only type the command to enable the putty Sudo chmod 666 /dev/ttyUSB0 Done Open the putty.

Rounding a double value to x number of decimal places in swift

Extension for Swift 2

A more general solution is the following extension, which works with Swift 2 & iOS 9:

extension Double {
    /// Rounds the double to decimal places value
    func roundToPlaces(places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return round(self * divisor) / divisor
    }
}


Extension for Swift 3

In Swift 3 round is replaced by rounded:

extension Double {
    /// Rounds the double to decimal places value
    func rounded(toPlaces places:Int) -> Double {
        let divisor = pow(10.0, Double(places))
        return (self * divisor).rounded() / divisor
    }
}


Example which returns Double rounded to 4 decimal places:

let x = Double(0.123456789).roundToPlaces(4)  // x becomes 0.1235 under Swift 2
let x = Double(0.123456789).rounded(toPlaces: 4)  // Swift 3 version

The type is defined in an assembly that is not referenced, how to find the cause?

For me, this was caused by the project both directly and indirectly (through another dependency) referencing two different builds of Bouncy Castle that had different assembly names. One of the Bouncy Castle builds was the NuGet package, the other one was a debug build of the source downloaded from GitHub. Both were nominally version 1.8.1, but the project settings of the GitHub code set the assembly name to BouncyCastle whereas the NuGet package had the assembly name BouncyCastle.Crypto. Changing the project settings, thus aligning the assembly names, fixed the problem.

When to use React "componentDidUpdate" method?

When something in the state has changed and you need to call a side effect (like a request to api - get, put, post, delete). So you need to call componentDidUpdate() because componentDidMount() is already called.

After calling side effect in componentDidUpdate(), you can set the state to new value based on the response data in the then((response) => this.setState({newValue: "here"})). Please make sure that you need to check prevProps or prevState to avoid infinite loop because when setting state to a new value, the componentDidUpdate() will call again.

There are 2 places to call a side effect for best practice - componentDidMount() and componentDidUpdate()

Add Favicon to Website

  1. This is not done in PHP. It's part of the <head> tags in a HTML page.
  2. That icon is called a favicon. According to Wikipedia:

    A favicon (short for favorites icon), also known as a shortcut icon, website icon, URL icon, or bookmark icon is a 16×16 or 32×32 pixel square icon associated with a particular website or webpage.

  3. Adding it is easy. Just add an .ico image file that is either 16x16 pixels or 32x32 pixels. Then, in the web pages, add <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"> to the <head> element.
  4. You can easily generate favicons here.

MySQL combine two columns into one column

table:

---------------------
| column1 | column2 |
---------------------
|   abc   |   xyz   |
---------------------

In Oracle:

SELECT column1 || column2 AS column3
FROM table_name;

Output:

table:

---------------------
| column3           |
---------------------
| abcxyz            |
---------------------

If you want to put ',' or '.' or any string within two column data then you may use:

SELECT column1 || '.' || column2 AS column3
FROM table_name;

Output:

table:

---------------------
| column3           |
---------------------
| abc.xyz           |
---------------------

Is it possible to get an Excel document's row count without loading the entire document into memory?

Python 3

import openpyxl as xl

wb = xl.load_workbook("Sample.xlsx", enumerate)

#the 2 lines under do the same. 
sheet = wb.get_sheet_by_name('sheet') 
sheet = wb.worksheets[0]

row_count = sheet.max_row
column_count = sheet.max_column

#this works fore me.

SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable

I resolved this issue by creating ANDROID_HOME environment variable as follows in windows.

ANDROID_HOME=C:\Users\<user_name>\AppData\Local\Android\sdk

Restart Android Studio it should build project!

Getting the difference between two sets

If you are using Java 8, you could try something like this:

public Set<Number> difference(final Set<Number> set1, final Set<Number> set2){
    final Set<Number> larger = set1.size() > set2.size() ? set1 : set2;
    final Set<Number> smaller = larger.equals(set1) ? set2 : set1;
    return larger.stream().filter(n -> !smaller.contains(n)).collect(Collectors.toSet());
}

What's the difference between using CGFloat and float?

just mention that - Jan, 2020 Xcode 11.3/iOS13

Swift 5

From the CoreGraphics source code

public struct CGFloat {
    /// The native type used to store the CGFloat, which is Float on
    /// 32-bit architectures and Double on 64-bit architectures.
    public typealias NativeType = Double

How does a ArrayList's contains() method evaluate objects?

class Thing {  
    public int value;  

    public Thing (int x) {
        value = x;
    }

    equals (Thing x) {
        if (x.value == value) return true;
        return false;
    }
}

You must write:

class Thing {  
    public int value;  

    public Thing (int x) {
        value = x;
    }

    public boolean equals (Object o) {
    Thing x = (Thing) o;
        if (x.value == value) return true;
        return false;
    }
}

Now it works ;)

Getting the parameters of a running JVM

Alternatively, you can use jinfo

jinfo -flags <vmid> 
jinfo -sysprops <vmid>

PHP Constants Containing Arrays?

Yes, You can define an array as constant. From PHP 5.6 onwards, it is possible to define a constant as a scalar expression, and it is also possible to define an array constant. It is possible to define constants as a resource, but it should be avoided, as it can cause unexpected results.

<?php
    // Works as of PHP 5.3.0
    const CONSTANT = 'Hello World';
    echo CONSTANT;

    // Works as of PHP 5.6.0
    const ANOTHER_CONST = CONSTANT.'; Goodbye World';
    echo ANOTHER_CONST;

    const ANIMALS = array('dog', 'cat', 'bird');
    echo ANIMALS[1]; // outputs "cat"

    // Works as of PHP 7
    define('ANIMALS', array(
        'dog',
        'cat',
        'bird'
    ));
    echo ANIMALS[1]; // outputs "cat"
?>

With the reference of this link

Have a happy coding.

regex with space and letters only?

Allowed only characters & spaces. Ex : Jayant Lonari

if (!/^[a-zA-Z\s]+$/.test(NAME)) {
    //Throw Error
}

Greater than and less than in one statement

Several third-party libraries have classes encapsulating the concept of a range, such as Apache commons-lang's Range (and subclasses).

Using classes such as this you could express your constraint similar to:

if (new IntRange(0, 5).contains(orderBean.getFiles().size())
// (though actually Apache's Range is INclusive, so it'd be new Range(1, 4) - meh

with the added bonus that the range object could be defined as a constant value elsewhere in the class.

However, without pulling in other libraries and using their classes, Java's strong syntax means you can't massage the language itself to provide this feature nicely. And (in my own opinion), pulling in a third party library just for this small amount of syntactic sugar isn't worth it.

transform object to array with lodash

Transforming object to array with plain JavaScript's(ECMAScript-2016) Object.values:

_x000D_
_x000D_
var obj = {_x000D_
    22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[]}},_x000D_
    12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[]}}_x000D_
}_x000D_
_x000D_
var values = Object.values(obj)_x000D_
_x000D_
console.log(values);
_x000D_
_x000D_
_x000D_

If you also want to keep the keys use Object.entries and Array#map like this:

_x000D_
_x000D_
var obj = {_x000D_
    22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[]}},_x000D_
    12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[]}}_x000D_
}_x000D_
_x000D_
var values = Object.entries(obj).map(([k, v]) => ({[k]: v}))_x000D_
_x000D_
console.log(values);
_x000D_
_x000D_
_x000D_

git add only modified changes and ignore untracked files

git commit -a -m "message"

-a : Includes all currently changed/deleted files in this commit. Keep in mind, however, that untracked (new) files are not included.

-m : Sets the commit's message

Convert XML String to Object

public string Serialize<T>(T settings)
{
    XmlSerializer serializer = new XmlSerializer(typeof(T));
    StringWriter outStream = new StringWriter();
    serializer.Serialize(outStream, settings);
    return outStream.ToString();
}

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How to insert image in mysql database(table)?

I tried all above solution and fail, it just added a null file to the DB.

However, I was able to get it done by moving the image(fileName.jpg) file first in to below folder(in my case) C:\ProgramData\MySQL\MySQL Server 5.7\Uploads and then I executed below command and it works for me,

INSERT INTO xx_BLOB(ID,IMAGE) VALUES(1,LOAD_FILE('C:/ProgramData/MySQL/MySQL Server 5.7/Uploads/fileName.jpg'));

Hope this helps.

git clone through ssh

For repositories on GitHub, try:

git clone ssh://[email protected]/<user>/<repository name>.git

For setting up git to clone via ssh see:

How to install and use "make" in Windows?

make is a GNU command so the only way you can get it on Windows is installing a Windows version like the one provided by GNUWin32. Anyway, there are several options for getting that:

  1. Using MinGW, be sure you have C:\MinGW\bin\mingw32-make.exe. Otherwise you're missing the mingw32-make additional utilities. Look for the link at MinGW's HowTo page to get it installed. Once you've got it, you have two choices:
  • 1.1 Copy the MinGW make executable to make.exe:

    copy c:\MinGW\bin\mingw32-make.exe c:\MinGW\bin\make.exe
    
  • 1.2 Create a link to the actual executable, in your PATH. In this case, if you update MinGW, the link is not deleted:

    mklink c:\bin\make.exe C:\MinGW\bin\mingw32-make.exe
    
  1. Other option is using Chocolatey. First you need to install this package manager. Once installed you simlpy need to install make:

    choco install make
    
  2. Last option is installing a Windows Subsystem for Linux (WSL), so you'll have a Linux distribution of your choice embedded in Windows 10 where you'll be able to install make, gccand all the tools you need to build C programs.

How to set the project name/group/version, plus {source,target} compatibility in the same file?

I found the solution to a similar problem. I am using Gradle 1.11 (as April, 2014). The project name can be changed directly in settings.gradle file as following:

  rootProject.name='YourNewName'

This takes care of uploading to repository (Artifactory w/ its plugin for me) with the correct artifactId.

HTML/CSS - Adding an Icon to a button

You could add a span before the link with a specific class like so:

<div class="btn btn_red"><span class="icon"></span><a href="#">Crimson</a><span></span></div>

And then give that a specific width and a background image just like you are doing with the button itself.

.btn span.icon {
    background: url(imgs/icon.png) no-repeat;
    float: left;
    width: 10px;
    height: 40px;
}

I am no CSS guru but off the top of my head I think that should work.

Allow only numeric value in textbox using Javascript

This code uses the event object's .keyCode property to check the characters typed into a given field. If the key pressed is a number, do nothing; otherwise, if it's a letter, alert "Error". If it is neither of these things, it returns false.

HTML:

<form>
    <input type="text" id="txt" />
</form>

JS:

(function(a) {
    a.onkeypress = function(e) {
        if (e.keyCode >= 49 && e.keyCode <= 57) {}
        else {
            if (e.keyCode >= 97 && e.keyCode <= 122) {
                alert('Error');
                // return false;
            } else return false;
        }
    };
})($('txt'));

function $(id) {
    return document.getElementById(id);
}

For a result: http://jsfiddle.net/uUc22/

Mind you that the .keyCode result for .onkeypress, .onkeydown, and .onkeyup differ from each other.

How to create a DB for MongoDB container on start up?

The official mongo image has merged a PR to include the functionality to databases and admin users at startup.

The database initialisation will run scripts in /docker-entrypoint-initdb.d/ when there is nothing populated in the /data/db directory.

Database Initialisation

The mongo container image provides the /docker-entrypoint-initdb.d/ path to deploy custom .js or .sh setup scripts that will be run once on database initialisation. .js scripts will be run against test by default or MONGO_INITDB_DATABASE if defined in the environment.

COPY mysetup.sh /docker-entrypoint-initdb.d/

or

COPY mysetup.js /docker-entrypoint-initdb.d/

A simple initialisation mongo shell javascript file that demonstrates setting up the container collection with data, logging and how to exit with an error (for result checking).

let error = true

let res = [
  db.container.drop(),
  db.container.createIndex({ myfield: 1 }, { unique: true }),
  db.container.createIndex({ thatfield: 1 }),
  db.container.createIndex({ thatfield: 1 }),
  db.container.insert({ myfield: 'hello', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello2', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello3', thatfield: 'testing' }),
  db.container.insert({ myfield: 'hello3', thatfield: 'testing' })
]

printjson(res)

if (error) {
  print('Error, exiting')
  quit(1)
}

Admin User Setup

The environment variables to control "root" user setup are

  • MONGO_INITDB_ROOT_USERNAME
  • MONGO_INITDB_ROOT_PASSWORD

Example

docker run -d \
  -e MONGO_INITDB_ROOT_USERNAME=admin \
  -e MONGO_INITDB_ROOT_PASSWORD=password \
  mongod

or Dockerfile

FROM docker.io/mongo
ENV MONGO_INITDB_ROOT_USERNAME admin
ENV MONGO_INITDB_ROOT_PASSWORD password

You don't need to use --auth on the command line as the docker entrypoint.sh script adds this in when it detects the environment variables exist.

Stop Chrome Caching My JS Files

  1. Open Developer Tools

    • Either F12
    • Or ... -> More Tools -> Developer Tools
  2. Click Empty Cache and Hard Reload

    • Either right-click refresh icon (just left to url address bar)
    • Or left-click refresh icon and holding it for 1 second

How to set the From email address for mailx command?

On debian where bsd-mailx is installed by default, the -r option does not work. However you can use mailx -s subject [email protected] -- -f [email protected] instead. According to man page, you can specify sendmail options after --.

Explaining Apache ZooKeeper

Zookeeper is one of the best open source server and service that helps to reliably coordinates distributed processes. Zookeeper is a CP system (Refer CAP Theorem) that provides Consistency and Partition tolerance. Replication of Zookeeper state across all the nodes makes it an eventually consistent distributed service.

Moreover, any newly elected leader will update its followers with missing proposals or with a snapshot of the state, if the followers have many proposals missing.

Zookeeper also provides an API that is very easy to use. This blog post, Zookeeper Java API examples, has some examples if you are looking for examples.

So where do we use this? If your distributed service needs a centralized, reliable and consistent configuration management, locks, queues etc, you will find Zookeeper a reliable choice.

Escape text for HTML

For those in the future looking for a simple way to do this in Razor pages, use the following:

In .cshtml:

@Html.Raw(Html.Encode("<span>blah<span>"))

In .cshtml.cs:

string rawHtml = Html.Raw(Html.Encode("<span>blah<span>"));

Use sudo with password as parameter

The -S switch makes sudo read the password from STDIN. This means you can do

echo mypassword | sudo -S command

to pass the password to sudo

However, the suggestions by others that do not involve passing the password as part of a command such as checking if the user is root are probably much better ideas for security reasons

Python copy files to a new directory and rename if file name already exists

For me shutil.copy is the best:

import shutil

#make a copy of the invoice to work with
src="invoice.pdf"
dst="copied_invoice.pdf"
shutil.copy(src,dst)

You can change the path of the files as you want.

Software Design vs. Software Architecture

Architecture and design are closely related; the main difference between them is really about which way we face. Architecture faces towards strategy, structure and purpose, towards the abstract. Design faces towards implementation and practice, towards the concrete.

How to sort List<Integer>?

You can use the utility method in Collections class public static <T extends Comparable<? super T>> void sort(List<T> list) or

public static <T> void sort(List<T> list,Comparator<? super T> c)

Refer to Comparable and Comparator interfaces for more flexibility on sorting the object.

Convert String with Dot or Comma as decimal separator to number in JavaScript

All the other solutions require you to know the format in advance. I needed to detect(!) the format in every case and this is what I end up with.

function detectFloat(source) {
    let float = accounting.unformat(source);
    let posComma = source.indexOf(',');
    if (posComma > -1) {
        let posDot = source.indexOf('.');
        if (posDot > -1 && posComma > posDot) {
            let germanFloat = accounting.unformat(source, ',');
            if (Math.abs(germanFloat) > Math.abs(float)) {
                float = germanFloat;
            }
        } else {
            // source = source.replace(/,/g, '.');
            float = accounting.unformat(source, ',');
        }
    }
    return float;
}

This was tested with the following cases:

        const cases = {
            "0": 0,
            "10.12": 10.12,
            "222.20": 222.20,
            "-222.20": -222.20,
            "+222,20": 222.20,
            "-222,20": -222.20,
            "-2.222,20": -2222.20,
            "-11.111,20": -11111.20,
        };

Suggestions welcome.

Setting environment variable in react-native?

The simplest (not the best or ideal) solution I found was to use react-native-dotenv. You simply add the "react-native-dotenv" preset to your .babelrc file at the project root like so:

{
  "presets": ["react-native", "react-native-dotenv"]
}

Create a .env file and add properties:

echo "SOMETHING=anything" > .env

Then in your project (JS):

import { SOMETHING } from 'react-native-dotenv'
console.log(SOMETHING) // "anything"

Error: allowDefinition='MachineToApplication' beyond application level

I had the same problem because a new global Web.Config is automatically created for the parent folder. It was \Website\Website.

After I moved all file from the child folder to the parent and delete the child folder, now I have only one Web.Config and the problem is resolved.

PPT to PNG with transparent background

It can't be done, either manually or progamatically. This is because the color behind every slide master is white. If you set your background to 100% transparent, it will print as white.

The best you could do is design your slide with all the stuff you want, group everything you want to appear in the transparent image and then right-click/save as picture/.PNG (or you could do that with a macro as well). In this way you would retain transparency.

Here's an example of how to export all slides' shapes to seperate PNG files. Note:

  1. This does not get any background shapes on the Slide Master.
  2. Resulting PNGs will not be the same size as each other, depending on where the shapes are located on each slide.
  3. This uses a depreciated function, namely Shape.Export. This means that while the function is still available up to PowerPoint 2010, it may be removed from PowerPoint VBA later.

    Sub PrintShapesToPng()
        Dim ap As Presentation: Set ap = ActivePresentation
        Dim sl As slide
        Dim shGroup As ShapeRange
        For Each sl In ap.Slides
            ActiveWindow.View.GotoSlide (sl.SlideIndex)
            sl.Shapes.SelectAll
            Set shGroup = ActiveWindow.Selection.ShapeRange
            shGroup.Export ap.Path & "\Slide" & sl.SlideIndex & ".png", _
                                ppShapeFormatPNG, , , ppRelativeToSlide
        Next
    End Sub
    

How to pass Multiple Parameters from ajax call to MVC Controller

$.ajax({
  type: "POST",
  contentType: "application/json; charset=utf-8",
  url: "ChnagePassword.aspx/AutocompleteSuggestions",
  data: "{'searchstring':'" + request.term + "','st':'Arb'}",
  dataType: "json",
  success: function (data) {
     response($.map(data.d, function (item) {
         return { value: item }
     }))
  },
  error: function (result) {
      alert("Error");
  }
});

How can I prevent the textarea from stretching beyond his parent DIV element? (google-chrome issue only)

textarea {
width: 700px;  
height: 100px;
resize: none; }

assign your required width and height for the textarea and then use. resize: none ; css property which will disable the textarea's stretchable property.

Creating a UICollectionView programmatically

Header file:--

@interface ViewController : UIViewController<UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
{
    UICollectionView *_collectionView;
}

Implementation File:--

- (void)viewDidLoad
{
     [super viewDidLoad];
     self.view = [[UIView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

     UICollectionViewFlowLayout *layout=[[UICollectionViewFlowLayout alloc] init];
    _collectionView=[[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:layout];
    [_collectionView setDataSource:self];
    [_collectionView setDelegate:self];

    [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"cellIdentifier"];
    [_collectionView setBackgroundColor:[UIColor redColor]];

    [self.view addSubview:_collectionView];


    // Do any additional setup after loading the view, typically from a nib.
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return 15;
}

// The cell that is returned must be retrieved from a call to -dequeueReusableCellWithReuseIdentifier:forIndexPath:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    UICollectionViewCell *cell=[collectionView dequeueReusableCellWithReuseIdentifier:@"cellIdentifier" forIndexPath:indexPath];

    cell.backgroundColor=[UIColor greenColor];
    return cell;
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(50, 50);
}

Output---

enter image description here

How to use opencv in using Gradle?

I've imported the Java project from OpenCV SDK into an Android Studio gradle project and made it available at https://github.com/ctodobom/OpenCV-3.1.0-Android

You can include it on your project only adding two lines into build.gradle file thanks to jitpack.io service.

Find Facebook user (url to profile page) by known email address

Simply use the graph API with this url format: https://graph.facebook.com/[email protected]&type=user&access_token=... You can easily create an application here and grab an access token for it here. I believe you get an estimated 600 requests per 600 seconds, although this isn't documented.

If you are doing this in bulk, you could use batch requests in batches of 20 email addresses. This may help with rate limits (I am not sure if you get 600 batch requests per 600 seconds or 600 individual requests).

Receiving login prompt using integrated windows authentication

Add permission [Domain Users] to your web security.

  • Right click on your site in IIS under the Sites folder
  • Click Edit Permissions...
  • Select the Security tab
  • Under the Group or usernames section click the Edit... button
  • In the Permissions pop up, under the Group or user names click Add...
  • Enter [Domain Users] in the object names to select text area and click OK to apply the change
  • Click OK to close the Permissions pop up
  • Click OK to close the Properties pop up and apply your new settings

Could not instantiate mail function. Why this error occurring

As noted here, "This means that your PHP installation is not configured to call the mail() function correctly (e.g. sendmail_path is not set correctly in your php.ini), or you have no local mail server installed and configured."

In my case I had to allow the mail() function ("activate the mail() queue") in the settings of my webhost.

How to call a stored procedure from Java and JPA

From JPA 2.1 , JPA supports to call stored procedures using the dynamic StoredProcedureQuery, and the declarative @NamedStoredProcedureQuery.

using nth-child in tables tr td

table tr td:nth-child(2) {
    background: #ccc;
}

Working example: http://jsfiddle.net/gqr3J/

Pandas read_csv low_memory and dtype options

It worked for me with low_memory = False while importing a DataFrame. That is all the change that worked for me:

df = pd.read_csv('export4_16.csv',low_memory=False)

Initializing IEnumerable<string> In C#

IEnumerable<T> is an interface. You need to initiate with a concrete type (that implements IEnumerable<T>). Example:

IEnumerable<string> m_oEnum = new List<string>() { "1", "2", "3"};

Validate form field only on submit or user input

If you want to show error messages on form submission, you can use condition form.$submitted to check if an attempt was made to submit the form. Check following example.

<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
  <input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user name.</div>
  </div>

  <input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user address.</div>
    <div ng-message="maxlength">Should be less than 30 chars</div>
  </div>

  <button type="submit">
    Create user
  </button>
</form>

How to clear the text of all textBoxes in the form?

I like lambda :)

 private void ClearTextBoxes()
 {
     Action<Control.ControlCollection> func = null;

     func = (controls) =>
         {
             foreach (Control control in controls)
                 if (control is TextBox)
                     (control as TextBox).Clear();
                 else
                     func(control.Controls);
         };

     func(Controls);
 }

Good luck!

How do I hide anchor text without hiding the anchor?

I was able to fix this problem by setting font-size: 0 .

How do you do exponentiation in C?

pow only works on floating-point numbers (doubles, actually). If you want to take powers of integers, and the base isn't known to be an exponent of 2, you'll have to roll your own.

Usually the dumb way is good enough.

int power(int base, unsigned int exp) {
    int i, result = 1;
    for (i = 0; i < exp; i++)
        result *= base;
    return result;
 }

Here's a recursive solution which takes O(log n) space and time instead of the easy O(1) space O(n) time:

int power(int base, int exp) {
    if (exp == 0)
        return 1;
    else if (exp % 2)
        return base * power(base, exp - 1);
    else {
        int temp = power(base, exp / 2);
        return temp * temp;
    }
}

Can't use SURF, SIFT in OpenCV

FYI, as of 3.0.0 SIFT and friends are in a contrib repo located at https://github.com/Itseez/opencv_contrib and are not included with opencv by default.

How can VBA connect to MySQL database in Excel?

Enable Microsoft ActiveX Data Objects 2.8 Library

Dim oConn As ADODB.Connection 
Private Sub ConnectDB()     
Set oConn = New ADODB.Connection    
oConn.Open "DRIVER={MySQL ODBC 5.1 Driver};" & _        
"SERVER=localhost;" & _         
"DATABASE=yourdatabase;" & _        
"USER=yourdbusername;" & _      
"PASSWORD=yourdbpassword;" & _      
"Option=3" 
End Sub

There rest is here: http://www.heritage-tech.net/908/inserting-data-into-mysql-from-excel-using-vba/

How to Rotate a UIImage 90 degrees?

Here is a Swift extension to UIImage that rotates the image by any arbitrary angle. Use it like this: let rotatedImage = image.rotated(byDegrees: degree). I used the Objective-C code in one of the other answers and removed a few lines that we incorrect (rotated box stuff) and turned it into an extension for UIImage.

extension UIImage {

func rotate(byDegrees degree: Double) -> UIImage {
    let radians = CGFloat(degree*M_PI)/180.0 as CGFloat
    let rotatedSize = self.size
    let scale = UIScreen.mainScreen().scale
    UIGraphicsBeginImageContextWithOptions(rotatedSize, false, scale)
    let bitmap = UIGraphicsGetCurrentContext()
    CGContextTranslateCTM(bitmap, rotatedSize.width / 2, rotatedSize.height / 2);
    CGContextRotateCTM(bitmap, radians);
    CGContextScaleCTM(bitmap, 1.0, -1.0);
    CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2 , self.size.width, self.size.height), self.CGImage );
    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    return newImage
}
}

Is there a simple way that I can sort characters in a string in alphabetical order

Yes; copy the string to a char array, sort the char array, then copy that back into a string.

static string SortString(string input)
{
    char[] characters = input.ToArray();
    Array.Sort(characters);
    return new string(characters);
}

flutter run: No connected devices

No one here mentions to make sure the Android device is not connected as "Media device" As soon as I turned this off and set it to "Charging" it worked.

I obviously installed the USB driver through Android studio, and also went through a step of adding "adb" to my system path by adding the location of it to "PATH"

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

You can mark source directory as a source root like so:

  • Right-click on source directory
  • Mark Directory As --> Source Root
  • File --> Invalidate Caches / Restart... -> Invalidate and Restart

Multiple queries executed in java in single statement

I think this is the easiest way for multy selection/update/insert/delete. You can run as many update/insert/delete as u want after select (you have to make a select first(a dummy if needed)) with executeUpdate(str) (just use new int(count1,count2,...)) and if u need a new selection close 'statement' and 'connection' and make new for next select. Like example:

String str1 = "select * from users";
String str9 = "INSERT INTO `port`(device_id, potition, port_type, di_p_pt) VALUE ('"+value1+"', '"+value2+"', '"+value3+"', '"+value4+"')";
String str2 = "Select port_id from port where device_id = '"+value1+"' and potition = '"+value2+"' and port_type = '"+value3+"' ";
try{  
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    theConnection=(Connection) DriverManager.getConnection(dbURL,dbuser,dbpassword);  
    theStatement = theConnection.prepareStatement(str1);
    ResultSet theResult = theStatement.executeQuery();
    int count8 = theStatement.executeUpdate(str9);
    theStatement.close();
    theConnection.close();
    theConnection=DriverManager.getConnection(dbURL,dbuser,dbpassword);
    theStatement = theConnection.prepareStatement(str2);
    theResult = theStatement.executeQuery();

    ArrayList<Port> portList = new ArrayList<Port>();
    while (theResult.next()) {
        Port port = new Port();
        port.setPort_id(theResult.getInt("port_id"));

        portList.add(port);
    }

I hope it helps

What to do about Eclipse's "No repository found containing: ..." error messages?

Probably, my experience with this bug will be needed for someone (including myself too... :) ).

So, I could to add one thing to the mentioned here answers. I mean playing with the trailing "/" symbol in the options, because playing with it does not work in my case. But when I have deleted the .eclipse/org.eclipse.oomph.p2/cache and the .eclipse/org.eclipse.oomph.setup/cache dirs (names are given relatively to the home dir) and then have done the well known procedure with "/", it started to work.

JavaScript file upload size validation

I made something like that:

_x000D_
_x000D_
$('#image-file').on('change', function() {
 var numb = $(this)[0].files[0].size/1024/1024;
numb = numb.toFixed(2);
if(numb > 2){
alert('to big, maximum is 2MiB. You file size is: ' + numb +' MiB');
} else {
alert('it okey, your file has ' + numb + 'MiB')
}
        });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<input type="file" id="image-file">
_x000D_
_x000D_
_x000D_

Splitting on first occurrence

>>> s = "123mango abcd mango kiwi peach"
>>> s.split("mango", 1)
['123', ' abcd mango kiwi peach']
>>> s.split("mango", 1)[1]
' abcd mango kiwi peach'

How to initialize java.util.date to empty

Try initializing with null value.

private java.util.Date date2 = null;

Also private java.util.Date date2 = ""; will not work as "" is a string.

Installation of SQL Server Business Intelligence Development Studio

It sounds like you have installed SQL Server 2005 Express Edition, which does not include SSIS or the Business Intelligence Development Studio.

BIDS is only provided with the (not free) Standard, Enterprise and Developer Editions.

EDIT

This information was correct for SQL Server 2005. Since SQL Server 2014, Developer Edition has been free. BIDS has been replaced by SQL Server Data Tools, a free plugin for Visual Studio (including the free Visual Studio Community Edition).

ImportError: No module named sqlalchemy

I just experienced the same problem. Apparently, there is a new distribution method, the extension code is no longer stored under flaskext.

Source: Flask CHANGELOG This worked for me:

from flask_sqlalchemy import SQLAlchemy

Remove Identity from a column in a table

I just had this same problem. 4 statements in SSMS instead of using the GUI and it was very fast.

  • Make a new column

    alter table users add newusernum int;

  • Copy values over

    update users set newusernum=usernum;

  • Drop the old column

    alter table users drop column usernum;

  • Rename the new column to the old column name

    EXEC sp_RENAME 'users.newusernum' , 'usernum', 'COLUMN';

How to compare two files in Notepad++ v6.6.8

There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.

Alternatively you can install a specialized file compare software like WinMerge.

What causes java.lang.IncompatibleClassChangeError?

If this is a record of possible occurences of this error then:

I just got this error on WAS (8.5.0.1), during the CXF (2.6.0) loading of the spring (3.1.1_release) configuration where a BeanInstantiationException rolled up a CXF ExtensionException, rolling up a IncompatibleClassChangeError. The following snippet shows the gist of the stack trace:

Caused by: org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [org.apache.cxf.bus.spring.SpringBus]: Constructor threw exception; nested exception is org.apache.cxf.bus.extension.ExtensionException
            at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:162)
            at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:76)
            at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:990)
            ... 116 more
Caused by: org.apache.cxf.bus.extension.ExtensionException
            at org.apache.cxf.bus.extension.Extension.tryClass(Extension.java:167)
            at org.apache.cxf.bus.extension.Extension.getClassObject(Extension.java:179)
            at org.apache.cxf.bus.extension.ExtensionManagerImpl.activateAllByType(ExtensionManagerImpl.java:138)
            at org.apache.cxf.bus.extension.ExtensionManagerBus.<init>(ExtensionManagerBus.java:131)
            [etc...]
            at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:147)
            ... 118 more

Caused by: java.lang.IncompatibleClassChangeError: 
org.apache.neethi.AssertionBuilderFactory
            at java.lang.ClassLoader.defineClassImpl(Native Method)
            at java.lang.ClassLoader.defineClass(ClassLoader.java:284)
            [etc...]
            at com.ibm.ws.classloader.CompoundClassLoader.loadClass(CompoundClassLoader.java:586)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:658)
            at org.apache.cxf.bus.extension.Extension.tryClass(Extension.java:163)
            ... 128 more

In this case, the solution was to change the classpath order of the module in my war file. That is, open up the war application in the WAS console under and select the client module(s). In the module configuration, set the class-loading to be "parent last".

This is found in the WAS console:

  • Applicatoins -> Application Types -> WebSphere Enterprise Applications
  • Click link representing your application (war)
  • Click "Manage Modules" under "Modules" section
  • Click link for the underlying module(s)
  • Change "Class loader order" to be "(parent last)".

Why can't I center with margin: 0 auto?

You need to define the width of the element you are centering, not the parent element.

#header ul {
    margin: 0 auto;
    width: 90%;
}

Edit: Ok, I've seen the testpage now, and here is how I think you want it:

#header ul {
    list-style:none;
    margin:0 auto;
    width:90%;
}

/* Remove the float: left; property, it interferes with display: inline and 
 * causes problems. (float: left; makes the element implicitly a block-level
 * element. It is still good to use display: inline on it to overcome a bug
 * in IE6 and below that doubles horizontal margins for floated elements)
 * The styles below is the full style for the list-items. 
 */
#header ul li {
    color:#CCCCCC;
    display:inline;
    font-size:20px;
    padding-right:20px;
}

How to see the proxy settings on windows?

You can figure out which proxy server you're using by accessing some websites with a browser and then running the DOS command:

netstat

and you'll see some connections in the Foreign Address column on port 80 or 8080 (common proxy server ports). Ideally you will be able to identify the proxy server by its naming convention.

[see also https://stackoverflow.com/a/8161865/3195477]

Convert List into Comma-Separated String

Enjoy!

Console.WriteLine(String.Join(",", new List<uint> { 1, 2, 3, 4, 5 }));

First Parameter: ","
Second Parameter: new List<uint> { 1, 2, 3, 4, 5 })

String.Join will take a list as a the second parameter and join all of the elements using the string passed as the first parameter into one single string.

How do I prevent people from doing XSS in Spring MVC?

I use Hibernate Validator via @Valid for all input objects (binding and @RequestBody json, see https://dzone.com/articles/spring-31-valid-requestbody). So @org.hibernate.validator.constraints.SafeHtml is a good solution for me.

Hibernate SafeHtmlValidator depends on org.jsoup, so it's needed to add one more project dependencies:

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.10.1</version>
</dependency>

For bean User with field

@NotEmpty
@SafeHtml
protected String name;

for update attempt with value <script>alert(123)</script> in controller

@PutMapping(value = "/{id}", consumes = MediaType.APPLICATION_JSON_VALUE)
public void update(@Valid @RequestBody User user, @PathVariable("id") int id) 

or

@PostMapping
public void createOrUpdate(@Valid User user) {

is thrown BindException for binding and MethodArgumentNotValidException for @RequestBody with default message:

name may have unsafe html content

Validator works as well for binding, as before persisting. Apps could be tested at http://topjava.herokuapp.com/

UPDATE: see also comment from @GuyT

CVE-2019-10219 and status of @SafeHtml

We have been made aware of a CVE-2019-10219 related to the @SafeHtml constraint and it was fixed in both 6.0.18.Final and 6.1.0.Final....

However, we came to the conclusion that the @SafeHtml constraint was fragile, highly security-sensitive and depending on an external library that wasn’t designed for this purpose. Having it included in core Hibernate Validator was not a very good idea. That’s why we deprecated it and marked it for removal.There is no magic plan here so our users will have to maintain this constraint themselves

Resume for myself: it is safe and could be used, until solution better be found.