Programs & Examples On #Idhttp

How do I use the Simple HTTP client in Android?

You can use like this:

public static String executeHttpPost1(String url,
            HashMap<String, String> postParameters) throws UnsupportedEncodingException {
        // TODO Auto-generated method stub

        HttpClient client = getNewHttpClient();

        try{
        request = new HttpPost(url);

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


        if(postParameters!=null && postParameters.isEmpty()==false){

            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
            String k, v;
            Iterator<String> itKeys = postParameters.keySet().iterator();
            while (itKeys.hasNext()) 
            {
                k = itKeys.next();
                v = postParameters.get(k);
                nameValuePairs.add(new BasicNameValuePair(k, v));
            }     

            UrlEncodedFormEntity urlEntity  = new  UrlEncodedFormEntity(nameValuePairs);
            request.setEntity(urlEntity);

        }
        try {


            Response = client.execute(request,localContext);
            HttpEntity entity = Response.getEntity();
            int statusCode = Response.getStatusLine().getStatusCode();
            Log.i(TAG, ""+statusCode);


            Log.i(TAG, "------------------------------------------------");





                try{
                    InputStream in = (InputStream) entity.getContent(); 
                    //Header contentEncoding = Response.getFirstHeader("Content-Encoding");
                    /*if (contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip")) {
                        in = new GZIPInputStream(in);
                    }*/
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder str = new StringBuilder();
                    String line = null;
                    while((line = reader.readLine()) != null){
                        str.append(line + "\n");
                    }
                    in.close();
                    response = str.toString();
                    Log.i(TAG, "response"+response);
                }
                catch(IllegalStateException exc){

                    exc.printStackTrace();
                }


        } catch(Exception e){

            Log.e("log_tag", "Error in http connection "+response);         

        }
        finally {

        }

        return response;
    }

How to call a .NET Webservice from Android using KSOAP2?

If more than one result is expected, then the getResponse() method will return a Vector containing the various responses.

In which case the offending code becomes:

Object result = envelope.getResponse();

// treat result as a vector
String resultText = null;
if (result instanceof Vector)
{
    SoapPrimitive element0 = (SoapPrimitive)((Vector) result).elementAt(0);
    resultText = element0.toString();
}

tv.setText(resultText);

Answer based on the ksoap2-android (mosabua fork)

Database Diagram Support Objects cannot be Installed ... no valid owner

An easier way to solve this issues would be to right click the name of your database, choose "New Query", type " exec sp_changedbowner 'sa' " and execute the query. Then you'll be good to go.

How to capture a list of specific type with mockito

The nested generics-problem can be avoided with the @Captor annotation:

public class Test{

    @Mock
    private Service service;

    @Captor
    private ArgumentCaptor<ArrayList<SomeType>> captor;

    @Before
    public void init(){
        MockitoAnnotations.initMocks(this);
    }

    @Test 
    public void shouldDoStuffWithListValues() {
        //...
        verify(service).doStuff(captor.capture()));
    }
}

Select from one table where not in another

You can LEFT JOIN the two tables. If there is no corresponding row in the second table, the values will be NULL.

SELECT id FROM partmaster LEFT JOIN product_details ON (...) WHERE product_details.part_num IS NULL

How do I format a date with Dart?

You can also specify the date format like stated earlier: https://pub.dev/documentation/intl/latest/intl/DateFormat-class.html

import 'package:intl/intl.dart';
String formatDate(DateTime date) => new DateFormat("MMMM d").format(date);

Produces: March 4

Issue with background color and Google Chrome

Everybody has said your code is fine, and you know it works on other browsers without problems. So it's time to drop the science and just try stuff :)

Try putting the background color IN the body tag itself instead of/as-well-as in the CSS. Maybe insist again (redudantly) in Javascript. At some point, Chrome will have to place the background as you want it every time. Might be a timing-interpreting issue...

[Should any of this work, of course, you can toggle it on the server-side so the funny code only shows up in Chrome. And in a few months, when Chrome has changed and the problem disappears... well, worry about that later.]

PHP Warning: PHP Startup: Unable to load dynamic library

It means there is an extension=... or zend_extension=... line in one of your php configuration files (php.ini, or another close to it) that is trying to load that extension : ixed.5.2.lin

Unfortunately that file or path doesn't exist or the permissions are incorrect.

  1. Try to search in the .ini files that are loaded by PHP (phpinfo() can indicate which ones are) - one of them should try to load that extension.
  2. Either correct the path to the file or comment out the corresponding line.

How to iterate over associative arrays in Bash

The keys are accessed using an exclamation point: ${!array[@]}, the values are accessed using ${array[@]}.

You can iterate over the key/value pairs like this:

for i in "${!array[@]}"
do
  echo "key  : $i"
  echo "value: ${array[$i]}"
done

Note the use of quotes around the variable in the for statement (plus the use of @ instead of *). This is necessary in case any keys include spaces.

The confusion in the other answer comes from the fact that your question includes "foo" and "bar" for both the keys and the values.

Multiplication on command line terminal

I use this function which uses bc and thus supports floating point calculations:

c () { 
    local a
    (( $# > 0 )) && a="$@" || read -r -p "calc: " a
    bc -l <<< "$a"
}

Example:

$ c '5*5'
25
$ c 5/5
1.00000000000000000000
$ c 3.4/7.9
.43037974683544303797

Bash's arithmetic expansion doesn't support floats (but Korn shell and zsh do).

Example:

$ ksh -c 'echo "$((3.0 / 4))"'
0.75

How do I set up IntelliJ IDEA for Android applications?

You just need to install Android development kit from http://developer.android.com/sdk/installing/studio.html#Updating

and also Download and install Java JDK (Choose the Java platform)

define the environment variable in windows System setting https://confluence.atlassian.com/display/DOC/Setting+the+JAVA_HOME+Variable+in+Windows

Voila ! You are Donezo !

How to create a inset box-shadow only on one side?

Quite a bit late, but a duplicate answer that doesn't require altering the padding or adding extra divs can be found here: Have an issue with box-shadow Inset bottom only. It says, "Use a negative value for the fourth length which defines the spread distance. This is often overlooked, but supported by all major browsers"

From the answerer's fiddle:

box-shadow: inset 0 -10px 10px -10px #000000;

Spring MVC UTF-8 Encoding

In addition to Benjamin's answer (which I've only skimmed), you need to make sure that your files are actually stored using the proper encoding (that would be UTF-8 for source code, JSPs etc., but note that Java Properties files must be encoded as ISO 8859-1 by definition).

The problem with this is that it's not possible to tell what encoding has been used to store a file. Your only option is to open the file using a specific encoding, and checking whether or not the content makes sense. You can also try to convert the file from the assumed encoding to the desired encoding using iconv - if that produces an error, your assumption was incorrect. So if you assume that hello.jsp is encoded as UTF-8, run "iconv -f UTF-16 -t UTF-8 hello.jsp" and check for errors.

If you should find out that your files are not properly encoded, you need to find out why. It's probably the editor or IDE you used to create the file. In case of Eclipse (and STS), make sure the Text File Encoding (Preferences / General / Workspace) is set to UTF-8 (it unfortunately defaults to your system's platform encoding).

What makes encoding problems so difficult to debug is that there's so many components involved (text editor, borwser, plus each and every software component in between, in some cases including a database), and each of them has the potential to introduce an error.

Apply a function to every row of a matrix or a data frame

Another approach if you want to use a varying portion of the dataset instead of a single value is to use rollapply(data, width, FUN, ...). Using a vector of widths allows you to apply a function on a varying window of the dataset. I've used this to build an adaptive filtering routine, though it isn't very efficient.

Get SELECT's value and text in jQuery

<select id="ddlViewBy">
    <option value="value">text</option>
</select>

JQuery

var txt = $("#ddlViewBy option:selected").text();
var val = $("#ddlViewBy option:selected").val();

JS Fiddle DEMO

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

First of all I wanted to thank jimbo and (his post / twitter-api-php simple library).

If you are going to use the GET search/tweets API with "twitter-api-php" PHP library (TwitterAPIExchange.php):

First, you have to just comment "Perform a POST request and echo the response " code area.

Just use "Perform a GET request and echo the response" code and echo the response and change these two lines:

$url = 'https://api.twitter.com/1.1/followers/ids.json';
$getfield = '?screen_name=J7mbo';

to

$url = 'https://api.twitter.com/1.1/search/tweets.json';
$getfield = '?q=J7mbo';

(Change screen_name to q, that's it :)

Setting dropdownlist selecteditem programmatically

ddList.Items.FindByText("oldValue").Selected = false;
ddList.Items.FindByText("newValue").Selected = true;

CSS background image URL failing to load

Source location should be the URL (relative to the css file or full web location), not a file system full path, for example:

background: url("http://localhost/media/css/static/img/sprites/buttons-v3-10.png");
background: url("static/img/sprites/buttons-v3-10.png");

Alternatively, you can try to use file:/// protocol prefix.

Android getting value from selected radiobutton

Tested and working. Check this

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class MyAndroidAppActivity extends Activity {

  private RadioGroup radioGroup;
  private RadioButton radioButton;
  private Button btnDisplay;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    addListenerOnButton();

  }

  public void addListenerOnButton() {

    radioGroup = (RadioGroup) findViewById(R.id.radio);
    btnDisplay = (Button) findViewById(R.id.btnDisplay);

    btnDisplay.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

                // get selected radio button from radioGroup
            int selectedId = radioGroup.getCheckedRadioButtonId();

            // find the radiobutton by returned id
            radioButton = (RadioButton) findViewById(selectedId);

            Toast.makeText(MyAndroidAppActivity.this,
                radioButton.getText(), Toast.LENGTH_SHORT).show();

        }

    });

  }
}

xml

<RadioGroup
        android:id="@+id/radio"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <RadioButton
            android:id="@+id/radioMale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_male" 
            android:checked="true" />

        <RadioButton
            android:id="@+id/radioFemale"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/radio_female" />

    </RadioGroup>

Datagridview full row selection but get single cell value

Just Use: dataGridView1.CurrentCell.Value.ToString()

        private void dataGridView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            MessageBox.Show(dataGridView1.CurrentCell.Value.ToString());
        }

or

 // dataGrid1.Rows[yourRowIndex ].Cells[yourColumnIndex].Value.ToString()

 //Example1:yourRowIndex=dataGridView1.CurrentRow.Index (from selectedRow );
 dataGrid1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value.ToString()

 //Example2:yourRowIndex=3,yourColumnIndex=2 (select by programmatically )
  dataGrid1.Rows[3].Cells[2].Value.ToString()

How do I disable right click on my web page?

If you are a jquery fan,use this

    $(function() {
        $(this).bind("contextmenu", function(e) {
            e.preventDefault();
        });
    }); 

key_load_public: invalid format

There is a simple solution if you can install and use puttygen tool. Below are the steps. You should have the passphrase of the private key.

step 1: Download latest puttygen and open puttygen

step 2: Load your existing private key file, see below image

Load an existing private key

step 3: Enter passphrase for key if asked and hit ok

enter paasphrase

step 4: as shown in the below image select "conversion" menu tab and select "Export OpenSSH key"

save OpenSSH file

Save new private key file at preferred location and use accordingly.

How can I sort generic list DESC and ASC?

With Linq

var ascendingOrder = li.OrderBy(i => i);
var descendingOrder = li.OrderByDescending(i => i);

Without Linq

li.Sort((a, b) => a.CompareTo(b)); // ascending sort
li.Sort((a, b) => b.CompareTo(a)); // descending sort

Note that without Linq, the list itself is being sorted. With Linq, you're getting an ordered enumerable of the list but the list itself hasn't changed. If you want to mutate the list, you would change the Linq methods to something like

li = li.OrderBy(i => i).ToList();

How do I make a transparent border with CSS?

Use transparent property

border-color : transparent;

Missing MVC template in Visual Studio 2015

Visual studio 2015 does not show MVC project template if you select .Net 4.0 or below. Select .Net 4.5 or above, and you will be able to see MVC project.

This is what showed when you select .NET Framework 4:

enter image description here

and this when you select .NET Framework 4.5:

enter image description here

However, make sure you have installed web developers tools. To do so, go to Add / remove programs -> Visual 2015 -> Modify --> Web developer tools : Check and proceed with the installation.

Limit to 2 decimal places with a simple pipe

Currency pipe uses the number one internally for number formatting. So you can use it like this:

{{ number | number : '1.2-2'}}

Bootstrap 3 only for mobile

You can create a jQuery function to unload Bootstrap CSS files at the size of 768px, and load it back when resized to lower width. This way you can design a mobile website without touching the desktop version, by using col-xs-* only

function resize() {
if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}   
else {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', false);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', false);
}
}

and

$(document).ready(function() {
$(window).resize(resize);
resize();   

if ($(window).width() > 767) {
$('link[rel=stylesheet][href~="bootstrap.min.css"]').prop('disabled', true);
$('link[rel=stylesheet][href~="bootstrap-theme.min.css"]').prop('disabled', true);
}
});

