Programs & Examples On #Utf

Unicode Transformation Format (8/16/32/...) used for encoding Unicode code points

How to convert php array to utf8?

You can send the array to this function:

function utf8_converter($array){
    array_walk_recursive($array, function(&$item, $key){
        if(!mb_detect_encoding($item, 'utf-8', true)){
            $item = utf8_encode($item);
        }
    }); 
    return $array;
}

It works for me.

Unicode, UTF, ASCII, ANSI format differences

Some reading to get you started on character encodings: Joel on Software: The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

By the way - ASP.NET has nothing to do with it. Encodings are universal.

Difference between UTF-8 and UTF-16?

This is unrelated to UTF-8/16 (in general, although it does convert to UTF16 and the BE/LE part can be set w/ a single line), yet below is the fastest way to convert String to byte[]. For instance: good exactly for the case provided (hash code). String.getBytes(enc) is relatively slow.

static byte[] toBytes(String s){
        byte[] b=new byte[s.length()*2];
        ByteBuffer.wrap(b).asCharBuffer().put(s);
        return b;
    }

UTF-8, UTF-16, and UTF-32

  • UTF-8 is variable 1 to 4 bytes.

  • UTF-16 is variable 2 or 4 bytes.

  • UTF-32 is fixed 4 bytes.

Note: UTF-8 can take 1 to 6 bytes with latest convention: https://lists.gnu.org/archive/html/help-flex/2005-01/msg00030.html

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

The best workaround for reading CSV files with UTF-8 on Mac is to convert them into XLSX format. I have found a script made by Konrad Foerstner, which I have improved little bit by adding support for different delimiter characters.

Download the script from Github https://github.com/brablc/clit/blob/master/csv2xlsx.py. In order to run it you will need to install a python module openpyxl for Excel file manipulation: sudo easy_install openpyxl.

Eclipse memory settings when getting "Java Heap Space" and "Out of Memory"

If you see an out of memory, consider if that is plausible: Do you really need that much memory? If not (i.e. when you don't have huge objects and if you don't need to create millions of objects for some reason), chances are that you have a memory leak.

In Java, this means that you're keeping a reference to an object somewhere even though you don't need it anymore. Common causes for this is forgetting to call close() on resources (files, DB connections, statements and result sets, etc.).

If you suspect a memory leak, use a profiler to find which object occupies all the available memory.

String to HashMap JAVA

Assuming no key contains either ',' or ':':

Map<String, Integer> map = new HashMap<String, Integer>();
for(final String entry : s.split(",")) {
    final String[] parts = entry.split(":");
    assert(parts.length == 2) : "Invalid entry: " + entry;
    map.put(parts[0], new Integer(parts[1]));
}

Object of class mysqli_result could not be converted to string in

mysqli:query() returns a mysqli_result object, which cannot be serialized into a string.

You need to fetch the results from the object. Here's how to do it.

If you need a single value.

Fetch a single row from the result and then access column index 0 or using an associative key. Use the null-coalescing operator in case no rows are present in the result.

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

$tourresult = $result->fetch_array()[0] ?? '';
// OR
$tourresult = $result->fetch_array()['roomprice'] ?? '';

echo '<strong>Per room amount:  </strong>'.$tourresult;

If you need multiple values.

Use foreach loop to iterate over the result and fetch each row one by one. You can access each column using the column name as an array index.

$result = $con->query($tourquery);  // or mysqli_query($con, $tourquery);

foreach($result as $row) {
    echo '<strong>Per room amount:  </strong>'.$row['roomprice'];
}

How to get a Static property with Reflection

Ok so the key for me was to use the .FlattenHierarchy BindingFlag. I don't really know why I just added it on a hunch and it started working. So the final solution that allows me to get Public Instance or Static Properties is:

obj.GetType.GetProperty(propName, Reflection.BindingFlags.Public _
  Or Reflection.BindingFlags.Static Or Reflection.BindingFlags.Instance Or _
  Reflection.BindingFlags.FlattenHierarchy)

how to convert numeric to nvarchar in sql command

declare @MyNumber int
set @MyNumber = 123
select 'My number is ' + CAST(@MyNumber as nvarchar(20))

select and echo a single field from mysql db using PHP

And escape your values with mysql_real_escape_string since PHP6 won't do that for you anymore! :)

How can I split a JavaScript string by white space or comma?

String.split() can also accept a regular expression:

input.split(/[ ,]+/);

This particular regex splits on a sequence of one or more commas or spaces, so that e.g. multiple consecutive spaces or a comma+space sequence do not produce empty elements in the results.

In Android EditText, how to force writing uppercase?

You can used two way.

First Way:

Set android:inputType="textCapSentences" on your EditText.

Second Way:

When user enter the number you have to used text watcher and change small to capital letter.

edittext.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {            

    }
        @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {             
    }
    @Override
    public void afterTextChanged(Editable et) {
          String s=et.toString();
      if(!s.equals(s.toUpperCase()))
      {
         s=s.toUpperCase();
         edittext.setText(s);
         edittext.setSelection(edittext.length()); //fix reverse texting
      }
    }
});  

angular.service vs angular.factory

The factory pattern is more flexible as it can return functions and values as well as objects.

There isn't a lot of point in the service pattern IMHO, as everything it does you can just as easily do with a factory. The exceptions might be:

  • If you care about the declared type of your instantiated service for some reason - if you use the service pattern, your constructor will be the type of the new service.
  • If you already have a constructor function that you're using elsewhere that you also want to use as a service (although probably not much use if you want to inject anything into it!).

Arguably, the service pattern is a slightly nicer way to create a new object from a syntax point of view, but it's also more costly to instantiate. Others have indicated that angular uses "new" to create the service, but this isn't quite true - it isn't able to do that because every service constructor has a different number of parameters. What angular actually does is use the factory pattern internally to wrap your constructor function. Then it does some clever jiggery pokery to simulate javascript's "new" operator, invoking your constructor with a variable number of injectable arguments - but you can leave out this step if you just use the factory pattern directly, thus very slightly increasing the efficiency of your code.

Stretch horizontal ul to fit width of div

This is the easiest way to do it: http://jsfiddle.net/thirtydot/jwJBd/

(or with table-layout: fixed for even width distribution: http://jsfiddle.net/thirtydot/jwJBd/59/)

This won't work in IE7.

#horizontal-style {
    display: table;
    width: 100%;
    /*table-layout: fixed;*/
}
#horizontal-style li {
    display: table-cell;
}
#horizontal-style a {
    display: block;
    border: 1px solid red;
    text-align: center;
    margin: 0 5px;
    background: #999;
}

Old answer before your edit: http://jsfiddle.net/thirtydot/DsqWr/

Reverse a string in Python

This is simple and meaningful reverse function, easy to understand and code

def reverse_sentence(text):
    words = text.split(" ")
    reverse =""
    for word in reversed(words):
        reverse += word+ " "
    return reverse

Does 'position: absolute' conflict with Flexbox?

No, absolutely positioning does not conflict with flex containers. Making an element be a flex container only affects its inner layout model, that is, the way in which its contents are laid out. Positioning affects the element itself, and can alter its outer role for flow layout.

That means that

  • If you add absolute positioning to an element with display: inline-flex, it will become block-level (like display: flex), but will still generate a flex formatting context.

  • If you add absolute positioning to an element with display: flex, it will be sized using the shrink-to-fit algorithm (typical of inline-level containers) instead of the fill-available one.

That said, absolutely positioning conflicts with flex children.

As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.

Why does Firebug say toFixed() is not a function?

You need convert to number type:

(+Low).toFixed(2)

unique combinations of values in selected columns in pandas data frame and count

You can groupby on cols 'A' and 'B' and call size and then reset_index and rename the generated column:

In [26]:

df1.groupby(['A','B']).size().reset_index().rename(columns={0:'count'})
Out[26]:
     A    B  count
0   no   no      1
1   no  yes      2
2  yes   no      4
3  yes  yes      3

update

A little explanation, by grouping on the 2 columns, this groups rows where A and B values are the same, we call size which returns the number of unique groups:

In[202]:
df1.groupby(['A','B']).size()

Out[202]: 
A    B  
no   no     1
     yes    2
yes  no     4
     yes    3
dtype: int64

So now to restore the grouped columns, we call reset_index:

In[203]:
df1.groupby(['A','B']).size().reset_index()

Out[203]: 
     A    B  0
0   no   no  1
1   no  yes  2
2  yes   no  4
3  yes  yes  3

This restores the indices but the size aggregation is turned into a generated column 0, so we have to rename this:

In[204]:
df1.groupby(['A','B']).size().reset_index().rename(columns={0:'count'})

Out[204]: 
     A    B  count
0   no   no      1
1   no  yes      2
2  yes   no      4
3  yes  yes      3

groupby does accept the arg as_index which we could have set to False so it doesn't make the grouped columns the index, but this generates a series and you'd still have to restore the indices and so on....:

In[205]:
df1.groupby(['A','B'], as_index=False).size()

Out[205]: 
A    B  
no   no     1
     yes    2
yes  no     4
     yes    3
dtype: int64

How to change the current URL in javascript?

What you're doing is appending a "1" (the string) to your URL. If you want page 1.html link to page 2.html you need to take the 1 out of the string, add one to it, then reassemble the string.

Why not do something like this:

var url = 'http://mywebsite.com/1.html';
var pageNum = parseInt( url.split("/").pop(),10 );
var nextPage = 'http://mywebsite.com/'+(pageNum+1)+'.html';

nextPage will contain the url http://mywebsite.com/2.html in this case. Should be easy to put in a function if needed.

Can't install Scipy through pip

The easy way to install scipy on Windows 10 100% is this: Just pip this ====> pip install scipy==1.0.0rc2

Thank me later :)

How to check if a std::thread is still running?

Create a mutex that the running thread and the calling thread both have access to. When the running thread starts it locks the mutex, and when it ends it unlocks the mutex. To check if the thread is still running, the calling thread calls mutex.try_lock(). The return value of that is the status of the thread. (Just make sure to unlock the mutex if the try_lock worked)

One small problem with this, mutex.try_lock() will return false between the time the thread is created, and when it locks the mutex, but this can be avoided using a slightly more complex method.

How to update Android Studio automatically?

Through Android Studio:

  1. Help
  2. Check for latest update
  3. Update

Meaning of Open hashing and Closed hashing

The name open addressing refers to the fact that the location ("address") of the element is not determined by its hash value. (This method is also called closed hashing).

In separate chaining, each bucket is independent, and has some sort of ADT (list, binary search trees, etc) of entries with the same index. In a good hash table, each bucket has zero or one entries, because we need operations of order O(1) for insert, search, etc.

This is a example of separate chaining using C++ with a simple hash function using mod operator (clearly, a bad hash function)

How to find difference between two Joda-Time DateTimes in minutes

Something like...

DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);

Duration duration = new Duration(yesterday, today);
System.out.println(duration.getStandardDays());
System.out.println(duration.getStandardHours());
System.out.println(duration.getStandardMinutes());

Which outputs

1
24
1440

or

System.out.println(Minutes.minutesBetween(yesterday, today).getMinutes());

Which is probably more what you're after

php pdo: get the columns name of a table

$sql = "select column_name from information_schema.columns where table_name = 'myTable'";

PHP function credits : http://www.sitepoint.com/forums/php-application-design-147/get-pdo-column-name-easy-way-559336.html

    function getColumnNames(){ 

    $sql = "select column_name from information_schema.columns where table_name = 'myTable'";
    #$sql = 'SHOW COLUMNS FROM ' . $this->table; 

    $stmt = $this->connection->prepare($sql); 

    try {     
        if($stmt->execute()){ 
            $raw_column_data = $stmt->fetchAll(PDO::FETCH_ASSOC); 

            foreach($raw_column_data as $outer_key => $array){ 
                foreach($array as $inner_key => $value){ 
                            if (!(int)$inner_key){ 
                                $this->column_names[] = $value; 
                            } 
                } 
            } 
            } 
            return $this->column_names; 
        } catch (Exception $e){ 
                return $e->getMessage(); //return exception 
        }         
    }  

How to get a value of an element by name instead of ID

Use the name attribute selector:

$("input[name='nameGoesHere']").val();

It is a mandatory requirement to include quotes around the value, see: http://api.jquery.com/attribute-equals-selector/

How to send HTTP request in java?

Apache HttpComponents. The examples for the two modules - HttpCore and HttpClient will get you started right away.

Not that HttpUrlConnection is a bad choice, HttpComponents will abstract a lot of the tedious coding away. I would recommend this, if you really want to support a lot of HTTP servers/clients with minimum code. By the way, HttpCore could be used for applications (clients or servers) with minimum functionality, whereas HttpClient is to be used for clients that require support for multiple authentication schemes, cookie support etc.

Pyspark: Filter dataframe based on multiple conditions

Your logic condition is wrong. IIUC, what you want is:

import pyspark.sql.functions as f

df.filter((f.col('d')<5))\
    .filter(
        ((f.col('col1') != f.col('col3')) | 
         (f.col('col2') != f.col('col4')) & (f.col('col1') == f.col('col3')))
    )\
    .show()

I broke the filter() step into 2 calls for readability, but you could equivalently do it in one line.

Output:

+----+----+----+----+---+
|col1|col2|col3|col4|  d|
+----+----+----+----+---+
|   A|  xx|   D|  vv|  4|
|   A|   x|   A|  xx|  3|
|   E| xxx|   B|  vv|  3|
|   F|xxxx|   F| vvv|  4|
|   G| xxx|   G|  xx|  4|
+----+----+----+----+---+

php codeigniter count rows

replace the query inside your model function with this

$query = $this->db->query("SELECT id FROM home");

in view:

echo $query->num_rows();

How do I print the type or class of a variable in Swift?

There appears to be no generic way to print the type name of an arbitrary value's type. As others have noted, for class instances you can print value.className but for primitive values it appears that at runtime, the type information is gone.

For instance, it looks as if there's not a way to type: 1.something() and get out Int for any value of something. (You can, as another answer suggested, use i.bridgeToObjectiveC().className to give you a hint, but __NSCFNumber is not actually the type of i -- just what it will be converted to when it crosses the boundary of an Objective-C function call.)

I would be happy to be proven wrong, but it looks like the type checking is all done at compile time, and like C++ (with RTTI disabled) much of the type information is gone at runtime.

How can I login to a website with Python?

Web page automation ? Definitely "webbot"

webbot even works web pages which have dynamically changing id and classnames and has more methods and features than selenium or mechanize.

Here's a snippet :)

from webbot import Browser 
web = Browser()
web.go_to('google.com') 
web.click('Sign in')
web.type('[email protected]' , into='Email')
web.click('NEXT' , tag='span')
web.type('mypassword' , into='Password' , id='passwordFieldId') # specific selection
web.click('NEXT' , tag='span') # you are logged in ^_^

The docs are also pretty straight forward and simple to use : https://webbot.readthedocs.io

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

With the addition of androidx in Studio 3.0+ the Toolbar compatibility is now in a new library, accessible like this

import androidx.appcompat.widget.Toolbar

How can I align button in Center or right using IONIC framework?

Another Ionic way. Using this ion-buttons tag, and the right keyword puts all the buttons in this group to the right. I made some custom toggle buttons that i wanted on one line, but the group to be right justified.

_x000D_
_x000D_
<ion-buttons right>_x000D_
<button ....>1</button>_x000D_
<button ....>2</button>_x000D_
<button ....>3</button>_x000D_
</ion-buttons>
_x000D_
_x000D_
_x000D_

Styling the arrow on bootstrap tooltips

In case you are going around and around to figure this out and none of the options above are working, it is possible you are experiencing a name space conflict of .tooltip with bootstrap and jquery.

See this answer on how to fix: jQueryUI Tooltips are competing with Twitter Bootstrap

What's the easiest way to escape HTML in Python?

If you wish to escape HTML in a URL:

This is probably NOT what the OP wanted (the question doesn't clearly indicate in which context the escaping is meant to be used), but Python's native library urllib has a method to escape HTML entities that need to be included in a URL safely.

The following is an example:

#!/usr/bin/python
from urllib import quote

x = '+<>^&'
print quote(x) # prints '%2B%3C%3E%5E%26'

Find docs here

How do I perform query filtering in django templates

You can't do this, which is by design. The Django framework authors intended a strict separation of presentation code from data logic. Filtering models is data logic, and outputting HTML is presentation logic.

So you have several options. The easiest is to do the filtering, then pass the result to render_to_response. Or you could write a method in your model so that you can say {% for object in data.filtered_set %}. Finally, you could write your own template tag, although in this specific case I would advise against that.

How to debug Javascript with IE 8

I was hoping to add this as a comment to Marcus Westin's reply, but I can't find a link - maybe I need more reputation?


Anyway, thanks, I found this code snippet useful for quick debugging in IE. I have made some quick tweaks to fix a problem that stopped it working for me, also to scroll down automatically and use fixed positioning so it will appear in the viewport. Here's my version in case anyone finds it useful:

myLog = function() {

    var _div = null;

    this.toJson = function(obj) {

        if (typeof window.uneval == 'function') { return uneval(obj); }
        if (typeof obj == 'object') {
            if (!obj) { return 'null'; }
            var list = [];
            if (obj instanceof Array) {
                    for (var i=0;i < obj.length;i++) { list.push(this.toJson(obj[i])); }
                    return '[' + list.join(',') + ']';
            } else {
                    for (var prop in obj) { list.push('"' + prop + '":' + this.toJson(obj[prop])); }
                    return '{' + list.join(',') + '}';
            }
        } else if (typeof obj == 'string') {
            return '"' + obj.replace(/(["'])/g, '\\$1') + '"';
        } else {
            return new String(obj);
        }

    };

    this.createDiv = function() {

        myLog._div = document.body.appendChild(document.createElement('div'));

        var props = {
            position:'fixed', top:'10px', right:'10px', background:'#333', border:'5px solid #333', 
            color: 'white', width: '400px', height: '300px', overflow: 'auto', fontFamily: 'courier new',
            fontSize: '11px', whiteSpace: 'nowrap'
        }

        for (var key in props) { myLog._div.style[key] = props[key]; }

    };


    if (!myLog._div) { this.createDiv(); }

    var logEntry = document.createElement('span');

    for (var i=0; i < arguments.length; i++) {
        logEntry.innerHTML += this.toJson(arguments[i]) + '<br />';
    }

    logEntry.innerHTML += '<br />';

    myLog._div.appendChild(logEntry);

    // Scroll automatically to the bottom
    myLog._div.scrollTop = myLog._div.scrollHeight;

}

How to use shared memory with Linux in C

Here is an example for shared memory :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 1024  /* make it a 1K shared memory segment */

int main(int argc, char *argv[])
{
    key_t key;
    int shmid;
    char *data;
    int mode;

    if (argc > 2) {
        fprintf(stderr, "usage: shmdemo [data_to_write]\n");
        exit(1);
    }

    /* make the key: */
    if ((key = ftok("hello.txt", 'R')) == -1) /*Here the file must exist */ 
{
        perror("ftok");
        exit(1);
    }

    /*  create the segment: */
    if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
        perror("shmget");
        exit(1);
    }

    /* attach to the segment to get a pointer to it: */
    data = shmat(shmid, NULL, 0);
    if (data == (char *)(-1)) {
        perror("shmat");
        exit(1);
    }

    /* read or modify the segment, based on the command line: */
    if (argc == 2) {
        printf("writing to segment: \"%s\"\n", argv[1]);
        strncpy(data, argv[1], SHM_SIZE);
    } else
        printf("segment contains: \"%s\"\n", data);

    /* detach from the segment: */
    if (shmdt(data) == -1) {
        perror("shmdt");
        exit(1);
    }

    return 0;
}

Steps :

  1. Use ftok to convert a pathname and a project identifier to a System V IPC key

  2. Use shmget which allocates a shared memory segment

  3. Use shmat to attache the shared memory segment identified by shmid to the address space of the calling process

  4. Do the operations on the memory area

  5. Detach using shmdt

clear table jquery

  $('#myTable > tr').remove();

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

If the charset of the tables is the same as it's content try to use mysql_set_charset('UTF8', $link_identifier). Note that MySQL uses UTF8 to specify the UTF-8 encoding instead of UTF-8 which is more common.

Check my other answer on a similar question too.

Read HttpContent in WebApi controller

By design the body content in ASP.NET Web API is treated as forward-only stream that can be read only once.

The first read in your case is being done when Web API is binding your model, after that the Request.Content will not return anything.

You can remove the contact from your action parameters, get the content and deserialize it manually into object (for example with Json.NET):

[HttpPut]
public HttpResponseMessage Put(int accountId)
{
    HttpContent requestContent = Request.Content;
    string jsonContent = requestContent.ReadAsStringAsync().Result;
    CONTACT contact = JsonConvert.DeserializeObject<CONTACT>(jsonContent);
    ...
}

That should do the trick (assuming that accountId is URL parameter so it will not be treated as content read).

Disable back button in android

Override the onBackPressed method and do nothing if you meant to handle the back button on the device.

@Override
public void onBackPressed() {
   if (shouldAllowBack()) {
       super.onBackPressed();
   } else {
       doSomething();
   }
}

Java Hashmap: How to get key from value?

I think keySet() may be well to find the keys mapping to the value, and have a better coding style than entrySet().

Ex:

Suppose you have a HashMap map, ArrayList res, a value you want to find all the key mapping to , then store keys to the res.

You can write code below:

    for (int key : map.keySet()) {
        if (map.get(key) == value) {
            res.add(key);
        }
    }

rather than use entrySet() below:

    for (Map.Entry s : map.entrySet()) {
        if ((int)s.getValue() == value) {
            res.add((int)s.getKey());
        }
    }

Hope it helps :)

Multiple selector chaining in jQuery?

I think you might see slightly better performance by doing it this way:

$("#Create, #Edit").find(".myClass").plugin(){
    // Options
});

Syntax for an If statement using a boolean

You can change the value of a bool all you want. As for an if:

if randombool == True:

works, but you can also use:

if randombool:

If you want to test whether something is false you can use:

if randombool == False

but you can also use:

if not randombool:

Use jQuery to scroll to the bottom of a div with lots of text

jQuery simple solution, one line, no external lib required :

$("#myDivID").animate({ scrollTop: $('#myDivID')[0].scrollHeight }, 1000);

Change 1000 to another value (this is the duration of the animation).

How do I center align horizontal <UL> menu?

ul{margin-left:33%}

Is a decent approximation on big screens. Its not good, but a good dirty fix.

How can I find the OWNER of an object in Oracle?

To find the name of the current user within an Oracle session, use the USER function.

Note that the owner of the constraint, the owner of the table containing the foreign key, and the owner of the referenced table may all be different. It sounds like it’s the table owner you’re interested in, in which case this should be close to what you want:

select Constraint_Name
from All_Constraints
where Table_Name = 'WHICHEVER_TABLE'
  and Constraint_Type = 'R' and Owner = User;

How to adjust text font size to fit textview

If a tranformation like allCaps is set, speedplane's approach is buggy. I fixed it, resulting in the following code (sorry, my reputation does not allow me to add this as a comment to speedplane's solution):

import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

public class FontFitTextView extends TextView {

    public FontFitTextView(Context context) {
        super(context);
        initialise();
    }

    public FontFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialise();
    }

    private void initialise() {
        mTestPaint = new Paint();
        mTestPaint.set(this.getPaint());
        //max size defaults to the initially specified text size unless it is too small
    }

    /* Re size the font so the specified text fits in the text box
     * assuming the text box is the specified width.
     */
    private void refitText(String text, int textWidth) 
    { 
        if (getTransformationMethod() != null) {
            text = getTransformationMethod().getTransformation(text, this).toString();
        }

        if (textWidth <= 0)
            return;
        int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
        float hi = 100;
        float lo = 2;
        final float threshold = 0.5f; // How close we have to be

        mTestPaint.set(this.getPaint());

        while((hi - lo) > threshold) {
            float size = (hi+lo)/2;
            if(mTestPaint.measureText(text) >= targetWidth) 
                hi = size; // too big
            else
                lo = size; // too small
        }
        // Use lo so that we undershoot rather than overshoot
        this.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int height = getMeasuredHeight();
        refitText(this.getText().toString(), parentWidth);
        this.setMeasuredDimension(parentWidth, height);
    }

    @Override
    protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
        refitText(text.toString(), this.getWidth());
    }

    @Override
    protected void onSizeChanged (int w, int h, int oldw, int oldh) {
        if (w != oldw) {
            refitText(this.getText().toString(), w);
      }
    }

    //Attributes
    private Paint mTestPaint;
}

Maximum number of rows in an MS Access database engine table?

Some comments:

  1. Jet/ACE files are organized in data pages, which means there is a certain amount of slack space when your record boundaries are not aligned with your data pages.

  2. Row-level locking will greatly reduce the number of possible records, since it forces one record per data page.

  3. In Jet 4, the data page size was increased to 4KBs (from 2KBs in Jet 3.x). As Jet 4 was the first Jet version to support Unicode, this meant that you could store 1GB of double-byte data (i.e., 1,000,000,000 double-byte characters), and with Unicode compression turned on, 2GBs of data. So, the number of records is going to be affected by whether or not you have Unicode compression on.

  4. Since we don't know how much room in a Jet/ACE file is taken up by headers and other metadata, nor precisely how much room index storage takes, the theoretical calculation is always going to be under what is practical.

  5. To get the most efficient possible storage, you'd want to use code to create your database rather than the Access UI, because Access creates certain properties that pure Jet does not need. This is not to say there are a lot of these, as properties set to the Access defaults are usually not set at all (the property is created only when you change it from the default value -- this can be seen by cycling through a field's properties collection, i.e., many of the properties listed for a field in the Access table designer are not there in the properties collection because they haven't been set), but you might want to limit yourself to Jet-specific data types (hyperlink fields are Access-only, for instance).

