Programs & Examples On #Hwpf

Apache POI - HWPF - Java API to Handle Microsoft Word Files

How read Doc or Docx file in java?

Here is the code of ReadDoc/docx.java: This will read a dox/docx file and print its content to the console. you can customize it your way.

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile
{
    public static void main(String[] args)
    {
        File file = null;
        WordExtractor extractor = null;
        try
        {

            file = new File("c:\\New.doc");
            FileInputStream fis = new FileInputStream(file.getAbsolutePath());
            HWPFDocument document = new HWPFDocument(fis);
            extractor = new WordExtractor(document);
            String[] fileData = extractor.getParagraphText();
            for (int i = 0; i < fileData.length; i++)
            {
                if (fileData[i] != null)
                    System.out.println(fileData[i]);
            }
        }
        catch (Exception exep)
        {
            exep.printStackTrace();
        }
    }
}

Give column name when read csv file pandas

we can do it with a single line of code.

 user1 = pd.read_csv('dataset/1.csv', names=['TIME', 'X', 'Y', 'Z'], header=None)

While variable is not defined - wait

I prefer something simple like this:

function waitFor(variable, callback) {
  var interval = setInterval(function() {
    if (window[variable]) {
      clearInterval(interval);
      callback();
    }
  }, 200);
}

And then to use it with your example variable of someVariable:

waitFor('someVariable', function() {
  // do something here now that someVariable is defined
});

Note that there are various tweaks you can do. In the above setInterval call, I've passed 200 as how often the interval function should run. There is also an inherent delay of that amount of time (~200ms) before the variable is checked for -- in some cases, it's nice to check for it right away so there is no delay.

CodeIgniter : Unable to load the requested file:

An Error Was Encountered Unable to load the requested file:

Sometimes we face this error because the requested file doesn't exist in that directory.

Suppose we have a folder home in views directory and trying to load home_view.php file as:

$this->load->view('home/home_view', $data);// $data is array

If home_view.php file doesn't exist in views/home directory then it will raise an error.

An Error Was Encountered Unable to load the requested file: home\home_view.php

So how to fix this error go to views/home and check the home_view.php file exist if not then create it.

How to make an image center (vertically & horizontally) inside a bigger div

This is coming a bit late, but here's a solution I use to vertical align elements within a parent div.

This is useful for when you know the size of the container div, but not that of the contained image. (this is frequently the case when working with lightboxes or image carousels).

Here's the styling you should try:

 container div
 {
   display:table-cell;
   vertical-align:middle;

   height:200px;
   width:200px;
 }

 img
 {
   /*Apply any styling here*/        
 }

How to remove provisioning profiles from Xcode

Post deleting and adding your new profile, you can verify if the profile is active and been take by your project by running below command.

grep -i "yourproject" *.mobileprovision

Android WebView Cookie Problem

I have faced same problem and It will resolve this issue in all android versions

private void setCookie() {
    try {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cookieManager.setCookie(Constant.BASE_URL, getCookie(), value -> {
                String cookie = cookieManager.getCookie(Constant.BASE_URL);
                CookieManager.getInstance().flush();
                CustomLog.d("cookie", "cookie ------>" + cookie);
                setupWebView();
            });
        } else {
            cookieManager.setCookie(webUrl, getCookie());
            new Handler().postDelayed(this::setupWebView, 700);
            CookieSyncManager.getInstance().sync();
        }

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

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Not a proper answer but in my case

something completely strange. I was trying from last six hours using Transporter app, Application Loader and via Xcode but none of them was working.
And suddenly I got an error message on the Transporter app that App with same version number is already available on Apple store. So App was uploaded but the progress status of the app (Transporter, Xcode, Application Loader) did not notify me. Try to change your network, if possible try with other system.

must appear in the GROUP BY clause or be used in an aggregate function

For me, it is not about a "common aggregation problem", but just about an incorrect SQL query. The single correct answer for "select the maximum avg for each cname..." is

SELECT cname, MAX(avg) FROM makerar GROUP BY cname;

The result will be:

 cname  |      MAX(avg)
--------+---------------------
 canada | 2.0000000000000000
 spain  | 5.0000000000000000

This result in general answers the question "What is the best result for each group?". We see that the best result for spain is 5 and for canada the best result is 2. It is true, and there is no error. If we need to display wmname also, we have to answer the question: "What is the RULE to choose wmname from resulting set?" Let's change the input data a bit to clarify the mistake:

  cname | wmname |        avg           
--------+--------+-----------------------
 spain  | zoro   |  1.0000000000000000
 spain  | luffy  |  5.0000000000000000
 spain  | usopp  |  5.0000000000000000

Which result do you expect on runnig this query: SELECT cname, wmname, MAX(avg) FROM makerar GROUP BY cname;? Should it be spain+luffy or spain+usopp? Why? It is not determined in the query how to choose "better" wmname if several are suitable, so the result is also not determined. That's why SQL interpreter returns an error - the query is not correct.

In the other word, there is no correct answer to the question "Who is the best in spain group?". Luffy is not better than usopp, because usopp has the same "score".

javax.xml.bind.JAXBException: Class *** nor any of its super class is known to this context

Ftrujillo's answer works well but if you only have one package to scan this is the shortest form::

    @Bean
    public Jaxb2Marshaller marshaller() {
        Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
        marshaller.setContextPath("your.package.to.scan");
        return marshaller;
    }

Algorithm for Determining Tic Tac Toe Game Over

I made some optimization in the row, col, diagonal checks. Its mainly decided in the first nested loop if we need to check a particular column or diagonal. So, we avoid checking of columns or diagonals saving time. This makes big impact when the board size is more and a significant number of the cells are not filled.

Here is the java code for that.

    int gameState(int values[][], int boardSz) {


    boolean colCheckNotRequired[] = new boolean[boardSz];//default is false
    boolean diag1CheckNotRequired = false;
    boolean diag2CheckNotRequired = false;
    boolean allFilled = true;


    int x_count = 0;
    int o_count = 0;
    /* Check rows */
    for (int i = 0; i < boardSz; i++) {
        x_count = o_count = 0;
        for (int j = 0; j < boardSz; j++) {
            if(values[i][j] == x_val)x_count++;
            if(values[i][j] == o_val)o_count++;
            if(values[i][j] == 0)
            {
                colCheckNotRequired[j] = true;
                if(i==j)diag1CheckNotRequired = true;
                if(i + j == boardSz - 1)diag2CheckNotRequired = true;
                allFilled = false;
                //No need check further
                break;
            }
        }
        if(x_count == boardSz)return X_WIN;
        if(o_count == boardSz)return O_WIN;         
    }


    /* check cols */
    for (int i = 0; i < boardSz; i++) {
        x_count = o_count = 0;
        if(colCheckNotRequired[i] == false)
        {
            for (int j = 0; j < boardSz; j++) {
                if(values[j][i] == x_val)x_count++;
                if(values[j][i] == o_val)o_count++;
                //No need check further
                if(values[i][j] == 0)break;
            }
            if(x_count == boardSz)return X_WIN;
            if(o_count == boardSz)return O_WIN;
        }
    }

    x_count = o_count = 0;
    /* check diagonal 1 */
    if(diag1CheckNotRequired == false)
    {
        for (int i = 0; i < boardSz; i++) {
            if(values[i][i] == x_val)x_count++;
            if(values[i][i] == o_val)o_count++;
            if(values[i][i] == 0)break;
        }
        if(x_count == boardSz)return X_WIN;
        if(o_count == boardSz)return O_WIN;
    }

    x_count = o_count = 0;
    /* check diagonal 2 */
    if( diag2CheckNotRequired == false)
    {
        for (int i = boardSz - 1,j = 0; i >= 0 && j < boardSz; i--,j++) {
            if(values[j][i] == x_val)x_count++;
            if(values[j][i] == o_val)o_count++;
            if(values[j][i] == 0)break;
        }
        if(x_count == boardSz)return X_WIN;
        if(o_count == boardSz)return O_WIN;
        x_count = o_count = 0;
    }

    if( allFilled == true)
    {
        for (int i = 0; i < boardSz; i++) {
            for (int j = 0; j < boardSz; j++) {
                if (values[i][j] == 0) {
                    allFilled = false;
                    break;
                }
            }

            if (allFilled == false) {
                break;
            }
        }
    }

    if (allFilled)
        return DRAW;

    return INPROGRESS;
}

How to scroll to the bottom of a UITableView on the iPhone before the view appears

I'm using autolayout and none of the answers worked for me. Here is my solution that finally worked:

@property (nonatomic, assign) BOOL shouldScrollToLastRow;


- (void)viewDidLoad {
    [super viewDidLoad];

    _shouldScrollToLastRow = YES;
}


- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    // Scroll table view to the last row
    if (_shouldScrollToLastRow)
    {
        _shouldScrollToLastRow = NO;
        [self.tableView setContentOffset:CGPointMake(0, CGFLOAT_MAX)];
    }
}

Are Git forks actually Git clones?

I think fork is a copy of other repository but with your account modification. for example, if you directly clone other repository locally, the remote object origin is still using the account who you clone from. You can't commit and contribute your code. It is just a pure copy of codes. Otherwise, If you fork a repository, it will clone the repo with the update of your account setting in you github account. And then cloning the repo in the context of your account, you can commit your codes.

Get webpage contents with Python?

A solution with works with Python 2.X and Python 3.X:

try:
    # For Python 3.0 and later
    from urllib.request import urlopen
except ImportError:
    # Fall back to Python 2's urllib2
    from urllib2 import urlopen

url = 'http://hiscore.runescape.com/index_lite.ws?player=zezima'
response = urlopen(url)
data = str(response.read())

Twitter Bootstrap 3 Sticky Footer

I wanted a flexible sticky footer, which is why I came here. Top answers got me in the right direction.

The current (2 Oct 16) Bootstrap 3 css Sticky footer (Fixed size) looks like this:

html {
  position: relative;
  min-height: 100%;
}
body {
  /* Margin bottom by footer height */
  margin-bottom: 60px;
}
.footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  /* Set the fixed height of the footer here */
  height: 60px;
  background-color: #f5f5f5;
}

As long as the footer has a fixed size, the body margin-bottom creates a push to allow a pocket for the footer to sit in. In this case, both are set to 60px. But if the footer is not fixed and exceeds 60px height, it will cover your page content.

Make Flexible: Delete the css body margin and footer height. Then add JavaScript to get the footer height and set the body marginBottom. That is done with the setfooter() function. Next add event listeners for when the page first loads and on resizing that run the setfooter. Note: If you footer has an accordion or anything else that triggers a size change, without a resize of window, you must call the setfooter() function again.

Run the snippet and then fullscreen to demo it.

_x000D_
_x000D_
function setfooter(){_x000D_
 var ht = document.getElementById("footer").scrollHeight;_x000D_
 document.body.style.marginBottom = ht + "px";_x000D_
}_x000D_
_x000D_
window.addEventListener('resize', function(){_x000D_
  setfooter();_x000D_
 }, true);_x000D_
window.addEventListener('load', function(){_x000D_
 setfooter();_x000D_
}, true);
_x000D_
html {_x000D_
  position: relative;_x000D_
  min-height: 100%;_x000D_
}_x000D_
.footer {_x000D_
  position: absolute;_x000D_
  bottom: 0;_x000D_
  width: 100%;_x000D_
  _x000D_
  /* additional style for effect only */_x000D_
   text-align: center;_x000D_
    background-color: #333;_x000D_
    color: #fff;_x000D_
}_x000D_
  _x000D_
_x000D_
_x000D_
body{_x000D_
/* additional style for effect only not needed in bootstrap*/_x000D_
  padding:0;_x000D_
  margin: 0;_x000D_
  }
_x000D_
<div>_x000D_
  Page content_x000D_
  <br>  <br>_x000D_
  line 3_x000D_
  <br>  <br>_x000D_
  line 5_x000D_
  <br>  <br>_x000D_
  line 7_x000D_
  _x000D_
 </div>_x000D_
_x000D_
_x000D_
<footer id="footer" class="footer">_x000D_
      <div class="container">_x000D_
        <p class="text-muted">Footer with a long text, so that resizing, to a smaller screen size, will cause the footer to grow taller. But the footer will not overflow onto the main page.</p>_x000D_
      </div>_x000D_
    </footer>
_x000D_
_x000D_
_x000D_

How to specify maven's distributionManagement organisation wide?

Regarding the answer from Michael Wyraz, where you use alt*DeploymentRepository in your settings.xml or command on the line, be careful if you are using version 3.0.0-M1 of the maven-deploy-plugin (which is the latest version at the time of writing), there is a bug in this version that could cause a server authentication issue.

A workaround is as follows. In the value:

releases::default::https://YOUR_NEXUS_URL/releases

you need to remove the default section, making it:

releases::https://YOUR_NEXUS_URL/releases

The prior version 2.8.2 does not have this bug.

Selecting all text in HTML text input when clicked

The problem with catching the click event is that each subsequent click within the text will select it again, whereas the user was probably expecting to reposition the cursor.

What worked for me was declaring a variable, selectSearchTextOnClick, and setting it to true by default. The click handler checks that the variable's still true: if it is, it sets it to false and performs the select(). I then have a blur event handler which sets it back to true.

Results so far seem like the behavior I'd expect.

(Edit: I neglected to say that I'd tried catching the focus event as someone suggested,but that doesn't work: after the focus event fires, the click event can fire, immediately deselecting the text).

Compile to stand alone exe for C# app in Visual Studio 2010

Are you sure you selected Console Application? I'm running VS 2010 and with the vanilla settings a C# console app builds to \bin\debug. Try to create a new Console Application project, with the language set to C#. Build the project, and go to Project/[Console Application 1]Properties. In the Build tab, what is the Output path? It should default to bin\debug, unless you have some restricted settings on your workstation,etc. Also review the build output window and see if any errors are being thrown - in which case nothing will be built to the output folder, of course...

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.

How to access elements of a JArray (or iterate over them)

Once you have a JArray you can treat it just like any other Enumerable object, and using linq you can access them, check them, verify them, and select them.

var str = @"[1, 2, 3]";
var jArray = JArray.Parse(str);
Console.WriteLine(String.Join("-", jArray.Where(i => (int)i > 1).Select(i => i.ToString())));

How does one represent the empty char?

To represent the fact that the value is not present you have two choices:

1) If the whole char range is meaningful and you cannot reserve any value, then use char* instead of char:

char** c = new char*[N];
c[0] = NULL; // no character
*c[1] = ' '; // ordinary character
*c[2] = 'a'; // ordinary character
*c[3] = '\0' // zero-code character

Then you'll have c[i] == NULL for when character is not present and otherwise *c[i] for ordinary characters.

2) If you don't need some values representable in char then reserve one for indicating that value is not present, for example the '\0' character.

char* c = new char[N];
c[0] = '\0'; // no character
c[1] = ' '; // ordinary character
c[2] = 'a'; // ordinary character

Then you'll have c[i] == '\0' for when character is not present and ordinary characters otherwise.

How do I get which JRadioButton is selected from a ButtonGroup

import javax.swing.Action;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.JRadioButton;
import javax.swing.JToggleButton;

public class RadioButton extends JRadioButton {

    public class RadioButtonModel extends JToggleButton.ToggleButtonModel {
        public Object[] getSelectedObjects() {
            if ( isSelected() ) {
                return new Object[] { RadioButton.this };
            } else {
                return new Object[0];
            }
        }

        public RadioButton getButton() { return RadioButton.this; }
    }

    public RadioButton() { super(); setModel(new RadioButtonModel()); }
    public RadioButton(Action action) { super(action); setModel(new RadioButtonModel()); }
    public RadioButton(Icon icon) { super(icon); setModel(new RadioButtonModel()); }
    public RadioButton(String text) { super(text); setModel(new RadioButtonModel()); }
    public RadioButton(Icon icon, boolean selected) { super(icon, selected); setModel(new RadioButtonModel()); }
    public RadioButton(String text, boolean selected) { super(text, selected); setModel(new RadioButtonModel()); }
    public RadioButton(String text, Icon icon) { super(text, icon); setModel(new RadioButtonModel()); }
    public RadioButton(String text, Icon icon, boolean selected) { super(text, icon, selected); setModel(new RadioButtonModel()); }

