Programs & Examples On #Java ee 5

Use this tag for questions relating specifically to Java Enterprise Edition 5.

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

Deleting queues in RabbitMQ

install

$ sudo rabbitmq-plugins enable rabbitmq_management

and go to http://localhost:15672/#/queues if you are using localhost. the default password will be username: guest, password: guest and go to queues tab and delete the queue.

Giving a border to an HTML table row, <tr>

Left cell:

style="border-style:solid;border-width: 1px 0px 1px 1px;"

midd cell(s):

style="border-style:solid;border-width: 1px 0px 1px 0px;"

right cell:

style="border-style:solid;border-width: 1px 1px 1px 0px;"

How to send HTML email using linux command line

you should use "append" mode redirection >> instead of >

SQL Server Script to create a new user

CREATE LOGIN AdminLOGIN WITH PASSWORD = 'pass'
GO


Use MyDatabase;
GO

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = N'AdminLOGIN')
BEGIN
    CREATE USER [AdminLOGIN] FOR LOGIN [AdminLOGIN]
    EXEC sp_addrolemember N'db_owner', N'AdminLOGIN'
    EXEC master..sp_addsrvrolemember @loginame = N'adminlogin', @rolename = N'sysadmin'
END;
GO

this full help you for network using:

1- Right-click on SQL Server instance at root of Object Explorer, click on Properties
Select Security from the left pane.

2- Select the SQL Server and Windows Authentication mode radio button, and click OK.

3- Right-click on the SQL Server instance, select Restart (alternatively, open up Services and restart the SQL Server service).

4- Close sql server application and reopen it

5- open 'SQL Server Configuration Manager' and tcp enabled for network

6-Double-click the TCP/IP protocol, go to the IP Addresses tab and scroll down to the IPAll section.

7-Specify the 1433 in the TCP Port field (or another port if 1433 is used by another MSSQL Server) and press the OK 

8-Open in Sql Server: Security And Login  And Right Click on Login Name And Select Peroperties And Select Server Roles And 
  Checked The Sysadmin And Bulkadmin then Ok.
9-firewall: Open cmd as administrator and type: 
      netsh firewall set portopening protocol = TCP port = 1433 name = SQLPort mode = ENABLE scope = SUBNET profile = CURRENT

What's the name for hyphen-separated case?

Adding the correct link here Kebab Case

which is All lowercase with - separating words.

How do I see which checkbox is checked?

Try this

index.html

<form action="form.php" method="post">
    Do you like stackoverflow?
    <input type="checkbox" name="like" value="Yes" />  
    <input type="submit" name="formSubmit" value="Submit" /> 
</form>

form.php

<html>
<head>
</head>
<body>

<?php
    if(isset($_POST['like']))
    {
        echo "<h1>You like Stackoverflow.<h1>";
    }
    else
    {
        echo "<h1>You don't like Stackoverflow.</h1>";
    }   
?>

</body>
</html>

Or this

<?php
    if(isset($_POST['like'])) && 
    $_POST['like'] == 'Yes') 
    {
        echo "You like Stackoverflow.";
    }
    else
    {
        echo "You don't like Stackoverflow.";
    }   
?>

Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

See Heroku “psql: FATAL: remaining connection slots are reserved for non-replication superuser connections”:

Heroku sometimes has a problem with database load balancing.

André Laszlo, markshiz and me all reported dealing with that in comments on the question.

To save you the support call, here's the response I got from Heroku Support for a similar issue:

Hello,

One of the limitations of the hobby tier databases is unannounced maintenance. Many hobby databases run on a single shared server, and we will occasionally need to restart that server for hardware maintenance purposes, or migrate databases to another server for load balancing. When that happens, you'll see an error in your logs or have problems connecting. If the server is restarting, it might take 15 minutes or more for the database to come back online.

Most apps that maintain a connection pool (like ActiveRecord in Rails) can just open a new connection to the database. However, in some cases an app won't be able to reconnect. If that happens, you can heroku restart your app to bring it back online.

This is one of the reasons we recommend against running hobby databases for critical production applications. Standard and Premium databases include notifications for downtime events, and are much more performant and stable in general. You can use pg:copy to migrate to a standard or premium plan.

If this continues, you can try provisioning a new database (on a different server) with heroku addons:add, then use pg:copy to move the data. Keep in mind that hobby tier rules apply to the $9 basic plan as well as the free database.

Thanks, Bradley

What is the purpose of using WHERE 1=1 in SQL statements?

The 1=1 is ignored by always all rdbms. There is no tradeoff executing a query with WHERE 1=1.

Building dynamic WHERE conditions, like ORM frameworks or other do very often, it is easier to append the real where conditions because you avoid checking for prepending an AND to the current condition.

stmt += "WHERE 1=1";
if (v != null) {
   stmt += (" AND col = " + v.ToString());
}

This is how it looks like without 1=1.

var firstCondition = true;
...
if (v != null) {
   if (!firstCondition) {
      stmt += " AND ";
   }
   else {
       stmt += " WHERE ";
       firstCondition = false;
   }
   stmt += "col = " + v.ToString());
}

Cross-Domain Cookies

I've created an NPM module, which allows you to share locally-stored data across domains: https://www.npmjs.com/package/cookie-toss

By using an iframe hosted on Domain A, you can store all of your user data on Domain A, and reference that data by posting requests to the Domain A iframe.

Thus, Domains B, C, etc. can inject the iframe and post requests to it to store and access the desired data. Domain A becomes the hub for all shared data.

With a domain whitelist inside of Domain A, you can ensure only your dependent sites can access the data on Domain A.

The trick is to have the code inside of the iframe on Domain A which is able to recognize which data is being requested. The README in the above NPM module goes more in depth into the procedure.

Hope this helps!

Restricting JTextField input to Integers

Here's one approach that uses a keylistener,but uses the keyChar (instead of the keyCode):

http://edenti.deis.unibo.it/utils/Java-tips/Validating%20numerical%20input%20in%20a%20JTextField.txt

 keyText.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      if (!((c >= '0') && (c <= '9') ||
         (c == KeyEvent.VK_BACK_SPACE) ||
         (c == KeyEvent.VK_DELETE))) {
        getToolkit().beep();
        e.consume();
      }
    }
  });

Another approach (which personally I find almost as over-complicated as Swing's JTree model) is to use Formatted Text Fields:

http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

Difference between one-to-many and many-to-one relationship

Example

Two tables with one relation

SQL

In SQL, there is only one kind of relationship, it is called a Reference. (Your front end may do helpful or confusing things [such as in some of the Answers], but that is a different story.)

  • A Foreign Key in one table (the referencing table)
    References
    a Primary Key in another table (the referenced table)
  • In SQL terms, Bar references Foo
    Not the other way around

    CREATE TABLE Foo (
        Foo   CHAR(10)  NOT NULL, -- primary key
        Name  CHAR(30)  NOT NULL
        CONSTRAINT PK             -- constraint name
            PRIMARY KEY (Foo)     -- pk
        )  
    CREATE TABLE Bar (
        Bar   CHAR(10)  NOT NULL, -- primary key
        Foo   CHAR(10)  NOT NULL, -- foreign key to Foo
        Name  CHAR(30)  NOT NULL
        CONSTRAINT PK                -- constraint name
            PRIMARY KEY (Bar),       -- pk
        CONSTRAINT Foo_HasMany_Bars  -- constraint name
            FOREIGN KEY   (Foo)      -- fk in (this) referencing table
            REFERENCES Foo(Foo)      -- pk in referenced table
        )
    
  • Since Foo.Foo is a Primary Key, it is unique, there is only one row for any given value of Foo

  • Since Bar.Foo is a Reference, a Foreign Key, and there is no unique index on it, there can be many rows for any given value of Foo
  • Therefore the relation Foo::Bar is one-to-many
  • Now you can perceive (look at) the relation the other way around, Bar::Foo is many-to-one
    • But do not let that confuse you: for any one Bar row, there is just one Foo row that it References
  • In SQL, that is all we have. That is all that is necessary.

What is the real difference between one to many and many to one relationship?

There is only one relation, therefore there is no difference. Perception (from one "end" or the other "end") or reading it backwards, does not change the relation.

Cardinality

Cardinality is declared first in the data model, which means Logical and Physical (the intent), and then in the implementation (the intent realised).

Cardinality

One to zero-to-many
In SQL that (the above) is all that is required.

One to one-to-many
You need a Transaction to enforce the one in the Referencing table.

One to zero-to-one
You need in Bar:

CONSTRAINT AK    -- constraint name
    UNIQUE (Foo) -- unique column, which makes it an Alternate Key

One to one
You need a Transaction to enforce the one in the Referencing table.

Many to many
There is no such thing at the Physical level (recall, there is only one type of relation in SQL).

At the early Logical levels during the modelling exercise, it is convenient to draw such a relation. Before the model gets close to implementation, it had better be elevated to using only things that can exist. Such a relation is resolved by implementing an Associative Table.

Many-to-many Resolved

How to upload folders on GitHub

You can also use the command line, Change directory where your folder is located then type the following :

     git init
     git add <folder1> <folder2> <etc.>
     git commit -m "Your message about the commit"
     git remote add origin https://github.com/yourUsername/yourRepository.git
     git push -u origin master
     git push origin master  

Set default syntax to different filetype in Sublime Text 2

You can turn on syntax highlighting based on the contents of the file.

For example, my Makefiles regardless of their extension the first line as follows:

#-*-Makefile-*- vim:syntax=make

This is typical practice for other editors such as vim.

However, for this to work you need to modify the Makefile.tmLanguage file.

  1. Find the file (for Sublime Text 3 in Ubuntu) at:

    /opt/sublime_text/Packages/Makefile.sublime-package
    

Note, that is really a zip file. Copy it, rename with .zip at the end, and extract the Makefile.tmLanguage file from it.

  1. Edit the new Makefile.tmLanguage by adding the "firstLineMatch" key and string after the "fileTypes" section. In the example below, the last two lines are new (should be added by you). The <string> section holds the regular expression, that will enable syntax highlighting for the files that match the first line. This expression recognizes two patterns: "-*-Makefile-*-" and "vim:syntax=make".

    ...
    <key>fileTypes</key>
    <array>
        <string>GNUmakefile</string>
        <string>makefile</string>
        <string>Makefile</string>
        <string>OCamlMakefile</string>
        <string>make</string>
    </array>
    
    <key>firstLineMatch</key>
    <string>^#\s*-\*-Makefile-\*-|^#.*\s*vim:syntax=make</string>
    
  2. Place the modified Makefile.tmLanguage in the User settings directory:

    ~/.config/sublime-text-3/Packages/User/Makefile.tmLanguage
    

All the files matching the first line rule should turn the syntax highlighting on when opened.

How to remove default chrome style for select Input?

-webkit-appearance: none;

and add your own style

Remove sensitive files and their commits from Git history

You can use git forget-blob.

The usage is pretty simple git forget-blob file-to-forget. You can get more info here

https://ownyourbits.com/2017/01/18/completely-remove-a-file-from-a-git-repository-with-git-forget-blob/

It will disappear from all the commits in your history, reflog, tags and so on

I run into the same problem every now and then, and everytime I have to come back to this post and others, that's why I automated the process.

Credits to contributors from Stack Overflow that allowed me to put this together

What is the 'dynamic' type in C# 4.0 used for?

The best use case of 'dynamic' type variables for me was when, recently, I was writing a data access layer in ADO.NET (using SQLDataReader) and the code was invoking the already written legacy stored procedures. There are hundreds of those legacy stored procedures containing bulk of the business logic. My data access layer needed to return some sort of structured data to the business logic layer, C# based, to do some manipulations (although there are almost none). Every stored procedures returns different set of data (table columns). So instead of creating dozens of classes or structs to hold the returned data and pass it to the BLL, I wrote the below code which looks quite elegant and neat.

public static dynamic GetSomeData(ParameterDTO dto)
        {
            dynamic result = null;
            string SPName = "a_legacy_stored_procedure";
            using (SqlConnection connection = new SqlConnection(DataConnection.ConnectionString))
            {
                SqlCommand command = new SqlCommand(SPName, connection);
                command.CommandType = System.Data.CommandType.StoredProcedure;                
                command.Parameters.Add(new SqlParameter("@empid", dto.EmpID));
                command.Parameters.Add(new SqlParameter("@deptid", dto.DeptID));
                connection.Open();
                using (SqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        dynamic row = new ExpandoObject();
                        row.EmpName = reader["EmpFullName"].ToString();
                        row.DeptName = reader["DeptName"].ToString();
                        row.AnotherColumn = reader["AnotherColumn"].ToString();                        
                        result = row;
                    }
                }
            }
            return result;
        }

Check which element has been clicked with jQuery

Answer from vpiTriumph lays out the details nicely.
Here's a small handy variation for when there are unique element ids for the data set you want to access:

$('.news-article').click(function(event){    
    var id = event.target.id;
    console.log('id = ' + id); 
});

In PHP how can you clear a WSDL cache?

if you already deployed the code or can't change any configuration, you could remove all temp files from wsdl:

rm /tmp/wsdl-*

Which HTML Parser is the best?

The best I've seen so far is HtmlCleaner:

HtmlCleaner is open-source HTML parser written in Java. HTML found on Web is usually dirty, ill-formed and unsuitable for further processing. For any serious consumption of such documents, it is necessary to first clean up the mess and bring the order to tags, attributes and ordinary text. For the given HTML document, HtmlCleaner reorders individual elements and produces well-formed XML. By default, it follows similar rules that the most of web browsers use in order to create Document Object Model. However, user may provide custom tag and rule set for tag filtering and balancing.

With HtmlCleaner you can locate any element using XPath.

For other html parsers see this SO question.

Making HTTP Requests using Chrome Developer tools

_x000D_
_x000D_
$.post(_x000D_
    'dom/data-home.php',_x000D_
    {_x000D_
    type : "home", id : "0"_x000D_
    },function(data){_x000D_
        console.log(data)_x000D_
    })
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

android.view.InflateException: Binary XML file: Error inflating class fragment

After long time of tries, this is how I solved the problem after none of the above answers could.

  1. Extend AppCompatActivity for your Main activity instead of Activity.
  2. Add android:theme="@style/Theme.AppCompat.Light" to your <Activity..../> in the AndroidManifest.xml
  3. In your NavigationDrawerFragment Class, change your ActionBar instances to

    ActionBar mActionBar=((AppCompatActivity)getActivity()).getSupportActionBar();
    

