Programs & Examples On #Amazon rds

Amazon Relational Database Service (Amazon RDS) is a web service that makes it easy to set up, operate, and scale a relational database in the cloud.

Access denied; you need (at least one of) the SUPER privilege(s) for this operation

Problem: You're trying to import data (using mysqldump file) to your mysql database ,but it seems you don't have permission to perform that operation.

Solution: Assuming you data is migrated ,seeded and updated in your mysql database, take snapshot using mysqldump and export it to file

mysqldump -u [username] -p [databaseName] --set-gtid-purged=OFF > [filename].sql

From mysql documentation:

GTID - A global transaction identifier (GTID) is a unique identifier created and associated with each transaction committed on the server of origin (master). This identifier is unique not only to the server on which it originated, but is unique across all servers in a given replication setup. There is a 1-to-1 mapping between all transactions and all GTIDs.

--set-gtid-purged=OFF SET @@GLOBAL.gtid_purged is not added to the output, and SET @@SESSION.sql_log_bin=0 is not added to the output. For a server where GTIDs are not in use, use this option or AUTO. Only use this option for a server where GTIDs are in use if you are sure that the required GTID set is already present in gtid_purged on the target server and should not be changed, or if you plan to identify and add any missing GTIDs manually.

Afterwards connect to your mysql with user root ,give permissions , flush them ,and verify that your user privileges were updated correctly.

mysql -u root -p
UPDATE mysql.user SET Super_Priv='Y' WHERE user='johnDoe' AND host='%';
FLUSH PRIVILEGES;
mysql> SHOW GRANTS FOR 'johnDoe';
+------------------------------------------------------------------+
| Grants for johnDoe                                               |
+------------------------------------------------------------------+
| GRANT USAGE ON *.* TO `johnDoe`                                  |
| GRANT ALL PRIVILEGES ON `db1`.* TO `johnDoe`                     |
+------------------------------------------------------------------+

now reload the data and the operation should be permitted.

mysql -h [host] -u [user] -p[pass] [db_name] < [mysql_dump_name].sql

how to run command "mysqladmin flush-hosts" on Amazon RDS database Server instance?

Login to any other EC2 instance you have that has access to the RDS instance in question and has mysqladmin installed and run

mysqladmin -h <RDS ENDPOINT URL> -P 3306 -u <USER> -p flush-hosts

you will be prompted for your password

Python: can't assign to literal

The left hand side of the = operator needs to be a variable. What you're doing here is telling python: "You know the number one? Set it to the inputted string.". 1 is a literal number, not a variable. 1 is always 1, you can't "set" it to something else.

A variable is like a box in which you can store a value. 1 is a value that can be stored in the variable. The input call returns a string, another value that can be stored in a variable.

Instead, use lists:

import random

namelist = []
namelist.append(input("Please enter name 1:"))  #Stored in namelist[0]
namelist.append(input('Please enter name 2:'))  #Stored in namelist[1]
namelist.append(input('Please enter name 3:'))  #Stored in namelist[2]
namelist.append(input('Please enter name 4:'))  #Stored in namelist[3]
namelist.append(input('Please enter name 5:'))  #Stored in namelist[4]

nameindex = random.randint(0, 5)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

Using a for loop, you can cut down even more:

import random

namecount = 5
namelist=[]
for i in range(0, namecount):
  namelist.append(input("Please enter name %s:" % (i+1))) #Stored in namelist[i]

nameindex = random.randint(0, namecount)
print('Well done {}. You are the winner!'.format(namelist[nameindex]))

Excel: Search for a list of strings within a particular string using array formulas?

This will return the matching word or an error if no match is found. For this example I used the following.

List of words to search for: G1:G7
Cell to search in: A1

=INDEX(G1:G7,MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*(ROW(G1:G7)-ROW(G1)+1)))

Enter as an array formula by pressing Ctrl+Shift+Enter.

This formula works by first looking through the list of words to find matches, then recording the position of the word in the list as a positive value if it is found or as a negative value if it is not found. The largest value from this array is the position of the found word in the list. If no word is found, a negative value is passed into the INDEX() function, throwing an error.

To return the row number of a matching word, you can use the following:

=MAX(IF(ISERROR(FIND(G1:G7,A1)),-1,1)*ROW(G1:G7))

This also must be entered as an array formula by pressing Ctrl+Shift+Enter. It will return -1 if no match is found.

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

A lot depends on what kind of project it is. WTP's JSP support either expects the JSP files to be under the same folder that's the parent of the WEB-INF folder (src/web, which it will then treat as "/" to find TLDs), or to have project metadata set up to help it know where that root is (done for you in a Dynamic Web Project through Deployment Assembly). How are you referring to the TLD file, and where is the JSP file located?

And maybe I missed the original post to the Eclipse forums; the one I saw was posted a full day after this one.

Get generic type of class at runtime

As others mentioned, it's only possible via reflection in certain circumstances.

If you really need the type, this is the usual (type-safe) workaround pattern:

public class GenericClass<T> {

     private final Class<T> type;

     public GenericClass(Class<T> type) {
          this.type = type;
     }

     public Class<T> getMyType() {
         return this.type;
     }
}

mysql alphabetical order

but result showing all records starting with a or c or d i want to show records only starting with b

You should use WHERE in that case:

select name from user where name = 'b' order by name

If you want to allow regex, you can use the LIKE operator there too if you want. Example:

select name from user where name like 'b%' order by name

That will select records starting with b. Following query on the other hand will select all rows where b is found anywhere in the column:

select name from user where name like '%b%' order by name

How do I send a POST request as a JSON?

In the lastest requests package, you can use json parameter in requests.post() method to send a json dict, and the Content-Type in header will be set to application/json. There is no need to specify header explicitly.

import requests

payload = {'key': 'value'}
requests.post(url, json=payload)

Install php-zip on php 5.6 on Ubuntu

Try either

  • sudo apt-get install php-zip or
  • sudo apt-get install php5.6-zip

Then, you might have to restart your web server.

  • sudo service apache2 restart or
  • sudo service nginx restart

If you are installing on centos or fedora OS then use yum in place of apt-get. example:-

sudo yum install php-zip or sudo yum install php5.6-zip and sudo service httpd restart

Plotting histograms from grouped data in a pandas DataFrame

I write this answer because I was looking for a way to plot together the histograms of different groups. What follows is not very smart, but it works fine for me. I use Numpy to compute the histogram and Bokeh for plotting. I think it is self-explanatory, but feel free to ask for clarifications and I'll be happy to add details (and write it better).

figures = {
    'Transit': figure(title='Transit', x_axis_label='speed [km/h]', y_axis_label='frequency'),
    'Driving': figure(title='Driving', x_axis_label='speed [km/h]', y_axis_label='frequency')
}

cols = {'Vienna': 'red', 'Turin': 'blue', 'Rome': 'Orange'}
for gr in df_trips.groupby(['locality', 'means']):
    locality = gr[0][0]
    means = gr[0][1]
    fig = figures[means]
    h, b = np.histogram(pd.DataFrame(gr[1]).speed.values)
    fig.vbar(x=b[1:], top=h, width=(b[1]-b[0]), legend_label=locality, fill_color=cols[locality], alpha=0.5)

show(gridplot([
    [figures['Transit']],
    [figures['Driving']],
]))

Determining complexity for recursive functions (Big O notation)

The key here is to visualise the call tree. Once done that, the complexity is:

nodes of the call tree * complexity of other code in the function

the latter term can be computed the same way we do for a normal iterative function.

Instead, the total nodes of a complete tree are computed as

                  C^L - 1
                  -------  , when C>1
               /   C - 1
              /
 # of nodes =
              \    
               \ 
                  L        , when C=1

Where C is number of children of each node and L is the number of levels of the tree (root included).

It is easy to visualise the tree. Start from the first call (root node) then draw a number of children same as the number of recursive calls in the function. It is also useful to write the parameter passed to the sub-call as "value of the node".

So, in the examples above:

  1. the call tree here is C = 1, L = n+1. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n+1) * O(1) = O(n)
n     level 1
n-1   level 2
n-2   level 3
n-3   level 4
... ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = (n/5) * O(1) = O(n)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5
  1. call tree here is C = 1, L = log(n). Complexity of the rest of function is O(1). Therefore total complexity is L * O(1) = log5(n) * O(1) = O(log(n))
n
n/5
n/5^2
n/5^3
... ~ log5(n) levels -> L = log5(n)
  1. call tree here is C = 2, L = n. Complexity of the rest of function is O(1). This time we use the full formula for the number of nodes in the call tree because C > 1. Therefore total complexity is (C^L-1)/(C-1) * O(1) = (2^n - 1) * O(1) = O(2^n).
               n                   level 1
      n-1             n-1          level 2
  n-2     n-2     n-2     n-2      ...
n-3 n-3 n-3 n-3 n-3 n-3 n-3 n-3    ...     
              ...                ~ n levels -> L = n
  1. call tree here is C = 1, L = n/5. Complexity of the rest of function is O(n). Therefore total complexity is L * O(1) = (n/5) * O(n) = O(n^2)
n
n-5
n-10
n-15
... ~ n/5 levels -> L = n/5

How to remove underline from a link in HTML?

<style="text-decoration: none">

The above code will be enough.Just paste this into the link you want to remove underline from.

Download all stock symbol list of a market

There does not seem to be a straight-forward way provided by Google or Yahoo finance portals to download the full list of tickers. One possible 'brute force' way to get it is to query their APIs for every possible combinations of letters and save only those that return valid results. As silly as it may seem there are people who actually do it (ie. check this: http://investexcel.net/all-yahoo-finance-stock-tickers/).

You can download lists of symbols from exchanges directly or 3rd party websites as suggested by @Eugene S and @Capn Sparrow, however if you intend to use it to fetch data from Google or Yahoo, you have to sometimes use prefixes or suffixes to make sure that you're getting the correct data. This is because some symbols may repeat between exchanges, so Google and Yahoo prepend or append exchange codes to the tickers in order to distinguish between them. Here's an example:

Company:  Vodafone
------------------
LSE symbol:    VOD
 in Google:    LON:VOD
 in Yahoo:     VOD.L
NASDAQ symbol: VOD
 in Google:    NASDAQ:VOD
 in Yahoo:     VOD

Classes residing in App_Code is not accessible

make sure that you are using the same namespace as your pages

jQuery return ajax result into outside variable

You are missing a comma after

'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' }

Also, if you want return_first to hold the result of your anonymous function, you need to make a function call:

var return_first = function () {
    var tmp = null;
    $.ajax({
        'async': false,
        'type': "POST",
        'global': false,
        'dataType': 'html',
        'url': "ajax.php?first",
        'data': { 'request': "", 'target': 'arrange_url', 'method': 'method_target' },
        'success': function (data) {
            tmp = data;
        }
    });
    return tmp;
}();

Note () at the end.

Git: Installing Git in PATH with GitHub client for Windows

Updated for the Github Desktop

Search up "Edit the system environment variables" on windows search

  • Click environmental variable on the bottom right corner

  • Find path under system variables and click edit on it

  • Click new to add a new path

  • add this path: C:\Users\yourUserName\AppData\Local\GitHubDesktop\bin\github.exe

To make sure everything is working fine, open cmd, and type github.exe

Proper way to empty a C-String

Two other ways are strcpy(str, ""); and string[0] = 0

To really delete the Variable contents (in case you have dirty code which is not working properly with the snippets above :P ) use a loop like in the example below.

#include <string.h>

...

int i=0;
for(i=0;i<strlen(string);i++)
{
    string[i] = 0;
}

In case you want to clear a dynamic allocated array of chars from the beginning, you may either use a combination of malloc() and memset() or - and this is way faster - calloc() which does the same thing as malloc but initializing the whole array with Null.

At last i want you to have your runtime in mind. All the way more, if you're handling huge arrays (6 digits and above) you should try to set the first value to Null instead of running memset() through the whole String.

It may look dirtier at first, but is way faster. You just need to pay more attention on your code ;)

I hope this was useful for anybody ;)

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

How to create the pom.xml for a Java project with Eclipse

The easiest way would be to create a new (simple) Maven project using the "new project" wizard. You can then migrate your source into the Maven folder structure + the auto generated POM file.

Best method to download image from url in Android

First Declare Permission in Android Manifest:-

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

MainActivityForDownloadImages.java

public class MainActivityForDownloadImages extends AppCompatActivity {


//    String urls = "https://stimg.cardekho.com/images/carexteriorimages/930x620/Kia/Kia-Seltos/6232/1562746799300/front-left-side-47.jpg";
    String urls = "https://images5.alphacoders.com/609/609173.jpg";
    Button button;
     public final Context context = this;
    ProgressDialog progressDialog ;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_for_download_images);
        if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
        }


        progressDialog = new ProgressDialog(context);
        button = findViewById(R.id.downloadImagebtn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // initialize the progress dialog like in the first example
                // this is how you fire the downloader

                Intent intent = new Intent(context, DownloadService.class);
                intent.putExtra("url", urls);
                intent.putExtra("receiver", new DownloadReceiver(new Handler()));
                startService(intent);


            }
        });


    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == 0) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                    && grantResults[1] == PackageManager.PERMISSION_GRANTED) {


            }
        }
    }

    private class DownloadReceiver extends ResultReceiver {

        public DownloadReceiver(Handler handler) {
            super(handler);
        }

        @Override
        protected void onReceiveResult(int resultCode, Bundle resultData) {

            super.onReceiveResult(resultCode, resultData);

            if (resultCode == DownloadService.UPDATE_PROGRESS) {

                int progress = resultData.getInt("progress"); //get the progress
                progressDialog.setProgress(progress);
                progressDialog.setMessage("Images Is Downloading");
                progressDialog.show();

                if (progress == 100) {

                    progressDialog.dismiss();

                }
            }
        }
    }

}

DownloadService.java