    public static void main(String[] args) {
        RadioButton b1 = new RadioButton("A");
        RadioButton b2 = new RadioButton("B");
        ButtonGroup group = new ButtonGroup();
        group.add(b1);
        group.add(b2);
        b2.setSelected(true);
        RadioButtonModel model = (RadioButtonModel)group.getSelection();
        System.out.println(model.getButton().getText());
    }
}

converting a base 64 string to an image and saving it

If you have a string of binary data which is Base64 encoded, you should be able to do the following:

byte[] encodedDataAsBytes = System.Convert.FromBase64String(encodedData);

You should be able to write the resulting array to a file.

How do I install the babel-polyfill library?

First off, the obvious answer that no one has provided, you need to install Babel into your application:

npm install babel --save

(or babel-core if you instead want to require('babel-core/polyfill')).

Aside from that, I have a grunt task to transpile my es6 and jsx as a build step (i.e. I don't want to use babel/register, which is why I am trying to use babel/polyfill directly in the first place), so I'd like to put more emphasis on this part of @ssube's answer:

Make sure you require it at the entry-point to your application, before anything else is called

I ran into some weird issue where I was trying to require babel/polyfill from some shared environment startup file and I got the error the user referenced - I think it might have had something to do with how babel orders imports versus requires but I'm unable to reproduce now. Anyway, moving import 'babel/polyfill' as the first line in both my client and server startup scripts fixed the problem.

Note that if you instead want to use require('babel/polyfill') I would make sure all your other module loader statements are also requires and not use imports - avoid mixing the two. In other words, if you have any import statements in your startup script, make import babel/polyfill the first line in your script rather than require('babel/polyfill').

Circle line-segment collision detection algorithm?

If the line's coordinates are A.x, A.y and B.x, B.y and the circles center is C.x, C.y then the lines formulae are:

x = A.x * t + B.x * (1 - t)

y = A.y * t + B.y * (1 - t)

where 0<=t<=1

and the circle is

(C.x - x)^2 + (C.y - y)^2 = R^2

if you substitute x and y formulae of the line into the circles formula you get a second order equation of t and its solutions are the intersection points (if there are any). If you get a t which is smaller than 0 or greater than 1 then its not a solution but it shows that the line is 'pointing' to the direction of the circle.

Nginx subdomain configuration

Another type of solution would be to autogenerate the nginx conf files via Jinja2 templates from ansible. The advantage of this is easy deployment to a cloud environment, and easy to replicate on multiple dev machines

Remove Primary Key in MySQL

I believe Quassnoi has answered your direct question. Just a side note: Maybe this is just some awkward wording on your part, but you seem to be under the impression that you have three primary keys, one on each field. This is not the case. By definition, you can only have one primary key. What you have here is a primary key that is a composite of three fields. Thus, you cannot "drop the primary key on a column". You can drop the primary key, or not drop the primary key. If you want a primary key that only includes one column, you can drop the existing primary key on 3 columns and create a new primary key on 1 column.

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.

For an array:

var array = [];
array[0] = "hello";
array[1] = 5498;
array[536] = new Date();

As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain any type of variable! That's pretty convenient.

But as we all know JavaScript is strange, so here are some weird bits:

array["0"] === "hello"; // This is true
array["hi"]; // undefined
array["hi"] = "weird"; // works but does not save any data to array
array["hi"]; // still undefined!

This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.

So what are Objects?

Objects in JavaScript are just like arrays but the "index" can be any string.

var object = {};
object[0] = "hello"; // OK
object["hi"] = "not weird"; // OK

You can even opt to not use the square brackets when working with objects!

console.log(object.hi); // Prints 'not weird'
object.hi = "overwriting 'not weird'";

You can go even further and define objects like so:

var newObject = {
    a: 2,
};
newObject.a === 2; // true

Why is Java's SimpleDateFormat not thread-safe?

Here’s an example defines a SimpleDateFormat object as a static field. When two or more threads access “someMethod” concurrently with different dates, they can mess with each other’s results.

    public class SimpleDateFormatExample {
         private static final SimpleDateFormat simpleFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

         public String someMethod(Date date) {
            return simpleFormat.format(date);
         }
    }

You can create a service like below and use jmeter to simulate concurrent users using the same SimpleDateFormat object formatting different dates and their results will be messed up.

public class FormattedTimeHandler extends AbstractHandler {

private static final String OUTPUT_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss.SSS";
private static final String INPUT_TIME_FORMAT = "yyyy-MM-ddHH:mm:ss";
private static final SimpleDateFormat simpleFormat = new SimpleDateFormat(OUTPUT_TIME_FORMAT);
// apache commons lang3 FastDateFormat is threadsafe
private static final FastDateFormat fastFormat = FastDateFormat.getInstance(OUTPUT_TIME_FORMAT);

public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {

    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    baseRequest.setHandled(true);

    final String inputTime = request.getParameter("time");
    Date date = LocalDateTime.parse(inputTime, DateTimeFormat.forPattern(INPUT_TIME_FORMAT)).toDate();

    final String method = request.getParameter("method");
    if ("SimpleDateFormat".equalsIgnoreCase(method)) {
        // use SimpleDateFormat as a static constant field, not thread safe
        response.getWriter().println(simpleFormat.format(date));
    } else if ("FastDateFormat".equalsIgnoreCase(method)) {
        // use apache commons lang3 FastDateFormat, thread safe
        response.getWriter().println(fastFormat.format(date));
    } else {
        // create new SimpleDateFormat instance when formatting date, thread safe
        response.getWriter().println(new SimpleDateFormat(OUTPUT_TIME_FORMAT).format(date));
    }
}

public static void main(String[] args) throws Exception {
    // embedded jetty configuration, running on port 8090. change it as needed.
    Server server = new Server(8090);
    server.setHandler(new FormattedTimeHandler());

    server.start();
    server.join();
}

}

The code and jmeter script can be downloaded here .

Import Excel to Datagridview

try this following snippet, its working fine.

private void button1_Click(object sender, EventArgs e)
{
     try
     {
             OpenFileDialog openfile1 = new OpenFileDialog();
             if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
             {
                   this.textBox1.Text = openfile1.FileName;
             }
             {
                   string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
                   OleDbConnection conn = new OleDbConnection(pathconn);
                   OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
                   DataTable dt = new DataTable();
                   MyDataAdapter.Fill(dt);
                   dataGridView1.DataSource = dt;
             }
      }
      catch { }
}

SPA best practices for authentication and session management

This question has been addressed, in a slightly different form, at length, here:

RESTful Authentication

But this addresses it from the server-side. Let's look at this from the client-side. Before we do that, though, there's an important prelude:

Javascript Crypto is Hopeless

Matasano's article on this is famous, but the lessons contained therein are pretty important:

https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/august/javascript-cryptography-considered-harmful/

To summarize:

  • A man-in-the-middle attack can trivially replace your crypto code with <script> function hash_algorithm(password){ lol_nope_send_it_to_me_instead(password); }</script>
  • A man-in-the-middle attack is trivial against a page that serves any resource over a non-SSL connection.
  • Once you have SSL, you're using real crypto anyways.

And to add a corollary of my own:

  • A successful XSS attack can result in an attacker executing code on your client's browser, even if you're using SSL - so even if you've got every hatch battened down, your browser crypto can still fail if your attacker finds a way to execute any javascript code on someone else's browser.

This renders a lot of RESTful authentication schemes impossible or silly if you're intending to use a JavaScript client. Let's look!

HTTP Basic Auth

First and foremost, HTTP Basic Auth. The simplest of schemes: simply pass a name and password with every request.

This, of course, absolutely requires SSL, because you're passing a Base64 (reversibly) encoded name and password with every request. Anybody listening on the line could extract username and password trivially. Most of the "Basic Auth is insecure" arguments come from a place of "Basic Auth over HTTP" which is an awful idea.

The browser provides baked-in HTTP Basic Auth support, but it is ugly as sin and you probably shouldn't use it for your app. The alternative, though, is to stash username and password in JavaScript.

This is the most RESTful solution. The server requires no knowledge of state whatsoever and authenticates every individual interaction with the user. Some REST enthusiasts (mostly strawmen) insist that maintaining any sort of state is heresy and will froth at the mouth if you think of any other authentication method. There are theoretical benefits to this sort of standards-compliance - it's supported by Apache out of the box - you could store your objects as files in folders protected by .htaccess files if your heart desired!

The problem? You are caching on the client-side a username and password. This gives evil.ru a better crack at it - even the most basic of XSS vulnerabilities could result in the client beaming his username and password to an evil server. You could try to alleviate this risk by hashing and salting the password, but remember: JavaScript Crypto is Hopeless. You could alleviate this risk by leaving it up to the Browser's Basic Auth support, but.. ugly as sin, as mentioned earlier.

HTTP Digest Auth

Is Digest authentication possible with jQuery?

A more "secure" auth, this is a request/response hash challenge. Except JavaScript Crypto is Hopeless, so it only works over SSL and you still have to cache the username and password on the client side, making it more complicated than HTTP Basic Auth but no more secure.

Query Authentication with Additional Signature Parameters.

Another more "secure" auth, where you encrypt your parameters with nonce and timing data (to protect against repeat and timing attacks) and send the. One of the best examples of this is the OAuth 1.0 protocol, which is, as far as I know, a pretty stonking way to implement authentication on a REST server.

http://tools.ietf.org/html/rfc5849

Oh, but there aren't any OAuth 1.0 clients for JavaScript. Why?

JavaScript Crypto is Hopeless, remember. JavaScript can't participate in OAuth 1.0 without SSL, and you still have to store the client's username and password locally - which puts this in the same category as Digest Auth - it's more complicated than HTTP Basic Auth but it's no more secure.

Token

The user sends a username and password, and in exchange gets a token that can be used to authenticate requests.

This is marginally more secure than HTTP Basic Auth, because as soon as the username/password transaction is complete you can discard the sensitive data. It's also less RESTful, as tokens constitute "state" and make the server implementation more complicated.

SSL Still

The rub though, is that you still have to send that initial username and password to get a token. Sensitive information still touches your compromisable JavaScript.

To protect your user's credentials, you still need to keep attackers out of your JavaScript, and you still need to send a username and password over the wire. SSL Required.

Token Expiry

It's common to enforce token policies like "hey, when this token has been around too long, discard it and make the user authenticate again." or "I'm pretty sure that the only IP address allowed to use this token is XXX.XXX.XXX.XXX". Many of these policies are pretty good ideas.

Firesheeping

However, using a token Without SSL is still vulnerable to an attack called 'sidejacking': http://codebutler.github.io/firesheep/

The attacker doesn't get your user's credentials, but they can still pretend to be your user, which can be pretty bad.

tl;dr: Sending unencrypted tokens over the wire means that attackers can easily nab those tokens and pretend to be your user. FireSheep is a program that makes this very easy.

A Separate, More Secure Zone

The larger the application that you're running, the harder it is to absolutely ensure that they won't be able to inject some code that changes how you process sensitive data. Do you absolutely trust your CDN? Your advertisers? Your own code base?

Common for credit card details and less common for username and password - some implementers keep 'sensitive data entry' on a separate page from the rest of their application, a page that can be tightly controlled and locked down as best as possible, preferably one that is difficult to phish users with.

Cookie (just means Token)

It is possible (and common) to put the authentication token in a cookie. This doesn't change any of the properties of auth with the token, it's more of a convenience thing. All of the previous arguments still apply.

Session (still just means Token)

Session Auth is just Token authentication, but with a few differences that make it seem like a slightly different thing:

  • Users start with an unauthenticated token.
  • The backend maintains a 'state' object that is tied to a user's token.
  • The token is provided in a cookie.
  • The application environment abstracts the details away from you.

Aside from that, though, it's no different from Token Auth, really.

This wanders even further from a RESTful implementation - with state objects you're going further and further down the path of plain ol' RPC on a stateful server.

OAuth 2.0

OAuth 2.0 looks at the problem of "How does Software A give Software B access to User X's data without Software B having access to User X's login credentials."

The implementation is very much just a standard way for a user to get a token, and then for a third party service to go "yep, this user and this token match, and you can get some of their data from us now."

Fundamentally, though, OAuth 2.0 is just a token protocol. It exhibits the same properties as other token protocols - you still need SSL to protect those tokens - it just changes up how those tokens are generated.

There are two ways that OAuth 2.0 can help you:

  • Providing Authentication/Information to Others
  • Getting Authentication/Information from Others

But when it comes down to it, you're just... using tokens.

Back to your question

So, the question that you're asking is "should I store my token in a cookie and have my environment's automatic session management take care of the details, or should I store my token in Javascript and handle those details myself?"

And the answer is: do whatever makes you happy.

The thing about automatic session management, though, is that there's a lot of magic happening behind the scenes for you. Often it's nicer to be in control of those details yourself.

I am 21 so SSL is yes

The other answer is: Use https for everything or brigands will steal your users' passwords and tokens.

What exactly does numpy.exp() do?

The exponential function is e^x where e is a mathematical constant called Euler's number, approximately 2.718281. This value has a close mathematical relationship with pi and the slope of the curve e^x is equal to its value at every point. np.exp() calculates e^x for each value of x in your input array.

How to paste into a terminal?

On windows 7:

Ctrl + Shift + Ins

works for me!

Insert current date in datetime format mySQL

It depends on what datatype you set for your db table.

DATETIME (datatype)

MYSQL
INSERT INTO t1 (dateposted) VALUES ( NOW() )
// This will insert date and time into the col. Do not use quote around the val
PHP
$dt = date('Y-m-d h:i:s');
INSERT INTO t1 (dateposted) VALUES ( '$dt' )
// This will insert date into the col using php var. Wrap with quote.

DATE (datatype)

MYSQL
INSERT INTO t1 (dateposted) VALUES ( NOW() )
// Yes, you use the same NOW() without the quotes.
// Because your datatype is set to DATE it will insert only the date
PHP
$dt = date('Y-m-d');
INSERT INTO t1 (dateposted) VALUES ( '$dt' )
// This will insert date into the col using php var.

TIME (datatype)

MYSQL
INSERT INTO t1 (dateposted) VALUES ( NOW() )
// Yes, you use the same NOW() as well. 
// Because your datatype is set to TIME it will insert only the time
PHP
$dt = date('h:i:s');
INSERT INTO t1 (dateposted) VALUES ( '$dt' )
// This will insert time.

How to normalize a histogram in MATLAB?

hist can not only plot an histogram but also return you the count of elements in each bin, so you can get that count, normalize it by dividing each bin by the total and plotting the result using bar. Example:

Y = rand(10,1);
C = hist(Y);
C = C ./ sum(C);
bar(C)

or if you want a one-liner:

bar(hist(Y) ./ sum(hist(Y)))

Documentation:

Edit: This solution answers the question How to have the sum of all bins equal to 1. This approximation is valid only if your bin size is small relative to the variance of your data. The sum used here correspond to a simple quadrature formula, more complex ones can be used like trapz as proposed by R. M.

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

I had the same problem. Thank you to everyone else who answered - I was able to get a solution together using parts of several of these answers.

My solution is using swift 5

The problem that we are trying to solve is that we may have images with different aspect ratios in our TableViewCells but we want them to render with consistent widths. The images should, of course, render with no distortion and fill the entire space. In my case, I was fine with some "cropping" of tall, skinny images, so I used the content mode .scaleAspectFill

To do this, I created a custom subclass of UITableViewCell. In my case, I named it StoryTableViewCell. The entire class is pasted below, with comments inline.

This approach worked for me when also using a custom Accessory View and long text labels. Here's an image of the final result:

Rendered Table View with consistent image width

class StoryTableViewCell: UITableViewCell {

    override func layoutSubviews() {
        super.layoutSubviews()

        // ==== Step 1 ====
        // ensure we have an image
        guard let imageView = self.imageView else {return}

        // create a variable for the desired image width
        let desiredWidth:CGFloat = 70;

        // get the width of the image currently rendered in the cell
        let currentImageWidth = imageView.frame.size.width;

        // grab the width of the entire cell's contents, to be used later
        let contentWidth = self.contentView.bounds.width

        // ==== Step 2 ====
        // only update the image's width if the current image width isn't what we want it to be
        if (currentImageWidth != desiredWidth) {
            //calculate the difference in width
            let widthDifference = currentImageWidth - desiredWidth;

            // ==== Step 3 ====
            // Update the image's frame,
            // maintaining it's original x and y values, but with a new width
            self.imageView?.frame = CGRect(imageView.frame.origin.x,
                                           imageView.frame.origin.y,
                                           desiredWidth,
                                           imageView.frame.size.height);

            // ==== Step 4 ====
            // If there is a texst label, we want to move it's x position to
            // ensure it isn't overlapping with the image, and that it has proper spacing with the image
            if let textLabel = self.textLabel
            {
                let originalFrame = self.textLabel?.frame

                // the new X position for the label is just the original position,
                // minus the difference in the image's width
                let newX = textLabel.frame.origin.x - widthDifference
                self.textLabel?.frame = CGRect(newX,
                                               textLabel.frame.origin.y,
                                               contentWidth - newX,
                                               textLabel.frame.size.height);
                print("textLabel info: Original =\(originalFrame!)", "updated=\(self.textLabel!.frame)")
            }

            // ==== Step 4 ====
            // If there is a detail text label, do the same as step 3
            if let detailTextLabel = self.detailTextLabel {
                let originalFrame = self.detailTextLabel?.frame
                let newX = detailTextLabel.frame.origin.x-widthDifference
                self.detailTextLabel?.frame = CGRect(x: newX,
                                                     y: detailTextLabel.frame.origin.y,
                                                     width: contentWidth - newX,
                                                     height: detailTextLabel.frame.size.height);
                print("detailLabel info: Original =\(originalFrame!)", "updated=\(self.detailTextLabel!.frame)")
            }

            // ==== Step 5 ====
            // Set the image's content modoe to scaleAspectFill so it takes up the entire view, but doesn't get distorted
            self.imageView?.contentMode = .scaleAspectFill;
        }
    }
}

YouTube Autoplay not working

You can use embed player with opacity over on a cover photo with a right positioned play icon. After this you can check the activeElement of your document.

Of course I know this is not an optimal solution, but works on mobile devices too.

<div style="position: relative;">
   <img src="http://s3.amazonaws.com/content.newsok.com/newsok/images/mobile/play_button.png" style="position:absolute;top:0;left:0;opacity:1;" id="cover">
   <iframe width="560" height="315" src="https://www.youtube.com/embed/2qhCjgMKoN4?controls=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in- picture" allowfullscreen style="position: absolute;top:0;left:0;opacity:0;" id="player"></iframe>
 </div>
 <script>
   setInterval(function(){
      if(document.activeElement instanceof HTMLIFrameElement){
         document.getElementById('cover').style.opacity=0;
         document.getElementById('player').style.opacity=1;
       }
    } , 50);
  </script>

Try it on codepen: https://codepen.io/sarkiroka/pen/OryxGP

How can I quickly delete a line in VIM starting at the cursor position?

(Edited to include commenter's good additions:)

D or its equivalent d$ will delete the rest of the line and leave you in command mode. C or c$ will delete the rest of the line and put you in insert mode, and new text will be appended to the line.

This is part of vitutor and vimtutor, excellent "reads" for vim beginners.

adb server version doesn't match this client

Got a quick way to do it First

sudo rm /usr/bin/adb

Then

sudo ln -s /home/{{username}}/Android/Sdk/platform-tools/adb  /usr/bin/adb

Fastest way to fix the issue

An existing connection was forcibly closed by the remote host

Simple solution for this common annoying issue:

Just go to your ".context.cs" file (located under ".context.tt" which located under your "*.edmx" file).

Then, add this line to your constructor:

public DBEntities() 
        : base("name=DBEntities") 
    { 
        this.Configuration.ProxyCreationEnabled = false; // ADD THIS LINE !
    }

hope this is helpful.

Calling @Html.Partial to display a partial view belonging to a different controller

As GvS said, but I also find it useful to use strongly typed views so that I can write something like

@Html.Partial(MVC.Student.Index(), model)

without magic strings.

Remove the complete styling of an HTML button/submit

I'm assuming that when you say 'click the button, it moves to the top a little' you're talking about the mouse down click state for the button, and that when you release the mouse click, it returns to its normal state? And that you're disabling the default rendering of the button by using:

input, button, submit { border:none; } 

If so..

Personally, I've found that you can't actually stop/override/disable this IE native action, which led me to change my markup a little to allow for this movement and not affect the overall look of the button for the various states.

This is my final mark-up:

_x000D_
_x000D_
<span class="your-button-class">_x000D_
    <span>_x000D_
        <input type="Submit" value="View Person">_x000D_
    </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

Django gives Bad Request (400) when DEBUG = False

I had to stop the apache server first.

(f.e. sudo systemctl stop httpd.service / sudo systemctl disable httpd.service).

That solved my problem besides editing the 'settings.py' file

to ALLOWED_HOSTS = ['se.rv.er.ip', 'www.example.com']

What is the most efficient way to create HTML elements using jQuery?

Actually, if you're doing $('<div>'), jQuery will also use document.createElement().

(Just take a look at line 117).

There is some function-call overhead, but unless performance is critical (you're creating hundreds [thousands] of elements), there isn't much reason to revert to plain DOM.

Just creating elements for a new webpage is probably a case in which you'll best stick to the jQuery way of doing things.

Error handling with PHPMailer

You can get more info about the error with the method $mail->ErrorInfo. For example:

if(!$mail->send()) {
    echo 'Message could not be sent.';
    echo 'Mailer Error: ' . $mail->ErrorInfo;
} else {
    echo 'Message has been sent';
}

This is an alternative to the exception model that you need to active with new PHPMailer(true). But if can use exception model, use it as @Phil Rykoff answer.

This comes from the main page of PHPMailer on github https://github.com/PHPMailer/PHPMailer.

Object passed as parameter to another class, by value or reference?

An Object if passed as a value type then changes made to the members of the object inside the method are impacted outside the method also. But if the object itself is set to another object or reinitialized then it will not be reflected outside the method. So i would say object as a whole is passed as Valuetype only but object members are still reference type.

        private void button1_Click(object sender, EventArgs e)
    {
        Class1 objc ;
         objc = new Class1();
        objc.empName = "name1";
        checkobj( objc);
        MessageBox.Show(objc.empName);  //propert value changed; but object itself did not change
    }
    private void checkobj ( Class1 objc)
    {
        objc.empName = "name 2";
        Class1 objD = new Class1();
        objD.empName ="name 3";
        objc = objD ;
        MessageBox.Show(objc.empName);  //name 3
    }

Fixed position but relative to container

You can give a try to my jQuery plugin, FixTo.

Usage:

$('#mydiv').fixTo('#centeredContainer');

How to store token in Local or Session Storage in Angular 2?

var arr=[{"username":"sai","email":"[email protected],"}]
localStorage.setItem('logInArr', JSON.stringfy(arr))

Java int to String - Integer.toString(i) vs new Integer(i).toString()

  1. new Integer(i).toString();

    This statement creates the object of the Integer and then call its methods toString(i) to return the String representation of Integer's value.

  2. Integer.toString(i);

    It returns the String object representing the specific int (integer), but here toString(int) is a static method.

Summary is in first case it returns the objects string representation, where as in second case it returns the string representation of integer.

Using Python's list index() method on a list of tuples or objects?

I guess the following is not the best way to do it (speed and elegance concerns) but well, it could help :

from collections import OrderedDict as od
t = [('pineapple', 5), ('cherry', 7), ('kumquat', 3), ('plum', 11)]
list(od(t).keys()).index('kumquat')
2
list(od(t).values()).index(7)
7
# bonus :
od(t)['kumquat']
3

list of tuples with 2 members can be converted to ordered dict directly, data structures are actually the same, so we can use dict method on the fly.

hasNext in Python iterators?

There's an alternative to the StopIteration by using next(iterator, default_value).

For exapmle:

>>> a = iter('hi')
>>> print next(a, None)
h
>>> print next(a, None)
i
>>> print next(a, None)
None

So you can detect for None or other pre-specified value for end of the iterator if you don't want the exception way.

How to check if the user can go back in browser history or not

this seems to do the trick:

function goBackOrClose() {  

    window.history.back();
    window.close(); 

    //or if you are not interested in closing the window, do something else here
    //e.g. 
    theBrowserCantGoBack();

}

Call history.back() and then window.close(). If the browser is able to go back in history it won't be able to get to the next statement. If it's not able to go back, it'll close the window.

However, please note that if the page has been reached by typing a url, then firefox wont allow the script to close the window.

Installation error: INSTALL_FAILED_OLDER_SDK

This error occurs when the sdk-version installed on your device (real or virtual device) is smaller than android:minSdkVersion in your android manifest.

You either have to decrease your android:minSdkVersion or you have to specify a higher api-version for your AVD.

Keep in mind, that it is not always trivial to decrease android:minSdkVersion as you have to make sure, your app cares about the actual installed API and uses the correct methods:

AsyncTask<String, Object, String> task = new AsyncTask<String, Object, String>() {
    @Override
    protected Boolean doInBackground(String... params) {
        if (params == null) return "";
        StringBuilder b = new StringBuilder();
        for (String p : params) {
             b.append(p);
        }
        return b.toString();
    }
};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,"Hello", " ", "world!");
} else {
    task.execute("Hello", " ", "world!");
}

Using the android-support-library and/or libraries like actionbar-sherlock will help you dealing especially with widgets of older versions.

How to resize the jQuery DatePicker control

We can alter in the default 'jquery-ui.css' file as below given code:

div.ui-datepicker {
font-size: 80%; 
}

However, changing the default 'jquery-ui.css' file is not recommended as it might have been used somewhere else in the project. Changing values in the default file can alter datepicker font in other webpages where it has been used.

I used the below code to alter "font-size". I placed it just after datepicker() is called as shown below.

<script>
        $(function () {
            $( "#datepicker" ).datepicker();
            $("div.ui-datepicker").css("font-size", "80%")
        });
</script>

Hope this helps...

How do I copy directories recursively with gulp?

So - the solution of providing a base works given that all of the paths have the same base path. But if you want to provide different base paths, this still won't work.

One way I solved this problem was by making the beginning of the path relative. For your case:

gulp.src([
    'index.php',
    '*css/**/*',
    '*js/**/*',
    '*src/**/*',
])
.pipe(gulp.dest('/var/www/'));

The reason this works is that Gulp sets the base to be the end of the first explicit chunk - the leading * causes it to set the base at the cwd (which is the result that we all want!)

This only works if you can ensure your folder structure won't have certain paths that could match twice. For example, if you had randomjs/ at the same level as js, you would end up matching both.

This is the only way that I have found to include these as part of a top-level gulp.src function. It would likely be simple to create a plugin/function that could separate out each of those globs so you could specify the base directory for them, however.

Cast object to T

You can presumably pass-in, as a parameter, a delegate which will convert from string to T.

Clear data in MySQL table with PHP?

TRUNCATE TABLE mytable

Be careful with it though.

How to process a file in PowerShell line-by-line as a stream

If you are really about to work on multi-gigabyte text files then do not use PowerShell. Even if you find a way to read it faster processing of huge amount of lines will be slow in PowerShell anyway and you cannot avoid this. Even simple loops are expensive, say for 10 million iterations (quite real in your case) we have:

# "empty" loop: takes 10 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) {} }

# "simple" job, just output: takes 20 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i } }

# "more real job": 107 seconds
measure-command { for($i=0; $i -lt 10000000; ++$i) { $i.ToString() -match '1' } }

UPDATE: If you are still not scared then try to use the .NET reader:

$reader = [System.IO.File]::OpenText("my.log")
try {
    for() {
        $line = $reader.ReadLine()
        if ($line -eq $null) { break }
        # process the line
        $line
    }
}
finally {
    $reader.Close()
}

UPDATE 2

There are comments about possibly better / shorter code. There is nothing wrong with the original code with for and it is not pseudo-code. But the shorter (shortest?) variant of the reading loop is

$reader = [System.IO.File]::OpenText("my.log")
while($null -ne ($line = $reader.ReadLine())) {
    $line
}

Arithmetic operation resulted in an overflow. (Adding integers)

The result integer value is out of the range which an integer data type can hold.

Try using Int64

How to monitor the memory usage of Node.js?

node-memwatch : detect and find memory leaks in Node.JS code. Check this tutorial Tracking Down Memory Leaks in Node.js

How to resize JLabel ImageIcon?

Try this :

ImageIcon imageIcon = new ImageIcon("./img/imageName.png"); // load the image to a imageIcon
Image image = imageIcon.getImage(); // transform it 
Image newimg = image.getScaledInstance(120, 120,  java.awt.Image.SCALE_SMOOTH); // scale it the smooth way  
imageIcon = new ImageIcon(newimg);  // transform it back

(found it here)

Question mark and colon in JavaScript

It is called the Conditional Operator (which is a ternary operator).

It has the form of: condition ? value-if-true : value-if-false
Think of the ? as "then" and : as "else".

Your code is equivalent to

if (max != 0)
  hsb.s = 255 * delta / max;
else
  hsb.s = 0;

Windows Bat file optional argument parsing

Dynamic variables creation

enter image description here

Pros

  • Works for >9 arguments
  • Keeps %1, %2, ... %* in tact
  • Works for both /arg and -arg style
  • No prior knowledge about arguments
  • Implementation is separate from main routine

Cons

  • Old arguments may leak into consecutive runs, therefore use setlocal for local scoping or write an accompanying :CLEAR-ARGS routine!
  • No alias support yet (like --force to -f)
  • No empty "" argument support

Usage

Here is an example how the following arguments relate to .bat variables:

>> testargs.bat /b 3 -c /d /e /f /g /h /i /j /k /bar 5 /foo "c:\"

echo %*        | /b 3 -c /d /e /f /g /h /i /j /k /bar 5 /foo "c:\"
echo %ARG_FOO% | c:\
echo %ARG_A%   |
echo %ARG_B%   | 3
echo %ARG_C%   | 1
echo %ARG_D%   | 1

Implementation

@echo off
setlocal

CALL :ARG-PARSER %*

::Print examples
echo: ALL: %*
echo: FOO: %ARG_FOO%
echo: A:   %ARG_A%
echo: B:   %ARG_B%
echo: C:   %ARG_C%
echo: D:   %ARG_D%


::*********************************************************
:: Parse commandline arguments into sane variables
:: See the following scenario as usage example:
:: >> thisfile.bat /a /b "c:\" /c /foo 5
:: >> CALL :ARG-PARSER %*
:: ARG_a=1
:: ARG_b=c:\
:: ARG_c=1
:: ARG_foo=5
::*********************************************************
:ARG-PARSER
    ::Loop until two consecutive empty args
    :loopargs
        IF "%~1%~2" EQU "" GOTO :EOF

        set "arg1=%~1" 
        set "arg2=%~2"
        shift

        ::Allow either / or -
        set "tst1=%arg1:-=/%"
        if "%arg1%" NEQ "" (
            set "tst1=%tst1:~0,1%"
        ) ELSE (
            set "tst1="
        )

        set "tst2=%arg2:-=/%"
        if "%arg2%" NEQ "" (
            set "tst2=%tst2:~0,1%"
        ) ELSE (
            set "tst2="
        )


        ::Capture assignments (eg. /foo bar)
        IF "%tst1%" EQU "/"  IF "%tst2%" NEQ "/" IF "%tst2%" NEQ "" (
            set "ARG_%arg1:~1%=%arg2%"
            GOTO loopargs
        )

        ::Capture flags (eg. /foo)
        IF "%tst1%" EQU "/" (
            set "ARG_%arg1:~1%=1"
            GOTO loopargs
        )
    goto loopargs
GOTO :EOF

How to escape the equals sign in properties files

The best way to avoid this kind of issues it to build properties programmatically and then store them. For example, using code like this:

java.util.Properties props = new java.util.Properties();
props.setProperty("table.whereclause", "where id=100");
props.store(System.out, null);

This would output to System.out the properly escaped version.

In my case the output was:

#Mon Aug 12 13:50:56 EEST 2013
table.whereclause=where id\=100

As you can see, this is an easy way to generate content of .properties files that's guaranteed to be correct. And you can put as many properties as you want.

HTML-parser on Node.js

If you want to build DOM you can use jsdom.

There's also cheerio, it has the jQuery interface and it's a lot faster than older versions of jsdom, although these days they are similar in performance.

You might wanna have a look at htmlparser2, which is a streaming parser, and according to its benchmark, it seems to be faster than others, and no DOM by default. It can also produce a DOM, as it is also bundled with a handler that creates a DOM. This is the parser that is used by cheerio.

parse5 also looks like a good solution. It's fairly active (11 days since the last commit as of this update), WHATWG-compliant, and is used in jsdom, Angular, and Polymer.

And if you want to parse HTML for web scraping, you can use YQL1. There is a node module for it. YQL I think would be the best solution if your HTML is from a static website, since you are relying on a service, not your own code and processing power. Though note that it won't work if the page is disallowed by the robot.txt of the website, YQL won't work with it.

If the website you're trying to scrape is dynamic then you should be using a headless browser like phantomjs. Also have a look at casperjs, if you're considering phantomjs. And you can control casperjs from node with SpookyJS.

Beside phantomjs there's zombiejs. Unlike phantomjs that cannot be embedded in nodejs, zombiejs is just a node module.

There's a nettuts+ toturial for the latter solutions.


1 Since Aug. 2014, YUI library, which is a requirement for YQL, is no longer actively maintained, source

View/edit ID3 data for MP3 files

TagLib Sharp has support for reading ID3 tags.

Test whether string is a valid integer

You can strip non-digits and do a comparison. Here's a demo script:

for num in "44" "-44" "44-" "4-4" "a4" "4a" ".4" "4.4" "-4.4" "09"
do
    match=${num//[^[:digit:]]}    # strip non-digits
    match=${match#0*}             # strip leading zeros
    echo -en "$num\t$match\t"
    case $num in
        $match|-$match)    echo "Integer";;
                     *)    echo "Not integer";;
    esac
done

This is what the test output looks like:

44      44      Integer
-44     44      Integer
44-     44      Not integer
4-4     44      Not integer
a4      4       Not integer
4a      4       Not integer
.4      4       Not integer
4.4     44      Not integer
-4.4    44      Not integer
09      9       Not integer

Angular2 set value for formGroup

You can use form.get to get the specific control object and use setValue

this.form.get(<formControlName>).setValue(<newValue>);

Running a command in a new Mac OS X Terminal window

I've been trying to do this for a while. Here is a script that changes to the same working directory, runs the command, and closes the terminal window.

#!/bin/sh 
osascript <<END 
tell application "Terminal"
    do script "cd \"`pwd`\";$1;exit"
end tell
END

How many times does each value appear in a column?

I second Dave's idea. I'm not always fond of pivot tables, but in this case they are pretty straightforward to use.

Here are my results:

Enter image description here

It was so simple to create it that I have even recorded a macro in case you need to do this with VBA:

Sub Macro2()
'
' Macro2 Macro
'

'
    Range("Table1[[#All],[DATA]]").Select
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "Table1", Version:=xlPivotTableVersion14).CreatePivotTable TableDestination _
        :="Sheet3!R3C7", TableName:="PivotTable4", DefaultVersion:= _
        xlPivotTableVersion14
    Sheets("Sheet3").Select
    Cells(3, 7).Select
    With ActiveSheet.PivotTables("PivotTable4").PivotFields("DATA")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable4").AddDataField ActiveSheet.PivotTables( _
        "PivotTable4").PivotFields("DATA"), "Count of DATA", xlCount