EDIT

It should be a consistency between the Activity and Layout. If the Layout has one of the AppCompat Theme such like Theme.AppCompat.Light, your Activity should extends AppCompatActivity.

I wanted to have the burger icon and a Navigation Drawer that looks like the Android Gmail App, but I ended up with an ugly Navigation Drawer. All that because all my Classes extends Activity instead of AppCompatActivity.

I re-factored the entire project to extend AppCompatActivity, then Right-Click on the Layout Folder, chose new -> Activity then Navigation Drawer Activity and Boom, everything is done for me!

How do I fix the indentation of an entire file in Vi?

:set paste is your friend I use putty and end up copying code between windows. Before I was turned on to :set paste (and :set nopaste) copy/paste gave me fits for that very reason.

JDBC connection failed, error: TCP/IP connection to host failed

The error is self explanatory:

  • Check if your SQL server is actually up and running
  • Check SQL server hostname, username and password is correct
  • Check there's no firewall rule blocking TCP connection to port 1433
  • Check the host is actually reachable

A good check I often use is to use telnet, eg on a windows command prompt run:

telnet 127.0.0.1 1433

If you get a blank screen it indicates network connection established successfully, and it's not a network problem. If you get 'Could not open connection to the host' then this is network problem

Replace new lines with a comma delimiter with Notepad++?

fapDaddy's answer using a macro pointed me in the right direction.

Here's precisely what worked for me.

  1. Place the cursor after the first data item. enter image description here

  2. Click 'Macro > Start Recording' in the menu. enter image description here

  3. Type this sequence: Comma, Space, Delete, End. enter image description here

  4. Click 'Macro > Stop recording' in the menu. enter image description here

  5. Click 'Macro > Run a Macro Multiple Times...' in the menu. enter image description here

  6. Click 'Run until the end of file' and click 'Run'. enter image description here

  7. Remove any trailing characters. enter image description here

  8. Done!

enter image description here

How to set .net Framework 4.5 version in IIS 7 application pool

There is no v4.5 shown in the gui, and typically you don't need to manually specify v4.5 since it's an in-place update. However, you can set it explicitly with appcmd like this:

appcmd set apppool /apppool.name: [App Pool Name] /managedRuntimeVersion:v4.5

Appcmd is located in %windir%\System32\inetsrv. This helped me to fix an issue with Web Deploy, where it was throwing an ERROR_APPPOOL_VERSION_MISMATCH error after upgrading from v4.0 to v4.5.

MS article on setting .Net version for App Pool

How can I change all input values to uppercase using Jquery?

Try like below,

$('input[type=text]').val (function () {
    return this.value.toUpperCase();
})

You should use input[type=text] instead of :input or input as I believe your intention are to operate on textbox only.

ModalPopupExtender OK Button click event not firing?

I often use a blank label as the TargetControlID. ex. <asp:Label ID="lblghost" runat="server" Text="" />

I've seen two things that cause the click event not fire:
1. you have to remove the OKControlID (as others have mentioned)
2. If you are using field validators you should add CausesValidation="false" on the button.

Both scenarios behaved the same way for me.

What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?

ArrayIndexOutOfBoundsException means that you are trying to access an index of the array that does not exist or out of the bound of this array. Array indexes start from 0 and end at length - 1.

In your case

for(int i = 0; i<=name.length; i++) {
    System.out.print(name[i] +'\n'); // i goes from 0 to length, Not correct
}

ArrayIndexOutOfBoundsException happens when you are trying to access the name.length indexed element which does not exist (array index ends at length -1). just replacing <= with < would solve this problem.

for(int i = 0; i < name.length; i++) {
    System.out.print(name[i] +'\n');  // i goes from 0 to length - 1, Correct
}

Exec : display stdout "live"

I have found it helpful to add a custom exec script to my utilities that do this.

utilities.js

const { exec } = require('child_process')

module.exports.exec = (command) => {
  const process = exec(command)

  process.stdout.on('data', (data) => {
    console.log('stdout: ' + data.toString())
  })

  process.stderr.on('data', (data) => {
    console.log('stderr: ' + data.toString())
  })

  process.on('exit', (code) => {
    console.log('child process exited with code ' + code.toString())
  })
}

app.js

const { exec } = require('./utilities.js')

exec('coffee -cw my_file.coffee')

clearing select using jquery

use .empty()

 $('select').empty().append('whatever');

you can also use .html() but note

When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Consider the following HTML:

alternative: --- If you want only option elements to-be-remove, use .remove()

$('select option').remove();

Formatting Decimal places in R

Background: Some answers suggested on this page (e.g., signif, options(digits=...)) do not guarantee that a certain number of decimals are displayed for an arbitrary number. I presume this is a design feature in R whereby good scientific practice involves showing a certain number of digits based on principles of "significant figures". However, in many domains (e.g., APA style, business reports) formatting requirements dictate that a certain number of decimal places are displayed. This is often done for consistency and standardisation purposes rather than being concerned with significant figures.

Solution:

The following code shows exactly two decimal places for the number x.

format(round(x, 2), nsmall = 2)

For example:

format(round(1.20, 2), nsmall = 2)
# [1] "1.20"
format(round(1, 2), nsmall = 2)
# [1] "1.00"
format(round(1.1234, 2), nsmall = 2)
# [1] "1.12"

A more general function is as follows where x is the number and k is the number of decimals to show. trimws removes any leading white space which can be useful if you have a vector of numbers.

specify_decimal <- function(x, k) trimws(format(round(x, k), nsmall=k))

E.g.,

specify_decimal(1234, 5)
# [1] "1234.00000"
specify_decimal(0.1234, 5)
# [1] "0.12340"

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

If you are using express you can use the cors package to allow CORS like so instead of writing your middleware;

var express = require('express')
, cors = require('cors')
, app = express();

app.use(cors());

app.get(function(req,res){ 
  res.send('hello');
});

How do I read all classes from a Java package in the classpath?

Java 1.6.0_24:

public static File[] getPackageContent(String packageName) throws IOException{
    ArrayList<File> list = new ArrayList<File>();
    Enumeration<URL> urls = Thread.currentThread().getContextClassLoader()
                            .getResources(packageName);
    while (urls.hasMoreElements()) {
        URL url = urls.nextElement();
        File dir = new File(url.getFile());
        for (File f : dir.listFiles()) {
            list.add(f);
        }
    }
    return list.toArray(new File[]{});
}

This solution was tested within the EJB environment.

How are Anonymous inner classes used in Java?

i use anonymous objects for calling new Threads..

new Thread(new Runnable() {
    public void run() {
        // you code
    }
}).start();

Invalid column name sql error

You probably need quotes around those string fields, but, you should be using parameterized queries!

cmd.CommandText = "INSERT INTO Data ([Name],PhoneNo,Address) VALUES (@name, @phone, @address)";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@phone", txtPhone.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Connection = connection;

Incidentally, your original query could have been fixed like this (note the single quotes):

"VALUES ('" + txtName.Text + "','" + txtPhone.Text + "','" + txtAddress.Text + "');";

but this would have made it vulnerable to SQL Injection attacks since a user could type in

'; drop table users; -- 

into one of your textboxes. Or, more mundanely, poor Daniel O'Reilly would break your query every time.

Getting results between two dates in PostgreSQL

No offense but to check for performance of sql I executed some of the above mentioned solutiona pgsql.

Let me share you Statistics of top 3 solution approaches that I come across.

1) Took : 1.58 MS Avg

2) Took : 2.87 MS Avg

3) Took : 3.95 MS Avg

Now try this :

 SELECT * FROM table WHERE DATE_TRUNC('day', date ) >= Start Date AND DATE_TRUNC('day', date ) <= End Date

Now this solution took : 1.61 Avg.

And best solution is 1st that suggested by marco-mariani

C# RSA encryption/decryption with transmission

well there are really enough examples for this, but anyway, here you go

using System;
using System.Security.Cryptography;

namespace RsaCryptoExample
{
  static class Program
  {
    static void Main()
    {
      //lets take a new CSP with a new 2048 bit rsa key pair
      var csp = new RSACryptoServiceProvider(2048);

      //how to get the private key
      var privKey = csp.ExportParameters(true);

      //and the public key ...
      var pubKey = csp.ExportParameters(false);

      //converting the public key into a string representation
      string pubKeyString;
      {
        //we need some buffer
        var sw = new System.IO.StringWriter();
        //we need a serializer
        var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
        //serialize the key into the stream
        xs.Serialize(sw, pubKey);
        //get the string from the stream
        pubKeyString = sw.ToString();
      }

      //converting it back
      {
        //get a stream from the string
        var sr = new System.IO.StringReader(pubKeyString);
        //we need a deserializer
        var xs = new System.Xml.Serialization.XmlSerializer(typeof(RSAParameters));
        //get the object back from the stream
        pubKey = (RSAParameters)xs.Deserialize(sr);
      }

      //conversion for the private key is no black magic either ... omitted

      //we have a public key ... let's get a new csp and load that key
      csp = new RSACryptoServiceProvider();
      csp.ImportParameters(pubKey);

      //we need some data to encrypt
      var plainTextData = "foobar";

      //for encryption, always handle bytes...
      var bytesPlainTextData = System.Text.Encoding.Unicode.GetBytes(plainTextData);

      //apply pkcs#1.5 padding and encrypt our data 
      var bytesCypherText = csp.Encrypt(bytesPlainTextData, false);

      //we might want a string representation of our cypher text... base64 will do
      var cypherText = Convert.ToBase64String(bytesCypherText);


      /*
       * some transmission / storage / retrieval
       * 
       * and we want to decrypt our cypherText
       */

      //first, get our bytes back from the base64 string ...
      bytesCypherText = Convert.FromBase64String(cypherText);

      //we want to decrypt, therefore we need a csp and load our private key
      csp = new RSACryptoServiceProvider();
      csp.ImportParameters(privKey);

      //decrypt and strip pkcs#1.5 padding
      bytesPlainTextData = csp.Decrypt(bytesCypherText, false);

      //get our original plainText back...
      plainTextData = System.Text.Encoding.Unicode.GetString(bytesPlainTextData);
    }
  }
}

as a side note: the calls to Encrypt() and Decrypt() have a bool parameter that switches between OAEP and PKCS#1.5 padding ... you might want to choose OAEP if it's available in your situation

Why do we use volatile keyword?

Consider this code,

int some_int = 100;

while(some_int == 100)
{
   //your code
}

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!

So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays its role. All you need to do is this,

volatile int some_int = 100; //note the 'volatile' qualifier now!

In other words, I would explain this as follows:

volatile tells the compiler that,

"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"

Well, that is how volatile prevents the compiler from optimizing code. Now search the web to see some sample examples.


Quoting from the C++ Standard ($7.1.5.1/8)

[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]

Related topic:

Does making a struct volatile make all its members volatile?

Android check null or empty string in Android

if you check null or empty String so you can try this

if (createReminderRequest.getDate() == null && createReminderRequest.getDate().trim().equals("")){
    DialogUtility.showToast(this, ProjectUtils.getString(R.string.please_select_date_n_time));
}

How to hash some string with sha256 in Java?

Full example hash to string as another string.

public static String sha256(String base) {
    try{
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(base.getBytes("UTF-8"));
        StringBuffer hexString = new StringBuffer();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
    } catch(Exception ex){
       throw new RuntimeException(ex);
    }
}

Is there a way to word-wrap long words in a div?

As david mentions, DIVs do wrap words by default.

If you are referring to really long strings of text without spaces, what I do is process the string server-side and insert empty spans:

thisIsAreallyLongStringThatIWantTo<span></span>BreakToFitInsideAGivenSpace

It's not exact as there are issues with font-sizing and such. The span option works if the container is variable in size. If it's a fixed width container, you could just go ahead and insert line breaks.

How to install libusb in Ubuntu

"I need to install it to the folder of my C program." Why?

Include usb.h:

#include <usb.h>

and remember to add -lusb to gcc:

gcc -o example example.c -lusb

This work fine for me.

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

You might just have to install the packages.

yum install php-pdo php-mysqli

After they're installed, restart Apache.

httpd restart

or

apachectl restart

forEach loop Java 8 for Map entry set

Maybe the best way to answer the questions like "which version is faster and which one shall I use?" is to look to the source code:

map.forEach() - from Map.java

default void forEach(BiConsumer<? super K, ? super V> action) {
    Objects.requireNonNull(action);
    for (Map.Entry<K, V> entry : entrySet()) {
        K k;
        V v;
        try {
            k = entry.getKey();
            v = entry.getValue();
        } catch(IllegalStateException ise) {
            // this usually means the entry is no longer in the map.
            throw new ConcurrentModificationException(ise);
        }
        action.accept(k, v);
    }
}

javadoc

map.entrySet().forEach() - from Iterable.java

default void forEach(Consumer<? super T> action) {
    Objects.requireNonNull(action);
    for (T t : this) {
        action.accept(t);
    }
}

javadoc

This immediately reveals that map.forEach() is also using Map.Entry internally. So I would not expect any performance benefit in using map.forEach() over the map.entrySet().forEach(). So in your case the answer really depends on your personal taste :)

For the complete list of differences please refer to the provided javadoc links. Happy coding!

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

You can track all calls to [ASIdentifierManager advertisingIdentifier] with symbolic breakpoint in Xcode: enter image description here

How do you access the element HTML from within an Angular attribute directive?

Base on @Mark answer, I add the constructor to directive and it work with me.

I share a sample to whom concern.

constructor(private el: ElementRef, private renderer: Renderer) {
}

TS file

@Directive({ selector: '[accordion]' })
export class AccordionDirective {

  constructor(private el: ElementRef, private renderer: Renderer) {
  }

  @HostListener('click', ['$event']) onClick($event) {
    console.info($event);

    this.el.nativeElement.classList.toggle('is-open');

    var content = this.el.nativeElement.nextElementSibling;
    if (content.style.maxHeight) {
      // accordion is currently open, so close it
      content.style.maxHeight = null;
    } else {
      // accordion is currently closed, so open it
      content.style.maxHeight = content.scrollHeight + "px";

    }
  }
}

HTML

<button accordion class="accordion">Accordian #1</button>
    <div class="accordion-content">
      <p>
        Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quas deleniti molestias necessitatibus quaerat quos incidunt! Quas officiis repellat dolore omnis nihil quo,
        ratione cupiditate! Sed, deleniti, recusandae! Animi, sapiente, nostrum?
      </p>     
    </div>

