Programs & Examples On #Stuarray

Is the size of C "int" 2 bytes or 4 bytes?

Does an Integer variable in C occupy 2 bytes or 4 bytes?

That depends on the platform you're using, as well as how your compiler is configured. The only authoritative answer is to use the sizeof operator to see how big an integer is in your specific situation.


What are the factors that it depends on?

Range might be best considered, rather than size. Both will vary in practice, though it's much more fool-proof to choose variable types by range than size as we shall see. It's also important to note that the standard encourages us to consider choosing our integer types based on range rather than size, but for now let's ignore the standard practice, and let our curiosity explore sizeof, bytes and CHAR_BIT, and integer representation... let's burrow down the rabbit hole and see it for ourselves...


sizeof, bytes and CHAR_BIT

The following statement, taken from the C standard (linked to above), describes this in words that I don't think can be improved upon.

The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand.

Assuming a clear understanding will lead us to a discussion about bytes. It's commonly assumed that a byte is eight bits, when in fact CHAR_BIT tells you how many bits are in a byte. That's just another one of those nuances which isn't considered when talking about the common two (or four) byte integers.

Let's wrap things up so far:

  • sizeof => size in bytes, and
  • CHAR_BIT => number of bits in byte

Thus, Depending on your system, sizeof (unsigned int) could be any value greater than zero (not just 2 or 4), as if CHAR_BIT is 16, then a single (sixteen-bit) byte has enough bits in it to represent the sixteen bit integer described by the standards (quoted below). That's not necessarily useful information, is it? Let's delve deeper...


Integer representation

The C standard specifies the minimum precision/range for all standard integer types (and CHAR_BIT, too, fwiw) here. From this, we can derive a minimum for how many bits are required to store the value, but we may as well just choose our variables based on ranges. Nonetheless, a huge part of the detail required for this answer resides here. For example, the following that the standard unsigned int requires (at least) sixteen bits of storage:

UINT_MAX                                65535 // 2¹6 - 1

Thus we can see that unsigned int require (at least) 16 bits, which is where you get the two bytes (assuming CHAR_BIT is 8)... and later when that limit increased to 2³² - 1, people were stating 4 bytes instead. This explains the phenomena you've observed:

Most of the textbooks say integer variables occupy 2 bytes. But when I run a program printing the successive addresses of an array of integers it shows the difference of 4.

You're using an ancient textbook and compiler which is teaching you non-portable C; the author who wrote your textbook might not even be aware of CHAR_BIT. You should upgrade your textbook (and compiler), and strive to remember that I.T. is an ever-evolving field that you need to stay ahead of to compete... Enough about that, though; let's see what other non-portable secrets those underlying integer bytes store...

Value bits are what the common misconceptions appear to be counting. The above example uses an unsigned integer type which typically contains only value bits, so it's easy to miss the devil in the detail.

Sign bits... In the above example I quoted UINT_MAX as being the upper limit for unsigned int because it's a trivial example to extract the value 16 from the comment. For signed types, in order to distinguish between positive and negative values (that's the sign), we need to also include the sign bit.

INT_MIN                                -32768 // -(2¹5)
INT_MAX                                +32767 // 2¹5 - 1

Padding bits... While it's not common to encounter computers that have padding bits in integers, the C standard allows that to happen; some machines (i.e. this one) implement larger integer types by combining two smaller (signed) integer values together... and when you combine signed integers, you get a wasted sign bit. That wasted bit is considered padding in C. Other examples of padding bits might include parity bits and trap bits.


As you can see, the standard seems to encourage considering ranges like INT_MIN..INT_MAX and other minimum/maximum values from the standard when choosing integer types, and discourages relying upon sizes as there are other subtle factors likely to be forgotten such as CHAR_BIT and padding bits which might affect the value of sizeof (int) (i.e. the common misconceptions of two-byte and four-byte integers neglects these details).

Perform a Shapiro-Wilk Normality Test

What does shapiro.test do?

shapiro.test tests the Null hypothesis that "the samples come from a Normal distribution" against the alternative hypothesis "the samples do not come from a Normal distribution".

How to perform shapiro.test in R?

The R help page for ?shapiro.test gives,

x - a numeric vector of data values. Missing values are allowed, 
    but the number of non-missing values must be between 3 and 5000.

That is, shapiro.test expects a numeric vector as input, that corresponds to the sample you would like to test and it is the only input required. Since you've a data.frame, you'll have to pass the desired column as input to the function as follows:

> shapiro.test(heisenberg$HWWIchg)
#   Shapiro-Wilk normality test

# data:  heisenberg$HWWIchg 
# W = 0.9001, p-value = 0.2528

Interpreting results from shapiro.test:

First, I strongly suggest you read this excellent answer from Ian Fellows on testing for normality.

As shown above, the shapiro.test tests the NULL hypothesis that the samples came from a Normal distribution. This means that if your p-value <= 0.05, then you would reject the NULL hypothesis that the samples came from a Normal distribution. As Ian Fellows nicely put it, you are testing against the assumption of Normality". In other words (correct me if I am wrong), it would be much better if one tests the NULL hypothesis that the samples do not come from a Normal distribution. Why? Because, rejecting a NULL hypothesis is not the same as accepting the alternative hypothesis.

In case of the null hypothesis of shapiro.test, a p-value <= 0.05 would reject the null hypothesis that the samples come from normal distribution. To put it loosely, there is a rare chance that the samples came from a normal distribution. The side-effect of this hypothesis testing is that this rare chance happens very rarely. To illustrate, take for example:

set.seed(450)
x <- runif(50, min=2, max=4)
shapiro.test(x)
#   Shapiro-Wilk normality test
# data:  runif(50, min = 2, max = 4) 
# W = 0.9601, p-value = 0.08995

So, this (particular) sample runif(50, min=2, max=4) comes from a normal distribution according to this test. What I am trying to say is that, there are many many cases under which the "extreme" requirements (p < 0.05) are not satisfied which leads to acceptance of "NULL hypothesis" most of the times, which might be misleading.

Another issue I'd like to quote here from @PaulHiemstra from under comments about the effects on large sample size:

An additional issue with the Shapiro-Wilk's test is that when you feed it more data, the chances of the null hypothesis being rejected becomes larger. So what happens is that for large amounts of data even very small deviations from normality can be detected, leading to rejection of the null hypothesis event though for practical purposes the data is more than normal enough.

Although he also points out that R's data size limit protects this a bit:

Luckily shapiro.test protects the user from the above described effect by limiting the data size to 5000.

If the NULL hypothesis were the opposite, meaning, the samples do not come from a normal distribution, and you get a p-value < 0.05, then you conclude that it is very rare that these samples do not come from a normal distribution (reject the NULL hypothesis). That loosely translates to: It is highly likely that the samples are normally distributed (although some statisticians may not like this way of interpreting). I believe this is what Ian Fellows also tried to explain in his post. Please correct me if I've gotten something wrong!

@PaulHiemstra also comments about practical situations (example regression) when one comes across this problem of testing for normality:

In practice, if an analysis assumes normality, e.g. lm, I would not do this Shapiro-Wilk's test, but do the analysis and look at diagnostic plots of the outcome of the analysis to judge whether any assumptions of the analysis where violated too much. For linear regression using lm this is done by looking at some of the diagnostic plots you get using plot(lm()). Statistics is not a series of steps that cough up a few numbers (hey p < 0.05!) but requires a lot of experience and skill in judging how to analysis your data correctly.

Here, I find the reply from Ian Fellows to Ben Bolker's comment under the same question already linked above equally (if not more) informative:

For linear regression,

  1. Don't worry much about normality. The CLT takes over quickly and if you have all but the smallest sample sizes and an even remotely reasonable looking histogram you are fine.

  2. Worry about unequal variances (heteroskedasticity). I worry about this to the point of (almost) using HCCM tests by default. A scale location plot will give some idea of whether this is broken, but not always. Also, there is no a priori reason to assume equal variances in most cases.

  3. Outliers. A cooks distance of > 1 is reasonable cause for concern.

Those are my thoughts (FWIW).

Hope this clears things up a bit.

LINQ equivalent of foreach for IEnumerable<T>

There is an experimental release by Microsoft of Interactive Extensions to LINQ (also on NuGet, see RxTeams's profile for more links). The Channel 9 video explains it well.

Its docs are only provided in XML format. I have run this documentation in Sandcastle to allow it to be in a more readable format. Unzip the docs archive and look for index.html.

Among many other goodies, it provides the expected ForEach implementation. It allows you to write code like this:

int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8 };

numbers.ForEach(x => Console.WriteLine(x*x));

Convert Long into Integer

Integer i = theLong != null ? theLong.intValue() : null;

or if you don't need to worry about null:

// auto-unboxing does not go from Long to int directly, so
Integer i = (int) (long) theLong;

And in both situations, you might run into overflows (because a Long can store a wider range than an Integer).

Java 8 has a helper method that checks for overflow (you get an exception in that case):

Integer i = theLong == null ? null : Math.toIntExact(theLong);

unary operator expected in shell script when comparing null value with string

Why all people want to use '==' instead of simple '=' ? It is bad habit! It used only in [[ ]] expression. And in (( )) too. But you may use just = too! It work well in any case. If you use numbers, not strings use not parcing to strings and then compare like strings but compare numbers. like that

let -i i=5 # garantee that i is nubmber
test $i -eq 5 && echo "$i is equal 5" || echo "$i not equal 5"

It's match better and quicker. I'm expert in C/C++, Java, JavaScript. But if I use bash i never use '==' instead '='. Why you do so?

Set scroll position

Also worth noting window.scrollBy(dx,dy) (ref)

How to perform keystroke inside powershell?

Also the $wshell = New-Object -ComObject wscript.shell; helped a script that was running in the background, it worked fine with just but adding $wshell. fixed it from running as background! [Microsoft.VisualBasic.Interaction]::AppActivate("App Name")

Comparing two hashmaps for equal values and same key sets?

/* JAVA 8 using streams*/
   public static void main(String args[])
    {
        Map<Integer, Boolean> map = new HashMap<Integer, Boolean>();
        map.put(100, true);
        map.put(1011, false);
        map.put(1022, false);

        Map<Integer, Boolean> map1 = new HashMap<Integer, Boolean>();
        map1.put(100, false);
        map1.put(101, false);
        map1.put(102, false);

        boolean b = map.entrySet().stream().filter(value -> map1.entrySet().stream().anyMatch(value1 -> (value1.getKey() == value.getKey() && value1.getValue() == value.getValue()))).findAny().isPresent();
        System.out.println(b);
    }

Is there a destructor for Java?

Because Java is a garbage collected language you cannot predict when (or even if) an object will be destroyed. Hence there is no direct equivalent of a destructor.

There is an inherited method called finalize, but this is called entirely at the discretion of the garbage collector. So for classes that need to explicitly tidy up, the convention is to define a close method and use finalize only for sanity checking (i.e. if close has not been called do it now and log an error).

There was a question that spawned in-depth discussion of finalize recently, so that should provide more depth if required...

How to use org.apache.commons package?

You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.

For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.

If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.

For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.

If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.

How can I insert values into a table, using a subquery with more than one result?

If you are inserting one record into your table, you can do

INSERT INTO yourTable 
VALUES(value1, value2)

But since you want to insert more than one record, you can use a SELECT FROM in your SQL statement.

so you will want to do this:

INSERT INTO prices (group, id, price) 
SELECT 7, articleId, 1.50
from article 
WHERE name LIKE 'ABC%'

Is there an equivalent to background-size: cover and contain for image elements?

Assuming you can arrange to have a container element you wish to fill, this appears to work, but feels a bit hackish. In essence, I just use min/max-width/height on a larger area and then scale that area back into the original dimensions.

_x000D_
_x000D_
.container {_x000D_
  width: 800px;_x000D_
  height: 300px;_x000D_
  border: 1px solid black;_x000D_
  overflow:hidden;_x000D_
  position:relative;_x000D_
}_x000D_
.container.contain img {_x000D_
  position: absolute;_x000D_
  left:-10000%; right: -10000%; _x000D_
  top: -10000%; bottom: -10000%;_x000D_
  margin: auto auto;_x000D_
  max-width: 10%;_x000D_
  max-height: 10%;_x000D_
  -webkit-transform:scale(10);_x000D_
  transform: scale(10);_x000D_
}_x000D_
.container.cover img {_x000D_
  position: absolute;_x000D_
  left:-10000%; right: -10000%; _x000D_
  top: -10000%; bottom: -10000%;_x000D_
  margin: auto auto;_x000D_
  min-width: 1000%;_x000D_
  min-height: 1000%;_x000D_
  -webkit-transform:scale(0.1);_x000D_
  transform: scale(0.1);_x000D_
}
_x000D_
<h1>contain</h1>_x000D_
  <div class="container contain">_x000D_
    <img _x000D_
       src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" _x000D_
       />_x000D_
    <!-- 366x200 -->_x000D_
  </div>_x000D_
  <h1>cover</h1>_x000D_
  <div class="container cover">_x000D_
    <img _x000D_
       src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" _x000D_
       />_x000D_
    <!-- 366x200 -->_x000D_
  </div>
_x000D_
_x000D_
_x000D_

Where can I view Tomcat log files in Eclipse?

I'm not sure if you were after catalina.out or one of the other logs produced by Tomcat.

But, if you're after the catalina.out log file then follow the directions below:

  • In the servers tab, double-click on the Tomcat Server. You will get a screen called Overview.

  • Click on "Open launch configuration". Click on the "Common" tab.

  • Towards the bottom of the screen you can check the "File" checkbox and then specify a file that can be used to log your console (catalina.out) output.

  • Finally, restart the Tomcat server.

How do you make an anchor link non-clickable or disabled?

You could use the onclick event to disable the click action:

<a href='' id='ThisLink' onclick='return false'>some text</a>

Or you could just use something other than an <a> tag.

Finding the max value of an attribute in an array of objects

I'd like to explain the terse accepted answer step-by-step:

_x000D_
_x000D_
var objects = [{ x: 3 }, { x: 1 }, { x: 2 }];_x000D_
_x000D_
// array.map lets you extract an array of attribute values_x000D_
var xValues = objects.map(function(o) { return o.x; });_x000D_
// es6_x000D_
xValues = Array.from(objects, o => o.x);_x000D_
_x000D_
// function.apply lets you expand an array argument as individual arguments_x000D_
// So the following is equivalent to Math.max(3, 1, 2)_x000D_
// The first argument is "this" but since Math.max doesn't need it, null is fine_x000D_
var xMax = Math.max.apply(null, xValues);_x000D_
// es6_x000D_
xMax = Math.max(...xValues);_x000D_
_x000D_
// Finally, to find the object that has the maximum x value (note that result is array):_x000D_
var maxXObjects = objects.filter(function(o) { return o.x === xMax; });_x000D_
_x000D_
// Altogether_x000D_
xMax = Math.max.apply(null, objects.map(function(o) { return o.x; }));_x000D_
var maxXObject = objects.filter(function(o) { return o.x === xMax; })[0];_x000D_
// es6_x000D_
xMax = Math.max(...Array.from(objects, o => o.x));_x000D_
maxXObject = objects.find(o => o.x === xMax);_x000D_
_x000D_
_x000D_
document.write('<p>objects: ' + JSON.stringify(objects) + '</p>');_x000D_
document.write('<p>xValues: ' + JSON.stringify(xValues) + '</p>');_x000D_
document.write('<p>xMax: ' + JSON.stringify(xMax) + '</p>');_x000D_
document.write('<p>maxXObjects: ' + JSON.stringify(maxXObjects) + '</p>');_x000D_
document.write('<p>maxXObject: ' + JSON.stringify(maxXObject) + '</p>');
_x000D_
_x000D_
_x000D_

Further information:

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

Kotlin version:

Use these extensions with infix functions that simplify later calls

infix fun View.below(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.BELOW, view.id)
}

infix fun View.leftOf(view: View) {
    (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.LEFT_OF, view.id)
}

infix fun View.alightParentRightIs(aligned: Boolean) {
    val layoutParams = this.layoutParams as? RelativeLayout.LayoutParams
    if (aligned) {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT)
    } else {
        (this.layoutParams as? RelativeLayout.LayoutParams)?.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, 0)
    }
    this.layoutParams = layoutParams
}

Then use them as infix functions calls:

view1 below view2
view1 leftOf view2
view1 alightParentRightIs true

Or you can use them as normal functions:

view1.below(view2)
view1.leftOf(view2)
view1.alightParentRightIs(true)

Regex to check whether a string contains only numbers

You need the * so it says "zero or more of the previous character" and this should do it:

var reg = new RegExp('^\\d*$');

Replace part of a string in Python?

You can easily use .replace() as also previously described. But it is also important to keep in mind that strings are immutable. Hence if you do not assign the change you are making to a variable, then you will not see any change. Let me explain by;

    >>stuff = "bin and small"
    >>stuff.replace('and', ',')
    >>print(stuff)
    "big and small" #no change

To observe the change you want to apply, you can assign same or another variable;

    >>stuff = "big and small"
    >>stuff = stuff.replace("and", ",")   
    >>print(stuff)
    'big, small'

Linq select objects in list where exists IN (A,B,C)

var statuses = new[] { "A", "B", "C" };

var filteredOrders = from order in orders.Order
                             where statuses.Contains(order.StatusCode)
                             select order;

How to customize Bootstrap 3 tab color

On the selector .nav-tabs > li > a:hover add !important to the background-color.

_x000D_
_x000D_
.nav-tabs{_x000D_
  background-color:#161616;_x000D_
}_x000D_
.tab-content{_x000D_
    background-color:#303136;_x000D_
    color:#fff;_x000D_
    padding:5px_x000D_
}_x000D_
.nav-tabs > li > a{_x000D_
  border: medium none;_x000D_
}_x000D_
.nav-tabs > li > a:hover{_x000D_
  background-color: #303136 !important;_x000D_
    border: medium none;_x000D_
    border-radius: 0;_x000D_
    color:#fff;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>_x000D_
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<ul class="nav nav-tabs" id="myTab">_x000D_
    <li class="active"><a data-toggle="tab" href="#search">SEARCH</a></li>_x000D_
    <li><a data-toggle="tab" href="#advanced">ADVANCED</a></li>_x000D_
</ul>_x000D_
<div class="tab-content">_x000D_
    <div id="search" class="tab-pane fade in active">_x000D_
        Aliquip placeat salvia cillum iphone. Seitan aliquip quis cardigan american apparel,_x000D_
        butcher voluptate nisi qui._x000D_
    </div>_x000D_
    <div id="advanced" class="tab-pane fade">_x000D_
        Vestibulum nec erat eu nulla rhoncus fringilla ut non neque. Vivamus nibh urna._x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

Master:

mysqldump -u root -p --all-databases --master-data | gzip > /tmp/dump.sql.gz  

scp master:/tmp/dump.sql.gz slave:/tmp/ Move dump file to slave server

Slave:

STOP SLAVE;

zcat /tmp/dump.sql.gz | mysql -u root -p

START SLAVE;
SHOW SLAVE STATUS;  

NOTE:
On master you can run SET GLOBAL expire_logs_days = 3 to keep binlogs for 3 days in case of slave issues.

How to get the public IP address of a user in C#

In MVC IP can be obtained by the following Code

string ipAddress = Request.ServerVariables["REMOTE_ADDR"];

How do I measure a time interval in C?

The following is a group of versatile C functions for timer management based on the gettimeofday() system call. All the timer properties are contained in a single ticktimer struct - the interval you want, the total running time since the timer initialization, a pointer to the desired callback you want to call, the number of times the callback was called. A callback function would look like this:

void your_timer_cb (struct ticktimer *t) {
  /* do your stuff here */
}

To initialize and start a timer, call ticktimer_init(your_timer, interval, TICKTIMER_RUN, your_timer_cb, 0).

In the main loop of your program call ticktimer_tick(your_timer) and it will decide whether the appropriate amount of time has passed to invoke the callback.

To stop a timer, just call ticktimer_ctl(your_timer, TICKTIMER_STOP).

ticktimer.h:

#ifndef __TICKTIMER_H
#define __TICKTIMER_H

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>

#define TICKTIMER_STOP         0x00
#define TICKTIMER_UNCOMPENSATE 0x00
#define TICKTIMER_RUN          0x01
#define TICKTIMER_COMPENSATE   0x02

struct ticktimer {
  u_int64_t tm_tick_interval;
  u_int64_t tm_last_ticked;
  u_int64_t tm_total;
  unsigned ticks_total;
  void (*tick)(struct ticktimer *);
  unsigned char flags;
  int id;
};

void ticktimer_init (struct ticktimer *, u_int64_t, unsigned char, void (*)(struct ticktimer *), int);
unsigned ticktimer_tick (struct ticktimer *);
void ticktimer_ctl (struct ticktimer *, unsigned char);
struct ticktimer *ticktimer_alloc (void);
void ticktimer_free (struct ticktimer *);
void ticktimer_tick_all (void);

#endif

ticktimer.c:

#include "ticktimer.h"

#define TIMER_COUNT 100

static struct ticktimer timers[TIMER_COUNT];
static struct timeval tm;

/*!
  @brief
    Initializes/sets the ticktimer struct.

  @param timer
    Pointer to ticktimer struct.
  @param interval
    Ticking interval in microseconds.
  @param flags
    Flag bitmask. Use TICKTIMER_RUN | TICKTIMER_COMPENSATE
    to start a compensating timer; TICKTIMER_RUN to start
    a normal uncompensating timer.
  @param tick
    Ticking callback function.
  @param id
    Timer ID. Useful if you want to distinguish different
    timers within the same callback function.
*/
void ticktimer_init (struct ticktimer *timer, u_int64_t interval, unsigned char flags, void (*tick)(struct ticktimer *), int id) {
  gettimeofday(&tm, NULL);
  timer->tm_tick_interval = interval;
  timer->tm_last_ticked = tm.tv_sec * 1000000 + tm.tv_usec;
  timer->tm_total = 0;
  timer->ticks_total = 0;
  timer->tick = tick;
  timer->flags = flags;
  timer->id = id;
}

/*!
  @brief 
    Checks the status of a ticktimer and performs a tick(s) if 
    necessary.

  @param timer
    Pointer to ticktimer struct.

  @return
    The number of times the timer was ticked.
*/
unsigned ticktimer_tick (struct ticktimer *timer) {
  register typeof(timer->tm_tick_interval) now;
  register typeof(timer->ticks_total) nticks, i;

  if (timer->flags & TICKTIMER_RUN) {
    gettimeofday(&tm, NULL);
    now = tm.tv_sec * 1000000 + tm.tv_usec;

    if (now >= timer->tm_last_ticked + timer->tm_tick_interval) {
      timer->tm_total += now - timer->tm_last_ticked;

      if (timer->flags & TICKTIMER_COMPENSATE) {
        nticks = (now - timer->tm_last_ticked) / timer->tm_tick_interval;
        timer->tm_last_ticked = now - ((now - timer->tm_last_ticked) % timer->tm_tick_interval);

        for (i = 0; i < nticks; i++) {
          timer->tick(timer);
          timer->ticks_total++;

          if (timer->tick == NULL) {
            break;
          }
        }

        return nticks;
      } else {
        timer->tm_last_ticked = now;
        timer->tick(timer);
        timer->ticks_total++;
        return 1;
      }
    }
  }

  return 0;
}

/*!
  @brief
    Controls the behaviour of a ticktimer.

  @param timer
    Pointer to ticktimer struct.
  @param flags
    Flag bitmask.
*/
inline void ticktimer_ctl (struct ticktimer *timer, unsigned char flags) {
  timer->flags = flags;
}

/*!
  @brief
    Allocates a ticktimer struct from an internal
    statically allocated list.

  @return
    Pointer to the newly allocated ticktimer struct
    or NULL when no more space is available.
*/
struct ticktimer *ticktimer_alloc (void) {
  register int i;

  for (i = 0; i < TIMER_COUNT; i++) {
    if (timers[i].tick == NULL) {
      return timers + i;
    }
  }

  return NULL;
}

/*!
  @brief
    Marks a previously allocated ticktimer struct as free.

  @param timer
    Pointer to ticktimer struct, usually returned by 
    ticktimer_alloc().
*/
inline void ticktimer_free (struct ticktimer *timer) {
  timer->tick = NULL;
}

/*!
  @brief
    Checks the status of all allocated timers from the 
    internal list and performs ticks where necessary.

  @note
    Should be called in the main loop.
*/
inline void ticktimer_tick_all (void) {
  register int i;

  for (i = 0; i < TIMER_COUNT; i++) {
    if (timers[i].tick != NULL) {
      ticktimer_tick(timers + i);
    }
  }
}

SQL comment header examples

set timing on <br>
set linesize 180<br>
spool template.log

/*<br>
##########################################################################<br>
-- Name : Template.sql<br>
-- Date             : (sysdate) <br>
-- Author           :   Duncan van der Zalm - dvdzalm<br>
-- Company          :   stanDaarD-Z.nl<br>
-- Purpose          :   <br>
-- Usage        sqlplus <br>
-- Impact   :<br>
-- Required grants  :   sel on A, upd on B, drop on C<br>
-- Called by        :   some other process<br
##########################################################################<br>
-- ver  user    date        change  <br>
-- 1.0  DDZ 20110622    initial<br>
##########################################################################<br>
*/<br>

sho user<br>

select name from v$database;

select to_char(sysdate, 'Day DD Month yyyy HH24:MI:SS') "Start time"
from dual
;


-- script


select to_char(sysdate, 'Day DD Month yyyy HH24:MI:SS') "End time"
from dual
;

spool off

c++ array assignment of multiple values

const static int newvals[] = {34,2,4,5,6};

std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);

Can I set enum start value in Java?

Java enums are not like C or C++ enums, which are really just labels for integers.

Java enums are implemented more like classes - and they can even have multiple attributes.

public enum Ids {
    OPEN(100), CLOSE(200);

    private final int id;
    Ids(int id) { this.id = id; }
    public int getValue() { return id; }
}

The big difference is that they are type-safe which means you don't have to worry about assigning a COLOR enum to a SIZE variable.

See http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html for more.

How to know whether refresh button or browser back button is clicked in Firefox

Use for on refresh event

window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};

https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload?redirectlocale=en-US&redirectslug=DOM%2Fwindow.onbeforeunload

And

$(window).unload(function() {
      alert('Handler for .unload() called.');
});

@ variables in Ruby on Rails

A tutorial about What is Variable Scope? presents some details quite well, just enclose the related here.


+------------------+----------------------+
| Name Begins With |    Variable Scope    |
+------------------+----------------------+
| $                | A global variable    |
| @                | An instance variable |
| [a-z] or _       | A local variable     |
| [A-Z]            | A constant           |
| @@               | A class variable     |
+------------------+----------------------+

Printing an int list in a single line python3

you can use more elements "end" in print:

for iValue in arr:
   print(iValue, end = ", ");

Set and Get Methods in java?

I think you want something like this:

public class Person {

  private int age;

  //public method to get the age variable
  public int getAge(){
       return this.age
  }

  //public method to set the age variable
  public void setAge(int age){
       this.age = age;
  }
}

You're simply calling such a method on an object instance. Such methods are useful especially if setting something is supposed to have side effects. E.g. if you want to react to certain events like:

  public void setAge(int age){

       this.age = age;

       double averageCigarettesPerYear = this.smokedCigarettes * 1.0 / age;

       if(averageCigarettesPerYear >= 7300.0) {
           this.eventBus.fire(new PersonSmokesTooMuchEvent(this));
       }
  }

Of course this can be dangerous if somebody forgets to call setAge(int) where he should and sets age directly using this.age.

HTML Mobile -forcing the soft keyboard to hide

example how i made it , After i fill a Maximum length it will blur from my Field (and the Keyboard will disappear ) , if you have more than one field , you can just add the line that i add '//'

var MaxLength = 8;
    $(document).ready(function () {
        $('#MyTB').keyup(function () {
            if ($(this).val().length >= MaxLength) {
               $('#MyTB').blur();
             //  $('#MyTB2').focus();
         }
          }); });

How to make a view with rounded corners?