End Sub

What does "Git push non-fast-forward updates were rejected" mean?

GitHub has a nice section called "Dealing with “non-fast-forward” errors"

This error can be a bit overwhelming at first, do not fear.
Simply put, git cannot make the change on the remote without losing commits, so it refuses the push.
Usually this is caused by another user pushing to the same branch. You can remedy this by fetching and merging the remote branch, or using pull to perform both at once.

In other cases this error is a result of destructive changes made locally by using commands like git commit --amend or git rebase.
While you can override the remote by adding --force to the push command, you should only do so if you are absolutely certain this is what you want to do.
Force-pushes can cause issues for other users that have fetched the remote branch, and is considered bad practice. When in doubt, don’t force-push.


Git cannot make changes on the remote like a fast-forward merge, which a Visual Git Reference illustrates like:

alt text

This is not exactly your case, but helps to see what "fast-forward" is (where the HEAD of a branch is simply moved to a new more recent commit).


The "branch master->master (non-fast-forward) Already-up-to-date" is usually for local branches which don't track their remote counter-part.
See for instance this SO question "git pull says up-to-date but git push rejects non-fast forward".
Or the two branches are connected, but in disagreement with their respective history:
See "Never-ending GIT story - what am I doing wrong here?"

This means that your subversion branch and your remote git master branch do not agree on something.
Some change was pushed/committed to one that is not in the other.
Fire up gitk --all, and it should give you a clue as to what went wrong - look for "forks" in the history.