Demo https://stackblitz.com/edit/angular-directive-accordion?file=src/app/app.component.ts

List to array conversion to use ravel() function

create an int array and a list

from array import array
listA = list(range(0,50))
for item in listA:
    print(item)
arrayA = array("i", listA)
for item in arrayA:
    print(item)

How to scale down a range of numbers with a known min and max value

I sometimes find a variation of this useful.

  1. Wrapping the scale function in a class so that I do not need to pass around the min/max values if scaling the same ranges in several places
  2. Adding two small checks that ensures that the result value stays within the expected range.

Example in JavaScript:

class Scaler {
  constructor(inMin, inMax, outMin, outMax) {
    this.inMin = inMin;
    this.inMax = inMax;
    this.outMin = outMin;
    this.outMax = outMax;
  }

  scale(value) {
    const result = (value - this.inMin) * (this.outMax - this.outMin) / (this.inMax - this.inMin) + this.outMin;

    if (result < this.outMin) {
      return this.outMin;
    } else if (result > this.outMax) {
      return this.outMax;
    }

    return result;
  }
}

This example along with a function based version comes from the page https://writingjavascript.com/scaling-values-between-two-ranges

Understanding the order() function

This seems to explain it.

The definition of order is that a[order(a)] is in increasing order. This works with your example, where the correct order is the fourth, second, first, then third element.

You may have been looking for rank, which returns the rank of the elements
R> a <- c(4.1, 3.2, 6.1, 3.1)
R> order(a)
[1] 4 2 1 3
R> rank(a)
[1] 3 2 4 1
so rank tells you what order the numbers are in, order tells you how to get them in ascending order.

plot(a, rank(a)/length(a)) will give a graph of the CDF. To see why order is useful, though, try plot(a, rank(a)/length(a),type="S") which gives a mess, because the data are not in increasing order

If you did
oo<-order(a)
plot(a[oo],rank(a[oo])/length(a),type="S")
or simply
oo<-order(a)
plot(a[oo],(1:length(a))/length(a)),type="S")
you get a line graph of the CDF.

I'll bet you're thinking of rank.

How to get a subset of a javascript object's properties

Using Object Destructuring and Property Shorthand

_x000D_
_x000D_
const object = { a: 5, b: 6, c: 7  };_x000D_
const picked = (({ a, c }) => ({ a, c }))(object);_x000D_
_x000D_
console.log(picked); // { a: 5, c: 7 }
_x000D_
_x000D_
_x000D_


From Philipp Kewisch:

This is really just an anonymous function being called instantly. All of this can be found on the Destructuring Assignment page on MDN. Here is an expanded form

_x000D_
_x000D_
let unwrap = ({a, c}) => ({a, c});_x000D_
_x000D_
let unwrap2 = function({a, c}) { return { a, c }; };_x000D_
_x000D_
let picked = unwrap({ a: 5, b: 6, c: 7 });_x000D_
_x000D_
let picked2 = unwrap2({a: 5, b: 6, c: 7})_x000D_
_x000D_
console.log(picked)_x000D_
console.log(picked2)
_x000D_
_x000D_
_x000D_

Check whether a table contains rows or not sql server 2005

Like Other said you can use something like that:

IF NOT EXISTS (SELECT 1 FROM Table)
  BEGIN 
    --Do Something
  END 
ELSE
  BEGIN
    --Do Another Thing
  END

How to add an element to a list?

import json

myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}]}

myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}

jQuery: get parent tr for selected radio button

Try this.

You don't need to prefix attribute name by @ in jQuery selector. Use closest() method to get the closest parent element matching the selector.

$("#MwDataList input[name=selectRadioGroup]:checked").closest('tr');

You can simplify your method like this

function getSelectedRowGuid() {
    return GetRowGuid(
      $("#MwDataList > input:radio[@name=selectRadioGroup]:checked :parent tr"));
}

closest() - Gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.

As a side note, the ids of the elements should be unique on the page so try to avoid having same ids for radio buttons which I can see in your markup. If you are not going to use the ids then just remove it from the markup.

CSS display: inline vs inline-block

Inline elements:

  1. respect left & right margins and padding, but not top & bottom
  2. cannot have a width and height set
  3. allow other elements to sit to their left and right.
  4. see very important side notes on this here.

Block elements:

  1. respect all of those
  2. force a line break after the block element
  3. acquires full-width if width not defined

Inline-block elements:

  1. allow other elements to sit to their left and right
  2. respect top & bottom margins and padding
  3. respect height and width

From W3Schools:

  • An inline element has no line break before or after it, and it tolerates HTML elements next to it.

  • A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.

  • An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.

When you visualize this, it looks like this:

CSS block vs inline vs inline-block

The image is taken from this page, which also talks some more about this subject.

Script to get the HTTP status code of a list of urls?

This relies on widely available wget, present almost everywhere, even on Alpine Linux.

wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'

The explanations are as follow :

--quiet

Turn off Wget's output.

Source - wget man pages

--spider

[ ... ] it will not download the pages, just check that they are there. [ ... ]

Source - wget man pages

--server-response

Print the headers sent by HTTP servers and responses sent by FTP servers.

Source - wget man pages

What they don't say about --server-response is that those headers output are printed to standard error (sterr), thus the need to redirect to stdin.

The output sent to standard input, we can pipe it to awk to extract the HTTP status code. That code is :

  • the second ($2) non-blank group of characters: {$2}
  • on the very first line of the header: NR==1

And because we want to print it... {print $2}.

wget --server-response --spider --quiet "${url}" 2>&1 | awk 'NR==1{print $2}'

Any easy way to use icons from resources?

After adding the ICO file to your apps resources, you can use references it using My.Resources.YourIconNameWithoutExtension

For example if I had a file called Logo-square.ico added to my apps resources, I can set it to an icon with:

NotifyIcon1.Icon = My.Resources.Logo_square

Project Links do not work on Wamp Server

I believe this is the best solution:

Open index.php in www folder and set

change line 30:$suppress_localhost = true;

to $suppress_localhost = false;

This will ensure the project is prefixed with your local host IP/name

curl: (6) Could not resolve host: google.com; Name or service not known

Try nslookup google.com to determine if there's a DNS issue. 192.168.1.254 is your local network address and it looks like your system is using it as a DNS server. Is this your gateway/modem router as well? What happens when you try ping google.com. Can you browse to it on a Internet web browser?

List of All Locales and Their Short Codes?

If you are using php-intl to localize your application, you probably want to use ResourceBundle::getLocales() instead of static list that you maintain yourself. It can also give you locales for particular language.

<?php
print_r(ResourceBundle::getLocales(''));

/* Output might show
  * Array
  * (
  *    [0] => af
  *    [1] => af_NA
  *    [2] => af_ZA
  *    [3] => am
  *    [4] => am_ET
  *    [5] => ar
  *    [6] => ar_AE
  *    [7] => ar_BH
  *    [8] => ar_DZ
  *    [9] => ar_EG
  *    [10] => ar_IQ
  *  ...
  */
?>

warning about too many open figures

The following snippet solved the issue for me:


class FigureWrapper(object):
    '''Frees underlying figure when it goes out of scope. 
    '''

    def __init__(self, figure):
        self._figure = figure

    def __del__(self):
        plt.close(self._figure)
        print("Figure removed")


# .....
    f, ax = plt.subplots(1, figsize=(20, 20))
    _wrapped_figure = FigureWrapper(f)

    ax.plot(...
    plt.savefig(...
# .....

When _wrapped_figure goes out of scope the runtime calls our __del__() method with plt.close() inside. It happens even if exception fires after _wrapped_figure constructor.

Program to find prime numbers

Try this:

void prime_num(long num)
{

    // bool isPrime = true;
    for (long i = 0; i <= num; i++)
    {
        bool isPrime = true; // Move initialization to here
        for (long j = 2; j < i; j++) // you actually only need to check up to sqrt(i)
        {
            if (i % j == 0) // you don't need the first condition
            {
                isPrime = false;
                break;
            }
        }
        if (isPrime)
        {
            Console.WriteLine ( "Prime:" + i );
        }
        // isPrime = true;
    }
}

How to implement zoom effect for image view in android?

Very simple way (Tested) :-

PhotoViewAttacher pAttacher;
pAttacher = new PhotoViewAttacher(Your_Image_View);
pAttacher.update();

Add bellow line in build.gradle :-

compile 'com.commit451:PhotoView:1.2.4'

How to get the changes on a branch in Git

git cherry branch [newbranch]

does exactly what you are asking, when you are in the master branch.

I am also very fond of:

git diff --name-status branch [newbranch]

Which isn't exactly what you're asking, but is still very useful in the same context.

Truncate all tables in a MySQL database in one command?

Here is my variant to have 'one statement to truncate 'em all'.

First, I am using a separate database named 'util' for my helper stored procedures. The code of my stored procedure to truncate all tables is:

DROP PROCEDURE IF EXISTS trunctables;
DELIMITER ;;
CREATE  PROCEDURE trunctables(theDb varchar(64))
BEGIN
    declare tname varchar(64);
    declare tcursor CURSOR FOR 
    SELECT table_name FROM information_schema.tables WHERE table_type <> 'VIEW' AND table_schema = theDb;
    SET FOREIGN_KEY_CHECKS = 0; 
    OPEN tcursor;
    l1: LOOP
        FETCH tcursor INTO tname;
        if tname = NULL then leave l1; end if;
        set @sql = CONCAT('truncate `', theDB, '`.`', tname, '`');
        PREPARE stmt from @sql;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;
    END LOOP l1;
    CLOSE tcursor;
    SET FOREIGN_KEY_CHECKS = 1; 
END ;;
DELIMITER ;

Once you have this stored procedure in your util database, you can call it like

call util.trunctables('nameofdatabase');

which is now exactly one statement :-)

Remove all stylings (border, glow) from textarea

If you want to remove EVERYTHING :

textarea {
    border: none;
    background-color: transparent;
    resize: none;
    outline: none;
}

What is the difference between _tmain() and main() in C++?

With a little effort of templatizing this, it wold work with any list of objects.

#include <iostream>
#include <string>
#include <vector>

char non_repeating_char(std::string str){
    while(str.size() >= 2){
        std::vector<size_t> rmlist; 
        for(size_t  i = 1;  i < str.size(); i++){        
            if(str[0] == str[i]) {
                rmlist.push_back(i);
            }      
        }          

        if(rmlist.size()){            
            size_t s = 0;  // Need for terator position adjustment   
            str.erase(str.begin() + 0);
            ++s;
            for (size_t j : rmlist){   
                str.erase(str.begin() + (j-s));                
                ++s;
            }
         continue;
        }
        return str[0];
   }
    if(str.size() == 1) return str[0];
    else return -1;
}

int main(int argc, char ** args)
{
    std::string test = "FabaccdbefafFG";
    test = args[1];
    char non_repeating = non_repeating_char(test);
    Std::cout << non_repeating << '\n';
}

How to disable the back button in the browser using JavaScript

One cannot disable the browser back button functionality. The only thing that can be done is prevent them.

The below JavaScript code needs to be placed in the head section of the page where you don’t want the user to revisit using the back button:

<script>
    function preventBack() {
        window.history.forward();
    }

    setTimeout("preventBack()", 0);
    window.onunload = function() {
        null
    };
</script>

Suppose there are two pages Page1.php and Page2.php and Page1.php redirects to Page2.php.

Hence to prevent user from visiting Page1.php using the back button you will need to place the above script in the head section of Page1.php.

For more information: Reference

Android: how to get the current day of the week (Monday, etc...) in the user's language?

Try this...

//global declaration
private TextView timeUpdate;
Calendar calendar;

.......

timeUpdate = (TextView) findViewById(R.id.timeUpdate); //initialize in onCreate()

.......

//in onStart()
calendar = Calendar.getInstance();
//date format is:  "Date-Month-Year Hour:Minutes am/pm"
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy HH:mm a"); //Date and time
String currentDate = sdf.format(calendar.getTime());

//Day of Name in full form like,"Saturday", or if you need the first three characters you have to put "EEE" in the date format and your result will be "Sat".
SimpleDateFormat sdf_ = new SimpleDateFormat("EEEE"); 
Date date = new Date();
String dayName = sdf_.format(date);
timeUpdate.setText("" + dayName + " " + currentDate + "");

The result is... enter image description here

happy coding.....

How can one develop iPhone apps in Java?

I think Google Open Sources Java To Objective-C Translator will make it possiblöe to develop in Java for iOS https://code.google.com/p/j2objc/

How to show SVG file on React Native?

you can convert any SVG to a component and make it reusable.

here is my answer for the easiest way you can do it

SVG to component

"And" and "Or" troubles within an IF statement

The problem is probably somewhere else. Try this code for example:

Sub test()

  origNum = "006260006"
  creditOrDebit = "D"

  If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
    MsgBox "OK"
  End If

End Sub

And you will see that your Or works as expected. Are you sure that your ElseIf statement is executed (it will not be executed if any of the if/elseif before is true)?

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

I am creating Dialog in onCreate and using it with show and hide. For me the root cause was not dismissing onBackPressed, which was finishing the Home activity.

@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Home.this.finish();
                                return;
                            }
                        }).create().show();

I was finishing the Home Activity onBackPressed without closing / dismissing my dialogs.

When I dismissed my dialogs the crash disappeared.

new AlertDialog.Builder(this)
                .setTitle("Really Exit?")
                .setMessage("Are you sure you want to exit?")
                .setNegativeButton(android.R.string.no, null)
                .setPositiveButton(android.R.string.yes,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                networkErrorDialog.dismiss() ;
                                homeLocationErrorDialog.dismiss() ;
                                currentLocationErrorDialog.dismiss() ;
                                Home.this.finish();
                                return;
                            }
                        }).create().show();

How to view DLL functions?

Use dumpbin command-line.

  • dumpbin /IMPORTS <path-to-file> should provide the function imported into that DLL.
  • dumpbin /EXPORTS <path-to-file> should provide the functions it exports.

How to conditionally take action if FINDSTR fails to find a string

I presume you want to copy C:\OtherFolder\fileToCheck.bat to C:\MyFolder if the existing file in C:\MyFolder is either missing entirely, or if it is missing "stringToCheck".