I just wasted an hour mucking around with this using Rnd() to populate 4 fields defined as type byte, with composite PK on the four fields, and it took forever to append enough records to get up to any significant portion of 2GBs. At over 2 million records, the file was under 80MBs. I finally quit after reaching just 700K 7 MILLION records and the file compacted to 184MBs. The amount of time it would take to get up near 2GBs is just more than I'm willing to invest!

Error: EPERM: operation not permitted, unlink 'D:\Sources\**\node_modules\fsevents\node_modules\abbrev\package.json'

For me it was Docker...

The moment that I closed the app container, I could do an npm install without any proble

P.S My node version is 14.15.5

Sharing link on WhatsApp from mobile website (not application) for Android

In general it makes sense only to display the Whatsapp Link on iOS or Android Devices only, using java script:

   if (navigator.userAgent.match(/iPhone|Android/i)) {
      document.write('<a href="whatsapp://send?text=See..">Share on WhatApp</a>');
   }

How to properly use the "choices" field option in Django

$ pip install django-better-choices

For those who are interested, I have created django-better-choices library, that provides a nice interface to work with Django choices for Python 3.7+. It supports custom parameters, lots of useful features and is very IDE friendly.

You can define your choices as a class:

from django_better_choices import Choices


class PAGE_STATUS(Choices):
    CREATED = 'Created'
    PENDING = Choices.Value('Pending', help_text='This set status to pending')
    ON_HOLD = Choices.Value('On Hold', value='custom_on_hold')

    VALID = Choices.Subset('CREATED', 'ON_HOLD')

    class INTERNAL_STATUS(Choices):
        REVIEW = 'On Review'

    @classmethod
    def get_help_text(cls):
        return tuple(
            value.help_text
            for value in cls.values()
            if hasattr(value, 'help_text')
        )

Then do the following operations and much much more:

print( PAGE_STATUS.CREATED )                # 'created'
print( PAGE_STATUS.ON_HOLD )                # 'custom_on_hold'
print( PAGE_STATUS.PENDING.display )        # 'Pending'
print( PAGE_STATUS.PENDING.help_text )      # 'This set status to pending'

'custom_on_hold' in PAGE_STATUS.VALID       # True
PAGE_STATUS.CREATED in PAGE_STATUS.VALID    # True

PAGE_STATUS.extract('CREATED', 'ON_HOLD')   # ~= PAGE_STATUS.VALID

for value, display in PAGE_STATUS:
    print( value, display )

PAGE_STATUS.get_help_text()
PAGE_STATUS.VALID.get_help_text()

And of course, it is fully supported by Django and Django Migrations:

class Page(models.Model):
    status = models.CharField(choices=PAGE_STATUS, default=PAGE_STATUS.CREATED)

Full documentation here: https://pypi.org/project/django-better-choices/

"Port 4200 is already in use" when running the ng serve command

I also faced the same error msg, so i tried ng serve --port 12012 and it worked fine.

How do I skip a header from CSV files in Spark?

For python developers. I have tested with spark2.0. Let's say you want to remove first 14 rows.

sc = spark.sparkContext
lines = sc.textFile("s3://folder_location_of_csv/")
parts = lines.map(lambda l: l.split(","))
parts.zipWithIndex().filter(lambda tup: tup[1] > 14).map(lambda x:x[0])

withColumn is df function. So below will not work in RDD style as used above.

parts.withColumn("index",monotonically_increasing_id()).filter(index > 14)

Java recursive Fibonacci sequence

It is a basic sequence that display or get a output of 1 1 2 3 5 8 it is a sequence that the sum of previous number the current number will be display next.

Try to watch link below Java Recursive Fibonacci sequence Tutorial

public static long getFibonacci(int number){
if(number<=1) return number;
else return getFibonacci(number-1) + getFibonacci(number-2);
}

Click Here Watch Java Recursive Fibonacci sequence Tutorial for spoon feeding

Cannot import XSSF in Apache POI

For OOXML to work you need the POI-OOXML jar which is separately packaged from the POI jar.

Download the POI-OOXML jar from the following location -

http://repo1.maven.org/maven2/org/apache/poi/poi-ooxml/3.11/poi-ooxml-3.11.jar

For Maven2 add the below dependency -

<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.11</version>
</dependency>

How to remove unwanted space between rows and columns in table?

This worked for me:

#table {
  border-collapse: collapse;
  border-spacing: 0;
}

Unpacking a list / tuple of pairs into two lists / tuples

>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')

Edit: Note that zip(*iterable) is its own inverse:

>>> list(source_list) == zip(*zip(*source_list))
True

When unpacking into two lists, this becomes:

>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True

Addition suggested by rocksportrocker.

How to get a list of user accounts using the command line in MySQL?

This displays list of unique users:

SELECT DISTINCT User FROM mysql.user;

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

java.time

We have new technology for this problem: the java.time framework built into Java 8 and later.

Your input string is in standard ISO 8601 format. That standard is used by default in the java.time classes for parsing/generating textual representations of date-time values.

OffsetDateTime odt = OffsetDateTime.parse( "2012-10-01T09:45:00.000+02:00" );

Your Question suggests you want to truncate to a whole second.

OffsetDateTime odtTruncatedToWholeSecond = odt.truncatedTo( ChronoUnit.SECONDS );

It seems you want to omit the offset and time zone info. The pre-defined formatter DateTimeFormatter.ISO_LOCAL_DATE_TIME does that.

And apparently you want to use a space in the middle rather than the standard T. You could define your own formatter for this, but I would just do a string manipulation to replace the T with a SPACE.

String output = odtTruncatedToWholeSecond.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ).replace( "T" , " " );

Simply String Manipulations

As the comments on the Question suggest, strictly speaking you can accomplish your goal by working only with strings and not converting to any date-time objects. But I provide this Answer here assuming you may have other business logic to work with these date-time values.


Table of date-time types in Java, both modern and legacy


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

Table of which java.time library to use with which version of Java or Android

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

After a recent update on my Ubuntu 16.04 system I have also started getting this error when trying to run convert on .ps files to convert them into pdfs.

This fix worked for me:

In a terminal run:

sudo gedit /etc/ImageMagick-6/policy.xml

This should open the policy.xml file in the gedit text editor. If it doesn't, your image magick might be installed in a different place. Then change

rights="none" 

to

rights="read | write" 

for PDF, EPS and PS lines near the bottom of the file. Save and exit, and image magick should then work again.

Error in contrasts when defining a linear model in R

From my experience ten minutes ago this situation can happen where there are more than one category but with a lot of NAs. Taking the Kaggle Houseprice Dataset as example, if you loaded data and run a simple regression,

train.df = read.csv('train.csv')
lm1 = lm(SalePrice ~ ., data = train.df)

you will get same error. I also tried testing the number of levels of each factor, but none of them says it has less than 2 levels.

cols = colnames(train.df)
for (col in cols){
  if(is.factor(train.df[[col]])){
    cat(col, ' has ', length(levels(train.df[[col]])), '\n')
  }
}

So after a long time I used summary(train.df) to see details of each col, and removed some, and it finally worked:

train.df = subset(train.df, select=-c(Id, PoolQC,Fence, MiscFeature, Alley, Utilities))
lm1 = lm(SalePrice ~ ., data = train.df)

and removing any one of them the regression fails to run again with same error (which I have tested myself).

And above attributes generally have 1400+ NAs and 10 useful values, so you might want to remove these garbage attributes, even they have 3 or 4 levels. I guess a function counting how many NAs in each column will help.

Query to list all stored procedures

As Mike stated, the best way is to use information_schema. As long as you're not in the master database, system stored procedures won't be returned.

SELECT * 
  FROM DatabaseName.INFORMATION_SCHEMA.ROUTINES
 WHERE ROUTINE_TYPE = 'PROCEDURE'

If for some reason you had non-system stored procedures in the master database, you could use the query (this will filter out MOST system stored procedures):

SELECT * 
  FROM [master].INFORMATION_SCHEMA.ROUTINES
 WHERE ROUTINE_TYPE = 'PROCEDURE' 
   AND LEFT(ROUTINE_NAME, 3) NOT IN ('sp_', 'xp_', 'ms_')

How to add an extra language input to Android?

I don't know about sliding the space bar. I have a small box on the left of my keyboard that indicates which language is selected ( when english is selected it shows the words EN with a small microphone on top. Being that I also have spanish as one of my languages, I just tap that button and it swithces back and forth from spanish to english.

Load image from resources

    this.toolStrip1 = new System.Windows.Forms.ToolStrip();
    this.toolStrip1.Location = new System.Drawing.Point(0, 0);
    this.toolStrip1.Name = "toolStrip1";
    this.toolStrip1.Size = new System.Drawing.Size(444, 25);
    this.toolStrip1.TabIndex = 0;
    this.toolStrip1.Text = "toolStrip1";
    object O = global::WindowsFormsApplication1.Properties.Resources.ResourceManager.GetObject("best_robust_ghost");

    ToolStripButton btn = new ToolStripButton("m1");
    btn.DisplayStyle = ToolStripItemDisplayStyle.Image;
    btn.Image = (Image)O;
    this.toolStrip1.Items.Add(btn);

    this.Controls.Add(this.toolStrip1);

Forward declaring an enum in C++

There's some dissent since this got bumped (sort of), so here's some relevant bits from the standard. Research shows that the standard doesn't really define forward declaration, nor does it explicitly state that enums can or can't be forward declared.

First, from dcl.enum, section 7.2:

The underlying type of an enumeration is an integral type that can represent all the enumerator values defined in the enumeration. It is implementation-defined which integral type is used as the underlying type for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is as if the enumeration had a single enumerator with value 0. The value of sizeof() applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of sizeof() applied to the underlying type.

So the underlying type of an enum is implementation-defined, with one minor restriction.

Next we flip to the section on "incomplete types" (3.9), which is about as close as we come to any standard on forward declarations:

A class that has been declared but not defined, or an array of unknown size or of incomplete element type, is an incompletely-defined object type.

A class type (such as "class X") might be incomplete at one point in a translation unit and complete later on; the type "class X" is the same type at both points. The declared type of an array object might be an array of incomplete class type and therefore incomplete; if the class type is completed later on in the translation unit, the array type becomes complete; the array type at those two points is the same type. The declared type of an array object might be an array of unknown size and therefore be incomplete at one point in a translation unit and complete later on; the array types at those two points ("array of unknown bound of T" and "array of N T") are different types. The type of a pointer to array of unknown size, or of a type defined by a typedef declaration to be an array of unknown size, cannot be completed.

So there, the standard pretty much laid out the types that can be forward declared. Enum wasn't there, so compiler authors generally regard forward declaring as disallowed by the standard due to the variable size of its underlying type.

It makes sense, too. Enums are usually referenced in by-value situations, and the compiler would indeed need to know the storage size in those situations. Since the storage size is implementation defined, many compilers may just choose to use 32 bit values for the underlying type of every enum, at which point it becomes possible to forward declare them. An interesting experiment might be to try forward declaring an enum in visual studio, then forcing it to use an underlying type greater than sizeof(int) as explained above to see what happens.

Single selection in RecyclerView

The following might be helpful for RecyclerView with Single Choice.

Three steps to do that, 1) Declare a global integer variable,

private int mSelectedItem = -1;

2) in onBindViewHolder

 mRadio.setChecked(position == mSelectedItem);

3) in onClickListener

mSelectedItem = getAdapterPosition();
notifyItemRangeChanged(0, mSingleCheckList.size());
mAdapter.onItemHolderClick(SingleCheckViewHolder.this);

ORA-28000: the account is locked error getting frequently

Way to unlock the user :

$ sqlplus  /nolog
SQL > conn sys as sysdba
SQL > ALTER USER USER_NAME ACCOUNT UNLOCK;

and open new terminal

SQL > sqlplus / as sysdba
connected
SQL > conn username/password  //which username u gave before unlock
  • it will ask new password:password
  • it will ask re-type password:password
  • press enter u will get loggedin

How to include JavaScript file or library in Chrome console?

If anyone, fails to load because hes script violates the script-src "Content Security Policy" or "because unsafe-eval' is not an allowed", I will advice using my pretty-small module-injector as a dev-tools snippet, then you'll be able to load like this:

_x000D_
_x000D_
imports('https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js')_x000D_
  .then(()=>alert(`today is ${moment().format('dddd')}`));
_x000D_
<script src="https://raw.githack.com/shmuelf/PowerJS/master/src/power-moduleInjector.js"></script>
_x000D_
_x000D_
_x000D_