How to edit default dark theme for Visual Studio Code?

The simplest way is to edit the user settings and customise workbench.colorCustomizations

Editing color customizations

If you want to make your theme

There is also the option modify the current theme which will copy the current theme settings and let you save it as a *.color-theme.json JSON5 file

Generate color theme from current settings

Explicitly select items from a list or tuple

Maybe a list comprehension is in order:

L = ['a', 'b', 'c', 'd', 'e', 'f']
print [ L[index] for index in [1,3,5] ]

Produces:

['b', 'd', 'f']

Is that what you are looking for?

What does "restore purchases" in In-App purchases mean?

You will get rejection message from apple just because the product you have registered for inApp purchase might come under category Non-renewing subscriptions and consumable products. These type of products will not automatically renewable. you need to have explicit restore button in your application.

for other type of products it will automatically restore it.

Please read following text which will clear your concept about this :

Once a transaction has been processed and removed from the queue, your application normally never sees it again. However, if your application supports product types that must be restorable, you must include an interface that allows users to restore these purchases. This interface allows a user to add the product to other devices or, if the original device was wiped, to restore the transaction on the original device.

Store Kit provides built-in functionality to restore transactions for non-consumable products, auto-renewable subscriptions and free subscriptions. To restore transactions, your application calls the payment queue’s restoreCompletedTransactions method. The payment queue sends a request to the App Store to restore the transactions. In return, the App Store generates a new restore transaction for each transaction that was previously completed. The restore transaction object’s originalTransaction property holds a copy of the original transaction. Your application processes a restore transaction by retrieving the original transaction and using it to unlock the purchased content. After Store Kit restores all the previous transactions, it notifies the payment queue observers by calling their paymentQueueRestoreCompletedTransactionsFinished: method.

If the user attempts to purchase a restorable product (instead of using the restore interface you implemented), the application receives a regular transaction for that item, not a restore transaction. However, the user is not charged again for that product. Your application should treat these transactions identically to those of the original transaction. Non-renewing subscriptions and consumable products are not automatically restored by Store Kit. Non-renewing subscriptions must be restorable, however. To restore these products, you must record transactions on your own server when they are purchased and provide your own mechanism to restore those transactions to the user’s devices

Autocompletion in Vim

I'm a bit late to the party but autocomplpop might be helpful.

Angular 4 - Observable catch error

With angular 6 and rxjs 6 Observable.throw(), Observable.off() has been deprecated instead you need to use throwError

ex :

return this.http.get('yoururl')
  .pipe(
    map(response => response.json()),
    catchError((e: any) =>{
      //do your processing here
      return throwError(e);
    }),
  );

Call to getLayoutInflater() in places not in activity

LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );

Use this instead!

Splitting string with pipe character ("|")

String rat_values = "Food 1 | Service 3 | Atmosphere 3 | Value for money 1 ";
    String[] value_split = rat_values.split("\\|");
    for (String string : value_split) {

        System.out.println(string);

    }

Scraping data from website using vba

This question asked long before. But I thought following information will useful for newbies. Actually you can easily get the values from class name like this.

Sub ExtractLastValue()

Set objIE = CreateObject("InternetExplorer.Application")

objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 600

objIE.Visible = True

objIE.Navigate ("https://uk.investing.com/rates-bonds/financial-futures/")

Do
DoEvents
Loop Until objIE.readystate = 4

MsgBox objIE.document.getElementsByClassName("pid-8907-last")(0).innerText

End Sub

And if you are new to web scraping please read this blog post.

Web Scraping - Basics

And also there are various techniques to extract data from web pages. This article explain few of them with examples.

Web Scraping - Collecting Data From a Webpage

How do I make Git use the editor of my choice for commits?

For IntelliJ users

When i was trying to git rebase i was getting the following error: 'hint: Waiting for your editor to close the file... code -n -w: code: command not found error: There was a problem with the editor 'code -n -w'.'

The same error showed up when i was trying to associate IntelliJ with Git: enter image description here

The problem was that I did not have the command code added in my environment PATH variable. And i didn't want to use Visual Studio Code from my terminal. So that is why it prompted "command not found". I solved this by deleting

editor = code -n -w

from the core section in my .gitconfig file. Git worked properly again.

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

I ran into a similar problem when trying to use the JQuery generator for Rails 3

I solved it like this:

  1. Get the CURL Certificate Authority (CA) bundle. You can do this with:

    • sudo port install curl-ca-bundle [if you are using MacPorts]
    • or just pull it down directly wget http://curl.haxx.se/ca/cacert.pem
  2. Execute the ruby code that is trying to verify the SSL certification: SSL_CERT_FILE=/opt/local/etc/certs/cacert.pem rails generate jquery:install. In your case, you want to either set this as an environment variable somewhere the server picks it up or add something like ENV['SSL_CERT_FILE'] = /path/to/your/new/cacert.pem in your environment.rb file.

You can also just install the CA files (I haven't tried this) to the OS -- there are lengthy instructions here -- this should work in a similar fashion, but I have not tried this personally.

Basically, the issue you are hitting is that some web service is responding with a certificate signed against a CA that OpenSSL cannot verify.

How to solve time out in phpmyadmin?

None of the above answers solved it for me.

I cant even find the 'libraries' folder in my xampp - ubuntu also.

So, I simply restarted using the following commands:

sudo service apache2 restart

and

sudo service mysql restart
  • Just restarted apache and mysql. Logged in phpmyadmin again and it worked as usual.

Thanks me..!!

How to send a GET request from PHP?

For more advanced GET/POST requests, you can install the CURL library (http://us3.php.net/curl):

$ch = curl_init("REMOTE XML FILE URL GOES HERE"); // such as http://example.com/example.xml
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
$data = curl_exec($ch);
curl_close($ch);

Should I learn C before learning C++?

I'm going to disagree with the majority here. I think you should learn C before learning C++. It's definitely not necessary, but I think it makes learning C++ a lot easier. C is at the heart of C++. Anything you learn about C is applicable to C++, but C is a lot smaller and easier to learn.

Pick up K&R and read through that. It is short and will give you a sufficient sense of the language. Once you have the basics of pointers and function calls down, you can move on to C++ a little easier.

Counting the number of elements with the values of x in a vector

One option could be to use vec_count() function from the vctrs library:

vec_count(numbers)

   key count
1  435     3
2   67     2
3    4     2
4   34     2
5   56     2
6   23     2
7  456     1
8   43     1
9  453     1
10   5     1
11 657     1
12 324     1
13  54     1
14 567     1
15  65     1

The default ordering puts the most frequent values at top. If looking for sorting according keys (a table()-like output):

vec_count(numbers, sort = "key")

   key count
1    4     2
2    5     1
3   23     2
4   34     2
5   43     1
6   54     1
7   56     2
8   65     1
9   67     2
10 324     1
11 435     3
12 453     1
13 456     1
14 567     1
15 657     1

Select first and last row from grouped data

A different base R alternative would be to first order by id and stopSequence, split them based on id and for every id we select only the first and last index and subset the dataframe using those indices.

df[sapply(with(df, split(order(id, stopSequence), id)), function(x) 
                   c(x[1], x[length(x)])), ]


#  id stopId stopSequence
#1  1      a            1
#3  1      c            3
#5  2      b            1
#6  2      c            4
#8  3      b            1
#7  3      a            3

Or similar using by

df[unlist(with(df, by(order(id, stopSequence), id, function(x) 
                   c(x[1], x[length(x)])))), ]

Log exception with traceback

Use logging.exception from within the except: handler/block to log the current exception along with the trace information, prepended with a message.

import logging
LOG_FILENAME = '/tmp/logging_example.out'
logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)

logging.debug('This message should go to the log file')

try:
    run_my_stuff()
except:
    logging.exception('Got exception on main handler')
    raise

Now looking at the log file, /tmp/logging_example.out:

DEBUG:root:This message should go to the log file
ERROR:root:Got exception on main handler
Traceback (most recent call last):
  File "/tmp/teste.py", line 9, in <module>
    run_my_stuff()
NameError: name 'run_my_stuff' is not defined

Calculate logarithm in python

The math.log function is to the base e, i.e. natural logarithm. If you want to the base 10 use math.log10.

Gitignore not working

@Ahmad's answer is working but if you just want to git ignore 1 specific file or few files do as @Nicolas suggests

step 1

add filename to .gitignore file

step 2

[remove filename (file path) from git cache

git rm --cached filename

setp 3

commit changes git add filename

git commit -m "add filename to .gitignore"

it will keep your git history clean because if you do git rm -r --cached . and add back all and commit them it will pollute your git history (it will show that you add a lot of files at one commit) not sure am I expressing my thought right but hope you get the point

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

That is an HTTP header. You would configure your webserver or webapp to send this header ideally. Perhaps in htaccess or PHP.

Alternatively you might be able to use

<head>...<meta http-equiv="Access-Control-Allow-Origin" content="*">...</head>

I do not know if that would work. Not all HTTP headers can be configured directly in the HTML.

This works as an alternative to many HTTP headers, but see @EricLaw's comment below. This particular header is different.

Caveat

This answer is strictly about how to set headers. I do not know anything about allowing cross domain requests.

About HTTP Headers

Every request and response has headers. The browser sends this to the webserver

GET /index.htm HTTP/1.1

Then the headers

Host: www.example.com
User-Agent: (Browser/OS name and version information)
.. Additional headers indicating supported compression types and content types and other info

Then the server sends a response

Content-type: text/html
Content-length: (number of bytes in file (optional))
Date: (server clock)
Server: (Webserver name and version information)

Additional headers can be configured for example Cache-Control, it all depends on your language (PHP, CGI, Java, htaccess) and webserver (Apache, etc).

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

Docker is installed but Docker Compose is not ? why?

You also need to install Docker Compose. See the manual. Here are the commands you need to execute

sudo curl -L "https://github.com/docker/compose/releases/download/1.26.0/docker-compose-$(uname -s)-$(uname -m)"  -o /usr/local/bin/docker-compose
sudo mv /usr/local/bin/docker-compose /usr/bin/docker-compose
sudo chmod +x /usr/bin/docker-compose

How to assign string to bytes array

For converting from a string to a byte slice, string -> []byte:

[]byte(str)

For converting an array to a slice, [20]byte -> []byte:

arr[:]

For copying a string to an array, string -> [20]byte:

copy(arr[:], str)

Same as above, but explicitly converting the string to a slice first:

copy(arr[:], []byte(str))

  • The built-in copy function only copies to a slice, from a slice.
  • Arrays are "the underlying data", while slices are "a viewport into underlying data".
  • Using [:] makes an array qualify as a slice.
  • A string does not qualify as a slice that can be copied to, but it qualifies as a slice that can be copied from (strings are immutable).
  • If the string is too long, copy will only copy the part of the string that fits.

This code:

var arr [20]byte
copy(arr[:], "abc")
fmt.Printf("array: %v (%T)\n", arr, arr)

...gives the following output:

array: [97 98 99 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] ([20]uint8)

I also made it available at the Go Playground

Determining if a number is prime

//simple function to determine if a number is a prime number
//to state if it is a prime number


#include <iostream>

using namespace std;


int isPrime(int x);  //functioned defined after int main()


int main()
{
 int y;
    cout<<"enter value"<<endl;

    cin>>y;

    isPrime(y);    

  return 0;

 } //end of main function


//-------------function

  int isPrime(int x)
 {
   int counter =0;
     cout<<"factors of "<<x<<" are "<<"\n\n";    //print factors of the number

     for (int i =0; i<=x; i++)

     {
       for (int j =0; j<=x; j++)

         {
           if (i * j == x)      //check if the number has multiples;
                {

                  cout<<i<<" ,  ";  //output provided for the reader to see the
                                    // muliples
                  ++counter;        //counts the number of factors

                 }


          }


    }
  cout<<"\n\n";

  if(counter>2) 
     { 
      cout<<"value is not a prime number"<<"\n\n";
     }

  if(counter<=2)
     {
       cout<<"value is a prime number"<<endl;
     }
 }

Converting file into Base64String and back again

For Java, consider using Apache Commons FileUtils:

/**
 * Convert a file to base64 string representation
 */
public String fileToBase64(File file) throws IOException {
    final byte[] bytes = FileUtils.readFileToByteArray(file);
    return Base64.getEncoder().encodeToString(bytes);
}

/**
 * Convert base64 string representation to a file
 */
public void base64ToFile(String base64String, String filePath) throws IOException {
    byte[] bytes = Base64.getDecoder().decode(base64String);
    FileUtils.writeByteArrayToFile(new File(filePath), bytes);
}

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

UPDATE: 2019-12-30

It seem that this tool is no longer working! [Request for update!]

UPDATE 2019-01-06: You can bypass X-Frame-Options in an <iframe> using my X-Frame-Bypass Web Component. It extends the IFrame element by using multiple CORS proxies and it was tested in the latest Firefox and Chrome.

You can use it as follows:

  1. (Optional) Include the Custom Elements with Built-in Extends polyfill for Safari:

    <script src="https://unpkg.com/@ungap/custom-elements-builtin"></script>
    
  2. Include the X-Frame-Bypass JS module:

    <script type="module" src="x-frame-bypass.js"></script>
    
  3. Insert the X-Frame-Bypass Custom Element:

    <iframe is="x-frame-bypass" src="https://example.org/"></iframe>
    

SQLAlchemy: how to filter date field?

In fact, your query is right except for the typo: your filter is excluding all records: you should change the <= for >= and vice versa:

qry = DBSession.query(User).filter(
        and_(User.birthday <= '1988-01-17', User.birthday >= '1985-01-17'))
# or same:
qry = DBSession.query(User).filter(User.birthday <= '1988-01-17').\
        filter(User.birthday >= '1985-01-17')

Also you can use between:

qry = DBSession.query(User).filter(User.birthday.between('1985-01-17', '1988-01-17'))

Could not find any resources appropriate for the specified culture or the neutral culture

In my case a series of badly thought global text replacements had inadvertently changed this line in the resource designer cs file.

enter image description here

Since the namespace in that argument did not match the namespace of the class anymore, the application got confused at run time.

Check that the namespace of the designer matches the string argument in that line.

How to filter empty or NULL names in a QuerySet?

this is another simple way to do it .

Name.objects.exclude(alias=None)

CURL to pass SSL certifcate and password

Addition to previous answer make sure that your curl installation supports https.
You can use curl --version to get information about supported protocols.

If your curl supports https follow the previous answer.

curl --cert certificate_path:password https://www.example.com

If it does not support https, you need to install a cURL version that supports https.

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

Actually you can use an interface to achieve what you want.

public interface Animal {
    String getName();
    String getVoice();
}
public class Dog implements Animal{
    @Override 
    String getName(){return "Dog";}
    @Override
    String getVoice(){return "woof!";}

}

you can then use the collections using

List <Animal> animalGroup = new ArrayList<Animal>();
animalGroup.add(new Dog());

Can an AJAX response set a cookie?

Yes, you can set cookie in the AJAX request in the server-side code just as you'd do for a normal request since the server cannot differentiate between a normal request or an AJAX request.

AJAX requests are just a special way of requesting to server, the server will need to respond back as in any HTTP request. In the response of the request you can add cookies.

How do I clear all options in a dropdown box?

var select = document.getElementById("DropList");
var length = select.options.length;
for (i = 0; i < length; i++) {
  select.options[i].remove();
}

Hope, this code will helps you

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

Works for me >

the environment:

localhost
Windows 10
PHP 5.6.31
MYSQL 8

set:

default-character-set=utf8

on:

c:\programdata\mysql\mysql server 8.0\my.ini

  • Not works on> C:\Program Files\MySQL\MySQL Server 5.5\my.ini

Tools that helps:

C:\Program Files\MySQL\MySQL Server 8.0\bin>mysql -u root -p

mysql> show variables like 'char%';

mysql> show variables like 'collation%';

\m/

How to store array or multiple values in one column

Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:

create table foo (
  bar  int[] default '{}'
);

select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]

create index on foo using gin (bar); -- allows to use an index in the above query

But as the prior answer suggests, it will be better to normalize properly.

How to re-render flatlist?

For quick and simple solution Try:

  1. set extra data to a boolean value.

    extraData={this.state.refresh}

  2. Toggle the value of boolean state when you want to re-render/refresh list

    this.setState({ 
        refresh: !this.state.refresh
    })
    

How to dynamically set bootstrap-datepicker's date value?

$("#datepicker").datepicker("setDate", new Date);

What are the differences between the BLOB and TEXT datatypes in MySQL?

According to High-performance Mysql book:

The only difference between the BLOB and TEXT families is that BLOB types store binary data with no collation or character set, but TEXT types have a character set and collation.

How to configure slf4j-simple

I noticed that Eemuli said that you can't change the log level after they are created - and while that might be the design, it isn't entirely true.

I ran into a situation where I was using a library that logged to slf4j - and I was using the library while writing a maven mojo plugin.

Maven uses a (hacked) version of the slf4j SimpleLogger, and I was unable to get my plugin code to reroute its logging to something like log4j, which I could control.

And I can't change the maven logging config.

So, to quiet down some noisy info messages, I found I could use reflection like this, to futz with the SimpleLogger at runtime.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
    try
    {
        Logger l = LoggerFactory.getLogger("full.classname.of.noisy.logger");  //This is actually a MavenSimpleLogger, but due to various classloader issues, can't work with the directly.
        Field f = l.getClass().getSuperclass().getDeclaredField("currentLogLevel");
        f.setAccessible(true);
        f.set(l, LocationAwareLogger.WARN_INT);
    }
    catch (Exception e)
    {
        getLog().warn("Failed to reset the log level of " + loggerName + ", it will continue being noisy.", e);
    }

Of course, note, this isn't a very stable / reliable solution... as it will break the next time the maven folks change their logger.

"date(): It is not safe to rely on the system's timezone settings..."

<? date_default_timezone_set('Europe/Istanbul'); ?>

For php (or your location).

How can I get (query string) parameters from the URL in Next.js?

If you need to retrieve a URL query from outside a component:

import router from 'next/router'

console.log(router.query)

What does "all" stand for in a makefile?

A build, as Makefile understands it, consists of a lot of targets. For example, to build a project you might need

  1. Build file1.o out of file1.c
  2. Build file2.o out of file2.c
  3. Build file3.o out of file3.c
  4. Build executable1 out of file1.o and file3.o
  5. Build executable2 out of file2.o

If you implemented this workflow with makefile, you could make each of the targets separately. For example, if you wrote

make file1.o

it would only build that file, if necessary.

The name of all is not fixed. It's just a conventional name; all target denotes that if you invoke it, make will build all what's needed to make a complete build. This is usually a dummy target, which doesn't create any files, but merely depends on the other files. For the example above, building all necessary is building executables, the other files being pulled in as dependencies. So in the makefile it looks like this:

all: executable1 executable2

all target is usually the first in the makefile, since if you just write make in command line, without specifying the target, it will build the first target. And you expect it to be all.

all is usually also a .PHONY target. Learn more here.

Creating a new dictionary in Python

>>> dict.fromkeys(['a','b','c'],[1,2,3])


{'a': [1, 2, 3], 'b': [1, 2, 3], 'c': [1, 2, 3]}

How do I launch a Git Bash window with particular working directory using a script?

In addition, Win10 gives you an option to open git bash from your working directory by right-clicking on your folder and selecting GitBash here.

enter image description here

How to group time by hour or by 10 minutes

I know I am late to the show with this one, but I used this - pretty simple approach. This allows you to get the 60 minute slices without any rounding issues.

Select 
   CONCAT( 
            Format(endtime,'yyyy-MM-dd_HH:'),  
            LEFT(Format(endtime,'mm'),1),
            '0' 
          ) as [Time-Slice]

Change a column type from Date to DateTime during ROR migration

AFAIK, migrations are there to try to reshape data you care about (i.e. production) when making schema changes. So unless that's wrong, and since he did say he does not care about the data, why not just modify the column type in the original migration from date to datetime and re-run the migration? (Hope you've got tests:)).