FINDSTR sets ERRORLEVEL to 0 if the string is found, to 1 if it is not. It also sets errorlevel to 1 if the file is missing. It also prints out each line that matches. Since you are trying to use it as a condition, I presume you don't need or want to see any of the output. The 1st thing I would suggest is to redirect both the normal and error output to nul using >nul 2>&1.

Solution 1 (mostly the same as previous answers)

You can use IF ERRORRLEVEL N to check if the errorlevel is >= N. Or you can use IF NOT ERRORLEVEL N to check if errorlevel is < N. In your case you want the former.

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if errorlevel 1 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

Solution 2

You can test for a specific value of errorlevel by using %ERRORLEVEL%. You can probably check if the value is equal to 1, but it might be safer to check if the value is not equal to 0, since it is only set to 0 if the file exists and it contains the string.

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if not %errorlevel% == 0 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

or

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1
if %errorlevel% neq 0 xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

Solution 3

There is a very compact syntax to conditionally execute a command based on the success or failure of the previous command: cmd1 && cmd2 || cmd3 which means execute cmd2 if cmd1 was successful (errorlevel=0), else execute cmd3 if cmd1 failed (errorlevel<>0). You can use && alone, or || alone. All the commands need to be on the same line. If you need to conditionally execute multiple commands you can use multiple lines by adding parentheses

cmd1 && (
   cmd2
   cmd3
) || (
   cmd4
   cmd5
)

So for your case, all you need is

findstr /c:"stringToCheck" "c:\MyFolder\fileToCheck.bat" >nul 2>&1 || xcopy "C:\OtherFolder\fileToCheck.bat" "c:\MyFolder"

But beware - the || will respond to the return code of the last command executed. In my earlier pseudo code the || will obviously fire if cmd1 fails, but it will also fire if cmd1 succeeds but then cmd3 fails.

So if your success block ends with a command that may fail, then you should append a harmless command that is guaranteed to succeed. I like to use (CALL ), which is harmless, and always succeeds. It also is handy that it sets the ERRORLEVEL to 0. There is a corollary (CALL) that always fails and sets ERRORLEVEL to 1.

Is it possible to get only the first character of a String?

Java strings are simply an array of char. So, char c = s[0] where s is string.

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

I believe some of the respondents of this question have missed the broader implication of the fold function as an abstract tool. Yes, sum can do the same thing for a list of integers, but this is a trivial case. fold is more generic. It is useful when you have a sequence of data structures of varying shape and want to cleanly express an aggregation. So instead of having to build up a for loop with an aggregate variable and manually recompute it each time, a fold function (or the Python version, which reduce appears to correspond to) allows the programmer to express the intent of the aggregation much more plainly by simply providing two things:

  • A default starting or "seed" value for the aggregation.
  • A function that takes the current value of the aggregation (starting with the "seed") and the next element in the list, and returns the next aggregation value.

How to interpret "loss" and "accuracy" for a machine learning model

They are two different metrics to evaluate your model's performance usually being used in different phases.

Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)

y1 = 0, x1_w = 50kg, x2_h = 160cm;

y2 = 0, x2_w = 60kg, x2_h = 170cm;

y3 = 1, x3_w = 55kg, x3_h = 175cm;

You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))

How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.

In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)

We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?

so the loss is

Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.

What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?

Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%

PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.

How do I clear all options in a dropdown box?

var select = document.getElementById('/*id attribute of your select here*/');
for (var option in select){
    select.remove(option);
}

How to use the ProGuard in Android Studio?

Here is Some of Most Common Proguard Rules that you need to add in proguard-rules.pro file in Android Sutdio.

ButterKnife

 -keep class butterknife.** { *; }
 -dontwarn butterknife.internal.**
 -keep class **$$ViewBinder { *; }
 -keepclasseswithmembernames class * {
        @butterknife.* <fields>;
  }
 -keepclasseswithmembernames class * {
        @butterknife.* <methods>;
  }

Retrofit

 -dontwarn retrofit.**
 -keep class retrofit.** { *; }
 -keepattributes Signature
 -keepattributes Exceptions

OkHttp3

 -keepattributes Signature
 -keepattributes *Annotation*
 -keep class okhttp3.** { *; }
 -keep interface okhttp3.** { *; }
 -dontwarn okhttp3.** 
 -keep class sun.misc.Unsafe { *; }
 -dontwarn java.nio.file.*
 -dontwarn org.codehaus.mojo.animal_sniffer.IgnoreJRERequirement 

Gson

 -keep class sun.misc.Unsafe { *; }
 -keep class com.google.gson.stream.** { *; }

Code obfuscation

-keepclassmembers class com.yourname.models** { <fields>; }

How to get the filename without the extension from a path in Python?

If you want to keep the path to the file and just remove the extension

>>> file = '/root/dir/sub.exten/file.data.1.2.dat'
>>> print ('.').join(file.split('.')[:-1])
/root/dir/sub.exten/file.data.1.2

How do I format a Microsoft JSON date?

I get the date like this:

"/Date(1276290000000+0300)/"

In some examples the date is in slightly different formats:

"/Date(12762900000000300)/"
"Date(1276290000000-0300)"

etc.

So I came up with the following RegExp:

/\/+Date\(([\d+]+)\)\/+/

and the final code is:

var myDate = new Date(parseInt(jsonWcfDate.replace(/\/+Date\(([\d+-]+)\)\/+/, '$1')));

Hope it helps.

Update: I found this link from Microsoft: How do I Serialize Dates with JSON?

This seems like the one we are all looking for.

A SQL Query to select a string between two known strings

Try this and replace '[' & ']' with your string

SELECT SUBSTRING(@TEXT,CHARINDEX('[',@TEXT)+1,(CHARINDEX(']',@TEXT)-CHARINDEX('[',@TEXT))-1)

HTML5 Canvas Resize (Downscale) Image High Quality?

Here is a reusable Angular service for high quality image / canvas resizing: https://gist.github.com/fisch0920/37bac5e741eaec60e983

The service supports lanczos convolution and step-wise downscaling. The convolution approach is higher quality at the cost of being slower, whereas the step-wise downscaling approach produces reasonably antialiased results and is significantly faster.

Example usage:

angular.module('demo').controller('ExampleCtrl', function (imageService) {
  // EXAMPLE USAGE
  // NOTE: it's bad practice to access the DOM inside a controller, 
  // but this is just to show the example usage.

  // resize by lanczos-sinc filter
  imageService.resize($('#myimg')[0], 256, 256)
    .then(function (resizedImage) {
      // do something with resized image
    })

  // resize by stepping down image size in increments of 2x
  imageService.resizeStep($('#myimg')[0], 256, 256)
    .then(function (resizedImage) {
      // do something with resized image
    })
})

how to run or install a *.jar file in windows?

To run usually click and it should run, that is if you have java installed. If not get java from here Sorry thought it was more general open a command prompt and type java -jar jbpm-installer-3.2.7.jar

What is the C# version of VB.net's InputDialog?

Add a reference to Microsoft.VisualBasic, InputBox is in the Microsoft.VisualBasic.Interaction namespace:

using Microsoft.VisualBasic;
string input = Interaction.InputBox("Prompt", "Title", "Default", x_coordinate, y_coordinate);

Only the first argument for prompt is mandatory

How to set UITextField height?

If you're creating a lot of UITextFields it can be quicker to subclass UITextViews and override the setFrame method with

-(void)setFrame:(CGRect)frame{
    [self setBorderStyle:UITextBorderStyleRoundedRect];
    [super setFrame:frame];
    [self setBorderStyle:UITextBorderStyleNone];
}  

This way you can just call
[customTextField setFrame:<rect>];

Inline CSS styles in React: how to implement a:hover?

Adding on to Jonathan's answer, here are the events to cover the focus and active states, and a using onMouseOver instead of onMouseEnter since the latter will not bubble if you have any child elements within the target the event is being applied to.