this solution works because:

  1. It loades the library in xhr - which allows CORS from console, and avoids the script-src policy.
  2. It uses the synchronous option of xhr which allows you to stay at the console/snippet's context, so you'll have the permission to eval the script, and not to get-treated as an unsafe-eval.

jQuery Event : Detect changes to the html/text of a div

If you don't want use timer and check innerHTML you can try this event

$('mydiv').bind('DOMSubtreeModified', function(){
  console.log('changed');
});

More details and browser support datas are Here.

Attention: in newer jQuery versions bind() is deprecated, so you should use on() instead:

$('body').on('DOMSubtreeModified', 'mydiv', function(){
  console.log('changed');
});

How to get the next auto-increment id in mysql

You can't use the ID while inserting, neither do you need it. MySQL does not even know the ID when you are inserting that record. You could just save "sahf4d2fdd45" in the payment_code table and use id and payment_code later on.

If you really need your payment_code to have the ID in it then UPDATE the row after the insert to add the ID.

How to implement endless list with RecyclerView?

This is how I do it, simple and short:

    recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
    {
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy)
        {
            if(!recyclerView.canScrollVertically(1) && dy != 0)
            {
                // Load more results here

            }
        }
    });

Sorting a List<int>

double jhon = 3;
double[] numbers = new double[3];
for (int i = 0; i < 3; i++)

{
    numbers[i] = double.Parse(Console.ReadLine());

}
Console.WriteLine("\n");

Array.Sort(numbers);

for (int i = 0; i < 3; i++)
{
    Console.WriteLine(numbers[i]);

}

Console.ReadLine();

Val and Var in Kotlin

Val is immutable and its properties are set at run time, but you can use a const modifier to make it as a compile time constant. Val in kotlin is same as final in java.

Var is mutable and its type is identified at compile time.

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

Your proposed doCalculationsAndUpdateUIs does data processing and dispatches UI updates to the main queue. I presume that you have dispatched doCalculationsAndUpdateUIs to a background queue when you first called it.

While technically fine, that's a little fragile, contingent upon your remembering to dispatch it to the background every time you call it: I would, instead, suggest that you do your dispatch to the background and dispatch back to the main queue from within the same method, as it makes the logic unambiguous and more robust, etc.

Thus it might look like:

- (void)doCalculationsAndUpdateUIs {

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL), ^{

        // DATA PROCESSING 1 

        dispatch_async(dispatch_get_main_queue(), ^{
            // UI UPDATION 1
        });

        /* I expect the control to come here after UI UPDATION 1 */

        // DATA PROCESSING 2

        dispatch_async(dispatch_get_main_queue(), ^{
            // UI UPDATION 2
        });

        /* I expect the control to come here after UI UPDATION 2 */

        // DATA PROCESSING 3

        dispatch_async(dispatch_get_main_queue(), ^{
            // UI UPDATION 3
        });
    });
}

In terms of whether you dispatch your UI updates asynchronously with dispatch_async (where the background process will not wait for the UI update) or synchronously with dispatch_sync (where it will wait for the UI update), the question is why would you want to do it synchronously: Do you really want to slow down the background process as it waits for the UI update, or would you like the background process to carry on while the UI update takes place.

Generally you would dispatch the UI update asynchronously with dispatch_async as you've used in your original question. Yes, there certainly are special circumstances where you need to dispatch code synchronously (e.g. you're synchronizing the updates to some class property by performing all updates to it on the main queue), but more often than not, you just dispatch the UI update asynchronously and carry on. Dispatching code synchronously can cause problems (e.g. deadlocks) if done sloppily, so my general counsel is that you should probably only dispatch UI updates synchronously if there is some compelling need to do so, otherwise you should design your solution so you can dispatch them asynchronously.


In answer to your question as to whether this is the "best way to achieve this", it's hard for us to say without knowing more about the business problem being solved. For example, if you might be calling this doCalculationsAndUpdateUIs multiple times, I might be inclined to use my own serial queue rather than a concurrent global queue, in order to ensure that these don't step over each other. Or if you might need the ability to cancel this doCalculationsAndUpdateUIs when the user dismisses the scene or calls the method again, then I might be inclined to use a operation queue which offers cancelation capabilities. It depends entirely upon what you're trying to achieve.

But, in general, the pattern of asynchronously dispatching a complicated task to a background queue and then asynchronously dispatching the UI update back to the main queue is very common.

codes for ADD,EDIT,DELETE,SEARCH in vb2010

A good resource start off point would be MSDN as your looking into a microsoft product

How to compile for Windows on Linux with gcc/g++?

mingw32 exists as a package for Linux. You can cross-compile and -link Windows applications with it. There's a tutorial here at the Code::Blocks forum. Mind that the command changes to x86_64-w64-mingw32-gcc-win32, for example.

Ubuntu, for example, has MinGW in its repositories:

$ apt-cache search mingw
[...]
g++-mingw-w64 - GNU C++ compiler for MinGW-w64
gcc-mingw-w64 - GNU C compiler for MinGW-w64
mingw-w64 - Development environment targeting 32- and 64-bit Windows
[...]

Changing cursor to waiting in javascript/jquery

The following is my preferred way, and will change the cursor everytime a page is about to change i.e. beforeunload

$(window).on('beforeunload', function(){
   $('*').css("cursor", "progress");
});

Inline list initialization in VB.NET

Collection initializers are only available in VB.NET 2010, released 2010-04-12:

Dim theVar = New List(Of String) From { "one", "two", "three" }

PHP namespaces and "use"

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use My\Full\Namespace;

is equivalent to:

use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.

Ng-model does not update controller value

For me the problem was solved by stocking my datas into an object (here "datas").

_x000D_
_x000D_
NgApp.controller('MyController', function($scope) {_x000D_
_x000D_
   $scope.my_title = ""; // This don't work in ng-click function called_x000D_
_x000D_
   $scope.datas = {_x000D_
      'my_title' : "",_x000D_
   };_x000D_
_x000D_
   $scope.doAction = function() {_x000D_
         console.log($scope.my_title); // bad value_x000D_
         console.log($scope.datas.my_title); // Good Value binded by'ng-model'_x000D_
   }_x000D_
   _x000D_
_x000D_
});
_x000D_
_x000D_
_x000D_

I Hop it will help

Function to convert column number to letter?

This formula will give the column based on a range (i.e., A1), where range is a single cell. If a multi-cell range is given it will return the top-left cell. Note, both cell references must be the same:

MID(CELL("address",A1),2,SEARCH("$",CELL("address",A1),2)-2)

How it works:

CELL("property","range") returns a specific value of the range depending on the property used. In this case the cell address. The address property returns a value $[col]$[row], i.e. A1 -> $A$1. The MID function parses out the column value between the $ symbols.

How can I use an array of function pointers?

You have a good example here (Array of Function pointers), with the syntax detailed.

int sum(int a, int b);
int subtract(int a, int b);
int mul(int a, int b);
int div(int a, int b);

int (*p[4]) (int x, int y);

int main(void)
{
  int result;
  int i, j, op;

  p[0] = sum; /* address of sum() */
  p[1] = subtract; /* address of subtract() */
  p[2] = mul; /* address of mul() */
  p[3] = div; /* address of div() */
[...]

To call one of those function pointers:

result = (*p[op]) (i, j); // op being the index of one of the four functions

How to output MySQL query results in CSV format?

If you are getting an error of secure-file-priv then, also after shifting your destination file location inside the C:\ProgramData\MySQL\MySQL Server 8.0\Uploads and also after then the query-

SELECT * FROM attendance INTO OUTFILE 'C:\ProgramData\MySQL\MySQL Server 8.0\Uploads\FileName.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

is not working, you have to just change \(backsplash) from the query to / (forwardsplash)

And that works !!

Example:

SELECT * FROM attendance INTO OUTFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/FileName.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n';

Each time when you run the successful query, it will generate the new csv file each time! Cool Right?

Get path from open file in Python

I had the exact same issue. If you are using a relative path os.path.dirname(path) will only return the relative path. os.path.realpath does the trick:

>>> import os
>>> f = open('file.txt')
>>> os.path.realpath(f.name)

Random integer in VB.NET

To get a random integer value between 1 and N (inclusive) you can use the following.

CInt(Math.Ceiling(Rnd() * n)) + 1

Spring Maven clean error - The requested profile "pom.xml" could not be activated because it does not exist

This link has solution of how to get it working. Removing "pom.xml" from the "Profiles:" line and then click "Run".

Convert HTML Character Back to Text Using Java Standard Library

The URL decoder should only be used for decoding strings from the urls generated by html forms which are in the "application/x-www-form-urlencoded" mime type. This does not support html characters.

After a search I found a Translate class within the HTML Parser library.

No String-argument constructor/factory method to deserialize from String value ('')

Use below code snippet This worked for me

ObjectMapper objectMapper = new ObjectMapper();
String jsonString = "{\"symbol\":\"ABCD\}";
objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
Trade trade = objectMapper.readValue(jsonString, new TypeReference<Symbol>() {});

Model Class

@JsonIgnoreProperties    public class Symbol {
    @JsonProperty("symbol")
    private String symbol;
}

Is there any way to wait for AJAX response and halt execution?

New, using jquery's promise implementation:

function functABC(){

  // returns a promise that can be used later. 

  return $.ajax({
    url: 'myPage.php',
    data: {id: id}
  });
}


functABC().then( response => 
  console.log(response);
);

Nice read e.g. here.

This is not "synchronous" really, but I think it achieves what the OP intends.

Old, (jquery's async option has since been deprecated):

All Ajax calls can be done either asynchronously (with a callback function, this would be the function specified after the 'success' key) or synchronously - effectively blocking and waiting for the servers answer. To get a synchronous execution you have to specify

async: false 

like described here

Note, however, that in most cases asynchronous execution (via callback on success) is just fine.

Turn on torch/flash on iPhone

This work's very well.. hope it help's someone !

-(IBAction)flashlight:(id)sender {

    AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];

    if ([device hasTorch] && [device hasFlash]){

        if (device.torchMode == AVCaptureTorchModeOff) {

            [sender setTitle:@"Torch Off" forState:UIControlStateNormal];

            AVCaptureDeviceInput *flashInput = [AVCaptureDeviceInput deviceInputWithDevice:device error: nil];
            AVCaptureVideoDataOutput *output = [[AVCaptureVideoDataOutput alloc] init];

            AVCaptureSession *cam = [[AVCaptureSession alloc] init];

            [cam beginConfiguration];
            [device lockForConfiguration:nil];

            [device setTorchMode:AVCaptureTorchModeOn];
            [device setFlashMode:AVCaptureFlashModeOn];

            [cam addInput:flashInput];
            [cam addOutput:output];

            [device unlockForConfiguration];

            [cam commitConfiguration];
            [cam startRunning];

            [self setTorchSession:cam];
        }
        else {
            [sender setTitle:@"Torch On" forState:UIControlStateNormal];
            [_torchSession stopRunning];
        }
    }
}

Is there any way to delete local commits in Mercurial?

hg strip is what you are looking for. It's analogous of git reset if you familiar with git.

Use console:

  1. You need to know the revision number. hg log -l 10. This command shows the last 10 commits. Find commit you are looking for. You need 4 digit number from changeset line changeset: 5888:ba6205914681

  2. Then hg strip -r 5888 --keep. This removes the record of the commit but keeps all files modified and then you could recommit them. (if you want to delete files to just remove --keep hg strip -r 5888

Jquery resizing image

You can resize image with this piece of code

    var maxWidth = 600;
    $("img").each(function () {
      var imageWidth = $(this).width();
      var imageHeight = $(this).height();
        if (imageWidth > maxWidth) {
          var percentdiff = (imageWidth - maxWidth) / imageWidth * 100;
          $(this).width(maxWidth);
          $(this).height(imageHeight - (imageHeight * percentdiff / 100));
        }
   });

Remove trailing comma from comma-separated string

(^(\s*?\,+)+\s?)|(^\s+)|(\s+$)|((\s*?\,+)+\s?$)

Regexr

ex:

a, b, c
, ,a, b, c, 
,a, b, c   ,
,,a, b, c, ,,,
, a, b, c,    ,
    a, b, c     
     a, b, c ,,
, a, b, c, 
, ,a, b, c, ,
 , a, b, c , 
,,, a, b, c,,, 
,,, ,,,a, b, c,,, ,,,
,,, ,,, a, b, c,,, ,,,
 ,,,a, b, c ,,,
 ,,,a, b, c,,, 
   a, b, c   

becomes:

a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c
a, b, c

Write objects into file with Node.js

Building on what deb2fast said I would also pass in a couple of extra parameters to JSON.stringify() to get it to pretty format:

fs.writeFileSync('./data.json', JSON.stringify(obj, null, 2) , 'utf-8');

The second param is an optional replacer function which you don't need in this case so null works.

The third param is the number of spaces to use for indentation. 2 and 4 seem to be popular choices.

What are database normal forms and can you give examples?

I've never had a good memory for exact wording, but in my database class I think the professor always said something like:

The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF].

Registry key Error: Java version has value '1.8', but '1.7' is required

I've had the same problem. Simple solution that worked for me is to rearrange the entries in the PATH for JRE/JDK. This problem started to appear after installing JRE 8 whose installation has put some executable files in System32 or SysWOW64 directories, these executable files are messing up. To resolve the problem:

  1. Create environment variable pointing to JDK home as JAVA_HOME.

    set JAVA_HOME=C:\Progra~1\Java\jdk1.8.0_45

  2. Put the entry %JAVA_HOME%\bin at start in your PATH environment variable. Appending existing value of PATH. For example:

    path=C:\Program Files\Java\jdk1.8.0_45\bin;%path%

What is tempuri.org?

Unfortunately the tempuri.org URL now just redirects to Bing.

You can see what it used to render via archive.org:

https://web.archive.org/web/20090304024056/http://tempuri.org/

To quote:

Each XML Web Service needs a unique namespace in order for client applications to distinguish it from other services on the Web. By default, ASP.Net Web Services use http://tempuri.org/ for this purpose. While this suitable for XML Web Services under development, published services should use a unique, permanent namespace.

Your XML Web Service should be identified by a namespace that you control. For example, you can use your company's Internet domain name as part of the namespace. Although many namespaces look like URLs, they need not point to actual resources on the Web.

For XML Web Services creating[sic] using ASP.NET, the default namespace can be changed using the WebService attribute's Namespace property. The WebService attribute is applied to the class that contains the XML Web Service methods. Below is a code example that sets the namespace to "http://microsoft.com/webservices/":

C#

[WebService(Namespace="http://microsoft.com/webservices/")]
public class MyWebService {
   // implementation
}

Visual Basic.NET

<WebService(Namespace:="http://microsoft.com/webservices/")> Public Class MyWebService
    ' implementation
End Class

Visual J#.NET

/**@attribute WebService(Namespace="http://microsoft.com/webservices/")*/
public class MyWebService {
    // implementation
}

It's also worth reading section 'A 1.3 Generating URIs' at:

http://www.w3.org/TR/wsdl#_Toc492291092

Convert Variable Name to String?

Totally possible with the python-varname package (python3):

from varname import nameof

s = 'Hey!'

print (nameof(s))

Output:

s

Get the package here:

https://github.com/pwwang/python-varname

Authentication plugin 'caching_sha2_password' is not supported

i try to resolve this error and finally install PyMySQL instead of mysql library and it's working properly.

thanks.

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
attr(,"levels")
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Amazon products API - Looking for basic overview and information

I wrote a blog post on this subject, after spending hours wading through Amazon's obscure documentation. Maybe useful as another view on the process.

d3 add text to circle

Here's a way that I consider easier: The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre.

const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ]

