Programs & Examples On #Unsigned

An unsigned variable is a variable that can only represent non-negative numbers.

What is the difference between “int” and “uint” / “long” and “ulong”?

The primitive data types prefixed with "u" are unsigned versions with the same bit sizes. Effectively, this means they cannot store negative numbers, but on the other hand they can store positive numbers twice as large as their signed counterparts. The signed counterparts do not have "u" prefixed.

The limits for int (32 bit) are:

int: –2147483648 to 2147483647 
uint: 0 to 4294967295 

And for long (64 bit):

long: -9223372036854775808 to 9223372036854775807
ulong: 0 to 18446744073709551615

Iteration over std::vector: unsigned vs signed index variable

The two code segments work the same. However, unsigned int" route is correct. Using unsigned int types will work better with the vector in the instance you used it. Calling the size() member function on a vector returns an unsigned integer value, so you want to be comparing the variable "i" to a value of its own type.

Also, if you are still a little uneasy about how "unsigned int" looks in your code, try "uint". This is basically a shortened version of "unsigned int" and it works exactly the same. You also don't need to include other headers to use it.

Unsigned values in C

When you initialize unsigned int a to -1; it means that you are storing the 2's complement of -1 into the memory of a.
Which is nothing but 0xffffffff or 4294967295.

Hence when you print it using %x or %u format specifier you get that output.

By specifying signedness of a variable to decide on the minimum and maximum limit of value that can be stored.

Like with unsigned int: the range is from 0 to 4,294,967,295 and int: the range is from -2,147,483,648 to 2,147,483,647

For more info on signedness refer this

Declaring an unsigned int in Java

There are good answers here, but I don’t see any demonstrations of bitwise operations. Like Visser (the currently accepted answer) says, Java signs integers by default (Java 8 has unsigned integers, but I have never used them). Without further ado, let‘s do it...

RFC 868 Example

What happens if you need to write an unsigned integer to IO? Practical example is when you want to output the time according to RFC 868. This requires a 32-bit, big-endian, unsigned integer that encodes the number of seconds since 12:00 A.M. January 1, 1900. How would you encode this?

Make your own unsigned 32-bit integer like this:

Declare a byte array of 4 bytes (32 bits)

Byte my32BitUnsignedInteger[] = new Byte[4] // represents the time (s)

This initializes the array, see Are byte arrays initialised to zero in Java?. Now you have to fill each byte in the array with information in the big-endian order (or little-endian if you want to wreck havoc). Assuming you have a long containing the time (long integers are 64 bits long in Java) called secondsSince1900 (Which only utilizes the first 32 bits worth, and you‘ve handled the fact that Date references 12:00 A.M. January 1, 1970), then you can use the logical AND to extract bits from it and shift those bits into positions (digits) that will not be ignored when coersed into a Byte, and in big-endian order.

my32BitUnsignedInteger[0] = (byte) ((secondsSince1900 & 0x00000000FF000000L) >> 24); // first byte of array contains highest significant bits, then shift these extracted FF bits to first two positions in preparation for coersion to Byte (which only adopts the first 8 bits)
my32BitUnsignedInteger[1] = (byte) ((secondsSince1900 & 0x0000000000FF0000L) >> 16);
my32BitUnsignedInteger[2] = (byte) ((secondsSince1900 & 0x000000000000FF00L) >> 8);
my32BitUnsignedInteger[3] = (byte) ((secondsSince1900 & 0x00000000000000FFL); // no shift needed

Our my32BitUnsignedInteger is now equivalent to an unsigned 32-bit, big-endian integer that adheres to the RCF 868 standard. Yes, the long datatype is signed, but we ignored that fact, because we assumed that the secondsSince1900 only used the lower 32 bits). Because of coersing the long into a byte, all bits higher than 2^7 (first two digits in hex) will be ignored.

Source referenced: Java Network Programming, 4th Edition.

Can we make unsigned byte in Java

I am trying to use this data as a parameter to a function of Java that accepts only a byte as parameter

This is not substantially different from a function accepting an integer to which you want to pass a value larger than 2^32-1.

That sounds like it depends on how the function is defined and documented; I can see three possibilities:

  1. It may explicitly document that the function treats the byte as an unsigned value, in which case the function probably should do what you expect but would seem to be implemented wrong. For the integer case, the function would probably declare the parameter as an unsigned integer, but that is not possible for the byte case.

  2. It may document that the value for this argument must be greater than (or perhaps equal to) zero, in which case you are misusing the function (passing an out-of-range parameter), expecting it to do more than it was designed to do. With some level of debugging support you might expect the function to throw an exception or fail an assertion.

  3. The documentation may say nothing, in which case a negative parameter is, well, a negative parameter and whether that has any meaning depends on what the function does. If this is meaningless then perhaps the function should really be defined/documented as (2). If this is meaningful in an nonobvious manner (e.g. non-negative values are used to index into an array, and negative values are used to index back from the end of the array so -1 means the last element) the documentation should say what it means and I would expect that it isn't what you want it to do anyway.

Why doesn't Java support unsigned ints?

I've heard stories that they were to be included close to the orignal Java release. Oak was the precursor to Java, and in some spec documents there was mention of usigned values. Unfortunately these never made it into the Java language. As far as anyone has been able to figure out they just didn't get implemented, likely due to a time constraint.

Difference between signed / unsigned char

There are three char types: (plain) char, signed char and unsigned char. Any char is usually an 8-bit integer* and in that sense, a signed and unsigned char have a useful meaning (generally equivalent to uint8_t and int8_t). When used as a character in the sense of text, use a char (also referred to as a plain char). This is typically a signed char but can be implemented either way by the compiler.

* Technically, a char can be any size as long as sizeof(char) is 1, but it is usually an 8-bit integer.

Is unsigned integer subtraction defined behavior?

With unsigned numbers of type unsigned int or larger, in the absence of type conversions, a-b is defined as yielding the unsigned number which, when added to b, will yield a. Conversion of a negative number to unsigned is defined as yielding the number which, when added to the sign-reversed original number, will yield zero (so converting -5 to unsigned will yield a value which, when added to 5, will yield zero).

Note that unsigned numbers smaller than unsigned int may get promoted to type int before the subtraction, the behavior of a-b will depend upon the size of int.

Unsigned keyword in C++

From the link above:

Several of these types can be modified using the keywords signed, unsigned, short, and long. When one of these type modifiers is used by itself, a data type of int is assumed

This means that you can assume the author is using ints.

Calculating bits required to store decimal number

The simplest answer would be to convert the required values to binary, and see how many bits are required for that value. However, the question asks how many bits for a decimal number of X digits. In this case, it seems like you have to choose the highest value with X digits, and then convert that number to binary.

As a basic example, Let's assume we wanted to store a 1 digit base ten number, and wanted to know how many bits that would require. The largest 1 digit base ten number is 9, so we need to convert it to binary. This yields 1001, which has a total of 4 bits. This same example can be applied to a two digit number (with the max value being 99, which converts to 1100011). To solve for n digits, you probably need to solve the others and search for a pattern.

To convert values to binary, you repeatedly divide by two until you get a quotient of 0 (and all of your remainders will be 0 or 1). You then reverse the orders of your remainders to get the number in binary.

Exampe: 13 to binary.

  • 13/2 = 6 r 1
  • 6/2 = 3 r 0
  • 3/2 = 1 r 1
  • 1/2 = 0 r 1
  • = 1101 ((8*1) + (4*1) + (2*0) + (1*1))

Hope this helps out.

How to convert signed to unsigned integer in python

Assuming:

  1. You have 2's-complement representations in mind; and,
  2. By (unsigned long) you mean unsigned 32-bit integer,

then you just need to add 2**32 (or 1 << 32) to the negative value.

For example, apply this to -1:

>>> -1
-1
>>> _ + 2**32
4294967295L
>>> bin(_)
'0b11111111111111111111111111111111'

Assumption #1 means you want -1 to be viewed as a solid string of 1 bits, and assumption #2 means you want 32 of them.