var Link = React.createClass({

  getInitialState: function(){
    return {hover: false, active: false, focus: false}
  },

  toggleHover: function(){
    this.setState({hover: !this.state.hover})
  },

  toggleActive: function(){
    this.setState({active: !this.state.active})
  },

  toggleFocus: function(){
    this.setState({focus: !this.state.focus})
  },

  render: function() {
    var linkStyle;
    if (this.state.hover) {
      linkStyle = {backgroundColor: 'red'}
    } else if (this.state.active) {
      linkStyle = {backgroundColor: 'blue'}
    } else if (this.state.focus) {
      linkStyle = {backgroundColor: 'purple'}
    } 

    return(
      <div>
        <a style={linkStyle} 
          onMouseOver={this.toggleHover} 
          onMouseOut={this.toggleHover} 
          onMouseUp={this.toggleActive} 
          onMouseDown={this.toggleActive} 
          onFocus={this.toggleFocus}> 
          Link 
        </a>
      </div>
    )
  }

Convert double to BigDecimal and set BigDecimal Precision

BigDecimal b = new BigDecimal(c).setScale(2,BigDecimal.ROUND_HALF_UP);

How to add style from code behind?

You can use the CssClass property of the hyperlink:

LiteralControl ltr = new LiteralControl();
        ltr.Text = "<style type=\"text/css\" rel=\"stylesheet\">" +
                    @".d
                    {
                        background-color:Red;
                    }
                    .d:hover
                    {
                        background-color:Yellow;
                    }
                    </style>
                    ";
        this.Page.Header.Controls.Add(ltr);
        this.HyperLink1.CssClass = "d";

how to detect search engine bots with php?

Check the $_SERVER['HTTP_USER_AGENT'] for some of the strings listed here:

http://www.useragentstring.com/pages/useragentstring.php

Or more specifically for crawlers:

http://www.useragentstring.com/pages/useragentstring.php?typ=Crawler

If you want to -say- log the number of visits of most common search engine crawlers, you could use

$interestingCrawlers = array( 'google', 'yahoo' );
$pattern = '/(' . implode('|', $interestingCrawlers) .')/';
$matches = array();
$numMatches = preg_match($pattern, strtolower($_SERVER['HTTP_USER_AGENT']), $matches, 'i');
if($numMatches > 0) // Found a match
{
  // $matches[1] contains an array of all text matches to either 'google' or 'yahoo'
}

How to split a large text file into smaller files with equal number of lines?

you can also use awk

awk -vc=1 'NR%200000==0{++c}{print $0 > c".txt"}' largefile

Android ClassNotFoundException: Didn't find class on path

This following method worked for me

  • Right click on your project and select properties
  • The "Properties for " panel will open. From the menu on the left go to Java Build Path -> Order and Export
  • From the list below uncheck the box next to "Android Dependencies"
  • Finally clean your project and run

Difference between an API and SDK

How about... It's like if you wanted to install a home theatre system in your house. Using an API is like getting all the wires, screws, bits, and pieces. The possibilities are endless (constrained only by the pieces you receive), but sometimes overwhelming. An SDK is like getting a kit. You still have to put it together, but it's more like getting pre-cut pieces and instructions for an IKEA bookshelf than a box of screws.

How to solve a timeout error in Laravel 5

try

ini_set('max_execution_time', $time);
$articles = Article::all();

where $time is in seconds, set it to 0 for no time. make sure to make it 60 back after your function finish

take(1) vs first()

It seems that in RxJS 5.2.0 the .first() operator has a bug,

Because of that bug .take(1) and .first() can behave quite different if you are using them with switchMap:

With take(1) you will get behavior as expected:

var x = Rx.Observable.interval(1000)
   .do( x=> console.log("One"))
   .take(1)
   .switchMap(x => Rx.Observable.interval(1000))
   .do( x=> console.log("Two"))
   .subscribe((x) => {})

// In the console you will see:
// One
// Two
// Two
// Two
// Two
// etc...

But with .first() you will get wrong behavior:

var x = Rx.Observable.interval(1000)
  .do( x=> console.log("One"))
  .first()
  .switchMap(x => Rx.Observable.interval(1000))
  .do( x=> console.log("Two"))
  .subscribe((x) => {})

// In console you will see:
// One
// One
// Two
// One
// Two
// One
// etc... 

Here's a link to codepen

How to create temp table using Create statement in SQL Server?

A temporary table can have 3 kinds, the # is the most used. This is a temp table that only exists in the current session. An equivalent of this is @, a declared table variable. This has a little less "functions" (like indexes etc) and is also only used for the current session. The ## is one that is the same as the #, however, the scope is wider, so you can use it within the same session, within other stored procedures.

You can create a temp table in various ways:

declare @table table (id int)
create table #table (id int)
create table ##table (id int)
select * into #table from xyz

Is it possible to start a shell session in a running container (without ssh)

Here's my solution

In the Dockerfile:

# ...
RUN mkdir -p /opt
ADD initd.sh /opt/
RUN chmod +x /opt/initd.sh
ENTRYPOINT ["/opt/initd.sh"]

In the initd.sh file

#!/bin/bash
...
/etc/init.d/gearman-job-server start
/etc/init.d/supervisor start
#very important!!!
/bin/bash

After image is built you have two options using exec or attach:

  1. Use exec (preferred) and run:

    docker run --name $CONTAINER_NAME -dt $IMAGE_NAME
    

    then

    docker exec -it $CONTAINER_NAME /bin/bash
    

    and use CTRL + D to detach

  2. Use attach and run:

    docker run --name $CONTAINER_NAME -dit $IMAGE_NAME
    

    then

    docker attach $CONTAINER_NAME
    

    and use CTRL + P and CTRL + Q to detach

    Note: The difference between options is in parameter -i

How do I define and use an ENUM in Objective-C?

Your typedef needs to be in the header file (or some other file that's #imported into your header), because otherwise the compiler won't know what size to make the PlayerState ivar. Other than that, it looks ok to me.

Range with step of type float

When you add floating point numbers together, there's often a little bit of error. Would a range(0.0, 2.2, 1.1) return [0.0, 1.1] or [0.0, 1.1, 2.199999999]? There's no way to be certain without rigorous analysis.

The code you posted is an OK work-around if you really need this. Just be aware of the possible shortcomings.

How to print the current Stack Trace in .NET without any exception?

There are two ways to do this. The System.Diagnostics.StackTrace() will give you a stack trace for the current thread. If you have a reference to a Thread instance, you can get the stack trace for that via the overloaded version of StackTrace().

You may also want to check out Stack Overflow question How to get non-current thread's stacktrace?.

Python script to copy text to clipboard

Use Tkinter:

https://stackoverflow.com/a/4203897/2804197

try:
    from Tkinter import Tk
except ImportError:
    from tkinter import Tk
r = Tk()
r.withdraw()
r.clipboard_clear()
r.clipboard_append('i can has clipboardz?')
r.update() # now it stays on the clipboard after the window is closed
r.destroy()

(Original author: https://stackoverflow.com/users/449571/atomizer)

Change MySQL default character set to UTF-8 in my.cnf?

This question already has a lot of answers, but Mathias Bynens mentioned that 'utf8mb4' should be used instead of 'utf8' in order to have better UTF-8 support ('utf8' does not support 4 byte characters, fields are truncated on insert). I consider this to be an important difference. So here is yet another answer on how to set the default character set and collation. One that'll allow you to insert a pile of poo ().

This works on MySQL 5.5.35.

Note, that some of the settings may be optional. As I'm not entirely sure that I haven't forgotten anything, I'll make this answer a community wiki.

Old Settings

mysql> SHOW VARIABLES LIKE 'char%'; SHOW VARIABLES LIKE 'collation%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8                       |
| character_set_connection | utf8                       |
| character_set_database   | latin1                     |
| character_set_filesystem | binary                     |
| character_set_results    | utf8                       |
| character_set_server     | latin1                     |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

+----------------------+-------------------+
| Variable_name        | Value             |
+----------------------+-------------------+
| collation_connection | utf8_general_ci   |
| collation_database   | latin1_swedish_ci |
| collation_server     | latin1_swedish_ci |
+----------------------+-------------------+
3 rows in set (0.00 sec)

Config

#  
# UTF-8 should be used instead of Latin1. Obviously.
# NOTE "utf8" in MySQL is NOT full UTF-8: http://mathiasbynens.be/notes/mysql-utf8mb4

[client]
default-character-set = utf8mb4

[mysqld]
character-set-server = utf8mb4
collation-server = utf8mb4_unicode_ci

[mysql]
default-character-set = utf8mb4

New Settings

mysql> SHOW VARIABLES LIKE 'char%'; SHOW VARIABLES LIKE 'collation%';
+--------------------------+----------------------------+
| Variable_name            | Value                      |
+--------------------------+----------------------------+
| character_set_client     | utf8mb4                    |
| character_set_connection | utf8mb4                    |
| character_set_database   | utf8mb4                    |
| character_set_filesystem | binary                     |
| character_set_results    | utf8mb4                    |
| character_set_server     | utf8mb4                    |
| character_set_system     | utf8                       |
| character_sets_dir       | /usr/share/mysql/charsets/ |
+--------------------------+----------------------------+
8 rows in set (0.00 sec)

+----------------------+--------------------+
| Variable_name        | Value              |
+----------------------+--------------------+
| collation_connection | utf8mb4_general_ci |
| collation_database   | utf8mb4_unicode_ci |
| collation_server     | utf8mb4_unicode_ci |
+----------------------+--------------------+
3 rows in set (0.00 sec)

character_set_system is always utf8.

This won't affect existing tables, it's just the default setting (used for new tables). The following ALTER code can be used to convert an existing table (without the dump-restore workaround):

ALTER DATABASE databasename CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;

Edit:

On a MySQL 5.0 server: character_set_client, character_set_connection, character_set_results, collation_connection remain at latin1. Issuing SET NAMES utf8 (utf8mb4 not available in that version) sets those to utf8 as well.


Caveat: If you had a utf8 table with an index column of type VARCHAR(255), it can't be converted in some cases, because the maximum key length is exceeded (Specified key was too long; max key length is 767 bytes.). If possible, reduce the column size from 255 to 191 (because 191 * 4 = 764 < 767 < 192 * 4 = 768). After that, the table can be converted.

Disable back button in android

You can override the onBackPressed() method in your activity and remove the call to super class.

@Override
public void onBackPressed() {
  //remove call to the super class
  //super.onBackPressed();
}

How to get the number of days of difference between two dates on mysql?

Get days between Current date to destination Date

 SELECT DATEDIFF('2019-04-12', CURDATE()) AS days;

output

days

 335

How to use moment.js library in angular 2 typescript app?

I followed advice to allow allowSyntheticDefaultImports (since there is no export from moment to use for me), using System. Then I followed someone's advice to use:

import moment from 'moment';

With moment being mapped in my system.js config. The other import statements wouldn't work for me, for some reason

What's the difference between an element and a node in XML?

Element is the only kind of node that can have child nodes and attributes.

Document also has child nodes, BUT
no attributes, no text, exactly one child element.

Run/install/debug Android applications over Wi-Fi?

That is too much simple...

Step 1:

connect mobile to laptop (PC)
find adb path in Eclipse or Go Tast manager (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>Esc</kbd>) -> process -> adb.exe -> right-click -> open file location -> copy the path of the open window (like D:\.....)

Step 2:

open cmd and change directory like C:, D:, E:, and G:
 1: C:\Users\UMT>D:
 2: D:\> cd (past path of adb) like (ANDROID eclipse\Eclipse Setup\adt-bundle-windows-x86_64-202\sdk\plat-form-tools) and press enter
 3: Then type `adb tcpip 5555`. Press <kbd>Enter</kbd> ... make sure your mobile connects to the PC

Step 3:

Open new cmd and same above, go to the adb directory and type
adb connect 192.168.x.x(device ip):5555
press enter now connect it.

Device IP address: Setting -> About phone -> Status -> IP address

How to open every file in a folder

you should try using os.walk

yourpath = 'path'

import os
for root, dirs, files in os.walk(yourpath, topdown=False):
    for name in files:
        print(os.path.join(root, name))
        stuff
    for name in dirs:
        print(os.path.join(root, name))
        stuff

Moment JS start and end of given month

Try the following code:

moment(startDate).startOf('months')
moment(startDate).endOf('months')

changing visibility using javascript

function loadpage (page_request, containerid)
{
  var loading = document.getElementById ( "loading" ) ;

  // when connecting to server
  if ( page_request.readyState == 1 )
      loading.style.visibility = "visible" ;

  // when loaded successfully
  if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
  {
      document.getElementById(containerid).innerHTML=page_request.responseText ;
      loading.style.visibility = "hidden" ;
  }
}

"column not allowed here" error in INSERT statement

What you missed is " " in postcode because it is a varchar.

There are two ways of inserting.

When you created a table Table created. and you add a row just after creating it, you can use the following method.

INSERT INTO table_name
VALUES (value1,value2,value3,...);

1 row created.

You've added so many tables, or it is saved and you are reopening it, you need to mention the table's column name too or else it will display the same error.

ERROR at line 2:
ORA-00984: column not allowed here


INSERT INTO table_name (column1,column2,column3,...)
VALUES (value1,value2,value3,...);

1 row created.

How do you detect where two line segments intersect?

Many answers have wrapped up all the calculations into a single function. If you need to calculate the line slopes, y-intercepts, or x-intercepts for use elsewhere in your code, you'll be making those calculations redundantly. I have separated out the respective functions, used obvious variable names, and commented my code to make it easier to follow. I needed to know if lines intersect infinitely beyond their endpoints, so in JavaScript:

http://jsfiddle.net/skibulk/evmqq00u/

var point_a = {x:0, y:10},
    point_b = {x:12, y:12},
    point_c = {x:10, y:0},
    point_d = {x:0, y:0},
    slope_ab = slope(point_a, point_b),
    slope_bc = slope(point_b, point_c),
    slope_cd = slope(point_c, point_d),
    slope_da = slope(point_d, point_a),
    yint_ab = y_intercept(point_a, slope_ab),
    yint_bc = y_intercept(point_b, slope_bc),
    yint_cd = y_intercept(point_c, slope_cd),
    yint_da = y_intercept(point_d, slope_da),
    xint_ab = x_intercept(point_a, slope_ab, yint_ab),
    xint_bc = x_intercept(point_b, slope_bc, yint_bc),
    xint_cd = x_intercept(point_c, slope_cd, yint_cd),
    xint_da = x_intercept(point_d, slope_da, yint_da),
    point_aa = intersect(slope_da, yint_da, xint_da, slope_ab, yint_ab, xint_ab),
    point_bb = intersect(slope_ab, yint_ab, xint_ab, slope_bc, yint_bc, xint_bc),
    point_cc = intersect(slope_bc, yint_bc, xint_bc, slope_cd, yint_cd, xint_cd),
    point_dd = intersect(slope_cd, yint_cd, xint_cd, slope_da, yint_da, xint_da);

console.log(point_a, point_b, point_c, point_d);
console.log(slope_ab, slope_bc, slope_cd, slope_da);
console.log(yint_ab, yint_bc, yint_cd, yint_da);
console.log(xint_ab, xint_bc, xint_cd, xint_da);
console.log(point_aa, point_bb, point_cc, point_dd);

function slope(point_a, point_b) {
  var i = (point_b.y - point_a.y) / (point_b.x - point_a.x);
  if (i === -Infinity) return Infinity;
  if (i === -0) return 0;
  return i;
}

function y_intercept(point, slope) {
    // Horizontal Line
    if (slope == 0) return point.y;
  // Vertical Line
    if (slope == Infinity)
  {
    // THE Y-Axis
    if (point.x == 0) return Infinity;
    // No Intercept
    return null;
  }
  // Angled Line
  return point.y - (slope * point.x);
}

function x_intercept(point, slope, yint) {
    // Vertical Line
    if (slope == Infinity) return point.x;
  // Horizontal Line
    if (slope == 0)
  {
    // THE X-Axis
    if (point.y == 0) return Infinity;
    // No Intercept
    return null;
  }
  // Angled Line
  return -yint / slope;
}

// Intersection of two infinite lines
function intersect(slope_a, yint_a, xint_a, slope_b, yint_b, xint_b) {
  if (slope_a == slope_b)
  {
    // Equal Lines
    if (yint_a == yint_b && xint_a == xint_b) return Infinity;
    // Parallel Lines
    return null;
  }
  // First Line Vertical
    if (slope_a == Infinity)
  {
    return {
        x: xint_a,
      y: (slope_b * xint_a) + yint_b
    };
  }
  // Second Line Vertical
    if (slope_b == Infinity)
  {
    return {
        x: xint_b,
      y: (slope_a * xint_b) + yint_a
    };
  }
  // Not Equal, Not Parallel, Not Vertical
  var i = (yint_b - yint_a) / (slope_a - slope_b);
  return {
    x: i,
    y: (slope_a * i) + yint_a
  };
}

Adding days to $Date in PHP

Here is the simplest solution to your query

$date=date_create("2013-03-15"); // or your date string
date_add($date,date_interval_create_from_date_string("40 days"));// add number of days 
echo date_format($date,"Y-m-d"); //set date format of the result

Google OAUTH: The redirect URI in the request did not match a registered redirect URI

You need to go into the developer console and set

http://localhost:8080/WEBAPP/youtube-callback.html

as your callback URL.

This video is slightly outdated, as it shows the older Developer Console instead of the new one, however, the concepts should still apply. You need to find your project in the developer console and register a callback URL.

What is System, out, println in System.out.println() in Java

System is a final class from the java.lang package.

out is a class variable of type PrintStream declared in the System class.

println is a method of the PrintStream class.

ArrayBuffer to base64 encoded string

function _arrayBufferToBase64(uarr) {
    var strings = [], chunksize = 0xffff;
    var len = uarr.length;

    for (var i = 0; i * chunksize < len; i++){
        strings.push(String.fromCharCode.apply(null, uarr.subarray(i * chunksize, (i + 1) * chunksize)));
    }

    return strings.join("");
}

This is better, if you use JSZip for unpack archive from string

react-router scroll to top on every transition

This answer is for legacy code, for router v4+ check other answers

<Router onUpdate={() => window.scrollTo(0, 0)} history={createBrowserHistory()}>
  ...
</Router>

If it's not working, you should find the reason. Also inside componentDidMount

document.body.scrollTop = 0;
// or
window.scrollTo(0,0);

you could use:

componentDidUpdate() {
  window.scrollTo(0,0);
}

you could add some flag like "scrolled = false" and then in update:

componentDidUpdate() {
  if(this.scrolled === false){
    window.scrollTo(0,0);
    scrolled = true;
  }
}

Remove title in Toolbar in appcompat-v7

if your using default toolbar then you can add this line of code

Objects.requireNonNull(getSupportActionBar()).setDisplayShowTitleEnabled(false);

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

How to select a div element in the code-behind page?

id + runat="server" leads to accessible at the server

Where can I find the .apk file on my device, when I download any app and install?

There is an app in google play known as MyAppSharer. Open the app, search for the app that you have installed, check apk and select share. The app would take some time and build the apk. You can then close the app. The apk of the file is located in /sdcard/MyAppSharer

This does not require rooting your phone and works only for apps that are currently installed on your phone

Is Secure.ANDROID_ID unique for each device?

//Fields
String myID;
int myversion = 0;


myversion = Integer.valueOf(android.os.Build.VERSION.SDK);
if (myversion < 23) {
        TelephonyManager mngr = (TelephonyManager) 
getSystemService(Context.TELEPHONY_SERVICE);
        myID= mngr.getDeviceId();
    }
    else
    {
        myID = 
Settings.Secure.getString(getApplicationContext().getContentResolver(), 
Settings.Secure.ANDROID_ID);
    }

Yes, Secure.ANDROID_ID is unique for each device.

How are ssl certificates verified?

I KNOW THE BELOW IS LONG, BUT IT IS DETAILED, YET SIMPLIFIED ENOUGH. READ CAREFULLY AND I GUARANTEE YOU'LL START FINDING THIS TOPIC IS NOT ALL THAT COMPLICATED.

First of all, anyone can create 2 keys. One to encrypt data, and another to decrypt data. The former can be a private key, and the latter a public key, AND VICERZA.

Second of all, in simplest terms, a Certificate Authority (CA) offers the service of creating a certificate for you. How? They use certain values (the CA's issuer name, your server's public key, company name, domain, etc.) and they use their SUPER DUPER ULTRA SECURE SECRET private key and encrypt this data. The result of this encrypted data is a SIGNATURE.

So now the CA gives you back a certificate. The certificate is basically a file containing the values previously mentioned (CA's issuer name, company name, domain, your server's public key, etc.), INCLUDING the signature (i.e. an encrypted version of the latter values).

Now, with all that being said, here is a REALLY IMPORTANT part to remember: your device/OS (Windows, Android, etc.) pretty much keeps a list of all major/trusted CA's and their PUBLIC KEYS (if you're thinking that these public keys are used to decrypt the signatures inside the certificates, YOU ARE CORRECT!).

Ok, if you read the above, this sequential example will be a breeze now:

  1. Example-Company asks Example-CA to create for them a certificate.
  2. Example-CA uses their super private key to sign this certificate and gives Example-Company the certificate.
  3. Tomorrow, internet-user-Bob uses Chrome/Firefox/etc. to browse to https://example-company.com. Most, if not all, browsers nowadays will expect a certificate back from the server.
  4. The browser gets the certificate from example-company.com. The certificate says it's been issued by Example-CA. It just so happens to be that Bob's OS already has Example-CA in its list of trusted CA's, so the browser gets Example-CA's public key. Remember: this is all happening in Bob's computer/mobile/etc., not over the wire.
  5. So now the browser decrypts the signature in the certificate. FINALLY, the browser compares the decrypted values with the contents of the certificate itself. IF THE CONTENTS MATCH, THAT MEANS THE SIGNATURE IS VALID!

Why? Think about it, only this public key can decrypt the signature in such a way that the contents look like they did before the private key encrypted them.

How about man in the middle attacks?

This is one of the main reasons (if not the main reason) why the above standard was created.

Let's say hacker-Jane intercepts internet-user-Bob's request, and replies with her own certificate. However, hacker-Jane is still careful enough to state in the certificate that the issuer was Example-CA. Lastly, hacker-Jane remembers that she has to include a signature on the certificate. But what key does Jane use to sign (i.e. create an encrypted value of the certificate main contents) the certificate?????

So even if hacker-Jane signed the certificate with her own key, you see what's gonna happen next. The browser is gonna say: "ok, this certificate is issued by Example-CA, let's decrypt the signature with Example-CA's public key". After decryption, the browser notices that the certificate contents don't match at all. Hence, the browser gives a very clear warning to the user, and it says it doesn't trust the connection.

Disable keyboard on EditText

try: android:editable="false" or android:inputType="none"

What are the differences between WCF and ASMX web services?

There's a lot of talks going on regarding the simplicity of asmx web services over WCF. Let me clarify few points here.

  • Its true that novice web service developers will get started easily in asmx web services. Visual Studio does all the work for them and readily creates a Hello World project.
  • But if you can learn WCF (which off course wont take much time) then you can get to see that WCF is also quite simple, and you can go ahead easily.
  • Its important to remember that these said complexities in WCF are actually attributed to the beautiful features that it brings along with it. There are addressing, bindings, contracts and endpoints, services & clients all mentioned in the config file. The beauty is your business logic is segregated and maintained safely. Tomorrow if you need to change the binding from basicHttpBinding to netTcpBinding you can easily create a binding in config file and use it. So all the changes related to clients, communication channels, bindings etc are to be done in the configuration leaving the business logic safe & intact, which makes real good sense.
  • WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
  • Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. You can host your WCF services in Console, Windows Services, IIS & WAS, which are again different ways of creating new projects in Visual Studio.
  • ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
  • You will always like to use Visual Studio for NET 4.0 or 4.5 as it makes life easy while creating WCF services.
  • The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer. That's why WCF performs way better than other communication technology counterparts from .NET like asmx, .NET remoting etc.

Not to forget that I was one of those guys who liked asmx services more than WCF, but that time I was not well aware of WCF services and its capabilities. I was scared of the WCF configurations. But I dared and and tried writing few WCF services of my own, and when I learnt more of WCF, now I have no inhibitions about WCF and I recommend them to anyone & everyone. Happy coding!!!

Bootstrap - How to add a logo to navbar class?

I would suggest you to use either an image or text. So, Remove the text and add it in your image(using Photoshop, maybe). Then, Use a width and height 100% for the image. it will do the trick. because the image can be resized based on the container. But, you have to manually resize the text. If you can provide the fiddle, I can help you achieve this.

Angular: Can't find Promise, Map, Set and Iterator

I noticed these problems showing up after upgrading from Angular 5 to Angular 6. I was able to fix this by doing the following in VS2017:

  • Ensure the TypeScript SDK was installed (via the Visual Studio Installer) for my particular version of TypeScript, 2.9
  • Ensure that the Module System project property is set to match that in my tsconfig.json: ES2015. This is often automatically in sync if the tsconfig file is in the root of the project. However, since I was using the VS Angular template, it places these files in a "ClientApp" subfolder, and the Module System project property was not set.

VS2017 Project Properties

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es5",
    "lib": [
      "es2017",
      "dom"
    ],
    "module": "es2015",
    "baseUrl": "./"
  }
}

How to stop a vb script running in windows

Create a Name.bat file that has the following line in it.

taskkill /F /IM wscript.exe /T

Be sure not to overpower your processor. If you're running long scripts, your processor speed changes and script lines will override each other.

Run Android studio emulator on AMD processor

I have a Ryzen 2600X and I am able to run the emulator without problems. Here are the tweaks I made:

*NOTE: You don't need the beta version of Android Studio or Android Emulator.

  1. Go to the MB bios and turn SVM on (CPU Virtualization).
  2. In Windows right click Windows Button => Select "Apps and Features" => "Programs and features" => "Turn Windows Features on and off"
  3. In the displayed list select Hyper-V checkbox == Make sure the subfolders are all selected. When prompted to restart, restart the PC.
  4. After restart and update instalation screen you are back in Windows and you should be able to run the Emulator.

**Note: I have selected x86_64 and plain x86 images(both API 28) from the x86 Images tab and they work just fine.

***Note: Might also check for Android Licenses if errors pop up, I had an issue because of this while using Flutter, maybe it's related to that.

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

In case of Mac OSX,

Go to Targets -> Build Phases click + to Copy new files build phases Select product directory and drop the file there.

Clean and run the project.

Detecting installed programs via registry

Win32_Product never shows everything, only software installed via an MSI installer (as far as I can tell.)

There are lots of software packages that get installed via other installers that don't show up in there. another way is needed.

How can I run a html file from terminal?

Skip reading the html and use curl to POST whatever form data you want to submit to the server.

Using "like" wildcard in prepared statement

String fname = "Sam\u0025";

PreparedStatement ps= conn.prepareStatement("SELECT * FROM Users WHERE User_FirstName LIKE ? ");

ps.setString(1, fname);

Using variable in SQL LIKE statement

DECLARE @SearchLetter2 char(1)

Set this to a longer char.

Java 8 stream reverse order

Many of the solutions here sort or reverse the IntStream, but that unnecessarily requires intermediate storage. Stuart Marks's solution is the way to go:

static IntStream revRange(int from, int to) {
    return IntStream.range(from, to).map(i -> to - i + from - 1);
}

It correctly handles overflow as well, passing this test:

@Test
public void testRevRange() {
    assertArrayEquals(revRange(0, 5).toArray(), new int[]{4, 3, 2, 1, 0});
    assertArrayEquals(revRange(-5, 0).toArray(), new int[]{-1, -2, -3, -4, -5});
    assertArrayEquals(revRange(1, 4).toArray(), new int[]{3, 2, 1});
    assertArrayEquals(revRange(0, 0).toArray(), new int[0]);
    assertArrayEquals(revRange(0, -1).toArray(), new int[0]);
    assertArrayEquals(revRange(MIN_VALUE, MIN_VALUE).toArray(), new int[0]);
    assertArrayEquals(revRange(MAX_VALUE, MAX_VALUE).toArray(), new int[0]);
    assertArrayEquals(revRange(MIN_VALUE, MIN_VALUE + 1).toArray(), new int[]{MIN_VALUE});
    assertArrayEquals(revRange(MAX_VALUE - 1, MAX_VALUE).toArray(), new int[]{MAX_VALUE - 1});
}

Difference in Months between two dates in JavaScript

If you need to count full months, regardless of the month being 28, 29, 30 or 31 days. Below should work.

var months = to.getMonth() - from.getMonth() 
    + (12 * (to.getFullYear() - from.getFullYear()));

if(to.getDate() < from.getDate()){
    months--;
}
return months;

This is an extended version of the answer https://stackoverflow.com/a/4312956/1987208 but fixes the case where it calculates 1 month for the case from 31st of January to 1st of February (1day).

This will cover the following;

  • 1st Jan to 31st Jan ---> 30days ---> will result in 0 (logical since it is not a full month)
  • 1st Feb to 1st Mar ---> 28 or 29 days ---> will result in 1 (logical since it is a full month)
  • 15th Feb to 15th Mar ---> 28 or 29 days ---> will result in 1 (logical since a month passed)
  • 31st Jan to 1st Feb ---> 1 day ---> will result in 0 (obvious but the mentioned answer in the post results in 1 month)

How to focus on a form input text field on page load using jQuery?

HTML:

  <input id="search" size="10" />

jQuery:

$("#search").focus();

iOS Safari – How to disable overscroll but allow scrollable divs to scroll normally?

this one works for me (plain javascript)

var fixScroll = function (className, border) {  // className = class of scrollElement(s), border: borderTop + borderBottom, due to offsetHeight
var reg = new RegExp(className,"i"); var off = +border + 1;
function _testClass(e) { var o = e.target; while (!reg.test(o.className)) if (!o || o==document) return false; else o = o.parentNode; return o;}
document.ontouchmove  = function(e) { var o = _testClass(e); if (o) { e.stopPropagation(); if (o.scrollTop == 0) { o.scrollTop += 1; e.preventDefault();}}}
document.ontouchstart = function(e) { var o = _testClass(e); if (o && o.scrollHeight >= o.scrollTop + o.offsetHeight - off) o.scrollTop -= off;}
}

fixScroll("fixscroll",2); // assuming I have a 1px border in my DIV

html:

<div class="fixscroll" style="border:1px gray solid">content</div>

Java HttpRequest JSON & Response Handling

The simplest way is using libraries like google-http-java-client but if you want parse the JSON response by yourself you can do that in a multiple ways, you can use org.json, json-simple, Gson, minimal-json, jackson-mapper-asl (from 1.x)... etc

A set of simple examples:

Using Gson:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

public class Gson {

    public static void main(String[] args) {
    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);
            String json = EntityUtils.toString(result.getEntity(), "UTF-8");

            com.google.gson.Gson gson = new com.google.gson.Gson();
            Response respuesta = gson.fromJson(json, Response.class);

            System.out.println(respuesta.getExample());
            System.out.println(respuesta.getFr());

        } catch (IOException ex) {
        }
        return null;
    }

    public class Response{

        private String example;
        private String fr;

        public String getExample() {
            return example;
        }
        public void setExample(String example) {
            this.example = example;
        }
        public String getFr() {
            return fr;
        }
        public void setFr(String fr) {
            this.fr = fr;
        }
    }
}