How to determine the longest increasing subsequence using dynamic programming?

def longestincrsub(arr1):
    n=len(arr1)
    l=[1]*n
    for i in range(0,n):
        for j in range(0,i)  :
            if arr1[j]<arr1[i] and l[i]<l[j] + 1:
                l[i] =l[j] + 1
    l.sort()
    return l[-1]
arr1=[10,22,9,33,21,50,41,60]
a=longestincrsub(arr1)
print(a)

even though there is a way by which you can solve this in O(nlogn) time(this solves in O(n^2) time) but still this way gives the dynamic programming approach which is also good .

Why am I getting an OPTIONS request instead of a GET request?

I had the same problem. My fix was to add headers to my PHP script which are present only when in dev environment.

This allows cross-domain requests:

header("Access-Control-Allow-Origin: *");

This tells the preflight request that it is OK for the client to send any headers it wants:

header("Access-Control-Allow-Headers: *");

This way there is no need to modify the request.

If you have sensitive data in your dev database that might potentially be leaked, then you might think twice about this.

Method to Add new or update existing item in Dictionary

I know it is not Dictionary<TKey, TValue> class, however you can avoid KeyNotFoundException while incrementing a value like:

dictionary[key]++; // throws `KeyNotFoundException` if there is no such key  

by using ConcurrentDictionary<TKey, TValue> and its really nice method AddOrUpdate()..

Let me show an example:

var str = "Hellooo!!!";
var characters = new ConcurrentDictionary<char, int>();
foreach (var ch in str)
    characters.AddOrUpdate(ch, 1, (k, v) => v + 1);

AppFabric installation failed because installer MSI returned with error code : 1603

I fixed this error in my deployment. It only occured for me if I had run the installer once before. As soon as you start the Installer, it will create a temporary folder. Copy that folder and save it off with a different name. Now cancel that install.

Open Regedit and search (CTRL+F) for "AppFabric". You should find an entry under HKEY_CLASSES_ROOT\Installer\Products{SomeStringOfCharacters}. Under that check SourceList it will have a Key called LastUsedSource. Update the folder path within it to match the temporary folder we just saved off. Also check SourceList/Net. It will likely have multiple keys with numeric Names. Make sure the Data value for them match your temporary folder path as well.

Now go into your temporary folder and run Setup.exe. It should complete now. I've seen behavior like this with other installers that first extract files to a temporary folder. Re-running the installer mostly works from the new temporary folder but some aspect of it holds on to the old temporary folder in the registry and tries to load something up from the old location.

@Scope("prototype") bean scope not creating new bean

Just because the bean injected into the controller is prototype-scoped doesn't mean the controller is!

What does java.lang.Thread.interrupt() do?

An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate. A very good referance: https://docs.oracle.com/javase/tutorial/essential/concurrency/interrupt.html

PHP new line break in emails

you can use "Line1<br>Line2"

Find the greatest number in a list of numbers

    #Ask for number input
first = int(raw_input('Please type a number: '))
second = int(raw_input('Please type a number: '))
third = int(raw_input('Please type a number: '))
fourth = int(raw_input('Please type a number: '))
fifth = int(raw_input('Please type a number: '))
sixth = int(raw_input('Please type a number: '))
seventh = int(raw_input('Please type a number: '))
eighth = int(raw_input('Please type a number: '))
ninth = int(raw_input('Please type a number: '))
tenth = int(raw_input('Please type a number: '))

    #create a list for variables
sorted_list = [first, second, third, fourth, fifth, sixth, seventh, 
              eighth, ninth, tenth]
odd_numbers = []

    #filter list and add odd numbers to new list
for value in sorted_list:
    if value%2 != 0:
        odd_numbers.append(value)
print 'The greatest odd number you typed was:', max(odd_numbers)

How to serialize a JObject without the formatting?

You can also do the following;

string json = myJObject.ToString(Newtonsoft.Json.Formatting.None);

Retrieve column names from java.sql.ResultSet

ResultSet rsTst = hiSession.connection().prepareStatement(queryStr).executeQuery(); 
ResultSetMetaData meta = rsTst.getMetaData();
int columnCount = meta.getColumnCount();
// The column count starts from 1

String nameValuePair = "";
while (rsTst.next()) {
    for (int i = 1; i < columnCount + 1; i++ ) {
        String name = meta.getColumnName(i);
        // Do stuff with name

        String value = rsTst.getString(i); //.getObject(1);
        nameValuePair = nameValuePair + name + "=" +value + ",";
        //nameValuePair = nameValuePair + ", ";
    }
    nameValuePair = nameValuePair+"||" + "\t";
}

Overriding the java equals() method - not working?

Slightly off-topic to your question, but it's probably worth mentioning anyway:

Commons Lang has got some excellent methods you can use in overriding equals and hashcode. Check out EqualsBuilder.reflectionEquals(...) and HashCodeBuilder.reflectionHashCode(...). Saved me plenty of headache in the past - although of course if you just want to do "equals" on ID it may not fit your circumstances.

I also agree that you should use the @Override annotation whenever you're overriding equals (or any other method).

What's the difference between import java.util.*; and import java.util.Date; ?

Your program should work exactly the same with either import java.util.*; or import java.util.Date;. There has to be something else you did in between.

What is the purpose of flush() in Java streams?

For performance issue, first data is to be written into Buffer. When buffer get full then data is written to output (File,console etc.). When buffer is partially filled and you want to send it to output(file,console) then you need to call flush() method manually in order to write partially filled buffer to output(file,console).

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

I finally found a solution. I wasted hours just trying to figure what this issue was. I tried deleting all those files suggested above and it didn't work for me, I tried adding new inbound rules to firewall for myslqd.exe and it didn't work. The thing that is causing this error is MySQL port is misconfigured and the fix was really simple. if you are using Wamp or Xampp go to Main Folder/Bin/mysql/mysql/ and find a file named my.ini

Open my.ini file press CTRL + F and inside it search for PORT and change whatever value of port to - 3306 and save file;

After that go to Wamp icon at the bottom of the taskbar (system tray) and left click choose mysql option and click "test port 3306 used" and see if it gives you any error. you can also click use other port other than whatever is shown there and port 3306.

Goodluck. if it works comment.

enter image description here

How to edit binary file on Unix systems

There are much more hexeditors on Linux/Unix....

I use hexedit on Ubuntu

sudo apt-get install hexedit

Auto increment primary key in SQL Server Management Studio 2012

Expand your database, expand your table right click on your table and select design from dropdown. ITlooks like this

Now go Column properties below of it scroll down and find Identity Specification, expand it and you will find Is Identity make it Yes. Now choose Identity Increment right below of it give the value you want to increment in it. enter image description here

Need to navigate to a folder in command prompt

Just use the change directory (cd) command.

cd d:\windows\movie

Enabling the OpenSSL in XAMPP

Yes, you must open php.ini and remove the semicolon to:

;extension=php_openssl.dll

If you don't have that line, check that you have the file (In my PC is on D:\xampp\php\ext) and add this to php.ini in the "Dynamic Extensions" section:

extension=php_openssl.dll

Things have changed for PHP > 7. This is what i had to do for PHP 7.2.

Step: 1: Uncomment extension=openssl

Step: 2: Uncomment extension_dir = "ext"

Step: 3: Restart xampp.

Done.

Explanation: ( From php.ini )

If you wish to have an extension loaded automatically, use the following syntax:

extension=modulename