Nobody but you can say what your hidden assumptions are, though. If, for example, you have 1's-complement representations in mind, then you need to apply the ~ prefix operator instead. Python integers work hard to give the illusion of using an infinitely wide 2's complement representation (like regular 2's complement, but with an infinite number of "sign bits").

And to duplicate what the platform C compiler does, you can use the ctypes module:

>>> import ctypes
>>> ctypes.c_ulong(-1)  # stuff Python's -1 into a C unsigned long
c_ulong(4294967295L)
>>> _.value
4294967295L

C's unsigned long happens to be 4 bytes on the box that ran this sample.

What is the difference between signed and unsigned variables?

Signed variables use one bit to flag whether they are positive or negative. Unsigned variables don't have this bit, so they can store larger numbers in the same space, but only nonnegative numbers, e.g. 0 and higher.

For more: Unsigned and Signed Integers

Signed versus Unsigned Integers

Generally speaking that is correct. Without knowing anything more about why you are looking for the differences I can't think of any other differentiators between signed and unsigned.

Java equivalent of unsigned long long?

Nope, there is not. You'll have to use the primitive long data type and deal with signedness issues, or use a class such as BigInteger.

How to determine a Python variable's type?

How to determine the variable type in Python?

So if you have a variable, for example:

one = 1

You want to know its type?

There are right ways and wrong ways to do just about everything in Python. Here's the right way:

Use type

>>> type(one)
<type 'int'>

You can use the __name__ attribute to get the name of the object. (This is one of the few special attributes that you need to use the __dunder__ name to get to - there's not even a method for it in the inspect module.)

>>> type(one).__name__
'int'

Don't use __class__

In Python, names that start with underscores are semantically not a part of the public API, and it's a best practice for users to avoid using them. (Except when absolutely necessary.)

Since type gives us the class of the object, we should avoid getting this directly. :

>>> one.__class__

This is usually the first idea people have when accessing the type of an object in a method - they're already looking for attributes, so type seems weird. For example:

class Foo(object):
    def foo(self):
        self.__class__

Don't. Instead, do type(self):

class Foo(object):
    def foo(self):
        type(self)

Implementation details of ints and floats

How do I see the type of a variable whether it is unsigned 32 bit, signed 16 bit, etc.?

In Python, these specifics are implementation details. So, in general, we don't usually worry about this in Python. However, to sate your curiosity...

In Python 2, int is usually a signed integer equal to the implementation's word width (limited by the system). It's usually implemented as a long in C. When integers get bigger than this, we usually convert them to Python longs (with unlimited precision, not to be confused with C longs).

For example, in a 32 bit Python 2, we can deduce that int is a signed 32 bit integer:

>>> import sys

>>> format(sys.maxint, '032b')
'01111111111111111111111111111111'
>>> format(-sys.maxint - 1, '032b') # minimum value, see docs.
'-10000000000000000000000000000000'

In Python 3, the old int goes away, and we just use (Python's) long as int, which has unlimited precision.

We can also get some information about Python's floats, which are usually implemented as a double in C:

>>> sys.float_info
sys.floatinfo(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, 
min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, 
mant_dig=53, epsilon=2.2204460492503131e-16, radix=2, rounds=1)

Conclusion

Don't use __class__, a semantically nonpublic API, to get the type of a variable. Use type instead.

And don't worry too much about the implementation details of Python. I've not had to deal with issues around this myself. You probably won't either, and if you really do, you should know enough not to be looking to this answer for what to do.

How to printf "unsigned long" in C?

int main()
{
    unsigned long long d;
    scanf("%llu",&d);
    printf("%llu",d);
    getch();
}

This will be helpful . . .

How to use the unsigned Integer in Java 8 and Java 9?

Per the documentation you posted, and this blog post - there's no difference when declaring the primitive between an unsigned int/long and a signed one. The "new support" is the addition of the static methods in the Integer and Long classes, e.g. Integer.divideUnsigned. If you're not using those methods, your "unsigned" long above 2^63-1 is just a plain old long with a negative value.

From a quick skim, it doesn't look like there's a way to declare integer constants in the range outside of +/- 2^31-1, or +/- 2^63-1 for longs. You would have to manually compute the negative value corresponding to your out-of-range positive value.

should use size_t or ssize_t

ssize_t is not included in the standard and isn't portable. size_t should be used when handling the size of objects (there's ptrdiff_t too, for pointer differences).

How to cast or convert an unsigned int to int in C?

If an unsigned int and a (signed) int are used in the same expression, the signed int gets implicitly converted to unsigned. This is a rather dangerous feature of the C language, and one you therefore need to be aware of. It may or may not be the cause of your bug. If you want a more detailed answer, you'll have to post some code.

what is the unsigned datatype?

According to C17 6.7.2 §2:

Each list of type specifiers shall be one of the following multisets (delimited by commas, when there is more than one multiset per item); the type specifiers may occur in any order, possibly intermixed with the other declaration specifiers

— void
— char
— signed char
— unsigned char
— short, signed short, short int, or signed short int
— unsigned short, or unsigned short int
— int, signed, or signed int
— unsigned, or unsigned int
— long, signed long, long int, or signed long int
— unsigned long, or unsigned long int
— long long, signed long long, long long int, or signed long long int
— unsigned long long, or unsigned long long int
— float
— double
— long double
— _Bool
— float _Complex
— double _Complex
— long double _Complex
— atomic type specifier
— struct or union specifier
— enum specifier
— typedef name

So in case of unsigned int we can either write unsigned or unsigned int, or if we are feeling crazy, int unsigned. The latter since the standard is stupid enough to allow "...may occur in any order, possibly intermixed". This is a known flaw of the language.

Proper C code uses unsigned int.

Get Selected value from dropdown using JavaScript

Maybe it's the comma in your if condition.

function answers() {
var answer=document.getElementById("mySelect");
 if(answer[answer.selectedIndex].value == "To measure time.") {
  alert("That's correct!"); 
 }
}

You can also write it like this.

function answers(){
 document.getElementById("mySelect").value!="To measure time."||(alert('That's correct!'))
}

How to set a hidden value in Razor

If I understand correct you will have something like this:

<input value="default" id="sth" name="sth" type="hidden">

And to get it you have to write:

@Html.HiddenFor(m => m.sth, new { Value = "default" })

for Strongly-typed view.

Single quotes vs. double quotes in C or C++

Some compilers also implement an extension, that allows multi-character constants. The C99 standard says:

6.4.4.4p10: "The value of an integer character constant containing more than one character (e.g., 'ab'), or containing a character or escape sequence that does not map to a single-byte execution character, is implementation-defined."

This could look like this, for instance:

const uint32_t png_ihdr = 'IHDR';

The resulting constant (in GCC, which implements this) has the value you get by taking each character and shifting it up, so that 'I' ends up in the most significant bits of the 32-bit value. Obviously, you shouldn't rely on this if you are writing platform independent code.

Is there a job scheduler library for node.js?

You can use timexe

It's simple to use, light weight, has no dependencies, has an improved syntax over cron, with a resolution in milliseconds and works in the browser.

Install:

npm install timexe

Use:

var timexe = require('timexe');
var res = timexe("* * * 15 30", function(){ console.log("It's now 3:30 pm"); });

(I'm the author)

How do I get indices of N maximum values in a NumPy array?

The simplest I've been able to come up with is:

In [1]: import numpy as np

In [2]: arr = np.array([1, 3, 2, 4, 5])

In [3]: arr.argsort()[-3:][::-1]
Out[3]: array([4, 3, 1])

This involves a complete sort of the array. I wonder if numpy provides a built-in way to do a partial sort; so far I haven't been able to find one.

If this solution turns out to be too slow (especially for small n), it may be worth looking at coding something up in Cython.

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

I looked at most the solutions posted, but came across a different one that I prefer. It's simple, doesn't use threads, and works for what I want it to.

http://weblogs.asp.net/kennykerr/archive/2004/11/26/where-is-form-s-loaded-event.aspx

I added to the solution in the article and moved the code into a base class that all my forms inherit from. Now I just call one function: ShowWaitForm() during the frm_load() event of any form that needs a wait dialogue box while the form is loading. Here's the code:

public class MyFormBase : System.Windows.Forms.Form
{
    private MyWaitForm _waitForm;

    protected void ShowWaitForm(string message)
    {
        // don't display more than one wait form at a time
        if (_waitForm != null && !_waitForm.IsDisposed) 
        {
            return;
        }

        _waitForm = new MyWaitForm();
        _waitForm.SetMessage(message); // "Loading data. Please wait..."
        _waitForm.TopMost = true;
        _waitForm.StartPosition = FormStartPosition.CenterScreen;
        _waitForm.Show();
        _waitForm.Refresh();

        // force the wait window to display for at least 700ms so it doesn't just flash on the screen
        System.Threading.Thread.Sleep(700);         
        Application.Idle += OnLoaded;
    }

    private void OnLoaded(object sender, EventArgs e)
    {
        Application.Idle -= OnLoaded;
        _waitForm.Close();
    }
}

MyWaitForm is the name of a form you create to look like a wait dialogue. I added a SetMessage() function to customize the text on the wait form.

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(R.id.textView1);
   holder.textAddress = (TextView) row.findViewById(R.id.textView2);
   holder.textLocation = (TextView) row.findViewById(R.id.textView3);
   holder.btnEdit = (Button) row.findViewById(R.id.button1);
   holder.btnDelete = (Button) row.findViewById(R.id.button2);
   row.setTag(holder);
  } else {
   holder = (UserHolder) row.getTag();
  }
  User user = data.get(position);
  holder.textName.setText(user.getName());
  holder.textAddress.setText(user.getAddress());
  holder.textLocation.setText(user.getLocation());
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  return row;

 }

 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;
 }
}

Hey Please have a look here-

I have same answer here on my blog ..

How to display a content in two-column layout in LaTeX?

Load the multicol package, like this \usepackage{multicol}. Then use:

\begin{multicols}{2}
Column 1
\columnbreak
Column 2
\end{multicols}

If you omit the \columnbreak, the columns will balance automatically.

PostgreSQL next value of the sequences?

If your are not in a session you can just nextval('you_sequence_name') and it's just fine.

No server in windows>preferences

If above answers did not work for you then just click this link https://www.eclipse.org/downloads/packages/release/2020-06/r/eclipse-ide-enterprise-java-developers download according to your OS. And after downloading and extracting the ZIP open the extract folder and click on Eclipse application icon. enter image description here

Then just enter your workspace and get started. Now you will be able to see the servers option in Window->Show View, like this:

enter image description here

Use of var keyword in C#

First.

var is not a type and not some special feature (like c# 4.0 dynamic). It is just a syntax sugar. You ask compiler to infer the type by the right hand side expression. The only necessary place is anonymous types.

I don't think that using var is neither good or evil, it is coding style. Personally i don't use it, but i don't mind using it by other team members.

Which browser has the best support for HTML 5 currently?

To test your browser, go to http://html5test.com/. The code is being maintained at: github dot com slash NielsLeenheer slash html5test.

Right way to split an std::string into a vector<string>

For space separated strings, then you can do this:

std::string s = "What is the right way to split a string into a vector of strings";
std::stringstream ss(s);
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

Output:

What
is
the
right
way
to
split
a
string
into
a
vector
of
strings

string that have both comma and space

struct tokens: std::ctype<char> 
{
    tokens(): std::ctype<char>(get_table()) {}
 
    static std::ctype_base::mask const* get_table()
    {
        typedef std::ctype<char> cctype;
        static const cctype::mask *const_rc= cctype::classic_table();
 
        static cctype::mask rc[cctype::table_size];
        std::memcpy(rc, const_rc, cctype::table_size * sizeof(cctype::mask));
 
        rc[','] = std::ctype_base::space; 
        rc[' '] = std::ctype_base::space; 
        return &rc[0];
    }
};
 
std::string s = "right way, wrong way, correct way";
std::stringstream ss(s);
ss.imbue(std::locale(std::locale(), new tokens()));
std::istream_iterator<std::string> begin(ss);
std::istream_iterator<std::string> end;
std::vector<std::string> vstrings(begin, end);
std::copy(vstrings.begin(), vstrings.end(), std::ostream_iterator<std::string>(std::cout, "\n"));

Output:

right
way
wrong
way
correct
way

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

The first thing you need to check is your build configuration of your application.

  • If you have built your project under x86 platform, then in order to resolve you issue you should install the following packages on your machine:

    1. In order to use the 'Microsoft.ACE.OLEDB.12.0' provider you must install the Microsoft Access Database Engine 2010 Redistributable first, this installation is available at: http://www.microsoft.com/download/en/details.aspx?id=13255 .

      After the installation has complete, try running you application, if this solves the issue great, if not, continue to step 2.

    2. This next step is an unexplained workaround, which works for Office 2010, even though it is the Data Connectivity Components of Office 2007. I am not quite sure why this works, but it does and this has been proven to work in almost all cases. You need to install the 2007 Office System Driver: Data Connectivity Components, this installation is available at: http://www.microsoft.com/download/en/confirmation.aspx?id=23734 .

      After this installation is complete, try running your application, this should resolve the issue.

  • If you are trying to run an application built under x64 or AnyCPU platform, I would recommend first validating that it runs as expected under the x86 platform. In the event that it does not run under that x86 platform, perform the steps in the first part and validate that it runs as expected.

    I did read that the MS Access drivers including the OLEDB Database driver works only under the x86 platform and is incompatible under the x64 or AnyCPU platform. But this appears to be untrue. I validated my application was running when building x86, then I installed the Access Database Engine using the passive flag.

    1. First download the file locally You can download the installation here: http://www.microsoft.com/en-us/download/details.aspx?id=13255
    2. Installing using the command prompt with the '/passive' flag. In the command prompt run the following command: 'AccessDatabaseEngine_x64.exe /passive'

    After these 2 steps I managed to run my application after building in x64 or AnyCPU build configuration. This appeared to solve my issue.

Note: The order of the steps seems to make a difference, so please follow accordingly.

Gradle build without tests

You will have to add -x test

e.g. ./gradlew build -x test

or

gradle build -x test

How do I use StringUtils in Java?

If you're developing for Android there is TextUtils class which may help you:

import android.text.TextUtils;

It is really helps a lot to check equality of Strings.
For example if you need to check Strings s1, s2 equality (which may be nulls) you may use instead of

if( (s1 != null && !s1.equals(s2)) || (s1 == null && s2 != null) ) 
{ ... }

this simple method:

if( !TextUtils.equals(s1, s2) )
{ ... }

As for initial question - for replacement it's easier to use s1.replace().

Console logging for react?

If you're just after console logging here's what I'd do:

export default class App extends Component {
  componentDidMount() {
    console.log('I was triggered during componentDidMount')
  }

  render() {
    console.log('I was triggered during render')
    return ( 
      <div> I am the App component </div>
    )
  }
}

Shouldn't be any need for those packages just to do console logging.

Starting of Tomcat failed from Netbeans

For NetBeans to be able to interact with tomcat, it needs the user as setup in netbeans to be properly configured in the tomcat-users.xml file. NetBeans can do so automatically.

That is, within the tomcat-users.xml, which you can find in ${CATALINA_HOME}/conf, or ${CATALINA_BASE}/conf,

  1. make sure that the user (as chosen in netbeans) is added the script-manager role

Example, change

<user password="tomcat" roles="manager,admin" username="tomcat"/>

To

<user password="tomcat" roles="manager-script,manager,admin" username="tomcat"/>
  1. make sure that the manager-script role is declared

Add

<role rolename="manager-script"/>

Actually the netbeans online-help incorrectly states:

Username - Specifies the user name that the IDE uses to log into the server's manager application. The user must be associated with the manager role. The first time the IDE started the Tomcat Web Server, such as through the Start/Stop menu action or by executing a web component from the IDE, the IDE adds an admin user with a randomly-generated password to the tomcat-base-path/conf/tomcat-users.xml file. (Right-click the Tomcat Web server instance node in the Services window and select Properties. In the Properties dialog box, the Base Directory property points to the base-dir directory.) The admin user entry in the tomcat-users.xml file looks similar to the following: <user username="idea" password="woiehh" roles="manager"/>

The role should be manager-script, and not manager.

For a more complete tomcat-users.xml file:

<?xml version='1.0' encoding='utf-8'?>
<tomcat-users>
  <role rolename="manager-script"/>
  <role rolename="manager-gui"/>
  <user password="tomcat" roles="manager-script" username="tomcat"/>
  <user password="pass" roles="manager-gui" username="me"/>
</tomcat-users>

There is another nice posting on why am I getting the deployment error?

Print multiple arguments in Python

There are many ways to do this. To fix your current code using %-formatting, you need to pass in a tuple:

  1. Pass it as a tuple:

    print("Total score for %s is %s" % (name, score))
    

A tuple with a single element looks like ('this',).

Here are some other common ways of doing it:

  1. Pass it as a dictionary:

    print("Total score for %(n)s is %(s)s" % {'n': name, 's': score})
    

There's also new-style string formatting, which might be a little easier to read:

  1. Use new-style string formatting:

    print("Total score for {} is {}".format(name, score))
    
  2. Use new-style string formatting with numbers (useful for reordering or printing the same one multiple times):

    print("Total score for {0} is {1}".format(name, score))
    
  3. Use new-style string formatting with explicit names:

    print("Total score for {n} is {s}".format(n=name, s=score))
    
  4. Concatenate strings:

    print("Total score for " + str(name) + " is " + str(score))
    

The clearest two, in my opinion:

  1. Just pass the values as parameters:

    print("Total score for", name, "is", score)
    

    If you don't want spaces to be inserted automatically by print in the above example, change the sep parameter:

    print("Total score for ", name, " is ", score, sep='')
    

    If you're using Python 2, won't be able to use the last two because print isn't a function in Python 2. You can, however, import this behavior from __future__:

    from __future__ import print_function
    
  2. Use the new f-string formatting in Python 3.6:

    print(f'Total score for {name} is {score}')
    

PostgreSQL - max number of parameters in "IN" clause?

According to the source code located here, starting at line 850, PostgreSQL doesn't explicitly limit the number of arguments.

The following is a code comment from line 870:

/*
 * We try to generate a ScalarArrayOpExpr from IN/NOT IN, but this is only
 * possible if the inputs are all scalars (no RowExprs) and there is a
 * suitable array type available.  If not, we fall back to a boolean
 * condition tree with multiple copies of the lefthand expression.
 * Also, any IN-list items that contain Vars are handled as separate
 * boolean conditions, because that gives the planner more scope for
 * optimization on such clauses.
 *
 * First step: transform all the inputs, and detect whether any are
 * RowExprs or contain Vars.
 */

form action with javascript

Absolutely valid.

    <form action="javascript:alert('Hello there, I am being submitted');">
        <button type="submit">
            Let's do it
        </button>
    </form>
    <!-- Tested in Firefox, Chrome, Edge and Safari -->

So for a short answer: yes, this is an option, and a nice one. It says "when submitted, please don't go anywhere, just run this script" - quite to the point.

A minor improvement

To let the event handler know which form we're dealing with, it would seem an obvious way to pass on the sender object:

    <form action="javascript:myFunction(this)">  <!-- should work, but it won't -->

But instead, it will give you undefined. You can't access it because javascript: links live in a separate scope. Therefore I'd suggest the following format, it's only 13 characters more and works like a charm:

    <form action="javascript:;" onsubmit="myFunction(this)">  <!-- now you have it! -->

... now you can access the sender form properly. (You can write a simple "#" as action, it's quite common - but it has a side effect of scrolling to the top when submitting.)

Again, I like this approach because it's effortless and self-explaining. No "return false", no jQuery/domReady, no heavy weapons. It just does what it seems to do. Surely other methods work too, but for me, this is The Way Of The Samurai.

A note on validation

Forms only get submitted if their onsubmit event handler returns something truthy, so you can easily run some preemptive checks:

    <form action="/something.php" onsubmit="return isMyFormValid(this)">

Now isMyFormValid will run first, and if it returns false, server won't even be bothered. Needless to say, you will have to validate on server side too, and that's the more important one. But for quick and convenient early detection this is fine.

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Here's a different approach. Create a custom Exception annotated with @ResponseStatus, like the following one.

@ResponseStatus(code = HttpStatus.NOT_FOUND, reason = "Not Found")
public class NotFoundException extends Exception {

    public NotFoundException() {
    }
}

And throw it when needed.

@RequestMapping(value = "/matches/{matchId}", produces = "application/json")
@ResponseBody
public String match(@PathVariable String matchId) {
    String json = matchService.getMatchJson(matchId);
    if (json == null) {
        throw new NotFoundException();
    }
    return json;
}

Check out the Spring documentation here: http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#mvc-ann-annotated-exceptions.

Best way to read a large file into a byte array in C#?

If you're dealing with files above 2 GB, you'll find that the above methods fail.

It's much easier just to hand the stream off to MD5 and allow that to chunk your file for you:

private byte[] computeFileHash(string filename)
{
    MD5 md5 = MD5.Create();
    using (FileStream fs = new FileStream(filename, FileMode.Open))
    {
        byte[] hash = md5.ComputeHash(fs);
        return hash;
    }
}

In a Git repository, how to properly rename a directory?

lots of correct answers, but as I landed here to copy & paste a folder rename with history, I found that this

git mv <old name> <new name>

will move the old folder (itself) to nest within the new folder

while

git mv <old name>/ <new name>

(note the '/') will move the nested content from the old folder to the new folder

both commands didn't copy along the history of nested files. I eventually renamed each nested folder individually ?

git mv <old name>/<nest-folder> <new name>/<nest-folder>

Recover SVN password from local cache

On Windows, Subversion stores the auth data in %APPDATA%\Subversion\auth. The passwords however are stored encrypted, not in plaintext.

You can decrypt those, but only if you log in to Windows as the same user for which the auth data was saved.

Someone even wrote a tool to decrypt those. Never tried the tool myself so I don't know how well it works, but you might want to try it anyway:

http://www.leapbeyond.com/ric/TSvnPD/

Update: In TortoiseSVN 1.9 and later, you can do it without any additional tools:

Settings Dialog -> Saved Data, then click the "Clear..." button right of the text "Authentication Data". A new dialog pops up, showing all stored authentication data where you can chose which one(s) to clear. Instead of clearing, hold down the Shift and Ctrl button, and then double click on the list. A new column is shown in the dialog which shows the password in clear.

How to add data into ManyToMany field?

There's a whole page of the Django documentation devoted to this, well indexed from the contents page.

As that page states, you need to do:

my_obj.categories.add(fragmentCategory.objects.get(id=1))

or

my_obj.categories.create(name='val1')

Refresh Fragment at reload

   MyFragment fragment = (MyFragment) getSupportFragmentManager().findFragmentByTag(FRAGMENT_TAG);
        getSupportFragmentManager().beginTransaction().detach(fragment).attach(fragment).commit();

this will only work if u use FragmentManager to initialize the fragment. If u have it as a <fragment ... /> in XML, it won't call the onCreateView again. Wasted my 30 minutes to figure this out.

Android : difference between invisible and gone?

when you make it Gone every time of compilation of program the component gets initialized that means you are removing the component from layout and when you make it invisible the component it will take the same space in the layout but every time you dont need to initialize it.

if you set Visibility=Gone then you have to initialize the component..like

eg Button _mButton = new Button(this);

_mButton = (Button)findViewByid(R.id.mButton);

so it will take more time as compared to Visibility = invisible.

How to count the number of observations in R like Stata command count

You can also use the filter function from the dplyr package which returns rows with matching conditions.

> library(dplyr)

> nrow(filter(aaa, sex == 1 & group1 == 2))
[1] 3
> nrow(filter(aaa, sex == 1 & group2 == "A"))
[1] 2

Splitting a dataframe string column into multiple different columns

A very direct way is to just use read.table on your character vector:

> read.table(text = text, sep = ".", colClasses = "character")
   V1 V2  V3  V4
1   F US CLE V13
2   F US CA6 U13
3   F US CA6 U13
4   F US CA6 U13
5   F US CA6 U13
6   F US CA6 U13
7   F US CA6 U13
8   F US CA6 U13
9   F US  DL U13
10  F US  DL U13
11  F US  DL U13
12  F US  DL Z13
13  F US  DL Z13

colClasses needs to be specified, otherwise F gets converted to FALSE (which is something I need to fix in "splitstackshape", otherwise I would have recommended that :) )


Update (> a year later)...

Alternatively, you can use my cSplit function, like this:

cSplit(as.data.table(text), "text", ".")
#     text_1 text_2 text_3 text_4
#  1:      F     US    CLE    V13
#  2:      F     US    CA6    U13
#  3:      F     US    CA6    U13
#  4:      F     US    CA6    U13
#  5:      F     US    CA6    U13
#  6:      F     US    CA6    U13
#  7:      F     US    CA6    U13
#  8:      F     US    CA6    U13
#  9:      F     US     DL    U13
# 10:      F     US     DL    U13
# 11:      F     US     DL    U13
# 12:      F     US     DL    Z13
# 13:      F     US     DL    Z13

Or, separate from "tidyr", like this:

library(dplyr)
library(tidyr)

as.data.frame(text) %>% separate(text, into = paste("V", 1:4, sep = "_"))
#    V_1 V_2 V_3 V_4
# 1    F  US CLE V13
# 2    F  US CA6 U13
# 3    F  US CA6 U13
# 4    F  US CA6 U13
# 5    F  US CA6 U13
# 6    F  US CA6 U13
# 7    F  US CA6 U13
# 8    F  US CA6 U13
# 9    F  US  DL U13
# 10   F  US  DL U13
# 11   F  US  DL U13
# 12   F  US  DL Z13
# 13   F  US  DL Z13

How to split a string content into an array of strings in PowerShell?

[string[]]$recipients = $address.Split('; ',[System.StringSplitOptions]::RemoveEmptyEntries)

How can I create a copy of an Oracle table without copying the data?

Just use a where clause that won't select any rows:

create table xyz_new as select * from xyz where 1=0;

Limitations

The following things will not be copied to the new table:

  • sequences
  • triggers
  • indexes
  • some constraints may not be copied
  • materialized view logs

This also does not handle partitions


Angular + Material - How to refresh a data source (mat-table)

I don't know if the ChangeDetectorRef was required when the question was created, but now this is enough:

import { MatTableDataSource } from '@angular/material/table';

// ...

dataSource = new MatTableDataSource<MyDataType>();

refresh() {
  this.myService.doSomething().subscribe((data: MyDataType[]) => {
    this.dataSource.data = data;
  }
}

Example:
StackBlitz

Python equivalent of D3.js

Plotly supports interactive 2D and 3D graphing. Graphs are rendered with D3.js and can be created with a Python API, matplotlib, ggplot for Python, Seaborn, prettyplotlib, and pandas. You can zoom, pan, toggle traces on and off, and see data on the hover. Plots can be embedded in HTML, apps, dashboards, and IPython Notebooks. Below is a temperature graph showing interactivity. See the gallery of IPython Notebooks tutorials for more examples.

enter image description here



The docs provides examples of supported plot types and code snippets.



enter image description here

Specifically to your question, you can also make interactive plots from NetworkX.

enter image description here

For 3D plotting with Python, you can make 3D scatter, line, and surface plots that are similarly interactive. Plots are rendered with WebGL. For example, see a 3D graph of UK Swap rates.



enter image description here

Disclosure: I'm on the Plotly team.

Regex Last occurrence?

Your negative lookahead solution would e.g. be this:

\\(?:.(?!\\))+$

See it here on Regexr

switch case statement error: case expressions must be constant expression

Solution can be done be this way:

  1. Just assign the value to Integer
  2. Make variable to final

Example:

public static final int cameraRequestCode = 999;

Hope this will help you.

How can I draw vertical text with CSS cross-browser?

Updated this answer with recent information (from CSS Tricks). Kudos to Matt and Douglas for pointing out the filter implementation.

.rotate {
  -webkit-transform: rotate(-90deg);
  -moz-transform: rotate(-90deg);
  -ms-transform: rotate(-90deg);
  -o-transform: rotate(-90deg);
  transform: rotate(-90deg);

  /* also accepts left, right, top, bottom coordinates; not required, but a good idea for styling */
  -webkit-transform-origin: 50% 50%;
  -moz-transform-origin: 50% 50%;
  -ms-transform-origin: 50% 50%;
  -o-transform-origin: 50% 50%;
  transform-origin: 50% 50%;

  /* Should be unset in IE9+ I think. */
  filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}

Old answer:

For FF 3.5 or Safari/Webkit 3.1, check out: -moz-transform (and -webkit-transform). IE has a Matrix filter(v5.5+), but I'm not certain how to use it. Opera has no transformation capabilities yet.

.rot-neg-90 {
  /* rotate -90 deg, not sure if a negative number is supported so I used 270 */
  -moz-transform: rotate(270deg);
  -moz-transform-origin: 50% 50%;
  -webkit-transform: rotate(270deg);
  -webkit-transform-origin: 50% 50%;
  /* IE support too convoluted for the time I've got on my hands... */
}

jQuery equivalent of JavaScript's addEventListener method

Here is an excellent treatment on the Mozilla Development Network (MDN) of this issue for standard JavaScript (if you do not wish to rely on jQuery or understand it better in general):

https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener

Here is a discussion of event flow from a link in the above treatment:

http://www.w3.org/TR/DOM-Level-3-Events/#event-flow

Some key points are:

  • It allows adding more than a single handler for an event
  • It gives you finer-grained control of the phase when the listener gets activated (capturing vs. bubbling)
  • It works on any DOM element, not just HTML elements
  • The value of "this" passed to the event is not the global object (window), but the element from which the element is fired. This is very convenient.
  • Code for legacy IE browsers is simple and included under the heading "Legacy Internet Explorer and attachEvent"
  • You can include parameters if you enclose the handler in an anonymous function

Declaring a python function with an array parameters and passing an array argument to the function call?

What you have is on the right track.

def dosomething( thelist ):
    for element in thelist:
        print element

dosomething( ['1','2','3'] )
alist = ['red','green','blue']
dosomething( alist )  

Produces the output:

1
2
3
red
green
blue

A couple of things to note given your comment above: unlike in C-family languages, you often don't need to bother with tracking the index while iterating over a list, unless the index itself is important. If you really do need the index, though, you can use enumerate(list) to get index,element pairs, rather than doing the x in range(len(thelist)) dance.

Extract hostname name from string

This is not a full answer, but the below code should help you:

function myFunction() {
    var str = "https://www.123rf.com/photo_10965738_lots-oop.html";
    matches = str.split('/');
    return matches[2];
}

I would like some one to create code faster than mine. It help to improve my-self also.

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

Based on Mark's answer above (and Geo's comment), I created a two liner version to remove all ASCII exception cases from a string. Provided for people searching for this answer (as I did).

using System.Text;

// Create encoder with a replacing encoder fallback
var encoder = ASCIIEncoding.GetEncoding("us-ascii", 
    new EncoderReplacementFallback(string.Empty), 
    new DecoderExceptionFallback());

string cleanString = encoder.GetString(encoder.GetBytes(dirtyString)); 

What is the best way to delete a component with CLI

If you looking for some command in CLI, Then ans is NO for now. But you can do manually by deleting the component folder and all the references.

Difference between CLOCK_REALTIME and CLOCK_MONOTONIC?

CLOCK_REALTIME represents the machine's best-guess as to the current wall-clock, time-of-day time. As Ignacio and MarkR say, this means that CLOCK_REALTIME can jump forwards and backwards as the system time-of-day clock is changed, including by NTP.

CLOCK_MONOTONIC represents the absolute elapsed wall-clock time since some arbitrary, fixed point in the past. It isn't affected by changes in the system time-of-day clock.

If you want to compute the elapsed time between two events observed on the one machine without an intervening reboot, CLOCK_MONOTONIC is the best option.

Note that on Linux, CLOCK_MONOTONIC does not measure time spent in suspend, although by the POSIX definition it should. You can use the Linux-specific CLOCK_BOOTTIME for a monotonic clock that keeps running during suspend.

Change UITextField and UITextView Cursor / Caret Color

yourTextField.tintColor = [UIColor whiteColor];

It works if you set it in code, 'cos somehow color trigger doesn't do it in the Interface Builder (Xcode 6.1.1). It suited well without a need to change any appearance proxy.

websocket closing connection automatically

You can actually set the timeout interval at the Jetty server side configuration using the WebSocketServletFactory instance. For example:

WebSocketHandler wsHandler = new WebSocketHandler() {
    @Override
    public void configure(WebSocketServletFactory factory) {
        factory.getPolicy().setIdleTimeout(1500);
        factory.register(MyWebSocketAdapter.class);
        ...
    }
}

How to create multiple class objects with a loop in python?

Using a dictionary for unique names without a name list:

class MyClass:
    def __init__(self, name):
        self.name = name
        self.pretty_print_name()

    def pretty_print_name(self):
    print("This object's name is {}.".format(self.name))

my_objects = {}
for i in range(1,11):
    name = 'obj_{}'.format(i)
    my_objects[name] = my_objects.get(name, MyClass(name = name))

Output:

"This object's name is obj_1."
"This object's name is obj_2."
"This object's name is obj_3."
"This object's name is obj_4."
"This object's name is obj_5."
"This object's name is obj_6."
"This object's name is obj_7."
"This object's name is obj_8."
"This object's name is obj_9."
"This object's name is obj_10."

Android Studio : unmappable character for encoding UTF-8

I have the problem with encoding in javadoc generated by intellij idea. The solution is to add

-encoding UTF-8 -docencoding utf-8 -charset utf-8

into command line arguments!

UPDATE: more information about compilation Javadoc in Intellij IDEA see in my post

Lock screen orientation (Android)

I had a similar problem.

When I entered

<activity android:name="MyActivity" android:screenOrientation="landscape"></activity>

In the manifest file this caused that activity to display in landscape. However when I returned to previous activities they displayed in lanscape even though they were set to portrait. However by adding

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

immediately after the OnCreate section of the target activity resolved the problem. So I now use both methods.

Java error: Implicit super constructor is undefined for default constructor

Sorry for necroposting but faced this problem just today. For everybody also facing with this problem - one of he possible reasons - you don't call super at the first line of method. Second, third and other lines fire this error. Call of super should be very first call in your method. In this case everything is well.

Calling jQuery method from onClick attribute in HTML

I know this was answered long ago, but if you don't mind creating the button dynamically, this works using only the jQuery framework:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $button = $('<input id="1" type="button" value="ahaha" />');_x000D_
  $('body').append($button);_x000D_
  $button.click(function() {_x000D_
    console.log("Id clicked: " + this.id ); // or $(this) or $button_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<p>And here is my HTML page:</p>_x000D_
_x000D_
<div class="Title">Welcome!</div>
_x000D_
_x000D_
_x000D_

PowerShell try/catch/finally

That is very odd.

I went through ItemNotFoundException's base classes and tested the following multiple catches to see what would catch it:

try {
  remove-item C:\nonexistent\file.txt -erroraction stop
}
catch [System.Management.Automation.ItemNotFoundException] {
  write-host 'ItemNotFound'
}
catch [System.Management.Automation.SessionStateException] {
  write-host 'SessionState'
}
catch [System.Management.Automation.RuntimeException] {
  write-host 'RuntimeException'
}
catch [System.SystemException] {
  write-host 'SystemException'
}
catch [System.Exception] {
  write-host 'Exception'
}
catch {
  write-host 'well, darn'
}

As it turns out, the output was 'RuntimeException'. I also tried it with a different exception CommandNotFoundException:

try {
  do-nonexistent-command
}
catch [System.Management.Automation.CommandNotFoundException] {
  write-host 'CommandNotFoundException'
}
catch {
  write-host 'well, darn'
}

That output 'CommandNotFoundException' correctly.

I vaguely remember reading elsewhere (though I couldn't find it again) of problems with this. In such cases where exception filtering didn't work correctly, they would catch the closest Type they could and then use a switch. The following just catches Exception instead of RuntimeException, but is the switch equivalent of my first example that checks all base types of ItemNotFoundException:

try {
  Remove-Item C:\nonexistent\file.txt -ErrorAction Stop
}
catch [System.Exception] {
  switch($_.Exception.GetType().FullName) {
    'System.Management.Automation.ItemNotFoundException' {
      write-host 'ItemNotFound'
    }
    'System.Management.Automation.SessionStateException' {
      write-host 'SessionState'
    }
    'System.Management.Automation.RuntimeException' {
      write-host 'RuntimeException'
    }
    'System.SystemException' {
      write-host 'SystemException'
    }
    'System.Exception' {
      write-host 'Exception'
    }
    default {'well, darn'}
  }
}

This writes 'ItemNotFound', as it should.

Escaping regex string

Unfortunately, re.escape() is not suited for the replacement string:

>>> re.sub('a', re.escape('_'), 'aa')
'\\_\\_'

A solution is to put the replacement in a lambda:

>>> re.sub('a', lambda _: '_', 'aa')
'__'

because the return value of the lambda is treated by re.sub() as a literal string.

How do you determine what technology a website is built on?

Some people might even deliberately obscure the technology they use. After all, it wouldn't take me long to tweak apache so that ".asp" actually ran perl scripts and put "powered by Microsoft IIS" into my footer despite the fact I used MySQL.

That way you'd spend all your time trying to hack my site using vulnerabilities it doesn't actually have.

SQL Stored Procedure set variables using SELECT

select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
    from table1
    where IsCurrent = 1

Why would a JavaScript variable start with a dollar sign?

As others have mentioned the dollar sign is intended to be used by mechanically generated code. However, that convention has been broken by some wildly popular JavaScript libraries. JQuery, Prototype and MS AJAX (AKA Atlas) all use this character in their identifiers (or as an entire identifier).

In short you can use the $ whenever you want. (The interpreter won't complain.) The question is when do you want to use it?

I personally do not use it, but I think its use is valid. I think MS AJAX uses it to signify that a function is an alias for some more verbose call.

For example:

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

That seems like a reasonable convention.

Find unique rows in numpy.array

Beyond @Jaime excellent answer, another way to collapse a row is to uses a.strides[0] (assuming a is C-contiguous) which is equal to a.dtype.itemsize*a.shape[0]. Furthermore void(n) is a shortcut for dtype((void,n)). we arrive finally to this shortest version :

a[unique(a.view(void(a.strides[0])),1)[1]]

For

[[0 1 1 1 0 0]
 [1 1 1 0 0 0]
 [1 1 1 1 1 0]]

Use custom build output folder when using create-react-app

I had the scenario like want to rename the folder and change the build output location, and used below code in the package.json with the latest version

"build": "react-scripts build && mv build ../my_bundles"

How to extract year and month from date in PostgreSQL without using to_char() function?

You Can use EXTRACT function pgSQL

EX- date = 1981-05-31
EXTRACT(MONTH FROM date)
it will Give 05

For more details PGSQL Date-Time

How to prevent rm from reporting that a file was not found?

I had same issue for cshell. The only solution I had was to create a dummy file that matched pattern before "rm" in my script.

How to iterate through range of Dates in Java?

We can migrate the logic to various methods foe Java 7, Java 8 and Java 9:

public static List<Date> getDatesRangeJava7(Date startDate, Date endDate) {
    List<Date> datesInRange = new ArrayList<>();
    Calendar startCalendar = new GregorianCalendar();
    startCalendar.setTime(startDate);
    Calendar endCalendar = new GregorianCalendar();
    endCalendar.setTime(endDate);
    while (startCalendar.before(endCalendar)) {
        Date result = startCalendar.getTime();
        datesInRange.add(result);
        startCalendar.add(Calendar.DATE, 1);
    }
    return datesInRange;
}

public static List<LocalDate> getDatesRangeJava8(LocalDate startDate, LocalDate endDate) {
    int numOfDays = (int) ChronoUnit.DAYS.between(startDate, endDate);
    return IntStream.range(0, numOfDays)
            .mapToObj(startDate::plusDays)
            .collect(Collectors.toList());
}

public static List<LocalDate> getDatesRangeJava9(LocalDate startDate, LocalDate endDate) {
    return startDate.datesUntil(endDate).collect(Collectors.toList());
}

Then we can invoke these methods as:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date startDate = formatter.parse("2010-12-20");
Date endDate = formatter.parse("2010-12-26");
List<Date> dateRangeList = getDatesRangeJava7(startDate, endDate);
System.out.println(dateRangeList);

LocalDate startLocalDate = startDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
LocalDate endLocalDate = endDate.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
List<LocalDate> dateRangeList8 = getDatesRangeJava8(startLocalDate, endLocalDate);
System.out.println(dateRangeList8);
List<LocalDate> dateRangeList9 = getDatesRangeJava8(startLocalDate, endLocalDate);
System.out.println(dateRangeList9);

The output would be:

[Mon Dec 20 00:00:00 IST 2010, Tue Dec 21 00:00:00 IST 2010, Wed Dec 22 00:00:00 IST 2010, Thu Dec 23 00:00:00 IST 2010, Fri Dec 24 00:00:00 IST 2010, Sat Dec 25 00:00:00 IST 2010]

[2010-12-20, 2010-12-21, 2010-12-22, 2010-12-23, 2010-12-24, 2010-12-25]

[2010-12-20, 2010-12-21, 2010-12-22, 2010-12-23, 2010-12-24, 2010-12-25]

How do I debug error ECONNRESET in Node.js?

Yes, your serving of the policy file can definitely cause the crash.

To repeat, just add a delay to your code:

net.createServer( function(socket) 
{
    for (i=0; i<1000000000; i++) ;
    socket.write("<?xml version=\"1.0\"?>\n");
…

… and use telnet to connect to the port. If you disconnect telnet before the delay has expired, you'll get a crash (uncaught exception) when socket.write throws an error.

To avoid the crash here, just add an error handler before reading/writing the socket:

net.createServer(function(socket)
{
    for(i=0; i<1000000000; i++);
    socket.on('error', function(error) { console.error("error", error); });
    socket.write("<?xml version=\"1.0\"?>\n");
}

When you try the above disconnect, you'll just get a log message instead of a crash.

And when you're done, remember to remove the delay.

What is a user agent stylesheet?

I had the same problem as one of my <div>'s had the margin set by the browser. It was quite annoying but then I figured out as most of the people said, it's a markup error.

I went back and checked my <head> section and my CSS link was like below:

<link rel="stylesheet" href="ex.css">

I included type in it and made it like below:

<link rel="stylesheet" type="text/css" href="ex.css">

My problem was solved.

PHP - find entry by object property from an array of objects

class ArrayUtils
{
    public static function objArraySearch($array, $index, $value)
    {
        foreach($array as $arrayInf) {
            if($arrayInf->{$index} == $value) {
                return $arrayInf;
            }
        }
        return null;
    }
}

Using it the way you wanted would be something like:

ArrayUtils::objArraySearch($array,'ID',$v);

Where do I put image files, css, js, etc. in Codeigniter?

I use the following folder structure:

application 
system 
static
    admin
        js
        css
        images
    public
        js
        css
        images
    uploads
        original
        thumbs

How to set bot's status

    client.user.setStatus('dnd', 'Made by KwinkyWolf') 

And change 'dnd' to whatever status you want it to have. And then the next field 'Made by KwinkyWolf' is where you change the game. Hope this helped :)

List of status':

  • online
  • idle
  • dnd
  • invisible

Not sure if they're still the same, or if there's more but hope that helped too :)

How to remove item from a python list in a loop?

You can't remove items from a list while iterating over it. It's much easier to build a new list based on the old one:

y = [s for s in x if len(s) == 2]

Drawing a simple line graph in Java

Override the paintComponent method of your panel so you can custom draw. Like this:

@Override
public void paintComponent(Graphics g) {
    Graphics2D gr = (Graphics2D) g; //this is if you want to use Graphics2D
    //now do the drawing here
    ...
}

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

You can access the Axes instance (ax) with plt.gca(). In this case, you can use

plt.gca().legend()

You can do this either by using the label= keyword in each of your plt.plot() calls or by assigning your labels as a tuple or list within legend, as in this working example:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()

pltGcaLegend

However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax with

ax = plt.gca()

and then calling ax instead of plt.gca().

How to enumerate an enum with String type?

Swift 5 Solution:

enum Suit: String, CaseIterable {
    case spades = "?"
    case hearts = "?"
    case diamonds = "?"
    case clubs = "?"
}

// access cases like this:

for suitKey in Suit.allCases {
    print(suitKey)
}

Vertical dividers on horizontal UL menu

This can also be done via CSS:pseudo-classes. Support isn't quite as wide and the answer above gives you the same result, but it's pure CSS-y =)

.ULHMenu li { border-left: solid 2px black; }
.ULHMenu li:first-child { border: 0px; }

OR:

.ULHMenu li { border-right: solid 2px black; }
.ULHMenu li:last-child { border: 0px; }

See: http://www.quirksmode.org/css/firstchild.html
Or: http://www.w3schools.com/cssref/sel_firstchild.asp

How can I check if a date is the same day as datetime.today()?

You can set the hours, minutes, seconds and microseconds to whatever you like

datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)

but trutheality's answer is probably best when they are all to be zero and you can just compare the .date()s of the times

Maybe it is faster though if you have to compare hundreds of datetimes because you only need to do the replace() once vs hundreds of calls to date()

CSS3 background image transition

The solution (that I found by myself) is a ninja trick, I can offer you two ways:

first you need to make a "container" for the <img>, it will contain normal and hover states at the same time:

<div class="images-container">
    <img src="http://lorempixel.com/400/200/animals/9/">
    <img src="http://lorempixel.com/400/200/animals/10/">
</div>

Basically, you need to hide "normal" state and show their "hover" when you hover it

and that's it, I hope somebody find it useful.

Reset IntelliJ UI to Default

The existing answers are outdated. This is now doable from the menu:

Window -> Restore Default Layout (shift+f12)

Make sure nothing is currently running, as the Run/Debug window layout will not be reset otherwise.

Creating a REST API using PHP

Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.

Your best bet is to use a framework that already has this functionality ready and tested for you.

Some suggestions are:

Phalcon - REST API building - Easy to use all in one framework with huge performance

Apigility - A one size fits all API handling framework by Zend Technologies

Laravel API Building Tutorial

and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.

When to use async false and async true in ajax function in jquery

It is best practice to go asynchronous if you can do several things in parallel (no inter-dependencies). If you need it to complete to continue loading the next thing you could use synchronous, but note that this option is deprecated to avoid abuse of sync:

jQuery.ajax() method's async option deprecated, what now?

Synchronously waiting for an async operation, and why does Wait() freeze the program here

Calling async code from synchronous code can be quite tricky.

I explain the full reasons for this deadlock on my blog. In short, there's a "context" that is saved by default at the beginning of each await and used to resume the method.

So if this is called in an UI context, when the await completes, the async method tries to re-enter that context to continue executing. Unfortunately, code using Wait (or Result) will block a thread in that context, so the async method cannot complete.

The guidelines to avoid this are:

  1. Use ConfigureAwait(continueOnCapturedContext: false) as much as possible. This enables your async methods to continue executing without having to re-enter the context.
  2. Use async all the way. Use await instead of Result or Wait.

If your method is naturally asynchronous, then you (probably) shouldn't expose a synchronous wrapper.

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

OnCreate:

//Add comment fragment
            container = FindViewById<FrameLayout>(Resource.Id.frmAttachPicture);
            mPictureFragment = new fmtAttachPicture();

            var trans = SupportFragmentManager.BeginTransaction();
            trans.Add(container.Id, mPictureFragment, "fmtPicture");
            trans.Show(mPictureFragment); trans.Commit();

This is how I hide the fragment in click event 1

//Close fragment
    var trans = SupportFragmentManager.BeginTransaction();
    trans.Hide(mPictureFragment);
    trans.AddToBackStack(null);
    trans.Commit();

Then Shows it back int event 2

var trans = SupportFragmentManager.BeginTransaction();
            trans.Show(mPictureFragment); trans.Commit();

How to extract text from an existing docx file using python-docx

You can use python-docx2txt which is adapted from python-docx but can also extract text from links, headers and footers. It can also extract images.

Chrome dev tools fails to show response even the content returned has header Content-Type:text/html; charset=UTF-8

For me, the issue happens when the returned JSON file is too large.

If you just want to see the response, you can get it with the help of Postman. See the steps below:

  1. Copy the request with all information(including URL, header, token, etc) from chrome debugger through Chrome Developer Tools->Network Tab->find the request->right click on it->Copy->Copy as cURL.
  2. Open postman, import->Rawtext, paste the content. Postman will recreate the same request. Then run the request you should see the JSON response. [Import cURL in postmain][1]: https://i.stack.imgur.com/dL9Qo.png

If you want to reduce the size of the API response, maybe you can return fewer fields in the response. For mongoose, you can easily do this by providing a field name list when calling the find() method. For exmaple, convert the method from:

const users = await User.find().lean();

To:

const users = await User.find({}, '_id username email role timecreated').lean();

In my case, there is field called description, which is a large string. After removing it from the field list, the response size is reduced from 6.6 MB to 404 KB.

How can I scan barcodes on iOS?

with Swift 5 it's Simple and Super fast!!

You just need to add cocoa pods "BarcodeScanner" here is the full code

source 'https://github.com/CocoaPods/Specs.git' 
platform :ios, '12.0' 
target 'Simple BarcodeScanner' 
do   
pod 'BarcodeScanner' 
end

Make sure add Camera permission in your .plist file

<key>NSCameraUsageDescription</key>
<string>Camera usage description</string>

And add Scanner and handle result in your ViewController this way

import UIKit
import BarcodeScanner

class ViewController: UIViewController, BarcodeScannerCodeDelegate, BarcodeScannerErrorDelegate, BarcodeScannerDismissalDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let viewController = BarcodeScannerViewController()
        viewController.codeDelegate = self
        viewController.errorDelegate = self
        viewController.dismissalDelegate = self

        present(viewController, animated: true, completion: nil)
    }

    func scanner(_ controller: BarcodeScannerViewController, didCaptureCode code: String, type: String) {
        print("Product's Bar code is :", code)
        controller.dismiss(animated: true, completion: nil)
    }

    func scanner(_ controller: BarcodeScannerViewController, didReceiveError error: Error) {
        print(error)
    }

    func scannerDidDismiss(_ controller: BarcodeScannerViewController) {
        controller.dismiss(animated: true, completion: nil)
    }
}

Still and any question or challenges, please check sample application here with full source code

python: [Errno 10054] An existing connection was forcibly closed by the remote host

I know this is a very old question but it may be that you need to set the request headers. This solved it for me.

For example 'user-agent', 'accept' etc. here is an example with user-agent:

url = 'your-url-here'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.75 Safari/537.36'}
r = requests.get(url, headers=headers)

String to object in JS

This is universal code , no matter how your input is long but in same schema if there is : separator :)

var string = "firstName:name1, lastName:last1"; 
var pass = string.replace(',',':');
var arr = pass.split(':');
var empty = {};
arr.forEach(function(el,i){
  var b = i + 1, c = b/2, e = c.toString();
     if(e.indexOf('.') != -1 ) {
     empty[el] = arr[i+1];
  } 
}); 
  console.log(empty)

CSS: center element within a <div> element

Assign text-align: center; to the parent and display: inline-block; to the div.

How to solve javax.net.ssl.SSLHandshakeException Error?

Whenever we are trying to connect to URL,

if server at the other site is running on https protocol and is mandating that we should communicate via information provided in certificate then we have following option:

1) ask for the certificate(download the certificate), import this certificate in trustore. Default trustore java uses can be found in \Java\jdk1.6.0_29\jre\lib\security\cacerts, then if we retry to connect to the URL connection would be accepted.

2) In normal business cases, we might be connecting to internal URLS in organizations and we know that they are correct. In such cases, you trust that it is the correct URL, In such cases above, code can be used which will not mandate to store the certificate to connect to particular URL.