To create round corner image using com.google.android.material:material:1.2.0-beta01

 float radius = context.getResources().getDimension(R.dimen.border_radius_hug);
    shapeAppearanceModel = new ShapeAppearanceModel()
            .toBuilder()
            .setAllCorners(CornerFamily.ROUNDED,radius)
            .build();

imageView.setShapeAppearanceModel(shapeAppearanceModel)

or if you want to use it in xml file:

  <com.google.android.material.imageview.ShapeableImageView
            android:id="@+id/thumb"
            android:layout_width="80dp"
            android:layout_height="60dp"
            app:shapeAppearanceOverlay="@style/circleImageView"
            />

in style.xml add this:

<style name="circleImageView" parent="">
      <item name="cornerFamily">rounded</item>
      <item name="cornerSize">10%</item>
</style>

Regular expression for matching latitude/longitude coordinates?

This would work for format like this: 31 ? 37.4' E

^[-]?\d{1,2}[ ]*?[ ]*\d{1,2}\.?\d{1,2}[ ]*\x27[ ]*\w$

How do I copy an entire directory of files into an existing directory using Python?

This is inspired from the original best answer provided by atzz, I just added replace file / folder logic. So it doesn't actually merge, but deletes the existing file/ folder and copies the new one:

import shutil
import os
def copytree(src, dst, symlinks=False, ignore=None):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.exists(d):
            try:
                shutil.rmtree(d)
            except Exception as e:
                print e
                os.unlink(d)
        if os.path.isdir(s):
            shutil.copytree(s, d, symlinks, ignore)
        else:
            shutil.copy2(s, d)
    #shutil.rmtree(src)

Uncomment the rmtree to make it a move function.

Java, return if trimmed String in List contains String

With Java 8 Stream API:

List<String> myList = Arrays.asList("  A", "B  ", "  C  ");
return myList.stream().anyMatch(str -> str.trim().equals("B"));

Getting "project" nuget configuration is invalid error

Simply restarting Visual Studio worked for me.

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

Make sure you have a jdk setup. To do this, create a new project and then go to file -> project structure. From there you can add a new jdk. Once that is setup, go back to your gradle project and you should have a jdk to select in the 'Gradle JVM' field.

jQuery - Detecting if a file has been selected in the file input

I'd suggest try the change event? test to see if it has a value if it does then you can continue with your code. jQuery has

.bind("change", function(){ ... });

Or

.change(function(){ ... }); 

which are equivalents.

http://api.jquery.com/change/

for a unique selector change your name attribute to id and then jQuery("#imafile") or a general jQuery('input[type="file"]') for all the file inputs

Convert seconds to HH-MM-SS with JavaScript?

I just wanted to give a little explanation to the nice answer above:

var totalSec = new Date().getTime() / 1000;
var hours = parseInt( totalSec / 3600 ) % 24;
var minutes = parseInt( totalSec / 60 ) % 60;
var seconds = totalSec % 60;

var result = (hours < 10 ? "0" + hours : hours) + "-" + (minutes < 10 ? "0" + minutes : minutes) + "-" + (seconds  < 10 ? "0" + seconds : seconds);

On the second line, since there are 3600 seconds in 1 hour, we divide the total number of seconds by 3600 to get the total number of hours. We use parseInt to strip off any decimal. If totalSec was 12600 (3 and half hours), then parseInt( totalSec / 3600 ) would return 3, since we will have 3 full hours. Why do we need the % 24 in this case? If we exceed 24 hours, let's say we have 25 hours (90000 seconds), then the modulo here will take us back to 1 again, rather than returning 25. It is confining the result within a 24 hour limit, since there are 24 hours in one day.

When you see something like this:

25 % 24

Think of it like this:

25 mod 24 or what is the remainder when we divide 25 by 24

How to detect Ctrl+V, Ctrl+C using JavaScript?

There is some ways to prevent it.

However the user will be always able to turn the javascript off or just look on the source code of the page.

Some examples (require jQuery)

/**
* Stop every keystroke with ctrl key pressed
*/
$(".textbox").keydown(function(){
    if (event.ctrlKey==true) {
        return false;
    }
});

/**
* Clear all data of clipboard on focus
*/
$(".textbox").focus(function(){
    if ( window.clipboardData ) {
        window.clipboardData.setData('text','');
    }
});

/**
* Block the paste event
*/
$(".textbox").bind('paste',function(e){return false;});

Edit: How Tim Down said, this functions are all browser dependents.

What is a blob URL and why it is used?

What is blob url? Why it is used?

BLOB is just byte sequence. Browser recognize it as byte stream. It is used to get byte stream from source.

A Blob object represents a file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

Can i make my own blob url on a server?

Yes you can there are serveral ways to do so for example try http://php.net/manual/en/function.ibase-blob-echo.php

Read more on

Create a git patch from the uncommitted changes in the current working directory

To create a patch with both modified & new files (staged) you can run:

git diff HEAD > file_name.patch

Binding value to style

Turns out the binding of style to a string doesn't work. The solution would be to bind the background of the style.

 <div class="circle" [style.background]="color">

How can I start an interactive console for Perl?

Not only did Matt Trout write an article about a REPL, he actually wrote one - Devel::REPL

I've used it a bit and it works fairly well, and it's under active development.

BTW, I have no idea why someone modded down the person who mentioned using "perl -e" from the console. This isn't really a REPL, true, but it's fantastically useful, and I use it all the time.

How to get ID of the last updated row in MySQL?

ID of the last updated row is the same ID that you use in the 'updateQuery' to found & update that row. So, just save(call) that ID on anyway you want.

last_insert_id() depends of the AUTO_INCREMENT, but the last updated ID not.

SyntaxError: import declarations may only appear at top level of a module

I got this on Firefox (FF58). I fixed this with:

  1. It is still experimental on Firefox (from v54): You have to set to true the variable dom.moduleScripts.enabled in about:config

Source: Import page on mozilla (See Browser compatibility)

  1. Add type="module" to your script tag where you import the js file

<script type="module" src="appthatimports.js"></script>

  1. Import files have to be prefixed (./, /, ../ or http:// before)

import * from "./mylib.js"

For more examples, this blog post is good.

How to multiply a BigDecimal by an integer in Java

You have a lot of type-mismatches in your code such as trying to put an int value where BigDecimal is required. The corrected version of your code:

public class Payment
{
    BigDecimal itemCost  = BigDecimal.ZERO;
    BigDecimal totalCost = BigDecimal.ZERO;

    public BigDecimal calculateCost(int itemQuantity, BigDecimal itemPrice)
    {
        itemCost  = itemPrice.multiply(new BigDecimal(itemQuantity));
        totalCost = totalCost.add(itemCost);
        return totalCost;
    }
}

browser.msie error after update to jQuery 1.9.1

$.browser was deprecated in version 1.3 and removed in 1.9

You can verify this by viewing the documentation.

How to detect when WIFI Connection has been established in Android?

I used this code:

public class MainActivity extends Activity
    {
    .
    .
    .
    @Override
    protected void onCreate(Bundle savedInstanceState)
        {
        super.onCreate(savedInstanceState);
        .
        .
        .
        }

    @Override
    protected void onResume()
        {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        registerReceiver(broadcastReceiver, intentFilter);  
        }

    @Override
    protected void onPause()
        {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
        }

    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
        {
        @Override
        public void onReceive(Context context, Intent intent)
            {
            final String action = intent.getAction();
            if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION))
                {
                if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false))
                    {
                    // wifi is enabled
                    }
                else
                    {
                    // wifi is disabled
                    }
                }
            }
        };
    }

How can I create a Java method that accepts a variable number of arguments?

Take a look at the Java guide on varargs.