const nodeElems = svg.append('g')
.selectAll('circle')
.data(nodes)
.enter().append('circle')
.attr('r',radius)
.attr('fill', getNodeColor)

const textElems = svg.append('g')
.selectAll('text')
.data(nodes)
.enter().append('text')
.text(node => node.label)
.attr('font-size',8)//font size
.attr('dx', -10)//positions text towards the left of the center of the circle
.attr('dy',4)

Updating the list view when the adapter data changes

substitute:

mMyListView.invalidate();

for:

((BaseAdapter) mMyListView.getAdapter()).notifyDataSetChanged(); 

If that doesnt work, refer to this thread: Android List view refresh

Copying files using rsync from remote server to local machine

I think it is better to copy files from your local computer, because if files number or file size is very big, copying process could be interrupted if your current ssh session would be lost (broken pipe or whatever).

If you have configured ssh key to connect to your remote server, you could use the following command:

rsync -avP -e "ssh -i /home/local_user/ssh/key_to_access_remote_server.pem" remote_user@remote_host.ip:/home/remote_user/file.gz /home/local_user/Downloads/

Where v option is --verbose, a option is --archive - archive mode, P option same as --partial - keep partially transferred files, e option is --rsh=COMMAND - specifying the remote shell to use.

rsync man page

clk'event vs rising_edge()

Practical example:

Imagine that you are modelling something like an I2C bus (signals called SCL for clock and SDA for data), where the bus is tri-state and both nets have a weak pull-up. Your testbench should model the pull-up resistor on the PCB with a value of 'H'.

scl <= 'H'; -- Testbench resistor pullup

Your I2C master or slave devices can drive the bus to '1' or '0' or leave it alone by assigning a 'Z'

Assigning a '1' to the SCL net will cause an event to happen, because the value of SCL changed.

  • If you have a line of code that relies on (scl'event and scl = '1'), then you'll get a false trigger.

  • If you have a line of code that relies on rising_edge(scl), then you won't get a false trigger.

Continuing the example: you assign a '0' to SCL, then assign a 'Z'. The SCL net goes to '0', then back to 'H'.

Here, going from '1' to '0' isn't triggering either case, but going from '0' to 'H' will trigger a rising_edge(scl) condition (correct), but the (scl'event and scl = '1') case will miss it (incorrect).

General Recommenation:

Use rising_edge(clk) and falling_edge(clk) instead of clk'event for all code.

<xsl:variable> Print out value of XSL variable using <xsl:value-of>

Your main problem is thinking that the variable you declared outside of the template is the same variable being "set" inside the choose statement. This is not how XSLT works, the variable cannot be reassigned. This is something more like what you want:

<xsl:template match="class">
  <xsl:copy><xsl:apply-templates select="@*|node()"/></xsl:copy>
  <xsl:variable name="subexists">
    <xsl:choose>
      <xsl:when test="joined-subclass">true</xsl:when>
      <xsl:otherwise>false</xsl:otherwise>
    </xsl:choose>
  </xsl:variable>
  subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

And if you need the variable to have "global" scope then declare it outside of the template:

<xsl:variable name="subexists">
  <xsl:choose>
     <xsl:when test="/path/to/node/joined-subclass">true</xsl:when>
     <xsl:otherwise>false</xsl:otherwise>
  </xsl:choose>
</xsl:variable>

<xsl:template match="class">
   subexists:      <xsl:value-of select="$subexists" />
</xsl:template>

How to manually reload Google Map with JavaScript

Yes, you can 'refresh' a Google Map like this:

google.maps.event.trigger(map, 'resize');

This basically sends a signal to your map to redraw it.

Hope that helps!

@class vs. #import