Using json-simple:

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

public class JsonSimple {

    public static void main(String[] args) {

    }

    public HttpResponse http(String url, String body) {

        try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {
            HttpPost request = new HttpPost(url);
            StringEntity params = new StringEntity(body);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
            HttpResponse result = httpClient.execute(request);

            String json = EntityUtils.toString(result.getEntity(), "UTF-8");
            try {
                JSONParser parser = new JSONParser();
                Object resultObject = parser.parse(json);

                if (resultObject instanceof JSONArray) {
                    JSONArray array=(JSONArray)resultObject;
                    for (Object object : array) {
                        JSONObject obj =(JSONObject)object;
                        System.out.println(obj.get("example"));
                        System.out.println(obj.get("fr"));
                    }

                }else if (resultObject instanceof JSONObject) {
                    JSONObject obj =(JSONObject)resultObject;
                    System.out.println(obj.get("example"));
                    System.out.println(obj.get("fr"));
                }

            } catch (Exception e) {
                // TODO: handle exception
            }

        } catch (IOException ex) {
        }
        return null;
    }
}

etc...

Custom UITableViewCell from nib in Swift

For fix the "Overriding method... has incompatible type..." error I've changed the function declaration to

override func tableView(tableView: (UITableView!), 
                        cellForRowAtIndexPath indexPath: (NSIndexPath!)) 
    -> UITableViewCell {...}

(was -> UITableViewCell! -- with exclamation mark at the end)

How do I sort a vector of pairs based on the second element of the pair?

You can use boost like this:

std::sort(a.begin(), a.end(), 
          boost::bind(&std::pair<int, int>::second, _1) <
          boost::bind(&std::pair<int, int>::second, _2));

I don't know a standard way to do this equally short and concise, but you can grab boost::bind it's all consisting of headers.

Python loop counter in a for loop

Use enumerate() like so:

def draw_menu(options, selected_index):
    for counter, option in enumerate(options):
        if counter == selected_index:
            print " [*] %s" % option
        else:
            print " [ ] %s" % option    

options = ['Option 0', 'Option 1', 'Option 2', 'Option 3']
draw_menu(options, 2)

Note: You can optionally put parenthesis around counter, option, like (counter, option), if you want, but they're extraneous and not normally included.

How to place the ~/.composer/vendor/bin directory in your PATH?

my path didn't have /.composer, just /composer so my path was:-

export PATH="$PATH:$HOME/.config/composer/vendor/bin"

This worked for me on ubuntu 20.04

how to change color of TextinputLayout's label and edittext underline android

This Blog Post describes various styling aspects of EditText and AutoCompleteTextView wrapped by TextInputLayout.

For EditText and AppCompat lib 22.1.0+ you can set theme attribute with some theme related settings:

<style name="StyledTilEditTextTheme">
   <item name="android:imeOptions">actionNext</item>
   <item name="android:singleLine">true</item>
   <item name="colorControlNormal">@color/greyLight</item>
   <item name="colorControlActivated">@color/blue</item>
   <item name="android:textColorPrimary">@color/blue</item>
   <item name="android:textSize">@dimen/styledtil_edit_text_size</item>
</style>

<style name="StyledTilEditText">
    <item name="android:theme">@style/StyledTilEditTextTheme</item>
    <item name="android:paddingTop">4dp</item>
</style>

and apply them on EditText:

<EditText
    android:id="@+id/etEditText"
    style="@style/StyledTilEditText"

For AutoCompleteTextView things are more complicated because wrapping it in TextInputLayout and applying this theme breaks floating label behaviour. You need to fix this in code:

private void setStyleForTextForAutoComplete(int color) {
    Drawable wrappedDrawable =     DrawableCompat.wrap(autoCompleteTextView.getBackground());
    DrawableCompat.setTint(wrappedDrawable, color);
    autoCompleteTextView.setBackgroundDrawable(wrappedDrawable);
}

and in Activity.onCreate:

setStyleForTextForAutoComplete(getResources().getColor(R.color.greyLight));
autoCompleteTextView.setOnFocusChangeListener((v, hasFocus) -> {
    if(hasFocus) {
        setStyleForTextForAutoComplete(getResources().getColor(R.color.blue));
    } else {
        if(autoCompleteTextView.getText().length() == 0) {  
              setStyleForTextForAutoComplete(getResources().getColor(R.color.greyLight));
        }
    }
});

How to set a Postgresql default value datestamp like 'YYYYMM'?

Why would you want to do this?

IMHO you should store the date as default type and if needed fetch it transforming to desired format.

You could get away with specifying column's format but with a view. I don't know other methods.

Edited:

Seriously, in my opinion, you should create a view on that a table with date type. I'm talking about something like this:

create table sample_table ( id serial primary key, timestamp date); 

and than

create view v_example_table as select id, to_char(date, 'yyyymmmm');

And use v_example_table in your application.

Prevent text selection after double click

For those looking for a solution for Angular 2+.

You can use the mousedown output of the table cell.

<td *ngFor="..."
    (mousedown)="onMouseDown($event)"
    (dblclick) ="onDblClick($event)">
  ...
</td>

And prevent if the detail > 1.

public onMouseDown(mouseEvent: MouseEvent) {
  // prevent text selection for dbl clicks.
  if (mouseEvent.detail > 1) mouseEvent.preventDefault();
}

public onDblClick(mouseEvent: MouseEvent) {
 // todo: do what you really want to do ...
}

The dblclick output continues to work as expected.

How to dynamically change a web page's title?

The code is
document.title = 'test'

Get checkbox list values with jQuery

Try this one..

var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
     console.log($(this).val());
     listCheck .push($(this).val());
});
console.log(listCheck);

How to invert a grep expression

As stated multiple times, inversion is achieved by the -v option to grep. Let me add the (hopefully amusing) note that you could have figured this out yourself by grepping through the grep help text:

grep --help | grep invert

-v, --invert-match select non-matching lines

What is a difference between unsigned int and signed int in C?

ISO C states what the differences are.

The int data type is signed and has a minimum range of at least -32767 through 32767 inclusive. The actual values are given in limits.h as INT_MIN and INT_MAX respectively.

An unsigned int has a minimal range of 0 through 65535 inclusive with the actual maximum value being UINT_MAX from that same header file.

Beyond that, the standard does not mandate twos complement notation for encoding the values, that's just one of the possibilities. The three allowed types would have encodings of the following for 5 and -5 (using 16-bit data types):

        two's complement  |  ones' complement   |   sign/magnitude
    +---------------------+---------------------+---------------------+
 5  | 0000 0000 0000 0101 | 0000 0000 0000 0101 | 0000 0000 0000 0101 |
-5  | 1111 1111 1111 1011 | 1111 1111 1111 1010 | 1000 0000 0000 0101 |
    +---------------------+---------------------+---------------------+
  • In two's complement, you get a negative of a number by inverting all bits then adding 1.
  • In ones' complement, you get a negative of a number by inverting all bits.
  • In sign/magnitude, the top bit is the sign so you just invert that to get the negative.

Note that positive values have the same encoding for all representations, only the negative values are different.

Note further that, for unsigned values, you do not need to use one of the bits for a sign. That means you get more range on the positive side (at the cost of no negative encodings, of course).

And no, 5 and -5 cannot have the same encoding regardless of which representation you use. Otherwise, there'd be no way to tell the difference.


As an aside, there are currently moves underway, in both C and C++ standards, to nominate two's complement as the only encoding for negative integers.

CocoaPods Errors on Project Build

Had the same issue saying /Pods/Pods-resources.sh: No such file or directory even after files etc related to pods were removed.

Got rid of it by going to target->Build phases and then removing the build phase "Copy Pod Resources".

C# How can I check if a URL exists/is valid?

This solution seems easy to follow:

public static bool isValidURL(string url) {
    WebRequest webRequest = WebRequest.Create(url);
    WebResponse webResponse;
    try
    {
        webResponse = webRequest.GetResponse();
    }
    catch //If exception thrown then couldn't get response from address
    {
        return false ;
    }
    return true ;
}

Python Checking a string's first and last character

When you say [:-1] you are stripping the last element. Instead of slicing the string, you can apply startswith and endswith on the string object itself like this

if str1.startswith('"') and str1.endswith('"'):

So the whole program becomes like this

>>> str1 = '"xxx"'
>>> if str1.startswith('"') and str1.endswith('"'):
...     print "hi"
>>> else:
...     print "condition fails"
...
hi

Even simpler, with a conditional expression, like this

>>> print("hi" if str1.startswith('"') and str1.endswith('"') else "fails")
hi

MySQL select 10 random rows from 600K rows fast

Another simple solution would be ranking the rows and fetch one of them randomly and with this solution you won't need to have any 'Id' based column in the table.

SELECT d.* FROM (
SELECT  t.*,  @rownum := @rownum + 1 AS rank
FROM mytable AS t,
    (SELECT @rownum := 0) AS r,
    (SELECT @cnt := (SELECT RAND() * (SELECT COUNT(*) FROM mytable))) AS n
) d WHERE rank >= @cnt LIMIT 10;

You can change the limit value as per your need to access as many rows as you want but that would mostly be consecutive values.

However, if you don't want consecutive random values then you can fetch a bigger sample and select randomly from it. something like ...

SELECT * FROM (
SELECT d.* FROM (
    SELECT  c.*,  @rownum := @rownum + 1 AS rank
    FROM buildbrain.`commits` AS c,
        (SELECT @rownum := 0) AS r,
        (SELECT @cnt := (SELECT RAND() * (SELECT COUNT(*) FROM buildbrain.`commits`))) AS rnd
) d 
WHERE rank >= @cnt LIMIT 10000 
) t ORDER BY RAND() LIMIT 10;

How to use google maps without api key

source

In June 2016 Google announced that they would stop supporting keyless usage, meaning any request that doesn’t include an API key or Client ID. This will go into effect on June 11 2018, and keyless access will no longer be supported

Fatal error: Call to a member function prepare() on null

In ---- model: Add use Jenssegers\Mongodb\Eloquent\Model as Eloquent;

Change the class ----- extends Model to class ----- extends Eloquent

What is the difference/usage of homebrew, macports or other package installation tools?

By default, Homebrew installs packages to your /usr/local. Macport commands require sudo to install and upgrade (similar to apt-get in Ubuntu).

For more detail:

This site suggests using Hombrew: http://deephill.com/macports-vs-homebrew/

whereas this site lists the advantages of using Macports: http://arstechnica.com/civis/viewtopic.php?f=19&t=1207907

I also switched from Ubuntu recently, and I enjoy using homebrew (it's simple and easy to use!), but if you feel attached to using sudo, Macports might be the better way to go!

When is "java.io.IOException:Connection reset by peer" thrown?

For me useful code witch help me was http://rox-xmlrpc.sourceforge.net/niotut/src/NioServer.java

// The remote forcibly closed the connection, cancel

// the selection key and close the channel.

    private void read(SelectionKey key) throws IOException {
            SocketChannel socketChannel = (SocketChannel) key.channel();

            // Clear out our read buffer so it's ready for new data
            this.readBuffer.clear();

            // Attempt to read off the channel
            int numRead;
            try {
                numRead = socketChannel.read(this.readBuffer);
            } catch (IOException e) {
                // The remote forcibly closed the connection, cancel
                // the selection key and close the channel.
                key.cancel();
                socketChannel.close();
                return;
            }

            if (numRead == -1) {
                // Remote entity shut the socket down cleanly. Do the
                // same from our end and cancel the channel.
                key.channel().close();
                key.cancel();
                return;
            }
...

Implement division with bit-wise operator

All these solutions are too long. The base idea is to write the quotient (for example, 5=101) as 100 + 00 + 1 = 101.

public static Point divide(int a, int b) {

    if (a < b)
        return new Point(0,a);
    if (a == b)
        return new Point(1,0);
    int q = b;
    int c = 1;
    while (q<<1 < a) {
        q <<= 1;
        c <<= 1;
    }
    Point r = divide(a-q, b);
    return new Point(c + r.x, r.y);
}


public static class Point {
    int x;
    int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    public int compare(Point b) {
        if (b.x - x != 0) {
            return x - b.x;
        } else {
            return y - b.y;
        }
    }

    @Override
    public String toString() {
        return " (" + x + " " + y + ") ";
    }
}

Return multiple values to a method caller

There are several ways to do this. You can use ref parameters:

int Foo(ref Bar bar) { }

This passes a reference to the function thereby allowing the function to modify the object in the calling code's stack. While this is not technically a "returned" value it is a way to have a function do something similar. In the code above the function would return an int and (potentially) modify bar.

Another similar approach is to use an out parameter. An out parameter is identical to a ref parameter with an additional, compiler enforced rule. This rule is that if you pass an out parameter into a function, that function is required to set its value prior to returning. Besides that rule, an out parameter works just like a ref parameter.

The final approach (and the best in most cases) is to create a type that encapsulates both values and allow the function to return that:

class FooBar 
{
    public int i { get; set; }
    public Bar b { get; set; }
}

FooBar Foo(Bar bar) { }

This final approach is simpler and easier to read and understand.

Subtract two dates in Java

Edit 2018-05-28 I have changed the example to use Java 8's Time API:

LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();

How can I select the row with the highest ID in MySQL?

SELECT *
FROM permlog
WHERE id = ( SELECT MAX(id) FROM permlog ) ;

This would return all rows with highest id, in case id column is not constrained to be unique.

importing pyspark in python shell

For a Spark execution in pyspark two components are required to work together:

  • pyspark python package
  • Spark instance in a JVM

When launching things with spark-submit or pyspark, these scripts will take care of both, i.e. they set up your PYTHONPATH, PATH, etc, so that your script can find pyspark, and they also start the spark instance, configuring according to your params, e.g. --master X

Alternatively, it is possible to bypass these scripts and run your spark application directly in the python interpreter likepython myscript.py. This is especially interesting when spark scripts start to become more complex and eventually receive their own args.

  1. Ensure the pyspark package can be found by the Python interpreter. As already discussed either add the spark/python dir to PYTHONPATH or directly install pyspark using pip install.
  2. Set the parameters of spark instance from your script (those that used to be passed to pyspark).
    • For spark configurations as you'd normally set with --conf they are defined with a config object (or string configs) in SparkSession.builder.config
    • For main options (like --master, or --driver-mem) for the moment you can set them by writing to the PYSPARK_SUBMIT_ARGS environment variable. To make things cleaner and safer you can set it from within Python itself, and spark will read it when starting.
  3. Start the instance, which just requires you to call getOrCreate() from the builder object.

Your script can therefore have something like this:

from pyspark.sql import SparkSession

if __name__ == "__main__":
    if spark_main_opts:
        # Set main options, e.g. "--master local[4]"
        os.environ['PYSPARK_SUBMIT_ARGS'] = spark_main_opts + " pyspark-shell"

    # Set spark config
    spark = (SparkSession.builder
             .config("spark.checkpoint.compress", True)
             .config("spark.jars.packages", "graphframes:graphframes:0.5.0-spark2.1-s_2.11")
             .getOrCreate())

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

You module and class AthleteList have the same name. Change:

import AthleteList

to:

from AthleteList import AthleteList

This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList

Can I scale a div's height proportionally to its width using CSS?

You can use the view width to set the height. 100 vw is 100% of the width. height: 60vw; would make the height 60% of the width.

git discard all changes and pull from upstream

git reset <hash>  # you need to know the last good hash, so you can remove all your local commits

git fetch upstream
git checkout master
git merge upstream/master
git push origin master -f

voila, now your fork is back to same as upstream.

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

I just had the same happen on me when I tried to run a python script from a shared folder in VirtualBox within the new Ubuntu 20.04 LTS. Python bailed with Killed while loading my own personal library. When I moved the folder to a local directory, the issue went away. It appears that the Killed stop happened during the initial imports of my library as I got messages of missing libraries once I moved the folder over.

The issue went away after I restarted my computer.

Therefore, people may want to try moving the program to a local directory if its over a share of some kind or it could be a transient problem that just requires a reboot of the OS.

Code signing is required for product type 'Application' in SDK 'iOS5.1'

TN2250 Tech document was retired,To resolve this add IOs5.1 or 8.1 sdk field under Anyios SDK field

in code sign problem will solved

How to add a custom CA Root certificate to the CA Store used by pip in Windows?

Alternative solution on Windows is to install python-certifi-win32 that will allow Python to use Windows Certificate Store.

pip install python-certifi-win32

The type WebMvcConfigurerAdapter is deprecated

I have been working on Swagger equivalent documentation library called Springfox nowadays and I found that in the Spring 5.0.8 (running at present), interface WebMvcConfigurer has been implemented by class WebMvcConfigurationSupport class which we can directly extend.

import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

public class WebConfig extends WebMvcConfigurationSupport { }

And this is how I have used it for setting my resource handling mechanism as follows -

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("swagger-ui.html")
            .addResourceLocations("classpath:/META-INF/resources/");

    registry.addResourceHandler("/webjars/**")
            .addResourceLocations("classpath:/META-INF/resources/webjars/");
}

How to get a Color from hexadecimal Color String

XML file saved at res/values/colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <color name="opaque_red">#f00</color>
   <color name="translucent_red">#80ff0000</color>
</resources>

This application code retrieves the color resource:

Resources res = getResources();
int color = res.getColor(R.color.opaque_red);

This layout XML applies the color to an attribute:

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="@color/translucent_red"
    android:text="Hello"/>

adding child nodes in treeview

I needed to do something similar and came across the same issues. I used the AfterSelect event to make sure I wasn't getting the previously selected node.

It's actually really easy to reference the correct node to receive the new child node.

private void TreeView1_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
{
   //show dialogbox to let user name the new node
   frmDialogInput f = new frmDialogInput();
   f.ShowDialog();

    //find the node that was selected
    TreeNode myNode = TreeView1.SelectedNode;
    //create the new node to add
    TreeNode newNode = new TreeNode(f.EnteredText);
    //add the new child to the selected node
    myNode.Nodes.Add(newNode);
}

Smooth scroll without the use of jQuery

You can also use Scroll Behaviour Property. for example add below line to your css

_x000D_
_x000D_
html{_x000D_
scroll-behavior:smooth;_x000D_
}
_x000D_
_x000D_
_x000D_

and this will result a native smooth scrolling feature . Read More about Scroll behavior

MVC If statement in View

Every time you use html syntax you have to start the next razor statement with a @. So it should be @if ....

Android ListView Selector Color

The list selector drawable is a StateListDrawable — it contains reference to multiple drawables for each state the list can be, like selected, focused, pressed, disabled...

While you can retrieve the drawable using getSelector(), I don't believe you can retrieve a specific Drawable from a StateListDrawable, nor does it seem possible to programmatically retrieve the colour directly from a ColorDrawable anyway.

As for setting the colour, you need a StateListDrawable as described above. You can set this on your list using the android:listSelector attribute, defining the drawable in XML like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_enabled="false" android:state_focused="true"
        android:drawable="@drawable/item_disabled" />
  <item android:state_pressed="true"
        android:drawable="@drawable/item_pressed" />
  <item android:state_focused="true"
        android:drawable="@drawable/item_focused" />
</selector>

How do I mock a service that returns promise in AngularJS Jasmine unit test?

We can also write jasmine's implementation of returning promise directly by spy.

spyOn(myOtherService, "makeRemoteCallReturningPromise").andReturn($q.when({}));

For Jasmine 2:

spyOn(myOtherService, "makeRemoteCallReturningPromise").and.returnValue($q.when({}));

(copied from comments, thanks to ccnokes)

What are the differences between ArrayList and Vector?

Basically both ArrayList and Vector both uses internal Object Array.

ArrayList: The ArrayList class extends AbstractList and implements the List interface and RandomAccess (marker interface). ArrayList supports dynamic arrays that can grow as needed. It gives us first iteration over elements. ArrayList uses internal Object Array; they are created with an default initial size of 10. When this size is exceeded, the collection is automatically increases to half of the default size that is 15.

Vector: Vector is similar to ArrayList but the differences are, it is synchronized and its default initial size is 10 and when the size exceeds its size increases to double of the original size that means the new size will be 20. Vector is the only class other than ArrayList to implement RandomAccess. Vector is having four constructors out of that one takes two parameters Vector(int initialCapacity, int capacityIncrement) capacityIncrement is the amount by which the capacity is increased when the vector overflows, so it have more control over the load factor.

Some other differences are: enter image description here

Get LatLng from Zip Code - Google Maps API

Here is the function I am using for my work

function getLatLngByZipcode(zipcode) 
{
    var geocoder = new google.maps.Geocoder();
    var address = zipcode;
    geocoder.geocode({ 'address': address }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var latitude = results[0].geometry.location.lat();
            var longitude = results[0].geometry.location.lng();
            alert("Latitude: " + latitude + "\nLongitude: " + longitude);
        } else {
            alert("Request failed.")
        }
    });
    return [latitude, longitude];
}

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