You can create a method as shown below. Simply call System.out.printf instead of System.out.println(String.format(....

public static void print(String format, Object... args) {
    System.out.printf(format, args);
}

Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:

import static java.lang.System.out;

out.printf("Numer of apples: %d", 10);

Post order traversal of binary tree without recursion

void postorder_stack(Node * root){
    stack ms;
    ms.top = -1;
    if(root == NULL) return ;

    Node * temp ;
    push(&ms,root);
    Node * prev = NULL;
    while(!is_empty(ms)){
        temp = peek(ms);
        /* case 1. We are nmoving down the tree. */
        if(prev == NULL || prev->left == temp || prev->right == temp){
             if(temp->left)
                  push(&ms,temp->left);
             else if(temp->right)
                  push(&ms,temp->right);
             else {
                /* If node is leaf node */
                   printf("%d ", temp->value);
                   pop(&ms);
             }
         }
         /* case 2. We are moving up the tree from left child */
         if(temp->left == prev){
              if(temp->right)
                   push(&ms,temp->right);
              else
                   printf("%d ", temp->value);
         }

        /* case 3. We are moving up the tree from right child */
         if(temp->right == prev){
              printf("%d ", temp->value);
              pop(&ms);
         }
         prev = temp;
      }

}

Difference between numpy.array shape (R, 1) and (R,)

For its base array class, 2d arrays are no more special than 1d or 3d ones. There are some operations the preserve the dimensions, some that reduce them, other combine or even expand them.

M=np.arange(9).reshape(3,3)
M[:,0].shape # (3,) selects one column, returns a 1d array
M[0,:].shape # same, one row, 1d array
M[:,[0]].shape # (3,1), index with a list (or array), returns 2d
M[:,[0,1]].shape # (3,2)

In [20]: np.dot(M[:,0].reshape(3,1),np.ones((1,3)))

Out[20]: 
array([[ 0.,  0.,  0.],
       [ 3.,  3.,  3.],
       [ 6.,  6.,  6.]])

In [21]: np.dot(M[:,[0]],np.ones((1,3)))
Out[21]: 
array([[ 0.,  0.,  0.],
       [ 3.,  3.,  3.],
       [ 6.,  6.,  6.]])

Other expressions that give the same array

np.dot(M[:,0][:,np.newaxis],np.ones((1,3)))
np.dot(np.atleast_2d(M[:,0]).T,np.ones((1,3)))
np.einsum('i,j',M[:,0],np.ones((3)))
M1=M[:,0]; R=np.ones((3)); np.dot(M1[:,None], R[None,:])

MATLAB started out with just 2D arrays. Newer versions allow more dimensions, but retain the lower bound of 2. But you still have to pay attention to the difference between a row matrix and column one, one with shape (1,3) v (3,1). How often have you written [1,2,3].'? I was going to write row vector and column vector, but with that 2d constraint, there aren't any vectors in MATLAB - at least not in the mathematical sense of vector as being 1d.

Have you looked at np.atleast_2d (also _1d and _3d versions)?

Cannot open solution file in Visual Studio Code

But you can open the folder with the .SLN in to edit the code in the project, which will detect the .SLN to select the library that provides Intellisense.

Using FileSystemWatcher to monitor a directory

You did not supply the file handling code, but I assume you made the same mistake everyone does when first writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time for the file to be finished. Take a file size of 1 GB for example. The file may be created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised at creation time and you need to wait for the file to be ready to be copied.

You can wait for a file to be ready by using this function in a loop.

Installing J2EE into existing eclipse IDE

Go to Help -> Install new softwares-> add -> paste this link in location box http://download.eclipse.org/webtools/repository/luna/ install all new versions..

How can I get last characters of a string

The Substr function allows you to use a minus to get the last character.

var string = "hello";
var last = string.substr(-1);

It's very flexible. For example:

// Get 2 characters, 1 character from end
// The first part says how many characters
// to go back and the second says how many
// to go forward. If you don't say how many
// to go forward it will include everything
var string = "hello!";
var lasttwo = string.substr(-3,2);
// = "lo"

How to parse this string in Java?

 String result;
 String str = "/usr/local/apache2/resumes/dir1/dir2/dir3/dir4";
 String regex ="(dir)+[\\d]";
 Matcher matcher = Pattern.compile( regex ).matcher( str);
  while (matcher.find( ))
  {
  result = matcher.group();     
  System.out.println(result);                 
}

output-- dir1 dir2 dir3 dir4

Using the && operator in an if statement

So to make your expression work, changing && for -a will do the trick.

It is correct like this:

 if [ -f $VAR1 ] && [ -f $VAR2 ] && [ -f $VAR3 ]
 then  ....

or like

 if [[ -f $VAR1 && -f $VAR2 && -f $VAR3 ]]
 then  ....

or even

 if [ -f $VAR1 -a -f $VAR2 -a -f $VAR3 ]
 then  ....

You can find further details in this question bash : Multiple Unary operators in if statement and some references given there like What is the difference between test, [ and [[ ?.

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

Also take care not to write

google.maps.event.addDomListener(window, "load", init())

correct:

google.maps.event.addDomListener(window, "load", init)

Update records in table from CTE

WITH CTE_DocTotal (DocTotal, InvoiceNumber)
AS
(
    SELECT  InvoiceNumber,
            SUM(Sale + VAT) AS DocTotal
    FROM    PEDI_InvoiceDetail
    GROUP BY InvoiceNumber
)    
UPDATE PEDI_InvoiceDetail
SET PEDI_InvoiceDetail.DocTotal = CTE_DocTotal.DocTotal
FROM CTE_DocTotal
INNER JOIN PEDI_InvoiceDetail ON ...

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

If you don't necessarily need the resources, use parseColor(String):
Color.parseColor("#cc0066")

Usage of $broadcast(), $emit() And $on() in AngularJS

$emit

It dispatches an event name upwards through the scope hierarchy and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $emit was called. The event traverses upwards toward the root scope and calls all registered listeners along the way. The event will stop propagating if one of the listeners cancels it.

$broadcast

It dispatches an event name downwards to all child scopes (and their children) and notify to the registered $rootScope.Scope listeners. The event life cycle starts at the scope on which $broadcast was called. All listeners for the event on this scope get notified. Afterwards, the event traverses downwards toward the child scopes and calls all registered listeners along the way. The event cannot be canceled.

$on

It listen on events of a given type. It can catch the event dispatched by $broadcast and $emit.


Visual demo:

Demo working code, visually showing scope tree (parent/child relationship):
http://plnkr.co/edit/am6IDw?p=preview

Demonstrates the method calls:

  $scope.$on('eventEmitedName', function(event, data) ...
  $scope.broadcastEvent
  $scope.emitEvent

TypeError: a bytes-like object is required, not 'str'

Simply replace message parameter passed in clientSocket.sendto(message,(serverName, serverPort)) to clientSocket.sendto(message.encode(),(serverName, serverPort)). Then you would successfully run in in python3

How to read appSettings section in the web.config file?

Add namespace

using System.Configuration;

and in place of

ConfigurationSettings.AppSettings

you should use

ConfigurationManager.AppSettings

String path = ConfigurationManager.AppSettings["configFile"];

How can I change the color of a Google Maps marker?

enter image description here enter image description here Material Design

EDITED MARCH 2019 now with programmatic pin color,

PURE JAVASCRIPT, NO IMAGES, SUPPORTS LABELS

no longer relies on deprecated Charts API

    var pinColor = "#FFFFFF";
    var pinLabel = "A";

    // Pick your pin (hole or no hole)
    var pinSVGHole = "M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z";
    var labelOriginHole = new google.maps.Point(12,15);
    var pinSVGFilled = "M 12,2 C 8.1340068,2 5,5.1340068 5,9 c 0,5.25 7,13 7,13 0,0 7,-7.75 7,-13 0,-3.8659932 -3.134007,-7 -7,-7 z";
    var labelOriginFilled =  new google.maps.Point(12,9);


    var markerImage = {  // https://developers.google.com/maps/documentation/javascript/reference/marker#MarkerLabel
        path: pinSVGFilled,
        anchor: new google.maps.Point(12,17),
        fillOpacity: 1,
        fillColor: pinColor,
        strokeWeight: 2,
        strokeColor: "white",
        scale: 2,
        labelOrigin: labelOriginFilled
    };
    var label = {
        text: pinLabel,
        color: "white",
        fontSize: "12px",
    }; // https://developers.google.com/maps/documentation/javascript/reference/marker#Symbol
    this.marker        = new google.maps.Marker({
        map: map.MapObject,
        //OPTIONAL: label: label,
        position: this.geographicCoordinates,
        icon: markerImage,
        //OPTIONAL: animation: google.maps.Animation.DROP,
    });

Table fixed header and scrollable body

Likely you'll get multiple tables on one page, therefore you need CSS classes. Please find a modified @giulio's solution for that.

Just declare it in table:

<table class="table table-striped header-fixed"></table>

CSS

.header-fixed {
    width: 100% 
}

.header-fixed > thead,
.header-fixed > tbody,
.header-fixed > thead > tr,
.header-fixed > tbody > tr,
.header-fixed > thead > tr > th,
.header-fixed > tbody > tr > td {
    display: block;
}

.header-fixed > tbody > tr:after,
.header-fixed > thead > tr:after {
    content: ' ';
    display: block;
    visibility: hidden;
    clear: both;
}

.header-fixed > tbody {
    overflow-y: auto;
    height: 150px;
}

.header-fixed > tbody > tr > td,
.header-fixed > thead > tr > th {
    width: 20%;
    float: left;
}

Be aware that current implementation suits five columns only. If you need a different number, change the width parameter from 20% to *100% / number_of_columns*.

How to get a list of all valid IP addresses in a local network?

Try following steps:

  1. Type ipconfig (or ifconfig on Linux) at command prompt. This will give you the IP address of your own machine. For example, your machine's IP address is 192.168.1.6. So your broadcast IP address is 192.168.1.255.
  2. Ping your broadcast IP address ping 192.168.1.255 (may require -b on Linux)
  3. Now type arp -a. You will get the list of all IP addresses on your segment.

Difference between DOM parentNode and parentElement

Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element or null. Properties without can return any other kind of node.

console.log(document.body.parentNode, "is body's parent node");    // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>

var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null

Get table name by constraint name

SELECT constraint_name, constraint_type, column_name
from user_constraints natural join user_cons_columns
where table_name = "my_table_name";

will give you what you need

Remove Project from Android Studio

  1. Go to your Android project directory

    C:\Users\HP\AndroidStudioProjects
    

    Screenshot

  2. Delete which one you need to delete

  3. Restart Android Studio

GROUP BY to combine/concat a column

A good question. Should tell you it took some time to crack this one. Here is my result.

DECLARE @TABLE TABLE
(  
ID INT,  
USERS VARCHAR(10),  
ACTIVITY VARCHAR(10),  
PAGEURL VARCHAR(10)  
)

INSERT INTO @TABLE  
VALUES  (1, 'Me', 'act1', 'ab'),
        (2, 'Me', 'act1', 'cd'),
        (3, 'You', 'act2', 'xy'),
        (4, 'You', 'act2', 'st')


SELECT T1.USERS, T1.ACTIVITY,   
        STUFF(  
        (  
        SELECT ',' + T2.PAGEURL  
        FROM @TABLE T2  
        WHERE T1.USERS = T2.USERS  
        FOR XML PATH ('')  
        ),1,1,'')  
FROM @TABLE T1  
GROUP BY T1.USERS, T1.ACTIVITY

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

Personally i prefer the format function, allows you to simply change the date part very easily.

     declare @format varchar(100) = 'yyyy/MM/dd'
     select 
        format(the_date,@format), 
        sum(myfield) 
     from mytable 
     group by format(the_date,@format) 
     order by format(the_date,@format) desc;

CSS getting text in one line rather than two

The best way to use is white-space: nowrap; This will align the text to one line.

Arrow operator (->) usage in C

#include<stdio.h>

int main()
{
    struct foo
    {
        int x;
        float y;
    } var1;
    struct foo var;
    struct foo* pvar;

    pvar = &var1;
    /* if pvar = &var; it directly 
       takes values stored in var, and if give  
       new > values like pvar->x = 6; pvar->y = 22.4; 
       it modifies the values of var  
       object..so better to give new reference. */
    var.x = 5;
    (&var)->y = 14.3;
    printf("%i - %.02f\n", var.x, (&var)->y);

    pvar->x = 6;
    pvar->y = 22.4;
    printf("%i - %.02f\n", pvar->x, pvar->y);

    return 0;
}

Create an enum with string values

I have tried in TypeScript 1.5 like below and it's worked for me

module App.Constants {
   export enum e{
        Hello= ("Hello") as any,
World= ("World") as any
    }
}

Declaring & Setting Variables in a Select Statement

The SET command is TSQL specific - here's the PLSQL equivalent to what you posted:

v_date1 DATE := TO_DATE('03-AUG-2010', 'DD-MON-YYYY');

SELECT u.visualid
  FROM USAGE u 
 WHERE u.usetime > v_date1;

There's also no need for prefixing variables with "@"; I tend to prefix variables with "v_" to distinguish between variables & columns/etc.

See this thread about the Oracle equivalent of NOLOCK...

How to convert Strings to and from UTF8 byte arrays in Java

Reader reader = new BufferedReader(
    new InputStreamReader(
        new ByteArrayInputStream(
            string.getBytes(StandardCharsets.UTF_8)), StandardCharsets.UTF_8));

Detect if a page has a vertical scrollbar?

Simply compare the width of the documents root element (i.e. html element) against the inner portion of the window:

if ((window.innerWidth - document.documentElement.clientWidth) >0) console.log('V-scrollbar active')

If you also need to know the scrollbar width:

vScrollbarWidth = window.innerWidth - document.documentElement.clientWidth;

Checking if a double (or float) is NaN in C++

There is no isnan() function available in current C++ Standard Library. It was introduced in C99 and defined as a macro not a function. Elements of standard library defined by C99 are not part of current C++ standard ISO/IEC 14882:1998 neither its update ISO/IEC 14882:2003.

In 2005 Technical Report 1 was proposed. The TR1 brings compatibility with C99 to C++. In spite of the fact it has never been officially adopted to become C++ standard, many (GCC 4.0+ or Visual C++ 9.0+ C++ implementations do provide TR1 features, all of them or only some (Visual C++ 9.0 does not provide C99 math functions).

If TR1 is available, then cmath includes C99 elements like isnan(), isfinite(), etc. but they are defined as functions, not macros, usually in std::tr1:: namespace, though many implementations (i.e. GCC 4+ on Linux or in XCode on Mac OS X 10.5+) inject them directly to std::, so std::isnan is well defined.

Moreover, some implementations of C++ still make C99 isnan() macro available for C++ (included through cmath or math.h), what may cause more confusions and developers may assume it's a standard behaviour.

A note about Viusal C++, as mentioned above, it does not provide std::isnan neither std::tr1::isnan, but it provides an extension function defined as _isnan() which has been available since Visual C++ 6.0

On XCode, there is even more fun. As mentioned, GCC 4+ defines std::isnan. For older versions of compiler and library form XCode, it seems (here is relevant discussion), haven't had chance to check myself) two functions are defined, __inline_isnand() on Intel and __isnand() on Power PC.

jquery mobile background image

For jquery mobile and phonegap this is the correct code:

<style type="text/css">
body {
    background: url(imgage.gif);
    background-repeat:repeat-y;
    background-position:center center;
    background-attachment:scroll;
    background-size:100% 100%;
}
.ui-page {
    background: transparent;
}
.ui-content{
    background: transparent;
}
</style>

How can I get an int from stdio in C?

The typical way is with scanf:

int input_value;

scanf("%d", &input_value);

In most cases, however, you want to check whether your attempt at reading input succeeded. scanf returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:

if (scanf("%d", &input_value) == 1)
    // it succeeded
else
    // it failed

Of course, the same is true of all the scanf family (sscanf, fscanf and so on).

Simple way to encode a string according to a password?

Here's a Python 3 version of the functions from @qneill 's answer:

import base64
def encode(key, clear):
    enc = []
    for i in range(len(clear)):
        key_c = key[i % len(key)]
        enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
        enc.append(enc_c)
    return base64.urlsafe_b64encode("".join(enc).encode()).decode()

def decode(key, enc):
    dec = []
    enc = base64.urlsafe_b64decode(enc).decode()
    for i in range(len(enc)):
        key_c = key[i % len(key)]
        dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
        dec.append(dec_c)
    return "".join(dec)

The extra encode/decodes are needed because Python 3 has split strings/byte arrays into two different concepts, and updated their APIs to reflect that..

Open file with associated application

Just write

System.Diagnostics.Process.Start(@"file path");

example

System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...

And shell will run associated program reading it from the registry, like usual double click does.

Laravel migration: unique key is too long, even if specified

If you have tried every other answer and they have not worked, you can drop all tables from the database and then execute the migrate command all at once using this command:

php artisan migrate:fresh

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

What is String pool in Java?

Let's start with a quote from the virtual machine spec:

Loading of a class or interface that contains a String literal may create a new String object (§2.4.8) to represent that literal. This may not occur if the a String object has already been created to represent a previous occurrence of that literal, or if the String.intern method has been invoked on a String object representing the same string as the literal.

This may not occur - This is a hint, that there's something special about String objects. Usually, invoking a constructor will always create a new instance of the class. This is not the case with Strings, especially when String objects are 'created' with literals. Those Strings are stored in a global store (pool) - or at least the references are kept in a pool, and whenever a new instance of an already known Strings is needed, the vm returns a reference to the object from the pool. In pseudo code, it may go like that:

1: a := "one" 
   --> if(pool[hash("one")] == null)  // true
           pool[hash("one") --> "one"]
       return pool[hash("one")]

2: b := "one" 
  --> if(pool[hash("one")] == null)   // false, "one" already in pool
        pool[hash("one") --> "one"]
      return pool[hash("one")] 

So in this case, variables a and b hold references to the same object. IN this case, we have (a == b) && (a.equals(b)) == true.

This is not the case if we use the constructor:

1: a := "one"
2: b := new String("one")

Again, "one" is created on the pool but then we create a new instance from the same literal, and in this case, it leads to (a == b) && (a.equals(b)) == false

So why do we have a String pool? Strings and especially String literals are widely used in typical Java code. And they are immutable. And being immutable allowed to cache String to save memory and increase performance (less effort for creation, less garbage to be collected).

As programmers we don't have to care much about the String pool, as long as we keep in mind:

  • (a == b) && (a.equals(b)) may be true or false (always use equals to compare Strings)
  • Don't use reflection to change the backing char[] of a String (as you don't know who is actualling using that String)

How to change Oracle default data pump directory to import dumpfile?

use DIRECTORY option.

Documentation here: http://docs.oracle.com/cd/E11882_01/server.112/e22490/dp_import.htm#SUTIL907

  DIRECTORY

  Default: DATA_PUMP_DIR

  Purpose

  Specifies the default location in which the import job can find the dump file set and where it should create log and SQL files.

  Syntax and Description

  DIRECTORY=directory_object
  The directory_object is the name of a database directory object (not the file path of an actual directory). Upon installation, privileged users have access to a default directory object named DATA_PUMP_DIR. Users with access to the default DATA_PUMP_DIR directory object do not need to use the DIRECTORY parameter at all.

  A directory object specified on the DUMPFILE, LOGFILE, or SQLFILE parameter overrides any directory object that you specify for the DIRECTORY parameter. You must have Read access to the directory used for the dump file set and Write access to the directory used to create the log and SQL files.

  Example

  The following is an example of using the DIRECTORY parameter. You can create the expfull.dmp dump file used in this example by running the example provided for the Export FULL parameter. See "FULL".

  > impdp hr DIRECTORY=dpump_dir1 DUMPFILE=expfull.dmp 
  LOGFILE=dpump_dir2:expfull.log
  This command results in the import job looking for the expfull.dmp dump file in the directory pointed to by the dpump_dir1 directory object. The dpump_dir2 directory object specified on the LOGFILE parameter overrides the DIRECTORY parameter so that the log file is written to dpump_dir2.

Convert timestamp long to normal date format

java.time

    ZoneId usersTimeZone = ZoneId.of("Asia/Tashkent");
    Locale usersLocale = Locale.forLanguageTag("ga-IE");
    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(usersLocale);

    long microsSince1970 = 1_512_345_678_901_234L;
    long secondsSince1970 = TimeUnit.MICROSECONDS.toSeconds(microsSince1970);
    long remainingMicros = microsSince1970 - TimeUnit.SECONDS.toMicros(secondsSince1970);
    ZonedDateTime dateTime = Instant.ofEpochSecond(secondsSince1970, 
                    TimeUnit.MICROSECONDS.toNanos(remainingMicros))
            .atZone(usersTimeZone);
    String dateTimeInUsersFormat = dateTime.format(formatter);
    System.out.println(dateTimeInUsersFormat);

The above snippet prints:

4 Noll 2017 05:01:18

“Noll” is Gaelic for December, so this should make your user happy. Except there may be very few Gaelic speaking people living in Tashkent, so please specify the user’s correct time zone and locale yourself.

I am taking seriously that you got microseconds from your database. If second precision is fine, you can do without remainingMicros and just use the one-arg Instant.ofEpochSecond(), which will make the code a couple of lines shorter. Since Instant and ZonedDateTime do support nanosecond precision, I found it most correct to keep the full precision of your timestamp. If your timestamp was in milliseconds rather than microseconds (which they often are), you may just use Instant.ofEpochMilli().

The answers using Date, Calendar and/or SimpleDateFormat were fine when this question was asked 7 years ago. Today those classes are all long outdated, and we have so much better in java.time, the modern Java date and time API.

For most uses I recommend you use the built-in localized formats as I do in the code. You may experiment with passing SHORT, LONG or FULL for format style. Yo may even specify format style for the date and for the time of day separately using an overloaded ofLocalizedDateTime method. If a specific format is required (this was asked in a duplicate question), you can have that:

    DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm:ss, dd/MM/uuuu");

Using this formatter instead we get

05:01:18, 04/12/2017

Link: Oracle tutorial: Date Time explaining how to use java.time.

setTimeout or setInterval?

setInterval()

setInterval() is a time interval based code execution method that has the native ability to repeatedly run a specified script when the interval is reached. It should not be nested into its callback function by the script author to make it loop, since it loops by default. It will keep firing at the interval unless you call clearInterval().

If you want to loop code for animations or on a clock tick, then use setInterval().

function doStuff() {
    alert("run your code here when time interval is reached");
}
var myTimer = setInterval(doStuff, 5000);

setTimeout()

setTimeout() is a time based code execution method that will execute a script only one time when the interval is reached. It will not repeat again unless you gear it to loop the script by nesting the setTimeout() object inside of the function it calls to run. If geared to loop, it will keep firing at the interval unless you call clearTimeout().

function doStuff() {
    alert("run your code here when time interval is reached");
}
var myTimer = setTimeout(doStuff, 5000);

If you want something to happen one time after a specified period of time, then use setTimeout(). That is because it only executes one time when the specified interval is reached.

C# Regex for Guid

I use an easier regex pattern

^[0-9A-Fa-f\-]{36}$

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

I needed to add this to the solution posted in 12 as I was using a list with a mixture of ordered list and unordered lists components. content: no-close-quote seems like an odd thing to add I know, but it works...

ol ul li:before {
    content: no-close-quote;
    counter-increment: none;
    display: list-item;
    margin-right: 100%;
    position: absolute;
    right: 10px;
}

How can I schedule a daily backup with SQL Server Express?

The folks at MSSQLTips have some very helpful articles, the one most relevant for this is "Automating SQL Server 2005 Express Backups and Deletion of Older Backup Files"

The basic approach is to set up two tasks using the Windows Task Scheduler. One task runs a TSQL script that generates separate backup files for all MSSQL databases (except TEMPDB) with the database name and a date/time stamp in the file name into a specified directory. The second task runs a VBScript script that goes through that directory and deletes all files with a .BAK extension that are more than 3 days old.

Both scripts require minor editing for your environment (paths, how long to keep those database dumps) but are very close to drop-in-and-run.

Note that there are possible security implications if you're sloppy with these or with directory permissions, since they are plain text files that will need to run with some level of privilege. Don't be sloppy.

How do I create a file AND any folders, if the folders don't exist?

To summarize what has been commented in other answers:

//path = @"C:\Temp\Bar\Foo\Test.txt";
Directory.CreateDirectory(Path.GetDirectoryName(path));

Directory.CreateDirectory will create the directories recursively and if the directory already exist it will return without an error.

If there happened to be a file Foo at C:\Temp\Bar\Foo an exception will be thrown.

Correct way to load a Nib for a UIView subclass

If you want to keep your CustomView and its xib independent of File's Owner, then follow these steps

  • Leave the File's Owner field empty.
  • Click on actual view in xib file of your CustomView and set its Custom Class as CustomView (name of your custom view class)
  • Add IBOutlet in .h file of your custom view.
  • In .xib file of your custom view, click on view and go in Connection Inspector. Here you will all your IBOutlets which you define in .h file
  • Connect them with their respective view.

in .m file of your CustomView class, override the init method as follow

-(CustomView *) init{
    CustomView *result = nil;
    NSArray* elements = [[NSBundle mainBundle] loadNibNamed: NSStringFromClass([self class]) owner:self options: nil];
    for (id anObject in elements)
    {
        if ([anObject isKindOfClass:[self class]])
        {
            result = anObject;
            break;
        }
    }
    return result;
}

Now when you want to load your CustomView, use the following line of code [[CustomView alloc] init];

Android layout replacing a view with another view on run time

private void replaceView(View oldV,View newV){
        ViewGroup par = (ViewGroup)oldV.getParent();
        if(par == null){return;}
        int i1 = par.indexOfChild(oldV);
        par.removeViewAt(i1);
        par.addView(newV,i1);
    }

Android Layout Animations from bottom to top and top to bottom on ImageView click

create directory in /res/anim and create bottom_to_original.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <translate
        android:duration="1500"
        android:fromYDelta="100%"
        android:toYDelta="1%" />
</set>

JAVA:

    LinearLayout ll = findViewById(R.id.ll);

    Animation animation;
    animation = AnimationUtils.loadAnimation(getApplicationContext(),
            R.anim.sample_animation);
    ll .setAnimation(animation);

How to name an object within a PowerPoint slide?

Select the Object -> Format -> Selection Pane -> Double click to change the name

enter image description here

Export to csv/excel from kibana

To export data to csv/excel from Kibana follow the following steps:-

  1. Click on Visualize Tab & select a visualization (if created). If not created create a visualziation.

  2. Click on caret symbol (^) which is present at the bottom of the visualization.

  3. Then you will get an option of Export:Raw Formatted as the bottom of the page.

Please find below attached image showing Export option after clicking on caret symbol.

Please find below attached image showing Export option after clicking on caret symbol.

Better way to find last used row

This function should do the trick if you want to specify a particular sheet. I took the solution from user6432984 and modified it to not throw any errors. I am using Excel 2016 so it may not work for older versions:

Function findLastRow(ByVal inputSheet As Worksheet) As Integer
    findLastRow = inputSheet.cellS(inputSheet.Rows.Count, 1).End(xlUp).Row
End Function

This is the code to run if you are already working in the sheet you want to find the last row of:

Dim lastRow as Integer
lastRow = cellS(Rows.Count, 1).End(xlUp).Row

Flask SQLAlchemy query, specify column names

As session.query(SomeModel.col1) returns an array of tuples like this [('value_1',),('value_2',)] if you want t cast the result to a plain array you can do it by using one of the following statements:

values = [value[0] for value in session.query(SomeModel.col1)]
values = [model.col1 for model in session.query(SomeModel).options(load_only('col1'))]

Result:

 ['value_1', 'value_2']

Can I convert a boolean to Yes/No in a ASP.NET GridView

I use this code for VB:

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%#IIf(Boolean.Parse(Eval("Active").ToString()), "Yes", "No")%></ItemTemplate>
</asp:TemplateField>

And this should work for C# (untested):

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate>
</asp:TemplateField>

Change CSS class properties with jQuery

Didn't find the answer I wanted, so I solved it myself:
modify a container div!

<div class="rotation"> <!-- Set the container div's css -->
  <div class="content" id='content-1'>This div gets scaled on hover</div>
</div>

<!-- Since there is no parent here the transform doesnt have specificity! -->
<div class="rotation content" id='content-2'>This div does not</div>

css you want to persist after executing $target.css()

.content:hover {
    transform: scale(1.5);
}

modify content's containing div with css()

$(".rotation").css("transform", "rotate(" + degrees + "deg)");

Codepen example

Reading HTML content from a UIWebView

In Swift v3:

let doc = webView.stringByEvaluatingJavaScript(from: "document.documentElement.outerHTML")

Angular2: How to load data before rendering the component?

update

original

When console.log(this.ev) is executed after this.fetchEvent();, this doesn't mean the fetchEvent() call is done, this only means that it is scheduled. When console.log(this.ev) is executed, the call to the server is not even made and of course has not yet returned a value.

Change fetchEvent() to return a Promise

     fetchEvent(){
        return  this._apiService.get.event(this.eventId).then(event => {
            this.ev = event;
            console.log(event); // Has a value
            console.log(this.ev); // Has a value
        });
     }

change ngOnInit() to wait for the Promise to complete

    ngOnInit() {
        this.fetchEvent().then(() =>
        console.log(this.ev)); // Now has value;
    }

This actually won't buy you much for your use case.

My suggestion: Wrap your entire template in an <div *ngIf="isDataAvailable"> (template content) </div>

and in ngOnInit()

    isDataAvailable:boolean = false;

    ngOnInit() {
        this.fetchEvent().then(() =>
        this.isDataAvailable = true); // Now has value;
    }

What is the difference between Normalize.css and Reset CSS?

This question has been answered already several times, I'll short summary for each of them, an example and insights as of September 2019:

  • Normalize.css - as the name suggests, it normalizes styles in the browsers for their user agents, i.e. makes them the same across all browsers due to the reason by default they're slightly different.

Example: <h1> tag inside <section> by default Google Chrome will make smaller than the "expected" size of <h1> tag. Microsoft Edge on the other hand is making the "expected" size of <h1> tag. Normalize.css will make it consistent.

Current status: the npm repository shows that normalize.css package has currently more than 500k downloads per week. GitHub stars in the project of the repository are more than 36k.

  • Reset CSS - as the name suggests, it resets all styles, i.e. it removes all browser's user agent styles.

Example: it would do something like that below:

html, body, div, span, ..., audio, video {  
   margin: 0;  
   padding: 0;  
   border: 0;  
   font-size: 100%;  
   font: inherit;  
   vertical-align: baseline; 
}

Current status: it's much less popular than Normalize.css, the reset-css package shows it's something around 26k downloads per week. GitHub stars are only 200, as it can be noticed from the project's repository.

How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?

SELECT c1, c2, c3, c4, c5 FROM table1 WHERE c3 = (select max(c3) from table)

SELECT * FROM table1 WHERE c3 = (select max(c3) from table1)

Convert StreamReader to byte[]

A StreamReader is for text, not plain bytes. Don't use a StreamReader, and instead read directly from the underlying stream.

How can I escape a single quote?

If for some reason you cannot escape the apostrophe character and you can't change it into a HTML entity (as it was in my case for a specific Vue.js property) you can use replace to change it into different apostrophe character from the UTF8 characters set, for instance:

' - U+02BC
’ - U+2019

Outline radius?

I like this way.

.circle:before {
   content: "";
   width: 14px;
   height: 14px;
   border: 3px solid #fff;
   background-color: #ced4da;
   border-radius: 7px;
   display: inline-block;
   margin-bottom: -2px;
   margin-right: 7px;
   box-shadow: 0px 0px 0px 1px #ced4da;
}

It will create gray circle with wit border around it and again 1px around border!

Ajax LARAVEL 419 POST error

You don't have any data that you're submitting! Try adding this line to your ajax:

data: $('form').serialize(),

Make sure you change the name to match!

Also your data should be submitted inside of a form submit function.

Your code should look something like this:

_x000D_
_x000D_
<script>_x000D_
 $(function () {_x000D_
  $('form').on('submit', function (e) {_x000D_
   e.preventDefault();_x000D_
   $.ajax({_x000D_
    type: 'post',_x000D_
    url: 'company.php',_x000D_
    data: $('form').serialize(),_x000D_
    success: function () {_x000D_
     alert('form was submitted');_x000D_
    }_x000D_
   });_x000D_
  });_x000D_
 });_x000D_
</script>
_x000D_
_x000D_
_x000D_

Get the first key name of a JavaScript object

I use Lodash for defensive coding reasons.

In particular, there are cases where I do not know if there will or will not be any properties in the object I'm trying to get the key for.

A "fully defensive" approach with Lodash would use both keys as well as get:

const firstKey = _.get(_.keys(ahash), 0);

Add to Array jQuery

For JavaScript arrays, you use Both push() and concat() function.

var array = [1, 2, 3];
array.push(4, 5);         //use push for appending a single array.




var array1 = [1, 2, 3];
var array2 = [4, 5, 6];

var array3 = array1.concat(array2);   //It is better use concat for appending more then one array.

How do I fix "The expression of type List needs unchecked conversion...'?

SyndFeedInput fr = new SyndFeedInput();
SyndFeed sf = fr.build(new XmlReader(myInputStream));
List<?> entries = sf.getEntries();

MySQL default datetime through phpmyadmin

You're getting that error because the default value current_time is not valid for the type DATETIME. That's what it says, and that's whats going on.

The only field you can use current_time on is a timestamp.

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

What's wrong with using Git For Windows? From the repo view, there's an icon of the branch you're in (at the top), and if you click on manage you can drag&drop in a very visual and convenient way.

Find and replace strings in vim on multiple lines

VI search and replace command examples

Let us say you would like to find a word called “foo” and replace with “bar”.

First hit [Esc] key

Type : (colon) followed by %s/foo/bar/ and hit [Enter] key

:%s/foo/bar/

What is *.o file?

It is important to note that object files are assembled to binary code in a format that is relocatable. This is a form which allows the assembled code to be loaded anywhere into memory for use with other programs by a linker.

Instructions that refer to labels will not yet have an address assigned for these labels in the .o file.

These labels will be written as '0' and the assembler creates a relocation record for these unknown addresses. When the file is linked and output to an executable the unknown addresses are resolved and the program can be executed.

You can use the nm tool on an object file to list the symbols defined in a .o file.

Multi-dimensional arraylist or list in C#?

You can create a list of lists

   public class MultiDimList: List<List<string>> {  }

or a Dictionary of key-accessible Lists

   public class MultiDimDictList: Dictionary<string, List<int>>  { }
   MultiDimDictList myDicList = new MultiDimDictList ();
   myDicList.Add("ages", new List<int>()); 
   myDicList.Add("Salaries", new List<int>()); 
   myDicList.Add("AccountIds", new List<int>()); 

Generic versions, to implement suggestion in comment from @user420667

  public class MultiDimList<T>: List<List<T>> {  }

and for the dictionary,

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  { }

  // to use it, in client code
   var myDicList = new MultiDimDictList<string, int> ();
   myDicList.Add("ages", new List<T>()); 
   myDicList["ages"].Add(23);
   myDicList["ages"].Add(32);
   myDicList["ages"].Add(18);

   myDicList.Add("salaries", new List<T>());
   myDicList["salaries"].Add(80000);
   myDicList["salaries"].Add(100000);

   myDicList.Add("accountIds", new List<T>()); 
   myDicList["accountIds"].Add(321123);
   myDicList["accountIds"].Add(342653);

or, even better, ...

   public class MultiDimDictList<K, T>: Dictionary<K, List<T>>  
   {
       public void Add(K key, T addObject)
       {
           if(!ContainsKey(key)) Add(key, new List<T>());
           if (!base[key].Contains(addObject)) base[key].Add(addObject);
       }           
   }


  // and to use it, in client code
    var myDicList = new MultiDimDictList<string, int> ();
    myDicList.Add("ages", 23);
    myDicList.Add("ages", 32);
    myDicList.Add("ages", 18);
    myDicList.Add("salaries", 80000);
    myDicList.Add("salaries", 110000);
    myDicList.Add("accountIds", 321123);
    myDicList.Add("accountIds", 342653);

EDIT: to include an Add() method for nested instance:

public class NestedMultiDimDictList<K, K2, T>: 
           MultiDimDictList<K, MultiDimDictList<K2, T>>: 
{
       public void Add(K key, K2 key2, T addObject)
       {
           if(!ContainsKey(key)) Add(key, 
                  new MultiDimDictList<K2, T>());
           if (!base[key].Contains(key2)) 
               base[key].Add(key2, addObject);
       }    
}

Android Pop-up message

Suppose you want to set a pop-up text box for clicking a button lets say bt whose id is button, then code using Toast will somewhat look like this:

Button bt;
bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {            
Toast.makeText(getApplicationContext(),"The text you want to display",Toast.LENGTH_LONG)
}

Casting int to bool in C/C++

The following cites the C11 standard (final draft).

6.3.1.2: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

bool (mapped by stdbool.h to the internal name _Bool for C) itself is an unsigned integer type:

... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.

According to 6.2.5p2:

An object declared as type _Bool is large enough to store the values 0 and 1.

AFAIK these definitions are semantically identical to C++ - with the minor difference of the built-in(!) names. bool for C++ and _Bool for C.

Note that C does not use the term rvalues as C++ does. However, in C pointers are scalars, so assigning a pointer to a _Bool behaves as in C++.

How to add extra whitespace in PHP?

source

<?php
echo "<p>hello\n";
echo "world</p>";

echo "\n\n";

echo "<p>\n\tindented\n</p>\n";

echo "
<div>
  easy formatting<br />
  across multiple lines!
</div>
";
?>

output

<p>hello
world</p> 

<p> 
    indented
</p>

<div> 
  easy formatting<br /> 
  across multiple lines!
</div>

How to Set Variables in a Laravel Blade Template

It's better to practice to define variable in Controller and then pass to view using compact() or ->with() method.

Otherwise #TLGreg gave best answer.

How do I post button value to PHP?

    $restore = $this->createElement('submit', 'restore', array(
        'label' => 'FILE_RESTORE',
        'class' => 'restore btn btn-small btn-primary',
        'attribs' => array(
            'onClick' => 'restoreCheck();return false;'
        )
    ));

Jackson overcoming underscores in favor of camel-case

The current best practice is to configure Jackson within the application.yml (or properties) file.

Example:

spring:
  jackson:
    property-naming-strategy: SNAKE_CASE

If you have more complex configuration requirements, you can also configure Jackson programmatically.

import com.fasterxml.jackson.databind.PropertyNamingStrategy;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;

@Configuration
public class JacksonConfiguration {

    @Bean
    public Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder() {
        return new Jackson2ObjectMapperBuilder()
                .propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        // insert other configurations
    }

} 

How do I create a simple 'Hello World' module in Magento?

I was trying to make my module from magaplaza hello world tutorial, but something went wrong. I imported code of this module https://github.com/astorm/magento2-hello-world from github and it worked. from that module, i created it a categories subcategories ajax select drop downs Module. After installing it in aap/code directory of your magento2 installation follow this URL.. http://www.example.com/hello_mvvm/hello/world You can download its code from here https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns and place it in your aap/code folder. than run these commands...

php bin/magento setup:update
php bin/magento setup:static-content:deploy -f
php bin/magento c:c

Now you can check module functionality with following URL http://{{www.example.com}}/hello_mvvm/hello/world

Convert XML to JSON (and back) using Javascript

The best way to do it using server side as client side doesn't work well in all scenarios. I was trying to build online json to xml and xml to json converter using javascript and I felt almost impossible as it was not working in all scenarios. Ultimately I ended up doing it server side using Newtonsoft in ASP.MVC. Here is the online converter http://techfunda.com/Tools/XmlToJson

Ignore outliers in ggplot2 boxplot

One idea would be to winsorize the data in a two-pass procedure:

  1. run a first pass, learn what the bounds are, e.g. cut of at given percentile, or N standard deviation above the mean, or ...

  2. in a second pass, set the values beyond the given bound to the value of that bound

I should stress that this is an old-fashioned method which ought to be dominated by more modern robust techniques but you still come across it a lot.

How to iterate over a JSONObject?

With Java 8 and lambda, cleaner:

JSONObject jObject = new JSONObject(contents.trim());

jObject.keys().forEachRemaining(k ->
{

});

https://docs.oracle.com/javase/8/docs/api/java/util/Iterator.html#forEachRemaining-java.util.function.Consumer-

Alter column, add default constraint

I confirm like the comment from JohnH, never use column types in the your object names! It's confusing. And use brackets if possible.

Try this:

ALTER TABLE [TableName]
ADD  DEFAULT (getutcdate()) FOR [Date]; 

Sites not accepting wget user agent header

It seems Yahoo server does some heuristic based on User-Agent in a case Accept header is set to */*.

Accept: text/html

did the trick for me.

e.g.

wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0"  http://yahoo.com

Note: if you don't declare Accept header then wget automatically adds Accept:*/* which means give me anything you have.

Getting the error "Java.lang.IllegalStateException Activity has been destroyed" when using tabs with ViewPager

I had this problem and I couldn't find the solution here, so I want to share my solution in case someone else has this problem again.

I had this code:

public void finishAction() {
  onDestroy();
  finish();
}

and solved the problem by deleting the line "onDestroy();"

public void finishAction() {
  finish();
}

The reason I wrote the initial code: I know that when you execute "finish()" the activity calls "onDestroy()", but I'm using threads and I wanted to ensure that all the threads are destroyed before starting the next activity, and it looks like "finish()" is not always immediate. I need to process/reduce a lot of “Bitmap” and display big “bitmaps” and I’m working on improving the use of the memory in my app

Now I will kill the threads using a different method and I’ll execute this method from "onDestroy();" and when I think I need to kill all the threads.

public void finishAction() {
  onDestroyThreads();
  finish();
}

Regex Email validation

Try this, it's working for me:

public bool IsValidEmailAddress(string s)
{
    if (string.IsNullOrEmpty(s))
        return false;
    else
    {
        var regex = new Regex(@"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*");
        return regex.IsMatch(s) && !s.EndsWith(".");
    }
}

Reading a text file in MATLAB line by line

Just read it in to MATLAB in one block

fid = fopen('file.csv');
data=textscan(fid,'%s %f %f','delimiter',',');
fclose(fid);

You can then process it using logical addressing

ind50 = data{2}>=50 ;

ind50 is then an index of the rows where column 2 is greater than 50. So

data{1}(ind50)

will list all the strings for the rows of interest. Then just use fprintf to write out your data to the new file

Auto populate columns in one sheet from another sheet

In Google Sheets you can use =ArrayFormula(Sheet1!B2:B)on the first cell and it will populate all column contents not sure if that will work in excel

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

You can pass in any CMake variable on the command line, or edit cached variables using ccmake/cmake-gui. On the command line,

cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr . && make all install

Would configure the project, build all targets and install to the /usr prefix. The type (PATH) is not strictly necessary, but would cause the Qt based cmake-gui to present the directory chooser dialog.

Some minor additions as comments make it clear that providing a simple equivalence is not enough for some. Best practice would be to use an external build directory, i.e. not the source directly. Also to use more generic CMake syntax abstracting the generator.

mkdir build && cd build && cmake -DCMAKE_INSTALL_PREFIX:PATH=/usr .. && cmake --build . --target install --config Release

You can see it gets quite a bit longer, and isn't directly equivalent anymore, but is closer to best practices in a fairly concise form... The --config is only used by multi-configuration generators (i.e. MSVC), ignored by others.

Extract filename and extension in Bash

Maybe there is an option in tar to do this; did you check the man? Otherwise, you can use Bash string expansion:

test="mpc-1.0.1.tar.gz"
noExt="${test/.tar.gz/}" # Remove the string '.tar.gz'
echo $noExt

JavaScript style.display="none" or jQuery .hide() is more efficient?

a = 2;

vs

a(2);
function a(nb) {
    lot;
    of = cross;
    browser();
    return handling(nb);
}

In your opinion, what do you think is going to be the fastest?

Display all dataframe columns in a Jupyter Python Notebook

Python 3.x for large (but not too large) DataFrames

Maybe because I have an older version of pandas but on Jupyter notebook this work for me

import pandas as pd
from IPython.core.display import HTML

df=pd.read_pickle('Data1')
display(HTML(df.to_html()))

How to compare objects by multiple fields

Following blog given good chained Comparator example

http://www.codejava.net/java-core/collections/sorting-a-list-by-multiple-attributes-example

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

/**
 * This is a chained comparator that is used to sort a list by multiple
 * attributes by chaining a sequence of comparators of individual fields
 * together.
 *
 */
public class EmployeeChainedComparator implements Comparator<Employee> {

    private List<Comparator<Employee>> listComparators;

    @SafeVarargs
    public EmployeeChainedComparator(Comparator<Employee>... comparators) {
        this.listComparators = Arrays.asList(comparators);
    }

    @Override
    public int compare(Employee emp1, Employee emp2) {
        for (Comparator<Employee> comparator : listComparators) {
            int result = comparator.compare(emp1, emp2);
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }
}

Calling Comparator:

Collections.sort(listEmployees, new EmployeeChainedComparator(
                new EmployeeJobTitleComparator(),
                new EmployeeAgeComparator(),
                new EmployeeSalaryComparator())
        );

How to use onResume()?

KOTLIN

Any Activity that restarts has its onResume() method executed first.

To use this method, do this:

override fun onResume() {
        super.onResume()
        // your code here
    }

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

I had the same error message but the solution is different.

The compiler parses the file from top to bottom.

Make sure a struct is defined BEFORE using it into another:

typedef struct
{
    char name[50];
    wheel_t wheels[4]; //wrong, wheel_t is not defined yet
} car_t;

typedef struct
{
    int weight;
} wheel_t;

Can't operator == be applied to generic types in C#?

It appears that without the class constraint:

bool Compare<T> (T x, T y) where T: class
{
    return x == y;
}

One should realize that while class constrained Equals in the == operator inherits from Object.Equals, while that of a struct overrides ValueType.Equals.

Note that:

bool Compare<T> (T x, T y) where T: struct
{
    return x == y;
}

also gives out the same compiler error.

As yet I do not understand why having a value type equality operator comparison is rejected by the compiler. I do know for a fact though, that this works:

bool Compare<T> (T x, T y)
{
    return x.Equals(y);
}

ActivityCompat.requestPermissions not showing dialog box

Here's an example of using requestPermissions():

First, define the permission (as you did in your post) in the manifest, otherwise, your request will automatically be denied:

<uses-permission android:name="android.permission.READ_PHONE_STATE" />

Next, define a value to handle the permission callback, in onRequestPermissionsResult():

private final int REQUEST_PERMISSION_PHONE_STATE=1;

Here's the code to call requestPermissions():

private void showPhoneStatePermission() {
    int permissionCheck = ContextCompat.checkSelfPermission(
            this, Manifest.permission.READ_PHONE_STATE);
    if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.READ_PHONE_STATE)) {
            showExplanation("Permission Needed", "Rationale", Manifest.permission.READ_PHONE_STATE, REQUEST_PERMISSION_PHONE_STATE);
        } else {
            requestPermission(Manifest.permission.READ_PHONE_STATE, REQUEST_PERMISSION_PHONE_STATE);
        }
    } else {
        Toast.makeText(MainActivity.this, "Permission (already) Granted!", Toast.LENGTH_SHORT).show();
    }
}

First, you check if you already have permission (remember, even after being granted permission, the user can later revoke the permission in the App Settings.)

And finally, this is how you check if you received permission or not:

@Override
public void onRequestPermissionsResult(
        int requestCode,
        String permissions[],
        int[] grantResults) {
    switch (requestCode) {
        case REQUEST_PERMISSION_PHONE_STATE:
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Toast.makeText(MainActivity.this, "Permission Granted!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(MainActivity.this, "Permission Denied!", Toast.LENGTH_SHORT).show();
            }
    }
}

private void showExplanation(String title,
                             String message,
                             final String permission,
                             final int permissionRequestCode) {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(title)
            .setMessage(message)
            .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    requestPermission(permission, permissionRequestCode);
                }
            });
    builder.create().show();
}

private void requestPermission(String permissionName, int permissionRequestCode) {
    ActivityCompat.requestPermissions(this,
            new String[]{permissionName}, permissionRequestCode);
}

Count number of occurrences for each unique value

If i am understanding your question, would this work? (you will have to replace with your actual column and table names)

SELECT time_col, COUNT(time_col) As Count
FROM time_table
GROUP BY time_col
WHERE activity_col = 3

Right click to select a row in a Datagridview and show a menu to delete it

You can also make this a little simpler by using the following inside the event code:

private void MyDataGridView_MouseDown(object sender, MouseEventArgs e) 
{     
    if (e.Button == MouseButtons.Right)     
    {         
        rowToDelete = e.RowIndex;
        MyDataGridView.Rows.RemoveAt(rowToDelete);         
        MyDataGridView.ClearSelection();     
    } 
}

preventDefault() on an <a> tag

Set the href attribute as href="javascript:;"

<ul class="product-info">
  <li>
   <a href="javascript:;">YOU CLICK THIS TO SHOW/HIDE</a>
  <div class="toggle">
    <p>CONTENT TO SHOW/HIDE</p>
  </div>
 </li>
</ul>

Proper way to initialize C++ structs

From what you've told us it does appear to be a false positive in valgrind. The new syntax with () should value-initialize the object, assuming it is POD.

Is it possible that some subpart of your struct isn't actually POD and that's preventing the expected initialization? Are you able to simplify your code into a postable example that still flags the valgrind error?

Alternately perhaps your compiler doesn't actually value-initialize POD structures.

In any case probably the simplest solution is to write constructor(s) as needed for the struct/subparts.

cvc-elt.1: Cannot find the declaration of element 'MyElement'

Your schema is for its target namespace http://www.example.org/Test so it defines an element with name MyElement in that target namespace http://www.example.org/Test. Your instance document however has an element with name MyElement in no namespace. That is why the validating parser tells you it can't find a declaration for that element, you haven't provided a schema for elements in no namespace.

You either need to change the schema to not use a target namespace at all or you need to change the instance to use e.g. <MyElement xmlns="http://www.example.org/Test">A</MyElement>.

Select first 10 distinct rows in mysql

SELECT  DISTINCT *
FROM    people
WHERE   names = 'Smith'
ORDER BY
        names
LIMIT 10

Skipping every other element after the first

def skip_elements(elements):
   new_list = [ ]
   i = 0
   for element in elements:
       if i%2==0:
         c=elements[i]
         new_list.append(c)
       i+=1
  return new_list

Format numbers to strings in Python

If you have a value that includes a decimal, but the decimal value is negligible (ie: 100.0) and try to int that, you will get an error. It seems silly, but calling float first fixes this.

str(int(float([variable])))

Extract substring in Bash

Generic solution where the number can be anywhere in the filename, using the first of such sequences:

number=$(echo $filename | egrep -o '[[:digit:]]{5}' | head -n1)

Another solution to extract exactly a part of a variable:

number=${filename:offset:length}

If your filename always have the format stuff_digits_... you can use awk:

number=$(echo $filename | awk -F _ '{ print $2 }')

Yet another solution to remove everything except digits, use

number=$(echo $filename | tr -cd '[[:digit:]]')

Converting a char to uppercase

Instead of using existing utilities, you may try below conversion using boolean operation:

To upper case:

 char upperChar = 'l' & 0x5f

To lower case:

   char lowerChar = 'L' ^ 0x20

How it works:

Binary, hex and decimal table:

------------------------------------------
| Binary   |   Hexadecimal     | Decimal |
-----------------------------------------
| 1011111  |    0x5f           |  95     |
------------------------------------------
| 100000   |    0x20           |  32     |
------------------------------------------

Let's take an example of small l to L conversion:

The binary AND operation: (l & 0x5f)

l character has ASCII 108 and 01101100 is binary represenation.

   1101100
&  1011111
-----------
   1001100 = 76 in decimal which is **ASCII** code of L

Similarly the L to l conversion:

The binary XOR operation: (L ^ 0x20)

   1001100
^  0100000
-----------
   1101100 = 108 in decimal which is **ASCII** code of l

CASE IN statement with multiple values

Yes. You need to use the "Searched" form rather than the "Simple" form of the CASE expression

SELECT CASE
         WHEN c.Number IN ( '1121231', '31242323' ) THEN 1
         WHEN c.Number IN ( '234523', '2342423' ) THEN 2
       END AS Test
FROM   tblClient c  

Getting the difference between two repositories

Meld can compare directories:

meld directory1 directory2

Just use the directories of the two git repos and you will get a nice graphical comparison:

enter image description here

When you click on one of the blue items, you can see what changed.

How do I find an element position in std::vector?

std::vector has random-access iterators. You can do pointer arithmetic with them. In particular, this my_vec.begin() + my_vec.size() == my_vec.end() always holds. So you could do

const vector<type>::const_iterator pos = std::find_if( firstVector.begin()
                                                     , firstVector.end()
                                                     , some_predicate(parameter) );
if( position != firstVector.end() ) {
    const vector<type>::size_type idx = pos-firstVector.begin();
    doAction( secondVector[idx] );
}

As an alternative, there's always std::numeric_limits<vector<type>::size_type>::max() to be used as an invalid value.

Converting a sentence string to a string array of words in Java

Try this:

String[] stringArray = Pattern.compile("ian").split(
"This is a sample sentence"
.replaceAll("[^\\p{Alnum}]+", "") //this will remove all non alpha numeric chars
);

for (int j=0; i<stringArray .length; j++) {
  System.out.println(i + " \"" + stringArray [j] + "\"");
}

jQuery UI autocomplete with item and id

<script type="text/javascript">
$(function () {
    $("#MyTextBox").autocomplete({
        source: "MyDataFactory.ashx",
        minLength: 2,
        select: function (event, ui) {
            $('#MyIdTextBox').val(ui.item.id);
            return ui.item.label;
        }
    });
});

The above responses helped but, did not work in my implementation. The instead of using setting the value using jQuery, I am returning the value from the function to the select option.

The MyDataFactory.ashx page has a class with three properties Id, Label, Value.

Pass the List into the JavaScript serializer, and return the response.

How to find the date of a day of the week from a date using PHP?

PHP Manual said :

w Numeric representation of the day of the week

You can therefore construct a date with mktime, and use in it date("w", $yourTime);

how to use Blob datatype in Postgres

I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB

Read the part with the title 'What is the best way to store the files in the Database?'

Run command on the Ansible host

you can try this way

What is the purpose of global.asax in asp.net

MSDN has an outline of the purpose of the global.asax file.

Effectively, global.asax allows you to write code that runs in response to "system level" events, such as the application starting, a session ending, an application error occuring, without having to try and shoe-horn that code into each and every page of your site.

You can use it by by choosing Add > New Item > Global Application Class in Visual Studio. Once you've added the file, you can add code under any of the events that are listed (and created by default, at least in Visual Studio 2008):

  • Application_Start
  • Application_End
  • Session_Start
  • Session_End
  • Application_BeginRequest
  • Application_AuthenticateRequest
  • Application_Error

There are other events that you can also hook into, such as "LogRequest".

How to choose multiple files using File Upload Control?

here is the complete example of how you can select and upload multiple files in asp.net using file upload control....

write this code in .aspx file..

<head runat="server">
    <title></title>
</head>
<body>
<form id="form1" runat="server" enctype="multipart/form-data">
<div>
    <input type="file" id="myfile" multiple="multiple" name="myfile" runat="server" size="100" />
    <br />
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
    <br />
    <asp:Label ID="Span1" runat="server"></asp:Label>
</div>
</form>
</body>
</html>

after that write this code in .aspx.cs file..

   protected void Button1_Click(object sender,EventArgs e) {
          string filepath = Server.MapPath("\\Upload");
          HttpFileCollection uploadedFiles = Request.Files;
          Span1.Text = string.Empty;

          for(int i = 0;i < uploadedFiles.Count;i++) {
              HttpPostedFile userPostedFile = uploadedFiles[i];

              try {
                  if (userPostedFile.ContentLength > 0) {
                     Span1.Text += "<u>File #" + (i + 1) +  "</u><br>";
                     Span1.Text += "File Content Type: " +  userPostedFile.ContentType      + "<br>";
                     Span1.Text += "File Size: " + userPostedFile.ContentLength           + "kb<br>";
                     Span1.Text += "File Name: " + userPostedFile.FileName + "<br>";

                     userPostedFile.SaveAs(filepath + "\\" +    Path.GetFileName(userPostedFile.FileName));                  
                     Span1.Text += "Location where saved: " +   filepath + "\\" +   Path.GetFileName(userPostedFile.FileName) + "<p>";
                  }
              } catch(Exception Ex) {
                  Span1.Text += "Error: <br>" + Ex.Message;
              }
           }
        }
    }