The common practice is using @class in header files (but you still need to #import the superclass), and #import in implementation files. This will avoid any circular inclusions, and it just works.

What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?

To have a good follow-up about all this, Twitter - one of the pioneers of hashbang URL's and single-page-interface - admitted that the hashbang system was slow in the long run and that they have actually started reversing the decision and returning to old-school links.

Article about this is here.

Convert floating point number to a certain precision, and then copy to string

To set precision with 9 digits, get:

print "%.9f" % numvar

Return precision with 2 digits:

print "%.2f" % numvar 

Return precision with 2 digits and float converted value:

numvar = 4.2345
print float("%.2f" % numvar) 

Regular expression matching a multiline block of text

If each file only has one sequence of aminoacids, I wouldn't use regular expressions at all. Just something like this:

def read_amino_acid_sequence(path):
    with open(path) as sequence_file:
        title = sequence_file.readline() # read 1st line
        aminoacid_sequence = sequence_file.read() # read the rest

    # some cleanup, if necessary
    title = title.strip() # remove trailing white spaces and newline
    aminoacid_sequence = aminoacid_sequence.replace(" ","").replace("\n","")
    return title, aminoacid_sequence

process.env.NODE_ENV is undefined

It is due to OS

In your package.json, make sure to have your scripts(Where app.js is your main js file to be executed & NODE_ENV is declared in a .env file).Eg:

"scripts": {
    "start": "node app.js",
    "dev": "nodemon server.js",
    "prod": "NODE_ENV=production & nodemon app.js"
  }

For windows

Also set up your .env file variable having NODE_ENV=development

If your .env file is in a folder for eg.config folder make sure to specify in app.js(your main js file)

const dotenv = require('dotenv'); dotenv.config({ path: './config/config.env' });

How to replace a character with a newline in Emacs?

There are four ways I've found to put a newline into the minibuffer.

  1. C-o

  2. C-q C-j

  3. C-q 12 (12 is the octal value of newline)

  4. C-x o to the main window, kill a newline with C-k, then C-x o back to the minibuffer, yank it with C-y

Running a cron job at 2:30 AM everyday

crontab -e

add:

30 2 * * * /your/command

How do I turn off the mysql password validation?

On some installations, you cannot execute this command until you have reset the root password. You cannot reset the root password, until you execute this command. Classic Catch-22.

One solution not mention by other responders is to temporarily disable the plugin via mysql configuration. In any my.cnf, in the [mysqld] section, add:

skip-validate_password=1

and restart the server. Change the password, and set the value back to 0, and restart again.

How do I "decompile" Java class files?

There are a few programs you can use. You will get the actual Java code, but sometimes the code will have been obfuscated so methods are named by one letter or number or a random mix of letters and numbers.

DJ Decompiler Mocha

NULL vs nullptr (Why was it replaced?)

nullptr is always a pointer type. 0 (aka. C's NULL bridged over into C++) could cause ambiguity in overloaded function resolution, among other things:

f(int);
f(foo *);

How to run an android app in background?

You can probably start a Service here if you want your Application to run in Background. This is what Service in Android are used for - running in background and doing longtime operations.

UDPATE

You can use START_STICKY to make your Service running continuously.

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handleCommand(intent);
    // We want this service to continue running until it is explicitly
    // stopped, so return sticky.
    return START_STICKY;
}

Read/Parse text file line by line in VBA

For completeness; working with the data loaded into memory;

dim hf As integer: hf = freefile
dim lines() as string, i as long

open "c:\bla\bla.bla" for input as #hf
    lines = Split(input$(LOF(hf), #hf), vbnewline)
close #hf

for i = 0 to ubound(lines)
    debug.? "Line"; i; "="; lines(i)
next

phpmailer: Reply using only "Reply To" address

At least in the current versions of PHPMailers, there's a function clearReplyTos() to empty the reply-to array.

    $mail->ClearReplyTos();
    $mail->addReplyTo([email protected], 'EXAMPLE');

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I had this error. Nothing worked for me until I opened the SQLServer log file in the "MSSQL10_50" Log folder. That clearly stated which file could not be overwritten. It turned out that the .mdf file was being written into the "MSSQL10" data folder. I made sure that folder had the same SQLServer user permissions as the "MSSQL10_50" equivalent folder. Then it all worked.

The issue here is that the error detail is logged but not reported, so check the logs.

Finding out current index in EACH loop (Ruby)

X.each_with_index do |item, index|
  puts "current_index: #{index}"
end

How do I iterate over a range of numbers defined by variables in Bash?

The seq method is the simplest, but Bash has built-in arithmetic evaluation.

END=5
for ((i=1;i<=END;i++)); do
    echo $i
done
# ==> outputs 1 2 3 4 5 on separate lines

The for ((expr1;expr2;expr3)); construct works just like for (expr1;expr2;expr3) in C and similar languages, and like other ((expr)) cases, Bash treats them as arithmetic.

Pass entire form as data in jQuery Ajax function

There's a function that does exactly this:

http://api.jquery.com/serialize/

var data = $('form').serialize();
$.post('url', data);

How to read numbers separated by space using scanf

int main()
{
char string[200];
int g,a,i,G[20],A[20],met;

gets(string);
g=convert_input(G,string);

for(i=0;i<=g;i++)
    printf("\n%d>>%d",i,G[i]);
return 0;
}

int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
    temp=0;
    while(string[i]!=' ' && string[i]!='\0')
        temp=temp*10 + (string[i++]-'0') ;
    if(string[i]==' ')
        i++;
    K[j++]=temp;
}
return j-1;
}

How do I make the return type of a method generic?

You have to convert the type of your return value of the method to the Generic type which you pass to the method during calling.

    public static T values<T>()
    {
        Random random = new Random();
        int number = random.Next(1, 4);
        return (T)Convert.ChangeType(number, typeof(T));
    }

You need pass a type that is type casteable for the value you return through that method.

If you would want to return a value which is not type casteable to the generic type you pass, you might have to alter the code or make sure you pass a type that is casteable for the return value of method. So, this approach is not reccomended.

Flexbox not giving equal width to elements

To create elements with equal width using Flex, you should set to your's child (flex elements):

flex-basis: 25%;
flex-grow: 0;

It will give to all elements in row 25% width. They will not grow and go one by one.

How to use split?

If it is the basic JavaScript split function, look at documentation, JavaScript split() Method.

Basically, you just do this:

var array = myString.split(' -- ')

Then your two values are stored in the array - you can get the values like this:

var firstValue = array[0];
var secondValue = array[1];

PHP $_FILES['file']['tmp_name']: How to preserve filename and extension?

$_FILES["file"]["tmp_name"] contains the actual copy of your file content on the server while
$_FILES["file"]["name"] contains the name of the file which you have uploaded from the client computer.

Angular 4 setting selected option in Dropdown

Remove [selected] from option tag:

<option *ngFor="let opt of question.options" [value]="opt.key">
  {{opt.selected+opt.value}}
</option>

And in your form builder add:

key: this.question.options.filter(val => val.selected === true).map(data => data.key)

Java: unparseable date exception

I encountered this error working in Talend. I was able to store S3 CSV files created from Redshift without a problem. The error occurred when I was trying to load the same S3 CSV files into an Amazon RDS MySQL database. I tried the default timestamp Talend timestamp formats but they were throwing exception:unparseable date when loading into MySQL.

This from the accepted answer helped me solve this problem:

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern

The key to my solution was changing the Talend schema. Talend set the timestamp field to "date" so I changed it to "timestamp" then I inserted "yyyy-MM-dd HH:mm:ss z" into the format string column view a screenshot here talend schema

I had other issues with 12 hour and 24 hour timestamp translations until I added the "z" at the end of the timestamp string.

Permissions error when connecting to EC2 via SSH on Mac OSx

If you have a PPK file working on a PC, then export it as OpenSSH file using puttygen.exe for PC and use that on Mac (any Unix machine).

I was getting the same error --

debug1: Authentications that can continue: publickey,gssapi-with-mic
debug1: Next authentication method: publickey
debug1: Trying private key: ec2-keypair
debug1: read PEM private key done: type RSA
debug1: Authentications that can continue: publickey,gssapi-with-mic
debug1: No more authentication methods to try.
Permission denied (publickey,gssapi-with-mic)

As I was using a PPK file on Windows, I followed the steps as described above and Bingo!

$ ssh -i ec2-openssh-key root@ec2-instance-ip

Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

I had this problem and used this technique.

Its the best solution i found which is very flexible.

Also please vote here to add support for cumulative section declaration

log4j vs logback

Should you? Yes.

Why? Log4J has essentially been deprecated by Logback.

Is it urgent? Maybe not.

Is it painless? Probably, but it may depend on your logging statements.

Note that if you really want to take full advantage of LogBack (or SLF4J), then you really need to write proper logging statements. This will yield advantages like faster code because of the lazy evaluation, and less lines of code because you can avoid guards.

Finally, I highly recommend SLF4J. (Why recreate the wheel with your own facade?)

How can I add a vertical scrollbar to my div automatically?

Since OS X Lion, the scrollbar on websites are hidden by default and only visible once you start scrolling. Personally, I prefer the hidden scrollbar, but in case you really need it, you can overwrite the default and force the scrollbar in WebKit browsers back like this:

_x000D_
_x000D_
::-webkit-scrollbar {
    -webkit-appearance: none;
    width: 7px;
}
::-webkit-scrollbar-thumb {
    border-radius: 4px;
    background-color: rgba(0,0,0,.5);
    -webkit-box-shadow: 0 0 1px rgba(255,255,255,.5);
}
_x000D_
_x000D_
_x000D_

How to split a string with angularJS

You may want to wrap that functionality up into a filter, this way you don't have to put the mySplit function in all of your controllers. For example

angular.module('myModule', [])
    .filter('split', function() {
        return function(input, splitChar, splitIndex) {
            // do some bounds checking here to ensure it has that index
            return input.split(splitChar)[splitIndex];
        }
    });

From here, you can use a filter as you originally intended

{{test | split:',':0}}
{{test | split:',':0}}

More info at http://docs.angularjs.org/guide/filter (thanks ross)

Plunkr @ http://plnkr.co/edit/NA4UeL

Mockito: InvalidUseOfMatchersException

For my case, the exception was raised because I tried to mock a package-access method. When I changed the method access level from package to protected the exception went away. E.g. inside below Java class,

public class Foo {
    String getName(String id) {
        return mMap.get(id);
    }
}

the method String getName(String id) has to be AT LEAST protected level so that the mocking mechanism (sub-classing) can work.

What is a classpath and how do I set it?

When programming in Java, you make other classes available to the class you are writing by putting something like this at the top of your source file:

import org.javaguy.coolframework.MyClass;

Or sometimes you 'bulk import' stuff by saying:

import org.javaguy.coolframework.*;

So later in your program when you say:

MyClass mine = new MyClass();

The Java Virtual Machine will know where to find your compiled class.

It would be impractical to have the VM look through every folder on your machine, so you have to provide the VM a list of places to look. This is done by putting folder and jar files on your classpath.

Before we talk about how the classpath is set, let's talk about .class files, packages, and .jar files.

First, let's suppose that MyClass is something you built as part of your project, and it is in a directory in your project called output. The .class file would be at output/org/javaguy/coolframework/MyClass.class (along with every other file in that package). In order to get to that file, your path would simply need to contain the folder 'output', not the whole package structure, since your import statement provides all that information to the VM.

Now let's suppose that you bundle CoolFramework up into a .jar file, and put that CoolFramework.jar into a lib directory in your project. You would now need to put lib/CoolFramework.jar into your classpath. The VM will look inside the jar file for the org/javaguy/coolframework part, and find your class.

So, classpaths contain:

  • JAR files, and
  • Paths to the top of package hierarchies.

How do you set your classpath?

The first way everyone seems to learn is with environment variables. On a unix machine, you can say something like:

export CLASSPATH=/home/myaccount/myproject/lib/CoolFramework.jar:/home/myaccount/myproject/output/

On a Windows machine you have to go to your environment settings and either add or modify the value that is already there.

The second way is to use the -cp parameter when starting Java, like this:

java -cp "/home/myaccount/myproject/lib/CoolFramework.jar:/home/myaccount/myproject/output/"  MyMainClass

A variant of this is the third way which is often done with a .sh or .bat file that calculates the classpath and passes it to Java via the -cp parameter.

There is a "gotcha" with all of the above. On most systems (Linux, Mac OS, UNIX, etc) the colon character (':') is the classpath separator. In windowsm the separator is the semicolon (';')

So what's the best way to do it?

Setting stuff globally via environment variables is bad, generally for the same kinds of reasons that global variables are bad. You change the CLASSPATH environment variable so one program works, and you end up breaking another program.

The -cp is the way to go. I generally make sure my CLASSPATH environment variable is an empty string where I develop, whenever possible, so that I avoid global classpath issues (some tools aren't happy when the global classpath is empty though - I know of two common, mega-thousand dollar licensed J2EE and Java servers that have this kind of issue with their command-line tools).

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

Use Libre Office API Here is an example

libreoffice --headless --convert-to html docx-file-path --outdir html-dir-path

JQuery: if div is visible

You can use .is(':visible')

Selects all elements that are visible.

For example:

if($('#selectDiv').is(':visible')){

Also, you can get the div which is visible by:

$('div:visible').callYourFunction();

Live example:

_x000D_
_x000D_
console.log($('#selectDiv').is(':visible'));_x000D_
console.log($('#visibleDiv').is(':visible'));
_x000D_
#selectDiv {_x000D_
  display: none;  _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="selectDiv"></div>_x000D_
<div id="visibleDiv"></div>
_x000D_
_x000D_
_x000D_

The static keyword and its various uses in C++

Static storage duration means that the variable resides in the same place in memory through the lifetime of the program.

Linkage is orthogonal to this.

I think this is the most important distinction you can make. Understand this and the rest, as well as remembering it, should come easy (not addressing @Tony directly, but whoever might read this in the future).

The keyword static can be used to denote internal linkage and static storage, but in essence these are different.

What does it mean with local variable? Is that a function local variable?

Yes. Regardless of when the variable is initialized (on first call to the function and when execution path reaches the declaration point), it will reside in the same place in memory for the life of the program. In this case, static gives it static storage.

Now what about the case with static and file scope? Are all global variables considered to have static storage duration by default?

Yes, all globals have by definition static storage duration (now that we cleared up what that means). But namespace scoped variables aren't declared with static, because that would give them internal linkage, so a variable per translation unit.

How does static relate to the linkage of a variable?

It gives namespace-scoped variables internal linkage. It gives members and local variables static storage duration.

Let's expand on all this:

//

static int x; //internal linkage
              //non-static storage - each translation unit will have its own copy of x
              //NOT A TRUE GLOBAL!

int y;        //static storage duration (can be used with extern)
              //actual global
              //external linkage
struct X
{
   static int x;     //static storage duration - shared between class instances 
};

void foo()
{
   static int x;     //static storage duration - shared between calls
}

This whole static keyword is downright confusing

Definitely, unless you're familiar with it. :) Trying to avoid adding new keywords to the language, the committee re-used this one, IMO, to this effect - confusion. It's used to signify different things (might I say, probably opposing things).

How do I count the number of occurrences of a char in a String?

With you could also use streams to achieve this. Obviously there is an iteration behind the scenes, but you don't have to write it explicitly!

public static long countOccurences(String s, char c){
    return s.chars().filter(ch -> ch == c).count();
}

countOccurences("a.b.c.d", '.'); //3
countOccurences("hello world", 'l'); //3

SQL Logic Operator Precedence: And and Or

  1. Arithmetic operators
  2. Concatenation operator
  3. Comparison conditions
  4. IS [NOT] NULL, LIKE, [NOT] IN
  5. [NOT] BETWEEN
  6. Not equal to
  7. NOT logical condition
  8. AND logical condition
  9. OR logical condition

You can use parentheses to override rules of precedence.

How to get the type of a variable in MATLAB?

MATLAB - Checking type of variables

class() exactly works like Javascript's typeof operator.

To get more details about variables you can use whos command or whos() function.

Here is the example code executed on MATLAB R2017a's Command Window.

>> % Define a number
>> num = 67

num =

    67

>> % Get type of variable num
>> class(num)

ans =

    'double'

>> % Define character vector
>> myName = 'Rishikesh Agrawani'

myName =

    'Rishikesh Agrwani'

>> % Check type of myName
>> class(myName)

ans =

    'char'

>> % Define a cell array
>> cellArr = {'This ', 'is ', 'a ', 'big chance to learn ', 'MATLAB.'}; % Cell array
>> 
>> class(cellArr)

ans =

    'cell'

>> % Get more details including type
>> whos num
  Name      Size            Bytes  Class     Attributes

  num       1x1                 8  double              

>> whos myName
  Name        Size            Bytes  Class    Attributes

  myName      1x17               34  char               

>> whos cellArr
  Name         Size            Bytes  Class    Attributes

  cellArr      1x5               634  cell               

>> % Another way to use whos i.e using whos(char_vector)
>> whos('cellArr')
  Name         Size            Bytes  Class    Attributes

  cellArr      1x5               634  cell               

>> whos('num')
  Name      Size            Bytes  Class     Attributes

  num       1x1                 8  double              

>> whos('myName')
  Name        Size            Bytes  Class    Attributes

  myName      1x17               34  char               

>> 

Convert a list of objects to an array of one of the object's properties

You are looking for

MyList.Select(x=>x.Name).ToArray();

Since Select is an Extension method make sure to add that namespace by adding a

using System.Linq

to your file - then it will show up with Intellisense.

Git stash pop- needs merge, unable to refresh index

First, check git status.
As the OP mentions,

The actual issue was an unresolved merge conflict from the merge, NOT that the stash would cause a merge conflict.

That is where git status would mention that file as being "both modified"

Resolution: Commit the conflicted file.


You can find a similar situation 4 days ago at the time of writing this answer (March 13th, 2012) with this post: "‘Pull is not possible because you have unmerged files’":

julita@yulys:~/GNOME/baobab/help/C$ git stash pop
help/C/scan-remote.page: needs merge
unable to refresh index

What you did was to fix the merge conflict (editing the right file, and committing it):
See "How do I fix merge conflicts in Git?"

What the blog post's author did was:

julita@yulys:~/GNOME/baobab/help/C$ git reset --hard origin/mallard-documentation
HEAD is now at ff2e1e2 Add more steps for optional information for scanning.

I.e aborting the current merge completely, allowing the git stash pop to be applied.
See "Aborting a merge in Git".

Those are your two options.

keycode and charcode

It is a conditional statement.

If browser supprts e.keyCode then take e.keyCode else e.charCode.

It is similar to

var code = event.keyCode || event.charCode

event.keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event.

event.charCode: Returns the Unicode value of a character key pressed during a keypress event.

Navigation bar with UIImage for title

If you'd prefer to use autolayout, and want a permanent fixed image in the navigation bar, that doesn't animate in with each screen, this solution works well:

class CustomTitleNavigationController: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()

    let logo = UIImage(named: "MyHeaderImage")

    let imageView = UIImageView(image:logo)
    imageView.contentMode = .scaleAspectFit
    imageView.translatesAutoresizingMaskIntoConstraints = false

    navigationBar.addSubview(imageView)

    navigationBar.addConstraint (navigationBar.leftAnchor.constraint(equalTo: imageView.leftAnchor, constant: 0))
    navigationBar.addConstraint (navigationBar.rightAnchor.constraint(equalTo: imageView.rightAnchor, constant: 0))
    navigationBar.addConstraint (navigationBar.topAnchor.constraint(equalTo: imageView.topAnchor, constant: 0))
    navigationBar.addConstraint (navigationBar.bottomAnchor.constraint(equalTo: imageView.bottomAnchor, constant: 0))
}

Using Linq select list inside list

If you want to filter the models by applicationname and the remaining models by surname:

List<Model> newList = list.Where(m => m.application == "applicationname")
    .Select(m => new Model { 
        application = m.application, 
        users = m.users.Where(u => u.surname == "surname").ToList() 
    }).ToList();

As you can see, it needs to create new models and user-lists, hence it is not the most efficient way.

If you instead don't want to filter the list of users but filter the models by users with at least one user with a given username, use Any:

List<Model> newList = list
    .Where(m => m.application == "applicationname"
            &&  m.users.Any(u => u.surname == "surname"))
    .ToList();

Rest-assured. Is it possible to extract value from request json?

To serialize the response into a class, define the target class

public class Result {
    public Long user_id;
}

And map response to it:

Response response = given().body(requestBody).when().post("/admin");
Result result = response.as(Result.class);

You must have Jackson or Gson in the classpath as the documentation states: http://rest-assured.googlecode.com/svn/tags/2.3.1/apidocs/com/jayway/restassured/response/ResponseBodyExtractionOptions.html#as(java.lang.Class)

Simple WPF RadioButton Binding?

I created an attached property based on Aviad's Answer which doesn't require creating a new class

public static class RadioButtonHelper
{
    [AttachedPropertyBrowsableForType(typeof(RadioButton))]
    public static object GetRadioValue(DependencyObject obj) => obj.GetValue(RadioValueProperty);
    public static void SetRadioValue(DependencyObject obj, object value) => obj.SetValue(RadioValueProperty, value);
    public static readonly DependencyProperty RadioValueProperty =
        DependencyProperty.RegisterAttached("RadioValue", typeof(object), typeof(RadioButtonHelper), new PropertyMetadata(new PropertyChangedCallback(OnRadioValueChanged)));

    private static void OnRadioValueChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is RadioButton rb)
        {
            rb.Checked -= OnChecked;
            rb.Checked += OnChecked;
        }
    }

    public static void OnChecked(object sender, RoutedEventArgs e)
    {
        if (sender is RadioButton rb)
        {
            rb.SetCurrentValue(RadioBindingProperty, rb.GetValue(RadioValueProperty));
        }
    }

    [AttachedPropertyBrowsableForType(typeof(RadioButton))]
    public static object GetRadioBinding(DependencyObject obj) => obj.GetValue(RadioBindingProperty);
    public static void SetRadioBinding(DependencyObject obj, object value) => obj.SetValue(RadioBindingProperty, value);

    public static readonly DependencyProperty RadioBindingProperty =
        DependencyProperty.RegisterAttached("RadioBinding", typeof(object), typeof(RadioButtonHelper), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault, new PropertyChangedCallback(OnRadioBindingChanged)));

    private static void OnRadioBindingChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is RadioButton rb && rb.GetValue(RadioValueProperty).Equals(e.NewValue))
        {
            rb.SetCurrentValue(RadioButton.IsCheckedProperty, true);
        }
    }
}