for the point no 2 we have to follow below steps :

1) write below method which sets HostnameVerifier for HttpsURLConnection which returns true for all cases meaning we are trusting the trustStore.

  // trusting all certificate 
 public void doTrustToCertificates() throws Exception {
        Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
        TrustManager[] trustAllCerts = new TrustManager[]{
                new X509TrustManager() {
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }

                    public void checkServerTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                        return;
                    }

                    public void checkClientTrusted(X509Certificate[] certs, String authType) throws CertificateException {
                        return;
                    }
                }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                if (!urlHostName.equalsIgnoreCase(session.getPeerHost())) {
                    System.out.println("Warning: URL host '" + urlHostName + "' is different to SSLSession host '" + session.getPeerHost() + "'.");
                }
                return true;
            }
        };
        HttpsURLConnection.setDefaultHostnameVerifier(hv);
    }

2) write below method, which calls doTrustToCertificates before trying to connect to URL

    // connecting to URL
    public void connectToUrl(){
     doTrustToCertificates();//  
     URL url = new URL("https://www.example.com");
     HttpURLConnection conn = (HttpURLConnection)url.openConnection(); 
     System.out.println("ResponseCode ="+conn.getResponseCode());
   }

This call will return response code = 200 means connection is successful.

For more detail and sample example you can refer to URL.