and here you go...your multiple file upload control is ready..have a happy day.

How do I compile the asm generated by GCC?

You can use GAS, which is gcc's backend assembler:

http://linux.die.net/man/1/as

how to use getSharedPreferences in android

First get the instance of SharedPreferences using

SharedPreferences userDetails = context.getSharedPreferences("userdetails", MODE_PRIVATE);

Now to save the values in the SharedPreferences

Editor edit = userDetails.edit();
edit.putString("username", username.getText().toString().trim());
edit.putString("password", password.getText().toString().trim());
edit.apply();

Above lines will write username and password to preference

Now to to retrieve saved values from preference, you can follow below lines of code

String userName = userDetails.getString("username", "");
String password = userDetails.getString("password", "");

(NOTE: SAVING PASSWORD IN THE APP IS NOT RECOMMENDED. YOU SHOULD EITHER ENCRYPT THE PASSWORD BEFORE SAVING OR SKIP THE SAVING THE PASSWORD)

How to catch exception correctly from http.request()?

There are several ways to do this. Both are very simple. Each of the examples works great. You can copy it into your project and test it.

The first method is preferable, the second is a bit outdated, but so far it works too.

1) Solution 1

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpClientModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
import { catchError, tap } from 'rxjs/operators'; // Important! Be sure to connect operators