Hexadecimal string to byte array in C

Following is the solution I wrote up for performance reasons:

void hex2bin(const char* in, size_t len, unsigned char* out) {

  static const unsigned char TBL[] = {
     0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  58,  59,  60,  61,
    62,  63,  64,  10,  11,  12,  13,  14,  15,  71,  72,  73,  74,  75,
    76,  77,  78,  79,  80,  81,  82,  83,  84,  85,  86,  87,  88,  89,
    90,  91,  92,  93,  94,  95,  96,  10,  11,  12,  13,  14,  15
  };

  static const unsigned char *LOOKUP = TBL - 48;

  const char* end = in + len;

  while(in < end) *(out++) = LOOKUP[*(in++)] << 4 | LOOKUP[*(in++)];

}

Example:

unsigned char seckey[32];

hex2bin("351aaaec0070d13d350afae2bc43b68c7e590268889869dde489f2f7988f3fee", 64, seckey);

/*
  seckey = {
     53,  26, 170, 236,   0, 112, 209,  61,  53,  10, 250, 226, 188,  67, 182, 140, 
    126,  89,   2, 104, 136, 152, 105, 221, 228, 137, 242, 247, 152, 143,  63, 238
  };
*/

If you don't need to support lowercase:

static const unsigned char TBL[] = {
     0,   1,   2,   3,   4,   5,   6,   7,   8,   9,  58,  59,
    60,  61,  62,  63,  64,  10,  11,  12,  13,  14,  15
};

How to get anchor text/href on click using jQuery?

Alternative

Using the example from Sarfraz above.

<div class="res">
    <a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
        ~/Resumes/Resumes1271354404687.docx
    </a>
</div>

For href:

$(function(){
  $('.res').on('click', '.info_link', function(){
    alert($(this)[0].href);
  });
});

C# listView, how do I add items to columns 2, 3 and 4 etc?

There are several ways to do it, but here is one solution (for 4 columns).

string[] row1 = { "s1", "s2", "s3" };
listView1.Items.Add("Column1Text").SubItems.AddRange(row1);

And a more verbose way is here:

ListViewItem item1 = new ListViewItem("Something");
item1.SubItems.Add("SubItem1a");
item1.SubItems.Add("SubItem1b");
item1.SubItems.Add("SubItem1c");

ListViewItem item2 = new ListViewItem("Something2");
item2.SubItems.Add("SubItem2a");
item2.SubItems.Add("SubItem2b");
item2.SubItems.Add("SubItem2c");

ListViewItem item3 = new ListViewItem("Something3");
item3.SubItems.Add("SubItem3a");
item3.SubItems.Add("SubItem3b");
item3.SubItems.Add("SubItem3c");

ListView1.Items.AddRange(new ListViewItem[] {item1,item2,item3});

Determine path of the executing script

I also had this problem, and none of the above solutions worked for me. Maybe with the source or things like that, but it was not clear enough.

I found this, for me elegant, solution:

paste0(gsub("\\", "/", fileSnapshot()$path, fixed=TRUE),"/")

The important thing in that is the fileSnapshot() that gives you a lot of information about a file. It returns a list of 8 elements. When you pick path as the list element, the path is returned with \\ as separator, so the rest of the code is just to change that.

I hope this helps.

Landscape printing from HTML

-webkit-transform: rotate(-90deg); -moz-transform:rotate(-90deg);
     filter:progid:DXImageTransform.Microsoft.BasicImage(rotation=3);

not working in Firefox 16.0.2 but it is working in Chrome

Stored procedure or function expects parameter which is not supplied

Your stored procedure expects 5 parameters as input

@userID int, 
@userName varchar(50), 
@password nvarchar(50), 
@emailAddress nvarchar(50), 
@preferenceName varchar(20) 

So you should add all 5 parameters to this SP call:

    cmd.CommandText = "SHOWuser";
    cmd.Parameters.AddWithValue("@userID",userID);
    cmd.Parameters.AddWithValue("@userName", userName);
    cmd.Parameters.AddWithValue("@password", password);
    cmd.Parameters.AddWithValue("@emailAddress", emailAddress);
    cmd.Parameters.AddWithValue("@preferenceName", preferences);
    dbcon.Open();

PS: It's not clear what these parameter are for. You don't use these parameters in your SP body so your SP should looks like:

ALTER PROCEDURE [dbo].[SHOWuser] AS BEGIN ..... END

How Long Does it Take to Learn Java for a Complete Newbie?

I worked with some self-taught programmers who read stuff like "learn javascript in 0.01 days". Everyday was worth it's share of thedailywtf.com.

Besides, at a job inteview you get asked "how much javascript experience do you have?", your answer "0.01 days".

so good luck but I hope our path won't cross before a few more years

How to set a radio button in Android

Just to clarify this: if we have a RadioGroup with several RadioButtons and need to activate one by index, implies that:

radioGroup.check(R.id.radioButtonId)

and