What is an undefined reference/unresolved external symbol error and how do I fix it?

Since people seem to be directed to this question when it comes to linker errors I am going to add this here.

One possible reason for linker errors with GCC 5.2.0 is that a new libstdc++ library ABI is now chosen by default.

If you get linker errors about undefined references to symbols that involve types in the std::__cxx11 namespace or the tag [abi:cxx11] then it probably indicates that you are trying to link together object files that were compiled with different values for the _GLIBCXX_USE_CXX11_ABI macro. This commonly happens when linking to a third-party library that was compiled with an older version of GCC. If the third-party library cannot be rebuilt with the new ABI then you will need to recompile your code with the old ABI.

So if you suddenly get linker errors when switching to a GCC after 5.1.0 this would be a thing to check out.

SQLite - getting number of rows in a database

In SQL, NULL = NULL is false, you usually have to use IS NULL:

SELECT CASE WHEN MAX(id) IS NULL THEN 0 ELSE (MAX(id) + 1) END FROM words

But, if you want the number of rows, you should just use count(id) since your solution will give 10 if your rows are (0,1,3,5,9) where it should give 5.

If you can guarantee you will always ids from 0 to N, max(id)+1 may be faster depending on the index implementation (it may be faster to traverse the right side of a balanced tree rather than traversing the whole tree, counting.

But that's very implementation-specific and I would advise against relying on it, not least because it locks your performance to a specific DBMS.

How to print float to n decimal places including trailing 0s?

The cleanest way in modern Python >=3.6, is to use an f-string with string formatting:

>>> var = 1.6
>>> f"{var:.15f}"
'1.600000000000000'

Counter inside xsl:for-each loop

Try:

<xsl:value-of select="count(preceding-sibling::*) + 1" />

Edit - had a brain freeze there, position() is more straightforward!

Ruby: Merging variables in to a string

You can use it with your local variables, like this:

@animal = "Dog"
@action = "licks"
@second_animal = "Bird"

"The #{@animal} #{@action} the #{@second_animal}"

the output would be: "The Dog licks the Bird"

How do I insert an image in an activity with android studio?

When you have image into yours drawable gallery then you just need to pick the option of image view pick and drag into app activity you want to show and select the required image.

Sending websocket ping/pong frame from browser

There is no Javascript API to send ping frames or receive pong frames. This is either supported by your browser, or not. There is also no API to enable, configure or detect whether the browser supports and is using ping/pong frames. There was discussion about creating a Javascript ping/pong API for this. There is a possibility that pings may be configurable/detectable in the future, but it is unlikely that Javascript will be able to directly send and receive ping/pong frames.

However, if you control both the client and server code, then you can easily add ping/pong support at a higher level. You will need some sort of message type header/metadata in your message if you don't have that already, but that's pretty simple. Unless you are planning on sending pings hundreds of times per second or have thousands of simultaneous clients, the overhead is going to be pretty minimal to do it yourself.

How can I pass some data from one controller to another peer controller

In one controller, you can do:

$rootScope.$broadcast('eventName', data);

and listen to the event in another:

$scope.$on('eventName', function (event, data) {...});

How to hide Bootstrap modal with javascript?

I had better luck making the call after the "shown" callback occurred:

$('#myModal').on('shown', function () {
      $('#myModal').modal('hide');
})

This ensured the modal was done loading before the hide() call was made.

How to fix missing dependency warning when using useEffect React Hook?

This article is a good primer on fetching data with hooks: https://www.robinwieruch.de/react-hooks-fetch-data/

Essentially, include the fetch function definition inside useEffect:

useEffect(() => {
  const fetchBusinesses = () => {
    return fetch("theUrl"...
      // ...your fetch implementation
    );
  }

  fetchBusinesses();
}, []);

What is the best way to ensure only one instance of a Bash script is running?

If the script is the same across all users, you can use a lockfile approach. If you acquire the lock, proceed else show a message and exit.

As an example:

[Terminal #1] $ lockfile -r 0 /tmp/the.lock
[Terminal #1] $ 

[Terminal #2] $ lockfile -r 0 /tmp/the.lock
[Terminal #2] lockfile: Sorry, giving up on "/tmp/the.lock"

[Terminal #1] $ rm -f /tmp/the.lock
[Terminal #1] $ 

[Terminal #2] $ lockfile -r 0 /tmp/the.lock
[Terminal #2] $ 

After /tmp/the.lock has been acquired your script will be the only one with access to execution. When you are done, just remove the lock. In script form this might look like:

#!/bin/bash

lockfile -r 0 /tmp/the.lock || exit 1

# Do stuff here

rm -f /tmp/the.lock

How to add one column into existing SQL Table

Its work perfectly

ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL;

But if you want more precise in table then you can try AFTER.

ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL AFTER `column_name`;

It will add LastUpdate column after specified column name (column_name).

Compare two files report difference in python

You can add an conditional statement. If your array goes beyond index, then break and print the rest of the file.

jQuery .ready in a dynamically inserted iframe

I answered a similar question (see Javascript callback when IFRAME is finished loading?). You can obtain control over the iframe load event with the following code:

function callIframe(url, callback) {
    $(document.body).append('<IFRAME id="myId" ...>');
    $('iframe#myId').attr('src', url);

    $('iframe#myId').load(function() {
        callback(this);
    });
}

In dealing with iframes I found good enough to use load event instead of document ready event.

Detecting the onload event of a window opened with window.open

First of all, when your first initial window is loaded, it is cached. Therefore, when creating a new window from the first window, the contents of the new window are not loaded from the server, but are loaded from the cache. Consequently, no onload event occurs when you create the new window.

However, in this case, an onpageshow event occurs. It always occurs after the onload event and even when the page is loaded from cache. Plus, it now supported by all major browsers.

 window.popup = window.open($(this).attr('href'), 'Ad', 'left=20,top=20,width=500,height=500,toolbar=1,resizable=0');
 $(window.popup).onpageshow = function() {
     alert("Popup has loaded a page");
 };

The w3school website elaborates more on this:

The onpageshow event is similar to the onload event, except that it occurs after the onload event when the page first loads. Also, the onpageshow event occurs every time the page is loaded, whereas the onload event does not occur when the page is loaded from the cache.

What's the difference between RANK() and DENSE_RANK() functions in oracle?

select empno
       ,salary
       ,row_number() over(order by salary desc) as Serial
       ,Rank() over(order by salary desc) as rank
       ,dense_rank() over(order by salary desc) as denseRank
from emp ;

Row_number() -> Used for generating serial number

Dense_rank() will give continuous rank but rank will skip rank in case of clash of rank.

How to export table data in MySql Workbench to csv?

U can use mysql dump or query to export data to csv file

SELECT *
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM products

Postgres: INSERT if does not exist already

INSERT .. WHERE NOT EXISTS is good approach. And race conditions can be avoided by transaction "envelope":

BEGIN;
LOCK TABLE hundred IN SHARE ROW EXCLUSIVE MODE;
INSERT ... ;
COMMIT;

Do not want scientific notation on plot axis

You can use the axis() command for that, eg :

x <- 1:100000
y <- 1:100000
marks <- c(0,20000,40000,60000,80000,100000)
plot(x,y,log="x",yaxt="n",type="l")
axis(2,at=marks,labels=marks)

gives :

enter image description here

EDIT : if you want to have all of them in the same format, you can use the solution of @Richie to get them :

x <- 1:100000
y <- 1:100000
format(y,scientific=FALSE)
plot(x,y,log="x",yaxt="n",type="l")
axis(2,at=marks,labels=format(marks,scientific=FALSE))

How to know if docker is already logged in to a docker registry server

Just checked, today it looks like this:

$ docker login
Authenticating with existing credentials...
Login Succeeded

NOTE: this is on a macOS with the latest version of Docker CE, docker-credential-helper - both installed with homebrew.

Which HTML Parser is the best?

The best I've seen so far is HtmlCleaner:

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

With HtmlCleaner you can locate any element using XPath.

For other html parsers see this SO question.

How can I use a JavaScript variable as a PHP variable?

You can take all values like this:

$abc = "<script>document.getElementByID('yourid').value</script>";

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

It boils down to:

Class<? extends Serializable> c1 = null;
Class<java.util.Date> d1 = null;
c1 = d1; // compiles
d1 = c1; // wont compile - would require cast to Date

You can see the Class reference c1 could contain a Long instance (since the underlying object at a given time could have been List<Long>), but obviously cannot be cast to a Date since there is no guarantee that the "unknown" class was Date. It is not typsesafe, so the compiler disallows it.

However, if we introduce some other object, say List (in your example this object is Matcher), then the following becomes true:

List<Class<? extends Serializable>> l1 = null;
List<Class<java.util.Date>> l2 = null;
l1 = l2; // wont compile
l2 = l1; // wont compile

...However, if the type of the List becomes ? extends T instead of T....

List<? extends Class<? extends Serializable>> l1 = null;
List<? extends Class<java.util.Date>> l2 = null;
l1 = l2; // compiles
l2 = l1; // won't compile

I think by changing Matcher<T> to Matcher<? extends T>, you are basically introducing the scenario similar to assigning l1 = l2;

It's still very confusing having nested wildcards, but hopefully that makes sense as to why it helps to understand generics by looking at how you can assign generic references to each other. It's also further confusing since the compiler is inferring the type of T when you make the function call (you are not explicitly telling it was T is).

UITableView with fixed section headers

The headers only remain fixed when the UITableViewStyle property of the table is set to UITableViewStylePlain. If you have it set to UITableViewStyleGrouped, the headers will scroll up with the cells.

Mac SQLite editor

MesaSQLite is the best I've found so far.

www.desertsandsoftware.com

Looks very promising indeed.

Override element.style using CSS

element.style comes from the markup.

<li style="display: none;">

Just remove the style attribute from the HTML.

How to print a certain line of a file with PowerShell?

You can use the -TotalCount parameter of the Get-Content cmdlet to read the first n lines, then use Select-Object to return only the nth line:

Get-Content file.txt -TotalCount 9 | Select-Object -Last 1;

Per the comment from @C.B. this should improve performance by only reading up to and including the nth line, rather than the entire file. Note that you can use the aliases -First or -Head in place of -TotalCount.

powershell is missing the terminator: "

This error will also occur if you call .ps1 file from a .bat file and file path has spaces.

The fix is to make sure there are no spaces in the path of .ps1 file.

How do I convert csv file to rdd

Another alternative is to use the mapPartitionsWithIndex method as you'll get the partition index number and a list of all lines within that partition. Partition 0 and line 0 will be be the header

val rows = sc.textFile(path)
  .mapPartitionsWithIndex({ (index: Int, rows: Iterator[String]) => 
    val results = new ArrayBuffer[(String, Int)]

    var first = true
    while (rows.hasNext) {
      // check for first line
      if (index == 0 && first) {
        first = false
        rows.next // skip the first row
      } else {
        results += rows.next
      }
    }

    results.toIterator
}, true)

rows.flatMap { row => row.split(",") }

Convert integer to class Date

Another way to get the same result:

date <- strptime(v,format="%Y%m%d")

PackagesNotFoundError: The following packages are not available from current channels:

Have you tried:

pip install <package>

or

conda install -c conda-forge <package>

UIImageView aspect fit and center

[your_imageview setContentMode:UIViewContentModeCenter];

ImportError: No module named pandas

As of Dec 2020, I had the same issue when installing python v 3.8.6 via pyenv. So, I started by:

  1. Installing pyenv via homebrew brew install pyenv
  2. Install xz compiling package via brew install xz
  3. pyenv install 3.8.6 pick the required version
  4. pyenv global 3.8.6 make this version as global
  5. python -m pip install -U pip to upgrade pip
  6. pip install virtualenv

After that, I initialized my new env, installed pandas via pip command, and everything worked again. The panda's version installed is 1.1.5 within my working project directory. I hope that might help!

Note: If you have installed python before xz, make sure to uninstall it first, otherwise the error might persist.

Search for a string in Enum and return the Enum

You can use Enum.Parse to get an enum value from the name. You can iterate over all values with Enum.GetNames, and you can just cast an int to an enum to get the enum value from the int value.

Like this, for example:

public MyColours GetColours(string colour)
{
    foreach (MyColours mc in Enum.GetNames(typeof(MyColours))) {
        if (mc.ToString().Contains(colour)) {
            return mc;
        }
    }
    return MyColours.Red; // Default value
}

or:

public MyColours GetColours(string colour)
{
    return (MyColours)Enum.Parse(typeof(MyColours), colour, true); // true = ignoreCase
}

The latter will throw an ArgumentException if the value is not found, you may want to catch it inside the function and return the default value.

How to add an image to the "drawable" folder in Android Studio?

Do it through the way Android Studio provided to you

Right click on the res folder and add your image as Image Assets in this way. Android studio will automatically generate image assets with different resolutions.

You can directly create the folder and drag image inside but you won't have the different sized icons if you do that.

enter image description here

convert date string to mysql datetime field

Use DateTime::createFromFormat like this :

$date = DateTime::createFromFormat('m/d/Y H:i:s', $input_string.' 00:00:00');
$mysql_date_string = $date->format('Y-m-d H:i:s');

You can adapt this to any input format, whereas strtotime() will assume you're using the US date format if you use /, even if you're not.

The added 00:00:00 is because createFromFormat will use the current date to fill missing data, ie : it will take the current hour:min:sec and not 00:00:00 if you don't precise it.

How can I get the average (mean) of selected columns

Here are some examples:

> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

weighted mean

> z$y <- rev(z$y)
> z
  w x  y mean
1 5 1 NA    1
2 6 2  3    2
3 7 3  2    3
4 8 4  1    4
> 
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
  w x  y mean    wmean
1 5 1 NA    1 1.000000
2 6 2  3    2 2.666667
3 7 3  2    3 2.333333
4 8 4  1    4 2.000000

*.h or *.hpp for your class definitions

Fortunately, it is simple.

You should use the .hpp extension if you're working with C++ and you should use .h for C or mixing C and C++.

How to pass value from <option><select> to form action

You don't have to use jQuery or Javascript.

Use the name tag of the select and let the form do it's job.

<select name="agent_id" id="agent_id">

jQuery AJAX Character Encoding

I have faced same problem and tried several ways. And i found the solution. If you set request header for "Accept" like below;

$.ajax({
        data: parameters,
        type: "POST",
        url: ajax_url,
        dataType: 'json',
        beforeSend : function(xhr) {
            xhr.setRequestHeader('Accept', "text/html; charset=utf-8");
        },
        success: callback
});

you will see that all the characters seems correct

What is __pycache__?

The python interpreter compiles the *.py script file and saves the results of the compilation to the __pycache__ directory.

When the project is executed again, if the interpreter identifies that the *.py script has not been modified, it skips the compile step and runs the previously generated *.pyc file stored in the __pycache__ folder.

When the project is complex, you can make the preparation time before the project is run shorter. If the program is too small, you can ignore that by using python -B abc.py with the B option.

How to set a maximum execution time for a mysql query?

You can find the answer on this other S.O. question:

MySQL - can I limit the maximum time allowed for a query to run?

a cron job that runs every second on your database server, connecting and doing something like this:

  • SHOW PROCESSLIST
  • Find all connections with a query time larger than your maximum desired time
  • Run KILL [process id] for each of those processes

How do I install a NuGet package .nupkg file locally?

On Linux, with NuGet CLI, the commands are similar. To install my.nupkg, run

nuget add -Source some/directory my.nupkg

Then run dotnet restore from that directory

dotnet restore --source some/directory Project.sln

or add that directory as a NuGet source

nuget sources Add -Name MySource -Source some/directory

and then tell msbuild to use that directory with /p:RestoreAdditionalSources=MySource or /p:RestoreSources=MySource. The second switch will disable all other sources, which is good for offline scenarios, for example.

What is the difference between ManualResetEvent and AutoResetEvent in .NET?

I created simple examples to clarify understanding of ManualResetEvent vs AutoResetEvent.

AutoResetEvent: lets assume you have 3 workers thread. If any of those threads will call WaitOne() all other 2 threads will stop execution and wait for signal. I am assuming they are using WaitOne(). It is like; if I do not work, nobody works. In first example you can see that

autoReset.Set();
Thread.Sleep(1000);
autoReset.Set();

When you call Set() all threads will work and wait for signal. After 1 second I am sending second signal and they execute and wait (WaitOne()). Think about these guys are soccer team players and if one player says I will wait until manager calls me, and others will wait until manager tells them to continue (Set())

public class AutoResetEventSample
{
    private AutoResetEvent autoReset = new AutoResetEvent(false);

    public void RunAll()
    {
        new Thread(Worker1).Start();
        new Thread(Worker2).Start();
        new Thread(Worker3).Start();
        autoReset.Set();
        Thread.Sleep(1000);
        autoReset.Set();
        Console.WriteLine("Main thread reached to end.");
    }

    public void Worker1()
    {
        Console.WriteLine("Entered in worker 1");
        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker1 is running {0}", i);
            Thread.Sleep(2000);
            autoReset.WaitOne();
        }
    }
    public void Worker2()
    {
        Console.WriteLine("Entered in worker 2");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker2 is running {0}", i);
            Thread.Sleep(2000);
            autoReset.WaitOne();
        }
    }
    public void Worker3()
    {
        Console.WriteLine("Entered in worker 3");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker3 is running {0}", i);
            Thread.Sleep(2000);
            autoReset.WaitOne();
        }
    }
}

In this example you can clearly see that when you first hit Set() it will let all threads go, then after 1 second it signals all threads to wait! As soon as you set them again regardless they are calling WaitOne() inside, they will keep running because you have to manually call Reset() to stop them all.

manualReset.Set();
Thread.Sleep(1000);
manualReset.Reset();
Console.WriteLine("Press to release all threads.");
Console.ReadLine();
manualReset.Set();

It is more about Referee/Players relationship there regardless of any of the player is injured and wait for playing others will continue to work. If Referee says wait (Reset()) then all players will wait until next signal.

public class ManualResetEventSample
{
    private ManualResetEvent manualReset = new ManualResetEvent(false);

    public void RunAll()
    {
        new Thread(Worker1).Start();
        new Thread(Worker2).Start();
        new Thread(Worker3).Start();
        manualReset.Set();
        Thread.Sleep(1000);
        manualReset.Reset();
        Console.WriteLine("Press to release all threads.");
        Console.ReadLine();
        manualReset.Set();
        Console.WriteLine("Main thread reached to end.");
    }

    public void Worker1()
    {
        Console.WriteLine("Entered in worker 1");
        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker1 is running {0}", i);
            Thread.Sleep(2000);
            manualReset.WaitOne();
        }
    }
    public void Worker2()
    {
        Console.WriteLine("Entered in worker 2");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker2 is running {0}", i);
            Thread.Sleep(2000);
            manualReset.WaitOne();
        }
    }
    public void Worker3()
    {
        Console.WriteLine("Entered in worker 3");

        for (int i = 0; i < 5; i++) {
            Console.WriteLine("Worker3 is running {0}", i);
            Thread.Sleep(2000);
            manualReset.WaitOne();
        }
    }
}

Removing an item from a select box

JavaScript

_x000D_
_x000D_
function removeOptionsByValue(selectBox, value)_x000D_
{_x000D_
  for (var i = selectBox.length - 1; i >= 0; --i) {_x000D_
    if (selectBox[i].value == value) {_x000D_
      selectBox.remove(i);_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
function addOption(selectBox, text, value, selected)_x000D_
{_x000D_
  selectBox.add(new Option(text, value || '', false, selected || false));_x000D_
}_x000D_
_x000D_
var selectBox = document.getElementById('selectBox');_x000D_
_x000D_
removeOptionsByValue(selectBox, 'option3');_x000D_
addOption(selectBox, 'option5', 'option5', true);
_x000D_
<select name="selectBox" id="selectBox">_x000D_
    <option value="option1">option1</option>_x000D_
    <option value="option2">option2</option>_x000D_
    <option value="option3">option3</option>_x000D_
    <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

jQuery

_x000D_
_x000D_
jQuery(function($) {_x000D_
  $.fn.extend({_x000D_
    remove_options: function(value) {_x000D_
      return this.each(function() {_x000D_
        $('> option', this)_x000D_
          .filter(function() {_x000D_
            return this.value == value;_x000D_
          })_x000D_
          .remove();_x000D_
      });_x000D_
    },_x000D_
    add_option: function(text, value, selected) {_x000D_
      return this.each(function() {_x000D_
        $(this).append(new Option(text, value || '', false, selected || false));_x000D_
      });_x000D_
    }_x000D_
  });_x000D_
});_x000D_
_x000D_
jQuery(function($) {_x000D_
  $('#selectBox')_x000D_
    .remove_options('option3')_x000D_
    .add_option('option5', 'option5', true);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="selectBox" id="selectBox">_x000D_
    <option value="option1">option1</option>_x000D_
    <option value="option2">option2</option>_x000D_
    <option value="option3">option3</option>_x000D_
    <option value="option4">option4</option> _x000D_
</select>
_x000D_
_x000D_
_x000D_

How can I set response header on express.js assets

Short Answer:

  • res.setHeaders - calls the native Node.js method

  • res.set - sets headers

  • res.headers - an alias to res.set

How to extract file name from path?

Function file_name_only(file_path As String) As String

Dim temp As Variant

temp = Split(file_path, Application.PathSeparator)

file_name_only = temp(UBound(temp))

End Function
  1. here you give your file name as input of the function
  2. the split function of VBA splits the path in different portion by using "\" as path separator & stores them in an array named "temp"
  3. the UBound() finds the max item number of array and finally assigns the result to "file_name_only" function

Hope this will be helpful.

Why are empty catch blocks a bad idea?

Per Josh Bloch - Item 65: Don't ignore Exceptions of Effective Java:

  1. An empty catch block defeats the purpose of exceptions
  2. At the very least, the catch block should contain a comment explaining why it is appropriate to ignore the exception.

Laravel migration table field's type change

2018 Solution, still other answers are valid but you dont need to use any dependency:

First you have to create a new migration:

php artisan make:migration change_appointment_time_column_type

Then in that migration file up(), try:

    Schema::table('appointments', function ($table) {
        $table->string('time')->change();
    });

If you donot change the size default will be varchar(191) but If you want to change size of the field:

    Schema::table('appointments', function ($table) {
        $table->string('time', 40)->change();
    });

Then migrate the file by:

php artisan migrate

more info from doc.

center aligning a fixed position div

If you want to center aligning a fixed position div both vertically and horizontally use this

position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);

CSS to line break before/after a particular `inline-block` item

An easy way to split lists into rows is by floating the individual list items and then the item that you want to go to the next line you can clear the float.

for example

<li style="float: left; display: inline-block"></li>
<li style="float: left; display: inline-block"></li>
<li style="float: left; display: inline-block"></li>

<li style="float: left; display: inline-block; clear: both"></li> --- this will start on a new line
<li style="float: left; display: inline-block"></li>
<li style="float: left; display: inline-block"></li>

Disable building workspace process in Eclipse

Building workspace is about incremental build of any evolution detected in one of the opened projects in the currently used workspace.

You can also disable it through the menu "Project / Build automatically".

But I would recommend first to check:

  • if a Project Clean all / Build result in the same kind of long wait (after disabling this option)
  • if you have (this time with building automatically activated) some validation options you could disable to see if they have an influence on the global compilation time (Preferences / Validations, or Preferences / XML / ... if you have WTP installed)
  • if a fresh eclipse installation referencing the same workspace (see this eclipse.ini for more) results in the same issue (with building automatically activated)

Note that bug 329657 (open in 2011, in progress in 2014) is about interrupting a (too lengthy) build, instead of cancelling it:

There is an important difference between build interrupt and cancel.

  • When a build is cancelled, it typically handles this by discarding incremental build state and letting the next build be a full rebuild. This can be quite expensive in some projects.
    As a user I think I would rather wait for the 5 second incremental build to finish rather than cancel and result in a 30 second rebuild afterwards.

  • The idea with interrupt is that a builder could more efficiently handle interrupt by saving its intermediate state and resuming on the next invocation.
    In practice this is hard to implement so the most common boundary is when we check for interrupt before/after calling each builder in the chain.

 

JavaScript alert not working in Android WebView

Check this link , and last comment , You have to use WebChromeClient for your purpose.

What does 'super' do in Python?

When calling super() to resolve to a parent's version of a classmethod, instance method, or staticmethod, we want to pass the current class whose scope we are in as the first argument, to indicate which parent's scope we're trying to resolve to, and as a second argument the object of interest to indicate which object we're trying to apply that scope to.

Consider a class hierarchy A, B, and C where each class is the parent of the one following it, and a, b, and c respective instances of each.

super(B, b) 
# resolves to the scope of B's parent i.e. A 
# and applies that scope to b, as if b was an instance of A

super(C, c) 
# resolves to the scope of C's parent i.e. B
# and applies that scope to c

super(B, c) 
# resolves to the scope of B's parent i.e. A 
# and applies that scope to c

Using super with a staticmethod

e.g. using super() from within the __new__() method

class A(object):
    def __new__(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        return super(A, cls).__new__(cls, *a, **kw)

Explanation:

1- even though it's usual for __new__() to take as its first param a reference to the calling class, it is not implemented in Python as a classmethod, but rather a staticmethod. That is, a reference to a class has to be passed explicitly as the first argument when calling __new__() directly:

# if you defined this
class A(object):
    def __new__(cls):
        pass

# calling this would raise a TypeError due to the missing argument
A.__new__()

# whereas this would be fine
A.__new__(A)

2- when calling super() to get to the parent class we pass the child class A as its first argument, then we pass a reference to the object of interest, in this case it's the class reference that was passed when A.__new__(cls) was called. In most cases it also happens to be a reference to the child class. In some situations it might not be, for instance in the case of multiple generation inheritances.

super(A, cls)

3- since as a general rule __new__() is a staticmethod, super(A, cls).__new__ will also return a staticmethod and needs to be supplied all arguments explicitly, including the reference to the object of insterest, in this case cls.

super(A, cls).__new__(cls, *a, **kw)

4- doing the same thing without super

class A(object):
    def __new__(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        return object.__new__(cls, *a, **kw)

Using super with an instance method

e.g. using super() from within __init__()

class A(object): 
    def __init__(self, *a, **kw):
        # ...
        # you make some changes here
        # ...

        super(A, self).__init__(*a, **kw)

Explanation:

1- __init__ is an instance method, meaning that it takes as its first argument a reference to an instance. When called directly from the instance, the reference is passed implicitly, that is you don't need to specify it:

# you try calling `__init__()` from the class without specifying an instance
# and a TypeError is raised due to the expected but missing reference
A.__init__() # TypeError ...

# you create an instance
a = A()

# you call `__init__()` from that instance and it works
a.__init__()

# you can also call `__init__()` with the class and explicitly pass the instance 
A.__init__(a)

2- when calling super() within __init__() we pass the child class as the first argument and the object of interest as a second argument, which in general is a reference to an instance of the child class.

super(A, self)

3- The call super(A, self) returns a proxy that will resolve the scope and apply it to self as if it's now an instance of the parent class. Let's call that proxy s. Since __init__() is an instance method the call s.__init__(...) will implicitly pass a reference of self as the first argument to the parent's __init__().

4- to do the same without super we need to pass a reference to an instance explicitly to the parent's version of __init__().

class A(object): 
    def __init__(self, *a, **kw):
        # ...
        # you make some changes here
        # ...

        object.__init__(self, *a, **kw)

Using super with a classmethod

class A(object):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        print "A.alternate_constructor called"
        return cls(*a, **kw)

class B(A):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        print "B.alternate_constructor called"
        return super(B, cls).alternate_constructor(*a, **kw)

Explanation:

1- A classmethod can be called from the class directly and takes as its first parameter a reference to the class.

# calling directly from the class is fine,
# a reference to the class is passed implicitly
a = A.alternate_constructor()
b = B.alternate_constructor()

2- when calling super() within a classmethod to resolve to its parent's version of it, we want to pass the current child class as the first argument to indicate which parent's scope we're trying to resolve to, and the object of interest as the second argument to indicate which object we want to apply that scope to, which in general is a reference to the child class itself or one of its subclasses.

super(B, cls_or_subcls)

3- The call super(B, cls) resolves to the scope of A and applies it to cls. Since alternate_constructor() is a classmethod the call super(B, cls).alternate_constructor(...) will implicitly pass a reference of cls as the first argument to A's version of alternate_constructor()

super(B, cls).alternate_constructor()

4- to do the same without using super() you would need to get a reference to the unbound version of A.alternate_constructor() (i.e. the explicit version of the function). Simply doing this would not work:

class B(A):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        print "B.alternate_constructor called"
        return A.alternate_constructor(cls, *a, **kw)

The above would not work because the A.alternate_constructor() method takes an implicit reference to A as its first argument. The cls being passed here would be its second argument.

class B(A):
    @classmethod
    def alternate_constructor(cls, *a, **kw):
        # ...
        # whatever you want to specialize or override here
        # ...

        print "B.alternate_constructor called"
        # first we get a reference to the unbound 
        # `A.alternate_constructor` function 
        unbound_func = A.alternate_constructor.im_func
        # now we call it and pass our own `cls` as its first argument
        return unbound_func(cls, *a, **kw)

Deserialize JSON to Array or List with HTTPClient .ReadAsAsync using .NET 4.0 Task pattern

Instead of handcranking your models try using something like the Json2csharp.com website. Paste In an example JSON response, the fuller the better and then pull in the resultant generated classes. This, at least, takes away some moving parts, will get you the shape of the JSON in csharp giving the serialiser an easier time and you shouldnt have to add attributes.

Just get it working and then make amendments to your class names, to conform to your naming conventions, and add in attributes later.

EDIT: Ok after a little messing around I have successfully deserialised the result into a List of Job (I used Json2csharp.com to create the class for me)

public class Job
{
        public string id { get; set; }
        public string position_title { get; set; }
        public string organization_name { get; set; }
        public string rate_interval_code { get; set; }
        public int minimum { get; set; }
        public int maximum { get; set; }
        public string start_date { get; set; }
        public string end_date { get; set; }
        public List<string> locations { get; set; }
        public string url { get; set; }
}

And an edit to your code:

        List<Job> model = null;
        var client = new HttpClient();
        var task = client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs")
          .ContinueWith((taskwithresponse) =>
          {
              var response = taskwithresponse.Result;
              var jsonString = response.Content.ReadAsStringAsync();
              jsonString.Wait();
              model = JsonConvert.DeserializeObject<List<Job>>(jsonString.Result);

          });
        task.Wait();

This means you can get rid of your containing object. Its worth noting that this isn't a Task related issue but rather a deserialisation issue.

EDIT 2:

There is a way to take a JSON object and generate classes in Visual Studio. Simply copy the JSON of choice and then Edit> Paste Special > Paste JSON as Classes. A whole page is devoted to this here:

http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/

How can I simulate a click to an anchor tag?

There is a simpler way to achieve it,

HTML

<a href="https://getbootstrap.com/" id="fooLinkID" target="_blank">Bootstrap is life !</a>

JavaScript

// Simulating click after 3 seconds
setTimeout(function(){
  document.getElementById('fooLinkID').click();
}, 3 * 1000);

Using plain javascript to simulate a click along with addressing the target property.

You can check working example here on jsFiddle.

Error installing mysql2: Failed to build gem native extension

Have you tried using

 gem install mysql -- --with-mysql-lib=/usr/lib/mysql/lib 

to specify the location of thebase directory as well as the path to the MySQL libraries that are necessary to complete the gem installation?

Sources: MySQL Gem Install ERROR: Failed to build gem native extension MySQL Forums :: Ruby :: Help needed with installing MySQL binding for Ruby

How to clone an InputStream?

This might not work in all situations, but here is what I did: I extended the FilterInputStream class and do the required processing of the bytes as the external lib reads the data.

public class StreamBytesWithExtraProcessingInputStream extends FilterInputStream {

    protected StreamBytesWithExtraProcessingInputStream(InputStream in) {
        super(in);
    }

    @Override
    public int read() throws IOException {
        int readByte = super.read();
        processByte(readByte);
        return readByte;
    }

    @Override
    public int read(byte[] buffer, int offset, int count) throws IOException {
        int readBytes = super.read(buffer, offset, count);
        processBytes(buffer, offset, readBytes);
        return readBytes;
    }

    private void processBytes(byte[] buffer, int offset, int readBytes) {
       for (int i = 0; i < readBytes; i++) {
           processByte(buffer[i + offset]);
       }
    }

    private void processByte(int readByte) {
       // TODO do processing here
    }

}

Then you simply pass an instance of StreamBytesWithExtraProcessingInputStream where you would have passed in the input stream. With the original input stream as constructor parameter.

It should be noted that this works byte for byte, so don't use this if high performance is a requirement.

How to bind multiple values to a single WPF TextBlock?

I know this is a way late, but I thought I'd add yet another way of doing this.

You can take advantage of the fact that the Text property can be set using "Runs", so you can set up multiple bindings using a Run for each one. This is useful if you don't have access to MultiBinding (which I didn't find when developing for Windows Phone)

<TextBlock>
  <Run Text="Name = "/>
  <Run Text="{Binding Name}"/>
  <Run Text=", Id ="/>
  <Run Text="{Binding Id}"/>
</TextBlock>

How to create multidimensional array

var numeric = [
    ['input1','input2'],
    ['input3','input4']
];
numeric[0][0] == 'input1';
numeric[0][1] == 'input2';
numeric[1][0] == 'input3';
numeric[1][1] == 'input4';

var obj = {
    'row1' : {
        'key1' : 'input1',
        'key2' : 'input2'
    },
    'row2' : {
        'key3' : 'input3',
        'key4' : 'input4'
    }
};
obj.row1.key1 == 'input1';
obj.row1.key2 == 'input2';
obj.row2.key1 == 'input3';
obj.row2.key2 == 'input4';

var mixed = {
    'row1' : ['input1', 'inpu2'],
    'row2' : ['input3', 'input4']
};
mixed.row1[0] == 'input1';
mixed.row1[1] == 'input2';
mixed.row2[0] == 'input3';
mixed.row2[1] == 'input4';

http://jsfiddle.net/z4Un3/

And if you're wanting to store DOM elements:

var inputs = [
    [
        document.createElement('input'),
        document.createElement('input')
    ],
    [
        document.createElement('input'),
        document.createElement('input')
    ]
];
inputs[0][0].id = 'input1';
inputs[0][1].id = 'input2';
inputs[1][0].id = 'input3';
inputs[1][1].id = 'input4';

Not real sure how useful the above is until you attach the elements. The below may be more what you're looking for:

<input text="text" id="input5"/>
<input text="text" id="input6"/>
<input text="text" id="input7"/>
<input text="text" id="input8"/>    
var els = [
    [
        document.getElementById('input5'),
        document.getElementById('input6')
    ],
    [
        document.getElementById('input7'),
        document.getElementById('input8')
    ]
];    
els[0][0].id = 'input5';
els[0][1].id = 'input6';
els[1][0].id = 'input7';
els[1][1].id = 'input8';

http://jsfiddle.net/z4Un3/3/

Or, maybe this:

<input text="text" value="4" id="input5"/>
<input text="text" value="4" id="input6"/>
<br/>
<input text="text" value="2" id="input7"/>
<input text="text" value="4" id="input8"/>

var els = [
    [
        document.getElementById('input5'),
        document.getElementById('input6')
    ],
    [
        document.getElementById('input7'),
        document.getElementById('input8')
    ]
];

var result = [];

for (var i = 0; i < els.length; i++) {
    result[result.length] = els[0][i].value - els[1][i].value;
}

Which gives:

[2, 0]

In the console. If you want to output that to text, you can result.join(' ');, which would give you 2 0.

http://jsfiddle.net/z4Un3/6/

EDIT

And a working demonstration:

<input text="text" value="4" id="input5"/>
<input text="text" value="4" id="input6"/>
<br/>
<input text="text" value="2" id="input7"/>
<input text="text" value="4" id="input8"/>
<br/>
<input type="button" value="Add" onclick="add()"/>

// This would just go in a script block in the head
function add() {
    var els = [
        [
            document.getElementById('input5'),
            document.getElementById('input6')
        ],
        [
            document.getElementById('input7'),
            document.getElementById('input8')
        ]
    ];

    var result = [];

    for (var i = 0; i < els.length; i++) {
        result[result.length] = parseInt(els[0][i].value) - parseInt(els[1][i].value);
    }

    alert(result.join(' '));
}

http://jsfiddle.net/z4Un3/8/

Android studio doesn't list my phone under "Choose Device"

In my case, android studio selectively doesnt recognize my device for projects with COMPILE AND TARGET SDKVERSION 29 under the app level build.gradle.

I fixed this either by downloading 'sources for android 29' which comes up after clicking the 'show package details' under the sdk manager tab or by reducing the compile and targetsdkversions to 28

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

You should probably stop using launch images in iOS 8 and use a storyboard or nib/xib.

  • In Xcode 6, open the File menu and choose New ? File... ? iOS ? User Interface ? Launch Screen.

  • Then open the settings for your project by clicking on it.

  • In the General tab, in the section called App Icons and Launch Images, set the Launch Screen File to the files you just created (this will set UILaunchStoryboardName in info.plist).

Note that for the time being the simulator will only show a black screen, so you need to test on a real device.

Adding a Launch Screen xib file to your project:

Adding a new Launch Screen xib file

Configuring your project to use the Launch Screen xib file instead of the Asset Catalog:

Configure project to use Launch Screen xob

Java 8 lambdas, Function.identity() or t->t

As of the current JRE implementation, Function.identity() will always return the same instance while each occurrence of identifier -> identifier will not only create its own instance but even have a distinct implementation class. For more details, see here.

The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x, equivalent to return identifier;) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.

So using Function.identity() instead of x -> x might save some memory but that shouldn’t drive your decision if you really think that x -> x is more readable than Function.identity().

You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function instance while debugging. In contrast, when encountering the instance returned by Function.identity() during debugging an operation, you won’t know who has called that method and passed the instance to the operation.

How to trap the backspace key using jQuery?

Regular javascript can be used to trap the backspace key. You can use the event.keyCode method. The keycode is 8, so the code would look something like this:

if (event.keyCode == 8) {
    // Do stuff...
}

If you want to check for both the [delete] (46) as well as the [backspace] (8) keys, use the following:

if (event.keyCode == 8 || event.keyCode == 46) {
    // Do stuff...
}

Purpose of #!/usr/bin/python3 shebang

This line helps find the program executable that will run the script. This shebang notation is fairly standard across most scripting languages (at least as used on grown-up operating systems).

An important aspect of this line is specifying which interpreter will be used. On many development-centered Linux distributions, for example, it is normal to have several versions of python installed at the same time.

Python 2.x and Python 3 are not 100% compatible, so this difference can be very important. So #! /usr/bin/python and #! /usr/bin/python3 are not the same (and neither are quite the same as #! /usr/bin/env python3 as noted elsewhere on this page.

How to run a bash script from C++ program

StackOverflow: How to execute a command and get output of command within C++?

StackOverflow: (Using fork,pipe,select): ...nobody does things the hard way any more...

Also if you know how to make user become the super-user that would be nice also. Thanks!

sudo. su. chmod 04500. (setuid() & seteuid(), but they require you to already be root. E..g. chmod'ed 04***.)

Take care. These can open "interesting" security holes...

Depending on what you are doing, you may not need root. (For instance: I'll often chmod/chown /dev devices (serial ports, etc) (under sudo root) so I can use them from my software without being root. On the other hand, that doesn't work so well when loading/unloading kernel modules...)

How to read file from res/raw by name

With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

To get it as a InputStream

InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));

Delete branches in Bitbucket

If you are using a pycharm IDE for development and you already have added Git with it. you can directly delete remote branch from pycharm. From toolbar VCS-->Git-->Branches-->Select branch-->and Delete. It will delete it from remote git server.

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

Just to clarify the Training/Validation/Test data sets: The training set is used to perform the initial training of the model, initializing the weights of the neural network.

The validation set is used after the neural network has been trained. It is used for tuning the network's hyperparameters, and comparing how changes to them affect the predictive accuracy of the model. Whereas the training set can be thought of as being used to build the neural network's gate weights, the validation set allows fine tuning of the parameters or architecture of the neural network model. It's useful as it allows repeatable comparison of these different parameters/architectures against the same data and networks weights, to observe how parameter/architecture changes affect the predictive power of the network.

Then the test set is used only to test the predictive accuracy of the trained neural network on previously unseen data, after training and parameter/architecture selection with the training and validation data sets.

How to convert list data into json in java

Try like below with Gson Library.

Earlier Conversion List format were:

[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]

and here the conversion source begins.

//** Note I have created the method toString() in Product class.

//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();

//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();

//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());

//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();

//Run while loop till Product Object exists.
while(iterator.hasNext()){

    //Creating a fresh Gson Object
    Gson gs = new Gson();

    //Converting our Product Object to JsonElement 
    //Object by passing the Product Object String value (iterator.next())
    JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);

    //Creating JsonObject from JsonElement
    JsonObject jsonObject = element.getAsJsonObject();

    //Collecting the JsonObject to List
    entities.add(jsonObject);

}

//Do what you want to do with Array of JsonObject
System.out.println(entities);

Converted Json Result is :

[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]

Hope this would help many guys!

Rendering raw html with reactjs

You could leverage the html-to-react npm module.

Note: I'm the author of the module and just published it a few hours ago. Please feel free to report any bugs or usability issues.

How to trigger a phone call when clicking a link in a web page on mobile phone

Just use HTML anchor tag <a> and start the attribute href with tel:. I suggest starting the phone number with the country code. pay attention to the following example:

<a href="tel:+989123456789">NO Different What it is</a>

For this example, the country code is +98.

Hint: It is so suitable for cellphones, I know tel: prefix calls FaceTime on macOS but on Windows I'm not sure, but I guess it caused to launch Skype.

For more information: you can visit the list of URL schemes supported by browsers to know all href values prefixes.

Python read-only property

That's my workaround.

@property
def language(self):
    return self._language
@language.setter
def language(self, value):
    # WORKAROUND to get a "getter-only" behavior
    # set the value only if the attribute does not exist
    try:
        if self.language == value:
            pass
        print("WARNING: Cannot set attribute \'language\'.")
    except AttributeError:
        self._language = value

How do I import/include MATLAB functions?

If the folder just contains functions then adding the folders to the path at the start of the script will suffice.

addpath('../folder_x/');
addpath('../folder_y/');

If they are Packages, folders starting with a '+' then they also need to be imported.

import package_x.*
import package_y.*

You need to add the package folders parent to the search path.

Redirect to external URL with return in laravel

You should be able to redirect to the url like this

return Redirect::to($url);

You can read about Redirects in the Laravel docs here.

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

How to use onSaveInstanceState() and onRestoreInstanceState()?

  • onSaveInstanceState() is a method used to store data before pausing the activity.

Description : Hook allowing a view to generate a representation of its internal state that can later be used to create a new instance with that same state. This state should only contain information that is not persistent or can not be reconstructed later. For example, you will never store your current position on screen because that will be computed again when a new instance of the view is placed in its view hierarchy.

  • onRestoreInstanceState() is method used to retrieve that data back.

Description : This method is called after onStart() when the activity is being re-initialized from a previously saved state, given here in savedInstanceState. Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

Consider this example here:
You app has 3 edit boxes where user was putting in some info , but he gets a call so if you didn't use the above methods what all he entered will be lost.
So always save the current data in onPause() method of Activity as a bundle & in onResume() method call the onRestoreInstanceState() method .

Please see :

How to use onSavedInstanceState example please

http://www.how-to-develop-android-apps.com/tag/onrestoreinstancestate/

Add an element to an array in Swift

Use += and + operators :

extension Array {

}

func += <V> (inout left: [V], right: V) {
    left.append(right)
}

func + <V>(left: Array<V>, right: V) -> Array<V>
{
    var map = Array<V>()
    for (v) in left {
        map.append(v)
    }

    map.append(right)

    return map
}

then use :

var list = [AnyObject]()
list += "hello" 
list += ["hello", "world!"]
var list2 = list + "anything"

How to easily consume a web service from PHP

HI I got this from this site : http://forums.asp.net/t/887892.aspx?Consume+an+ASP+NET+Web+Service+with+PHP

The web service has method Add which takes two params:

<?php
    $client = new SoapClient("http://localhost/csharp/web_service.asmx?wsdl");

     print_r( $client->Add(array("a" => "5", "b" =>"2")));
?>

Convert Python dictionary to JSON array

ensure_ascii=False really only defers the issue to the decoding stage:

>>> dict2 = {'LeafTemps': '\xff\xff\xff\xff',}
>>> json1 = json.dumps(dict2, ensure_ascii=False)
>>> print(json1)
{"LeafTemps": "????"}
>>> json.loads(json1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/json/__init__.py", line 328, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python2.7/json/decoder.py", line 381, in raw_decode
    obj, end = self.scan_once(s, idx)
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0: invalid start byte

Ultimately you can't store raw bytes in a JSON document, so you'll want to use some means of unambiguously encoding a sequence of arbitrary bytes as an ASCII string - such as base64.

>>> import json
>>> from base64 import b64encode, b64decode
>>> my_dict = {'LeafTemps': '\xff\xff\xff\xff',} 
>>> my_dict['LeafTemps'] = b64encode(my_dict['LeafTemps'])
>>> json.dumps(my_dict)
'{"LeafTemps": "/////w=="}'
>>> json.loads(json.dumps(my_dict))
{u'LeafTemps': u'/////w=='}
>>> new_dict = json.loads(json.dumps(my_dict))
>>> new_dict['LeafTemps'] = b64decode(new_dict['LeafTemps'])
>>> print new_dict
{u'LeafTemps': '\xff\xff\xff\xff'}

How to pass variables from one php page to another without form?

If you are trying to access the variable from another PHP file directly, you can include that file with include() or include_once(), giving you access to that variable. Note that this will include the entire first file in the second file.

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

When saving, how can you check if a field has changed?

The mixin from @ivanlivski is great.

I've extended it to

  • Ensure it works with Decimal fields.
  • Expose properties to simplify usage

The updated code is available here: https://github.com/sknutsonsf/python-contrib/blob/master/src/django/utils/ModelDiffMixin.py

To help people new to Python or Django, I'll give a more complete example. This particular usage is to take a file from a data provider and ensure the records in the database reflect the file.

My model object:

class Station(ModelDiffMixin.ModelDiffMixin, models.Model):
    station_name = models.CharField(max_length=200)
    nearby_city = models.CharField(max_length=200)

    precipitation = models.DecimalField(max_digits=5, decimal_places=2)
    # <list of many other fields>

   def is_float_changed (self,v1, v2):
        ''' Compare two floating values to just two digit precision
        Override Default precision is 5 digits
        '''
        return abs (round (v1 - v2, 2)) > 0.01

The class that loads the file has these methods:

class UpdateWeather (object)
    # other methods omitted

    def update_stations (self, filename):
        # read all existing data 
        all_stations = models.Station.objects.all()
        self._existing_stations = {}

        # insert into a collection for referencing while we check if data exists
        for stn in all_stations.iterator():
            self._existing_stations[stn.id] = stn

        # read the file. result is array of objects in known column order
        data = read_tabbed_file(filename)

        # iterate rows from file and insert or update where needed
        for rownum in range(sh.nrows):
            self._update_row(sh.row(rownum));

        # now anything remaining in the collection is no longer active
        # since it was not found in the newest file
        # for now, delete that record
        # there should never be any of these if the file was created properly
        for stn in self._existing_stations.values():
            stn.delete()
            self._num_deleted = self._num_deleted+1


    def _update_row (self, rowdata):
        stnid = int(rowdata[0].value) 
        name = rowdata[1].value.strip()

        # skip the blank names where data source has ids with no data today
        if len(name) < 1:
            return

        # fetch rest of fields and do sanity test
        nearby_city = rowdata[2].value.strip()
        precip = rowdata[3].value

        if stnid in self._existing_stations:
            stn = self._existing_stations[stnid]
            del self._existing_stations[stnid]
            is_update = True;
        else:
            stn = models.Station()
            is_update = False;

        # object is new or old, don't care here            
        stn.id = stnid
        stn.station_name = name;
        stn.nearby_city = nearby_city
        stn.precipitation = precip

        # many other fields updated from the file 

        if is_update == True:

            # we use a model mixin to simplify detection of changes
            # at the cost of extra memory to store the objects            
            if stn.has_changed == True:
                self._num_updated = self._num_updated + 1;
                stn.save();
        else:
            self._num_created = self._num_created + 1;
            stn.save()

how do I give a div a responsive height

I know this is a little late to the party but you could use viewport units

From caniuse.com:

Viewport units: vw, vh, vmin, vmax - CR Length units representing 1% of the viewport size for viewport width (vw), height (vh), the smaller of the two (vmin), or the larger of the two (vmax).

Support: http://caniuse.com/#feat=viewport-units

_x000D_
_x000D_
div {_x000D_
/* 25% of viewport */_x000D_
  height: 25vh;_x000D_
  width: 15rem;_x000D_
  background-color: #222;_x000D_
  color: #eee;_x000D_
  font-family: monospace;_x000D_
  padding: 2rem;_x000D_
}
_x000D_
<div>responsive height</div>
_x000D_
_x000D_
_x000D_

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

You can use npm link to create a symbolic link to your global package in your projects folder.

Example:

$ npm install -g express
$ cd [local path]/project
$ npm link express

All it does is create a local node_modules folder and then create a symlink express -> [global directory]/node_modules/express which can then be resolved by require('express')

Using Excel as front end to Access database (with VBA)

It Depends how much functionality you are expecting by Excel<->Acess solution. In many cases where you don't have budget to get a complete application solution, these little utilities does work. If the Scope of project is limited then I would go for this solution, because excel does give you flexibility to design spreadsheets as in accordance to your needs and then you may use those predesigned sheets for users to use. Designing a spreadsheet like form in Access is more time consuming and difficult and does requires some ActiveX. It object might not only handling data but presenting in spreadsheet like formates then this solution should works with limited scope.

How can I call a method in Objective-C?

Use this:

[self score]; you don't need @sel for calling directly

Eclipse interface icons very small on high resolution screen in Windows 8.1

I had this problem when I changed my default Windows 10 language from Eng to Italian, with Eclipse being installed when default language was Eng. Reverting Windows language to Eng and rebooting solved the problem. I don’t know what’s happened, Windows rename some folders like C:\Users translating it in your default language (i.e. C:\Utenti) and maybe this is causing problems.

android.view.InflateException: Binary XML file line #12: Error inflating class <unknown>

I had the same error when creating custom view with only one constructor, try to define all constructor for your custom views.

   public CustomWebView(Context context) {
        super(context);
        init();
    }

    public CustomWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CustomWebView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

How should I edit an Entity Framework connection string?

If you remove the connection string from the app.config file, re-running the entity Data Model wizard will guide you to build a new connection.

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

Pass a variable to a PHP script running from the command line

Parameters send by index like other applications:

php myfile.php type=daily

And then you can get them like this:

<?php
    if (count($argv) == 0) 
        exit;

    foreach ($argv as $arg)
        echo $arg;
?>

How can I open a link in a new window?

Be aware if you want to execute AJAX requests inside the event handler function for the click event. For some reason Chrome (and maybe other browsers) will not open a new tab/window.

Android toolbar center title and custom font

we don't have direct access to the ToolBar title TextView so we use reflection to access it.

  private TextView getActionBarTextView() {
    TextView titleTextView = null;

    try {
        Field f = mToolBar.getClass().getDeclaredField("mTitleTextView");
        f.setAccessible(true);
        titleTextView = (TextView) f.get(mToolBar);
    } catch (NoSuchFieldException e) {
    } catch (IllegalAccessException e) {
    }
    return titleTextView;
}

How to keep environment variables when using sudo

If you have the need to keep the environment variables in a script you can put your command in a here document like this. Especially if you have lots of variables to set things look tidy this way.

# prepare a script e.g. for running maven
runmaven=/tmp/runmaven$$
# create the script with a here document 
cat << EOF > $runmaven
#!/bin/bash
# run the maven clean with environment variables set
export ANT_HOME=/usr/share/ant
export MAKEFLAGS=-j4
mvn clean install
EOF
# make the script executable
chmod +x $runmaven
# run it
sudo $runmaven
# remove it or comment out to keep
rm $runmaven

How do you assert that a certain exception is thrown in JUnit 4 tests?

try {
    my method();
    fail( "This method must thrwo" );
} catch (Exception ex) {
    assertThat(ex.getMessage()).isEqual(myErrormsg);
}

how to display variable value in alert box?

document.getElementById('one').innerText;
alert(content);

It does not print the value; But, if done this way

document.getElementById('one').value;
alert(content);

How to invert a grep expression

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

grep --help | grep invert

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

convert strtotime to date time format in php

Here is exp.

$date_search_strtotime = strtotime(date("Y-m-d"));
echo 'Now strtotime date : '.$date_search_strtotime;
echo '<br>';
echo 'Now date from strtotime : '.date('Y-m-d',$date_search_strtotime);

jQuery Toggle Text?

Modifying my answer from your other question, I would do this:

$(function() {
 $("#show-background").click(function () {
  var c = $("#content-area");
  var o = (c.css('opacity') == 0) ? 1 : 0;
  var t = (o==1) ? 'Show Background' : 'Show Text';
  c.animate({opacity: o}, 'slow');
  $(this).text(t);
 });
});

warning: assignment makes integer from pointer without a cast

What Jeremiah said, plus the compiler issues the warning because the production:

*src ="anotherstring";

says: take the address of "anotherstring" -- "anotherstring" IS a char pointer -- and store that pointer indirect through src (*src = ... ) into the first char of the string "abcdef..." The warning might be baffling because there is nowhere in your code any mention of any integer: the warning seems nonsensical. But, out of sight behind the curtain, is the rule that "int" and "char" are synonymous in terms of storage: both occupy the same number of bits. The compiler doesn't differentiate when it issues the warning that you are storing into an integer. Which, BTW, is perfectly OK and legal but probably not exactly what you want in this code.

-- pete

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

What is the difference between float and double?

The size of the numbers involved in the float-point calculations is not the most relevant thing. It's the calculation that is being performed that is relevant.

In essence, if you're performing a calculation and the result is an irrational number or recurring decimal, then there will be rounding errors when that number is squashed into the finite size data structure you're using. Since double is twice the size of float then the rounding error will be a lot smaller.

The tests may specifically use numbers which would cause this kind of error and therefore tested that you'd used the appropriate type in your code.

Print array elements on separate lines in Bash?

I tried the answers here in a giant for...if loop, but didn't get any joy - so I did it like this, maybe messy but did the job:

 # EXP_LIST2 is iterated    
 # imagine a for loop
     EXP_LIST="List item"    
     EXP_LIST2="$EXP_LIST2 \n $EXP_LIST"
 done 
 echo -e $EXP_LIST2

although that added a space to the list, which is fine - I wanted it indented a bit. Also presume the "\n" could be printed in the original $EP_LIST.

SQL WITH clause example

This has been fully answered here.

See Oracle's docs on SELECT to see how subquery factoring works, and Mark's example:

WITH employee AS (SELECT * FROM Employees)
SELECT * FROM employee WHERE ID < 20
UNION ALL
SELECT * FROM employee WHERE Sex = 'M'

symbol(s) not found for architecture i386

I had used a CLGeocoder without adding a Core.Location Framework. Basically this error can mean multiple things. I hope this helps someone else.

How to Get the Query Executed in Laravel 5? DB::getQueryLog() Returning Empty Array

For laravel 5.8 you just add dd or dump.

Ex:

DB::table('users')->where('votes', '>', 100)->dd();

or

DB::table('users')->where('votes', '>', 100)->dump();

reference: https://laravel.com/docs/5.8/queries#debugging

In Java, can you modify a List while iterating through it?

Use Java 8's removeIf(),

To remove safely,

letters.removeIf(x -> !x.equals("A"));

How to dynamically add a class to manual class names?

getBadgeClasses() {
    let classes = "badge m-2 ";
    classes += (this.state.count === 0) ? "badge-warning" : "badge-primary";
    return classes;
}

<span className={this.getBadgeClasses()}>Total Count</span>

When to encode space to plus (+) or %20?

So, the answers here are all a bit incomplete. The use of a '%20' to encode a space in URLs is explicitly defined in RFC3986, which defines how a URI is built. There is no mention in this specification of using a '+' for encoding spaces - if you go solely by this specification, a space must be encoded as '%20'.

The mention of using '+' for encoding spaces comes from the various incarnations of the HTML specification - specifically in the section describing content type 'application/x-www-form-urlencoded'. This is used for posting form data.

Now, the HTML 2.0 Specification (RFC1866) explicitly said, in section 8.2.2, that the Query part of a GET request's URL string should be encoded as 'application/x-www-form-urlencoded'. This, in theory, suggests that it's legal to use a '+' in the URL in the query string (after the '?').

But... does it really? Remember, HTML is itself a content specification, and URLs with query strings can be used with content other than HTML. Further, while the later versions of the HTML spec continue to define '+' as legal in 'application/x-www-form-urlencoded' content, they completely omit the part saying that GET request query strings are defined as that type. There is, in fact, no mention whatsoever about the query string encoding in anything after the HTML 2.0 spec.

Which leaves us with the question - is it valid? Certainly there's a LOT of legacy code which supports '+' in query strings, and a lot of code which generates it as well. So odds are good you won't break if you use '+'. (And, in fact, I did all the research on this recently because I discovered a major site which failed to accept '%20' in a GET query as a space. They actually failed to decode ANY percent encoded character. So the service you're using may be relevant as well.)

But from a pure reading of the specifications, without the language from the HTML 2.0 specification carried over into later versions, URLs are covered entirely by RFC3986, which means spaces ought to be converted to '%20'. And definitely that should be the case if you are requesting anything other than an HTML document.

How to take column-slices of dataframe in pandas

Another way to get a subset of columns from your DataFrame, assuming you want all the rows, would be to do:
data[['a','b']] and data[['c','d','e']]
If you want to use numerical column indexes you can do:
data[data.columns[:2]] and data[data.columns[2:]]

rsync copy over only certain types of files using include option

Wrote this handy function and put in my bash scripts or ~/.bash_aliases. Tested sync'ing locally on Linux with bash and awk installed. It works

selrsync(){
# selective rsync to sync only certain filetypes;
# based on: https://stackoverflow.com/a/11111793/588867
# Example: selrsync 'tsv,csv' ./source ./target --dry-run
types="$1"; shift; #accepts comma separated list of types. Must be the first argument.
includes=$(echo $types| awk  -F',' \
    'BEGIN{OFS=" ";}
    {
    for (i = 1; i <= NF; i++ ) { if (length($i) > 0) $i="--include=*."$i; } print
    }')
restargs="$@"

echo Command: rsync -avz --prune-empty-dirs --include="*/" $includes --exclude="*" "$restargs"
eval rsync -avz --prune-empty-dirs --include="*/" "$includes" --exclude="*" $restargs
}

Avantages:

short handy and extensible when one wants to add more arguments (i.e. --dry-run).

Example:

selrsync 'tsv,csv' ./source ./target --dry-run