// There may be your any object. For example, we will have a product object
import { ProductModule } from './product.module';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: HttpClient, private product: ProductModule){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will get into catchError and catch them.
    getProducts(): Observable<ProductModule[]>{
        const url = 'YOUR URL HERE';
        return this.http.get<ProductModule[]>(url).pipe(
            tap((data: any) => {
                console.log(data);
            }),
            catchError((err) => {
                throw 'Error in source. Details: ' + err; // Use console.log(err) for detail
            })
        );
    }
}

2) Solution 2. It is old way but still works.

// File - app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { ProductService } from './product.service';
import { ProductModule } from './product.module';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  providers: [ProductService, ProductModule],
  bootstrap: [AppComponent]
})
export class AppModule { }



// File - product.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';

// Importing rxjs
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';

@Injectable()
export class ProductService{
    // Initialize the properties.
    constructor(private http: Http){}

    // If there are no errors, then the object will be returned with the product data.
    // And if there are errors, we will to into catch section and catch error.
    getProducts(){
        const url = '';
        return this.http.get(url).map(
            (response: Response) => {
                const data = response.json();
                console.log(data);
                return data;
            }
        ).catch(
            (error: Response) => {
                console.log(error);
                return Observable.throw(error);
            }
        );
    }
}

How to pass multiple parameters from ajax to mvc controller?