radioGroup.getChildAt(index)`

We can to do:

radioGroup.check(radioGroup.getChildAt(index).getId());

How do I convert a calendar week into a date in Excel?

=(MOD(R[-1]C-1,100)*7+DATE(INT(R[-1]C/100+2000),1,1)-2)

yyww as the given week exp:week 51 year 2014 will be 1451

How to clear all data in a listBox?

this should work:

private void cleanlistbox(object sender, EventArgs e)
{
    listBox1.Items.Clear( );
}

Delayed function calls

This will work either on older versions of .NET
Cons: will execute in its own thread

class CancelableDelay
    {
        Thread delayTh;
        Action action;
        int ms;

        public static CancelableDelay StartAfter(int milliseconds, Action action)
        {
            CancelableDelay result = new CancelableDelay() { ms = milliseconds };
            result.action = action;
            result.delayTh = new Thread(result.Delay);
            result.delayTh.Start();
            return result;
        }

        private CancelableDelay() { }

        void Delay()
        {
            try
            {
                Thread.Sleep(ms);
                action.Invoke();
            }
            catch (ThreadAbortException)
            { }
        }

        public void Cancel() => delayTh.Abort();

    }

Usage:

var job = CancelableDelay.StartAfter(1000, () => { WorkAfter1sec(); });  
job.Cancel(); //to cancel the delayed job

how to convert image to byte array in java?

Try this code snippet

BufferedImage image = ImageIO.read(new File("filename.jpg"));

// Process image

ImageIO.write(image, "jpg", new File("output.jpg"));

Facebook API "This app is in development mode"

in your app dashboard check status to on facebook change develope mode to live

How to use AND in IF Statement

I think you should append .value in IF statement:

If Cells(i, "A").Value <> "Miami" And Cells(i, "D").Value <> "Florida" Then
    Cells(i, "C").Value = "BA"
End IF

npm not working - "read ECONNRESET"

Remove yarn.lock , package-lock.json, node_modules

and then

npm install -f 

Worked for me

This Handler class should be static or leaks might occur: IncomingHandler

This way worked well for me, keeps code clean by keeping where you handle the message in its own inner class.

The handler you wish to use

Handler mIncomingHandler = new Handler(new IncomingHandlerCallback());

The inner class

class IncomingHandlerCallback implements Handler.Callback{

        @Override
        public boolean handleMessage(Message message) {

            // Handle message code

            return true;
        }
}

Priority queue in .Net

Here is the another implementation from NGenerics team:

NGenerics PriorityQueue

Python - Get path of root project structure

I decided for myself as follows.
Need to get the path to 'MyProject/drivers' from the main file.

MyProject/
+--- RootPackge/
¦    +-- __init__.py
¦    +-- main.py
¦    +-- definitions.py
¦
+--- drivers/
¦    +-- geckodriver.exe
¦
+-- requirements.txt
+-- setup.py

definitions.py
Put not in the root of the project, but in the root of the main package

from pathlib import Path

ROOT_DIR = Path(__file__).parent.parent

Use ROOT_DIR:
main.py

# imports must be relative,
# not from the root of the project,
# but from the root of the main package.
# Not this way:
# from RootPackge.definitions import ROOT_DIR
# But like this:
from definitions import ROOT_DIR

# Here we use ROOT_DIR
# get path to MyProject/drivers
drivers_dir = ROOT_DIR / 'drivers'
# Thus, you can get the path to any directory
# or file from the project root

driver = webdriver.Firefox(drivers_dir)
driver.get('http://www.google.com')

Then PYTHON_PATH will not be used to access the 'definitions.py' file.

Works in PyCharm:
run file 'main.py' (ctrl + shift + F10 in Windows)

Works in CLI from project root:

$ py RootPackge/main.py

Works in CLI from RootPackge:

$ cd RootPackge
$ py main.py

Works from directories above project:

$ cd ../../../../
$ py MyWork/PythoProjects/MyProject/RootPackge/main.py

Works from anywhere if you give an absolute path to the main file.
Doesn't depend on venv.

VBA Excel - Insert row below with same format including borders and frames

Private Sub cmdInsertRow_Click()

    Dim lRow As Long
    Dim lRsp As Long
    On Error Resume Next

    lRow = Selection.Row()
    lRsp = MsgBox("Insert New row above " & lRow & "?", _
            vbQuestion + vbYesNo)
    If lRsp <> vbYes Then Exit Sub

    Rows(lRow).Select
    Selection.Copy
    Rows(lRow + 1).Select
    Selection.Insert Shift:=xlDown
    Application.CutCopyMode = False

   'Paste formulas and conditional formatting in new row created
    Rows(lRow).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone

End Sub

This is what I use. Tested and working,

Thanks,

Create two-dimensional arrays and access sub-arrays in Ruby

You didn't state your actual goal, but maybe this can help:

require 'matrix'  # bundled with Ruby
m = Matrix[
 [1, 2, 3],
 [4, 5, 6]
]

m.column(0) # ==> Vector[1, 4]

(and Vectors acts like arrays)

or, using a similar notation as you desire:

m.minor(0..1, 2..2) # => Matrix[[3], [6]]

Test for multiple cases in a switch, like an OR (||)

You can use fall-through:

switch (pageid)
{
    case "listing-page":
    case "home-page":
        alert("hello");
        break;
    case "details-page":
        alert("goodbye");
        break;
}

Java enum - why use toString instead of name

Use name() when you want to make a comparison or use the hardcoded value for some internal use in your code.

Use toString() when you want to present information to a user (including a developper looking at a log). Never rely in your code on toString() giving a specific value. Never test it against a specific string. If your code breaks when someone correctly changes the toString() return, then it was already broken.

From the javadoc (emphasis mine) :

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

Deploying website: 500 - Internal server error

Server Error 500 - Internal server error. There is a problem with the resource you are looking for, and it cannot be displayed. Goddady. Hosting - Web - Economy - Windows Plesk

In my case, I replace this code:

<configuration> 
  <system.webServer> 
    <httpErrors errorMode="Detailed" /> 
    <asp scriptErrorSentToBrowser="true"/> 
  </system.webServer> 
  <system.web> 
    <customErrors mode="Off"/>
    <compilation debug="true" targetFramework="4.0"/>
  </system.web> 
</configuration>

Then change framework 3.5 to framework 4. It shows my detailed error. I delete code in:

<httpModules></httpModules>

It solved my problem.

Select all 'tr' except the first one

By adding a class to either the first tr or the subsequent trs. There is no crossbrowser way of selecting the rows you want with CSS alone.

However, if you don't care about Internet Explorer 6, 7 or 8:

tr:not(:first-child) {
    color: red;
}

Can Console.Clear be used to only clear a line instead of whole console?

I think I found why there are a few varying answers for this question. When the window has been resized such that it has a horizontal scroll bar (because the buffer is larger than the window) Console.CursorTop seems to return the wrong line. The following code works for me, regardless of window size or cursor position.

public static void ClearLine()
{
    Console.SetCursorPosition(0, Console.CursorTop);
    Console.Write(new string(' ', Console.WindowWidth));
    Console.SetCursorPosition(0, Console.CursorTop - (Console.WindowWidth >= Console.BufferWidth ? 1 : 0));
}

Without the (Console.WindowWidth >= Console.BufferWidth ? 1 : 0), the code may either move the cursor up or down, depending on which version you use from this page, and the state of the window.

Set JavaScript variable = null, or leave undefined?

You can use ''; to declaring NULL variable in Javascript

Create text file and fill it using bash

#!/bin/bash
file_location=/home/test/$1.json
if [ -e $policy ]; then
  echo "File $1.json already exists!"
else
  cat > $file_location <<EOF
{
      "contact": {
          "name": "xyz",
          "phonenumber":   "xxx-xxx-xxxx"
      }
    }
EOF
fi

This code checks if the given JSON file of the user is present in test home directory or not. If it's not present it will create it with the content. You can modify the file location and content according to your needs.

How to get setuptools and easy_install?

please try to install the dependencie with pip, run this command:

sudo pip install -U setuptools

Command line: search and replace in all filenames matched by grep

find . -type f -print0 | xargs -0 <sed/perl/ruby cmd> will process multiple space contained file names at once loading one interpreter per batch. Much faster.

Replace "\\" with "\" in a string in C#

I suspect your string already actually only contains a single backslash, but you're looking at it in the debugger which is escaping it for you into a form which would be valid as a regular string literal in C#.

If print it out in the console, or in a message box, does it show with two backslashes or one?

If you actually want to replace a double backslash with a single one, it's easy to do so:

text = text.Replace(@"\\", @"\");

... but my guess is that the original doesn't contain a double backslash anyway. If this doesn't help, please give more details.

EDIT: In response to the edited question, your stringToBeReplaced only has a single backslash in. Really. Wherever you're seeing two backslashes, that viewer is escaping it. The string itself doesn't have two backslashes. Examine stringToBeReplaced.Length and count the characters.

Calling a php function by onclick event

probably the onclick handler should read onclick='hello();' instead of onclick=hello();

How to set time zone in codeigniter?

Add it to your project/application/config/config.php file, and it will work on all over your site.

date_default_timezone_set('Asia/Kolkata');

Opacity CSS not working in IE8

Using display: inline-block; works on IE8 to resolve this problem.

FWIW, opacity: 0.75 works on all standards-compliant browsers.

AngularJS $http, CORS and http authentication

No you don't have to put credentials, You have to put headers on client side eg:

 $http({
        url: 'url of service',
        method: "POST",
        data: {test :  name },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

And and on server side you have to put headers to this is example for nodejs:

/**
 * On all requests add headers
 */
app.all('*', function(req, res,next) {


    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

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

Your textboxes are probably inside of panels or other containers, and not directly inside the form.

You need to recursively traverse the Controls collection of every child control.

Query EC2 tags from within instance

For Python:

from boto import utils, ec2
from os import environ

# import keys from os.env or use default (not secure)
aws_access_key_id = environ.get('AWS_ACCESS_KEY_ID', failobj='XXXXXXXXXXX')
aws_secret_access_key = environ.get('AWS_SECRET_ACCESS_KEY', failobj='XXXXXXXXXXXXXXXXXXXXX')

#load metadata , if  = {} we are on localhost
# http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AESDG-chapter-instancedata.html
instance_metadata = utils.get_instance_metadata(timeout=0.5, num_retries=1)
region = instance_metadata['placement']['availability-zone'][:-1]
instance_id = instance_metadata['instance-id']

conn = ec2.connect_to_region(region, aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key)
# get tag status for our  instance_id using filters
# http://docs.aws.amazon.com/AWSEC2/latest/CommandLineReference/ApiReference-cmd-DescribeTags.html
tags = conn.get_all_tags(filters={'resource-id': instance_id, 'key': 'status'})
if tags:
    instance_status = tags[0].value
else:
    instance_status = None
    logging.error('no status tag for '+region+' '+instance_id)

Understanding The Modulus Operator %

(This explanation is only for positive numbers since it depends on the language otherwise)

Definition

The Modulus is the remainder of the euclidean division of one number by another. % is called the modulo operation.

For instance, 9 divided by 4 equals 2 but it remains 1. Here, 9 / 4 = 2 and 9 % 4 = 1.

Euclidean Division

In your example: 5 divided by 7 gives 0 but it remains 5 (5 % 7 == 5).

Calculation

The modulo operation can be calculated using this equation:

a % b = a - floor(a / b) * b
  • floor(a / b) represents the number of times you can divide a by b
  • floor(a / b) * b is the amount that was successfully shared entirely
  • The total (a) minus what was shared equals the remainder of the division

Applied to the last example, this gives:

5 % 7 = 5 - floor(5 / 7) * 7 = 5

Modular Arithmetic

That said, your intuition was that it could be -2 and not 5. Actually, in modular arithmetic, -2 = 5 (mod 7) because it exists k in Z such that 7k - 2 = 5.

You may not have learned modular arithmetic, but you have probably used angles and know that -90° is the same as 270° because it is modulo 360. It's similar, it wraps! So take a circle, and say that it's perimeter is 7. Then you read where is 5. And if you try with 10, it should be at 3 because 10 % 7 is 3.

HTML anchor link - href and onclick both?

If the link should only change the location if the function run is successful, then do onclick="return runMyFunction();" and in the function you would return true or false.

If you just want to run the function, and then let the anchor tag do its job, simply remove the return false statement.

As a side note, you should probably use an event handler instead, as inline JS isn't a very optimal way of doing things.

One liner to check if element is in the list

If he really wants a one liner without any collections, OK, he can have one:

for(String s:new String[]{"a", "b", "c")) if (s.equals("a")) System.out.println("It's there");

*smile*

(Isn't it ugly? Please, don't use it in real code)

Trigger Change event when the Input value changed programmatically?

Vanilla JS solution:

var el = document.getElementById('changeProgramatic');
el.value='New Value'
el.dispatchEvent(new Event('change'));

Note that dispatchEvent doesn't work in old IE (see: caniuse). So you should probably only use it on internal websites (not on websites having wide audience).

So as of 2019 you just might want to make sure your customers/audience don't use Windows XP (yes, some still do in 2019). You might want to use conditional comments to warn customers that you don't support old IE (pre IE 11 in this case), but note that conditional comments only work until IE9 (don't work in IE10). So you might want to use feature detection instead. E.g. you could do an early check for: typeof document.body.dispatchEvent === 'function'.

Why can't variables be declared in a switch statement?

Case statements are only labels. This means the compiler will interpret this as a jump directly to the label. In C++, the problem here is one of scope. Your curly brackets define the scope as everything inside the switch statement. This means that you are left with a scope where a jump will be performed further into the code skipping the initialization.

The correct way to handle this is to define a scope specific to that case statement and define your variable within it:

switch (val)
{   
case VAL:  
{
  // This will work
  int newVal = 42;  
  break;
}
case ANOTHER_VAL:  
...
break;
}

C/C++ switch case with string

Typically, you would use a hash table and function object, both available in Boost, TR1 and C++0x.

void func1() {
}
std::unordered_map<std::string, std::function<void()>> hash_map;
hash_map["Value1"] = &func1;
// .... etc
hash_map[mystring]();

This is a little more overhead at runtime but a bajillion times more maintainable. Hash tables offer O(1) insertion, lookup, and etc, which makes them the same complexity as the assembly-style jump-table.

React-router urls don't work when refreshing or writing manually

You can change your .htaccess file and insert this:

<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteCond %{REQUEST_FILENAME} !-l
  RewriteRule . /index.html [L]
</IfModule>

I am using react: "^16.12.0" and react-router: "^5.1.2" This method is the Catch-all and is probably the easiest way to get you started.

ASP.NET MVC 3 - redirect to another action

You will need to return the result of RedirectToAction.

How do I load a file from resource folder?

getResource() was working fine with the resources files placed in src/main/resources only. To get a file which is at the path other than src/main/resources say src/test/java you need to create it exlicitly.

the following example may help you

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

public class Main {
    public static void main(String[] args) throws URISyntaxException, IOException {
        URL location = Main.class.getProtectionDomain().getCodeSource().getLocation();
        BufferedReader br = new BufferedReader(new FileReader(location.getPath().toString().replace("/target/classes/", "/src/test/java/youfilename.txt")));
    }
}

Batch script: how to check for admin rights

Issues

blak3r / Rushyo's solution works fine for everything except Windows 8. Running AT on Windows 8 results in:

The AT command has been deprecated. Please use schtasks.exe instead.

The request is not supported.

(see screenshot #1) and will return %errorLevel% 1.

 

Research

So, I went searching for other commands that require elevated permissions. rationallyparanoid.com had a list of a few, so I ran each command on the two opposite extremes of current Windows OSs (XP and 8) in the hopes of finding a command that would be denied access on both OSs when run with standard permissions.

Eventually, I did find one - NET SESSION. A true, clean, universal solution that doesn't involve:

  • the creation of or interaction with data in secure locations
  • analyzing data returned from FOR loops
  • searching strings for "Administrator"
  • using AT (Windows 8 incompatible) or WHOAMI (Windows XP incompatible).

Each of which have their own security, usability, and portability issues.

 

Testing

I've independently confirmed that this works on:

  • Windows XP, x86
  • Windows XP, x64
  • Windows Vista, x86
  • Windows Vista, x64
  • Windows 7, x86
  • Windows 7, x64
  • Windows 8, x86
  • Windows 8, x64
  • Windows 10 v1909, x64

(see screenshot #2)

 

Implementation / Usage

So, to use this solution, simply do something like this:

@echo off
goto check_Permissions

:check_Permissions
    echo Administrative permissions required. Detecting permissions...

    net session >nul 2>&1
    if %errorLevel% == 0 (
        echo Success: Administrative permissions confirmed.
    ) else (
        echo Failure: Current permissions inadequate.
    )

    pause >nul

Available here, if you're lazy: https://dl.dropbox.com/u/27573003/Distribution/Binaries/check_Permissions.bat

 

Explanation

NET SESSION is a standard command used to "manage server computer connections. Used without parameters, [it] displays information about all sessions with the local computer."

So, here's the basic process of my given implementation:

  1. @echo off
    • Disable displaying of commands
  2. goto check_Permissions
    • Jump to the :check_Permissions code block
  3. net session >nul 2>&1
    • Run command
    • Hide visual output of command by
      1. Redirecting the standard output (numeric handle 1 / STDOUT) stream to nul
      2. Redirecting the standard error output stream (numeric handle 2 / STDERR) to the same destination as numeric handle 1
  4. if %errorLevel% == 0
    • If the value of the exit code (%errorLevel%) is 0 then this means that no errors have occurred and, therefore, the immediate previous command ran successfully
  5. else
    • If the value of the exit code (%errorLevel%) is not 0 then this means that errors have occurred and, therefore, the immediate previous command ran unsuccessfully
  6. The code between the respective parenthesis will be executed depending on which criteria is met

 

Screenshots

Windows 8 AT %errorLevel%:

[imgur]

 

NET SESSION on Windows XP x86 - Windows 8 x64:

[imgur]

 

Thank you, @Tilka, for changing your accepted answer to mine. :)

How do I launch a program from command line without opening a new cmd window?

In Windows 7+ the first quotations will be the title to the cmd window to open the program:

start "title" "C:\path\program.exe"

Formatting your command like the above will temporarily open a cmd window that goes away as fast as it comes up so you really never see it. It also allows you to open more than one program without waiting for the first one to close first.

How to change icon on Google map marker

Manish, Eden after your suggestion: here is the code. But still showing the red(Default) icon.

<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>

<script type="text/javascript">
var markers = [
            {
            "title": 'This is title',
            "lat": '-37.801578',
            "lng": '145.060508',
        "icon": 'http://maps.gstatic.com/mapfiles/ridefinder-images/mm_20_green.png',
            "description": 'Vikash Rathee. <br/><a href="http://www.pricingindia.in/pincode.aspx">Pin Code by City</a>'
        }
];
</script>
<script type="text/javascript">
    window.onload = function () {
        var mapOptions = {
            center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
            zoom: 10,
            flat: true,
            styles: [ { "stylers": [ { "hue": "#4bd6bf" }, { "gamma": "1.58" } ] } ],
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var infoWindow = new google.maps.InfoWindow();
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
        for (i = 0; i < markers.length; i++) {
            var data = markers[i]
            var myLatlng = new google.maps.LatLng(data.lat, data.lng);
            var marker = new google.maps.Marker({
                position: myLatlng,
                map: map,
        icon: markers[i][3],
                title: data.title
            });
            (function (marker, data) {
                google.maps.event.addListener(marker, "click", function (e) {
                    infoWindow.setContent(data.description);
                    infoWindow.open(map, marker);
                });
            })(marker, data);
        }
    }
</script>


<div id="dvMap" style="width: 100%; height: 100%">
</div>

SQL Query to find the last day of the month

Declare @GivenDate datetime 
Declare @ResultDate datetime 
DEclare @EOMDate datetime 
Declare @Day int 
set @GivenDate=getdate() 
set @GivenDate= (dateadd(mm,1,@GivenDate)) 
set @Day =day(@GivenDate) 
set @ResultDate=dateadd(dd,-@Day+1,@GivenDate) 
select @EOMDate =dateadd(dd,-1 ,@ResultDate) 
select @EOMDate 

How to put a text beside the image?

I had a similar issue, where I had one div holding the image, and one div holding the text. The reason mine wasn't working, was that the div holding the image had display: inline-block while the div holding the text had display: inline.

I changed it to both be display: inline and it worked.

Here's a solution for a basic header section with a logo, title and tagline:

HTML

<div class="site-branding">
  <div class="site-branding-logo">
    <img src="add/Your/URI/Here" alt="what Is The Image About?" />
  </div>
</div>
<div class="site-branding-text">
  <h1 id="site-title">Site Title</h1>
  <h2 id="site-tagline">Site Tagline</h2>
</div>

CSS

div.site-branding { /* Position Logo and Text  */
  display: inline-block;
  vertical-align: middle;
}

div.site-branding-logo { /* Position logo within site-branding */
  display: inline;
  vertical-align: middle;
}

div.site-branding-text { /* Position text within site-branding */
    display: inline;
    width: 350px;
    margin: auto 0;
    vertical-align: middle;
}

div.site-branding-title { /* Position title within text */
    display: inline;
}

div.site-branding-tagline { /* Position tagline within text */
    display: block;
}

video as site background? HTML 5

I might have a solution for the video as background, stretched to the browser-width or height, (but the video will still preserve the aspect ratio, couldnt find a solution for that yet.):

Put the video right after the body-tag with style="width:100%;". Right afterwords, put a "bodydummy"-tag:

<body>
<video id="bgVideo" autoplay poster="videos/poster.png">
    <source src="videos/test-h264-640x368-highqual-winff.mp4" type="video/mp4"/>
    <source src="videos/test-640x368-webmvp8-miro.webm" type="video/webm"/>
    <source src="videos/test-640x368-theora-miro.ogv" type="video/ogg"/>    
</video>

<img id="bgImg" src="videos/poster.png" />

<!-- This image stretches exactly to the browser width/height and lies behind the video-->

<div id="bodyDummy">

Put all your content inside the bodydummy-div and put the z-indexes correctly in CSS like this:

#bgImg{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 1;
    width: 100%;
    height: 100%;
}

#bgVideo{ 
    position: absolute;
    top: 0;
    left: 0;
    border: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
}

#bodyDummy{ 
    position: absolute;
    top: 0;
    left: 0;
    z-index: 3;
    overflow: auto;
    width: 100%;
    height: 100%;
}

Hope I could help. Let me know when you could find a solution that the video does not maintain the aspect ratio, so it could fill the whole browser window so we do not have to put a bgimage.

How to set space between listView Items in Android

My solution to add more space but keep the horizontal line was to add divider.xml in the res/drawable folder and define line shape inside:

divider.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="line" >

    <stroke
        android:width="1px"
        android:color="@color/nice_blue" />

</shape>

then in my list I reference my divider as follows:

<ListView
    android:id="@+id/listViewScheduledReminders"
    android:layout_width="match_parent"
    android:layout_height="0dip"
    android:layout_marginBottom="@dimen/mediumMargin"
    android:layout_weight="1"
    android:divider="@drawable/divider"
    android:dividerHeight="16.0dp"
    android:padding="@dimen/smallMargin" >

</ListView>

notice the android:dividerHeight="16.0dp" by increasing and decreasing this height I am basically adding more padding on top and bottom of the divider line.

I used this page for reference: http://developer.android.com/guide/topics/resources/drawable-resource.html#stroke-element

How to check if Thread finished execution

For a thread you have the myThread.IsAlive property. It is false if the thread method returned or the thread was aborted.

How do I remove a key from a JavaScript object?

The delete operator allows you to remove a property from an object.

The following examples all do the same thing.

// Example 1
var key = "Cow";
delete thisIsObject[key]; 

// Example 2
delete thisIsObject["Cow"];

// Example 3
delete thisIsObject.Cow;

If you're interested, read Understanding Delete for an in-depth explanation.

Node.js Port 3000 already in use but it actually isn't?

I also encountered the same issue. The best way to resolve is (for windows):

  1. Go to the Task Manager.

  2. Scroll and find a task process named. Node.js: Server-side JavaScript Image added for reference

  3. End this particular task.

There you go! Now do npm start and it will work as before!

How to insert an item at the beginning of an array in PHP?

Use array_unshift($array, $item);

$arr = array('item2', 'item3', 'item4');
array_unshift($arr , 'item1');
print_r($arr);

will give you

Array
(
 [0] => item1
 [1] => item2
 [2] => item3
 [3] => item4
)

Run bash script as daemon

A Daemon is just program that runs as a background process, rather than being under the direct control of an interactive user...

[The below bash code is for Debian systems - Ubuntu, Linux Mint distros and so on]

The simple way:

The simple way would be to edit your /etc/rc.local file and then just have your script run from there (i.e. everytime you boot up the system):

sudo nano /etc/rc.local

Add the following and save:

#For a BASH script
/bin/sh TheNameOfYourScript.sh > /dev/null &

The better way to do this would be to create a Daemon via Upstart:

sudo nano /etc/init/TheNameOfYourDaemon.conf

add the following:

description "My Daemon Job"
author "Your Name"
start on runlevel [2345]    

pre-start script
  echo "[`date`] My Daemon Starting" >> /var/log/TheNameOfYourDaemonJobLog.log
end script

exec /bin/sh TheNameOfYourScript.sh > /dev/null &

Save this.

Confirm that it looks ok:

init-checkconf /etc/init/TheNameOfYourDaemon.conf

Now reboot the machine:

sudo reboot

Now when you boot up your system, you can see the log file stating that your Daemon is running:

cat  /var/log/TheNameOfYourDaemonJobLog.log

• Now you may start/stop/restart/get the status of your Daemon via:

restart: this will stop, then start a service

sudo service TheNameOfYourDaemonrestart restart

start: this will start a service, if it's not running

sudo service TheNameOfYourDaemonstart start

stop: this will stop a service, if it's running

sudo service TheNameOfYourDaemonstop stop

status: this will display the status of a service

sudo service TheNameOfYourDaemonstatus status

Delete keychain items when an app is uninstalled

For users looking for a Swift 3.0 version of @amro's answer:

let userDefaults = UserDefaults.standard

if !userDefaults.bool(forKey: "hasRunBefore") {
     // Remove Keychain items here

     // Update the flag indicator
     userDefaults.set(true, forKey: "hasRunBefore")
}

*note that synchronize() function is deprecated

Change location of log4j.properties

In Eclipse you can set a VM argument to:

-Dlog4j.configuration=file:///${workspace_loc:/MyProject/log4j-full-debug.properties}

How to find the statistical mode?

Could try the following function:

  1. transform numeric values into factor
  2. use summary() to gain the frequency table
  3. return mode the index whose frequency is the largest
  4. transform factor back to numeric even there are more than 1 mode, this function works well!
mode <- function(x){
  y <- as.factor(x)
  freq <- summary(y)
  mode <- names(freq)[freq[names(freq)] == max(freq)]
  as.numeric(mode)
}

How to do an update + join in PostgreSQL?

Here we go:

update vehicles_vehicle v
set price=s.price_per_vehicle
from shipments_shipment s
where v.shipment_id=s.id;

Simple as I could make it. Thanks guys!

Can also do this:

-- Doesn't work apparently
update vehicles_vehicle 
set price=s.price_per_vehicle
from vehicles_vehicle v
join shipments_shipment s on v.shipment_id=s.id;

But then you've got the vehicle table in there twice, and you're only allowed to alias it once, and you can't use the alias in the "set" portion.

How unique is UUID?

Very safe:

the annual risk of a given person being hit by a meteorite is estimated to be one chance in 17 billion, which means the probability is about 0.00000000006 (6 × 10-11), equivalent to the odds of creating a few tens of trillions of UUIDs in a year and having one duplicate. In other words, only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%.

Caveat:

However, these probabilities only hold when the UUIDs are generated using sufficient entropy. Otherwise, the probability of duplicates could be significantly higher, since the statistical dispersion might be lower. Where unique identifiers are required for distributed applications, so that UUIDs do not clash even when data from many devices is merged, the randomness of the seeds and generators used on every device must be reliable for the life of the application. Where this is not feasible, RFC4122 recommends using a namespace variant instead.

Source: The Random UUID probability of duplicates section of the Wikipedia article on Universally unique identifiers (link leads to a revision from December 2016 before editing reworked the section).

Also see the current section on the same subject on the same Universally unique identifier article, Collisions.

Mocking HttpClient in unit tests

One alternative would be to setup a stub HTTP server that returns canned responses based on pattern matching the request url, meaning you test real HTTP requests not mocks. Historically this would have taken significant develoment effort and would have been far to slow to be considered for unit testing, however OSS library WireMock.net is easy to use and fast enough to be run with lots of tests so may be worth considering. Setup is a few lines of code:

var server = FluentMockServer.Start();
server.Given(
      Request.Create()
      .WithPath("/some/thing").UsingGet()
   )
   .RespondWith(
       Response.Create()
       .WithStatusCode(200)
       .WithHeader("Content-Type", "application/json")
       .WithBody("{'attr':'value'}")
   );

You can find a more details and guidance on using wiremock in tests here.

usr/bin/ld: cannot find -l<nameOfTheLibrary>

To figure out what the linker is looking for, run it in verbose mode.

For example, I encountered this issue while trying to compile MySQL with ZLIB support. I was receiving an error like this during compilation:

/usr/bin/ld: cannot find -lzlib

I did some Googl'ing and kept coming across different issues of the same kind where people would say to make sure the .so file actually exists and if it doesn't, then create a symlink to the versioned file, for example, zlib.so.1.2.8. But, when I checked, zlib.so DID exist. So, I thought, surely that couldn't be the problem.

I came across another post on the Internets that suggested to run make with LD_DEBUG=all:

LD_DEBUG=all make

Although I got a TON of debugging output, it wasn't actually helpful. It added more confusion than anything else. So, I was about to give up.

Then, I had an epiphany. I thought to actually check the help text for the ld command:

ld --help

From that, I figured out how to run ld in verbose mode (imagine that):

ld -lzlib --verbose

This is the output I got:

==================================================
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib64/libzlib.a failed
attempt to open /usr/local/lib64/libzlib.so failed
attempt to open /usr/local/lib64/libzlib.a failed
attempt to open /lib64/libzlib.so failed
attempt to open /lib64/libzlib.a failed
attempt to open /usr/lib64/libzlib.so failed
attempt to open /usr/lib64/libzlib.a failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.so failed
attempt to open /usr/x86_64-linux-gnu/lib/libzlib.a failed
attempt to open /usr/local/lib/libzlib.so failed
attempt to open /usr/local/lib/libzlib.a failed
attempt to open /lib/libzlib.so failed
attempt to open /lib/libzlib.a failed
attempt to open /usr/lib/libzlib.so failed
attempt to open /usr/lib/libzlib.a failed
/usr/bin/ld.bfd.real: cannot find -lzlib

Ding, ding, ding...

So, to finally fix it so I could compile MySQL with my own version of ZLIB (rather than the bundled version):

sudo ln -s /usr/lib/libz.so.1.2.8 /usr/lib/libzlib.so

Voila!

Properly escape a double quote in CSV

If a value contains a comma, a newline character or a double quote, then the string must be enclosed in double quotes. E.g: "Newline char in this field \n".

You can use below online tool to escape "" and , operators. https://www.freeformatter.com/csv-escape.html#ad-output

How do I split an int into its digits?

    int power(int n, int b) {
    int number;
    number = pow(n, b);
    return number;
}


void NumberOfDigits() {
    int n, a;
    printf("Eneter number \n");
    scanf_s("%d", &n);
    int i = 0;
    do{
        i++;
    } while (n / pow(10, i) > 1);
    printf("Number of digits is: \t %d \n", i);

    for (int j = i-1; j >= 0; j--) {
        a = n / power(10, j) % 10;
        printf("%d \n", a);
    }
}

int main(void) {
    NumberOfDigits();
}

Update with two tables?

It can be as follows:

UPDATE A 
SET A.`id` = (SELECT id from B WHERE A.title = B.title)

How to change a field name in JSON using Jackson

Have you tried using @JsonProperty?

@Entity
public class City {
   @id
   Long id;
   String name;

   @JsonProperty("label")
   public String getName() { return name; }

   public void setName(String name){ this.name = name; }

   @JsonProperty("value")
   public Long getId() { return id; }

   public void setId(Long id){ this.id = id; }
}

How to Identify Microsoft Edge browser via CSS?

More accurate for Edge (do not include latest IE 15) is:

@supports (display:-ms-grid) { ... }

@supports (-ms-ime-align:auto) { ... } works for all Edge versions (currently up to IE15).

jQuery - Add active class and remove active from other element on click

Try this one:

$(document).ready(function() {
    $(".tab").click(function () {
        $("this").addClass("active").siblings().removeClass("active");   
    });
});

How to implement drop down list in flutter?

Change

List<String> _locations = ['A', 'B', 'C', 'D'];

To

List<String> _locations = [_selectedLocation, 'A', 'B', 'C', 'D'];

_selectedLocation needs to be part of your item List;

How to scan a folder in Java?

You can also use the FileFilter interface to filter out what you want. It is best used when you create an anonymous class that implements it:

import java.io.File;
import java.io.FileFilter;

public class ListFiles {
    public File[] findDirectories(File root) { 
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isDirectory();
            }});
    }

    public File[] findFiles(File root) {
        return root.listFiles(new FileFilter() {
            public boolean accept(File f) {
                return f.isFile();
            }});
    }
}

Displaying Windows command prompt output and redirecting it to a file

A simple C# console application would do the trick:

using System;
using System.Collections.Generic;
using System.IO;

namespace CopyToFiles
{
    class Program
    {
        static void Main(string[] args)
        {
            var buffer = new char[100];
            var outputs = new List<TextWriter>();

            foreach (var file in args)
                outputs.Add(new StreamWriter(file));

            outputs.Add(Console.Out);

            int bytesRead;
            do
            {
                bytesRead = Console.In.ReadBlock(buffer, 0, buffer.Length);
                outputs.ForEach(o => o.Write(buffer, 0, bytesRead));
            } while (bytesRead == buffer.Length);

            outputs.ForEach(o => o.Close());
        }
    }
}

To use this you just pipe the source command into the program and provide the path of any files you want to duplicate the output to. For example:

dir | CopyToFiles files1.txt files2.txt 

Will display the results of dir as well as store the results in both files1.txt and files2.txt.

Note that there isn't much (anything!) in the way of error handling above, and supporting multiple files may not actually be required.

Django Rest Framework -- no module named rest_framework

Also, check for the possibility of a tiny typo:

It's rest_framework with an underscore (_) in between!

Took me a while to figure out that I was using a dash instead...

How to combine 2 plots (ggplot) into one plot?

Creating a single combined plot with your current data set up would look something like this

p <- ggplot() +
      # blue plot
      geom_point(data=visual1, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual1, aes(x=ISSUE_DATE, y=COUNTED), fill="blue",
        colour="darkblue", size=1) +
      # red plot
      geom_point(data=visual2, aes(x=ISSUE_DATE, y=COUNTED)) + 
      geom_smooth(data=visual2, aes(x=ISSUE_DATE, y=COUNTED), fill="red",
        colour="red", size=1)

however if you could combine the data sets before plotting then ggplot will automatically give you a legend, and in general the code looks a bit cleaner

visual1$group <- 1
visual2$group <- 2

visual12 <- rbind(visual1, visual2)

p <- ggplot(visual12, aes(x=ISSUE_DATE, y=COUNTED, group=group, col=group, fill=group)) +
      geom_point() +
      geom_smooth(size=1)

apache server reached MaxClients setting, consider raising the MaxClients setting

I recommend to use bellow formula suggested on Apache:

MaxClients = (total RAM - RAM for OS - RAM for external programs) / (RAM per httpd process)

Find my script here which is running on Rhel 6.7. you can made change according to your OS.

#!/bin/bash

echo "HostName=`hostname`"

#Formula
#MaxClients . (RAM - size_all_other_processes)/(size_apache_process)
total_httpd_processes_size=`ps -ylC httpd --sort:rss | awk '{ sum += $9 } END { print sum }'`
#echo "total_httpd_processes_size=$total_httpd_processes_size"
total_http_processes_count=`ps -ylC httpd --sort:rss | wc -l`
echo "total_http_processes_count=$total_http_processes_count"
AVG_httpd_process_size=$(expr $total_httpd_processes_size / $total_http_processes_count)
echo "AVG_httpd_process_size=$AVG_httpd_process_size"
total_httpd_process_size_MB=$(expr $AVG_httpd_process_size / 1024)
echo "total_httpd_process_size_MB=$total_httpd_process_size_MB"
total_pttpd_used_size=$(expr $total_httpd_processes_size / 1024)
echo "total_pttpd_used_size=$total_pttpd_used_size"
total_RAM_size=`free -m |grep Mem |awk '{print $2}'`
echo "total_RAM_size=$total_RAM_size"
total_used_size=`free -m |grep Mem |awk '{print $3}'`
echo "total_used_size=$total_used_size"
size_all_other_processes=$(expr $total_used_size - $total_pttpd_used_size)
echo "size_all_other_processes=$size_all_other_processes"
remaining_memory=$(($total_RAM_size - $size_all_other_processes))
echo "remaining_memory=$remaining_memory"
MaxClients=$((($total_RAM_size - $size_all_other_processes) / $total_httpd_process_size_MB))
echo "MaxClients=$MaxClients"
exit

How do I create a readable diff of two spreadsheets using git diff?

I found an openoffice macro here that will invoke openoffice's compare documents function on two files. Unfortunately, openoffice's spreadsheet compare seems a little flaky; I just had the 'Reject All' button insert a superfluous column in my document.

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

Option 1:

You can set CMake variables at command line like this:

cmake -D CMAKE_C_COMPILER="/path/to/your/c/compiler/executable" -D CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable" /path/to/directory/containing/CMakeLists.txt

See this to learn how to create a CMake cache entry.


Option 2:

In your shell script build_ios.sh you can set environment variables CC and CXX to point to your C and C++ compiler executable respectively, example:

export CC=/path/to/your/c/compiler/executable
export CXX=/path/to/your/cpp/compiler/executable
cmake /path/to/directory/containing/CMakeLists.txt

Option 3:

Edit the CMakeLists.txt file of "Assimp": Add these lines at the top (must be added before you use project() or enable_language() command)

set(CMAKE_C_COMPILER "/path/to/your/c/compiler/executable")
set(CMAKE_CXX_COMPILER "/path/to/your/cpp/compiler/executable")

See this to learn how to use set command in CMake. Also this is a useful resource for understanding use of some of the common CMake variables.


Here is the relevant entry from the official FAQ: https://gitlab.kitware.com/cmake/community/wikis/FAQ#how-do-i-use-a-different-compiler

SQL - select distinct only on one column

You will use the following query:

SELECT * FROM [table] GROUP BY NUMBER;

Where [table] is the name of the table.

This provides a unique listing for the NUMBER column however the other columns may be meaningless depending on the vendor implementation; which is to say they may not together correspond to a specific row or rows.

What is the difference between decodeURIComponent and decodeURI?

decodeURIComponent will decode URI special markers such as &, ?, #, etc, decodeURI will not.

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

On Chrome's latest update (38.0.2125.104 m at the moment), Google added the option to know whether the files loaded to the website were newly downloaded from the server - or read from the local cache.

When an error like yours "hits" the console - you know the files were just downloaded from the server and not read from the local cache. You can recreate this error by clicking Ctrl + F5 (refresh and erase cache).

It fits your description where Firebug (or equivalents) doesn't fire any errors to the console - whilst Chrome does.

So, the bottom line is - your're just fine and you can ignore this error - it's merely an indicator.

How to run multiple SQL commands in a single SQL connection?

I have not tested , but what the main idea is: put semicolon on each query.

SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = @"
     update table
     set somecol = somevalue;
     insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;

try
{
    connection.Open();
}
finally
{
    command.Dispose();
    connection.Dispose();
}

Update: you can follow Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too

Convert to absolute value in Objective-C

You can use this function to get the absolute value:

+(NSNumber *)absoluteValue:(NSNumber *)input {
  return [NSNumber numberWithDouble:fabs([input doubleValue])];
}

Can I have H2 autocreate a schema in an in-memory database?

If you are using spring with application.yml the following will work for you

spring: datasource: url: jdbc:h2:mem:mydb;DB_CLOSE_ON_EXIT=FALSE;MODE=PostgreSQL;INIT=CREATE SCHEMA IF NOT EXISTS calendar

How to include static library in makefile

use

LDFLAGS= -L<Directory where the library resides> -l<library name>

Like :

LDFLAGS = -L. -lmine

for ensuring static compilation you can also add

LDFLAGS = -static

Or you can just get rid of the whole library searching, and link with with it directly.

say you have main.c fun.c

and a static library libmine.a

then you can just do in your final link line of the Makefile

$(CC) $(CFLAGS) main.o fun.o libmine.a

Put quotes around a variable string in JavaScript

let's think urls = "http://example1.com http://example2.com"

function somefunction(urls){
var urlarray = urls.split(" ");
var text = "\"'" + urlarray[0] + "'\"";
}

output will be text = "'http://example1.com'"

Getting 400 bad request error in Jquery Ajax POST

Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.

400 Bad Request

Bad Request. Your browser sent a request that this server could not understand.

Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.

415 Unsupported Media Type

Try this.

var newData =   {
                  "subject:title":"Test Name",
                  "subject:description":"Creating test subject to check POST method API",
                  "sub:tags": ["facebook:work", "facebook:likes"],
                  "sampleSize" : 10,
                  "values": ["science", "machine-learning"]
                  };

var dataJson = JSON.stringify(newData);

$.ajax({
  type: 'POST',
  url: "http://localhost:8080/project/server/rest/subjects",
  data: dataJson,
  error: function(e) {
    console.log(e);
  },
  dataType: "json",
  contentType: "application/json"
});

With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.

How to SHUTDOWN Tomcat in Ubuntu?

Caveat: I'm running Ubuntu

sudo service --status-all

you can get a list of all running services by typing this command,

If you're running Tomcat as a service it will showes up as ("tomcat"), so run :

sudo service tomcat7 stop

(tomcat7 or 8 or depending to the name that you have in the list of running services )

else and if you are using apache tomcat you will see ("apache2") showing up with the list of services then run :

sudo service apache2 stop

Is there a JSON equivalent of XQuery/XPath?

XQuery can be used to query JSON, provided that the processor offers JSON support. This is a straightforward example how BaseX can be used to find objects with "id" = 1:

json:parse('[
    { "id": 1, "name": "One", "objects": [
        { "id": 1, "name": "Response 1", "objects": [ "etc." ] }
    ]}
]')//value[.//id = 1]

How can I open a link in a new window?

You can also use the jquery prop() method for this.

$(function(){
  $('yourselector').prop('target', '_blank');
}); 

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

I received the 'exited with code 4' error when the xcopy command tried to overwrite a readonly file. I managed to solve this problem by adding /R to the xcopy command. The /R indicates read only files should be overwritten

old command:

XCOPY /E /Y "$(ProjectDir)source file" "destination"

new command

XCOPY /E /Y /R "$(ProjectDir)source file" "destination"

Python - Using regex to find multiple matches and print them out

Using regexes for this purpose is the wrong approach. Since you are using python you have a really awesome library available to extract parts from HTML documents: BeautifulSoup.

Simple proof that GUID is not unique

Of course GUIDs can collide. Since GUIDs are 128-bits, just generate 2^128 + 1 of them and by the pigeonhole principle there must be a collision.

But when we say that a GUID is a unique, what we really mean is that the key space is so large that it is practically impossible to accidentally generate the same GUID twice (assuming that we are generating GUIDs randomly).

If you generate a sequence of n GUIDs randomly, then the probability of at least one collision is approximately p(n) = 1 - exp(-n^2 / 2 * 2^128) (this is the birthday problem with the number of possible birthdays being 2^128).

   n     p(n)
2^30 1.69e-21
2^40 1.77e-15
2^50 1.86e-10
2^60 1.95e-03

To make these numbers concrete, 2^60 = 1.15e+18. So, if you generate one billion GUIDs per second, it will take you 36 years to generate 2^60 random GUIDs and even then the probability that you have a collision is still 1.95e-03. You're more likely to be murdered at some point in your life (4.76e-03) than you are to find a collision over the next 36 years. Good luck.

Open an image using URI in Android's default gallery image viewer

This thing might help if your working with android N and below

 File file=new File(Environment.getExternalStorageDirectory()+"/directoryname/"+filename);
        Uri path= FileProvider.getUriForFile(MainActivity.this,BuildConfig.APPLICATION_ID + ".provider",file);

        Intent intent=new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(path,"image/*");
        intent.setFlags(FLAG_GRANT_READ_URI_PERMISSION | FLAG_GRANT_WRITE_URI_PERMISSION); //must for reading data from directory

How to configure Chrome's Java plugin so it uses an existing JDK in the machine

On Windows 7 64-bit, I added the registry entry using the following script:

@echo off
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Description" /t REG_SZ /d "Oracle Next Generation Java Plug-In"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "GeckoVersion" /t REG_SZ /d "1.9"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Path" /t REG_SZ /d "C:\Oracle\jdev11123\jdk160_24\jre\bin\new_plugin\npjp2.dll"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "ProductName" /t REG_SZ /d "Oracle Java Plug-In"
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Vendor" /t REG_SZ /d "Oracle Corp."
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\MozillaPlugins\@java.com/JavaPlugin" /v "Version" /t REG_SZ /d "10.3.1"

Note that you will have to change the Path.

How to delete a character from a string using Python

In Python, strings are immutable, so you have to create a new string. You have a few options of how to create the new string. If you want to remove the 'M' wherever it appears:

newstr = oldstr.replace("M", "")

If you want to remove the central character:

midlen = len(oldstr)/2   # //2 in python 3
newstr = oldstr[:midlen] + oldstr[midlen+1:]

You asked if strings end with a special character. No, you are thinking like a C programmer. In Python, strings are stored with their length, so any byte value, including \0, can appear in a string.

Regex to check with starts with http://, https:// or ftp://

You need a whole input match here.

System.out.println(test.matches("^(http|https|ftp)://.*$")); 

Edit:(Based on @davidchambers's comment)

System.out.println(test.matches("^(https?|ftp)://.*$")); 

Why is it said that "HTTP is a stateless protocol"?

Even though multiple requests can be sent over the same HTTP connection, the server does not attach any special meaning to their arriving over the same socket. That is solely a performance thing, intended to minimize the time/bandwidth that'd otherwise be spent reestablishing a connection for each request.

As far as HTTP is concerned, they are all still separate requests and must contain enough information on their own to fulfill the request. That is the essence of "statelessness". Requests will not be associated with each other absent some shared info the server knows about, which in most cases is a session ID in a cookie.

JavaScript - Get minutes between two dates

The following code worked for me,

function timeDiffCalc(dateNow,dateFuture) {
    var newYear1 = new Date(dateNow);
    var newYear2 = new Date(dateFuture);

        var dif = (newYear2 - newYear1);
        var dif = Math.round((dif/1000)/60);
        console.log(dif);

}

How to set root password to null

The answer by user64141

use mysql;
update user set password=null where User='root';
flush privileges;
quit;

didn't work for me in MariaDB 10.1.5 (supposed to be a drop in replacement for MySQL). While didn't tested it in MySQL 5.6 to see if is an upstream change, the error I got was:

ERROR 1048 (23000): Column 'Password' cannot be null

But replacing the null with empty single or double quotes worked fine.

update user set password='' where User='root';

or

update user set password="" where User='root';

Rethrowing exceptions in Java without losing the stack trace

something like this

try 
{
  ...
}
catch (FooException e) 
{
  throw e;
}
catch (Exception e)
{
  ...
}

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

Provide the :name option to add_index, e.g.:

add_index :studies,
  ["user_id", "university_id", "subject_name_id", "subject_type_id"], 
  unique: true,
  name: 'my_index'

If using the :index option on references in a create_table block, it takes the same options hash as add_index as its value:

t.references :long_name, index: { name: :my_index }

Get battery level and state in Android

Here is a code sample that explains how to get battery information.

To sum it up, a broadcast receiver for the ACTION_BATTERY_CHANGED intent is set up dynamically, because it can not be received through components declared in manifests, only by explicitly registering for it with Context.registerReceiver().

public class Main extends Activity {
  private TextView batteryTxt;
  private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
    @Override
    public void onReceive(Context ctxt, Intent intent) {
      int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
      int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
      float batteryPct = level * 100 / (float)scale;
      batteryTxt.setText(String.valueOf(batteryPct) + "%");
    }
  };

  @Override
  public void onCreate(Bundle b) {
    super.onCreate(b);
    setContentView(R.layout.main);
    batteryTxt = (TextView) this.findViewById(R.id.batteryTxt);
    this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
  }
}

Using .otf fonts on web browsers

From the Google Font Directory examples:

@font-face {
  font-family: 'Tangerine';
  font-style: normal;
  font-weight: normal;
  src: local('Tangerine'), url('http://example.com/tangerine.ttf') format('truetype');
}
body {
  font-family: 'Tangerine', serif;
  font-size: 48px;
}

This works cross browser with .ttf, I believe it may work with .otf. (Wikipedia says .otf is mostly backwards compatible with .ttf) If not, you can convert the .otf to .ttf

Here are some good sites:

How to Convert Int to Unsigned Byte and Back

Java 8 provides Byte.toUnsignedInt to convert byte to int by unsigned conversion. In Oracle's JDK this is simply implemented as return ((int) x) & 0xff; because HotSpot already understands how to optimize this pattern, but it could be intrinsified on other VMs. More importantly, no prior knowledge is needed to understand what a call to toUnsignedInt(foo) does.

In total, Java 8 provides methods to convert byte and short to unsigned int and long, and int to unsigned long. A method to convert byte to unsigned short was deliberately omitted because the JVM only provides arithmetic on int and long anyway.

To convert an int back to a byte, just use a cast: (byte)someInt. The resulting narrowing primitive conversion will discard all but the last 8 bits.

Is there a way to pass optional parameters to a function?

You can specify a default value for the optional argument with something that would never passed to the function and check it with the is operator:

class _NO_DEFAULT:
    def __repr__(self):return "<no default>"
_NO_DEFAULT = _NO_DEFAULT()

def func(optional= _NO_DEFAULT):
    if optional is _NO_DEFAULT:
        print("the optional argument was not passed")
    else:
        print("the optional argument was:",optional)

then as long as you do not do func(_NO_DEFAULT) you can be accurately detect whether the argument was passed or not, and unlike the accepted answer you don't have to worry about side effects of ** notation:

# these two work the same as using **
func()
func(optional=1)

# the optional argument can be positional or keyword unlike using **
func(1) 

#this correctly raises an error where as it would need to be explicitly checked when using **
func(invalid_arg=7)

How can I generate Unix timestamps?

In Bash 5 there's a new variable:

echo $EPOCHSECONDS

Or if you want higher precision (in microseconds):

echo $EPOCHREALTIME

How to compare only Date without Time in DateTime types in Linq to SQL with Entity Framework?

You can try

if(dtOne.Year == dtTwo.Year && dtOne.Month == dtTwo.Month && dtOne.Day == dtTwo.Day)
  ....

JBoss default password

I just had to uncomment the line in jboss-eap-5.0\jboss-as\server\default\conf\props\jmx-console-users.properties

admin=admin

Thats it. Restart Jboss and I was about to get in to JBOSS JMX. Magically this even fixed the error that I used to get while shutting down Jboss from Eclipse.

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

I researched on the internet and some answers includes enabling the "access for lesser app" and "unlocking gmail captcha" which sadly didn't work for me until I found the 2-step verification.

What I did the following was:

  1. enable the 2-step verification to google HERE

  2. Create App Password to be use by your system HERE

  3. I selected Others (custom name) and clicked generate

  4. Went to my env file in laravel and edited this

    [email protected]

    MAIL_PASSWORD=thepasswordgenerated

  5. Restarted my apache server and boom! It works again.

This was my solution. I created this to atleast make other people not go wasting their time researching for a possible answer.

Best way to check for IE less than 9 in JavaScript without library

This link contains relevant information on detecting versions of Internet Explorer:

http://tanalin.com/en/articles/ie-version-js/

Example:

if (document.all && !document.addEventListener) {
    alert('IE8 or older.');
}

How to measure height, width and distance of object using camera?

You can't.. You would have to know:

  • How far is the object (you can know your location from GPS.. but the object's location?)
  • What is the focal length of the camera

Maybe, just maybe if the object was optically tagged with for example a QR code, and you have a code-to-loc map...

How do I ignore all files in a folder with a Git repository in Sourcetree?

If your Ignore option is grayed out, you have to stop tracking the file before you can ignore it. You can simply right click on the file and hit "Stop Tracking".

A blue icon should appear next to it. Right click on it again and click ignore.

How do I get a PHP class constructor to call its parent's parent's constructor?

// main class that everything inherits
class Grandpa 
{
    public function __construct()
    {
        $this->___construct();
    }

    protected function ___construct()
    {
        // grandpa's logic
    }

}

class Papa extends Grandpa
{
    public function __construct()
    {
        // call Grandpa's constructor
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public function __construct()
    {
        parent::___construct();
    }
}

note that "___construct" is not some magic name, you can call it "doGrandpaStuff".

How to make bootstrap column height to 100% row height?

@Alan's answer will do what you're looking for, but this solution fails when you use the responsive capabilities of Bootstrap. In your case, you're using the xs sizes so you won't notice, but if you used anything else (e.g. col-sm, col-md, etc), you'd understand.

Another approach is to play with margins and padding. See the updated fiddle: http://jsfiddle.net/jz8j247x/1/

.left-side {
  background-color: blue;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.something {
  height: 100%;
  background-color: red;
  padding-bottom: 1000px;
  margin-bottom: -1000px;
  height: 100%;
}
.row {
  background-color: green;
  overflow: hidden;
}

How to outline text in HTML / CSS

With HTML5's support for svg, you don't need to rely on shadow hacks.

_x000D_
_x000D_
<svg  width="100%" viewBox="0 0 600 100">_x000D_
<text x=0 y=20 font-size=12pt fill=white stroke=black stroke-width=0.75>_x000D_
    This text exposes its vector representation, _x000D_
    making it easy to style shape-wise without hacks. _x000D_
    HTML5 supports it, so no browser issues. Only downside _x000D_
    is that svg has its own quirks and learning curve _x000D_
    (c.f. bounding box issue/no typesetting by default)_x000D_
</text>_x000D_
</svg>
_x000D_
_x000D_
_x000D_

Could not determine the dependencies of task ':app:crashlyticsStoreDeobsDebug' if I enable the proguard

You can run this command in your project directory. Basically it just cleans the build and gradle.

   cd android && rm -R .gradle && cd app && rm -R build

In my case, I was using react-native using this as a script in package.json

"scripts": { "clean-android": "cd android && rm -R .gradle && cd app && rm -R build" }

Is it possible to change a UIButtons background color?

Swift 3:

        static func imageFromColor(color: UIColor, width: CGFloat, height: CGFloat) -> UIImage {
            let rect = CGRect(x: 0, y: 0, width: width, height: height)
            UIGraphicsBeginImageContext(rect.size)
            let context = UIGraphicsGetCurrentContext()!
            context.setFillColor(color.cgColor)
            context.fill(rect)
            let img = UIGraphicsGetImageFromCurrentImageContext()!
            UIGraphicsEndImageContext()
            return img
        }

        let button = UIButton(type: .system)
        let image = imageFromColor(color: .red, width: 
        button.frame.size.width, height: button.frame.size.height)
        button.setBackgroundImage(image, for: .normal)

Fastest way to write huge data in text file Java

_x000D_
_x000D_
package all.is.well;_x000D_
import java.io.IOException;_x000D_
import java.io.RandomAccessFile;_x000D_
import java.util.concurrent.ExecutorService;_x000D_
import java.util.concurrent.Executors;_x000D_
import junit.framework.TestCase;_x000D_
_x000D_
/**_x000D_
 * @author Naresh Bhabat_x000D_
 * _x000D_
Following  implementation helps to deal with extra large files in java._x000D_
This program is tested for dealing with 2GB input file._x000D_
There are some points where extra logic can be added in future._x000D_
_x000D_
_x000D_
Pleasenote: if we want to deal with binary input file, then instead of reading line,we need to read bytes from read file object._x000D_
_x000D_
_x000D_
_x000D_
It uses random access file,which is almost like streaming API._x000D_
_x000D_
_x000D_
 * ****************************************_x000D_
Notes regarding executor framework and its readings._x000D_
Please note :ExecutorService executor = Executors.newFixedThreadPool(10);_x000D_
_x000D_
 *      for 10 threads:Total time required for reading and writing the text in_x000D_
 *         :seconds 349.317_x000D_
 * _x000D_
 *         For 100:Total time required for reading the text and writing   : seconds 464.042_x000D_
 * _x000D_
 *         For 1000 : Total time required for reading and writing text :466.538 _x000D_
 *         For 10000  Total time required for reading and writing in seconds 479.701_x000D_
 *_x000D_
 * _x000D_
 */_x000D_
public class DealWithHugeRecordsinFile extends TestCase {_x000D_
_x000D_
 static final String FILEPATH = "C:\\springbatch\\bigfile1.txt.txt";_x000D_
 static final String FILEPATH_WRITE = "C:\\springbatch\\writinghere.txt";_x000D_
 static volatile RandomAccessFile fileToWrite;_x000D_
 static volatile RandomAccessFile file;_x000D_
 static volatile String fileContentsIter;_x000D_
 static volatile int position = 0;_x000D_
_x000D_
 public static void main(String[] args) throws IOException, InterruptedException {_x000D_
  long currentTimeMillis = System.currentTimeMillis();_x000D_
_x000D_
  try {_x000D_
   fileToWrite = new RandomAccessFile(FILEPATH_WRITE, "rw");//for random write,independent of thread obstacles _x000D_
   file = new RandomAccessFile(FILEPATH, "r");//for random read,independent of thread obstacles _x000D_
   seriouslyReadProcessAndWriteAsynch();_x000D_
_x000D_
  } catch (IOException e) {_x000D_
   // TODO Auto-generated catch block_x000D_
   e.printStackTrace();_x000D_
  }_x000D_
  Thread currentThread = Thread.currentThread();_x000D_
  System.out.println(currentThread.getName());_x000D_
  long currentTimeMillis2 = System.currentTimeMillis();_x000D_
  double time_seconds = (currentTimeMillis2 - currentTimeMillis) / 1000.0;_x000D_
  System.out.println("Total time required for reading the text in seconds " + time_seconds);_x000D_
_x000D_
 }_x000D_
_x000D_
 /**_x000D_
  * @throws IOException_x000D_
  * Something  asynchronously serious_x000D_
  */_x000D_
 public static void seriouslyReadProcessAndWriteAsynch() throws IOException {_x000D_
  ExecutorService executor = Executors.newFixedThreadPool(10);//pls see for explanation in comments section of the class_x000D_
  while (true) {_x000D_
   String readLine = file.readLine();_x000D_
   if (readLine == null) {_x000D_
    break;_x000D_
   }_x000D_
   Runnable genuineWorker = new Runnable() {_x000D_
    @Override_x000D_
    public void run() {_x000D_
     // do hard processing here in this thread,i have consumed_x000D_
     // some time and eat some exception in write method._x000D_
     writeToFile(FILEPATH_WRITE, readLine);_x000D_
     // System.out.println(" :" +_x000D_
     // Thread.currentThread().getName());_x000D_
_x000D_
    }_x000D_
   };_x000D_
   executor.execute(genuineWorker);_x000D_
  }_x000D_
  executor.shutdown();_x000D_
  while (!executor.isTerminated()) {_x000D_
  }_x000D_
  System.out.println("Finished all threads");_x000D_
  file.close();_x000D_
  fileToWrite.close();_x000D_
 }_x000D_
_x000D_
 /**_x000D_
  * @param filePath_x000D_
  * @param data_x000D_
  * @param position_x000D_
  */_x000D_
 private static void writeToFile(String filePath, String data) {_x000D_
  try {_x000D_
   // fileToWrite.seek(position);_x000D_
   data = "\n" + data;_x000D_
   if (!data.contains("Randomization")) {_x000D_
    return;_x000D_
   }_x000D_
   System.out.println("Let us do something time consuming to make this thread busy"+(position++) + "   :" + data);_x000D_
   System.out.println("Lets consume through this loop");_x000D_
   int i=1000;_x000D_
   while(i>0){_x000D_
   _x000D_
    i--;_x000D_
   }_x000D_
   fileToWrite.write(data.getBytes());_x000D_
   throw new Exception();_x000D_
  } catch (Exception exception) {_x000D_
   System.out.println("exception was thrown but still we are able to proceeed further"_x000D_
     + " \n This can be used for marking failure of the records");_x000D_
   //exception.printStackTrace();_x000D_
_x000D_
  }_x000D_
_x000D_
 }_x000D_
}
_x000D_
_x000D_
_x000D_

How to assign an action for UIImageView object in Swift

Swift 4 Code


Step 1 In ViewdidLoad()

   let pictureTap = UITapGestureRecognizer(target: self, action: #selector(MyInfoTableViewController.imageTapped))
       userImageView.addGestureRecognizer(pictureTap)
       userImageView.isUserInteractionEnabled = true

Step 2 Add Following Function

@objc func imageTapped() {

        let imageView = userImageView
        let newImageView = UIImageView(image: imageView?.image)
        newImageView.frame = UIScreen.main.bounds
        newImageView.backgroundColor = UIColor.black
        newImageView.contentMode = .scaleAspectFit
        newImageView.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer(target: self, action: #selector(dismissFullscreenImage))
        newImageView.addGestureRecognizer(tap)
        self.view.addSubview(newImageView)

        self.navigationController?.isNavigationBarHidden = true
        self.tabBarController?.tabBar.isHidden = true

    }

It's Tested And Working Properly

Bring a window to the front in WPF

To make this a quick copy-paste one -
Use this class' DoOnProcess method to move process' main window to foreground (but not to steal focus from other windows)

public class MoveToForeground
{
    [DllImportAttribute("User32.dll")]
    private static extern int FindWindow(String ClassName, String WindowName);

    const int SWP_NOMOVE        = 0x0002;
    const int SWP_NOSIZE        = 0x0001;            
    const int SWP_SHOWWINDOW    = 0x0040;
    const int SWP_NOACTIVATE    = 0x0010;
    [DllImport("user32.dll", EntryPoint = "SetWindowPos")]
    public static extern IntPtr SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int x, int Y, int cx, int cy, int wFlags);

    public static void DoOnProcess(string processName)
    {
        var allProcs = Process.GetProcessesByName(processName);
        if (allProcs.Length > 0)
        {
            Process proc = allProcs[0];
            int hWnd = FindWindow(null, proc.MainWindowTitle.ToString());
            // Change behavior by settings the wFlags params. See http://msdn.microsoft.com/en-us/library/ms633545(VS.85).aspx
            SetWindowPos(new IntPtr(hWnd), 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW | SWP_NOACTIVATE);
        }
    }
}

HTH

Decode HTML entities in Python string?

You can use replace_entities from w3lib.html library

In [202]: from w3lib.html import replace_entities

In [203]: replace_entities("&pound;682m")
Out[203]: u'\xa3682m'

In [204]: print replace_entities("&pound;682m")
£682m

Forward X11 failed: Network error: Connection refused

Other answers are outdated, or incomplete, or simply don't work.

You need to also specify an X-11 server on the host machine to handle the launch of GUId programs. If the client is a Windows machine install Xming. If the client is a Linux machine install XQuartz.

Now suppose this is Windows connecting to Linux. In order to be able to launch X11 programs as well over putty do the following:

- Launch XMing on Windows client
- Launch Putty
    * Fill in basic options as you know in session category
    * Connection -> SSH -> X11
        -> Enable X11 forwarding
        -> X display location = :0.0
        -> MIT-Magic-Cookie-1
        -> X authority file for local display = point to the Xming.exe executable

Of course the ssh server should have permitted Desktop Sharing "Allow other user to view your desktop".

MobaXterm and other complete remote desktop programs work too.

"Default Activity Not Found" on Android Studio upgrade

check all the line in your manifest.

in my case i have this error :

android:theme="@android:style/Theme.Wallpaper.NoTitleBar.Fullscreen"

nothing in the logcat

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

Difference between classification and clustering in data mining?

By clustering, you can group data with your desired properties such as the number, the shape, and other properties of extracted clusters. While, in classification, the number and the shape of groups are fixed. Most of the clustering algorithms give the number of clusters as a parameter. However, there are some approaches to find out the appropriate number of clusters.