public class DownloadService extends IntentService {

public static final int UPDATE_PROGRESS = 8344;
String folder_main = "ImagesFolder";


public DownloadService() {
    super("DownloadService");
}


@Override
protected void onHandleIntent(Intent intent) {

    String urlToDownload = intent.getStringExtra("url");
    ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");

    try {

        //create url and connect
        URL url = new URL(urlToDownload);
        URLConnection connection = url.openConnection();
        connection.connect();

        // this will be useful so that you can show a typical 0-100% progress bar
        int fileLength = connection.getContentLength();

        // download the file
        InputStream input = new BufferedInputStream(connection.getInputStream());


        File outerFolder = new File(Environment.getExternalStorageDirectory(), folder_main);
        File inerDire = new File(outerFolder.getAbsoluteFile(), System.currentTimeMillis() + ".jpg");


        if (!outerFolder.exists()) {
            outerFolder.mkdirs();
        }

        inerDire.createNewFile();


        FileOutputStream output = new FileOutputStream(inerDire);

        byte data[] = new byte[1024];
        long total = 0;
        int count;
        while ((count = input.read(data)) != -1) {
            total += count;

            // publishing the progress....
            Bundle resultData = new Bundle();
            resultData.putInt("progress", (int) (total * 100 / fileLength));
            receiver.send(UPDATE_PROGRESS, resultData);
            output.write(data, 0, count);
        }

        // close streams
        output.flush();
        output.close();
        input.close();

    } catch (IOException e) {
        e.printStackTrace();

    }

    Bundle resultData = new Bundle();
    resultData.putInt("progress", 100);

    receiver.send(UPDATE_PROGRESS, resultData);
}

}

.NET / C# - Convert char[] to string

char[] chars = {'a', ' ', 's', 't', 'r', 'i', 'n', 'g'};
string s = new string(chars);

How to printf uint64_t? Fails with: "spurious trailing ‘%’ in format"

The ISO C99 standard specifies that these macros must only be defined if explicitly requested.

#define __STDC_FORMAT_MACROS
#include <inttypes.h>

... now PRIu64 will work

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

Saty described the differences between them. For your practice, you can use datetime in order to keep the output of NOW().

For example:

CREATE TABLE Orders
(
  OrderId int NOT NULL,
  ProductName varchar(50) NOT NULL,
  OrderDate datetime NOT NULL DEFAULT NOW(),
  PRIMARY KEY (OrderId)
)

You can read more at w3schools.

What is more efficient? Using pow to square or just multiply it with itself?

I was also wondering about the performance issue, and was hoping this would be optimised out by the compiler, based on the answer from @EmileCormier. However, I was worried that the test code he showed would still allow the compiler to optimise away the std::pow() call, since the same values were used in the call every time, which would allow the compiler to store the results and re-use it in the loop - this would explain the almost identical run-times for all cases. So I had a look into it too.

Here's the code I used (test_pow.cpp):

#include <iostream>                                                                                                                                                                                                                       
#include <cmath>
#include <chrono>

class Timer {
  public:
    explicit Timer () : from (std::chrono::high_resolution_clock::now()) { }

    void start () {
      from = std::chrono::high_resolution_clock::now();
    }

    double elapsed() const {
      return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - from).count() * 1.0e-6;
    }

  private:
    std::chrono::high_resolution_clock::time_point from;
};

int main (int argc, char* argv[])
{
  double total;
  Timer timer;



  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,2);
  std::cout << "std::pow(i,2): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i;
  std::cout << "i*i: " << timer.elapsed() << "s (result = " << total << ")\n";

  std::cout << "\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += std::pow (i,3);
  std::cout << "std::pow(i,3): " << timer.elapsed() << "s (result = " << total << ")\n";

  total = 0.0;
  timer.start();
  for (double i = 0.0; i < 1.0; i += 1e-8)
    total += i*i*i;
  std::cout << "i*i*i: " << timer.elapsed() << "s (result = " << total << ")\n";


  return 0;
}

This was compiled using:

g++ -std=c++11 [-O2] test_pow.cpp -o test_pow

Basically, the difference is the argument to std::pow() is the loop counter. As I feared, the difference in performance is pronounced. Without the -O2 flag, the results on my system (Arch Linux 64-bit, g++ 4.9.1, Intel i7-4930) were:

std::pow(i,2): 0.001105s (result = 3.33333e+07)
i*i: 0.000352s (result = 3.33333e+07)

std::pow(i,3): 0.006034s (result = 2.5e+07)
i*i*i: 0.000328s (result = 2.5e+07)

With optimisation, the results were equally striking:

std::pow(i,2): 0.000155s (result = 3.33333e+07)
i*i: 0.000106s (result = 3.33333e+07)

std::pow(i,3): 0.006066s (result = 2.5e+07)
i*i*i: 9.7e-05s (result = 2.5e+07)

So it looks like the compiler does at least try to optimise the std::pow(x,2) case, but not the std::pow(x,3) case (it takes ~40 times longer than the std::pow(x,2) case). In all cases, manual expansion performed better - but particularly for the power 3 case (60 times quicker). This is definitely worth bearing in mind if running std::pow() with integer powers greater than 2 in a tight loop...

Changing MongoDB data store directory

Resolved it in 2 minutes downtime :)
Just move your folder, add symlink, then tune permissions.

sudo service mongod stop
sudo mv mongodb /new/disk/mongodb/
sudo ln -s /new/disk/mongodb/ /var/lib/mongodb
sudo chown mongodb:mongodb /new/disk/mongodb/
sudo service mongod start

# test if mongodb user can access new location:
sudo -u mongodb -s cd /new/disk/mongodb/
# resolve other permissions issues if necessary
sudo usermod -a -G <newdisk_grp> mongodb

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

A simple answer would be (26 characters):

String.fromCharCode(97+n);

If space is precious you could do the following (20 characters):

(10+n).toString(36);

Think about what you could do with all those extra bytes!

How this works is you convert the number to base 36, so you have the following characters:

0123456789abcdefghijklmnopqrstuvwxyz
^         ^
n        n+10

By offsetting by 10 the characters start at a instead of 0.

Not entirely sure about how fast running the two different examples client-side would compare though.

How do I calculate a trendline for a graph?

Here's what I ended up using.

public class DataPoint<T1,T2>
{
    public DataPoint(T1 x, T2 y)
    {
        X = x;
        Y = y;
    }

    [JsonProperty("x")]
    public T1 X { get; }

    [JsonProperty("y")]
    public T2 Y { get; }
}

public class Trendline
{
    public Trendline(IEnumerable<DataPoint<long, decimal>> dataPoints)
    {
        int count = 0;
        long sumX = 0;
        long sumX2 = 0;
        decimal sumY = 0;
        decimal sumXY = 0;

        foreach (var dataPoint in dataPoints)
        {
            count++;
            sumX += dataPoint.X;
            sumX2 += dataPoint.X * dataPoint.X;
            sumY += dataPoint.Y;
            sumXY += dataPoint.X * dataPoint.Y;
        }

        Slope = (sumXY - ((sumX * sumY) / count)) / (sumX2 - ((sumX * sumX) / count));
        Intercept = (sumY / count) - (Slope * (sumX / count));
    }

    public decimal Slope { get; private set; }
    public decimal Intercept { get; private set; }
    public decimal Start { get; private set; }
    public decimal End { get; private set; }

    public decimal GetYValue(decimal xValue)
    {
        return Slope * xValue + Intercept;
    }
}

My data set is using a Unix timestamp for the x-axis and a decimal for the y. Change those datatypes to fit your need. I do all the sum calculations in one iteration for the best possible performance.

Can we use JSch for SSH key-based communication?

It is possible. Have a look at JSch.addIdentity(...)

This allows you to use key either as byte array or to read it from file.

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class UserAuthPubKey {
    public static void main(String[] arg) {
        try {
            JSch jsch = new JSch();

            String user = "tjill";
            String host = "192.18.0.246";
            int port = 10022;
            String privateKey = ".ssh/id_rsa";

            jsch.addIdentity(privateKey);
            System.out.println("identity added ");

            Session session = jsch.getSession(user, host, port);
            System.out.println("session created.");

            // disabling StrictHostKeyChecking may help to make connection but makes it insecure
            // see http://stackoverflow.com/questions/30178936/jsch-sftp-security-with-session-setconfigstricthostkeychecking-no
            // 
            // java.util.Properties config = new java.util.Properties();
            // config.put("StrictHostKeyChecking", "no");
            // session.setConfig(config);

            session.connect();
            System.out.println("session connected.....");

            Channel channel = session.openChannel("sftp");
            channel.setInputStream(System.in);
            channel.setOutputStream(System.out);
            channel.connect();
            System.out.println("shell channel connected....");

            ChannelSftp c = (ChannelSftp) channel;

            String fileName = "test.txt";
            c.put(fileName, "./in/");
            c.exit();
            System.out.println("done");

        } catch (Exception e) {
            System.err.println(e);
        }
    }
}

Java time-based map/cache with expiring keys

Apache Commons has decorator for Map to expire entries: PassiveExpiringMap It's more simple than caches from Guava.

P.S. be careful, it's not synchronized.

Mailto links do nothing in Chrome but work in Firefox?

Please check it this:

This is working in chrome and all browser.

<a href="mailto:[email protected]">Test</a>

try and working in great.

What does `m_` variable prefix mean?

To complete the current answers and as the question is not language specific, some C-project use the prefix m_ to define global variables that are specific to a file - and g_ for global variables that have a scoped larger than the file they are defined.
In this case global variables defined with prefix m_ should be defined as static.

See EDK2 (a UEFI Open-Source implementation) coding convention for an example of project using this convention.

Shell Script: How to write a string to file and to stdout on console?

Use the tee command:

echo "hello" | tee logfile.txt

PostgreSQL unnest() with element number

If the order of element is not important, you can

select 
  id, elem, row_number() over (partition by id) as nr
from (
  select
      id,
      unnest(string_to_array(elements, ',')) AS elem
  from myTable
) a

How to delete the last row of data of a pandas dataframe

Since index positioning in Python is 0-based, there won't actually be an element in index at the location corresponding to len(DF). You need that to be last_row = len(DF) - 1:

In [49]: dfrm
Out[49]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723
9  0.834706  0.002989  0.333436

[10 rows x 3 columns]

In [50]: dfrm.drop(dfrm.index[len(dfrm)-1])
Out[50]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723

[9 rows x 3 columns]

However, it's much simpler to just write DF[:-1].

Filtering by Multiple Specific Model Properties in AngularJS (in OR relationship)

If you're open to use third party libraries,'Angular Filters' with a nice collection of filters may be useful:

https://github.com/a8m/angular-filter#filterby

collection | filterBy: [prop, nested.prop, etc..]: search

How to retrieve value from elements in array using jQuery?

jQuery collections have a built in iterator with .each:

$("input[name^='card']").each(function () {
   console.log($(this).val());
}

Using a dispatch_once singleton model in Swift

Use:

class UtilSingleton: NSObject {

    var iVal: Int = 0

    class var shareInstance: UtilSingleton {
        get {
            struct Static {
                static var instance: UtilSingleton? = nil
                static var token: dispatch_once_t = 0
            }
            dispatch_once(&Static.token, {
                Static.instance = UtilSingleton()
            })
            return Static.instance!
        }
    }
}

How to use:

UtilSingleton.shareInstance.iVal++
println("singleton new iVal = \(UtilSingleton.shareInstance.iVal)")

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

Get Locale Short Date Format using javascript

If your question about <input type="date"> field, here is script for getting filed value="" attribute:

(new Date()).toISOString().split('T')[0]

You can use the Intl object (ecma-402) to get data-date-pattern="":

(new Intl.DateTimeFormat()).resolved.pattern // "M/d/y" for "en-US" in Google Chrome

And finnaly, to format date in current l10n, data-date="":

(new Intl.DateTimeFormat()).format(new Date());

Polyfill: https://github.com/andyearnshaw/Intl.js/issues/129

How to use PHP's password_hash to hash and verify passwords

I’ve built a function I use all the time for password validation and to create passwords, e.g. to store them in a MySQL database. It uses a randomly generated salt which is way more secure than using a static salt.

function secure_password($user_pwd, $multi) {

/*
    secure_password ( string $user_pwd, boolean/string $multi ) 

    *** Description: 
        This function verifies a password against a (database-) stored password's hash or
        returns $hash for a given password if $multi is set to either true or false

    *** Examples:
        // To check a password against its hash
        if(secure_password($user_password, $row['user_password'])) {
            login_function();
        } 
        // To create a password-hash
        $my_password = 'uber_sEcUrE_pass';
        $hash = secure_password($my_password, true);
        echo $hash;
*/

// Set options for encryption and build unique random hash
$crypt_options = ['cost' => 11, 'salt' => mcrypt_create_iv(22, MCRYPT_DEV_URANDOM)];
$hash = password_hash($user_pwd, PASSWORD_BCRYPT, $crypt_options);

// If $multi is not boolean check password and return validation state true/false
if($multi!==true && $multi!==false) {
    if (password_verify($user_pwd, $table_pwd = $multi)) {
        return true; // valid password
    } else {
        return false; // invalid password
    }
// If $multi is boolean return $hash
} else return $hash;

}

Memory address of variables in Java

In Java when you are making an object from a class like Person p = new Person();, p is actually an address of a memory location which is pointing to a type of Person.

When use a statemenet to print p you will see an address. The new key word makes a new memory location containing all the instance variables and methods which are included in class Person and p is the reference variable pointing to that memory location.

Convert and format a Date in JSP

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@page import="java.util.Locale"%>

<html>
<head>
<title>Date Format</title>
</head>
<body>
<%
String stringDate = "Fri May 13 2011 19:59:09 GMT 0530";
Date stringDate1 = new SimpleDateFormat("EEE MMM dd yyyy HH:mm:ss Z", Locale.ENGLISH).parse(stringDate);
String stringDate2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(stringDate1);

out.println(stringDate2);
%>
</body>
</html>

A SQL Query to select a string between two known strings

SELECT 
SUBSTRING( '[email protected]',  charindex('@','[email protected]',1) + 1, charindex('.','[email protected]',1) - charindex('@','[email protected]',1) - 1 )

Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'

I was facing the same error and struggled with it for hours. I had a web API project which is using Newtonsoft.json and another UnitTest project for the web API project. The unit test project also needed the Newtonsoft.json reference. But on adding the link I was getting the above exception.

I finally resolved it by adding the below code snippet in the app.config of the unit test project:

<dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>

Spring transaction REQUIRED vs REQUIRES_NEW : Rollback Transaction

Using REQUIRES_NEW is only relevant when the method is invoked from a transactional context; when the method is invoked from a non-transactional context, it will behave exactly as REQUIRED - it will create a new transaction.

That does not mean that there will only be one single transaction for all your clients - each client will start from a non-transactional context, and as soon as the the request processing will hit a @Transactional, it will create a new transaction.

So, with that in mind, if using REQUIRES_NEW makes sense for the semantics of that operation - than I wouldn't worry about performance - this would textbook premature optimization - I would rather stress correctness and data integrity and worry about performance once performance metrics have been collected, and not before.

On rollback - using REQUIRES_NEW will force the start of a new transaction, and so an exception will rollback that transaction. If there is also another transaction that was executing as well - that will or will not be rolled back depending on if the exception bubbles up the stack or is caught - your choice, based on the specifics of the operations. Also, for a more in-depth discussion on transactional strategies and rollback, I would recommend: «Transaction strategies: Understanding transaction pitfalls», Mark Richards.

Get cart item name, quantity all details woocommerce

Since WooCommerce 2.1 (2014) you should use the WC function instead of the global. You can also call more appropriate functions:

foreach ( WC()->cart->get_cart() as $cart_item ) {
   $item_name = $cart_item['data']->get_title();
   $quantity = $cart_item['quantity'];
   $price = $cart_item['data']->get_price();
   ...

This will not only be clean code, but it will be better than accessing the post_meta directly because it will apply filters if necessary.

How to pip install a package with min and max version range?

An elegant method would be to use the ~= compatible release operator according to PEP 440. In your case this would amount to:

package~=0.5.0

As an example, if the following versions exist, it would choose 0.5.9:

  • 0.5.0
  • 0.5.9
  • 0.6.0

For clarification, each pair is equivalent:

~= 0.5.0
>= 0.5.0, == 0.5.*

~= 0.5
>= 0.5, == 0.*

Bash Templating: How to build configuration files from templates with Bash?

Try envsubst

FOO=foo
BAR=bar
export FOO BAR

envsubst <<EOF
FOO is $FOO
BAR is $BAR
EOF

How to match all occurrences of a regex

Using scan should do the trick:

string.scan(/regex/)

How to get client IP address using jQuery

jQuery can handle JSONP, just pass an url formatted with the callback=? parameter to the $.getJSON method, for example:

_x000D_
_x000D_
$.getJSON("https://api.ipify.org/?format=json", function(e) {_x000D_
    console.log(e.ip);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

This example is of a really simple JSONP service implemented on with api.ipify.org.

If you aren't looking for a cross-domain solution the script can be simplified even more, since you don't need the callback parameter, and you return pure JSON.

Compare objects in Angular

Bit late on this thread. angular.equals does deep check, however does anyone know that why its behave differently if one of the member contain "$" in prefix ?

You can try this Demo with following input

var obj3 = {}
obj3.a=  "b";
obj3.b={};
obj3.b.$c =true;

var obj4 = {}
obj4.a=  "b";
obj4.b={};
obj4.b.$c =true;

angular.equals(obj3,obj4);

Ruby: Easiest Way to Filter Hash Keys?

If you work with rails and you have the keys in a separate list, you can use the * notation:

keys = [:foo, :bar]
hash1 = {foo: 1, bar:2, baz: 3}
hash2 = hash1.slice(*keys)
=> {foo: 1, bar:2}

As other answers stated, you can also use slice! to modify the hash in place (and return the erased key/values).

Get Base64 encode file-data from Input Form

My solution was use readAsBinaryString() and btoa() on its result.

uploadFileToServer(event) {
    var file = event.srcElement.files[0];
    console.log(file);
    var reader = new FileReader();
    reader.readAsBinaryString(file);

    reader.onload = function() {
        console.log(btoa(reader.result));
    };
    reader.onerror = function() {
        console.log('there are some problems');
    };
}

How to add image background to btn-default twitter-bootstrap button?

Instead of using input type button you can use button and insert the image inside the button content.

<button class="btn btn-default">
     <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook
</button>

The problem with doing this only with CSS is that you cannot set linear-gradient to the background you must use solid color.

.sign-in-facebook {
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }
  .sign-in-facebook:hover {
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;
    background-position: -9px -7px;
    background-repeat: no-repeat;
    background-size: 39px 43px;
    padding-left: 41px;
    color: #000;
  }

_x000D_
_x000D_
body {_x000D_
  padding: 30px;_x000D_
}
_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">_x000D_
_x000D_
<!-- Optional theme -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">_x000D_
_x000D_
<!-- Latest compiled and minified JavaScript -->_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<style type="text/css">_x000D_
  .sign-in-facebook {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #f2f2f2;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
  .sign-in-facebook:hover {_x000D_
    background: url('http://i.stack.imgur.com/e2S63.png') #e0e0e0;_x000D_
    background-position: -9px -7px;_x000D_
    background-repeat: no-repeat;_x000D_
    background-size: 39px 43px;_x000D_
    padding-left: 41px;_x000D_
    color: #000;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
_x000D_
<h4>Only with CSS</h4>_x000D_
_x000D_
<input type="button" value="Sign In with Facebook" class="btn btn-default sign-in-facebook" style="margin-top:2px; margin-bottom:2px;">_x000D_
_x000D_
<h4>Only with HTML</h4>_x000D_
_x000D_
<button class="btn btn-default">_x000D_
  <img src="http://i.stack.imgur.com/e2S63.png" width="20" /> Sign In with Facebook_x000D_
</button>
_x000D_
_x000D_
_x000D_

Why does ++[[]][+[]]+[+[]] return the string "10"?

Perhaps the shortest possible ways to evaluate an expression into "10" without digits are:

+!+[] + [+[]] // "10"

-~[] + [+[]] // "10"

//========== Explanation ==========\\

+!+[] : +[] Converts to 0. !0 converts to true. +true converts to 1. -~[] = -(-1) which is 1

[+[]] : +[] Converts to 0. [0] is an array with a single element 0.

Then JS evaluates the 1 + [0], thus Number + Array expression. Then the ECMA specification works: + operator converts both operands to a string by calling the toString()/valueOf() functions from the base Object prototype. It operates as an additive function if both operands of an expression are numbers only. The trick is that arrays easily convert their elements into a concatenated string representation.

Some examples:

1 + {} //    "1[object Object]"
1 + [] //    "1"
1 + new Date() //    "1Wed Jun 19 2013 12:13:25 GMT+0400 (Caucasus Standard Time)"

There's a nice exception that two Objects addition results in NaN:

[] + []   //    ""
[1] + [2] //    "12"
{} + {}   //    NaN
{a:1} + {b:2}     //    NaN
[1, {}] + [2, {}] //    "1,[object Object]2,[object Object]"

The type java.util.Map$Entry cannot be resolved. It is indirectly referenced from required .class files

I've seen occasional problems with Eclipse forgetting that built-in classes (including Object and String) exist. The way I've resolved them is to:

  • On the Project menu, turn off "Build Automatically"
  • Quit and restart Eclipse
  • On the Project menu, choose "Clean…" and clean all projects
  • Turn "Build Automatically" back on and let it rebuild everything.

This seems to make Eclipse forget whatever incorrect cached information it had about the available classes.

tsc is not recognized as internal or external command

If you want to run the tsc command from the integrated terminal with the TypeScript module installed locally, you can add the following to your .vscode\settings.json file.

{
  "terminal.integrated.env.windows": { "PATH": "${workspaceFolder}\\node_modules\\.bin;${env:PATH}" }
}

This will prepend the locally installed node module's binary/executable directory (where tsc.cmd is located) to the $env.PATH variable.

How to change the color of a button?

For the text color add:

android:textColor="<hex color>"


For the background color add:

android:background="<hex color>"


From API 21 you can use:

android:backgroundTint="<hex color>"
android:backgroundTintMode="<mode>"

Note: If you're going to work with android/java you really should learn how to google ;)
How to customize different buttons in Android

jQuery: find element by text

You can use the :contains selector to get elements based on their content.

Demo here

_x000D_
_x000D_
$('div:contains("test")').css('background-color', 'red');
_x000D_
<div>This is a test</div>_x000D_
<div>Another Div</div>_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How can I reverse a list in Python?

You could always treat the list like a stack just popping the elements off the top of the stack from the back end of the list. That way you take advantage of first in last out characteristics of a stack. Of course you are consuming the 1st array. I do like this method in that it's pretty intuitive in that you see one list being consumed from the back end while the other is being built from the front end.

>>> l = [1,2,3,4,5,6]; nl=[]
>>> while l:
        nl.append(l.pop())  
>>> print nl
[6, 5, 4, 3, 2, 1]

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

The string has a substring method that returns the string at the specified position.

String name="123456789";
System.out.println(name.substring(0,1));

Ruby on Rails - Import Data from a CSV file

Simpler version of yfeldblum's answer, that is simpler and works well also with large files:

require 'csv'    

CSV.foreach(filename, headers: true) do |row|
  Moulding.create!(row.to_hash)
end

No need for with_indifferent_access or symbolize_keys, and no need to read in the file to a string first.

It doesnt't keep the whole file in memory at once, but reads in line by line and creates a Moulding per line.

forward declaration of a struct in C?

Try this

#include <stdio.h>

struct context;

struct funcptrs{
  void (*func0)(struct context *ctx);
  void (*func1)(void);
};

struct context{
    struct funcptrs fps;
}; 

void func1 (void) { printf( "1\n" ); }
void func0 (struct context *ctx) { printf( "0\n" ); }

void getContext(struct context *con){
    con->fps.func0 = func0;  
    con->fps.func1 = func1;  
}

int main(int argc, char *argv[]){
 struct context c;
   c.fps.func0 = func0;
   c.fps.func1 = func1;
   getContext(&c);
   c.fps.func0(&c);
   getchar();
   return 0;
}

How to avoid HTTP error 429 (Too Many Requests) python

if response.status_code == 429:
  time.sleep(int(response.headers["Retry-After"]))

C++: Print out enum value as text

For this problem, I do a help function like this:

const char* name(Id id) {
    struct Entry {
        Id id;
        const char* name;
    };
    static const Entry entries[] = {
        { ErrorA, "ErrorA" },
        { ErrorB, "ErrorB" },
        { 0, 0 }
    }
    for (int it = 0; it < gui::SiCount; ++it) {
        if (entries[it].id == id) {
            return entries[it].name;
        }
    }
   return 0;
}

Linear search is usually more efficient than std::map for small collections like this.

Get folder name from full file path

Try this

var myFolderName = @"c:\projects\roott\wsdlproj\devlop\beta2\text";
var result = Path.GetFileName(myFolderName);

pandas: multiple conditions while indexing data frame - unexpected behavior

A little mathematical logic theory here:

"NOT a AND NOT b" is the same as "NOT (a OR b)", so:

"a NOT -1 AND b NOT -1" is equivalent of "NOT (a is -1 OR b is -1)", which is opposite (Complement) of "(a is -1 OR b is -1)".

So if you want exact opposite result, df1 and df2 should be as below:

df1 = df[(df.a != -1) & (df.b != -1)]
df2 = df[(df.a == -1) | (df.b == -1)]

How do I print to the debug output window in a Win32 app?

I was looking for a way to do this myself and figured out a simple solution.

I'm assuming that you started a default Win32 Project (Windows application) in Visual Studio, which provides a "WinMain" function. By default, Visual Studio sets the entry point to "SUBSYSTEM:WINDOWS". You need to first change this by going to:

Project -> Properties -> Linker -> System -> Subsystem

And select "Console (/SUBSYSTEM:CONSOLE)" from the drop-down list.

Now, the program will not run, since a "main" function is needed instead of the "WinMain" function.

So now you can add a "main" function like you normally would in C++. After this, to start the GUI program, you can call the "WinMain" function from inside the "main" function.

The starting part of your program should now look something like this:

#include <iostream>

using namespace std;

// Main function for the console
int main(){

    // Calling the wWinMain function to start the GUI program
    // Parameters:
    // GetModuleHandle(NULL) - To get a handle to the current instance
    // NULL - Previous instance is not needed
    // NULL - Command line parameters are not needed
    // 1 - To show the window normally
    wWinMain(GetModuleHandle(NULL), NULL,NULL, 1); 

    system("pause");
    return 0;
}

// Function for entry into GUI program
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
                     _In_opt_ HINSTANCE hPrevInstance,
                     _In_ LPWSTR    lpCmdLine,
                     _In_ int       nCmdShow)
{
    // This will display "Hello World" in the console as soon as the GUI begins.
    cout << "Hello World" << endl;
.
.
.

Result of my implementation

Now you can use functions to output to the console in any part of your GUI program for debugging or other purposes.

WhatsApp API (java/python)

This is the developers page of the Open WhatsApp official page: http://openwhatsapp.org/develop/

You can find a lot of information there about Yowsup.

Or, you can just go the the library's link (which I copied from the Open WhatsApp page anyway): https://github.com/tgalal/yowsup

Enjoy!

npm install hangs

When your ssh key is password protected run ssh-add. npm probably hangs somewhere asking for your password.

Swift - Integer conversion to Hours/Minutes/Seconds

Here is what I use for my Music Player in Swift 4+. I am converting seconds Int to readable String format

extension Int {
    var toAudioString: String {
        let h = self / 3600
        let m = (self % 3600) / 60
        let s = (self % 3600) % 60
        return h > 0 ? String(format: "%1d:%02d:%02d", h, m, s) : String(format: "%1d:%02d", m, s)
    }
}

Use like this:

print(7903.toAudioString)

Output: 2:11:43

Crop image in PHP

$image = imagecreatefromjpeg($_GET['src']);

Needs to be replaced with this:

$image = imagecreatefromjpeg('images/thumbnails/myimage.jpg');

Because imagecreatefromjpeg() is expecting a string.
This worked for me.

ref:
http://php.net/manual/en/function.imagecreatefromjpeg.php

How to fix org.hibernate.LazyInitializationException - could not initialize proxy - no Session

This happened to me when I was already using @Transactional(value=...) and was using multiple transaction managers.

My forms were sending back data that already had @JsonIgnore on them, so the data being sent back from forms was incomplete.

Originally I used the anti pattern solution, but found it was incredibly slow. I disabled this by setting it to false.

spring.jpa.properties.hibernate.enable_lazy_load_no_trans=false

The fix was to ensure that any objects that had lazy-loaded data that weren't loading were retrieved from the database first.

Optional<Object> objectDBOpt = objectRepository.findById(object.getId());

if (objectDBOpt.isEmpty()) {
    // Throw error
} else {
    Object objectFromDB = objectDBOpt.get();
}

In short, if you've tried all of the other answers, just make sure you look back to check you're loading from the database first if you haven't provided all the @JsonIgnore properties and are using them in your database query.

Android Studio Emulator and "Process finished with exit code 0"

I had this issue in Android Studio 3.1 :

I only have on board graphics. Went to Tools -> AVD Manager -> (Edit this AVD) under Actions -> Emulated Performance (Graphics): select "Software GLES 2.0".

How to get "GET" request parameters in JavaScript?

The function here returns the parameter by name. With tiny changes you will be able to return base url, parameter or anchor.

function getUrlParameter(name) {
    var urlOld          = window.location.href.split('?');
    urlOld[1]           = urlOld[1] || '';
    var urlBase         = urlOld[0];
    var urlQuery        = urlOld[1].split('#');
    urlQuery[1]         = urlQuery[1] || '';
    var parametersString = urlQuery[0].split('&');
    if (parametersString.length === 1 && parametersString[0] === '') {
        parametersString = [];
    }
    // console.log(parametersString);
    var anchor          = urlQuery[1] || '';

    var urlParameters = {};
    jQuery.each(parametersString, function (idx, parameterString) {
        paramName   = parameterString.split('=')[0];
        paramValue  = parameterString.split('=')[1];
        urlParameters[paramName] = paramValue;
    });
    return urlParameters[name];
}

Scheduled run of stored procedure on SQL server

If MS SQL Server Express Edition is being used then SQL Server Agent is not available. I found the following worked for all editions:

USE Master
GO

IF  EXISTS( SELECT *
            FROM sys.objects
            WHERE object_id = OBJECT_ID(N'[dbo].[MyBackgroundTask]')
            AND type in (N'P', N'PC'))
    DROP PROCEDURE [dbo].[MyBackgroundTask]
GO

CREATE PROCEDURE MyBackgroundTask
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- The interval between cleanup attempts
    declare @timeToRun nvarchar(50)
    set @timeToRun = '03:33:33'

    while 1 = 1
    begin
        waitfor time @timeToRun
        begin
            execute [MyDatabaseName].[dbo].[MyDatabaseStoredProcedure];
        end
    end
END
GO

-- Run the procedure when the master database starts.
sp_procoption    @ProcName = 'MyBackgroundTask',
                @OptionName = 'startup',
                @OptionValue = 'on'
GO

Some notes:

PHPMailer: SMTP Error: Could not connect to SMTP host

Followed code worked for me:

$mail = new PHPMailer(true);

$mail->isSMTP();// Set mailer to use SMTP
$mail->CharSet = "utf-8";// set charset to utf8
$mail->SMTPAuth = true;// Enable SMTP authentication
$mail->SMTPSecure = 'tls';// Enable TLS encryption, `ssl` also accepted

$mail->Host = 'smtp.gmail.com';// Specify main and backup SMTP servers
$mail->Port = 587;// TCP port to connect to
$mail->SMTPOptions = array(
    'ssl' => array(
        'verify_peer' => false,
        'verify_peer_name' => false,
        'allow_self_signed' => true
    )
);
$mail->isHTML(true);// Set email format to HTML

$mail->Username = 'Sender Email';// SMTP username
$mail->Password = 'Sender Email Password';// SMTP password

$mail->setFrom('[email protected]', 'John Smith');//Your application NAME and EMAIL
$mail->Subject = 'Test';//Message subject
$mail->MsgHTML('HTML code');// Message body
$mail->addAddress('User Email', 'User Name');// Target email


$mail->send();

Create PDF from a list of images

Some changes to make a pdf from the dir where the files are

I take the code and made some slight change to make it useable as it is.

from fpdf import FPDF
from PIL import Image
import os # I added this and the code at the end

def makePdf(pdfFileName, listPages, dir=''):
    if (dir):
        dir += "/"

    cover = Image.open(dir + str(listPages[0]))
    width, height = cover.size

    pdf = FPDF(unit="pt", format=[width, height])

    for page in listPages:
        pdf.add_page()
        pdf.image(dir + str(page), 0, 0)

    pdf.output(dir + pdfFileName + ".pdf", "F")


# this is what I added
x = [f for f in os.listdir() if f.endswith(".jpg")]
y = len(x)

makePdf("file", x)

Angular 2.0 and Modal Dialog

Now available as a NPM package

angular-custom-modal


@Stephen Paul continuation...

  • Angular 2 and up Bootstrap css (animation is preserved)
  • NO JQuery
  • NO bootstrap.js
  • Supports custom modal content
  • Support for multiple modals on top of each other.
  • Moduralized
  • Disable scroll when modal is open
  • Modal gets destroyed when navigating away.
  • Lazy content initialization, which gets ngOnDestroy(ed) when the modal is exited.
  • Parent scrolling disabled when modal is visible

Lazy content initialization

Why?

In some cases you might not want to modal to retain its status after having been closed, but rather restored to the initial state.

Original modal issue

Passing the content straightforward into the view actually generates initializes it even before the modal gets it. The modal doesn't have a way to kill such content even if using a *ngIf wrapper.

Solution

ng-template. ng-template doesn't render until ordered to do so.

my-component.module.ts

...
imports: [
  ...
  ModalModule
]

my-component.ts

<button (click)="reuseModal.open()">Open</button>
<app-modal #reuseModal>
  <ng-template #header></ng-template>
  <ng-template #body>
    <app-my-body-component>
      <!-- This component will be created only when modal is visible and will be destroyed when it's not. -->
    </app-my-body-content>
    <ng-template #footer></ng-template>
</app-modal>

modal.component.ts

export class ModalComponent ... {
  @ContentChild('header') header: TemplateRef<any>;
  @ContentChild('body') body: TemplateRef<any>;
  @ContentChild('footer') footer: TemplateRef<any>;
 ...
}

modal.component.html

<div ... *ngIf="visible">
  ...
  <div class="modal-body">
    ng-container *ngTemplateOutlet="body"></ng-container>
  </div>

References

I have to say that it wouldn't have been possible without the excellent official and community documentation around the net. It might help some of you too to understand better how ng-template, *ngTemplateOutlet and @ContentChild work.

https://angular.io/api/common/NgTemplateOutlet
https://blog.angular-university.io/angular-ng-template-ng-container-ngtemplateoutlet/
https://medium.com/claritydesignsystem/ng-content-the-hidden-docs-96a29d70d11b
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e
https://netbasal.com/understanding-viewchildren-contentchildren-and-querylist-in-angular-896b0c689f6e

Full copy-paste solution

modal.component.html

<div
  (click)="onContainerClicked($event)"
  class="modal fade"
  tabindex="-1"
  [ngClass]="{'in': visibleAnimate}"
  [ngStyle]="{'display': visible ? 'block' : 'none', 'opacity': visibleAnimate ? 1 : 0}"
  *ngIf="visible">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <ng-container *ngTemplateOutlet="header"></ng-container>
        <button class="close" data-dismiss="modal" type="button" aria-label="Close" (click)="close()">×</button>
      </div>
      <div class="modal-body">
        <ng-container *ngTemplateOutlet="body"></ng-container>
      </div>
      <div class="modal-footer">
        <ng-container *ngTemplateOutlet="footer"></ng-container>
      </div>
    </div>
  </div>
</div>

modal.component.ts

/**
 * @Stephen Paul https://stackoverflow.com/a/40144809/2013580
 * @zurfyx https://stackoverflow.com/a/46949848/2013580
 */
import { Component, OnDestroy, ContentChild, TemplateRef } from '@angular/core';

@Component({
  selector: 'app-modal',
  templateUrl: 'modal.component.html',
  styleUrls: ['modal.component.scss'],
})
export class ModalComponent implements OnDestroy {
  @ContentChild('header') header: TemplateRef<any>;
  @ContentChild('body') body: TemplateRef<any>;
  @ContentChild('footer') footer: TemplateRef<any>;

  public visible = false;
  public visibleAnimate = false;

  ngOnDestroy() {
    // Prevent modal from not executing its closing actions if the user navigated away (for example,
    // through a link).
    this.close();
  }

  open(): void {
    document.body.style.overflow = 'hidden';

    this.visible = true;
    setTimeout(() => this.visibleAnimate = true, 200);
  }

  close(): void {
    document.body.style.overflow = 'auto';

    this.visibleAnimate = false;
    setTimeout(() => this.visible = false, 100);
  }

  onContainerClicked(event: MouseEvent): void {
    if ((<HTMLElement>event.target).classList.contains('modal')) {
      this.close();
    }
  }
}

modal.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import { ModalComponent } from './modal.component';

@NgModule({
  imports: [
    CommonModule,
  ],
  exports: [ModalComponent],
  declarations: [ModalComponent],
  providers: [],
})
export class ModalModule { }

Table-level backup

Every recovery model lets you back up a whole or partial SQL Server database or individual files or filegroups of the database. Table-level backups cannot be created.

From: Backup Overview (SQL Server)

Eclipse C++: Symbol 'std' could not be resolved

This worked for me on Eclipse IDE for C/C++ Developers Version: 2020-03 (4.15.0) Build id: 20200313-1211. Also, my code is cross-compiled.

  1. Create a new project making sure it's created as a cross-compiled solution. You have to add the /usr/bin directory that matches your cross-compiler location.
  2. Add the C and C++ headers for the cross-compiler in the Project Properties.
  3. For C: Project > Properties > C/C++ General > Paths and Symbols > Includes > GNU C. Add... -> The path to your /usr/include directory from your cross-compiler.
  4. For C++: Project > Properties > C/C++ General > Paths and Symbols > Includes > GNU C++. Add... -> The path to your /usr/include/c++/ directory from your cross-compiler.
  5. If you don't know your gcc version, type this in a console (make sure it's your cross gcc binary):

    gcc -v

  6. Modify the dialect for the cross-compilers (this was the trick).

  7. For C: Project > Properties > C/C++ Build > Settings > Tool Settings > Cross GCC Compiler > Dialect. Set to ISO C99 (-std=C99) or whatever fits your C files standard.
  8. For C++: Project > Properties > C/C++ Build > Settings > Tool Settings > Cross G++ Compiler > Dialect. Set to ISO C++14 (-std=c++14) or whatever fits your C++ files standard.
  9. If needed, re-index all your project by right-clicking the project > Index > Rebuild.

How do I create a new Git branch from an old commit?

git checkout -b NEW_BRANCH_NAME COMMIT_ID

This will create a new branch called 'NEW_BRANCH_NAME' and check it out.

("check out" means "to switch to the branch")

git branch NEW_BRANCH_NAME COMMIT_ID

This just creates the new branch without checking it out.


in the comments many people seem to prefer doing this in two steps. here's how to do so in two steps:

git checkout COMMIT_ID
# you are now in the "detached head" state
git checkout -b NEW_BRANCH_NAME

Javascript - Get Image height

My preferred solution for this would be to do the resizing server-side, so you are transmitting less unnecessary data.

If you have to do it client-side though, and need to keep the image ratio, you could use the below:

var image_from_ajax = new Image();
image_from_ajax.src = fetch_image_from_ajax(); // Downloaded via ajax call?

image_from_ajax = rescaleImage(image_from_ajax);

// Rescale the given image to a max of max_height and max_width
function rescaleImage(image_name)
{
    var max_height = 100;
    var max_width = 100;

    var height = image_name.height;
    var width = image_name.width;
    var ratio = height/width;

    // If height or width are too large, they need to be scaled down
    // Multiply height and width by the same value to keep ratio constant
    if(height > max_height)
    {
        ratio = max_height / height;
        height = height * ratio;
        width = width * ratio;
    }

    if(width > max_width)
    {
        ratio = max_width / width;
        height = height * ratio;
        width = width * ratio;
    }

    image_name.width = width;
    image_name.height = height;
    return image_name;
}

What should I do if the current ASP.NET session is null?

ASP.NET Technical Articles

SUMMARY: In ASP.NET, every Web page derives from the System.Web.UI.Page class. The Page class aggregates an instance of the HttpSession object for session data. The Page class exposes different events and methods for customization. In particular, the OnInit method is used to set the initialize state of the Page object. If the request does not have the Session cookie, a new Session cookie will be issued to the requester.

EDIT:

Session: A Concept for Beginners

SUMMARY: Session is created when user sends a first request to the server for any page in the web application, the application creates the Session and sends the Session ID back to the user with the response and is stored in the client machine as a small cookie. So ideally the "machine that has disabled the cookies, session information will not be stored".

How to set the max size of upload file

More specifically, in your application.yml configuration file, add the following to the "spring:" section.

http:
    multipart:
        max-file-size: 512MB
        max-request-size: 512MB

Whitespace is important and you cannot use tabs for indentation.

Java Inheritance - calling superclass method

You can't call alpha's alphaMethod1() by using beta's object But you have two solutions:

solution 1: call alpha's alphaMethod1() from beta's alphaMethod1()

class Beta extends Alpha
{
  public void alphaMethod1()
  {
    super.alphaMethod1();
  }
}

or from any other method of Beta like:

class Beta extends Alpha
{
  public void foo()
  {
     super.alphaMethod1();
  }
}

class Test extends Beta 
{
   public static void main(String[] args)
   {
      Beta beta = new Beta();
      beta.foo();
   }
}

solution 2: create alpha's object and call alpha's alphaMethod1()

class Test extends Beta
{
   public static void main(String[] args)
   {
      Alpha alpha = new Alpha();
      alpha.alphaMethod1();
   }
}

Display Images Inline via CSS

You have a line break <br> in-between the second and third images in your markup. Get rid of that, and it'll show inline.

Convert Text to Date?

You can quickly convert a column of text that resembles dates into actual dates with the VBA equivalent of the worksheet's Data ? Text-to-Columns command.

With ActiveSheet.UsedRange.Columns("A").Cells
    .TextToColumns Destination:=.Cells(1), DataType:=xlFixedWidth, FieldInfo:=Array(0, xlYMDFormat)
    .NumberFormat = "yyyy-mm-dd"   'change to any date-based number format you prefer the cells to display
End With

Bulk operations are generally much quicker than looping through cells and the VBA's Range.TextToColumns method is very quick. It also allows you the freedom to set a MDY vs. DMY or YMD conversion mask that plagues many text imports where the date format does not match the system's regional settings. See TextFileColumnDataTypes property for a complete list of the available date formats available.

Caveat: Be careful when importing text that some of the dates have not already been converted. A text-based date with ambiguous month and day integers may already been converted wrongly; e.g. 07/11/2015 may have been interpreted as 07-Nov-2015 or 11-Jul-2015 depending upon system regional settings. In cases like this, abandon the import and bring the text back in with Data ? Get External Data ? From Text and specify the correct date conversion mask in the Text Import wizard. In VBA, use the Workbooks.OpenText method and specify the xlColumnDataType.

Get GPS location via a service in Android

ok , i've solved it by creating a handler on the onCreate of the service , and calling the gps functions through there .

The code is as simple as this:

final handler=new Handler(Looper.getMainLooper()); 

And then to force running things on the UI, I call post on it.

What are the most common font-sizes for H1-H6 tags

Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.

Storing a file in a database as opposed to the file system?

I agree with @ZombieSheep. Just one more thing - I generally don't think that databases actually need be portable because you miss all the features your DBMS vendor provides. I think that migrating to another database would be the last thing one would consider. Just my $.02

The listener supports no services

Check local_listener definition in your spfile or pfile. In my case, the problem was with pfile, I had moved the pfile from a similar environment and it had LISTENER_sid as LISTENER and not just LISTENER.

Android error: Failed to install *.apk on device *: timeout

Try changing the ADB connection timeout. I think it defaults that to 5000ms and I changed mine to 10000ms to get rid of that problem.

If you are in Eclipse, you can do this by going through

Window -> Preferences -> Android -> DDMS -> ADB Connection Timeout (ms)

C convert floating point to int

Good guestion! -- where I have not yet found a satisfying answer for my case, the answer I provide here works for me, but may not be future proof...

If one uses gcc (clang?) and have -Werror and -Wbad-function-cast defined,

int val = (int)pow(10,9);

will result:

error: cast from function call of type 'double' to non-matching type 'int' [-Werror=bad-function-cast]

(for a good reason, overflow and where values are rounded needs to be thought out)

EDIT: 2020-08-30: So, my use case casting the value from function returning double to int, and chose pow() to represent that in place of a private function somewhere. Then I sidestepped thinking pow() more. (See comments more why pow() used below could be problematic...).

After properly thought out (that parameters to pow() are good), int val = pow(10,9); seems to work with gcc 9.2 x86-64 ...

but note:

printf("%d\n", pow(10,4));

may output e.g.

-1121380856

(did for me) where

int i = pow(10,4); printf("%d\n", i);

printed

10000

in one particular case I tried.

"Could not find or load main class" Error while running java program using cmd prompt

I was facing similar issue but it was due to space character in my file directory where I kept my java class.

Scenario given below along with solution:

   public class Sample{
      public static void main(String[] args) {
        System.out.println("Hello world, Java");
      }
}
  • My Sample.java class was kept at Dir "D:\Java Programs\Sample.java"[NOTE: Package statement not present in java class].
  • In command prompt, changed directory to "D:\Java Programs\", my programmed compiled but failed to run with error "Could not find or load main class"
  • After all the possible solutions over SOF(nothing worked), I realized may b space causing me this issue.
  • Surprisingly removal of folder name space char['Java Programs' -> 'JavaPrograms'], my program executed successfully.

    Hope it helps

How to format a phone number with jQuery

Use a library to handle phone number. Libphonenumber by Google is your best bet.

// Require `PhoneNumberFormat`.
var PNF = require('google-libphonenumber').PhoneNumberFormat;

// Get an instance of `PhoneNumberUtil`.
var phoneUtil = require('google-libphonenumber').PhoneNumberUtil.getInstance();

// Parse number with country code.
var phoneNumber = phoneUtil.parse('202-456-1414', 'US');

// Print number in the international format.
console.log(phoneUtil.format(phoneNumber, PNF.INTERNATIONAL));
// => +1 202-456-1414

I recommend to use this package by seegno.

How do I count a JavaScript object's attributes?

For those which will read this question/answers, here is a JavaScript implementation of Dictionary collection very similar as functionality as .NET one: JavaScript Dictionary

An implementation of the fast Fourier transform (FFT) in C#

The guy that did AForge did a fairly good job but it's not commercial quality. It's great to learn from but you can tell he was learning too so he has some pretty serious mistakes like assuming the size of an image instead of using the correct bits per pixel.

I'm not knocking the guy, I respect the heck out of him for learning all that and show us how to do it. I think he's a Ph.D now or at least he's about to be so he's really smart it's just not a commercially usable library.

The Math.Net library has its own weirdness when working with Fourier transforms and complex images/numbers. Like, if I'm not mistaken, it outputs the Fourier transform in human viewable format which is nice for humans if you want to look at a picture of the transform but it's not so good when you are expecting the data to be in a certain format (the normal format). I could be mistaken about that but I just remember there was some weirdness so I actually went to the original code they used for the Fourier stuff and it worked much better. (ExocortexDSP v1.2 http://www.exocortex.org/dsp/)

Math.net also had some other funkyness I didn't like when dealing with the data from the FFT, I can't remember what it was I just know it was much easier to get what I wanted out of the ExoCortex DSP library. I'm not a mathematician or engineer though; to those guys it might make perfect sense.

So! I use the FFT code yanked from ExoCortex, which Math.Net is based on, without anything else and it works great.

And finally, I know it's not C#, but I've started looking at using FFTW (http://www.fftw.org/). And this guy already made a C# wrapper so I was going to check it out but haven't actually used it yet. (http://www.sdss.jhu.edu/~tamas/bytes/fftwcsharp.html)

OH! I don't know if you are doing this for school or work but either way there is a GREAT free lecture series given by a Stanford professor on iTunes University.

https://podcasts.apple.com/us/podcast/the-fourier-transforms-and-its-applications/id384232849

Regular expression for validating names and surnames?

I'll try to give a proper answer myself:

The only punctuations that should be allowed in a name are full stop, apostrophe and hyphen. I haven't seen any other case in the list of corner cases.

Regarding numbers, there's only one case with an 8. I think I can safely disallow that.

Regarding letters, any letter is valid.

I also want to include space.

This would sum up to this regex:

^[\p{L} \.'\-]+$

This presents one problem, i.e. the apostrophe can be used as an attack vector. It should be encoded.

So the validation code should be something like this (untested):

var name = nameParam.Trim();
if (!Regex.IsMatch(name, "^[\p{L} \.\-]+$")) 
    throw new ArgumentException("nameParam");
name = name.Replace("'", "&#39;");  //&apos; does not work in IE

Can anyone think of a reason why a name should not pass this test or a XSS or SQL Injection that could pass?


complete tested solution

using System;
using System.Text.RegularExpressions;

namespace test
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            var names = new string[]{"Hello World", 
                "John",
                "João",
                "???",
                "???",
                "??",
                "??",
                "??????",
                "Te???e?a",
                "?????????",
                "???? ?????",
                "?????????",
                "??????",
                "?",
                "D'Addario",
                "John-Doe",
                "P.A.M.",
                "' --",
                "<xss>",
                "\""
            };
            foreach (var nameParam in names)
            {
                Console.Write(nameParam+" ");
                var name = nameParam.Trim();
                if (!Regex.IsMatch(name, @"^[\p{L}\p{M}' \.\-]+$"))
                {
                    Console.WriteLine("fail");
                    continue;
                }
                name = name.Replace("'", "&#39;");
                Console.WriteLine(name);
            }
        }
    }
}

Multiple line comment in Python

#Single line

'''
multi-line
comment
'''

"""
also, 
multi-line comment
"""

LEFT function in Oracle

LEFT is not a function in Oracle. This probably came from someone familiar with SQL Server:

Returns the left part of a character string with the specified number of characters.

-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse  
LEFT ( character_expression , integer_expression )  

How to fix broken paste clipboard in VNC on Windows

You likely need to re-start VNC on both ends. i.e. when you say "restarted VNC", you probably just mean the client. But what about the other end? You likely need to re-start that end too. The root cause is likely a conflict. Many apps spy on the clipboard when they shouldn't. And many apps are not forgiving when they go to open the clipboard and can't. Robust ones will retry, others will simply not anticipate a failure and then they get fouled up and need to be restarted. Could be VNC, or it could be another app that's "listening" to the clipboard viewer chain, where it is obligated to pass along notifications to the other apps in the chain. If the notifications aren't sent, then VNC may not even know that there has been a clipboard update.

Datatables warning(table id = 'example'): cannot reinitialise data table

This problem occurs if we initialize dataTable more than once.Then we have to remove the previous.

On the other hand we can destroy the old datatable in this way also before creating the new datatable use the following code :

$(“#example”).dataTable().fnDestroy();

There is an another scenario ,say you send more than one ajax request which response will access same table in same template then we will get error also.In this case fnDestroy method doesn’t work properly because you don’t know which response comes first or later.Then you have to set bRetrieve TRUE in data table configuration.That’s it.

This is My senario:

<script type="text/javascript">

$(document).ready(function () {

        $('#DatatableNone').dataTable({
            "bDestroy": true
        }).fnDestroy();

        $('#DatatableOne').dataTable({
            "aoColumnDefs": [{
                "bSortable": false,
                "aTargets": ["sorting_disabled"]
            }],
            "bDestroy": true
        }).fnDestroy();

});

</script>

How do I format axis number format to thousands with a comma in matplotlib?

You can use matplotlib.ticker.funcformatter

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as tkr


def func(x, pos):  # formatter function takes tick label and tick position
    s = '%d' % x
    groups = []
    while s and s[-1].isdigit():
        groups.append(s[-3:])
        s = s[:-3]
    return s + ','.join(reversed(groups))

y_format = tkr.FuncFormatter(func)  # make formatter

x = np.linspace(0,10,501)
y = 1000000*np.sin(x)
ax = plt.subplot(111)
ax.plot(x,y)
ax.yaxis.set_major_formatter(y_format)  # set formatter to needed axis

plt.show()

enter image description here

Creating a system overlay window (always on top)

Starting with Android 4.x, Android team fixed a potential security problem by adding a new function adjustWindowParamsLw() in which it will add FLAG_NOT_FOCUSABLE, FLAG_NOT_TOUCHABLE and remove FLAG_WATCH_OUTSIDE_TOUCH flags for TYPE_SYSTEM_OVERLAY windows.

That is, a TYPE_SYSTEM_OVERLAY window won't receive any touch event on ICS platform and, of course, to use TYPE_SYSTEM_OVERLAY is not a workable solution for ICS and future devices.

Is there a goto statement in Java?

They are reserved for future use (see: Java Language Keywords)

The keywords const and goto are reserved, even though they are not currently used.

The reason why there is no goto statement in Java can be found in "The Java Language Environment":

Java has no goto statement. Studies illustrated that goto is (mis)used more often than not simply "because it's there". Eliminating goto led to a simplification of the language--there are no rules about the effects of a goto into the middle of a for statement, for example. Studies on approximately 100,000 lines of C code determined that roughly 90 percent of the goto statements were used purely to obtain the effect of breaking out of nested loops. As mentioned above, multi-level break and continue remove most of the need for goto statements.

How to trigger ngClick programmatically

Simple sample:

HTML

<div id='player'>
    <div id="my-button" ng-click="someFuntion()">Someone</div>
</div>

JavaScript

$timeout(function() {
    angular.element('#my-button').triggerHandler('click');
}, 0);

What this does is look for the button's id and perform a click action. Voila.

Source: https://techiedan.com/angularjs-how-to-trigger-click/

Animate visibility modes, GONE and VISIBLE

Well there is a very easy way, but just setting android:animateLayoutChanges="true" will not work. You need to enableTransitionType in you activity. Check this link for more info: http://www.thecodecity.com/2018/03/android-animation-on-view-visibility.html

How to fix Terminal not loading ~/.bashrc on OS X Lion

I have the following in my ~/.bash_profile:

if [ -f ~/.bashrc ]; then . ~/.bashrc; fi

If I had .bashrc instead of ~/.bashrc, I'd be seeing the same symptom you're seeing.

Removing items from a ListBox in VB.net

There is a simple method for deleting selected items, and all these people are going for a hard method:

lstYOURVARIABLE.Items.Remove(lstYOURVARIABLE.SelectedItem)

I used this in Visual Basic mode on Visual Studio.

How to get a product's image in Magento?

You can try to replace $this-> by Mage:: in some cases. You need to convert to string.

In my case i'm using DirectResize extension (direct link), so my code is like this:

(string)Mage::helper('catalog/image')->init($_product, 'image')->directResize(150,150,3)

The ratio options (3rd param) are :

  • none proportional. The image will be resized at the Width and Height values.
  • proportional, based on the Width value 2
  • proportional, based on the Height value 3
  • proportional for the new image can fit in the Width and the Height values. 4
  • proportional. The new image will cover an area with the Width and the Height values.

Update: other info and versions here


The common way, without plugin would be:

(string)Mage::helper('catalog/image')->init($_product, 'image')->resize(150)

You can replace 'image' with 'small_image' or 'thumbnail'.

R: += (plus equals) and ++ (plus plus) equivalent from c++/c#/java, etc.?

Following @GregaKešpret you can make an infix operator:

`%+=%` = function(e1,e2) eval.parent(substitute(e1 <- e1 + e2))
x = 1
x %+=% 2 ; x

Is there an easy way to add a border to the top and bottom of an Android View?

In android 2.2 you could do the following.

Create an xml drawable such as /res/drawable/textlines.xml and assign this as a TextView's background property.

<TextView
android:text="My text with lines above and below"
android:background="@drawable/textlines"
/>

/res/drawable/textlines.xml

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
      <shape 
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#FF000000" />
            <solid android:color="#FFDDDDDD" />

        </shape>
   </item>

   <item android:top="1dp" android:bottom="1dp"> 
      <shape 
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#FFDDDDDD" />
            <solid android:color="#00000000" />
        </shape>
   </item>

</layer-list>

The down side to this is that you have to specify an opaque background colour, as transparencies won't work. (At least i thought they did but i was mistaken). In the above example you can see that the solid colour of the first shape #FFdddddd is copied in the 2nd shapes stroke colour.

CodeIgniter Disallowed Key Characters

Took a while to figure this one out. Seems most of us missed the obvious error…the last “-” is not escaped.

Adding the . and | as I’ve seen other suggest may work for you, but the regex was supposed to be:

if ( ! preg_match("/^[a-z0-9:_\/\-\.|]+$/i", $str))  

How to subtract X days from a date using Java calendar?

Anson's answer will work fine for the simple case, but if you're going to do any more complex date calculations I'd recommend checking out Joda Time. It will make your life much easier.

FYI in Joda Time you could do

DateTime dt = new DateTime();
DateTime fiveDaysEarlier = dt.minusDays(5);

How to run only one unit test class using Gradle

Below is the command to run a single test class using gradlew command line option:

gradlew.bat Connected**your bundleVariant**AndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.example.TestClass

Below example to run class com.example.TestClass with variant Variant_1:

gradlew.bat ConnectedVariant_1AndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.example.TestClass 

optional parameters in SQL Server stored proc?

Yes, it is. Declare parameter as so:

@Sort varchar(50) = NULL

Now you don't even have to pass the parameter in. It will default to NULL (or whatever you choose to default to).

fatal: could not create work tree dir 'kivy'

You should do the command in a directory where you have write permission. So:

cd ~/
mkdir code
cd code
git clone https://github.com/kivy/kivy

For example.

How do you convert a jQuery object into a string?

The accepted answer doesn't cover text nodes (undefined is printed out).

This code snippet solves it:

_x000D_
_x000D_
var htmlElements = $('<p><a href="http://google.com">google</a></p>??<p><a href="http://bing.com">bing</a></p>'),_x000D_
    htmlString = '';_x000D_
    _x000D_
htmlElements.each(function () {_x000D_
    var element = $(this).get(0);_x000D_
_x000D_
    if (element.nodeType === Node.ELEMENT_NODE) {_x000D_
        htmlString += element.outerHTML;_x000D_
    }_x000D_
    else if (element.nodeType === Node.TEXT_NODE) {_x000D_
        htmlString += element.nodeValue;_x000D_
    }_x000D_
});_x000D_
_x000D_
alert('String html: ' + htmlString);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Spark DataFrame TimestampType - how to get Year, Month, Day values from field?

Actually, we really do not need to import any python library. We can separate the year, month, date using simple SQL. See the below example,

+----------+
|       _c0|
+----------+
|1872-11-30|
|1873-03-08|
|1874-03-07|
|1875-03-06|
|1876-03-04|
|1876-03-25|
|1877-03-03|
|1877-03-05|
|1878-03-02|
|1878-03-23|
|1879-01-18|

I have a date column in my data frame which contains the date, month and year and assume I want to extract only the year from the column.

df.createOrReplaceTempView("res")
sqlDF = spark.sql("SELECT EXTRACT(year from `_c0`) FROM res ")

Here I'm creating a temporary view and store the year values using this single line and the output will be,

+-----------------------+
|year(CAST(_c0 AS DATE))|
+-----------------------+
|                   1872|
|                   1873|
|                   1874|
|                   1875|
|                   1876|
|                   1876|
|                   1877|
|                   1877|
|                   1878|
|                   1878|
|                   1879|
|                   1879|
|                   1879|

How to sort List of objects by some property

We can sort the list in one of two ways:

1. Using Comparator : When required to use the sort logic in multiple places If you want to use the sorting logic in a single place, then you can write an anonymous inner class as follows, or else extract the comparator and use it in multiple places

  Collections.sort(arrayList, new Comparator<ActiveAlarm>() {
        public int compare(ActiveAlarm o1, ActiveAlarm o2) {
            //Sorts by 'TimeStarted' property
            return o1.getTimeStarted()<o2.getTimeStarted()?-1:o1.getTimeStarted()>o2.getTimeStarted()?1:doSecodaryOrderSort(o1,o2);
        }

        //If 'TimeStarted' property is equal sorts by 'TimeEnded' property
        public int doSecodaryOrderSort(ActiveAlarm o1,ActiveAlarm o2) {
            return o1.getTimeEnded()<o2.getTimeEnded()?-1:o1.getTimeEnded()>o2.getTimeEnded()?1:0;
        }
    });

We can have null check for the properties, if we could have used 'Long' instead of 'long'.

2. Using Comparable(natural ordering): If sort algorithm always stick to one property: write a class that implements 'Comparable' and override 'compareTo' method as defined below

class ActiveAlarm implements Comparable<ActiveAlarm>{

public long timeStarted;
public long timeEnded;
private String name = "";
private String description = "";
private String event;
private boolean live = false;

public ActiveAlarm(long timeStarted,long timeEnded) {
    this.timeStarted=timeStarted;
    this.timeEnded=timeEnded;
}

public long getTimeStarted() {
    return timeStarted;
}

public long getTimeEnded() {
    return timeEnded;
}

public int compareTo(ActiveAlarm o) {
    return timeStarted<o.getTimeStarted()?-1:timeStarted>o.getTimeStarted()?1:doSecodaryOrderSort(o);
}

public int doSecodaryOrderSort(ActiveAlarm o) {
    return timeEnded<o.getTimeEnded()?-1:timeEnded>o.getTimeEnded()?1:0;
}

}

call sort method to sort based on natural ordering

Collections.sort(list);

Slack URL to open a channel from browser

When I tried yorammi's solution I was taken to Slack, but not the channel I specified.

I had better luck with:

https://<organization>.slack.com/messages/#<channel>/

and

https://<organization>.slack.com/messages/<channel>/details/

Although, they were both still displayed in a browser window and not the app.

How to make (link)button function as hyperlink?

you can use linkbutton for navigating to another section in the same page by using PostBackUrl="#Section2"

Calculate difference between two dates (number of days)?

Get the difference between the two dates and then get the days from:

int total_days = (EndDate - StartDate).TotalDays

How to loop an object in React?

You can use map function

{Object.keys(tifs).map(key => (
    <option value={key}>{tifs[key]}</option>
))}

File name without extension name VBA

Answer is here: I think this answer is good, please try it http://mariaevert.dk/vba/?p=162

Getting all file names from a folder using C#

DirectoryInfo d = new DirectoryInfo(@"D:\Test");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";
foreach(FileInfo file in Files )
{
  str = str + ", " + file.Name;
}

Hope this will help...

How to repair COMException error 80040154?

To find the DLL, go to your 64-bit machine and open the registry. Find the key called HKEY_CLASSES_ROOT\CLSID\{681EF637-F129-4AE9-94BB-618937E3F6B6}\InprocServer32. This key will have the filename of the DLL as its default value.

If you solved the problem on your 64-bit machine by recompiling your project for x86, then you'll need to look in the 32-bit portion of the registry instead of in the normal place. This is HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Classes\CLSID\{681EF637-F129-4AE9-94BB-618937E3F6B6}\InprocServer32.

If the DLL is built for 32 bits then you can use it directly on your 32-bit machine. If it's built for 64 bits then you'll have to contact the vendor and get a 32-bit version from them.

When you have the DLL, register it by running c:\windows\system32\regsvr32.exe.

Simplest way to restart service on a remote computer

If it doesn't require human interaction which means there will be no UI that invokes this operation and I assume it would restart at some set interval? If you have access to machine, you could just set a scheduled task to execute a batch file using good old NET STOP and NET START

net stop "DNS Client"
net start "DNS client"

or if you want to get a little more sophisticated, you could try Powershell

AngularJS $watch window resize inside directive

You can listen resize event and fire where some dimension change

directive

(function() {
'use strict';

    angular
    .module('myApp.directives')
    .directive('resize', ['$window', function ($window) {
        return {
            link: link,
            restrict: 'A'
        };

        function link(scope, element, attrs){
            scope.width = $window.innerWidth;
            function onResize(){
                // uncomment for only fire when $window.innerWidth change   
                // if (scope.width !== $window.innerWidth)
                {
                    scope.width = $window.innerWidth;
                    scope.$digest();
                }
            };

            function cleanUp() {
                angular.element($window).off('resize', onResize);
            }

            angular.element($window).on('resize', onResize);
            scope.$on('$destroy', cleanUp);
        }
    }]);
})();

In html

<div class="row" resize> ,
    <div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod"> 
        <h4 ng-bind="::v.known_as"></h4>
    </div> 
</div> 

Controller :

$scope.$watch('width', function(old, newv){
     console.log(old, newv);
 })

Getting a timestamp for today at midnight?

$today_at_midnight = strtotime(date("Ymd"));

should give you what you're after.

explanation

What I did was use PHP's date function to get today's date without any references to time, and then pass it to the 'string to time' function which converts a date and time to a epoch timestamp. If it doesn't get a time, it assumes the first second of that day.

References: Date Function: http://php.net/manual/en/function.date.php

String To Time: http://us2.php.net/manual/en/function.strtotime.php

Postgresql tables exists, but getting "relation does not exist" when querying

The error can be caused by access restrictions. Solution:

GRANT ALL PRIVILEGES ON DATABASE my_database TO my_user;

How do I specify new lines on Python, when writing on files?

Platform independent line breaker: Linux,windows & IOS

import os
keyword = 'physical'+ os.linesep + 'distancing'
print(keyword)

Output:

physical
distancing

How using try catch for exception handling is best practice

The second approach is a good one.

If you don't want to show the error and confuse the user of application by showing runtime exception(i.e. error) which is not related to them, then just log error and the technical team can look for the issue and resolve it.

try
{
  //do some work
}
catch(Exception exception)
{
   WriteException2LogFile(exception);//it will write the or log the error in a text file
}

I recommend that you go for the second approach for your whole application.

SQL Server - after insert trigger - update another column in the same table

create or replace 
TRIGGER triggername BEFORE INSERT  ON 
table FOR EACH ROW 
BEGIN
/*
Write any select condition if you want to get the data from other tables
*/
:NEW.COLUMNA:= UPPER(COLUMNA); 
--:NEW.COUMNa:= NULL;
END; 

The above trigger will update the column value before inserting. For example if we give the value of COLUMNA as null it will update the column as null for each insert statement.

How to tell if a <script> tag failed to load

To check if the javascript in nonexistant.js returned no error you have to add a variable inside http://fail.org/nonexistant.js like var isExecuted = true; and then check if it exists when the script tag is loaded.

However if you only want to check that the nonexistant.js returned without a 404 (meaning it exists), you can try with a isLoaded variable ...

var isExecuted = false;
var isLoaded = false;
script_tag.onload = script_tag.onreadystatechange = function() {
    if(!this.readyState ||
        this.readyState == "loaded" || this.readyState == "complete") {
        // script successfully loaded
        isLoaded = true;

        if(isExecuted) // no error
    }
}

This will cover both cases.

How to permanently export a variable in Linux?

On Ubuntu systems, use the following locations:

  1. System-wide persistent variables in the format of JAVA_PATH=/usr/local/java store in

    /etc/environment
    
  2. System-wide persistent variables that reference variables such as
    export PATH="$JAVA_PATH:$PATH" store in

    /etc/.bashrc
    
  3. User specific persistent variables in the format of PATH DEFAULT=/usr/bin:usr/local/bin store in

    ~/.pam_environment
    

For more details on #2, check this Ask Ubuntu answer. NOTE: #3 is the Ubuntu recommendation but may have security concerns in the real world.

How to list only top level directories in Python?

You could also use os.scandir:

with os.scandir(os.getcwd()) as mydir:
    dirs = [i.name for i in mydir if i.is_dir()]

In case you want the full path you can use i.path.

Using scandir() instead of listdir() can significantly increase the performance of code that also needs file type or file attribute information, because os.DirEntry objects expose this information if the operating system provides it when scanning a directory.

JS Client-Side Exif Orientation: Rotate and Mirror JPEG Images

I created a class wrapped in an ES6 module that solves exactly this.

It's 103 lines, no dependencies, and fairly nicely structured and documented, meant to be easy to modify/reuse.

Handles all 8 possible orientations, and is Promise-based.

Here you go, hope this still helps someone: https://gist.github.com/vdavid/3f9b66b60f52204317a4cc0e77097913

How do I escape a reserved word in Oracle?

you have to rename the column to an other name because TABLE is reserved by Oracle.

You can see all reserved words of Oracle in the oracle view V$RESERVED_WORDS.

Is it a bad practice to use an if-statement without curly braces?

The problem with the first version is that if you go back and add a second statement to the if or else clauses without remembering to add the curly braces, your code will break in unexpected and amusing ways.

Maintainability-wise, it's always smarter to use the second form.

EDIT: Ned points this out in the comments, but it's worth linking to here, too, I think. This is not just some ivory-tower hypothetical bullshit: https://www.imperialviolet.org/2014/02/22/applebug.html

How to limit the maximum value of a numeric field in a Django model?

You could also create a custom model field type - see http://docs.djangoproject.com/en/dev/howto/custom-model-fields/#howto-custom-model-fields

In this case, you could 'inherit' from the built-in IntegerField and override its validation logic.

The more I think about this, I realize how useful this would be for many Django apps. Perhaps a IntegerRangeField type could be submitted as a patch for the Django devs to consider adding to trunk.

This is working for me:

from django.db import models

class IntegerRangeField(models.IntegerField):
    def __init__(self, verbose_name=None, name=None, min_value=None, max_value=None, **kwargs):
        self.min_value, self.max_value = min_value, max_value
        models.IntegerField.__init__(self, verbose_name, name, **kwargs)
    def formfield(self, **kwargs):
        defaults = {'min_value': self.min_value, 'max_value':self.max_value}
        defaults.update(kwargs)
        return super(IntegerRangeField, self).formfield(**defaults)

Then in your model class, you would use it like this (field being the module where you put the above code):

size = fields.IntegerRangeField(min_value=1, max_value=50)

OR for a range of negative and positive (like an oscillator range):

size = fields.IntegerRangeField(min_value=-100, max_value=100)

What would be really cool is if it could be called with the range operator like this:

size = fields.IntegerRangeField(range(1, 50))

But, that would require a lot more code since since you can specify a 'skip' parameter - range(1, 50, 2) - Interesting idea though...

OpenCV & Python - Image too big to display

Try with this code:

from PIL import Image

Image.fromarray(image).show()

GridView sorting: SortDirection always Ascending

In vb.net but very simple!

Protected Sub grTicketHistory_Sorting(sender As Object, e As GridViewSortEventArgs) Handles grTicketHistory.Sorting

    Dim dt As DataTable = Session("historytable")
    If Session("SortDirection" & e.SortExpression) = "ASC" Then
        Session("SortDirection" & e.SortExpression) = "DESC"
    Else
        Session("SortDirection" & e.SortExpression) = "ASC"
    End If
    dt.DefaultView.Sort = e.SortExpression & " " & Session("SortDirection" & e.SortExpression)
    grTicketHistory.DataSource = dt
    grTicketHistory.DataBind()

End Sub

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3

I have deleted the existing node module and run the below commands to fix my issue

npm install -all
npm audit fix

Environment Variable with Maven

in your code add:

System.getProperty("WSNSHELL_HOME")

Modify or add value property from maven command:

mvn clean test -DargLine=-DWSNSHELL_HOME=yourvalue

If you want to run it in Eclipse, add VM arguments in your Debug/Run configurations

  • Go to Run -> Run configurations
  • Select Tab Arguments
  • Add in section VM Arguments

-DWSNSHELL_HOME=yourvalue

See image example

you don't need to modify the POM

versionCode vs versionName in Android Manifest

It is indeed based on versionCode and not on versionName. However, I noticed that changing the versionCode in AndroidManifest.xml wasn't enough with Android Studio - Gradle build system. I needed to change it in the build.gradle.

How to get the sizes of the tables of a MySQL database?

Try the following shell command (replace DB_NAME with your database name):

mysql -uroot <<<"SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"DB_NAME\" ORDER BY (data_length + index_length) DESC;" | head

For Drupal/drush solution, check the following example script which will display the biggest tables in use:

#!/bin/sh
DB_NAME=$(drush status --fields=db-name --field-labels=0 | tr -d '\r\n ')
drush sqlq "SELECT table_name AS 'Tables', round(((data_length + index_length) / 1024 / 1024), 2) 'Size in MB' FROM information_schema.TABLES WHERE table_schema = \"${DB_NAME}\" ORDER BY (data_length + index_length) DESC;" | head -n20

Add php variable inside echo statement as href link address?

Basically like this,

<?php
$link = ""; // Link goes here!
print "<a href="'.$link.'">Link</a>";
?>

How to write files to assets folder or raw folder in android?

You cannot write data's to asset/Raw folder, since it is packed(.apk) and not expandable in size.

If your application need to download dependency files from server, you can go for APK Expansion Files provided by android (http://developer.android.com/guide/market/expansion-files.html).

Xcode 4: How do you view the console?

Here's an alternative.

  1. In XCode4 double-click your Project (Blueprint Icon).
  2. Select the Target (Gray Icon)
  3. Select the Build Phases (Top Center)
  4. Add Build Phase "Run Script" (Green Plus Button, bottom right)
  5. In the textbox below the Shell textfield replace "Type a script or drag a script file from your workspace" with "open ${TARGET_BUILD_DIR}/${TARGET_NAME}"

This will open a terminal window with your command-line app running in it.

This is not a great solution because XCode 4 still runs and debugs the app independently of what you're doing in the terminal window that pops up.

Get timezone from DateTime

DateTime itself contains no real timezone information. It may know if it's UTC or local, but not what local really means.

DateTimeOffset is somewhat better - that's basically a UTC time and an offset. However, that's still not really enough to determine the timezone, as many different timezones can have the same offset at any one point in time. This sounds like it may be good enough for you though, as all you've got to work with when parsing the date/time is the offset.

The support for time zones as of .NET 3.5 is a lot better than it was, but I'd really like to see a standard "ZonedDateTime" or something like that - a UTC time and an actual time zone. It's easy to build your own, but it would be nice to see it in the standard libraries.

EDIT: Nearly four years later, I'd now suggest using Noda Time which has a rather richer set of date/time types. I'm biased though, as the main author of Noda Time :)

Make a table fill the entire window

you can see the solution on http://jsfiddle.net/CBQCA/1/

OR

<table style="height:100%;width:100%; position: absolute; top: 0; bottom: 0; left: 0; right: 0;border:1px solid">
     <tr style="height: 25%;">
        <td>Region</td>
    </tr>
    <tr style="height: 75%;">
        <td>100.00%</td>
    </tr>
</table>?

I removed the font size, to show that columns are expanded. I added border:1px solid just to make sure table is expanded. you can remove it.

Playing mp3 song on python

Try this. It's simplistic, but probably not the best method.

from pygame import mixer  # Load the popular external library

mixer.init()
mixer.music.load('e:/LOCAL/Betrayer/Metalik Klinik1-Anak Sekolah.mp3')
mixer.music.play()

Please note that pygame's support for MP3 is limited. Also, as pointed out by Samy Bencherif, there won't be any silly pygame window popup when you run the above code.

Installation is simple -

pip install pygame

tr:hover not working

tr:hover doesn't work in old browsers.

You can use jQuery for this:

.tr-hover
{  
  background-color:#fefefe;
}
$('.list1 tr').hover(function()
{
    $(this).addClass('tr-hover');
},function()
{
    $(this).removeClass('tr-hover');
});

removing new line character from incoming stream using sed

This might work for you:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

or:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

or:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}

Jump into interface implementation in Eclipse IDE

Here is what I do:

I press command (on Mac, probably control on PC) and then hover over the method or class. When you do this a popup window will appear with the choices "Open Declaration", "Open Implementation", "Open Return Type". You can then click on what you want and Eclipse brings you right there. I believe this works for version 3.6 and up.

It is just as quick as IntelliJ I think.

getResourceAsStream returns null

The default JVM classloader will use parent-classloader to load resources first: deletegate-parent-classloader.

Lifepaths.class.getClass()'s classloader is bootstrap classloader, so getResourceAsStream will search $JAVA_HOME only, regardless of user provided classpath. Obviously, Lifepaths.txt is not there.

Lifepaths.class 's classloader is system classpath classloader, so getResourceAsStream will search user-defined classpath and Lifepaths.txt is there.

When using java.lang.Class#getResourceAsStream(String name), name which is not start with '/' will be added with package name as prefix. If you want avoid this, please using java.lang.ClassLoader#getResourceAsStream. For example:

ClassLoader loader = Thread.currentThread().getContextClassLoader();
String resourceName = "Lifepaths.txt";
InputStream resourceStream = loader.getResourceAsStream(resourceName); 

What is the best way to implement a "timer"?

Use the Timer class.

public static void Main()
{
    System.Timers.Timer aTimer = new System.Timers.Timer();
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Interval = 5000;
    aTimer.Enabled = true;

    Console.WriteLine("Press \'q\' to quit the sample.");
    while(Console.Read() != 'q');
}

 // Specify what you want to happen when the Elapsed event is raised.
 private static void OnTimedEvent(object source, ElapsedEventArgs e)
 {
     Console.WriteLine("Hello World!");
 }

The Elapsed event will be raised every X amount of milliseconds, specified by the Interval property on the Timer object. It will call the Event Handler method you specify. In the example above, it is OnTimedEvent.

Producer/Consumer threads using a Queue

You are reinventing the wheel.

If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).

If you need fast in-memory queues use one of the impementations of java's Queue.

If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.

Get the last three chars from any string - Java

Here is a method I use to get the last xx of a string:

public static String takeLast(String value, int count) {
    if (value == null || value.trim().length() == 0 || count < 1) {
        return "";
    }

    if (value.length() > count) {
        return value.substring(value.length() - count);
    } else {
        return value;
    }
}

Then use it like so:

String testStr = "this is a test string";
String last1 = takeLast(testStr, 1); //Output: g
String last4 = takeLast(testStr, 4); //Output: ring

UnicodeEncodeError: 'ascii' codec can't encode character at special name

Try setting the system default encoding as utf-8 at the start of the script, so that all strings are encoded using that.

Example -

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

The above should set the default encoding as utf-8 .

Draggable div without jQuery UI

Here is an implementation without using jQuery at all -
http://thezillion.wordpress.com/2012/09/27/javascript-draggable-2-no-jquery

Embed the JS file (http://zillionhost.xtreemhost.com/tzdragg/tzdragg.js) in your HTML code, and put the following code -

<script>
win.onload = function(){
 tzdragg.drag('elem1, elem2, ..... elemn');
 // ^ IDs of the draggable elements separated by a comma.
}
</script>

And the code is also easy to learn.
http://thezillion.wordpress.com/2012/08/29/javascript-draggable-no-jquery

Bootstrap modal - close modal when "call to action" button is clicked

Use data-dismiss="modal". In the version of Bootstrap I am using v3.3.5, when data-dismiss="modal" is added to the desired button like shown below it calls my external Javascript (JQuery) function beautifully and magically closes the modal. Its soo Sweet, I was worried I would have to call some modal hide in another function and chain that to the real working function

 <a href="#" id="btnReleaseAll" class="btn btn-primary btn-default btn-small margin-right pull-right" data-dismiss="modal">Yes</a>

In some external script file, and in my doc ready there is of course a function for the click of that identifier ID

 $("#divExamListHeader").on('click', '#btnReleaseAll', function () {
               // Do DatabaseMagic Here for a call a MVC ActionResult

How to center a button within a div?

et voila:

button {
  width: 100px; // whatever your button's width
  margin: 0 auto; // auto left/right margins
  display: block;
}

Update: If OP is looking for horizontal and vertical centre, this answer will do it for a fixed width/height element.

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!

Thus, the way I fixed it was:

apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -

Then running a new "apt-get update" worked flawlessly!

How to handle calendar TimeZones using Java?

Something that has worked for me in the past was to determine the offset (in milliseconds) between the user's timezone and GMT. Once you have the offset, you can simply add/subtract (depending on which way the conversion is going) to get the appropriate time in either timezone. I would usually accomplish this by setting the milliseconds field of a Calendar object, but I'm sure you could easily apply it to a timestamp object. Here's the code I use to get the offset

int offset = TimeZone.getTimeZone(timezoneId).getRawOffset();

timezoneId is the id of the user's timezone (such as EST).

Handling JSON Post Request in Go

I was driving myself crazy with this exact problem. My JSON Marshaller and Unmarshaller were not populating my Go struct. Then I found the solution at https://eager.io/blog/go-and-json:

"As with all structs in Go, it’s important to remember that only fields with a capital first letter are visible to external programs like the JSON Marshaller."

After that, my Marshaller and Unmarshaller worked perfectly!

How to fire an event on class change using jQuery?

You could replace the original jQuery addClass and removeClass functions with your own that would call the original functions and then trigger a custom event. (Using a self-invoking anonymous function to contain the original function reference)

(function( func ) {
    $.fn.addClass = function() { // replace the existing function on $.fn
        func.apply( this, arguments ); // invoke the original function
        this.trigger('classChanged'); // trigger the custom event
        return this; // retain jQuery chainability
    }
})($.fn.addClass); // pass the original function as an argument

(function( func ) {
    $.fn.removeClass = function() {
        func.apply( this, arguments );
        this.trigger('classChanged');
        return this;
    }
})($.fn.removeClass);

Then the rest of your code would be as simple as you'd expect.

$(selector).on('classChanged', function(){ /*...*/ });

Update:

This approach does make the assumption that the classes will only be changed via the jQuery addClass and removeClass methods. If classes are modified in other ways (such as direct manipulation of the class attribute through the DOM element) use of something like MutationObservers as explained in the accepted answer here would be necessary.

Also as a couple improvements to these methods:

  • Trigger an event for each class being added (classAdded) or removed (classRemoved) with the specific class passed as an argument to the callback function and only triggered if the particular class was actually added (not present previously) or removed (was present previously)
  • Only trigger classChanged if any classes are actually changed

    (function( func ) {
        $.fn.addClass = function(n) { // replace the existing function on $.fn
            this.each(function(i) { // for each element in the collection
                var $this = $(this); // 'this' is DOM element in this context
                var prevClasses = this.getAttribute('class'); // note its original classes
                var classNames = $.isFunction(n) ? n(i, prevClasses) : n.toString(); // retain function-type argument support
                $.each(classNames.split(/\s+/), function(index, className) { // allow for multiple classes being added
                    if( !$this.hasClass(className) ) { // only when the class is not already present
                        func.call( $this, className ); // invoke the original function to add the class
                        $this.trigger('classAdded', className); // trigger a classAdded event
                    }
                });
                prevClasses != this.getAttribute('class') && $this.trigger('classChanged'); // trigger the classChanged event
            });
            return this; // retain jQuery chainability
        }
    })($.fn.addClass); // pass the original function as an argument
    
    (function( func ) {
        $.fn.removeClass = function(n) {
            this.each(function(i) {
                var $this = $(this);
                var prevClasses = this.getAttribute('class');
                var classNames = $.isFunction(n) ? n(i, prevClasses) : n.toString();
                $.each(classNames.split(/\s+/), function(index, className) {
                    if( $this.hasClass(className) ) {
                        func.call( $this, className );
                        $this.trigger('classRemoved', className);
                    }
                });
                prevClasses != this.getAttribute('class') && $this.trigger('classChanged');
            });
            return this;
        }
    })($.fn.removeClass);
    

With these replacement functions you can then handle any class changed via classChanged or specific classes being added or removed by checking the argument to the callback function:

$(document).on('classAdded', '#myElement', function(event, className) {
    if(className == "something") { /* do something */ }
});

unexpected T_VARIABLE, expecting T_FUNCTION

Use access modifier before the member definition:

    private $connection;

As you cannot use function call in member definition in PHP, do it in constructor:

 public function __construct() {
      $this->connection = sqlite_open("[path]/data/users.sqlite", 0666);
 }

Traits vs. interfaces

An often-used metaphor to describe Traits is Traits are interfaces with implementation.

This is a good way of thinking about it in most circumstances, but there are a number of subtle differences between the two.

For a start, the instanceof operator will not work with traits (ie, a trait is not a real object), therefore you can't use that to see if a class has a certain trait (or to see if two otherwise unrelated classes share a trait). That's what they mean by it being a construct for horizontal code re-use.

There are functions now in PHP that will let you get a list of all the traits a class uses, but trait-inheritance means you'll need to do recursive checks to reliably check if a class at some point has a specific trait (there's example code on the PHP doco pages). But yeah, it's certainly not as simple and clean as instanceof is, and IMHO it's a feature that would make PHP better.

Also, abstract classes are still classes, so they don't solve multiple-inheritance related code re-use problems. Remember you can only extend one class (real or abstract) but implement multiple interfaces.

I've found traits and interfaces are really good to use hand in hand to create pseudo multiple inheritance. Eg:

class SlidingDoor extends Door implements IKeyed  
{  
    use KeyedTrait;  
    [...] // Generally not a lot else goes here since it's all in the trait  
}

Doing this means you can use instanceof to determine if the particular Door object is Keyed or not, you know you'll get a consistent set of methods, etc, and all the code is in one place across all the classes that use the KeyedTrait.

css background image in a different folder from css

you can use this

body{ background-image: url('../img/bg.png'); }


I tried this on my project where I need to set the background image of a div so I used this and it worked!

What are the differences between .gitignore and .gitkeep?

Many people prefer to use just .keep since the convention has nothing to do with git.

Set bootstrap modal body height by percentage

This worked for me

.modal-dialog,
.modal-content {
    /* 80% of window height */
    height: 80%;
}

.modal-body {
    /* 100% = dialog height, 120px = header + footer */
    max-height: calc(100% - 120px);
    overflow-y: scroll;
}

Fiddle: http://jsfiddle.net/mehmetatas/18dpgqpb/2/

Batch Renaming of Files in a Directory

I've written a python script on my own. It takes as arguments the path of the directory in which the files are present and the naming pattern that you want to use. However, it renames by attaching an incremental number (1, 2, 3 and so on) to the naming pattern you give.

import os
import sys

# checking whether path and filename are given.
if len(sys.argv) != 3:
    print "Usage : python rename.py <path> <new_name.extension>"
    sys.exit()

# splitting name and extension.
name = sys.argv[2].split('.')
if len(name) < 2:
    name.append('')
else:
    name[1] = ".%s" %name[1]

# to name starting from 1 to number_of_files.
count = 1

# creating a new folder in which the renamed files will be stored.
s = "%s/pic_folder" % sys.argv[1]
try:
    os.mkdir(s)
except OSError:
    # if pic_folder is already present, use it.
    pass

try:
    for x in os.walk(sys.argv[1]):
        for y in x[2]:
            # creating the rename pattern.
            s = "%spic_folder/%s%s%s" %(x[0], name[0], count, name[1])
            # getting the original path of the file to be renamed.
            z = os.path.join(x[0],y)
            # renaming.
            os.rename(z, s)
            # incrementing the count.
            count = count + 1
except OSError:
    pass

Hope this works for you.

get all the images from a folder in php

$dir = "mytheme/images/myimages";
$dh  = opendir($dir);
while (false !== ($filename = readdir($dh))) {
    $files[] = $filename;
}
$images=preg_grep ('/\.jpg$/i', $files);

Very fast because you only scan the needed directory.

command to remove row from a data frame

eldNew <- eld[-14,]

See ?"[" for a start ...

For ‘[’-indexing only: ‘i’, ‘j’, ‘...’ can be logical vectors, indicating elements/slices to select. Such vectors are recycled if necessary to match the corresponding extent. ‘i’, ‘j’, ‘...’ can also be negative integers, indicating elements/slices to leave out of the selection.

(emphasis added)

edit: looking around I notice How to delete the first row of a dataframe in R? , which has the answer ... seems like the title should have popped to your attention if you were looking for answers on SO?

edit 2: I also found How do I delete rows in a data frame? , searching SO for delete row data frame ...

Also http://rwiki.sciviews.org/doku.php?id=tips:data-frames:remove_rows_data_frame

Passing Javascript variable to <a href >

You can also use an express framework

app.get("/:id",function(req,res)
{
  var id = req.params.id;
  res.render("home.ejs",{identity : id});
});

Express file, which receives a JS variable identity from node.js

<a href = "/any_route/<%=identity%> includes identity JS variable into your href without a trouble enter

Bootstrap 3: Using img-circle, how to get circle from non-square image?

You could simply use .rounded-circle bootstrap.

 <img class="rounded-circle" src="http://placekitten.com/g/200/200"/>

You can even specify the width and height of the rounded image by providing an inline style to the image, which overrides the default size.

 <img class="rounded-circle" style="height:100px; width: 100px" src="http://placekitten.com/g/200/200" />

how to display a div triggered by onclick event

You'll have to give an ID to the div you want to show/hide, then use this code:

html:

<div id="one">
    <div id="tow">
        This is text
    </div>
    <button onclick="javascript:showDiv();">Click to show div</button>
</div>

javascript:

function showDiv() {
    div = document.getElementById('tow');
    div.style.display = "block";
}

CSS:

?#tow { display: none; }?

Fiddle: http://jsfiddle.net/xkdNa/

How to URL encode in Python 3?

You’re looking for urllib.parse.urlencode

import urllib.parse

params = {'username': 'administrator', 'password': 'xyz'}
encoded = urllib.parse.urlencode(params)
# Returns: 'username=administrator&password=xyz'

what exactly is device pixel ratio?

https://developer.mozilla.org/en/CSS/Media_queries#-moz-device-pixel-ratio

-moz-device-pixel-ratio
Gives the number of device pixels per CSS pixel.

this is almost self-explaining. the number describes the ratio of how much "real" pixels (physical pixerls of the screen) are used to display one "virtual" pixel (size set in CSS).

How to include() all PHP files from a directory?

How to do this in 2017:

spl_autoload_register( function ($class_name) {
    $CLASSES_DIR = __DIR__ . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR;  // or whatever your directory is
    $file = $CLASSES_DIR . $class_name . '.php';
    if( file_exists( $file ) ) include $file;  // only include if file exists, otherwise we might enter some conflicts with other pieces of code which are also using the spl_autoload_register function
} );

Recommended by PHP documentation here: Autoloading classes

ignoring any 'bin' directory on a git project

for 2.13.3 and onwards,writing just bin in your .gitignore file should ignore the bin and all its subdirectories and files

bin

The first day of the current month in php using date_modify as DateTime object

This is everything you need:

$week_start = strtotime('last Sunday', time());
$week_end = strtotime('next Sunday', time());

$month_start = strtotime('first day of this month', time());
$month_end = strtotime('last day of this month', time());

$year_start = strtotime('first day of January', time());
$year_end = strtotime('last day of December', time());

echo date('D, M jS Y', $week_start).'<br/>';
echo date('D, M jS Y', $week_end).'<br/>';

echo date('D, M jS Y', $month_start).'<br/>';
echo date('D, M jS Y', $month_end).'<br/>';

echo date('D, M jS Y', $year_start).'<br/>';
echo date('D, M jS Y', $year_end).'<br/>';

What good technology podcasts are out there?

My list includes: Herding Code, Deep Fried Bytes, Polymorohic Podcast, Pixel8, .Net Rocks, Hanselminutes, Powerscripting podcast. Full list: http://rtipton.wordpress.com/podcasts/

How do I make a transparent canvas in html5?

Just set the background of the canvas to transparent.

#canvasID{
    background:transparent;
}

Iterator over HashMap in Java

Several problems here:

  • You probably don't use the correct iterator class. As others said, use import java.util.Iterator
  • If you want to use Map.Entry entry = (Map.Entry) iter.next(); then you need to use hm.entrySet().iterator(), not hm.keySet().iterator(). Either you iterate on the keys, or on the entries.

Regex for string not ending with given suffix

.*[^a]$

the regex above will match strings which is not ending with a.

C++ int to byte array

I hope mine helps

template <typename t_int>
std::array<uint8_t, sizeof (t_int)> int2array(t_int p_value) {
    static const uint8_t _size_of (static_cast<uint8_t>(sizeof (t_int)));
    typedef std::array<uint8_t, _size_of> buffer;
    static const std::array<uint8_t, 8> _shifters = {8*0, 8*1, 8*2, 8*3, 8*4, 8*5, 8*6, 8*7};

    buffer _res;
    for (uint8_t _i=0; _i < _size_of; ++_i) {
        _res[_i] = static_cast<uint8_t>((p_value >> _shifters[_i]));
    }
    return _res;
}

Installing ADB on macOS

Option 3 - Using MacPorts

Analoguously to the two options (homebrew / manual) posted by @brismuth, here's the MacPorts way:

  1. Install the Android SDK:

    sudo port install android
    
  2. Run the SDK manager:

    sh /opt/local/share/java/android-sdk-macosx/tools/android
    
  3. As @brismuth suggested, uncheck everything but Android SDK Platform-tools (optional)

  4. Install the packages, accepting licenses. Close the SDK Manager.

  5. Add platform-tools to your path; in MacPorts, they're in /opt/local/share/java/android-sdk-macosx/platform-tools. E.g., for bash:

    echo 'export PATH=$PATH:/opt/local/share/java/android-sdk-macosx/platform-tools' >> ~/.bash_profile
    
  6. Refresh your bash profile (or restart your terminal/shell):

    source ~/.bash_profile
    
  7. Start using adb:

    adb devices
    

Multiple Java versions running concurrently under Windows

It is absolutely possible to install side-by-side several JRE/JDK versions. Moreover, you don't have to do anything special for that to happen, as Sun is creating a different folder for each (under Program Files).

There is no control panel to check which JRE works for each application. Basically, the JRE that will work would be the first in your PATH environment variable. You can change that, or the JAVA_HOME variable, or create specific cmd/bat files to launch the applications you desire, each with a different JRE in path.

.NET DateTime to SqlDateTime Conversion

-To compare only the date part, you can do:

var result = db.query($"SELECT * FROM table WHERE date >= '{fromDate.ToString("yyyy-MM-dd")}' and date <= '{toDate.ToString("yyyy-MM-dd"}'");

Concatenating Matrices in R

cbindX from the package gdata combines multiple columns of differing column and row lengths. Check out the page here:

http://hosho.ees.hokudai.ac.jp/~kubo/Rdoc/library/gdata/html/cbindX.html

It takes multiple comma separated matrices and data.frames as input :) You just need to

install.packages("gdata", dependencies=TRUE)

and then

library(gdata)
concat_data <- cbindX(df1, df2, df3) # or cbindX(matrix1, matrix2, matrix3, matrix4)

Android button with icon and text

@Liem Vo's answer is correct if you are using android.widget.Button without any overriding. If you are overriding your theme using MaterialComponents, this will not solve the issue.

So if you are

  1. Using com.google.android.material.button.MaterialButton or
  2. Overriding AppTheme using MaterialComponents

Use app:icon parameter.

<Button
    android:id="@+id/bSearch"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:text="Search"
    android:textSize="24sp"
    app:icon="@android:drawable/ic_menu_search" />

Sorting using Comparator- Descending order (User defined classes)

Using Google Collections:

class Person {
 private int age;

 public static Function<Person, Integer> GET_AGE =
  new Function<Person, Integer> {
   public Integer apply(Person p) { return p.age; }
  };

}

public static void main(String[] args) {
 ArrayList<Person> people;
 // Populate the list...

 Collections.sort(people, Ordering.natural().onResultOf(Person.GET_AGE).reverse());
}

Output (echo/print) everything from a PHP Array

You can use print_r to get human-readable output. But to display it as text we add "echo '';"

echo ''; print_r($row);

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

This error comes because compile does not know where to find the class..so it occurs mainly when u copy or import item ..to solve this .. 1.change the namespace in the formname.cs and formname.designer.cs to the name of your project .

How to set adaptive learning rate for GradientDescentOptimizer?

If you want to set specific learning rates for intervals of epochs like 0 < a < b < c < .... Then you can define your learning rate as a conditional tensor, conditional on the global step, and feed this as normal to the optimiser.

You could achieve this with a bunch of nested tf.cond statements, but its easier to build the tensor recursively:

def make_learning_rate_tensor(reduction_steps, learning_rates, global_step):
    assert len(reduction_steps) + 1 == len(learning_rates)
    if len(reduction_steps) == 1:
        return tf.cond(
            global_step < reduction_steps[0],
            lambda: learning_rates[0],
            lambda: learning_rates[1]
        )
    else:
        return tf.cond(
            global_step < reduction_steps[0],
            lambda: learning_rates[0],
            lambda: make_learning_rate_tensor(
                reduction_steps[1:],
                learning_rates[1:],
                global_step,)
            )

Then to use it you need to know how many training steps there are in a single epoch, so that we can use the global step to switch at the right time, and finally define the epochs and learning rates you want. So if I want the learning rates [0.1, 0.01, 0.001, 0.0001] during the epoch intervals of [0, 19], [20, 59], [60, 99], [100, \infty] respectively, I would do:

global_step = tf.train.get_or_create_global_step()
learning_rates = [0.1, 0.01, 0.001, 0.0001]
steps_per_epoch = 225
epochs_to_switch_at = [20, 60, 100]
epochs_to_switch_at = [x*steps_per_epoch for x in epochs_to_switch_at ]
learning_rate = make_learning_rate_tensor(epochs_to_switch_at , learning_rates, global_step)