How to permanently set $PATH on Linux/Unix?

Let's say you're running MacOS and you have a binary you trust and would like to make available across your system but don't necessarily want the directory in which the binary is to be added to your PATH, you can opt to copy/move the binary to /usr/local/bin, which should already be in your PATH. This will make the binary executable like any other binary you may already have access to in your terminal.

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

if you want to change menu item icons, arrow icon (back/up), and 3 dots icon you can use android:tint

  <style name="ToolbarTheme" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
    <item name="android:tint">@color/your_color</item>
  </style>

How To Remove Outline Border From Input Button

As many others have mentioned, selector:focus {outline: none;} will remove that border but that border is a key accessibility feature that allows for keyboard users to find the button and shouldn't be removed.

Since your concern seems to be an aesthetic one, you should know that you can change the color, style, and width of the outline, making it fit into your site styling better.

selector:focus {
  outline-width: 1px;
  outline-style: dashed;
  outline-color: red;
}

Shorthand:

selector:focus {
  outline: 1px dashed red;
}

How to solve error message: "Failed to map the path '/'."

i have tried following solution and it had work for me C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\devenv.exe right click on Devenv.exe in Compablity tab --> Privilage Level --> click on Run this Program as an Adminstrator If as for the Admin Password Provide it

if it is already selected deselect it and again select it -->Apply-->OK

restart the VS application and Publish your website again

Normalizing a list of numbers in Python

Try this :

from __future__ import division

raw = [0.07, 0.14, 0.07]  

def norm(input_list):
    norm_list = list()

    if isinstance(input_list, list):
        sum_list = sum(input_list)

        for value in input_list:
            tmp = value  /sum_list
            norm_list.append(tmp) 

    return norm_list

print norm(raw)

This will do what you asked. But I will suggest to try Min-Max normalization.

min-max normalization :

def min_max_norm(dataset):
    if isinstance(dataset, list):
        norm_list = list()
        min_value = min(dataset)
        max_value = max(dataset)

        for value in dataset:
            tmp = (value - min_value) / (max_value - min_value)
            norm_list.append(tmp)

    return norm_list

How many bytes is unsigned long long?

The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.

'ssh-keygen' is not recognized as an internal or external command

I just had this issue and thought I'd share what I thought was an easier way around this.

Open git-bash and run the same command with the addition of -C since you're commenting in your email address: ssh-keygen -t rsa -C "[email protected]" command. That's it.

git-bash should have been installed when you installed git. If you can't find it you can check C:\Program Files\Git\Git Bash

The first time I did this it failed to create the .ssh folder for me so I had to open a standard Command Prompt and mkdir C:\Users\yourusername\.ssh

CSS table layout: why does table-row not accept a margin?

There is a pretty simple fix for this, the border-spacing and border-collapse CSS attributes work on display: table.

You can use the following to get padding/margins in your cells.

_x000D_
_x000D_
.container {_x000D_
  width: 850px;_x000D_
  padding: 0;_x000D_
  display: table;_x000D_
  margin-left: auto;_x000D_
  margin-right: auto;_x000D_
  border-collapse: separate;_x000D_
  border-spacing: 15px;_x000D_
}_x000D_
_x000D_
.row {_x000D_
  display: table-row;_x000D_
}_x000D_
_x000D_
.home_1 {_x000D_
  width: 64px;_x000D_
  height: 64px;_x000D_
  padding-right: 20px;_x000D_
  margin-right: 10px;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_2 {_x000D_
  width: 350px;_x000D_
  height: 64px;_x000D_
  padding: 0px;_x000D_
  vertical-align: middle;_x000D_
  font-size: 150%;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_3 {_x000D_
  width: 64px;_x000D_
  height: 64px;_x000D_
  padding-right: 20px;_x000D_
  margin-right: 10px;_x000D_
  display: table-cell;_x000D_
}_x000D_
_x000D_
.home_4 {_x000D_
  width: 350px;_x000D_
  height: 64px;_x000D_
  padding: 0px;_x000D_
  vertical-align: middle;_x000D_
  font-size: 150%;_x000D_
  display: table-cell;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="home_1">Foo</div>_x000D_
    <div class="home_2">Foo</div>_x000D_
    <div class="home_3">Foo</div>_x000D_
    <div class="home_4">Foo</div>_x000D_
  </div>_x000D_
_x000D_
  <div class="row">_x000D_
    <div class="home_1">Foo</div>_x000D_
    <div class="home_2">Foo</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note that you have to have

border-collapse: separate;

Otherwise it will not work.

How do I create a basic UIButton programmatically?

Objective-C

UIButton *but= [UIButton buttonWithType:UIButtonTypeRoundedRect];
[but addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
 [but setFrame:CGRectMake(52, 252, 215, 40)];
[but setTitle:@"Login" forState:UIControlStateNormal];
[but setExclusiveTouch:YES];

 // if you like to add backgroundImage else no need
   [but setbackgroundImage:[UIImage imageNamed:@"XXX.png"] forState:UIControlStateNormal];

[self.view addSubview:but];

-(void) buttonClicked:(UIButton*)sender
 {
NSLog(@"you clicked on button %@", sender.tag);
 }

Swift

    let myButton = UIButton() // if you want to set the type use like UIButton(type: .RoundedRect) or UIButton(type: .Custom)
    myButton.setTitle("Hai Touch Me", forState: .Normal)
    myButton.setTitleColor(UIColor.blueColor(), forState: .Normal)
    myButton.frame = CGRectMake(15, 50, 300, 500)
    myButton.addTarget(self, action: "pressedAction:", forControlEvents: .TouchUpInside)

    self.view.addSubview( myButton)


func pressedAction(sender: UIButton!) {
   // do your stuff here 
  NSLog("you clicked on button %@", sender.tag)
}

Swift3 and above

  let myButton = UIButton() // if you want to set the type use like UIButton(type: .RoundedRect) or UIButton(type: .Custom)
    myButton.setTitle("Hi, Click me", for: .normal)
    myButton.setTitleColor(UIColor.blue, for: .normal)
    myButton.frame = CGRect(x: 15, y: 50, width: 300, height: 500)

    myButton.addTarget(self, action: #selector(pressedAction(_:)), for: .touchUpInside)
    self.view.addSubview( myButton)



func pressedAction(_ sender: UIButton) {
   // do your stuff here 
  print("you clicked on button \(sender.tag)")
}

SwiftUI

for example you get the step by step implemntation from SwiftUI Developer portal

import SwiftUI

struct ContentView : View {
    var body: some View {
        VStack {

            Text("Target Color Black")
             Button(action: { 
                 /* handle button action here */ })
            {
         Text("your Button Name")
          .color(.white)
                        .padding(10)
                        .background(Color.blue)
                        .cornerRadius(5)
                        .shadow(radius: 5)
                        .clipShape(RoundedRectangle(cornerRadius: 5))
     }


        }
    }
}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif

Minimal web server using netcat

I think the problem that all the solution listed doesn't work, is intrinsic in the nature of http service, the every request established is with a different client and the response need to be processed in a different context, every request must fork a new instance of response...

The current solution I think is the -e of netcat but I don't know why doesn't work... maybe is my nc version that I test on openwrt...

with socat it works....

I try this https://github.com/avleen/bashttpd

and it works, but I must run the shell script with this command.

socat tcp-l:80,reuseaddr,fork EXEC:bashttpd &

The socat and netcat samples on github doesn't works for me, but the socat that I used works.

Fastest way to check if a string is JSON in PHP?

We need to check if passed string is not numeric because in this case json_decode raises no error.

function isJson($str) {
    $result = false;
    if (!preg_match("/^\d+$/", trim($str))) {
        json_decode($str);
        $result = (json_last_error() == JSON_ERROR_NONE);
    }

    return $result;
}

SVN change username

If your protocol is http and you are using Subversion 1.7, you can switch the user at anytime by simply using the global --username option on any command.

When Ingo's method didn't work for me, this was what I found that worked.

Ruby: Calling class method from instance

Rather than referring to the literal name of the class, inside an instance method you can just call self.class.whatever.

class Foo
    def self.some_class_method
        puts self
    end

    def some_instance_method
        self.class.some_class_method
    end
end

print "Class method: "
Foo.some_class_method

print "Instance method: "
Foo.new.some_instance_method

Outputs:

Class method: Foo
Instance method: Foo

How can I implement a theme from bootswatch or wrapbootstrap in an MVC 5 project?

The steps to apply a theme are fairly simple. To really understand how everything works together, you'll need to understand what the ASP.NET MVC 5 template is providing out of the box and how you can customize it for your needs.

Note: If you have a basic understanding of how the MVC 5 template works, scroll down to the theming section.


ASP.NET MVC 5 Template: How it works

This walk-through goes over how to create an MVC 5 project and what's going on under the hood. See all the features of MVC 5 Template in this blog.

  1. Create a new project. Under Templates Choose Web > ASP.NET Web Application. Enter a name for your project and click OK.

  2. On the next wizard, choose MVC and click OK. This will apply the MVC 5 template.

    Example of choosing MVC Template

  3. The MVC 5 template creates an MVC application that uses Bootstrap to provide responsive design and theming features. Under the hood, the template includes a bootstrap 3.* nuget package that installs 4 files: bootstrap.css, bootstrap.min.css, bootstrap.js, and bootstrap.min.js.

    Example of installed css and js

  4. Bootstrap is bundled in your application by using the Web Optimization feature. Inspect Views/Shared/_Layout.cshtml and look for

    @Styles.Render("~/Content/css")
    

    and

    @Scripts.Render("~/bundles/bootstrap") 
    

    These two paths refer to bundles set up in App_Start/BundleConfig.cs:

    bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
        "~/Scripts/bootstrap.js",
        "~/Scripts/respond.js"));
    
    bundles.Add(new StyleBundle("~/Content/css").Include(
        "~/Content/bootstrap.css",
        "~/Content/site.css"));
    
  5. This is what makes it possible to run your application without any configuring up front. Try running your project now.

    Default Application Running


Applying Bootstrap Themes in ASP.NET MVC 5

This walk-through covers how to apply bootstrap themes in an MVC 5 project

  1. First, download the css of the theme you'd like to apply. For this example, I'll be using Bootswatch's Flatly. Include the downloaded flatly.bootstrap.css and flatly.bootstrap.min.css in the Content folder (be sure to Include in Project as well).
  2. Open App_Start/BundleConfig.cs and change the following:

    bundles.Add(new StyleBundle("~/Content/css").Include(
        "~/Content/bootstrap.css",
        "~/Content/site.css"));
    

    to include your new theme:

    bundles.Add(new StyleBundle("~/Content/css").Include(
        "~/Content/flatly.bootstrap.css",
        "~/Content/site.css"));
    
  3. If you're using the default _Layout.cshtml included in the MVC 5 template, you can skip to step 4. If not, as a bare minimum, include these two line in your layout along with your Bootstrap HTML template:

    In your <head>:

    @Styles.Render("~/Content/css")
    

    Last line before closing </body>:

    @Scripts.Render("~/bundles/bootstrap")
    
  4. Try running your project now. You should see your newly created application now using your theme.

    Default template using flatly theme


Resources

Check out this awesome 30 day walk-through guide by James Chambers for more information, tutorials, tips and tricks on how to use Twitter Bootstrap with ASP.NET MVC 5.

How to display with n decimal places in Matlab

i use like tim say sprintf('%0.6f', x), it's a string then i change it to number by using command str2double(x).

OAuth: how to test with local URLs?

I found xip.io which automatically converts a fixed url to a embedded localhost domain.

For example lets say your localhost server is running on 127.0.0.1:8000 You can go to http://www.127.0.0.1.xip.io:5555/ to access this server. You can then add this address to Oauth configuration for Facebook or Google.