Note : The syntax used in previous PHP versions (extension=<ext>.so and extension='php_<ext>.dll) is supported for legacy reasons and may be deprecated in a future PHP major version. So, when it is possible, please move to the new (extension=<ext>) syntax.

Special Note: Be sure to appropriately set the extension_dir directive.

Determine file creation date in Java

As a follow-up to this question - since it relates specifically to creation time and discusses obtaining it via the new nio classes - it seems right now in JDK7's implementation you're out of luck. Addendum: same behaviour is in OpenJDK7.

On Unix filesystems you cannot retrieve the creation timestamp, you simply get a copy of the last modification time. So sad, but unfortunately true. I'm not sure why that is but the code specifically does that as the following will demonstrate.

import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;

public class TestFA {
  static void getAttributes(String pathStr) throws IOException {
    Path p = Paths.get(pathStr);
    BasicFileAttributes view
       = Files.getFileAttributeView(p, BasicFileAttributeView.class)
              .readAttributes();
    System.out.println(view.creationTime()+" is the same as "+view.lastModifiedTime());
  }
  public static void main(String[] args) throws IOException {
    for (String s : args) {
        getAttributes(s);
    }
  }
}

C library function to perform sort

There are several C sorting functions available in stdlib.h. You can do man 3 qsort on a unix machine to get a listing of them but they include:

  • heapsort
  • quicksort
  • mergesort

How do I get Month and Date of JavaScript in 2 digit format?

My solution:

function addLeadingChars(string, nrOfChars, leadingChar) {
    string = string + '';
    return Array(Math.max(0, (nrOfChars || 2) - string.length + 1)).join(leadingChar || '0') + string;
}

Usage:

var
    date = new Date(),
    month = addLeadingChars(date.getMonth() + 1),
    day = addLeadingChars(date.getDate());

jsfiddle: http://jsfiddle.net/8xy4Q/1/

HTML5 <video> element on Android

According to : https://stackoverflow.com/a/24403519/365229

This should work, with plain Javascript:

var myVideo = document.getElementById('myVideoTag');

myVideo.play();
if (typeof(myVideo.webkitEnterFullscreen) != "undefined") {
    // This is for Android Stock.
    myVideo.webkitEnterFullscreen();
} else if (typeof(myVideo.webkitRequestFullscreen)  != "undefined") {
    // This is for Chrome.
    myVideo.webkitRequestFullscreen();
} else if (typeof(myVideo.mozRequestFullScreen)  != "undefined") {
    myVideo.mozRequestFullScreen();
}

You have to trigger play() before the fullscreen instruction, otherwise in Android Browser it will just go fullscreen but it will not start playing. Tested with the latest version of Android Browser, Chrome, Safari.

I've tested it on Android 2.3.3 & 4.4 browser.

How to add "active" class to Html.ActionLink in ASP.NET MVC

if is it is not showing at all, the reason is that you need two @ sign:

@@class

BUT, I believe you might need to have the active class on the "li" tag not on the "a" tag. according too bootstrap docs (http://getbootstrap.com/components/#navbar-default):

<ul class="nav navbar-nav">
  <li class="active"><a href="#">Home</a></li>
  <li><a href="#">Profile</a></li>
  <li><a href="#">Messages</a></li>
</ul>

therefore your code will be:

<ul class="nav navbar-nav">
  <li class="active">@Html.ActionLink("Home", "Index", "Home", null)</li>
  <li>@Html.ActionLink("About", "About", "Home")</li>
  <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>

Go install fails with error: no install location for directory xxx outside GOPATH

For any OS X users and future me, you also need to set GOBIN to avoid this confusing message on install and go get

mkdir bin 
export GOBIN=$GOPATH/bin

Html attributes for EditorFor() in ASP.NET MVC

If you don't want to use Metadata you can use a [UIHint("PeriodType")] attribute to decorate the property or if its a complex type you don't have to decorate anything. EditorFor will then look for a PeriodType.aspx or ascx file in the EditorTemplates folder and use that instead.

select certain columns of a data table

First store the table in a view, then select columns from that view into a new table.

// Create a table with abitrary columns for use with the example
System.Data.DataTable table = new System.Data.DataTable();
for (int i = 1; i <= 11; i++)
    table.Columns.Add("col" + i.ToString());

// Load the table with contrived data
for (int i = 0; i < 100; i++)
{
    System.Data.DataRow row = table.NewRow();
    for (int j = 0; j < 11; j++)
        row[j] = i.ToString() + ", " + j.ToString();
    table.Rows.Add(row);
}

// Create the DataView of the DataTable
System.Data.DataView view = new System.Data.DataView(table);
// Create a new DataTable from the DataView with just the columns desired - and in the order desired
System.Data.DataTable selected = view.ToTable("Selected", false, "col1", "col2", "col6", "col7", "col3");

Used the sample data to test this method I found: Create ADO.NET DataView showing only selected Columns

When should null values of Boolean be used?

Boolean wrapper is useful when you want to whether value was assigned or not apart from true and false. It has the following three states:

  • True
  • False
  • Not defined which is null

Whereas boolean has only two states:

  • True
  • False

The above difference will make it helpful in Lists of Boolean values, which can have True, False or Null.

Import .bak file to a database in SQL server

  1. Connect to a server you want to store your DB
  2. Right-click Database
  3. Click Restore
  4. Choose the Device radio button under the source section
  5. Click Add.
  6. Navigate to the path where your .bak file is stored, select it and click OK
  7. Enter the destination of your DB
  8. Enter the name by which you want to store your DB
  9. Click OK

Done

How can I avoid ResultSet is closed exception in Java?

I got same error everything was correct only i was using same statement interface object to execute and update the database. After separating i.e. using different objects of statement interface for updating and executing query i resolved this error. i.e. do get rid from this do not use same statement object for both updating and executing the query.

Why are my CSS3 media queries not working on mobile devices?

Don't forget to have the standard css declarations above the media query or the query won't work either.

.edcar_letter{
    font-size:180px;
}

@media screen and (max-width: 350px) {
    .edcar_letter{
        font-size:120px;
    }
}

How do I read text from the clipboard?

I've seen many suggestions to use the win32 module, but Tkinter provides the shortest and easiest method I've seen, as in this post: How do I copy a string to the clipboard on Windows using Python?

Plus, Tkinter is in the python standard library.

Why is visible="false" not working for a plain html table?

For the best practice - use style="display:"

it will work every where..

How to have Android Service communicate with Activity

To follow up on @MrSnowflake answer with a code example. This is the XABBER now open source Application class. The Application class is centralising and coordinating Listeners and ManagerInterfaces and more. Managers of all sorts are dynamically loaded. Activity´s started in the Xabber will report in what type of Listener they are. And when a Service start it report in to the Application class as started. Now to send a message to an Activity all you have to do is make your Activity become a listener of what type you need. In the OnStart() OnPause() register/unreg. The Service can ask the Application class for just that listener it need to speak to and if it's there then the Activity is ready to receive.

Going through the Application class you'll see there's a loot more going on then this.

Handling the null value from a resultset in JAVA

I came across with the same issue. But I believe , handling null in the sql is not a good option. such things should be handled in java program for better performance. secondly , rs.getString("column") != NULL is also not a good option as you are comparing string's reference not value. better to use .equals() method while checking null or isEmpty() method. Again, with this you can use null check, that is fine.

Is there any native DLL export functions viewer?

DLL Export Viewer by NirSoft can be used to display exported functions in a DLL.

This utility displays the list of all exported functions and their virtual memory addresses for the specified DLL files. You can easily copy the memory address of the desired function, paste it into your debugger, and set a breakpoint for this memory address. When this function is called, the debugger will stop in the beginning of this function.

enter image description here

how to programmatically fake a touch event to a UIButton?

An update to this answer for Swift

buttonObj.sendActionsForControlEvents(.TouchUpInside)

EDIT: Updated for Swift 3

buttonObj.sendActions(for: .touchUpInside)

Calling a Variable from another Class

I would suggest to use a variable instead of a public field:

public class Variables
{
   private static string name = "";

   public static string Name
   { 
        get { return name; }
        set { name = value; }

   }
}

From another class, you call your variable like this:

public class Main
{
    public void DoSomething()
    {
         string var = Variables.Name;
    }
}

How to make a section of an image a clickable link

You can auto generate Image map from this website for selected area of image. https://www.image-map.net/

Easiest way to execute!

Volatile boolean vs AtomicBoolean

If you have only one thread modifying your boolean, you can use a volatile boolean (usually you do this to define a stop variable checked in the thread's main loop).

However, if you have multiple threads modifying the boolean, you should use an AtomicBoolean. Else, the following code is not safe:

boolean r = !myVolatileBoolean;

This operation is done in two steps:

  1. The boolean value is read.
  2. The boolean value is written.

If an other thread modify the value between #1 and 2#, you might got a wrong result. AtomicBoolean methods avoid this problem by doing steps #1 and #2 atomically.

How can I add 1 day to current date?

int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);

CodePen

_x000D_
_x000D_
var days = 2;_x000D_
var newDate = new Date(Date.now()+days*24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
_x000D_
_x000D_

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

The return type depends on the server, sometimes the response is indeed a JSON array but sent as text/plain

Setting the accept headers in the request should get the correct type:

client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); 

which can then be serialized to a JSON list or array. Thanks for the comment from @svick which made me curious that it should work.

The Exception I got without configuring the accept headers was System.Net.Http.UnsupportedMediaTypeException.

Following code is cleaner and should work (untested, but works in my case):

    var client = new HttpClient();
    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
    var response = await client.GetAsync("http://api.usa.gov/jobs/search.json?query=nursing+jobs");
    var model = await response.Content.ReadAsAsync<List<Job>>();

Understanding the results of Execute Explain Plan in Oracle SQL Developer

FULL is probably referring to a full table scan, which means that no indexes are in use. This is usually indicating that something is wrong, unless the query is supposed to use all the rows in a table.

Cost is a number that signals the sum of the different loads, processor, memory, disk, IO, and high numbers are typically bad. The numbers are added up when moving to the root of the plan, and each branch should be examined to locate the bottlenecks.

You may also want to query v$sql and v$session to get statistics about SQL statements, and this will have detailed metrics for all kind of resources, timings and executions.

navbar color in Twitter Bootstrap

You can overwrite the bootstrap colors, including the .navbar-inner class, by targetting it in your own stylesheet as opposed to modifying the bootstrap.css stylesheet, like so:

.navbar-inner {
  background-color: #2c2c2c; /* fallback color, place your own */

  /* Gradients for modern browsers, replace as you see fit */
  background-image: -moz-linear-gradient(top, #333333, #222222);
  background-image: -ms-linear-gradient(top, #333333, #222222);
  background-image: -webkit-gradient(linear, 0 0, 0 100%, from(#333333), to(#222222));
  background-image: -webkit-linear-gradient(top, #333333, #222222);
  background-image: -o-linear-gradient(top, #333333, #222222);
  background-image: linear-gradient(top, #333333, #222222);
  background-repeat: repeat-x;

  /* IE8-9 gradient filter */
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#333333', endColorstr='#222222', GradientType=0);
}

You just have to modify all of those styles with your own and they will get picked up, like something like this for example, where i eliminate all gradient effects and just set a solid black background-color:

.navbar-inner {
  background-color: #000; /* background color will be black for all browsers */
  background-image: none;
  background-repeat: no-repeat;
  filter: none;
}

You can take advantage of such tools as the Colorzilla Gradient Editor and create your own gradient colors for all browsers and replace the original colors with your own.

And as i mentioned on the comments, i would not recommend you modifying the bootstrap.css stylesheet directly as all of your changes will be lost once the stylesheet gets updated (current version is v2.0.2) so it is preferred that you include all of your changes inside your own stylesheet, in tandem with the bootstrap.css stylesheet. But remember to overwrite all of the appropriate properties to have consistency across browsers.

Is there a way to create xxhdpi, xhdpi, hdpi, mdpi and ldpi drawables from a large scale image?

Update:

The plugin previously mentioned has been abandoned, but it apparently has an up-to-date fork here.

Old Answer:

I use the Android Studio plugin named Android Drawable Importer:

enter image description here

To use it after installed, right click your res/drawable folder and select New > Batch Drawable Import:

Then select your image via the + button and set the Resolution to be xxhdpi (or whatever the resolution of your source image is).

How do I pause my shell script for a second before continuing?

And what about:

read -p "Press enter to continue"

How to take backup of a single table in a MySQL database?

You can use this code:

This example takes a backup of sugarcrm database and dumps the output to sugarcrm.sql

# mysqldump -u root -ptmppassword sugarcrm > sugarcrm.sql

# mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

The sugarcrm.sql will contain drop table, create table and insert command for all the tables in the sugarcrm database. Following is a partial output of sugarcrm.sql, showing the dump information of accounts_contacts table:

--

-- Table structure for table accounts_contacts

DROP TABLE IF EXISTS `accounts_contacts`;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
CREATE TABLE `accounts_contacts` (
`id` varchar(36) NOT NULL,
`contact_id` varchar(36) default NULL,
`account_id` varchar(36) default NULL,
`date_modified` datetime default NULL,
`deleted` tinyint(1) NOT NULL default '0',
PRIMARY KEY (`id`),
KEY `idx_account_contact` (`account_id`,`contact_id`),
KEY `idx_contid_del_accid` (`contact_id`,`deleted`,`account_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
SET character_set_client = @saved_cs_client;

--

Drag and drop menuitems

jQuery UI draggable and droppable are the two plugins I would use to achieve this effect. As for the insertion marker, I would investigate modifying the div (or container) element that was about to have content dropped into it. It should be possible to modify the border in some way or add a JavaScript/jQuery listener that listens for the hover (element about to be dropped) event and modifies the border or adds an image of the insertion marker in the right place.

Add horizontal scrollbar to html table

I was running into the same issue. I discovered the following solution, which has only been tested in Chrome v31:

table {
    table-layout: fixed;
}

tbody {
    display: block;
    overflow: scroll;
}

how do I get eclipse to use a different compiler version for Java?

First off, are you setting your desired JRE or your desired JDK?

Even if your Eclipse is set up properly, there might be a wacky project-specific setting somewhere. You can open up a context menu on a given Java project in the Project Explorer and select Properties > Java Compiler to check on that.

If none of that helps, leave a comment and I'll take another look.

C Macro definition to determine big endian or little endian machine?

Don't forget that endianness is not the whole story - the size of char might not be 8 bits (e.g. DSP's), two's complement negation is not guaranteed (e.g. Cray), strict alignment might be required (e.g. SPARC, also ARM springs into middle-endian when unaligned), etc, etc.

It might be a better idea to target a specific CPU architecture instead.

For example:

#if defined(__i386__) || defined(_M_IX86) || defined(_M_IX64)
  #define USE_LITTLE_ENDIAN_IMPL
#endif

void my_func()
{
#ifdef USE_LITTLE_ENDIAN_IMPL
  // Intel x86-optimized, LE implementation
#else
  // slow but safe implementation
#endif
}

Note that this solution is also not ultra-portable unfortunately, as it depends on compiler-specific definitions (there is no standard, but here's a nice compilation of such definitions).

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

#ifdef replacement in the Swift language

As of Swift 4.1, if all you need is just check whether the code is built with debug or release configuration, you may use the built-in functions:

  • _isDebugAssertConfiguration() (true when optimization is set to -Onone)
  • _isReleaseAssertConfiguration() (true when optimization is set to -O) (not available on Swift 3+)
  • _isFastAssertConfiguration() (true when optimization is set to -Ounchecked)

e.g.

func obtain() -> AbstractThing {
    if _isDebugAssertConfiguration() {
        return DecoratedThingWithDebugInformation(Thing())
    } else {
        return Thing()
    }
}

Compared with preprocessor macros,

  • ? You don't need to define a custom -D DEBUG flag to use it
  • ~ It is actually defined in terms of optimization settings, not Xcode build configuration
  • ? Undocumented, which means the function can be removed in any update (but it should be AppStore-safe since the optimizer will turn these into constants)

  • ? Using in if/else will always generate a "Will never be executed" warning.

Bootstrap 3.0 Sliding Menu from left

I believe that although javascript is an option here, you have a smoother animation through forcing hardware accelerate with CSS3. You can achieve this by setting the following CSS3 properties on the moving div:

div.hardware-accelarate {
     -webkit-transform: translate3d(0,0,0);
        -moz-transform: translate3d(0,0,0);
         -ms-transform: translate3d(0,0,0);
          -o-transform: translate3d(0,0,0);
             transform: translate3d(0,0,0);
}

I've made a plunkr setup for ya'll to test and tweak...

How to set a timeout on a http.request() in Node?

The Rob Evans anwser works correctly for me but when I use request.abort(), it occurs to throw a socket hang up error which stays unhandled.

I had to add an error handler for the request object :

var options = { ... }
var req = http.request(options, function(res) {
  // Usual stuff: on(data), on(end), chunks, etc...
}

req.on('socket', function (socket) {
    socket.setTimeout(myTimeout);  
    socket.on('timeout', function() {
        req.abort();
    });
}

req.on('error', function(err) {
    if (err.code === "ECONNRESET") {
        console.log("Timeout occurs");
        //specific error treatment
    }
    //other error treatment
});

req.write('something');
req.end();

What is difference between XML Schema and DTD?

One difference is that in a DTD the content model of an element is completely determined by its name, independently of where it appears in the document:

Assuming you want to have

  • a person element
  • with a child element called name
  • an name itself has child elements first and last.

Like this

   <person>
       <name>
            <first></first>
            <last></last>
       </name>
   </person>

If a city element in the same document also needs to have a child element 'name' the DTD requires that this 'name' element must have child elements first and last as well. Despite the fact that city.name does not require first and last as children.

In contrast, XML Schema allows you to declare child element types locally; you could declare the name child elements for both person and city separately. Thus giving them their proper content models in those contexts.

The other major difference is support for namespaces. Since DTDs are part of the original XML specification (and inherited from SGML), they are not namespace-aware at all because XML namespaces were specified later. You can use DTDs in combination with namespaces, but it requires some contortions, like being forced to define the prefixes in the DTD and using only those prefixes, instead of being able to use arbitrary prefixes.

To me, other differences are mostly superficial. Datatype support could easily be added to DTDs, and syntax is just syntax. (I, for one, find the XML Schema syntax horrible and would never want to hand-maintain an XML Schema, which I wouldn't say about DTDs or RELAX NG schemas; if I need an XML Schema for some reason, I usually write a RELAX NG one and convert it with trang.)

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

Adding extra zeros in front of a number using jQuery?

var str = "43215"; 
console.log("Before : \n string :"+str+"\n Length :"+str.length);
var max = 9;
while(str.length < max ){
                                str = "0" + str;

                        }
console.log("After : \n string :"+str+"\n Length :"+str.length);

It worked for me ! To increase the zeroes, update the 'max' variable

Working Fiddle URL : Adding extra zeros in front of a number using jQuery?:

Use index in pandas to plot data

monthly_mean.plot(y='A')

Uses index as x-axis by default.

How do I get the last character of a string using an Excel function?

Looks like the answer above was a little incomplete try the following:-

=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))

Obviously, this is for cell A2...

What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.

After the length has been determined and the portion of that which is required - then the Right command will display the information you need.

This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...

=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)

Temporary table in SQL server causing ' There is already an object named' error

In Azure Data warehouse also this occurs sometimes, because temporary tables created for a user session.. I got the same issue fixed by reconnecting the database,

What is the optimal way to compare dates in Microsoft SQL server?

Here is an example:

I've an Order table with a DateTime field called OrderDate. I want to retrieve all orders where the order date is equals to 01/01/2006. there are next ways to do it:

1) WHERE DateDiff(dd, OrderDate, '01/01/2006') = 0
2) WHERE Convert(varchar(20), OrderDate, 101) = '01/01/2006'
3) WHERE Year(OrderDate) = 2006 AND Month(OrderDate) = 1 and Day(OrderDate)=1
4) WHERE OrderDate LIKE '01/01/2006%'
5) WHERE OrderDate >= '01/01/2006'  AND OrderDate < '01/02/2006'

Is found here

How to convert a GUID to a string in C#?

In Visual Basic, you can call a parameterless method without the braces (()). In C#, they're mandatory. So you should write:

String guid = System.Guid.NewGuid().ToString();

Without the braces, you're assigning the method itself (instead of its result) to the variable guid, and obviously the method cannot be converted to a String, hence the error.

How are software license keys generated?

Check tis article on Partial Key Verification which covers the following requirements:

  • License keys must be easy enough to type in.

  • We must be able to blacklist (revoke) a license key in the case of chargebacks or purchases with stolen credit cards.

  • No “phoning home” to test keys. Although this practice is becoming more and more prevalent, I still do not appreciate it as a user, so will not ask my users to put up with it.

  • It should not be possible for a cracker to disassemble our released application and produce a working “keygen” from it. This means that our application will not fully test a key for verification. Only some of the key is to be tested. Further, each release of the application should test a different portion of the key, so that a phony key based on an earlier release will not work on a later release of our software.

  • Important: it should not be possible for a legitimate user to accidentally type in an invalid key that will appear to work but fail on a future version due to a typographical error.

How do I time a method's execution in Java?

There are a couple of ways to do that. I normally fall back to just using something like this:

long start = System.currentTimeMillis();
// ... do something ...
long end = System.currentTimeMillis();

or the same thing with System.nanoTime();

For something more on the benchmarking side of things there seems also to be this one: http://jetm.void.fm/ Never tried it though.

Static Vs. Dynamic Binding in Java

Because the compiler knows the binding at compile time. If you invoke a method on an interface, for example, then the compiler can't know and the binding is resolved at runtime because the actual object having a method invoked on it could possible be one of several. Therefore that is runtime or dynamic binding.

Your invocation is bound to the Animal class at compile time because you've specified the type. If you passed that variable into another method somewhere else, noone would know (apart from you because you wrote it) what actual class it would be. The only clue is the declared type of Animal.

Replace spaces with dashes and make all letters lower-case

@CMS's answer is just fine, but I want to note that you can use this package: https://github.com/sindresorhus/slugify, which does it for you and covers many edge cases (i.e., German umlauts, Vietnamese, Arabic, Russian, Romanian, Turkish, etc.).

How do I declare an array of undefined or no initial size?

malloc() (and its friends free() and realloc()) is the way to do this in C.

null vs empty string in Oracle

This is because Oracle internally changes empty string to NULL values. Oracle simply won't let insert an empty string.

On the other hand, SQL Server would let you do what you are trying to achieve.

There are 2 workarounds here:

  1. Use another column that states whether the 'description' field is valid or not
  2. Use some dummy value for the 'description' field where you want it to store empty string. (i.e. set the field to be 'stackoverflowrocks' assuming your real data will never encounter such a description value)

Both are, of course, stupid workarounds :)

Return background color of selected cell

The code below gives the HEX and RGB value of the range whether formatted using conditional formatting or otherwise. If the range is not formatted using Conditional Formatting and you intend to use iColor function in the Excel as UDF. It won't work. Read the below excerpt from MSDN.

Note that the DisplayFormat property does not work in user defined functions. For example, in a worksheet function that returns the interior color of a cell, if you use a line similar to:

Range.DisplayFormat.Interior.ColorIndex

then the worksheet function executes to return a #VALUE! error. If you are not finding color of the conditionally formatted range, then I encourage you to rather use

Range.Interior.ColorIndex

as then the function can also be used as UDF in Excel. Such as iColor(B1,"HEX")

Public Function iColor(rng As Range, Optional formatType As String) As Variant
'formatType: Hex for #RRGGBB, RGB for (R, G, B) and IDX for VBA Color Index
    Dim colorVal As Variant
    colorVal = rng.DisplayFormat.Interior.Color
    Select Case UCase(formatType)
        Case "HEX"
            iColor = "#" & Format(Hex(colorVal Mod 256),"00") & _
                           Format(Hex((colorVal \ 256) Mod 256),"00") & _
                           Format(Hex((colorVal \ 65536)),"00")
        Case "RGB"
            iColor = Format((colorVal Mod 256),"00") & ", " & _
                     Format(((colorVal \ 256) Mod 256),"00") & ", " & _
                     Format((colorVal \ 65536),"00")
        Case "IDX"
            iColor = rng.Interior.ColorIndex
        Case Else
            iColor = colorVal
    End Select
End Function

'Example use of the iColor function
Sub Get_Color_Format()
    Dim rng As Range

    For Each rng In Selection.Cells
        rng.Offset(0, 1).Value = iColor(rng, "HEX")
        rng.Offset(0, 2).Value = iColor(rng, "RGB")
    Next
End Sub

Git reset single file in feature branch to be the same as in master

you are almost there; you just need to give the reference to master; since you want to get the file from the master branch:

git checkout master -- filename

Note that the differences will be cached; so if you want to see the differences you obtained; use

git diff --cached

System.Net.Http: missing from namespace? (using .net 4.5)

Making the "Copy Local" property True for the reference did it for me. Expand References, right-click on System.Net.Http and change the value of Copy Local property to True in the properties window. I'm using VS2019.

OR operator in switch-case?

What are the backgrounds for a switch-case to not accept this operator?

Because case requires constant expression as its value. And since an || expression is not a compile time constant, it is not allowed.

From JLS Section 14.11:

Switch label should have following syntax:

SwitchLabel:
case ConstantExpression :
case EnumConstantName :
default :


Under the hood:

The reason behind allowing just constant expression with cases can be understood from the JVM Spec Section 3.10 - Compiling Switches:

Compilation of switch statements uses the tableswitch and lookupswitch instructions. The tableswitch instruction is used when the cases of the switch can be efficiently represented as indices into a table of target offsets. The default target of the switch is used if the value of the expression of the switch falls outside the range of valid indices.

So, for the cases label to be used by tableswitch as a index into the table of target offsets, the value of the case should be known at compile time. That is only possible if the case value is a constant expression. And || expression will be evaluated at runtime, and the value will only be available at that time.

From the same JVM section, the following switch-case:

switch (i) {
    case 0:  return  0;
    case 1:  return  1;
    case 2:  return  2;
    default: return -1;
}

is compiled to:

0   iload_1             // Push local variable 1 (argument i)
1   tableswitch 0 to 2: // Valid indices are 0 through 2  (NOTICE This instruction?)
      0: 28             // If i is 0, continue at 28
      1: 30             // If i is 1, continue at 30
      2: 32             // If i is 2, continue at 32
      default:34        // Otherwise, continue at 34
28  iconst_0            // i was 0; push int constant 0...
29  ireturn             // ...and return it
30  iconst_1            // i was 1; push int constant 1...
31  ireturn             // ...and return it
32  iconst_2            // i was 2; push int constant 2...
33  ireturn             // ...and return it
34  iconst_m1           // otherwise push int constant -1...
35  ireturn             // ...and return it

So, if the case value is not a constant expressions, compiler won't be able to index it into the table of instruction pointers, using tableswitch instruction.

How do I install PHP cURL on Linux Debian?

I wrote an article on topis how to [manually install curl on debian linu][1]x.

[1]: http://www.jasom.net/how-to-install-curl-command-manually-on-debian-linux. This is its shortcut:

  1. cd /usr/local/src
  2. wget http://curl.haxx.se/download/curl-7.36.0.tar.gz
  3. tar -xvzf curl-7.36.0.tar.gz
  4. rm *.gz
  5. cd curl-7.6.0
  6. ./configure
  7. make
  8. make install

And restart Apache. If you will have an error during point 6, try to run apt-get install build-essential.

phpMyAdmin mbstring error

Before sometime I also had the same problem. I have tried replacing the .dll file but no result. After some debugging I found the solution.

I had this in my php.ini file:

extension_dir = "ext"

And I'm getting mbstring extension missing error. So I tried putting the full path for the extension directory and it works for me. like:

extension_dir = "C:\php\ext"

Hope this will help.

Cheers,

How to convert a char array back to a string?

Try to use java.util.Arrays. This module has a variety of useful methods that could be used related to Arrays.

Arrays.toString(your_array_here[]);

Converting Varchar Value to Integer/Decimal Value in SQL Server

You can use it without casting such as:

select sum(`stuff`) as mySum from test;

Or cast it to decimal:

select sum(cast(`stuff` as decimal(4,2))) as mySum from test;

SQLFiddle

EDIT

For SQL Server, you can use:

select sum(cast(stuff as decimal(5,2))) as mySum from test;

SQLFiddle

RegEx match open tags except XHTML self-contained tags

I used a open source tool called HTMLParser before. It's designed to parse HTML in various ways and serves the purpose quite well. It can parse HTML as different treenode and you can easily use its API to get attributes out of the node. Check it out and see if this can help you.

Difference between Node object and Element object?

Node is used to represent tags in general. Divided to 3 types:

Attribute Note: is node which inside its has attributes. Exp: <p id=”123”></p>

Text Node: is node which between the opening and closing its have contian text content. Exp: <p>Hello</p>

Element Node : is node which inside its has other tags. Exp: <p><b></b></p>

Each node may be types simultaneously, not necessarily only of a single type.

Element is simply a element node.

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

This provides an answer for people who arrive at this Question that may want to link an editor other than vim.

The linked resource, by Github,is likely to be kept up to date, when editors are updated, even if answers on SO (including this one) are not.

Associating Text Editors with git

Github's post shows exactly what to type in to your command line for various editors, including the options/flags specific to each editor for it to work best with git.

Notepad++:
git config --global core.editor "'C:/Program Files (x86)/Notepad++/notepad++.exe' -multiInst -notabbar -nosession -noPlugin"

Sublime Text:
git config --global core.editor "'c:/Program Files/sublime text 3/subl.exe' -w"

Atom:
git config --global core.editor "atom --wait"

The commands above assume your editor has been installed in the default directory for a windows machine.

The commands basically add the text between double-quotes to .gitconfig in your home directory.
On a windows machine home is likely to be C:\Users\your-user-name, where your-user-name is your login name.
From the command line, you can reach this directory by typing in cd ~.

for example, a command above would be add the following line under the [core] section like so:
[core] editor = 'C:/Program Files/sublime text 3/subl.exe' -w

If you have a different editor, just replace with the path to your editor, using either method above. (and hope no flags are needed for optimal usage.)

adding to window.onload event?

This might not be a popular option, but sometimes the scripts end up being distributed in various chunks, in that case I've found this to be a quick fix

if(window.onload != null){var f1 = window.onload;}
window.onload=function(){
    //do something

    if(f1!=null){f1();}
}

then somewhere else...

if(window.onload != null){var f2 = window.onload;}
window.onload=function(){
    //do something else

    if(f2!=null){f2();}
}

this will update the onload function and chain as needed

How can I open a website in my web browser using Python?

If you want to open any website first you need to import a module called "webbrowser". Then just use webbrowser.open() to open a website. e.g.

 import webbrowser

 webbrowser.open('https://yashprogrammer.wordpress.com/', new= 2)

How to add a WiX custom action that happens only on uninstall (via MSI)?

Here's a set of properties i made that feel more intuitive to use than the built in stuff. The conditions are based off of the truth table supplied above by ahmd0.

<!-- truth table for installer varables (install vs uninstall vs repair vs upgrade) https://stackoverflow.com/a/17608049/1721136 -->
 <SetProperty Id="_INSTALL"   After="FindRelatedProducts" Value="1"><![CDATA[Installed="" AND PREVIOUSVERSIONSINSTALLED=""]]></SetProperty>
 <SetProperty Id="_UNINSTALL" After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED="" AND REMOVE="ALL"]]></SetProperty>
 <SetProperty Id="_CHANGE"    After="FindRelatedProducts" Value="1"><![CDATA[Installed<>"" AND REINSTALL="" AND PREVIOUSVERSIONSINSTALLED<>"" AND REMOVE=""]]></SetProperty>
 <SetProperty Id="_REPAIR"    After="FindRelatedProducts" Value="1"><![CDATA[REINSTALL<>""]]></SetProperty>
 <SetProperty Id="_UPGRADE"   After="FindRelatedProducts" Value="1"><![CDATA[PREVIOUSVERSIONSINSTALLED<>"" ]]></SetProperty>

Here's some sample usage:

  <Custom Action="CaptureExistingLocalSettingsValues" After="InstallInitialize">NOT _UNINSTALL</Custom>
  <Custom Action="GetConfigXmlToPersistFromCmdLineArgs" After="InstallInitialize">_INSTALL OR _UPGRADE</Custom>
  <Custom Action="ForgetProperties" Before="InstallFinalize">_UNINSTALL OR _UPGRADE</Custom>
  <Custom Action="SetInstallCustomConfigSettingsArgs" Before="InstallCustomConfigSettings">NOT _UNINSTALL</Custom>
  <Custom Action="InstallCustomConfigSettings" Before="InstallFinalize">NOT _UNINSTALL</Custom>

Issues:

Why do people write #!/usr/bin/env python on the first line of a Python script?

It seems to me like the files run the same without that line.

If so, then perhaps you're running the Python program on Windows? Windows doesn't use that line—instead, it uses the file-name extension to run the program associated with the file extension.

However in 2011, a "Python launcher" was developed which (to some degree) mimics this Linux behaviour for Windows. This is limited just to choosing which Python interpreter is run — e.g. to select between Python 2 and Python 3 on a system where both are installed. The launcher is optionally installed as py.exe by Python installation, and can be associated with .py files so that the launcher will check that line and in turn launch the specified Python interpreter version.

Does C have a string type?

C does not and never has had a native string type. By convention, the language uses arrays of char terminated with a null char, i.e., with '\0'. Functions and macros in the language's standard libraries provide support for the null-terminated character arrays, e.g., strlen iterates over an array of char until it encounters a '\0' character and strcpy copies from the source string until it encounters a '\0'.

The use of null-terminated strings in C reflects the fact that C was intended to be only a little more high-level than assembly language. Zero-terminated strings were already directly supported at that time in assembly language for the PDP-10 and PDP-11.

It is worth noting that this property of C strings leads to quite a few nasty buffer overrun bugs, including serious security flaws. For example, if you forget to null-terminate a character string passed as the source argument to strcpy, the function will keep copying sequential bytes from whatever happens to be in memory past the end of the source string until it happens to encounter a 0, potentially overwriting whatever valuable information follows the destination string's location in memory.

In your code example, the string literal "Hello, world!" will be compiled into a 14-byte long array of char. The first 13 bytes will hold the letters, comma, space, and exclamation mark and the final byte will hold the null-terminator character '\0', automatically added for you by the compiler. If you were to access the array's last element, you would find it equal to 0. E.g.:

const char foo[] = "Hello, world!";
assert(foo[12] == '!');
assert(foo[13] == '\0');

However, in your example, message is only 10 bytes long. strcpy is going to write all 14 bytes, including the null-terminator, into memory starting at the address of message. The first 10 bytes will be written into the memory allocated on the stack for message and the remaining four bytes will simply be written on to the end of the stack. The consequence of writing those four extra bytes onto the stack is hard to predict in this case (in this simple example, it might not hurt a thing), but in real-world code it usually leads to corrupted data or memory access violation errors.

Django: save() vs update() to update the database?

There are several key differences.

update is used on a queryset, so it is possible to update multiple objects at once.

As @FallenAngel pointed out, there are differences in how custom save() method triggers, but it is also important to keep in mind signals and ModelManagers. I have build a small testing app to show some valuable differencies. I am using Python 2.7.5, Django==1.7.7 and SQLite, note that the final SQLs may vary on different versions of Django and different database engines.

Ok, here's the example code.

models.py:

from __future__ import print_function
from django.db import models
from django.db.models import signals
from django.db.models.signals import pre_save, post_save
from django.dispatch import receiver

__author__ = 'sobolevn'

class CustomManager(models.Manager):
    def get_queryset(self):
        super_query = super(models.Manager, self).get_queryset()
        print('Manager is called', super_query)
        return super_query


class ExtraObject(models.Model):
    name = models.CharField(max_length=30)

    def __unicode__(self):
        return self.name


class TestModel(models.Model):

    name = models.CharField(max_length=30)
    key = models.ForeignKey('ExtraObject')
    many = models.ManyToManyField('ExtraObject', related_name='extras')

    objects = CustomManager()

    def save(self, *args, **kwargs):
        print('save() is called.')
        super(TestModel, self).save(*args, **kwargs)

    def __unicode__(self):
        # Never do such things (access by foreing key) in real life,
        # because it hits the database.
        return u'{} {} {}'.format(self.name, self.key.name, self.many.count())


@receiver(pre_save, sender=TestModel)
@receiver(post_save, sender=TestModel)
def reicever(*args, **kwargs):
    print('signal dispatched')

views.py:

def index(request):
    if request and request.method == 'GET':

        from models import ExtraObject, TestModel

        # Create exmple data if table is empty:
        if TestModel.objects.count() == 0:
            for i in range(15):
                extra = ExtraObject.objects.create(name=str(i))
                test = TestModel.objects.create(key=extra, name='test_%d' % i)
                test.many.add(test)
                print test

        to_edit = TestModel.objects.get(id=1)
        to_edit.name = 'edited_test'
        to_edit.key = ExtraObject.objects.create(name='new_for')
        to_edit.save()

        new_key = ExtraObject.objects.create(name='new_for_update')
        to_update = TestModel.objects.filter(id=2).update(name='updated_name', key=new_key)
        # return any kind of HttpResponse

That resuled in these SQL queries:

# to_edit = TestModel.objects.get(id=1):
QUERY = u'SELECT "main_testmodel"."id", "main_testmodel"."name", "main_testmodel"."key_id" 
FROM "main_testmodel" 
WHERE "main_testmodel"."id" = %s LIMIT 21' 
- PARAMS = (u'1',)

# to_edit.save():
QUERY = u'UPDATE "main_testmodel" SET "name" = %s, "key_id" = %s 
WHERE "main_testmodel"."id" = %s' 
- PARAMS = (u"'edited_test'", u'2', u'1')

# to_update = TestModel.objects.filter(id=2).update(name='updated_name', key=new_key):
QUERY = u'UPDATE "main_testmodel" SET "name" = %s, "key_id" = %s 
WHERE "main_testmodel"."id" = %s' 
- PARAMS = (u"'updated_name'", u'3', u'2')

We have just one query for update() and two for save().

Next, lets talk about overriding save() method. It is called only once for save() method obviously. It is worth mentioning, that .objects.create() also calls save() method.

But update() does not call save() on models. And if no save() method is called for update(), so the signals are not triggered either. Output:

Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.

# TestModel.objects.get(id=1):
Manager is called [<TestModel: edited_test new_for 0>]
Manager is called [<TestModel: edited_test new_for 0>]
save() is called.
signal dispatched
signal dispatched

# to_update = TestModel.objects.filter(id=2).update(name='updated_name', key=new_key):
Manager is called [<TestModel: edited_test new_for 0>]

As you can see save() triggers Manager's get_queryset() twice. When update() only once.

Resolution. If you need to "silently" update your values, without save() been called - use update. Usecases: last_seen user's field. When you need to update your model properly use save().

How could others, on a local network, access my NodeJS app while it's running on my machine?

And Don't Forget To Change in Index.html Following Code :

 <script src="http://192.168.1.4:8000/socket.io/socket.io.js"></script>
 <script src="http://code.jquery.com/jquery-1.6.2.min.js"></script>

 var socket = io.connect('http://192.168.1.4:8000');

Good luck!

How to Find Item in Dictionary Collection?

thisTag = _tags.FirstOrDefault(t => t.Key == tag);

is an inefficient and a little bit strange way to find something by key in a dictionary. Looking things up for a Key is the basic function of a Dictionary.

The basic solution would be:

if (_tags.Containskey(tag)) { string myValue = _tags[tag]; ... }

But that requires 2 lookups.

TryGetValue(key, out value) is more concise and efficient, it only does 1 lookup. And that answers the last part of your question, the best way to do a lookup is:

string myValue;
if (_tags.TryGetValue(tag, out myValue)) { /* use myValue */ }

VS 2017 update, for C# 7 and beyond we can declare the result variable inline:

if (_tags.TryGetValue(tag, out string myValue))
{
    // use myValue;
}
// use myValue, still in scope, null if not found

LINQ query to find if items in a list are contained in another list

List<string> l = new List<string> { "@bob.com", "@tom.com" };
List<string> l2 = new List<string> { "[email protected]", "[email protected]" };
List<string> myboblist= (l2.Where (i=>i.Contains("bob")).ToList<string>());
foreach (var bob in myboblist)
    Console.WriteLine(bob.ToString());

WARNING: sanitizing unsafe style value url

Check this handy pipe for Angular2: Usage:

  1. in the SafePipe code, substitute DomSanitizationService with DomSanitizer

  2. provide the SafePipe if your NgModule

  3. <div [style.background-image]="'url(' + your_property + ')' | safe: 'style'"></div>

How to convert std::string to lower case?

Here's a macro technique if you want something simple:

#define STRTOLOWER(x) std::transform (x.begin(), x.end(), x.begin(), ::tolower)
#define STRTOUPPER(x) std::transform (x.begin(), x.end(), x.begin(), ::toupper)
#define STRTOUCFIRST(x) std::transform (x.begin(), x.begin()+1, x.begin(),  ::toupper); std::transform (x.begin()+1, x.end(),   x.begin()+1,::tolower)

However, note that @AndreasSpindler's comment on this answer still is an important consideration, however, if you're working on something that isn't just ASCII characters.

Delete item from array and shrink array

The size of a Java array is fixed when you allocate it, and cannot be changed.

  • If you want to "grow" or "shrink" an existing array, you have to allocate a new array of the appropriate size and copy the array elements; e.g. using System.arraycopy(...) or Arrays.copyOf(...). A copy loop works as well, though it looks a bit clunky ... IMO.

  • If you want to "delete" an item or items from an array (in the true sense ... not just replacing them with null), you need to allocate a new smaller array and copy across the elements you want to retain.

  • Finally, you can "erase" an element in an array of a reference type by assigning null to it. But this introduces new problems:

    • If you were using null elements to mean something, you can't do this.
    • All of the code that uses the array now has to deal with the possibility of a null element in the appropriate fashion. More complexity and potential for bugs1.

There are alternatives in the form of 3rd-party libraries (e.g. Apache Commons ArrayUtils), but you may want to consider whether it is worth adding a library dependency just for the sake of a method that you could implement yourself with 5-10 lines of code.


It is better (i.e. simpler ... and in many cases, more efficient2) to use a List class instead of an array. This will take care of (at least) growing the backing storage. And there are operations that take care of inserting and deleting elements anywhere in the list.

For instance, the ArrayList class uses an array as backing, and automatically grows the array as required. It does not automatically reduce the size of the backing array, but you can tell it to do this using the trimToSize() method; e.g.

ArrayList l = ...
l.remove(21);
l.trimToSize();  // Only do this if you really have to.

1 - But note that the explicit if (a[e] == null) checks themselves are likely to be "free", since they can be combined with the implicit null check that happens when you dereference the value of a[e].

2 - I say it is "more efficient in many cases" because ArrayList uses a simple "double the size" strategy when it needs to grow the backing array. This means that if grow the list by repeatedly appending to it, each element will be copied on average one extra time. By contrast, if you did this with an array you would end up copying each array element close to N/2 times on average.

Detecting Browser Autofill

In Chrome and Edge (2020) checking for :-webkit-autofill will tell you that the inputs have been filled. However, until the user interacts with the page in some way, your JavaScript cannot get the values in the inputs.

Using $('x').focus() and $('x').blur() or triggering a mouse event in code don't help.

See https://stackoverflow.com/a/35783761/32429

converting list to json format - quick and easy way

3 years of experience later, I've come back to this question and would suggest to write it like this:

string output = new JavaScriptSerializer().Serialize(ListOfMyObject);

One line of code.

What is the convention in JSON for empty vs. null?

"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types."

"The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."

Here is my source.

Assigning a function to a variable

lambda should be useful for this case. For example,

  1. create function y=x+1 y=lambda x:x+1

  2. call the function y(1) then return 2.

How do I pass multiple parameters in Objective-C?

Yes; the Objective-C method syntax is like this for a couple of reasons; one of these is so that it is clear what the parameters you are specifying are. For example, if you are adding an object to an NSMutableArray at a certain index, you would do it using the method:

- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;

This method is called insertObject:atIndex: and it is clear that an object is being inserted at a specified index.

In practice, adding a string "Hello, World!" at index 5 of an NSMutableArray called array would be called as follows:

NSString *obj = @"Hello, World!";
int index = 5;

[array insertObject:obj atIndex:index];

This also reduces ambiguity between the order of the method parameters, ensuring that you pass the object parameter first, then the index parameter. This becomes more useful when using functions that take a large number of arguments, and reduces error in passing the arguments.

Furthermore, the method naming convention is such because Objective-C doesn't support overloading; however, if you want to write a method that does the same job, but takes different data-types, this can be accomplished; take, for instance, the NSNumber class; this has several object creation methods, including:

  • + (id)numberWithBool:(BOOL)value;
  • + (id)numberWithFloat:(float)value;
  • + (id)numberWithDouble:(double)value;

In a language such as C++, you would simply overload the number method to allow different data types to be passed as the argument; however, in Objective-C, this syntax allows several different variants of the same function to be implemented, by changing the name of the method for each variant of the function.

React - How to force a function component to render?

Official FAQ ( https://reactjs.org/docs/hooks-faq.html#is-there-something-like-forceupdate ) now recommends this way if you really need to do it:

  const [ignored, forceUpdate] = useReducer(x => x + 1, 0);

  function handleClick() {
    forceUpdate();
  }

How to config routeProvider and locationProvider in angularJS?

@Simple-Solution

I use a simple Python HTTP server. When in the directory of the Angular app in question (using a MBP with Mavericks 10.9 and Python 2.x) I simply run

python -m SimpleHTTPServer 8080

And that sets up the simple server on port 8080 letting you visit localhost:8080 on your browser to view the app in development.

Hope that helped!

subquery in codeigniter active record

Like this in simple way .

    $this->db->select('*');
    $this->db->from('certs');
    $this->db->where('certs.id NOT IN (SELECT id_cer FROM revokace)');

    return $this->db->get()->result();

R Error in x$ed : $ operator is invalid for atomic vectors

From the help file about $ (See ?"$") you can read:

$ is only valid for recursive objects, and is only discussed in the section below on recursive objects.

Now, let's check whether x is recursive

> is.recursive(x)
[1] FALSE

A recursive object has a list-like structure. A vector is not recursive, it is an atomic object instead, let's check

> is.atomic(x)
[1] TRUE

Therefore you get an error when applying $ to a vector (non-recursive object), use [ instead:

> x["ed"]
ed 
 2 

You can also use getElement

> getElement(x, "ed")
[1] 2

How to refresh Android listview?

Also you can use this:

myListView.invalidateViews();

Difference of two date time in sql server

Please check below trick to find the date difference between two dates

 DATEDIFF(DAY,ordr.DocDate,RDR1.U_ProgDate) datedifff

where you can change according your requirement as you want difference of days or month or year or time.

Datatype for storing ip address in SQL Server

Here is some code to convert either IPV4 or IPv6 in varchar format to binary(16) and back. This is the smallest form I could think of. It should index well and provide a relatively easy way to filter on subnets. Requires SQL Server 2005 or later. Not sure it's totally bulletproof. Hope this helps.

-- SELECT dbo.fn_ConvertIpAddressToBinary('2002:1ff:6c2::1ff:6c2')
-- SELECT dbo.fn_ConvertIpAddressToBinary('10.4.46.2')
-- SELECT dbo.fn_ConvertIpAddressToBinary('bogus')

ALTER FUNCTION dbo.fn_ConvertIpAddressToBinary
(
     @ipAddress VARCHAR(39)
)
RETURNS BINARY(16) AS
BEGIN
DECLARE
     @bytes BINARY(16), @vbytes VARBINARY(16), @vbzone VARBINARY(2)
     , @colIndex TINYINT, @prevColIndex TINYINT, @parts TINYINT, @limit TINYINT
     , @delim CHAR(1), @token VARCHAR(4), @zone VARCHAR(4)

SELECT
     @delim = '.'
     , @prevColIndex = 0
     , @limit = 4
     , @vbytes = 0x
     , @parts = 0
     , @colIndex = CHARINDEX(@delim, @ipAddress)

IF @colIndex = 0
     BEGIN
           SELECT
                @delim = ':'
                , @limit = 8
                , @colIndex = CHARINDEX(@delim, @ipAddress)
           WHILE @colIndex > 0
                SELECT
                      @parts = @parts + 1
                      , @colIndex = CHARINDEX(@delim, @ipAddress, @colIndex + 1)
           SET @colIndex = CHARINDEX(@delim, @ipAddress)

           IF @colIndex = 0
                RETURN NULL     
     END

SET @ipAddress = @ipAddress + @delim

WHILE @colIndex > 0
     BEGIN
           SET @token = SUBSTRING(@ipAddress, @prevColIndex + 1, @Colindex - @prevColIndex - 1)

           IF @delim = ':'
                BEGIN
                      SET  @zone = RIGHT('0000' + @token, 4)

                      SELECT
                           @vbzone = CAST('' AS XML).value('xs:hexBinary(sql:variable("@zone"))', 'varbinary(2)')
                           , @vbytes = @vbytes + @vbzone

                      IF @token = ''
                           WHILE @parts + 1 < @limit
                                 SELECT
                                      @vbytes = @vbytes + @vbzone
                                      , @parts = @parts + 1
                END
           ELSE
                BEGIN
                      SET @zone = SUBSTRING('' + master.sys.fn_varbintohexstr(CAST(@token AS TINYINT)), 3, 2)

                      SELECT
                           @vbzone = CAST('' AS XML).value('xs:hexBinary(sql:variable("@zone"))', 'varbinary(1)')
                           , @vbytes = @vbytes + @vbzone
                END

           SELECT
                @prevColIndex = @colIndex
                , @colIndex = CHARINDEX(@delim, @ipAddress, @colIndex + 1) 
     END            

SET @bytes =
     CASE @delim
           WHEN ':' THEN @vbytes
           ELSE 0x000000000000000000000000 + @vbytes
     END 

RETURN @bytes

END
-- SELECT dbo.fn_ConvertBinaryToIpAddress(0x200201FF06C200000000000001FF06C2)
-- SELECT dbo.fn_ConvertBinaryToIpAddress(0x0000000000000000000000000A0118FF)

ALTER FUNCTION [dbo].[fn_ConvertBinaryToIpAddress]
(
     @bytes BINARY(16)
)
RETURNS VARCHAR(39) AS
BEGIN
DECLARE
     @part VARBINARY(2)
     , @colIndex TINYINT
     , @ipAddress VARCHAR(39)

SET @ipAddress = ''

IF SUBSTRING(@bytes, 1, 12) = 0x000000000000000000000000
     BEGIN
           SET @colIndex = 13
           WHILE @colIndex <= 16
                SELECT
                      @part = SUBSTRING(@bytes, @colIndex, 1)
                      , @ipAddress = @ipAddress
                           + CAST(CAST(@part AS TINYINT) AS VARCHAR(3))
                           + CASE @colIndex WHEN 16 THEN '' ELSE '.' END
                      , @colIndex = @colIndex + 1

           IF @ipAddress = '0.0.0.1'
                SET @ipAddress = '::1'
     END
ELSE
     BEGIN
           SET @colIndex = 1
           WHILE @colIndex <= 16
                BEGIN
                      SET @part = SUBSTRING(@bytes, @colIndex, 2)
                      SELECT
                           @ipAddress = @ipAddress
                                 + CAST('' as xml).value('xs:hexBinary(sql:variable("@part") )', 'varchar(4)')
                                 + CASE @colIndex WHEN 15 THEN '' ELSE ':' END
                           , @colIndex = @colIndex + 2
                END
     END

RETURN @ipAddress   

END 

PHP How to fix Notice: Undefined variable:

You should initialize your variables outside the while loop. Outside the while loop, they currently have no scope. You are just relying on the good graces of php to let the values carry over outside the loop

           $hn = "";
           $pid = "";
           $datereg = "";
           $prefix = "";
           $fname = "";
           $lname = "";
           $age = "";
           $sex = "";
           while (...){}

alternatively, it looks like you are just expecting a single row back. so you could just say

$row = pg_fetch_array($result);
if(!row) {
    return array();
}
$hn = $row["patient_hn"];
$pid = $row["patient_id"];
$datereg = $row["patient_date_register"];
$prefix = $row["patient_prefix"];
$fname = $row["patient_fname"];
$lname = $row["patient_lname"];
$age = $row["patient_age"];
$sex = $row["patient_sex"];

return array($hn,$pid,$datereg,$prefix,$fname,$lname,$age,$sex) ;

How to restart remote MySQL server running on Ubuntu linux?

  1. SSH into the machine. Using the proper credentials and ip address, ssh [email protected]. This should provide you with shell access to the Ubuntu server.
  2. Restart the mySQL service. sudo service mysql restart should do the job.

If your mySQL service is named something else like mysqld you may have to change the command accordingly or try this: sudo /etc/init.d/mysql restart

Java URL encoding of query string parameters

URLEncoder is the way to go. You only need to keep in mind to encode only the individual query string parameter name and/or value, not the entire URL, for sure not the query string parameter separator character & nor the parameter name-value separator character =.

String q = "random word £500 bank $";
String url = "https://example.com?q=" + URLEncoder.encode(q, StandardCharsets.UTF_8);

When you're still not on Java 10 or newer, then use StandardCharsets.UTF_8.toString() as charset argument, or when you're still not on Java 7 or newer, then use "UTF-8".


Note that spaces in query parameters are represented by +, not %20, which is legitimately valid. The %20 is usually to be used to represent spaces in URI itself (the part before the URI-query string separator character ?), not in query string (the part after ?).

Also note that there are three encode() methods. One without Charset as second argument and another with String as second argument which throws a checked exception. The one without Charset argument is deprecated. Never use it and always specify the Charset argument. The javadoc even explicitly recommends to use the UTF-8 encoding, as mandated by RFC3986 and W3C.

All other characters are unsafe and are first converted into one or more bytes using some encoding scheme. Then each byte is represented by the 3-character string "%xy", where xy is the two-digit hexadecimal representation of the byte. The recommended encoding scheme to use is UTF-8. However, for compatibility reasons, if an encoding is not specified, then the default encoding of the platform is used.

See also:

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

For those who need the same feature in IE 8, this is how I solved the problem:

  var myImage = $('<img/>');

               myImage.attr('width', 300);
               myImage.attr('height', 300);
               myImage.attr('class', "groupMediaPhoto");
               myImage.attr('src', photoUrl);

I could not force IE8 to use object in constructor.

Inserting an item in a Tuple

You can code simply like this as well:

T += (new_element,)

HTML/Javascript change div content

change onClick to onClick="changeDivContent(this)" and try

function changeDivContent(btn) {
  content.innerHTML = btn.value
}

_x000D_
_x000D_
function changeDivContent(btn) {_x000D_
  content.innerHTML = btn.value_x000D_
}
_x000D_
<input type="radio" name="radiobutton" value="A" onClick="changeDivContent(this)">_x000D_
<input type="radio" name="radiobutton" value="B" onClick="changeDivContent(this)">_x000D_
_x000D_
<div id="content"></div>
_x000D_
_x000D_
_x000D_

How can I show an image using the ImageView component in javafx and fxml?

The Code part :

Image imProfile = new Image(getClass().getResourceAsStream("/img/profile128.png"));

ImageView profileImage=new ImageView(imProfile);

in a javafx maven:

enter image description here

What's the best way to convert a number to a string in JavaScript?

Explicit conversions are very clear to someone that's new to the language. Using type coercion, as others have suggested, leads to ambiguity if a developer is not aware of the coercion rules. Ultimately developer time is more costly than CPU time, so I'd optimize for the former at the cost of the latter. That being said, in this case the difference is likely negligible, but if not I'm sure there are some decent JavaScript compressors that will optimize this sort of thing.

So, for the above reasons I'd go with: n.toString() or String(n). String(n) is probably a better choice because it won't fail if n is null or undefined.

Disable asp.net button after click to prevent double clicking

Disable the button on the OnClick event, then re-enable on the AJAX callback event handler. Here is how I do it with jQuery.

<script>
$(document).ready(function() {

    $('#buttonId').click(function() {
         $(this).attr('disabled', 'disabled');
         callAjax();
    });

});

function callAjax()
{
    $.ajax({
      url: 'ajax/test.html',
      success: function(data) {
         //enable button
         $('#buttonId').removeAttr('disabled');

      }
    });
}
</script>

Draw horizontal rule in React Native

One can use margin in order to change the width of a line and place it center.

import { StyleSheet } from 'react-native;
<View style = {styles.lineStyle} />

const styles = StyleSheet.create({
  lineStyle:{
        borderWidth: 0.5,
        borderColor:'black',
        margin:10,
   }
 });

if you want to give margin dynamically then you can use Dimension width.

Add support library to Android Studio project

This is way more simpler with Maven dependency feature:

  1. Open File -> Project Structure... menu.
  2. Select Modules in the left pane, choose your project's main module in the middle pane and open Dependencies tab in the right pane.
  3. Click the plus sign in the right panel and select "Maven dependency" from the list. A Maven dependency dialog will pop up.
  4. Enter "support-v4" into the search field and click the icon with magnifying glass.
  5. Select "com.google.android:support-v4:r7@jar" from the drop-down list.
  6. Click "OK".
  7. Clean and rebuild your project.

Hope this will help!

IF EXIST C:\directory\ goto a else goto b problems windows XP batch files

From the help (if /?):

The ELSE clause must occur on the same line as the command after the IF.  For
example:

    IF EXIST filename. (
        del filename.
    ) ELSE (
        echo filename. missing.
    )

The following would NOT work because the del command needs to be terminated
by a newline:

    IF EXIST filename. del filename. ELSE echo filename. missing

Nor would the following work, since the ELSE command must be on the same line
as the end of the IF command:

    IF EXIST filename. del filename.
    ELSE echo filename. missing

How do I do a not equal in Django queryset filtering?

What you are looking for are all objects that have either a=false or x=5. In Django, | serves as OR operator between querysets:

results = Model.objects.filter(a=false)|Model.objects.filter(x=5)

Move column by name to front of table in pandas

To reorder the rows of a DataFrame just use a list as follows.

df = df[['Mid', 'Net', 'Upper', 'Lower', 'Zsore']]

This makes it very obvious what was done when reading the code later. Also use:

df.columns
Out[1]: Index(['Net', 'Upper', 'Lower', 'Mid', 'Zsore'], dtype='object')

Then cut and paste to reorder.


For a DataFrame with many columns, store the list of columns in a variable and pop the desired column to the front of the list. Here is an example:

cols = [str(col_name) for col_name in range(1001)]
data = np.random.rand(10,1001)
df = pd.DataFrame(data=data, columns=cols)

mv_col = cols.pop(cols.index('77'))
df = df[[mv_col] + cols]

Now df.columns has.

Index(['77', '0', '1', '2', '3', '4', '5', '6', '7', '8',
       ...
       '991', '992', '993', '994', '995', '996', '997', '998', '999', '1000'],
      dtype='object', length=1001)

How do I modify fields inside the new PostgreSQL JSON datatype?

I wrote small function for myself that works recursively in Postgres 9.4. Here is the function (I hope it works well for you):

CREATE OR REPLACE FUNCTION jsonb_update(val1 JSONB,val2 JSONB)
RETURNS JSONB AS $$
DECLARE
    result JSONB;
    v RECORD;
BEGIN
    IF jsonb_typeof(val2) = 'null'
    THEN 
        RETURN val1;
    END IF;

    result = val1;

    FOR v IN SELECT key, value FROM jsonb_each(val2) LOOP

        IF jsonb_typeof(val2->v.key) = 'object'
            THEN
                result = result || jsonb_build_object(v.key, jsonb_update(val1->v.key, val2->v.key));
            ELSE
                result = result || jsonb_build_object(v.key, v.value);
        END IF;
    END LOOP;

    RETURN result;
END;
$$ LANGUAGE plpgsql;

Here is sample use:

select jsonb_update('{"a":{"b":{"c":{"d":5,"dd":6},"cc":1}},"aaa":5}'::jsonb, '{"a":{"b":{"c":{"d":15}}},"aa":9}'::jsonb);
                            jsonb_update                             
---------------------------------------------------------------------
 {"a": {"b": {"c": {"d": 15, "dd": 6}, "cc": 1}}, "aa": 9, "aaa": 5}
(1 row)

As you can see it analyze deep down and update/add values where needed.

Why use the params keyword?

One more important thing needs to be highlighted. It's better to use params because it is better for performance. When you call a method with params argument and passed to it nothing:

public void ExampleMethod(params string[] args)
{
// do some stuff
}

call:

ExampleMethod();

Then a new versions of the .Net Framework do this (from .Net Framework 4.6):

ExampleMethod(Array.Empty<string>());

This Array.Empty object can be reused by framework later, so there are no needs to do redundant allocations. These allocations will occur when you call this method like this:

 ExampleMethod(new string[] {});

How to sort a list of strings?

Basic answer:

mylist = ["b", "C", "A"]
mylist.sort()

This modifies your original list (i.e. sorts in-place). To get a sorted copy of the list, without changing the original, use the sorted() function:

for x in sorted(mylist):
    print x

However, the examples above are a bit naive, because they don't take locale into account, and perform a case-sensitive sorting. You can take advantage of the optional parameter key to specify custom sorting order (the alternative, using cmp, is a deprecated solution, as it has to be evaluated multiple times - key is only computed once per element).

So, to sort according to the current locale, taking language-specific rules into account (cmp_to_key is a helper function from functools):

sorted(mylist, key=cmp_to_key(locale.strcoll))

And finally, if you need, you can specify a custom locale for sorting:

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') # vary depending on your lang/locale
assert sorted((u'Ab', u'ad', u'aa'),
  key=cmp_to_key(locale.strcoll)) == [u'aa', u'Ab', u'ad']

Last note: you will see examples of case-insensitive sorting which use the lower() method - those are incorrect, because they work only for the ASCII subset of characters. Those two are wrong for any non-English data:

# this is incorrect!
mylist.sort(key=lambda x: x.lower())
# alternative notation, a bit faster, but still wrong
mylist.sort(key=str.lower)

Get Root Directory Path of a PHP project

you can try: $_SERVER['PATH_TRANSLATED']

quote:

Filesystem- (not document root-) based path to the current script, after the server has done any virtual-to-real mapping. Note: As of PHP 4.3.2, PATH_TRANSLATED is no longer set implicitly under the Apache 2 SAPI in contrast to the situation in Apache 1, where it's set to the same value as the SCRIPT_FILENAME server variable when it's not populated by Apache.
This change was made to comply with the CGI specification that PATH_TRANSLATED should only exist if PATH_INFO is defined. Apache 2 users may use AcceptPathInfo = On inside httpd.conf to define PATH_INFO

source: php.net/manual

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

I think the only cookie you need is JSESSIONID=xxx..

Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.

Store text file content line by line into array

The simplest solution:

List<String> list = Files.readAllLines(Paths.get("path/of/text"), StandardCharsets.UTF_8);
String[] a = list.toArray(new String[list.size()]); 

Note that java.nio.file.Files is since 1.7

Formatting a double to two decimal places

Since you are working in currency why not simply do this:

Console.Writeline("Earnings this week: {0:c}", answer);

This will format answer as currency, so on my machine (UK) it will come out as:

Earnings this week: £209.00

Javascript objects: get parent

No. There is no way of knowing which object it came from.

s and obj.subObj both simply have references to the same object.

You could also do:

var obj = { subObj: {foo: 'hello world'} };
var obj2 = {};
obj2.subObj = obj.subObj;
var s = obj.subObj;

You now have three references, obj.subObj, obj2.subObj, and s, to the same object. None of them is special.

failed to open stream: No such file or directory in

It's because you have included a leading / in your file path. The / makes it start at the top of your filesystem. Note: filesystem path, not Web site path (you're not accessing it over HTTP). You can use a relative path with include_once (one that doesn't start with a leading /).

You can change it to this:

include_once 'headerSite.php';

That will look first in the same directory as the file that's including it (i.e. C:\xampp\htdocs\PoliticalForum\ in your example.

MySQL select query with multiple conditions

@fthiella 's solution is very elegant.

If in future you want show more than user_id you could use joins, and there in one line could be all data you need.

If you want to use AND conditions, and the conditions are in multiple lines in your table, you can use JOINS example:

SELECT `w_name`.`user_id` 
     FROM `wp_usermeta` as `w_name`
     JOIN `wp_usermeta` as `w_year` ON `w_name`.`user_id`=`w_year`.`user_id` 
          AND `w_name`.`meta_key` = 'first_name' 
          AND `w_year`.`meta_key` = 'yearofpassing' 
     JOIN `wp_usermeta` as `w_city` ON `w_name`.`user_id`=`w_city`.user_id 
          AND `w_city`.`meta_key` = 'u_city'
     JOIN `wp_usermeta` as `w_course` ON `w_name`.`user_id`=`w_course`.`user_id` 
          AND `w_course`.`meta_key` = 'us_course'
     WHERE 
         `w_name`.`meta_value` = '$us_name' AND         
         `w_year`.meta_value   = '$us_yearselect' AND 
         `w_city`.`meta_value` = '$us_reg' AND 
         `w_course`.`meta_value` = '$us_course'

Other thing: Recommend to use prepared statements, because mysql_* functions is not SQL injection save, and will be deprecated. If you want to change your code the less as possible, you can use mysqli_ functions: http://php.net/manual/en/book.mysqli.php

Recommendation:

Use indexes in this table. user_id highly recommend to be and index, and recommend to be the meta_key AND meta_value too, for faster run of query.

The explain:

If you use AND you 'connect' the conditions for one line. So if you want AND condition for multiple lines, first you must create one line from multiple lines, like this.

Tests: Table Data:

          PRIMARY                 INDEX
      int       varchar(255)    varchar(255)
       /                \           |
  +---------+---------------+-----------+
  | user_id | meta_key      | meta_value|
  +---------+---------------+-----------+
  | 1       | first_name    | Kovge     |
  +---------+---------------+-----------+
  | 1       | yearofpassing | 2012      |
  +---------+---------------+-----------+
  | 1       | u_city        | GaPa      |
  +---------+---------------+-----------+
  | 1       | us_course     | PHP       |
  +---------+---------------+-----------+

The result of Query with $us_name='Kovge' $us_yearselect='2012' $us_reg='GaPa', $us_course='PHP':

 +---------+
 | user_id |
 +---------+
 | 1       |
 +---------+

So it should works.

How do I access command line arguments in Python?

Python tutorial explains it:

import sys

print(sys.argv)

More specifically, if you run python example.py one two three:

>>> import sys
>>> print(sys.argv)
['example.py', 'one', 'two', 'three']