usage :

<RadioButton GroupName="grp1" Content="Value 1"
    helpers:RadioButtonHelper.RadioValue="val1" helpers:RadioButtonHelper.RadioBinding="{Binding SelectedValue}"/>
<RadioButton GroupName="grp1" Content="Value 2"
    helpers:RadioButtonHelper.RadioValue="val2" helpers:RadioButtonHelper.RadioBinding="{Binding SelectedValue}"/>
<RadioButton GroupName="grp1" Content="Value 3"
    helpers:RadioButtonHelper.RadioValue="val3" helpers:RadioButtonHelper.RadioBinding="{Binding SelectedValue}"/>
<RadioButton GroupName="grp1" Content="Value 4"
    helpers:RadioButtonHelper.RadioValue="val4" helpers:RadioButtonHelper.RadioBinding="{Binding SelectedValue}"/>

Check if PHP session has already started

PHP_VERSION_ID is available as of PHP 5.2.7, so check this first and if necessary , create it. session_status is available as of PHP 5.4 , so we have to check this too:

if (!defined('PHP_VERSION_ID')) {
    $version = explode('.', PHP_VERSION);
    define('PHP_VERSION_ID', ($version[0] * 10000 + $version[1] * 100 + $version[2]));
}else{
    $version = PHP_VERSION_ID;
}
if($version < 50400){
    if(session_id() == '') {
        session_start();
    }
}else{
    if (session_status() !== PHP_SESSION_ACTIVE) {
        session_start();
    }
}

Maven project version inheritance - do I have to specify the parent version?

eFox's answer worked for a single project, but not when I was referencing a module from another one (the pom.xml were still stored in my .m2 with the property instead of the version).

However, it works if you combine it with the flatten-maven-plugin, since it generates the poms with the correct version, not the property.

The only option I changed in the plug-in definition is the outputDirectory, it's empty by default, but I prefer to have it in target, which is set in my .gitignore configuration:

<plugin>
   <groupId>org.codehaus.mojo</groupId>
   <artifactId>flatten-maven-plugin</artifactId>
   <version>1.0.1</version>
   <configuration>
      <updatePomFile>true</updatePomFile>
      <outputDirectory>target</outputDirectory>
   </configuration>
   <executions>
      <execution>
         <id>flatten</id>
         <phase>process-resources</phase>
         <goals>
            <goal>flatten</goal>
         </goals>
      </execution>
   </executions>
</plugin>

The plug-in configuration goes in the parent pom.xml

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

Maybe your network is slow, so that jar isn't downloaded completely.

There are two methods:

a. find your .m2 folder, you can find some path like this 'org/apache/maven/plugins/maven-resources-plugin', you need only delete this foldler 'maven-resources-plugin', because others are downloaded well.

Then maven build your project.

If other problem occures, repeat this process again.

b. you can change a more quick maven source.

Firstly, you should find maven's settings file(window ->prefernces -> maven -> user settings). If it is empty, you can create a new one (any path, for example, .m2/settings).

Secondly, add sth like this (From https://blog.csdn.net/liangyihuai/article/details/57406870). This example uses aliyun's maven.

<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                          https://maven.apache.org/xsd/settings-1.0.0.xsd">

      <mirrors>
        <mirror>  
            <id>alimaven</id>  
            <name>aliyun maven</name>  
            <url>http://maven.aliyun.com/nexus/content/groups/public/</url>  
            <mirrorOf>central</mirrorOf>          
        </mirror>  
      </mirrors>
</settings>

Thirdly, maven build again. (before this, you should delete your .m2 folder's files)

How to select distinct rows in a datatable and store into an array

it is easy

    DataView view = new DataView(dt);
DataTable dt2 = view.ToTable(true, "Column1", "Column2","Column3", ...,"ColumnNth");

and dt2 datatable contain column1,Column2..ColumnNth unique data.

How to compile without warnings being treated as errors?

If you are compiling linux kernel. For example, if you want to disable the warning that is "unused-but-set-variable" been treated as error. You can add a statement:

KBUILD_CFLAGS += $(call cc-option,-Wno-error=unused-but-set-variable,)

in your Makefile

converting Java bitmap to byte array

Do you need to rewind the buffer, perhaps?

Also, this might happen if the stride (in bytes) of the bitmap is greater than the row length in pixels * bytes/pixel. Make the length of bytes b.remaining() instead of size.

jQuery OR Selector?

If you're looking to use the standard construct of element = element1 || element2 where JavaScript will return the first one that is truthy, you could do exactly that:

element = $('#someParentElement .somethingToBeFound') || $('#someParentElement .somethingElseToBeFound');

which would return the first element that is actually found. But a better way would probably be to use the jQuery selector comma construct (which returns an array of found elements) in this fashion:

element = $('#someParentElement').find('.somethingToBeFound, .somethingElseToBeFound')[0];

which will return the first found element.

I use that from time to time to find either an active element in a list or some default element if there is no active element. For example:

element = $('ul#someList').find('li.active, li:first')[0] 

which will return any li with a class of active or, should there be none, will just return the last li.

Either will work. There are potential performance penalties, though, as the || will stop processing as soon as it finds something truthy whereas the array approach will try to find all elements even if it has found one already. Then again, using the || construct could potentially have performance issues if it has to go through several selectors before finding the one it will return, because it has to call the main jQuery object for each one (I really don't know if this is a performance hit or not, it just seems logical that it could be). In general, though, I use the array approach when the selector is a rather long string.

Rails filtering array of objects by attribute value

You can filter using where

Job.includes(:attachments).where(file_type: ["logo", "image"])

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

fs.writeFile in a promise, asynchronous-synchronous stuff

For easy to use asynchronous convert all callback to promise use some library like "bluebird" .

      .then(function(results) {
                fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
                    if (err) {
                        console.log(err);
                    } else {
                        console.log("JSON saved");
                        return results;
                    }
                })


            }).catch(function(err) {
                console.log(err);
            });

Try solution with promise (bluebird)

var amazon = require('amazon-product-api');
var fs = require('fs');
var Promise = require('bluebird');

var client = amazon.createClient({
    awsId: "XXX",
    awsSecret: "XXX",
    awsTag: "888"
});


var array = fs.readFileSync('./test.txt').toString().split('\n');
Promise.map(array, function (ASIN) {
    client.itemLookup({
        domain: 'webservices.amazon.de',
        responseGroup: 'Large',
        idType: 'ASIN',
        itemId: ASIN
    }).then(function(results) {
        fs.writeFile(ASIN + '.json', JSON.stringify(results), function(err) {
            if (err) {
                console.log(err);
            } else {
                console.log("JSON saved");
                return results;
            }
        })
    }).catch(function(err) {
        console.log(err);
    });
});

Read a file line by line assigning the value to a variable

Use IFS (internal field separator) tool in bash, defines the character using to separate lines into tokens, by default includes <tab> /<space> /<newLine>

step 1: Load the file data and insert into list:

# declaring array list and index iterator
declare -a array=()
i=0

# reading file in row mode, insert each line into array
while IFS= read -r line; do
    array[i]=$line
    let "i++"
    # reading from file path
done < "<yourFullFilePath>"

step 2: now iterate and print the output:

for line in "${array[@]}"
  do
    echo "$line"
  done

echo specific index in array: Accessing to a variable in array:

echo "${array[0]}"

How to serialize object to CSV file?

Though its very late reply, I have faced this problem of exporting java entites to CSV, EXCEL etc in various projects, Where we need to provide export feature on UI.

I have created my own light weight framework. It works with any Java Beans, You just need to add annotations on fields you want to export to CSV, Excel etc.

Link: https://github.com/abhisoni96/dev-tools

Calculating and printing the nth prime number

This program is an efficient one. I have added one more check-in if to get the square root of a number and check is it divisible or not if it's then its not a prime number. this will solve all the problems efficiently.

public static void main(String[] args) {

            Scanner sc = new Scanner(System.in);
        int T; // number of test cases
        T = sc.nextInt();
        long[] number = new long[T];
        if(1<= T && T <= 30){
        for(int i =0;i<T;i++){
            number[i]=sc.nextInt(); // read all the numbers
        }
        for(int i =0;i<T;i++){
            if(isPrime(number[i]))
                System.out.println("Prime");
            else
               System.out.println("Not prime");    
        }
    }
    else
      return;
    }
    // is prime or not
    static boolean isPrime(long num){
        if(num==1)
          return false;
        if(num <= 3)
          return true;
        if(num % 2 == 0 || num % 3 == 0 || num % (int)Math.sqrt(num) == 0)
          return false;  
        for(int i=4;i<(int)Math.sqrt(num);i++){
            if(num%i==0)
              return false;
        }
       return true;     
    }

How to get JQuery.trigger('click'); to initiate a mouse click

Try this that works for me:

$('#bar').mousedown();

How to save a Python interactive session?

Just putting another suggesting in the bowl: Spyder

enter image description here

It has History log and Variable explorer. If you have worked with MatLab, then you'll see the similarities.

TypeError: Router.use() requires middleware function but got a Object

I was getting the same error message but had a different issue. Posting for others that are stuck on same.

I ported the get, post, put, delete functions to new router file while refactoring, and forgot to edit the paths. Example:

Incorrect:

//server.js
app.use('/blog-posts', blogPostsRouter);

//routers/blogPostsRouter.js
router.get('/blog-posts', (req, res) => {
  res.json(BlogPosts.get());
});

Correct:

//server.js
app.use('/blog-posts', blogPostsRouter);

//routers/blogPostsRouter.js
router.get('/', (req, res) => {
  res.json(BlogPosts.get());
});

Took a while to spot, as the error had me checking syntax where I might have been wrapping an argument in an object or where I missed the module.exports = router;

AddRange to a Collection

You could add your IEnumerable range to a list then set the ICollection = to the list.

        IEnumerable<T> source;

        List<item> list = new List<item>();
        list.AddRange(source);

        ICollection<item> destination = list;

Pandas split DataFrame by column value

Using "groupby" and list comprehension:

Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.

DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]