Try this;

function X (id,parameter1,parameter2,...) {
    $.ajax({

            url: '@Url.Action("Actionre", "controller")',+ id,
            type: "Get",
            data: { parameter1: parameter1, parameter2: parameter2,...}

    }).done(function(result) {

        your code...
    });
}

So controller method would looks like :

public ActionResult ActionName(id,parameter1, parameter2,...)
{
   Your Code .......
}

Async/Await Class Constructor

If you can avoid extend, you can avoid classes all together and use function composition as constructors. You can use the variables in the scope instead of class members:

async function buildA(...) {
  const data = await fetch(...);
  return {
    getData: function() {
      return data;
    }
  }
}

and simple use it as

const a = await buildA(...);

If you're using typescript or flow, you can even enforce the interface of the constructors

Interface A {
  getData: object;
}

async function buildA0(...): Promise<A> { ... }
async function buildA1(...): Promise<A> { ... }
...

Xampp-mysql - "Table doesn't exist in engine" #1932

For me I removed whole data folder from xampp\mysql\ and pasted data folder of previous one here which solved my problem...

Is Fortran easier to optimize than C for heavy calculations?

There are several reasons why Fortran could be faster. However the amount they matter is so inconsequential or can be worked around anyways, that it shouldn't matter. The main reason to use Fortran nowadays is maintaining or extending legacy applications.

  • PURE and ELEMENTAL keywords on functions. These are functions that have no side effects. This allows optimizations in certain cases where the compiler knows the same function will be called with the same values. Note: GCC implements "pure" as an extension to the language. Other compilers may as well. Inter-module analysis can also perform this optimization but it is difficult.

  • standard set of functions that deal with arrays, not individual elements. Stuff like sin(), log(), sqrt() take arrays instead of scalars. This makes it easier to optimize the routine. Auto-vectorization gives the same benefits in most cases if these functions are inline or builtins

  • Builtin complex type. In theory this could allow the compiler to reorder or eliminate certain instructions in certain cases, but likely you'd see the same benefit with the struct { double re; double im; }; idiom used in C. It makes for faster development though as operators work on complex types in Fortran.

python: sys is not defined

You're trying to import all of those modules at once. Even if one of them fails, the rest will not import. For example:

try:
    import datetime
    import foo
    import sys
except ImportError:
    pass

Let's say foo doesn't exist. Then only datetime will be imported.

What you can do is import the sys module at the beginning of the file, before the try/except statement:

import sys
try:
    import numpy as np
    import pyfits as pf
    import scipy.ndimage as nd
    import pylab as pl
    import os
    import heapq
    from scipy.optimize import leastsq

except ImportError:
    print "Error: missing one of the libraries (numpy, pyfits, scipy, matplotlib)"
    sys.exit()

Read a javascript cookie by name

using jquery-cookie

I find this library helpful. 3.128 kb of pure convenience.

add script

<script src="/path/to/jquery.cookie.js"></script>

set cookie

$.cookie('name', 'value');

read cookie

$.cookie('name');

How to get text from EditText?

Put this in your MainActivity:

{
    public EditText bizname, storeno, rcpt, item, price, tax, total;
    public Button click, click2;
    int contentView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.main_activity );
        bizname = (EditText) findViewById( R.id.editBizName );
        item = (EditText) findViewById( R.id.editItem );
        price = (EditText) findViewById( R.id.editPrice );
        tax = (EditText) findViewById( R.id.editTax );
        total = (EditText) findViewById( R.id.editTotal );
        click = (Button) findViewById( R.id.button );
    }
}

Put this under a button or something

public void clickBusiness(View view) {
    checkPermsOfStorage( this );

    bizname = (EditText) findViewById( R.id.editBizName );
    item = (EditText) findViewById( R.id.editItem );
    price = (EditText) findViewById( R.id.editPrice );
    tax = (EditText) findViewById( R.id.editTax );
    total = (EditText) findViewById( R.id.editTotal );
    String x = ("\nItem/Price: " + item.getText() + price.getText() + "\nTax/Total" + tax.getText() + total.getText());
    Toast.makeText( this, x, Toast.LENGTH_SHORT ).show();
    try {
        this.WriteBusiness(bizname,storeno,rcpt,item,price,tax,total);
        String vv = tax.getText().toString();
        System.console().printf( "%s", vv );
        //new XMLDivisionWriter(getString(R.string.SDDoc) + "/tax_div_business.xml");
    } catch (ReflectiveOperationException e) {
        e.printStackTrace();
    }
}

There! The debate is settled!

Using a cursor with dynamic SQL in a stored procedure

This code is a very good example for a dynamic column with a cursor, since you cannot use '+' in @STATEMENT:

ALTER PROCEDURE dbo.spTEST
AS
    SET NOCOUNT ON
    DECLARE @query NVARCHAR(4000) = N'' --DATA FILTER
    DECLARE @inputList NVARCHAR(4000) = ''
    DECLARE @field sysname = '' --COLUMN NAME
    DECLARE @my_cur CURSOR
    EXECUTE SP_EXECUTESQL
        N'SET @my_cur = CURSOR FAST_FORWARD FOR
            SELECT
                CASE @field
                    WHEN ''fn'' then fn
                    WHEN ''n_family_name'' then n_family_name
                END
            FROM
                dbo.vCard
            WHERE
                CASE @field
                    WHEN ''fn'' then fn
                    WHEN ''n_family_name'' then n_family_name
                END
                LIKE ''%''+@query+''%'';
            OPEN @my_cur;',
        N'@field sysname, @query NVARCHAR(4000), @my_cur CURSOR OUTPUT',
        @field = @field,
        @query = @query,
        @my_cur = @my_cur OUTPUT
    FETCH NEXT FROM @my_cur INTO @inputList
    WHILE @@FETCH_STATUS = 0
    BEGIN
        PRINT @inputList
        FETCH NEXT FROM @my_cur INTO @inputList
    END
    RETURN

C free(): invalid pointer

You're attempting to free something that isn't a pointer to a "freeable" memory address. Just because something is an address doesn't mean that you need to or should free it.

There are two main types of memory you seem to be confusing - stack memory and heap memory.

  • Stack memory lives in the live span of the function. It's temporary space for things that shouldn't grow too big. When you call the function main, it sets aside some memory for your variables you've declared (p,token, and so on).

  • Heap memory lives from when you malloc it to when you free it. You can use much more heap memory than you can stack memory. You also need to keep track of it - it's not easy like stack memory!

You have a few errors:

  • You're trying to free memory that's not heap memory. Don't do that.

  • You're trying to free the inside of a block of memory. When you have in fact allocated a block of memory, you can only free it from the pointer returned by malloc. That is to say, only from the beginning of the block. You can't free a portion of the block from the inside.

For your bit of code here, you probably want to find a way to copy relevant portion of memory to somewhere else...say another block of memory you've set aside. Or you can modify the original string if you want (hint: char value 0 is the null terminator and tells functions like printf to stop reading the string).

EDIT: The malloc function does allocate heap memory*.

"9.9.1 The malloc and free Functions

The C standard library provides an explicit allocator known as the malloc package. Programs allocate blocks from the heap by calling the malloc function."

~Computer Systems : A Programmer's Perspective, 2nd Edition, Bryant & O'Hallaron, 2011

EDIT 2: * The C standard does not, in fact, specify anything about the heap or the stack. However, for anyone learning on a relevant desktop/laptop machine, the distinction is probably unnecessary and confusing if anything, especially if you're learning about how your program is stored and executed. When you find yourself working on something like an AVR microcontroller as H2CO3 has, it is definitely worthwhile to note all the differences, which from my own experience with embedded systems, extend well past memory allocation.

How to parse a text file with C#

You could do something like:

using (TextReader rdr = OpenYourFile()) {
    string line;
    while ((line = rdr.ReadLine()) != null) {
        string[] fields = line.Split('\t'); // THIS LINE DOES THE MAGIC
        int theInt = Convert.ToInt32(fields[1]);
    }
}

The reason you didn't find relevant result when searching for 'formatting' is that the operation you are performing is called 'parsing'.

Update Item to Revision vs Revert to Revision

The files in your working copy might look exactly the same after, but they are still very different actions -- the repository is in a completely different state, and you will have different options available to you after reverting than "updating" to an old revision.

Briefly, "update to" only affects your working copy, but "reverse merge and commit" will affect the repository.

If you "update" to an old revision, then the repository has not changed: in your example, the HEAD revision is still 100. You don't have to commit anything, since you are just messing around with your working copy. If you make modifications to your working copy and try to commit, you will be told that your working copy is out-of-date, and you will need to update before you can commit. If someone else working on the same repository performs an "update", or if you check out a second working copy, it will be r100.

However, if you "reverse merge" to an old revision, then your working copy is still based on the HEAD (assuming you are up-to-date) -- but you are creating a new revision to supersede the unwanted changes. You have to commit these changes, since you are changing the repository. Once done, any updates or new working copies based on the HEAD will show r101, with the contents you just committed.

Homebrew install specific version of formula?

Update on the Library/Formula/postgresql.rb line 8 to

http://ftp2.uk.postgresql.org/sites/ftp.postgresql.org/source/v8.4.6/postgresql-8.4.6.tar.bz2

And MD5 on line 9 to

fcc3daaf2292fa6bf1185ec45e512db6

Save and exit.

brew install postgres
initdb /usr/local/var/postgres

Now in this stage you might face the postgresql could not create shared memory segment error, to work around that update the /etc/sysctl.conf like this:

kern.sysv.shmall=65536
kern.sysv.shmmax=16777216

Try initdb /usr/local/var/postgres again, and it should run smooth.

To run postgresql on start

launchctl load -w /usr/local/Cellar/postgresql/8.4.6/org.postgresql.postgres.plist

Hope that helps :)

How do I specify C:\Program Files without a space in it for programs that can't handle spaces in file paths?

Never hardcode this location. Use the environment variables %ProgramFiles% or %ProgramFiles(x86)%.

When specifying these, always quote because Microsoft may have put spaces or other special characters in them.

"%ProgramFiles%\theapp\app.exe"
"%ProgramFiles(x86)%\theapp\app.exe"

In addition, the directory might be expressed in a language you do not know. http://www.samlogic.net/articles/program-files-folder-different-languages.htm

>set|findstr /i /r ".*program.*="
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files

Use these commands to find the values on a machine. DO NOT hardcode them into a program or .bat or .cmd file script. Use the variable.

set | findstr /R "^Program"
set | findstr /R "^Common"

How to use data-binding with Fragment

Even the other answers may work well, but I want tell best approach.

Use Binding class's inflate as recommended in Android Documentation.

One option is to inflate by DataBindingUtil but when only you don't know have generated binding class.

--You have auto generated binding class, use that class instead of using DataBindingUtil.

In Java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    HomeFragmentBinding binding = HomeFragmentBinding.inflate(inflater, container, false);
    //set binding variables here
    return binding.getRoot();
}

In Kotlin

lateinit var binding: HomeFragmentBinding 
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    binding = HomeFragmentBinding.inflate(inflater, container, false)
    return binding.root
}

In DataBindingUtil class documentation you can see.

inflate

T inflate (LayoutInflater inflater, 
                int layoutId, 
                ViewGroup parent, 
                boolean attachToParent)

Use this version only if layoutId is unknown in advance. Otherwise, use the generated Binding's inflate method to ensure type-safe inflation.

If your layout biniding class is not generated @See this answer.

JavaScript function in href vs. onclick

Personally, I find putting javascript calls in the HREF tag annoying. I usually don't really pay attention to whether or not something is a javascript link or not, and often times want to open things in a new window. When I try doing this with one of these types of links, I get a blank page with nothing on it and javascript in my location bar. However, this is sidestepped a bit by using an onlick.

MySQL Data - Best way to implement paging?

This tutorial shows a great way to do pagination. Efficient Pagination Using MySQL

In short, avoid to use OFFSET or large LIMIT

Can I dynamically add HTML within a div tag from C# on load event?

You can add a div with runat="server" to the page:

<div runat="server" id="myDiv">
</div>

and then set its InnerHtml property from the code-behind:

myDiv.InnerHtml = "your html here";

If you want to modify the DIV's contents on the client side, then you can use javascript code similar to this:

<script type="text/javascript">
    Sys.Application.add_load(MyLoad);
    function MyLoad(sender) {
        $get('<%= div.ClientID %>').innerHTML += " - text added on client";
    }
</script>

How can I extract audio from video with ffmpeg?

Just a guess:

-ab 192

should be

-ab 192k

Seems like that could be a problem, but maybe ffmpeg is smart enough to correct it.

How to create custom exceptions in Java?

public class MyException extends Exception {
        // special exception code goes here
}

Throw it as:

 throw new MyException ("Something happened")

Catch as:

catch (MyException e)
{
   // something
}

What is http multipart request?

A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.

What is a NullPointerException, and how do I fix it?

A lot of explanations are already present to explain how it happens and how to fix it, but you should also follow best practices to avoid NullPointerExceptions at all.

See also: A good list of best practices

I would add, very important, make a good use of the final modifier. Using the "final" modifier whenever applicable in Java

Summary:

  1. Use the final modifier to enforce good initialization.
  2. Avoid returning null in methods, for example returning empty collections when applicable.
  3. Use annotations @NotNull and @Nullable
  4. Fail fast and use asserts to avoid propagation of null objects through the whole application when they shouldn't be null.
  5. Use equals with a known object first: if("knownObject".equals(unknownObject)
  6. Prefer valueOf() over toString().
  7. Use null safe StringUtils methods StringUtils.isEmpty(null).
  8. Use Java 8 Optional as return value in methods, Optional class provide a solution for representing optional values instead of null references.

Determine if Android app is being used for the first time

You can use the SharedPreferences to identify if it is the "First time" the app is launched. Just use a Boolean variable ("my_first_time") and change its value to false when your task for "first time" is over.

This is my code to catch the first time you open the app:

final String PREFS_NAME = "MyPrefsFile";

SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

if (settings.getBoolean("my_first_time", true)) {
    //the app is being launched for first time, do something        
    Log.d("Comments", "First time");

             // first time task

    // record the fact that the app has been started at least once
    settings.edit().putBoolean("my_first_time", false).commit(); 
}

getting the error: expected identifier or ‘(’ before ‘{’ token

you need to place the opening brace after main , not before it

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{

how to check for null with a ng-if values in a view with angularjs?

You can also use ng-template, I think that would be more efficient while run time :)

<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
    <div>2</div>
</ng-template>

Cheers

Put current changes in a new Git branch

You can simply check out a new branch, and then commit:

git checkout -b my_new_branch
git commit

Checking out the new branch will not discard your changes.

Do I need to convert .CER to .CRT for Apache SSL certificates? If so, how?

I use command:

openssl x509 -inform PEM -in certificate.cer -out certificate.crt

But CER is an X.509 certificate in binary form, DER encoded. CRT is a binary X.509 certificate, encapsulated in text (base-64) encoding.

Because of that, you maybe should use:

openssl x509 -inform DER -in certificate.cer -out certificate.crt

And then to import your certificate:

Copy your CA to dir:

/usr/local/share/ca-certificates/

Use command:

sudo cp foo.crt /usr/local/share/ca-certificates/foo.crt

Update the CA store:

sudo update-ca-certificates

Python 3 TypeError: must be str, not bytes with sys.stdout.write()

Python 3 handles strings a bit different. Originally there was just one type for strings: str. When unicode gained traction in the '90s the new unicode type was added to handle Unicode without breaking pre-existing code1. This is effectively the same as str but with multibyte support.

In Python 3 there are two different types:

  • The bytes type. This is just a sequence of bytes, Python doesn't know anything about how to interpret this as characters.
  • The str type. This is also a sequence of bytes, but Python knows how to interpret those bytes as characters.
  • The separate unicode type was dropped. str now supports unicode.

In Python 2 implicitly assuming an encoding could cause a lot of problems; you could end up using the wrong encoding, or the data may not have an encoding at all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to guess) is often a lot better and much more in line with the "Python philosophy" of "explicit is better than implicit".

This change is incompatible with Python 2 as many return values have changed, leading to subtle problems like this one; it's probably the main reason why Python 3 adoption has been so slow. Since Python doesn't have static typing2 it's impossible to change this automatically with a script (such as the bundled 2to3).

  • You can convert str to bytes with bytes('h€llo', 'utf-8'); this should produce b'H\xe2\x82\xacllo'. Note how one character was converted to three bytes.
  • You can convert bytes to str with b'H\xe2\x82\xacllo'.decode('utf-8').

Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.

In your specific piece of code, nextline is of type bytes, not str, reading stdout and stdin from subprocess changed in Python 3 from str to bytes. This is because Python can't be sure which encoding this uses. It probably uses the same as sys.stdin.encoding (the encoding of your system), but it can't be sure.

You need to replace:

sys.stdout.write(nextline)

with:

sys.stdout.write(nextline.decode('utf-8'))

or maybe:

sys.stdout.write(nextline.decode(sys.stdout.encoding))

You will also need to modify if nextline == '' to if nextline == b'' since:

>>> '' == b''
False

Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.


1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A') and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.

2 Yes, you can use function annotations, but it's a comparatively new feature and little used.