accessing the separated DF like this:

ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF

accessing the column value of the separated DF like this:

ansI_chr=ans[i].chr 

EOFError: end of file reached issue with Net::HTTP

I had a similar problem with a request to a non-SSL service.

This blog suggested vaguely to try URI encoding the URL that is passed to 'get': http://www.loudthinking.org/2010/02/ruby-eoferror-end-of-file-reached.html

I took a shot at it, based on desperation, and in my limiting testing this seems to have fixed it for me. My new code is:

@http = Net::HTTP.new('domain.com')  
@http = @http.start    
url = 'http://domain.com/requested_url?blah=blah&etc=1'
req = Net::HTTP::Get.new(URI.encode(url))
req.basic_auth USERNAME, API_KEY
res = @http.request(req) 

Note that I use @http.start as I want to maintain the HTTP session over multiple requests. Other than that, you might like to try the most relevant part which is: URI.encode(url) inside the get call

What's a good (free) visual merge tool for Git? (on windows)

I don't know a good free tool but winmerge is ok(ish). I've been using the beyond compare tools since 1999 and can't rate it enough - it costs about 50 USD and this investment has paid for it self in time savings more than I can possible imagine.

Sometimes tools should be paid for if they are very very good.

Linking static libraries to other static libraries

If you are using Visual Studio then yes, you can do this.

The library builder tool that comes with Visual Studio allows you to join libraries together on the command line. I don't know of any way to do this in the visual editor though.

lib.exe /OUT:compositelib.lib  lib1.lib lib2.lib

Table column sizing

Disclaimer: This answer may be a bit old. Since the bootstrap 4 beta. Bootstrap has changed since then.

The table column size class has been changed from this

<th class="col-sm-3">3 columns wide</th>

to

<th class="col-3">3 columns wide</th>

Make selected block of text uppercase

The question is about how to make CTRL+SHIFT+U work in Visual Studio Code. Here is how to do it. (Version 1.8.1 or above).

File-> Preferences -> Keyboard Shortcuts.

An editor will appear with keybindings.json file. Place the following JSON in there and save.

[
 {
    "key": "ctrl+shift+u",
    "command": "editor.action.transformToUppercase",
    "when": "editorTextFocus"
 },
 {
    "key": "ctrl+shift+l",
    "command": "editor.action.transformToLowercase",
    "when": "editorTextFocus"
 }
]

Now CTRL+SHIFT+U will capitalise selected text, even if multi line. In the same way, CTRL+SHIFT+L will make selected text lowercase.

These commands are built into VS Code, and no extensions are required to make them work.

Handle spring security authentication exceptions with @ExceptionHandler

Ok, I tried as suggested writing the json myself from the AuthenticationEntryPoint and it works.

Just for testing I changed the AutenticationEntryPoint by removing response.sendError

@Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint{

    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authenticationException) throws IOException, ServletException {
    
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.getOutputStream().println("{ \"error\": \"" + authenticationException.getMessage() + "\" }");

    }
}

In this way you can send custom json data along with the 401 unauthorized even if you are using Spring Security AuthenticationEntryPoint.

Obviously you would not build the json as I did for testing purposes but you would serialize some class instance.

In Spring Boot, you should add it to http.authenticationEntryPoint() part of SecurityConfiguration file.

C compile error: Id returned 1 exit status

You may compiling your program while another program may be running in background. Firstly, see if another program is running .Close it and then try ro compile.

Tomcat 7: How to set initial heap size correctly?

Just came across this and I've implemented Nathan's solution:

add the line (changing the values as required):

export JAVA_OPTS="-Xms512M -Xmx1024M"

to /usr/share/tomcat7/bin/setenv.sh

If that file doesn't exists then create it and

chown root:root it
chmod 755 it

And then restart tomcat and check it with

ps aux | grep logging

Which should just pick up the instance and show the java parms

REST API - Bulk Create or Update in single request

In a project I worked at we solved this problem by implement something we called 'Batch' requests. We defined a path /batch where we accepted json in the following format:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 5,
         binder: 8
      }
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      }
   },
]

The response have the status code 207 (Multi-Status) and looks like this:

[  
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 1,
         binder: 1
      }
      status: 200
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         error: {
            msg: 'A document with doc_number 5 already exists'
            ...
         }
      },
      status: 409
   },
   {
      path: '/docs',
      method: 'post',
      body: {
         doc_number: 6,
         binder: 3
      },
      status: 200
   },
]

You could also add support for headers in this structure. We implemented something that proved useful which was variables to use between requests in a batch, meaning we can use the response from one request as input to another.

Facebook and Google have similar implementations:
https://developers.google.com/gmail/api/guides/batch
https://developers.facebook.com/docs/graph-api/making-multiple-requests

When you want to create or update a resource with the same call I would use either POST or PUT depending on the case. If the document already exist, do you want the entire document to be:

  1. Replaced by the document you send in (i.e. missing properties in request will be removed and already existing overwritten)?
  2. Merged with the document you send in (i.e. missing properties in request will not be removed and already existing properties will be overwritten)?

In case you want the behavior from alternative 1 you should use a POST and in case you want the behavior from alternative 2 you should use PUT.

http://restcookbook.com/HTTP%20Methods/put-vs-post/

As people already suggested you could also go for PATCH, but I prefer to keep API's simple and not use extra verbs if they are not needed.

How can I alter a primary key constraint using SQL syntax?

PRIMARY KEY CONSTRAINT cannot be altered, you may only drop it and create again. For big datasets it can cause a long run time and thus - table inavailability.

How can you speed up Eclipse?

One more trick is to disable automatic builds.

How can I export Excel files using JavaScript?

There is an interesting project on github called Excel Builder (.js) that offers a client-side way of downloading Excel xlsx files and includes options for formatting the Excel spreadsheet.
https://github.com/stephenliberty/excel-builder.js

You may encounter both browser and Excel compatibility issues using this library, but under the right conditions, it may be quite useful.

Another github project with less Excel options but less worries about Excel compatibility issues can be found here: ExcellentExport.js
https://github.com/jmaister/excellentexport

If you are using AngularJS, there is ng-csv:
a "Simple directive that turns arrays and objects into downloadable CSV files".

No value accessor for form control

If you must use the label for the formControl. Like the Ant Design Checkbox. It may throw this error while running tests. You can use ngDefaultControl

<label nz-checkbox formControlName="isEnabled" ngDefaultControl>
    Hello
</label>

<nz-switch nzSize="small" formControlName="mandatory" ngDefaultControl></nz-switch>

Given a starting and ending indices, how can I copy part of a string in C?

Have you checked strncpy?

char * strncpy ( char * destination, const char * source, size_t num );

You must realize that begin and end actually defines a num of bytes to be copied from one place to another.

Is there a function to round a float in C or do I need to write my own?

To print a rounded value, @Matt J well answers the question.

float x = 45.592346543;
printf("%0.1f\n", x);  // 45.6

As most floating point (FP) is binary based, exact rounding to one decimal place is not possible when the mathematically correct answer is x.1, x.2, ....

To convert the FP number to the nearest 0.1 is another matter.

Overflow: Approaches that first scale by 10 (or 100, 1000, etc) may overflow for large x.

float round_tenth1(float x) {
  x = x * 10.0f;
  ...
}

Double rounding: Adding 0.5f and then using floorf(x*10.0f + 0.5f)/10.0 returns the wrong result when the intermediate sum x*10.0f + 0.5f rounds up to a new integer.

// Fails to round 838860.4375 correctly, comes up with 838860.5 
// 0.4499999880790710449 fails as it rounds to 0.5
float round_tenth2(float x) {
  if (x < 0.0) {
    return ceilf(x*10.0f + 0.5f)/10.0f;
  }
  return floorf(x*10.0f + 0.5f)/10.0f;
}

Casting to int has the obvious problem when float x is much greater than INT_MAX.


Using roundf() and family, available in <math.h> is the best approach.

float round_tenthA(float x) {
  double x10 = 10.0 * x;
  return (float) (round(x10)/10.0);
}

To avoid using double, simply test if the number needs rounding.

float round_tenthB(float x) {
  const float limit = 1.0/FLT_EPSILON;
  if (fabsf(x) < limit) {
    return roundf(x*10.0f)/10.0f;
  }
  return x;
}

How do I hide an element when printing a web page?

_x000D_
_x000D_
@media print {_x000D_
  .no-print {_x000D_
    visibility: hidden;_x000D_
  }_x000D_
}
_x000D_
<div class="no-print">_x000D_
  Nope_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
  Yup_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I create 2 separate log files with one log4j config file?

Try the following configuration:

log4j.rootLogger=TRACE, stdout

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.debugLog=org.apache.log4j.FileAppender
log4j.appender.debugLog.File=logs/debug.log
log4j.appender.debugLog.layout=org.apache.log4j.PatternLayout
log4j.appender.debugLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.appender.reportsLog=org.apache.log4j.FileAppender
log4j.appender.reportsLog.File=logs/reports.log
log4j.appender.reportsLog.layout=org.apache.log4j.PatternLayout
log4j.appender.reportsLog.layout.ConversionPattern=%d [%24F:%t:%L] - %m%n

log4j.category.debugLogger=TRACE, debugLog
log4j.additivity.debugLogger=false

log4j.category.reportsLogger=DEBUG, reportsLog
log4j.additivity.reportsLogger=false

Then configure the loggers in the Java code accordingly:

static final Logger debugLog = Logger.getLogger("debugLogger");
static final Logger resultLog = Logger.getLogger("reportsLogger");

Do you want output to go to stdout? If not, change the first line of log4j.properties to:

log4j.rootLogger=OFF

and get rid of the stdout lines.

MySQL command line client for Windows

I have similar requirement where I need a MySQL client but not server (running in a virtual machine and don't want any additional overhead) and for me the easiest thing was to install MySQL community server taking typical installation options but NOT configure the server, so it never starts, never runs. Added C:\Program Files (x86)\MySQL\MySQL Server 5.5\bin to system path environment variable and I'm able to use the MySQL command line client mssql.exe and mysqladmin.exe programs.

JUnit: how to avoid "no runnable methods" in test utils classes

Ant now comes with the skipNonTests attribute which was designed to do exactly what you seem to be looking for. No need to change your base classes to abstract or add annotations to them.

jQuery: set selected value of dropdown list?

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

Format date in a specific timezone

You can Try this ,

Here you can get the date based on the Client Timezone (Browser).

moment(new Date().getTime()).zone(new Date().toString().match(/([-\+][0-9]+)\s/)[1]).format('YYYY-MM-DD HH:mm:ss')

The regex basically gets you the offset value.

Cheers!!

How to debug .htaccess RewriteRule not working

Enter some junk value into your .htaccess e.g. foo bar, sakjnaskljdnas any keyword not recognized by htaccess and visit your URL. If it is working, you should get a

500 Internal Server Error

Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request....

I suggest you to put it soon after RewriteEngine on.


Since you are on your machine. I presume you have access to apache .conf file.

open the .conf file, and look for a line similar to:

LoadModule rewrite_module modules/mod_rewrite.so

If it is commented(#), uncomment and restart apache.


To log rewrite

RewriteEngine On
RewriteLog "/path/to/rewrite.log"
RewriteLogLevel 9

Put the above 3 lines in your virtualhost. restart the httpd.

RewriteLogLevel 9 Using a high value for Level will slow down your Apache server dramatically! Use the rewriting logfile at a Level greater than 2 only for debugging! Level 9 will log almost every rewritelog detail.


UPDATE

Things have changed in Apache 2.4:

FROM Upgrading to 2.4 from 2.2

The RewriteLog and RewriteLogLevel directives have been removed. This functionality is now provided by configuring the appropriate level of logging for the mod_rewrite module using the LogLevel directive. See also the mod_rewrite logging section.

For more on LogLevel, refer LogLevel Directive

you can accomplish

RewriteLog "/path/to/rewrite.log"

in this manner now

LogLevel debug rewrite_module:debug

How to apply color in Markdown?

I've had success with

<span class="someclass"></span>

Caveat : the class must already exist on the site.

FCM getting MismatchSenderId

I found that the senderId is different from the project number in the FCM console
so I re-downloaded google-services.json and everything works fine

Asynchronous vs synchronous execution, what does it really mean?

Synchronous means queue way execution one by one task will be executed. Suppose there is only vehicle that need to be share among friend to reach their destination one by one vehicle will be share.
In asynchronous case each friend can get rented vehicle and reach its destination.