Programs & Examples On #Generic variance

Generic variance is the ability to assign a generic interface or delegate type to the same type with another parameter, for example, assign IEnumerable to IEnumerable. Generic variance has to be defined on the generic parameter type that supports them. There are two kinds of generic variance, covariance and contravariance.

How can I reverse the order of lines in a file?

rev
text here

or

rev <file>

or

rev texthere

How does Django's Meta class work?

Class Meta is the place in your code logic where your model.fields MEET With your form.widgets. So under Class Meta() you create the link between your model' fields and the different widgets you want to have in your form.

What is a regular expression for a MAC Address?

This link might help you. You can use this : (([0-9A-Fa-f]{2}[-:]){5}[0-9A-Fa-f]{2})|(([0-9A-Fa-f]{4}\.){2}[0-9A-Fa-f]{4})

How do you compare two version Strings in Java?

You need to normalise the version strings so they can be compared. Something like

import java.util.regex.Pattern;

public class Main {
    public static void main(String... args) {
        compare("1.0", "1.1");
        compare("1.0.1", "1.1");
        compare("1.9", "1.10");
        compare("1.a", "1.9");
    }

    private static void compare(String v1, String v2) {
        String s1 = normalisedVersion(v1);
        String s2 = normalisedVersion(v2);
        int cmp = s1.compareTo(s2);
        String cmpStr = cmp < 0 ? "<" : cmp > 0 ? ">" : "==";
        System.out.printf("'%s' %s '%s'%n", v1, cmpStr, v2);
    }

    public static String normalisedVersion(String version) {
        return normalisedVersion(version, ".", 4);
    }

    public static String normalisedVersion(String version, String sep, int maxWidth) {
        String[] split = Pattern.compile(sep, Pattern.LITERAL).split(version);
        StringBuilder sb = new StringBuilder();
        for (String s : split) {
            sb.append(String.format("%" + maxWidth + 's', s));
        }
        return sb.toString();
    }
}

Prints

'1.0' < '1.1'
'1.0.1' < '1.1'
'1.9' < '1.10'
'1.a' > '1.9'

What's the best way to iterate an Android Cursor?

The Do/While solution is more elegant, but if you do use just the While solution posted above, without the moveToPosition(-1) you will miss the first element (at least on the Contact query).

I suggest:

if (cursor.getCount() > 0) {
    cursor.moveToPosition(-1);
    while (cursor.moveToNext()) {
          <do stuff>
    }
}

Scheduling recurring task in Android

I have created on time task in which the task which user wants to repeat, add in the Custom TimeTask run() method. it is successfully reoccurring.

 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.Timer;
 import java.util.TimerTask;

 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.CheckBox;
 import android.widget.TextView;
 import android.app.Activity;
 import android.content.Intent;

 public class MainActivity extends Activity {

     CheckBox optSingleShot;
     Button btnStart, btnCancel;
     TextView textCounter;

     Timer timer;
     MyTimerTask myTimerTask;

     int tobeShown = 0  ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    optSingleShot = (CheckBox)findViewById(R.id.singleshot);
    btnStart = (Button)findViewById(R.id.start);
    btnCancel = (Button)findViewById(R.id.cancel);
    textCounter = (TextView)findViewById(R.id.counter);
    tobeShown = 1;

    if(timer != null){
        timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
        //singleshot delay 1000 ms
        timer.schedule(myTimerTask, 1000);
    }else{
        //delay 1000ms, repeat in 5000ms
        timer.schedule(myTimerTask, 1000, 1000);
    }

    btnStart.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {


            Intent i = new Intent(MainActivity.this, ActivityB.class);
            startActivity(i);

            /*if(timer != null){
                timer.cancel();
            }

            //re-schedule timer here
            //otherwise, IllegalStateException of
            //"TimerTask is scheduled already" 
            //will be thrown
            timer = new Timer();
            myTimerTask = new MyTimerTask();

            if(optSingleShot.isChecked()){
                //singleshot delay 1000 ms
                timer.schedule(myTimerTask, 1000);
            }else{
                //delay 1000ms, repeat in 5000ms
                timer.schedule(myTimerTask, 1000, 1000);
            }*/
        }});

    btnCancel.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            if (timer!=null){
                timer.cancel();
                timer = null;
            }
        }
    });

}

@Override
protected void onResume() {
    super.onResume();

    if(timer != null){
        timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
        //singleshot delay 1000 ms
        timer.schedule(myTimerTask, 1000);
    }else{
        //delay 1000ms, repeat in 5000ms
        timer.schedule(myTimerTask, 1000, 1000);
    }
}


@Override
protected void onPause() {
    super.onPause();

    if (timer!=null){
        timer.cancel();
        timer = null;
    }

}

@Override
protected void onStop() {
    super.onStop();

    if (timer!=null){
        timer.cancel();
        timer = null;
    }

}

class MyTimerTask extends TimerTask {

    @Override
    public void run() {

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = 
                new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
        final String strDate = simpleDateFormat.format(calendar.getTime());

        runOnUiThread(new Runnable(){

            @Override
            public void run() {
                textCounter.setText(strDate);
            }});
    }
}

}

How do I write a correct micro-benchmark in Java?

Tips about writing micro benchmarks from the creators of Java HotSpot:

Rule 0: Read a reputable paper on JVMs and micro-benchmarking. A good one is Brian Goetz, 2005. Do not expect too much from micro-benchmarks; they measure only a limited range of JVM performance characteristics.

Rule 1: Always include a warmup phase which runs your test kernel all the way through, enough to trigger all initializations and compilations before timing phase(s). (Fewer iterations is OK on the warmup phase. The rule of thumb is several tens of thousands of inner loop iterations.)

Rule 2: Always run with -XX:+PrintCompilation, -verbose:gc, etc., so you can verify that the compiler and other parts of the JVM are not doing unexpected work during your timing phase.

Rule 2.1: Print messages at the beginning and end of timing and warmup phases, so you can verify that there is no output from Rule 2 during the timing phase.

Rule 3: Be aware of the difference between -client and -server, and OSR and regular compilations. The -XX:+PrintCompilation flag reports OSR compilations with an at-sign to denote the non-initial entry point, for example: Trouble$1::run @ 2 (41 bytes). Prefer server to client, and regular to OSR, if you are after best performance.

Rule 4: Be aware of initialization effects. Do not print for the first time during your timing phase, since printing loads and initializes classes. Do not load new classes outside of the warmup phase (or final reporting phase), unless you are testing class loading specifically (and in that case load only the test classes). Rule 2 is your first line of defense against such effects.

Rule 5: Be aware of deoptimization and recompilation effects. Do not take any code path for the first time in the timing phase, because the compiler may junk and recompile the code, based on an earlier optimistic assumption that the path was not going to be used at all. Rule 2 is your first line of defense against such effects.

Rule 6: Use appropriate tools to read the compiler's mind, and expect to be surprised by the code it produces. Inspect the code yourself before forming theories about what makes something faster or slower.

Rule 7: Reduce noise in your measurements. Run your benchmark on a quiet machine, and run it several times, discarding outliers. Use -Xbatch to serialize the compiler with the application, and consider setting -XX:CICompilerCount=1 to prevent the compiler from running in parallel with itself. Try your best to reduce GC overhead, set Xmx(large enough) equals Xms and use UseEpsilonGC if it is available.

Rule 8: Use a library for your benchmark as it is probably more efficient and was already debugged for this sole purpose. Such as JMH, Caliper or Bill and Paul's Excellent UCSD Benchmarks for Java.

How do I "commit" changes in a git submodule?

You can treat a submodule exactly like an ordinary repository. To propagate your changes upstream just commit and push as you would normally within that directory.

setTimeout / clearTimeout problems

You need to declare timer outside the function. Otherwise, you get a brand new variable on each function invocation.

var timer;
function endAndStartTimer() {
  window.clearTimeout(timer);
  //var millisecBeforeRedirect = 10000; 
  timer = window.setTimeout(function(){alert('Hello!');},10000); 
}

How to quickly and conveniently create a one element arraylist

Collections.singletonList(object)

the list created by this method is immutable.

removing html element styles via javascript

In JavaScript:

document.getElementById("id").style.display = null;

In jQuery:

$("#id").css('display',null);

Increase number of axis ticks

The upcoming version v3.3.0 of ggplot2 will have an option n.breaks to automatically generate breaks for scale_x_continuous and scale_y_continuous

    devtools::install_github("tidyverse/ggplot2")

    library(ggplot2)

    plt <- ggplot(mtcars, aes(x = mpg, y = disp)) +
      geom_point()

    plt + 
      scale_x_continuous(n.breaks = 5)

enter image description here

    plt + 
      scale_x_continuous(n.breaks = 10) +
      scale_y_continuous(n.breaks = 10)

enter image description here

Time calculation in php (add 10 hours)?

In order to increase or decrease time using strtotime you could use a Relative format in the first argument.

In your case to increase the current time by 10 hours:

$date = date('h:i:s A', strtotime('+10 hours'));

In case you need to apply the change to another timestamp, the second argument can be specified.

Note:

Using this function for mathematical operations is not advisable. It is better to use DateTime::add() and DateTime::sub() in PHP 5.3 and later, or DateTime::modify() in PHP 5.2.

So, the recommended way since PHP 5.3:

$dt = new DateTime(); // assuming we need to add to the current time
$dt->add(new DateInterval('PT10H'));
$date = $dt->format('h:i:s A');

or using aliases:

$dt = date_create(); // assuming we need to add to the current time
date_add($dt, date_interval_create_from_date_string('10 hours')); 
$date = date_format($dt, 'h:i:s A');

In all cases the default time zone will be used unless a time zone is specified.

Repeating a function every few seconds

Use a timer. Keep in mind that .NET comes with a number of different timers. This article covers the differences.

Android 8: Cleartext HTTP traffic not permitted

I have removed this line from the android manifest file which is already there

 android:networkSecurityConfig="@xml/network_security_config" 

and added

android:usesCleartextTraffic="true"

this in to application tag in manifest

<application
    android:usesCleartextTraffic="true"
    android:allowBackup="true"
    android:label="@string/app_name"
    android:largeHeap="true"
    android:supportsRtl="true"
    android:theme="@style/AppTheme"
    >

then this error Cleartext HTTP traffic to overlay.openstreetmap.nl not permitted is gone for me in android 9 and 10.I hope this will work for android 8 also if it is helped you don't forget to vote thank you

Open Google Chrome from VBA/Excel

shell("C:\Users\USERNAME\AppData\Local\Google\Chrome\Application\Chrome.exe -url http:google.ca")

Excel to CSV with UTF8 encoding

Easy way to do it: download open office (here), load the spreadsheet and open the excel file (.xls or .xlsx). Then just save it as a text CSV file and a window opens asking to keep the current format or to save as a .ODF format. select "keep the current format" and in the new window select the option that works better for you, according with the language that your file is been written on. For Spanish language select Western Europe (Windows-1252/ WinLatin 1) and the file works just fine. If you select Unicode (UTF-8), it is not going to work with the spanish characters.

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

Chrome

This can be achieved by three different approaches (see my blog article here for more details):

  • Search in Elements panel like below
  • Execute $x() and $$() in Console panel, as shown in Lawrence's answer
  • Third party extensions (not really necessary in most of the cases, could be an overkill)

Here is how you search XPath in Elements panel:

  1. Press F12 to open Chrome Developer Tool
  2. In "Elements" panel, press Ctrl+F
  3. In the search box, type in XPath or CSS Selector, if elements are found, they will be highlighted in yellow.

enter image description here

Firefox (since version 75)

Since FF 75 it's possible to use raw xpath query without evaluation xpath expressions, see documentation for more info.

Firefox (prior version 75)

  1. Either select "Web Console" from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on Mac OS X)
    or press the Ctrl+Shift+K (Command+Option+K on OS X) keyboard shortcut.
  2. In the command line at the bottom use the following:

    • $(): Returns the first element that matches. Equivalent to document.querySelector() or calls the $ function in the page, if it exists.

    • $$(): Returns an array of DOM nodes that match. This is like for document.querySelectorAll(), but returns an array instead of a NodeList.

    • $x(): Evaluates an XPath expression and returns an array of matching nodes.


Firefox (prior version 49)

  1. Install Firebug
  2. Install Firepath
  3. Press F12 to open Firebug
  4. Switch to FirePath panel
  5. In dropdown, select XPathor CSS
  6. Type in to locate

enter image description here

In Windows cmd, how do I prompt for user input and use the result in another command?

@echo off
set /p input="Write something, it will be used in the command "echo""
echo %input%
pause

if i get what you want, this works fine. you can use %input% in other commands too.

@echo off
echo Write something, it will be used in the command "echo"
set /p input=""
cls
echo %input%
pause 

Return a 2d array from a function

What you are (trying to do)/doing in your snippet is to return a local variable from the function, which is not at all recommended - nor is it allowed according to the standard.

If you'd like to create a int[6][6] from your function you'll either have to allocate memory for it on the free-store (ie. using new T/malloc or similar function), or pass in an already allocated piece of memory to MakeGridOfCounts.

How to make war file in Eclipse

File -> Export -> Web -> WAR file

OR in Kepler follow as shown below :

enter image description here

CentOS: Enabling GD Support in PHP Installation

With CentOS 6.5+ and PHP 5.5:

yum install php55u-gd
service httpd restart

If you get an error like: cannot map zero-fill pages: Cannot allocate memory in Unknown on line 0, it could be because you don't have a swap file. I suggest you take a look at the tutorial mentioned in this answer: https://stackoverflow.com/a/20275282/828366

Tutorial: https://www.digitalocean.com/community/articles/how-to-add-swap-on-centos-6

Git vs Team Foundation Server

The whole Distributed thing of Git is really really great. it gives a few features Shelvesets don't have (in the current product) such as local rollback and commit options (such as Eclipse's localhistory feature). You could alleviate this using developer branches, but lets be honest, many developers don't like branching and merging one bit. I've been asked to turn on the old style "exclusive checkout" feature in TFS a few times too often (and denied it each and every time).

I think many large enterprises are quite scared to allow a dev to just bring the whole history into a local workspace and take it with them (to a new employer for example)... Stealing a snapshot is bad, but taking away a whole history is even more troublesome. (Not that you couldn't get a full history from TFS of you wanted it)...

It's mentioned that it's a great way to backup, which is great for open source again where the original maintainer might stop to care and removes his version, but for a enterprise plan this again falls short for many enterprises as there is no clear assignment of responsibility to keep backups. And it would be hard to figure out which version to use if the main 'project' vanishes somehow. Which would tend to appoint one repository as leading/central.

What I like most about Git is the Push/Pull option, where you can easily contribute code to a project without the need to have commit rights. I guess you could use very limited users and shelvesets in TFS to mimic this, but it isn't as powerful as the Git option. Branching across team projects might work as well, but from an administrative perspective it's not really feasible for many organisations as adding team projects adds a lot of administartive overhead.

I'd also like to add to the things mentioned in the non source control area. Features such as Work Item Tracking, Reporting and Build Automation (including lab management) greatly benefit from a central leading repository. These become a lot harder when you use a pure distributed model, unless you make one of the nodes leading (and thus go back to a less distributed model).

With TFS Basic coming with TFS 11, it might not be far off to expect a distributed TFS which allows you to sync your local TFS basic to a central TFS in the TFS 12+ era. I'll put my vote for that down in the uservoice!

How do I test for an empty JavaScript object?

This is my preferred solution:

var obj = {};
return Object.keys(obj).length; //returns 0 if empty or an integer > 0 if non-empty

Uncaught SyntaxError: Unexpected token with JSON.parse

Hopefully this helps someone else.

My issue was that I had commented HTML in a PHP callback function via AJAX that was parsing the comments and return invalid JSON.

Once I removed the commented HTML, all was good and the JSON was parsed with no issues.

Combine GET and POST request methods in Spring

@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
        @RequestParam(required = false) String parameter1,
        @RequestParam(required = false) String parameter2, 
        BindingResult result, HttpServletRequest request) 
        throws ParseException {

    LONG CODE and SAME LONG CODE with a minor difference
}

if @RequestParam(required = true) then you must pass parameter1,parameter2

Use BindingResult and request them based on your conditions.

The Other way

@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,  
    two @RequestParam parameters, HttpServletRequest request) throws ParseException {

    myMethod();

}


@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, 
        BindingResult result) throws ParseException {

    myMethod();

    do here your minor difference
}

private returntype myMethod(){
    LONG CODE
}

What is the equivalent to getch() & getche() in Linux?

#include <termios.h>
#include <stdio.h>

static struct termios old, current;

/* Initialize new terminal i/o settings */
void initTermios(int echo) 
{
  tcgetattr(0, &old); /* grab old terminal i/o settings */
  current = old; /* make new settings same as old settings */
  current.c_lflag &= ~ICANON; /* disable buffered i/o */
  if (echo) {
      current.c_lflag |= ECHO; /* set echo mode */
  } else {
      current.c_lflag &= ~ECHO; /* set no echo mode */
  }
  tcsetattr(0, TCSANOW, &current); /* use these new terminal i/o settings now */
}

/* Restore old terminal i/o settings */
void resetTermios(void) 
{
  tcsetattr(0, TCSANOW, &old);
}

/* Read 1 character - echo defines echo mode */
char getch_(int echo) 
{
  char ch;
  initTermios(echo);
  ch = getchar();
  resetTermios();
  return ch;
}

/* Read 1 character without echo */
char getch(void) 
{
  return getch_(0);
}

/* Read 1 character with echo */
char getche(void) 
{
  return getch_(1);
}

/* Let's test it out */
int main(void) {
  char c;
  printf("(getche example) please type a letter: ");
  c = getche();
  printf("\nYou typed: %c\n", c);
  printf("(getch example) please type a letter...");
  c = getch();
  printf("\nYou typed: %c\n", c);
  return 0;
}

Output:

(getche example) please type a letter: g
You typed: g
(getch example) please type a letter...
You typed: g

How to implement the factory method pattern in C++ correctly

Simple Factory Example:

// Factory returns object and ownership
// Caller responsible for deletion.
#include <memory>
class FactoryReleaseOwnership{
  public:
    std::unique_ptr<Foo> createFooInSomeWay(){
      return std::unique_ptr<Foo>(new Foo(some, args));
    }
};

// Factory retains object ownership
// Thus returning a reference.
#include <boost/ptr_container/ptr_vector.hpp>
class FactoryRetainOwnership{
  boost::ptr_vector<Foo>  myFoo;
  public:
    Foo& createFooInSomeWay(){
      // Must take care that factory last longer than all references.
      // Could make myFoo static so it last as long as the application.
      myFoo.push_back(new Foo(some, args));
      return myFoo.back();
    }
};

XSLT string replace

replace isn't available for XSLT 1.0.

Codesling has a template for string-replace you can use as a substitute for the function:

<xsl:template name="string-replace-all">
    <xsl:param name="text" />
    <xsl:param name="replace" />
    <xsl:param name="by" />
    <xsl:choose>
        <xsl:when test="$text = '' or $replace = ''or not($replace)" >
            <!-- Prevent this routine from hanging -->
            <xsl:value-of select="$text" />
        </xsl:when>
        <xsl:when test="contains($text, $replace)">
            <xsl:value-of select="substring-before($text,$replace)" />
            <xsl:value-of select="$by" />
            <xsl:call-template name="string-replace-all">
                <xsl:with-param name="text" select="substring-after($text,$replace)" />
                <xsl:with-param name="replace" select="$replace" />
                <xsl:with-param name="by" select="$by" />
            </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="$text" />
        </xsl:otherwise>
    </xsl:choose>
</xsl:template>

invoked as:

<xsl:variable name="newtext">
    <xsl:call-template name="string-replace-all">
        <xsl:with-param name="text" select="$text" />
        <xsl:with-param name="replace" select="a" />
        <xsl:with-param name="by" select="b" />
    </xsl:call-template>
</xsl:variable>

On the other hand, if you literally only need to replace one character with another, you can call translate which has a similar signature. Something like this should work fine:

<xsl:variable name="newtext" select="translate($text,'a','b')"/>

Also, note, in this example, I changed the variable name to "newtext", in XSLT variables are immutable, so you can't do the equivalent of $foo = $foo like you had in your original code.

get the titles of all open windows

Based on the previous answer that give me some errors, finaly I use this code with GetOpenedWindows function:

public class InfoWindow
{
            public IntPtr Handle = IntPtr.Zero;
            public FileInfo File = new FileInfo( Application.ExecutablePath );
            public string Title = Application.ProductName;
            public override string ToString() {
                return  File.Name + "\t>\t" + Title;
            }
 }//CLASS

/// <summary>Contains functionality to get info on the open windows.</summary>
public static class RuningWindows
{   
            internal static event EventHandler WindowActivatedChanged;    
            internal static Timer TimerWatcher = new Timer();    
            internal static InfoWindow WindowActive = new InfoWindow();       
            internal static void DoStartWatcher() {
                TimerWatcher.Interval = 500;
                TimerWatcher.Tick += TimerWatcher_Tick;
                TimerWatcher.Start();    
            }                    

            /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
            /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
            public static IDictionary<IntPtr , InfoWindow> GetOpenedWindows()
            {
                IntPtr shellWindow = GetShellWindow();
                Dictionary<IntPtr , InfoWindow> windows = new Dictionary<IntPtr , InfoWindow>();

                EnumWindows( new EnumWindowsProc( delegate( IntPtr hWnd , int lParam ) {
                    if ( hWnd == shellWindow ) return true;
                    if ( !IsWindowVisible( hWnd ) ) return true;    
                    int length = GetWindowTextLength( hWnd );
                    if ( length == 0 ) return true;    
                    StringBuilder builder = new StringBuilder( length );
                    GetWindowText( hWnd , builder , length + 1 );    
                    var info = new InfoWindow();
                    info.Handle = hWnd;
                    info.File = new FileInfo( GetProcessPath( hWnd ) );
                    info.Title = builder.ToString();    
                    windows[hWnd] = info;
                    return true;    
                } ) , 0 );    
                return windows;
            }

            private delegate bool EnumWindowsProc( IntPtr hWnd , int lParam );  

            public static string GetProcessPath( IntPtr hwnd )
            {
                uint pid = 0;
                GetWindowThreadProcessId( hwnd , out pid );
                if ( hwnd != IntPtr.Zero ) {
                    if ( pid != 0 ) {
                        var process = Process.GetProcessById( (int) pid );
                        if ( process != null ) {
                            return process.MainModule.FileName.ToString();
                        }
                    }
                }
                return "";
            }    

            [DllImport( "USER32.DLL" )]
            private static extern bool EnumWindows( EnumWindowsProc enumFunc , int lParam );

            [DllImport( "USER32.DLL" )]
            private static extern int GetWindowText( IntPtr hWnd , StringBuilder lpString , int nMaxCount );

            [DllImport( "USER32.DLL" )]
            private static extern int GetWindowTextLength( IntPtr hWnd );

            [DllImport( "USER32.DLL" )]
            private static extern bool IsWindowVisible( IntPtr hWnd );

            [DllImport( "USER32.DLL" )]
            private static extern IntPtr GetShellWindow();

            [DllImport( "user32.dll" )]
            private static extern IntPtr GetForegroundWindow();

            //WARN: Only for "Any CPU":
            [DllImport( "user32.dll" , CharSet = CharSet.Auto , SetLastError = true )]
            private static extern int GetWindowThreadProcessId( IntPtr handle , out uint processId );    


            static void TimerWatcher_Tick( object sender , EventArgs e )
            {
                var windowActive = new InfoWindow();
                windowActive.Handle = GetForegroundWindow();
                string path = GetProcessPath( windowActive.Handle );
                if ( string.IsNullOrEmpty( path ) ) return;
                windowActive.File = new FileInfo( path );
                int length = GetWindowTextLength( windowActive.Handle );
                if ( length == 0 ) return;
                StringBuilder builder = new StringBuilder( length );
                GetWindowText( windowActive.Handle , builder , length + 1 );
                windowActive.Title = builder.ToString();
                if ( windowActive.ToString() != WindowActive.ToString() ) {
                    //fire:
                    WindowActive = windowActive;
                    if ( WindowActivatedChanged != null ) WindowActivatedChanged( sender , e );
                    Console.WriteLine( "Window: " + WindowActive.ToString() );
                }
            }

}//CLASS

Warning: You can only compil/debug under "Any CPU" to access to 32bits Apps...

Configuring IntelliJ IDEA for unit testing with JUnit

Press Ctrl+Shift+T in the code editor. It will show you popup with suggestion to create a test.

Mac OS: ? Cmd+Shift+T

How do I call a JavaScript function on page load?

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <head>_x000D_
        <title>Test</title>_x000D_
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
        <script type="text/javascript">_x000D_
        function codeAddress() {_x000D_
            alert('ok');_x000D_
        }_x000D_
        window.onload = codeAddress;_x000D_
        </script>_x000D_
    </head>_x000D_
    <body>_x000D_
    _x000D_
    </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

CSS center content inside div

Try using flexbox. As an example, the following code shows the CSS for the container div inside which the contents needs to be centered aligned:

.absolute-center {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;

    align-items: center;

}

How to get response as String using retrofit without using GSON or any other library in android

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

Example interface --

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- Original Answer (still works, just more code) ---

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.

Java Webservice Client (Best way)

I have had good success using Spring WS for the client end of a web service app - see http://static.springsource.org/spring-ws/sites/1.5/reference/html/client.html

My project uses a combination of:

  • XMLBeans (generated from a simple Maven job using the xmlbeans-maven-plugin)

  • Spring WS - using marshalSendAndReceive() reduces the code down to one line for sending and receiving

  • some Dozer - mapping the complex XMLBeans to simple beans for the client GUI

Can't load IA 32-bit .dll on a AMD 64-bit platform

Short answer to first question: yes.

Longer answer: maybe; it depends on whether the build process for SVMLight behaves itself on 64-bit windows.

Final note: that call to System.loadLibrary is silly. Either call System.load with a full pathname or let it search java.library.path.

Select and trigger click event of a radio button in jquery

Switch the order of the code: You're calling the click event before it is attached.

$(document).ready(function() {
      $("#checkbox_div input:radio").click(function() {

           alert("clicked");

      });

      $("input:radio:first").prop("checked", true).trigger("click");

});

DROP IF EXISTS VS DROP?

If no table with such name exists, DROP fails with error while DROP IF EXISTS just does nothing.

This is useful if you create/modifi your database with a script; this way you do not have to ensure manually that previous versions of the table are deleted. You just do a DROP IF EXISTS and forget about it.

Of course, your current DB engine may not support this option, it is hard to tell more about the error with the information you provide.

Why this "Implicit declaration of function 'X'"?

summation and your other functions are defined after they're used in main, and so the compiler has made a guess about it's signature; in other words, an implicit declaration has been assumed.

You should declare the function before it's used and get rid of the warning. In the C99 specification, this is an error.

Either move the function bodies before main, or include method signatures before main, e.g.:

#include <stdio.h>

int summation(int *, int *, int *);

int main()
{
    // ...

How to remove a row from JTable?

The correct way to apply a filter to a JTable is through the RowFilter interface added to a TableRowSorter. Using this interface, the view of a model can be changed without changing the underlying model. This strategy preserves the Model-View-Controller paradigm, whereas removing the rows you wish hidden from the model itself breaks the paradigm by confusing your separation of concerns.

Auto expand a textarea using jQuery

This is the solution I ended up using. I wanted an inline solution, and this so far seems to work great:

<textarea onkeyup="$(this).css('height', 'auto').css('height', this.scrollHeight + this.offsetHeight - this.clientHeight);"></textarea>

Comparing arrays for equality in C++

When we use an array, we are really using a pointer to the first element in the array. Hence, this condition if( iar1 == iar2 ) actually compares two addresses. Those pointers do not address the same object.

How to check if array is not empty?

If you are talking about Python's actual array (available through import array from array), then the principle of least astonishment applies and you can check whether it is empty the same way you'd check if a list is empty.

from array import array
an_array = array('i') # an array of ints

if an_array:
    print("this won't be printed")

an_array.append(3)

if an_array:
    print("this will be printed")

How to check if a textbox is empty using javascript

You can also check it using jQuery.. It's quite easy:

<html>
    <head>
        <title>jQuery: Check if Textbox is empty</title>
        <script type="text/javascript" src="js/jquery_1.7.1_min.js"></script>
    </head>
    <body>
        <form name="form1" method="post" action="">
            <label for="city">City:</label>
            <input type="text" name="city" id="city">
        </form>
        <button id="check">Check</button>
        <script type="text/javascript">
             $('#check').click(function () {
                 if ($('#city').val() == '') {
                     alert('Empty!!!');
                 } else {
                     alert('Contains: ' + $('#city').val());
                 }
             });                
        </script>
    </body>
</html>

How can I bring my application window to the front?

Before stumbling onto this post, I came up with this solution - to toggle the TopMost property:

this.TopMost = true;
this.TopMost = false;

I have this code in my form's constructor, eg:

public MyForm()
{
    //...

    // Brint-to-front hack
    this.TopMost = true;
    this.TopMost = false;

    //...
}

Make a div into a link

An option that hasn't been mentioned is using flex. By applying flex: 1 to the a tag, it expands to fit the container.

_x000D_
_x000D_
div {_x000D_
  height: 100px;_x000D_
  width: 100px;_x000D_
  display: flex;_x000D_
  border: 1px solid;_x000D_
}_x000D_
_x000D_
a {_x000D_
  flex: 1;_x000D_
}
_x000D_
<div>_x000D_
  <a href="http://google.co.uk">Link</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

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

I use $(document.createElement('div')); Benchmarking shows this technique is the fastest. I speculate this is because jQuery doesn't have to identify it as an element and create the element itself.

You should really run benchmarks with different Javascript engines and weigh your audience with the results. Make a decision from there.

Can't execute jar- file: "no main manifest attribute"

For me, none of the answers really helped - I had the manifest file in correct place, containing the Main-Class and everything. What tripped me over was this:

Warning: The text file from which you are creating the manifest must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.

(source). Adding a newline at the end of the manifest fixed it.

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

How to set a text box for inputing password in winforms?

private void cbShowHide_CheckedChanged(object sender, EventArgs e)
{
    if (cbShowHide.Checked)
    {
        txtPin.UseSystemPasswordChar = PasswordPropertyTextAttribute.No.Password;
    }
    else
    {
        //Hides Textbox password
        txtPin.UseSystemPasswordChar = PasswordPropertyTextAttribute.Yes.Password;
    }
}

Copy this code to show and hide your textbox using a checkbox

How do I print a list of "Build Settings" in Xcode project?

This has been answered above, but I wanted to suggest an alternative.

When in the Build Settings for you project or target, you can go to the Editor menu and select Show Setting Names from the menu. This will change all of the options in the Build Settings pane to the build variable names. The option in the menu changes to Show Setting Titles, select this to change back to the original view.

This can be handy when you know what build setting you want to use in a script, toggle the setting names in the menu and you can see the variable name.

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

DbEntityValidationException - How can I easily tell what caused the error?

I think "The actual validation errors" may contain sensitive information, and this could be the reason why Microsoft chose to put them in another place (properties). The solution marked here is practical, but it should be taken with caution.

I would prefer to create an extension method. More reasons to this:

  • Keep original stack trace
  • Follow open/closed principle (ie.: I can use different messages for different kind of logs)
  • In production environments there could be other places (ie.: other dbcontext) where a DbEntityValidationException could be thrown.

Xcode 6 Storyboard the wrong size?

In Storyboard, select your ViewController and go to Atribute Inspector. At the very top, under Simulated Metrics you have Size and Orientation properties which are set to Inferred. Change them to desired values.

In order for an application to display properly on another screen size, you also have to setup constraints, as described by Can Poyrazoglu in the first post.

Flask ImportError: No Module Named Flask

If you are using Pycharm then this is the virtual environment issue.

So, at the time of creating your Python project you will have to select "Existing interpreter" option -> click "system Interpreter" -> select the correct option for example "*\AppData\Local\Programs\Python\Python3.6\python.exe".

You can use 'New Virtual Env' as well, but I have just given the quick fix that should work for Pycharm users.

Format Date/Time in XAML in Silverlight

<TextBlock Text="{Binding Date, StringFormat='{}{0:MM/dd/yyyy a\\t h:mm tt}'}" />

will return you

04/07/2011 at 1:28 PM (-04)

How to convert a string of numbers to an array of numbers?

You can use Array.map to convert each element into a number.

var a = "1,2,3,4";

var b = a.split(',').map(function(item) {
    return parseInt(item, 10);
});

Check the Docs


Or more elegantly as pointed out by User: thg435

var b = a.split(',').map(Number);

Where Number() would do the rest:check here


Note: For older browsers that don't support map, you can add an implementation yourself like:

Array.prototype.map = Array.prototype.map || function(_x) {
    for(var o=[], i=0; i<this.length; i++) { 
        o[i] = _x(this[i]); 
    }
    return o;
};

WAITING at sun.misc.Unsafe.park(Native Method)

unsafe.park is pretty much the same as thread.wait, except that it's using architecture specific code (thus the reason it's 'unsafe'). unsafe is not made available publicly, but is used within java internal libraries where architecture specific code would offer significant optimization benefits. It's used a lot for thread pooling.

So, to answer your question, all the thread is doing is waiting for something, it's not really using any CPU. Considering that your original stack trace shows that you're using a lock I would assume a deadlock is going on in your case.

Yes I know you have almost certainly already solved this issue by now. However, you're one of the top results if someone googles sun.misc.unsafe.park. I figure answering the question may help others trying to understand what this method that seems to be using all their CPU is.

How to create string with multiple spaces in JavaScript

With template literals, you can use multiple spaces or multi-line strings and string interpolation. Template Literals are a new ES2015 / ES6 feature that allows you to work with strings. The syntax is very simple, just use backticks instead of single or double quotes:

let a = `something                 something`;

and to make multiline strings just press enter to create a new line, with no special characters:

let a = `something 

    
                         something`;

The results are exactly the same as you write in the string.

How to get the current location in Google Maps Android API v2?

To get the location when the user clicks on a button call this method in the onClick-

void getCurrentLocation() {
    Location myLocation  = mMap.getMyLocation();
    if(myLocation!=null)
    {
        double dLatitude = myLocation.getLatitude();
        double dLongitude = myLocation.getLongitude();
        Log.i("APPLICATION"," : "+dLatitude);
        Log.i("APPLICATION"," : "+dLongitude);
        mMap.addMarker(new MarkerOptions().position(
                new LatLng(dLatitude, dLongitude)).title("My Location").icon(BitmapDescriptorFactory.fromBitmap(Utils.getBitmap("pointer_icon.png"))));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(dLatitude, dLongitude), 8));

    }
    else
    {
        Toast.makeText(this, "Unable to fetch the current location", Toast.LENGTH_SHORT).show();
    }

}

Also make sure that the

setMyLocationEnabled

is set to true.

Try and see if this works...

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

How do I round a float upwards to the nearest int in C#?

Off the top of my head:

float fl = 0.678;
int rounded_f = (int)(fl+0.5f);

Android 6.0 Marshmallow. Cannot write to SD Card

Android Documentation on Manifest.permission.Manifest.permission.WRITE_EXTERNAL_STORAGE states:

Starting in API level 19, this permission is not required to read/write files in your application-specific directories returned by getExternalFilesDir(String) and getExternalCacheDir().


I think that this means you do not have to code for the run-time implementation of the WRITE_EXTERNAL_STORAGE permission unless the app is writing to a directory that is not specific to your app.

You can define the max sdk version in the manifest per permission like:

 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" android:maxSdkVersion="19" />

Also make sure to change the target SDK in the build.graddle and not the manifest, the gradle settings will always overwrite the manifest settings.

android {
compileSdkVersion 23
buildToolsVersion '23.0.1'
defaultConfig {
    minSdkVersion 17
    targetSdkVersion 22
}

.NET Excel Library that can read/write .xls files

Is there a reason why you can't use the Excel ODBC connection to read and write to Excel? For example, I've used the following code to read from an Excel file row by row like a database:

private DataTable LoadExcelData(string fileName)
{
  string Connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\";";

  OleDbConnection con = new OleDbConnection(Connection);

  OleDbCommand command = new OleDbCommand();

  DataTable dt = new DataTable(); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$] WHERE LastName <> '' ORDER BY LastName, FirstName", con);

  myCommand.Fill(dt);

  Console.WriteLine(dt.Rows.Count);

  return dt;
}

You can write to the Excel "database" the same way. As you can see, you can select the version number to use so that you can downgrade Excel versions for the machine with Excel 2003. Actually, the same is true for using the Interop. You can use the lower version and it should work with Excel 2003 even though you only have the higher version on your development PC.

Are one-line 'if'/'for'-statements good Python style?

an example of a language feature that isn't just removing line breaks, although still not convinced this is clearer than the more verbose version

a = 1 if x > 15 else 2

Serving static web resources in Spring Boot & Spring Security application

There are a couple of things to be aware of:

  • The Ant matchers match against the request path and not the path of the resource on the filesystem.
  • Resources placed in src/main/resources/public will be served from the root of your application. For example src/main/resources/public/hello.jpg would be served from http://localhost:8080/hello.jpg

This is why your current matcher configuration hasn't permitted access to the static resources. For /resources/** to work, you would have to place the resources in src/main/resources/public/resources and access them at http://localhost:8080/resources/your-resource.

As you're using Spring Boot, you may want to consider using its defaults rather than adding extra configuration. Spring Boot will, by default, permit access to /css/**, /js/**, /images/**, and /**/favicon.ico. You could, for example, have a file named src/main/resources/public/images/hello.jpg and, without adding any extra configuration, it would be accessible at http://localhost:8080/images/hello.jpg without having to log in. You can see this in action in the web method security smoke test where access is permitted to the Bootstrap CSS file without any special configuration.

Using :focus to style outer div?

As far as I am aware you have to use javascript to travel up the dom.

Something like this:

$("textarea:focus").parent().attr("border", "thin solid black");

you'll need the jQuery libraries loaded as well.

SQL Logic Operator Precedence: And and Or

And has precedence over Or, so, even if a <=> a1 Or a2

Where a And b 

is not the same as

Where a1 Or a2 And b,

because that would be Executed as

Where a1 Or (a2 And b)

and what you want, to make them the same, is the following (using parentheses to override rules of precedence):

 Where (a1 Or a2) And b

Here's an example to illustrate:

Declare @x tinyInt = 1
Declare @y tinyInt = 0
Declare @z tinyInt = 0

Select Case When @x=1 OR @y=1 And @z=1 Then 'T' Else 'F' End -- outputs T
Select Case When (@x=1 OR @y=1) And @z=1 Then 'T' Else 'F' End -- outputs F

For those who like to consult references (in alphabetic order):

How do I set up Vim autoindentation properly for editing Python files?

for more advanced python editing consider installing the simplefold vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.

What is the fastest factorial function in JavaScript?

Well this question has more than enough answers, but just to post a readable, fast and short solution for factorial and reverse factorial.

{
    const cache = [1, 1];
    let i = 2;

    function factorial(n) {
        if (!isFinite(n = parseInt(n)) || n < 0)
            throw new Error('argument for factorial has to be a positive finite integer but was ' + n);

        for (; i <= n; i++)
            cache[i] = cache[i - 1] * i;

        return cache[n];
    }

    function reverseFactorial(n) {
        if (!isFinite(n = parseFloat(n)) || n < 0)
            throw new Error('argument for reverseFactorial has to be a positive finite floatingpoint number but was ' + n);

        let f = 1;

        while (true)
            if (factorial(++f) >= n)
                return f - 1; // lower bound (f! which will fit in the given n, for upper bound just return f)

    }
}

reverseFactorial will return an k which is the biggest k! which fits in the given n.

Both functions profit of the cache build by factorial.

If you want to test it a little:

for (let i = 0; i < 10; i++) {
    let random = Math.random() * 100;
    random = factorial(random) * Math.random() * random;

    const reverse = reverseFactorial(random);
    const resultOfReverse = factorial(reverse);

    function expo(x) {
        return x.toExponential(2);
    }

    console.log('%s fits %d! which is %s (upper bound %d! is %s)', expo(random), reverse, expo(resultOfReverse), reverse + 1, expo(factorial(reverse + 1)));
}

String date to xmlgregoriancalendar conversion

For me the most elegant solution is this one:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");

Using Java 8.

Extended example:

XMLGregorianCalendar result = DatatypeFactory.newInstance()
    .newXMLGregorianCalendar("2014-01-07");
System.out.println(result.getDay());
System.out.println(result.getMonth());
System.out.println(result.getYear());

This prints out:

7
1
2014

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

R dates "origin" must be supplied

I suspect you meant:

axis.Date(1, as.Date(sites$date, origin = "1970-01-01"))

as the 'x' argument to as.Date() has to be of type Date.

As an aside, this would have appropriate as a follow-up or edit of your previous question.

ASP.Net MVC 4 Form with 2 submit buttons/actions

We can have this in 2 ways,

Either have 2 form submissions within the same View and having 2 Action methods at the controller but you will need to have the required fields to be submitted with the form to be placed within

ex is given here with code Multiple forms in view asp.net mvc with multiple submit buttons

Or

Have 2 or multiple submit buttons say btnSubmit1 and btnSubmit2 and check on the Action method which button was clicked using the code

if (Request.Form["btnSubmit1"] != null)
{
 //
}
if (Request.Form["btnSubmit2"] != null)
{
 //
}

Replace only some groups with Regex

go through the below coding to get the separate group replacement.

new_bib = Regex.Replace(new_bib, @"(?s)(\\bibitem\[[^\]]+\]\{" + pat4 + @"\})[\s\n\v]*([\\\{\}a-zA-Z\.\s\,\;\\\#\\\$\\\%\\\&\*\@\\\!\\\^+\-\\\=\\\~\\\:\\\" + dblqt + @"\\\;\\\`\\\']{20,70})", delegate(Match mts)
                    {
                           var fg = mts.Groups[0].Value.ToString(); 
                           var fs = mts.Groups[1].Value.ToString();
                           var fss = mts.Groups[2].Value.ToString();
                               fss = Regex.Replace(fss, @"[\\\{\}\\\#\\\$\\\%\\\&\*\@\\\!\\\^+\-\\\=\\\~\\\:\\\" + dblqt + @"\\\;\\\`\\\']+", "");
                           return "<augroup>" + fss + "</augroup>" + fs;
                    }, RegexOptions.IgnoreCase);

Graph implementation C++

This question is ancient but for some reason I can't seem to get it out of my mind.

While all of the solutions do provide an implementation of graphs, they are also all very verbose. They are simply not elegant.

Instead of inventing your own graph class all you really need is a way to tell that one point is connected to another -- for that, std::map and std::unordered_map work perfectly fine. Simply, define a graph as a map between nodes and lists of edges. If you don't need extra data on the edge, a list of end nodes will do just fine.

Thus a succinct graph in C++, could be implemented like so:

using graph = std::map<int, std::vector<int>>;

Or, if you need additional data,

struct edge {
    int nodes[2];
    float cost; // add more if you need it
};

using graph = std::map<int, std::vector<edge>>;

Now your graph structure will plug nicely into the rest of the language and you don't have to remember any new clunky interface -- the old clunky interface will do just fine.

No benchmarks, but I have a feeling this will also outperform the other suggestions here.

NB: the ints are not indices -- they are identifiers.

Convert unsigned int to signed int C

You are expecting that your int type is 16 bit wide, in which case you'd indeed get a negative value. But most likely it's 32 bits wide, so a signed int can represent 65529 just fine. You can check this by printing sizeof(int).

How to host a Node.Js application in shared hosting

I installed Node.js on bluehost.com (a shared server) using:

wget <path to download file>
tar -xf <gzip file>
mv <gzip_file_dir> node

This will download the tar file, extract to a directory and then rename that directory to the name 'node' to make it easier to use.

then

./node/bin/npm install jt-js-sample

Returns:
npm WARN engine [email protected]: wanted: {"node":"0.10.x"} (current: {"node":"0.12.4","npm":"2.10.1"})
[email protected] node_modules/jt-js-sample
+-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])

I can now use the commands:

# ~/node/bin/node -v
v0.12.4

# ~/node/bin/npm -v
2.10.1

For security reasons, I have renamed my node directory to something else.

Putting an if-elif-else statement on one line?

There's an alternative that's quite unreadable in my opinion but I'll share anyway just as a curiosity:

x = (i>100 and 2) or (i<100 and 1) or 0

More info here: https://docs.python.org/3/library/stdtypes.html#boolean-operations-and-or-not

Get the first element of an array

From Laravel's helpers:

function head($array)
{
    return reset($array);
}

The array being passed by value to the function, the reset() affects the internal pointer of a copy of the array, and it doesn't touch the original array (note it returns false if the array is empty).

Usage example:

$data = ['foo', 'bar', 'baz'];

current($data); // foo
next($data); // bar
head($data); // foo
next($data); // baz

Also, here is an alternative. It's very marginally faster, but more interesting. It lets easily change the default value if the array is empty:

function head($array, $default = null)
{
    foreach ($array as $item) {
        return $item;
    }
    return $default;
}

For the record, here is another answer of mine, for the array's last element.

Convert float to double without losing precision

I've encountered this issue today and could not use refactor to BigDecimal, because the project is really huge. However I found solution using

Float result = new Float(5623.23)
Double doubleResult = new FloatingDecimal(result.floatValue()).doubleValue()

And this works.

Note that calling result.doubleValue() returns 5623.22998046875

But calling doubleResult.doubleValue() returns correctly 5623.23

But I am not entirely sure if its a correct solution.

How to get a Static property with Reflection

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

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

What is causing this error - "Fatal error: Unable to find local grunt"

I had the same issue in Vagrant.

I have used sudo to run the command to install.

sudo npm install -g grunt-cli

It worked for me.

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

You don't need to uninstall WebDAV, just add these lines to the web.config:

<system.webServer>
  <modules>
    <remove name="WebDAVModule" />
  </modules>
  <handlers>
    <remove name="WebDAV" />
  </handlers>
</system.webServer>

Can't bind to 'ngModel' since it isn't a known property of 'input'

Import FormModule in file app.module

import { FormsModule } from '@angular/forms'; [...] @NgModule({ imports: [ [...] FormsModule ], [...] })

How to set a class attribute to a Symfony2 form input

You can to this in Twig or the FormClass as shown in the examples above. But you might want to decide in the controller which class your form should get. Just keep in mind to not have much logic in the controller in general!

    $form = $this->createForm(ContactForm::class, null, [
        'attr' => [
            'class' => 'my_contact_form'
        ]
    ]);

Using import fs from 'fs'

Building on RobertoNovelo's answer:

import * as fs from 'fs';

is currently the simplest way to do it.

It was tested with a Node.js project (Node.js v10.15.3), with esm, allowing to use import.

Exclude all transitive dependencies of a single dependency

Use the latest maven in your classpath.. It will remove the duplicate artifacts and keep the latest maven artifact..

how to change background image of button when clicked/focused?

You can also create shapes directly inside the item tag, in case you want to add some more details to your view, like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="#81ba73" />
            <corners android:radius="6dp" />
        </shape>
        <ripple android:color="#c62828"/>
    </item>
    <item android:state_enabled="false">
        <shape>
            <solid android:color="#788e73" />
            <corners android:radius="6dp" />
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="#add8a3" />
            <corners android:radius="6dp" />
        </shape>
    </item>
</selector>

Beware that Android will cycle through the items from top to bottom, therefore, you must place the item without condition on the bottom of the list (so it acts like a default/fallback).

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

Thanks @CFinck ! Just to add a tip to others : I changed the ResourceManager line with this :

New Global.System.Resources.ResourceManager(Reflection.Assembly.GetCallingAssembly.GetName.Name & ".CommonNameOf.Resources", Reflection.Assembly.GetCallingAssembly())

I'm in vb.net but I think in C# the only difference would be + instead of & to concatenate strings.

This way I can use the same linked assembly files in two similar projects that share the resources.

Retrieve CPU usage and memory usage of a single process on Linux?

This is a nice trick to follow one or more programs in real time while also watching some other tool's output: watch "top -bn1 -p$(pidof foo),$(pidof bar); tool"

Select tableview row programmatically

There are two different methods for iPad and iPhone platforms, so you need to implement both:

  • selection handler and
  • segue.

    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    
    // Selection handler (for horizontal iPad)
    [self tableView:self.tableView didSelectRowAtIndexPath:indexPath];
    
    // Segue (for iPhone and vertical iPad)
    [self performSegueWithIdentifier:"showDetail" sender:self];
    

AES Encrypt and Decrypt

I found the solution, it is a good library.

Cross platform 256bit AES encryption / decryption.

This project contains the implementation of 256 bit AES encryption which works on all the platforms (C#, iOS, Android). One of the key objective is to make AES work on all the platforms with simple implementation.

Platforms Supported: iOS , Android , Windows (C#).

https://github.com/Pakhee/Cross-platform-AES-encryption

C# string replace

You can't use string.replace...as one string is assigned you cannot manipulate. For that, we use string builder. Here is my example. In the HTML page I add [Name] which is replaced by Name. Make sure [Name] is unique or you can give any unique name:

string Name = txtname.Text;
string contents = File.ReadAllText(Server.MapPath("~/Admin/invoice.html"));

StringBuilder builder = new StringBuilder(contents);

builder.Replace("[Name]", Name);

StringReader sr = new StringReader(builder.ToString());

Using Font Awesome icon for bullet points, with a single list item element

There's an example of how to use Font Awesome alongside an unordered list on their examples page.

<ul class="icons">
  <li><i class="icon-ok"></i> Lists</li>
  <li><i class="icon-ok"></i> Buttons</li>
  <li><i class="icon-ok"></i> Button groups</li>
  <li><i class="icon-ok"></i> Navigation</li>
  <li><i class="icon-ok"></i> Prepended form inputs</li>
</ul>

If you can't find it working after trying this code then you're not including the library correctly. According to their website, you should include the libraries as such:

<link rel="stylesheet" href="../css/bootstrap.css">
<link rel="stylesheet" href="../css/font-awesome.css">

Also check out the whimsical Chris Coyier's post on icon fonts on his website CSS Tricks.

Here's a screencast by him as well talking about how to create your own icon font-face.

Why use $_SERVER['PHP_SELF'] instead of ""

The action attribute will default to the current URL. It is the most reliable and easiest way to say "submit the form to the same place it came from".

There is no reason to use $_SERVER['PHP_SELF'], and # doesn't submit the form at all (unless there is a submit event handler attached that handles the submission).

Select values of checkbox group with jQuery

I'm not 100% entirely sure how you want to "grab" the values. But if you want to iterate over the checkboxes you can use .each like so:

("input[@name='user_group[]']").each( function() {
    alert($(this).val());
});

Of course a better selector is available:

$(':checkbox')

ASP.NET Identity DbContext confusion

If you drill down through the abstractions of the IdentityDbContext you'll find that it looks just like your derived DbContext. The easiest route is Olav's answer, but if you want more control over what's getting created and a little less dependency on the Identity packages have a look at my question and answer here. There's a code example if you follow the link, but in summary you just add the required DbSets to your own DbContext subclass.

How to add buttons at top of map fragment API v2 layout

You can use the below code to change the button to Left side.

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:map="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/map"
    android:name="com.google.android.gms.maps.SupportMapFragment"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.zakasoft.mymap.MapsActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left|top"
        android:text="Send"
        android:padding="10dp"
        android:layout_marginTop="20dp"
        android:paddingRight="10dp"/>

</fragment>

Postgresql - unable to drop database because of some auto connections to DB

Whenever I try to drop database I get:

ERROR:  database "pilot" is being accessed by other users
DETAIL:  There is 1 other session using the database.

First You need to revoke

REVOKE CONNECT ON DATABASE TARGET_DB FROM public;

Then use:

SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
WHERE pg_stat_activity.datname = 'TARGET_DB';

It will surely work.

OpenCV - Apply mask to a color image

Well, here is a solution if you want the background to be other than a solid black color. We only need to invert the mask and apply it in a background image of the same size and then combine both background and foreground. A pro of this solution is that the background could be anything (even other image).

This example is modified from Hough Circle Transform. First image is the OpenCV logo, second the original mask, third the background + foreground combined.

apply mask and get a customized background

# http://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_houghcircles/py_houghcircles.html
import cv2
import numpy as np

# load the image
img = cv2.imread('E:\\FOTOS\\opencv\\opencv_logo.png')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

# detect circles
gray = cv2.medianBlur(cv2.cvtColor(img, cv2.COLOR_RGB2GRAY), 5)
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=50, minRadius=0, maxRadius=0)
circles = np.uint16(np.around(circles))

# draw mask
mask = np.full((img.shape[0], img.shape[1]), 0, dtype=np.uint8)  # mask is only 
for i in circles[0, :]:
    cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)

# get first masked value (foreground)
fg = cv2.bitwise_or(img, img, mask=mask)

# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(img.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)

# combine foreground+background
final = cv2.bitwise_or(fg, bk)

Note: It is better to use the opencv methods because they are optimized.

what is the difference between XSD and WSDL

If someone is looking for analogy , this answer might be helpful.

WSDL is like 'SHOW TABLE STATUS' command in mysql. It defines all the elements(request type, response type, format of URL to hit request,etc.,) which should be part of XML. By definition I mean: 1) Names of request or response 2) What should be treated as input , what should be treated as output.

XSD is like DESCRIBE command in mysql. It tells what all variables and their types, a request and response contains.

How to delete a workspace in Perforce (using p4v)?

  1. Ctrl + 5

view workspace in p4v

  1. Delete the relevant workspace

enter image description here

Entity Framework: table without primary key

This maybe to late to reply...however...

If a table does't have a primary key then there are few scenarios that need to be analyzed in order to make the EF work properly. The rule is: EF will work with tables/classes with primary key. That is how it does tracking...

Say, your table 1. Records are unique: the uniqueness is made by a single foreign key column: 2. Records are unique: the uniqueness are made by a combination of multiple columns. 3. Records are not unique (for the most part*).

For scenarios #1 and #2 you can add the following line to DbContext module OnModelCreating method: modelBuilder.Entity().HasKey(x => new { x.column_a, x.column_b }); // as many columns as it takes to make records unique.

For the scenario #3 you can still use the above solution (#1 + #2) after you study the table (*what makes all records unique anyway). If you must have include ALL columns to make all records unique then you may want to add a primary key column to your table. If this table is from a 3rd party vendor than clone this table to your local database (overnight or as many time you needed) with primary key column added arbitrary through your clone script.

Spring jUnit Testing properties file

I faced the same issue, spent too much calories searching for the right fix until I decided to settle down with file reading:

Properties configProps = new Properties();
InputStream iStream = new ClassPathResource("myapp-test.properties").getInputStream();
InputStream iStream = getConfigFile();
configProps.load(iStream);

Get Absolute Position of element within the window in wpf

To get the absolute position of an UI element within the window you can use:

Point position = desiredElement.PointToScreen(new Point(0d, 0d));

If you are within an User Control, and simply want relative position of the UI element within that control, simply use:

Point position = desiredElement.PointToScreen(new Point(0d, 0d)),
controlPosition = this.PointToScreen(new Point(0d, 0d));

position.X -= controlPosition.X;
position.Y -= controlPosition.Y;

Can you explain the HttpURLConnection connection process?

On which point does HTTPURLConnection try to establish a connection to the given URL?

It's worth clarifying, there's the 'UrlConnection' instance and then there's the underlying Tcp/Ip/SSL socket connection, 2 different concepts. The 'UrlConnection' or 'HttpUrlConnection' instance is synonymous with a single HTTP page request, and is created when you call url.openConnection(). But if you do multiple url.openConnection()'s from the one 'url' instance then if you're lucky, they'll reuse the same Tcp/Ip socket and SSL handshaking stuff...which is good if you're doing lots of page requests to the same server, especially good if you're using SSL where the overhead of establishing the socket is very high.

See: HttpURLConnection implementation

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

Your status-codes are also a collection, so use Contains:

var allowedStatus = new[]{ "A", "B", "C" };
var filteredOrders = orders.Order.Where(o => allowedStatus.Contains(o.StatusCode));

or in query syntax:

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

wait process until all subprocess finish?

subprocess.call

Automatically waits , you can also use:

p1.wait()

How to make a browser display a "save as dialog" so the user can save the content of a string to a file on his system?

There is a javascript library for this, see FileSaver.js on Github

However the saveAs() function won't send pure string to the browser, you need to convert it to blob:

function data2blob(data, isBase64) {
  var chars = "";

  if (isBase64)
    chars = atob(data);
  else
    chars = data;

  var bytes = new Array(chars.length);
  for (var i = 0; i < chars.length; i++) {
    bytes[i] = chars.charCodeAt(i);
  }

  var blob = new Blob([new Uint8Array(bytes)]);
  return blob;
}

and then call saveAs on the blob, as like:

var myString = "my string with some stuff";
saveAs( data2blob(myString), "myString.txt" );

Of course remember to include the above-mentioned javascript library on your webpage using <script src=FileSaver.js>

Go to beginning of line without opening new line in VI

You can use 0 or ^ to move to beginning of the line.
And can use Shift+I to move to the beginning and switch to editing mode (Insert).

How to test if JSON object is empty in Java

If you're okay with a hack -

obj.toString().equals("{}");

Serializing the object is expensive and moreso for large objects, but it's good to understand that JSON is transparent as a string, and therefore looking at the string representation is something you can always do to solve a problem.

Setting up Vim for Python

Put the following in your .vimrc

autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
autocmd BufRead *.py set nocindent
autocmd BufWritePre *.py normal m`:%s/\s\+$//e ``
filetype plugin indent on

See also the detailed instructions

I personally use JetBrain's PyCharm with the IdeaVIM plugin when doing anything complex, for simple editing the additions to .vimrc seem sufficient.

Bootstrap: Position of dropdown menu relative to navbar item

Boostrap has a class for that called navbar-right. So your code will look as follows:

<ul class="nav navbar-right">
    <li class="dropdown">
      <a class="dropdown-toggle" href="#" data-toggle="dropdown">Link</a>
      <ul class="dropdown-menu">
         <li>...</li>
      </ul>
    </li>
</ul>

How do I convert csv file to rdd

We can use the new DataFrameRDD for reading and writing the CSV data. There are few advantages of DataFrameRDD over NormalRDD:

  1. DataFrameRDD are bit more faster than NormalRDD since we determine the schema and which helps to optimize a lot on runtime and provide us with significant performance gain.
  2. Even if the column shifts in CSV it will automatically take the correct column as we are not hard coding the column number which was present in reading the data as textFile and then splitting it and then using the number of column to get the data.
  3. In few lines of code you can read the CSV file directly.

You will be required to have this library: Add it in build.sbt

libraryDependencies += "com.databricks" % "spark-csv_2.10" % "1.2.0"

Spark Scala code for it:

val sc = new SparkContext(conf)
val sqlContext = new SQLContext(sc)
val csvInPath = "/path/to/csv/abc.csv"
val df = sqlContext.read.format("com.databricks.spark.csv").option("header","true").load(csvInPath)
//format is for specifying the type of file you are reading
//header = true indicates that the first line is header in it

To convert to normal RDD by taking some of the columns from it and

val rddData = df.map(x=>Row(x.getAs("colA")))
//Do other RDD operation on it

Saving the RDD to CSV format:

val aDf = sqlContext.createDataFrame(rddData,StructType(Array(StructField("colANew",StringType,true))))
aDF.write.format("com.databricks.spark.csv").option("header","true").save("/csvOutPath/aCSVOp")

Since the header is set to true we will be getting the header name in all the output files.

How to select rows with NaN in particular column?

@qbzenker provided the most idiomatic method IMO

Here are a few alternatives:

In [28]: df.query('Col2 != Col2') # Using the fact that: np.nan != np.nan
Out[28]:
   Col1  Col2  Col3
1     0   NaN   0.0

In [29]: df[np.isnan(df.Col2)]
Out[29]:
   Col1  Col2  Col3
1     0   NaN   0.0

ssl_error_rx_record_too_long and Apache SSL

My problem was due to a LOW MTU over a VPN connection.

netsh interface ipv4 show inter

Idx  Met   MTU   State        Name
---  ---  -----  -----------  -------------------
  1 4275 4294967295  connected    Loopback Pseudo-Interface 1
 10 4250   **1300**  connected    Wireless Network Connection
 31   25   1400  connected    Remote Access to XYZ Network

Fix: netsh interface ipv4 set interface "Wireless Network Connection" mtu=1400

It may be an issue over a non-VPN connection also...

How do I install Python 3 on an AWS EC2 instance?

If you do a

sudo yum list | grep python3

you will see that while they don't have a "python3" package, they do have a "python34" package, or a more recent release, such as "python36". Installing it is as easy as:

sudo yum install python34 python34-pip

Git workflow and rebase vs merge questions

I have one question after reading your explanation: Could it be that you never did a

git checkout master
git pull origin
git checkout my_new_feature

before doing the 'git rebase/merge master' in your feature branch?

Because your master branch won't update automatically from your friend's repository. You have to do that with the git pull origin. I.e. maybe you would always rebase from a never-changing local master branch? And then come push time, you are pushing in a repository which has (local) commits you never saw and thus the push fails.

How to set a time zone (or a Kind) of a DateTime value?

If you want to get advantage of your local machine timezone you can use myDateTime.ToUniversalTime() to get the UTC time from your local time or myDateTime.ToLocalTime() to convert the UTC time to the local machine's time.

// convert UTC time from the database to the machine's time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var localTime = databaseUtcTime.ToLocalTime();

// convert local time to UTC for database save
var databaseUtcTime = localTime.ToUniversalTime();

If you need to convert time from/to other timezones, you may use TimeZoneInfo.ConvertTime() or TimeZoneInfo.ConvertTimeFromUtc().

// convert UTC time from the database to japanese time
DateTime databaseUtcTime = new DateTime(2011,6,5,10,15,00);
var japaneseTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time");
var japaneseTime = TimeZoneInfo.ConvertTimeFromUtc(databaseUtcTime, japaneseTimeZone);

// convert japanese time to UTC for database save
var databaseUtcTime = TimeZoneInfo.ConvertTimeToUtc(japaneseTime, japaneseTimeZone);

List of available timezones

TimeZoneInfo class on MSDN

Is there any simple way to convert .xls file to .csv file? (Excel)

This is a modification of nate_weldon's answer with a few improvements:

  • More robust releasing of Excel objects
  • Set application.DisplayAlerts = false; before attempting to save to hide prompts

Also note that the application.Workbooks.Open and ws.SaveAs methods expect sourceFilePath and targetFilePath to be full paths (ie. directory path + filename)

private static void SaveAs(string sourceFilePath, string targetFilePath)
{
    Application application = null;
    Workbook wb = null;
    Worksheet ws = null;

    try
    {
        application = new Application();
        application.DisplayAlerts = false;
        wb = application.Workbooks.Open(sourceFilePath);
        ws = (Worksheet)wb.Sheets[1];
        ws.SaveAs(targetFilePath, XlFileFormat.xlCSV);
    }
    catch (Exception e)
    {
        // Handle exception
    }
    finally
    {
        if (application != null) application.Quit();
        if (ws != null) Marshal.ReleaseComObject(ws);
        if (wb != null) Marshal.ReleaseComObject(wb);
        if (application != null) Marshal.ReleaseComObject(application);
    }
}

Is there a way to get rid of accents and convert a whole string to regular letters?

As of 2011 you can use Apache Commons StringUtils.stripAccents(input) (since 3.0):

    String input = StringUtils.stripAccents("Thïs iš â funky Štring");
    System.out.println(input);
    // Prints "This is a funky String"

Note:

The accepted answer (Erick Robertson's) doesn't work for Ø or L. Apache Commons 3.5 doesn't work for Ø either, but it does work for L. After reading the Wikipedia article for Ø, I'm not sure it should be replaced with "O": it's a separate letter in Norwegian and Danish, alphabetized after "z". It's a good example of the limitations of the "strip accents" approach.

Where can I find the error logs of nginx, using FastCGI and Django?

You can use lsof (list of open files) in most cases to find open log files without knowing the configuration.

Example:

Find the PID of httpd (the same concept applies for nginx and other programs):

$ ps aux | grep httpd
...
root     17970  0.0  0.3 495964 64388 ?        Ssl  Oct29   3:45 /usr/sbin/httpd
...

Then search for open log files using lsof with the PID:

$ lsof -p 17970 | grep log
httpd   17970 root    2w   REG             253,15     2278      6723 /var/log/httpd/error_log
httpd   17970 root   12w   REG             253,15        0      1387 /var/log/httpd/access_log

If lsof prints nothing, even though you expected the log files to be found, issue the same command using sudo.

You can read a little more here.

Show or hide element in React

React circa 2020

In the onClick callback, call the state hook's setter function to update the state and re-render:

_x000D_
_x000D_
const Search = () => {_x000D_
  const [showResults, setShowResults] = React.useState(false)_x000D_
  const onClick = () => setShowResults(true)_x000D_
  return (_x000D_
    <div>_x000D_
      <input type="submit" value="Search" onClick={onClick} />_x000D_
      { showResults ? <Results /> : null }_x000D_
    </div>_x000D_
  )_x000D_
}_x000D_
_x000D_
const Results = () => (_x000D_
  <div id="results" className="search-results">_x000D_
    Some Results_x000D_
  </div>_x000D_
)_x000D_
_x000D_
ReactDOM.render(<Search />, document.querySelector("#container"))
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.13.1/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.13.1/umd/react-dom.production.min.js"></script>_x000D_
_x000D_
<div id="container">_x000D_
  <!-- This element's contents will be replaced with your component. -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle

React circa 2014

The key is to update the state of the component in the click handler using setState. When the state changes get applied, the render method gets called again with the new state:

_x000D_
_x000D_
var Search = React.createClass({_x000D_
    getInitialState: function() {_x000D_
        return { showResults: false };_x000D_
    },_x000D_
    onClick: function() {_x000D_
        this.setState({ showResults: true });_x000D_
    },_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div>_x000D_
                <input type="submit" value="Search" onClick={this.onClick} />_x000D_
                { this.state.showResults ? <Results /> : null }_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
var Results = React.createClass({_x000D_
    render: function() {_x000D_
        return (_x000D_
            <div id="results" className="search-results">_x000D_
                Some Results_x000D_
            </div>_x000D_
        );_x000D_
    }_x000D_
});_x000D_
_x000D_
ReactDOM.render( <Search /> , document.getElementById('container'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.2/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/15.6.2/react-dom.min.js"></script>_x000D_
_x000D_
<div id="container">_x000D_
  <!-- This element's contents will be replaced with your component. -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

JSFiddle

Pass a reference to DOM object with ng-click

The angular way is shown in the angular docs :)

https://docs.angularjs.org/api/ng/directive/ngReadonly

Here is the example they use:

<body>
    Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
    <input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>

Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).

So basically in your case you would want to do something like below or check out this working example.

<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>

"unadd" a file to svn before commit

Try svn revert filename for every file you don't need and haven't yet committed. Or alternatively do svn revert -R folder for the problematic folder and then re-do the operation with correct ignoring configuration.

From the documentation:

 you can undo any scheduling operations:

$ svn add mistake.txt whoops
A         mistake.txt
A         whoops
A         whoops/oopsie.c

$ svn revert mistake.txt whoops
Reverted mistake.txt
Reverted whoops

Python Pylab scatter plot error bars (the error on each point is unique)

>>> import matplotlib.pyplot as plt
>>> a = [1,3,5,7]
>>> b = [11,-2,4,19]
>>> plt.pyplot.scatter(a,b)
>>> plt.scatter(a,b)
<matplotlib.collections.PathCollection object at 0x00000000057E2CF8>
>>> plt.show()
>>> c = [1,3,2,1]
>>> plt.errorbar(a,b,yerr=c, linestyle="None")
<Container object of 3 artists>
>>> plt.show()

where a is your x data b is your y data c is your y error if any

note that c is the error in each direction already

Access multiple viewchildren using @viewchild

Use @ViewChildren from @angular/core to get a reference to the components

template

<div *ngFor="let v of views">
    <customcomponent #cmp></customcomponent>
</div>

component

import { ViewChildren, QueryList } from '@angular/core';

/** Get handle on cmp tags in the template */
@ViewChildren('cmp') components:QueryList<CustomComponent>;

ngAfterViewInit(){
    // print array of CustomComponent objects
    console.log(this.components.toArray());
}

l?i?v?e? ?d?e?m?o?

Remove local git tags that are no longer on the remote repository

this is a good method:

git tag -l | xargs git tag -d && git fetch -t

Source: demisx.GitHub.io

How can I create a carriage return in my C# string

Along with Environment.NewLine and the literal \r\n or just \n you may also use a verbatim string in C#. These begin with @ and can have embedded newlines. The only thing to keep in mind is that " needs to be escaped as "". An example:

string s = @"This is a string
that contains embedded new lines,
that will appear when this string is used."

Reading a List from properties file and load with spring annotation @Value

Consider using Commons Configuration. It have built in feature to break an entry in properties file to array/list. Combing with SpEL and @Value should give what you want


As requested, here is what you need (Haven't really tried the code, may got some typoes, please bear with me):

In Apache Commons Configuration, there is PropertiesConfiguration. It supports the feature of converting delimited string to array/list.

For example, if you have a properties file

#Foo.properties
foo=bar1, bar2, bar3

With the below code:

PropertiesConfiguration config = new PropertiesConfiguration("Foo.properties");
String[] values = config.getStringArray("foo");

will give you a string array of ["bar1", "bar2", "bar3"]

To use with Spring, have this in your app context xml:

<bean id="fooConfig" class="org.apache.commons.configuration.PropertiesConfiguration">
    <constructor-arg type="java.lang.String" value="classpath:/Foo.properties"/>
</bean>

and have this in your spring bean:

public class SomeBean {

    @Value("fooConfig.getStringArray('foo')")
    private String[] fooArray;
}

I believe this should work :P

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

FYI, in case you need to add attributes to your dictionary (things that are attached to the dictionary, but are not one of the keys), then you'll need the second form. In that case, you can initialize your dictionary with keys having arbitrary characters, one at a time, like so:

    class mydict(dict): pass
    a = mydict()        
    a["b=c"] = 'value'
    a.test = False

Find something in column A then show the value of B for that row in Excel 2010

I figured out such data design:

Main sheet: Column A: Pump codes (numbers)

Column B: formula showing a corresponding row in sheet 'Ruhrpumpen'

=ROW(Pump_codes)+MATCH(A2;Ruhrpumpen!$I$5:$I$100;0)

Formulae have ";" instead of ",", it should be also German notation. If not, pleace replace.

Column C: formula showing data in 'Ruhrpumpen' column A from a row found by formula in col B

=INDIRECT("Ruhrpumpen!A"&$B2)

Column D: formula showing data in 'Ruhrpumpen' column B from a row found by formula in col B:

=INDIRECT("Ruhrpumpen!B"&$B2)

Sheet 'Ruhrpumpen':

Column A: some data about a certain pump

Column B: some more data

Column I: pump codes. Beginning of the list includes defined name 'Pump_codes' used by the formula in column B of the main sheet.

Spreadsheet example: http://www.bumpclub.ee/~jyri_r/Excel/Data_from_other_sheet_by_code_row.xls

How to fix "ImportError: No module named ..." error in Python?

Example solution for adding the library to your PYTHONPATH.

  1. Add the following line into your ~/.bashrc or just run it directly:

    export PYTHONPATH="$PYTHONPATH:$HOME/.python"
    
  2. Then link your required library into your ~/.python folder, e.g.

    ln -s /home/user/work/project/foo ~/.python/
    

Telegram Bot - how to get a group chat id?

create a bot, or if already created set as follows:

has access to messages

apparently, regardless of how old/new the Telegram group is:

  1. add a bot to the group

  2. remove bot from the group

  3. add bot again to the group

  4. create a script file and run getUpdates method example:

    var vApiTokenTelegram = "1234567890:???>yg5GeL5PuItAOEhvdcPPELAOCCy3jBo"; // @?????Bot API token
    var vUrlTelegram = "https://api.telegram.org/bot" + vApiTokenTelegram;

    function getUpdates() {
        var response = UrlFetchApp.fetch(vUrlTelegram + "/getUpdates");
        console.log(response.getContentText());
    }
  1. function shall log to the console the following:
[20-04-21 00:46:11:130 PDT] {"ok":true,"result":[{"update_id":81329501,
"message":{"message_id":975,"from":{"id":962548471,"is_bot":false,"first_name":"Trajano","last_name":"Roberto","username":"TrajanoRoberto","language_code":"en"},"chat":{"id":-1001202656383,"title":"R\u00e1dioRN - A voz da na\u00e7\u00e3o!","type":"supergroup"},"date":1587454914,"left_chat_participant":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"left_chat_member":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"}}},{"update_id":81329502,
"message":{"message_id":976,"from":{"id":962548471,"is_bot":false,"first_name":"Trajano","last_name":"Roberto","username":"TrajanoRoberto","language_code":"en"},"chat":{"id":-1001202656383,"title":"R\u00e1dioRN - A voz da na\u00e7\u00e3o!","type":"supergroup"},"date":1587454932,"new_chat_participant":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"new_chat_member":{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"},"new_chat_members":[{"id":1215098445,"is_bot":true,"first_name":"MediaFlamengoRawBot","username":"MediaFlamengoRawBot"}]}}]}
  1. Telegram group chat_id can be extracted from above message "chat":{"id":-1001202656383,"title"

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

POST data to a URL in PHP

cURL-less you can use in php5

$url = 'URL';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
        'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

how to run python files in windows command prompt?

You have to install Python and add it to PATH on Windows. After that you can try:

python `C:/pathToFolder/prog.py`

or go to the files directory and execute:

python prog.py

CMD what does /im (taskkill)?

im is "image process name" example /f /im notepad.exe is specified to kill image process name (program) notepad.exe

javascript close current window

To close your current window using JS, do this. First open the current window to trick your current tab into thinking it has been opened by a script. Then close it using window.close(). The below script should go into the parent window, not the child window. You could run this after running the script to open the child.

<script type="text/javascript">
    window.open('','_parent',''); 
    window.close();
</script>

If conditions in a Makefile, inside a target

You can simply use shell commands. If you want to suppress echoing the output, use the "@" sign. For example:

clean:
    @if [ "test" = "test" ]; then\
        echo "Hello world";\
    fi

Note that the closing ";" and "\" are necessary.

Python string prints as [u'String']

Maybe i dont understand , why cant you just get the element.text and then convert it before using it ? for instance (dont know why you would do this but...) find all label elements of the web page and iterate between them until you find one called MyText

        avail = []
        avail = driver.find_elements_by_class_name("label");
        for i in avail:
                if  i.text == "MyText":

Convert the string from i and do whatever you wanted to do ... maybe im missing something in the original message ? or was this what you were looking for ?

java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/dbname

try this

String url = "jdbc:mysql://localhost:3306/<dbname>";
String user = "<username>";
String password = "<password>";
conn = DriverManager.getConnection(url, user, password); 

How to automatically import data from uploaded CSV or XLS file into Google Sheets

In case anyone would be searching - I created utility for automated import of xlsx files into google spreadsheet: xls2sheets. One can do it automatically via setting up the cronjob for ./cmd/sheets-refresh, readme describes it all. Hope that would be of use.

Abstraction vs Encapsulation in Java

Abstraction is about identifying commonalities and reducing features that you have to work with at different levels of your code.

e.g. I may have a Vehicle class. A Car would derive from a Vehicle, as would a Motorbike. I can ask each Vehicle for the number of wheels, passengers etc. and that info has been abstracted and identified as common from Cars and Motorbikes.

In my code I can often just deal with Vehicles via common methods go(), stop() etc. When I add a new Vehicle type later (e.g. Scooter) the majority of my code would remain oblivious to this fact, and the implementation of Scooter alone worries about Scooter particularities.

Haversine Formula in Python (Bearing and Distance between two GPS points)

You can try the following:

from haversine import haversine
haversine((45.7597, 4.8422),(48.8567, 2.3508), unit='mi')
243.71209416020253

Hive: how to show all partitions of a table?

Okay, I'm writing this answer by extending wmky's answer above & also, assuming that you've configured mysql for your metastore instead of derby.

select PART_NAME FROM PARTITIONS WHERE TBL_ID=(SELECT TBL_ID FROM TBLS WHERE TBL_NAME='<table_name>');

The above query gives you all possible values of the partition columns.

Example:

hive> desc clicks_fact;
OK
time                    timestamp                                   
..                              
day                     date                                        
file_date               varchar(8)                                  

# Partition Information      
# col_name              data_type               comment             

day                     date                                        
file_date               varchar(8)                                  
Time taken: 1.075 seconds, Fetched: 28 row(s)

I'm going to fetch the values of partition columns.

mysql> select PART_NAME FROM PARTITIONS WHERE TBL_ID=(SELECT TBL_ID FROM TBLS WHERE TBL_NAME='clicks_fact');
+-----------------------------------+
| PART_NAME                         |
+-----------------------------------+
| day=2016-08-16/file_date=20160816 |
| day=2016-08-17/file_date=20160816 |
....
....
| day=2017-09-09/file_date=20170909 |
| day=2017-09-08/file_date=20170909 |
| day=2017-09-09/file_date=20170910 |
| day=2017-09-10/file_date=20170910 |
+-----------------------------------+

1216 rows in set (0.00 sec)

Returns all partition columns.

Note: JOIN table DBS ON DB_ID when there is a DB involved (i.e, when, multiple DB's have same table_name)

Checking for an empty field with MySQL

Yes, what you are doing is correct. You are checking to make sure the email field is not an empty string. NULL means the data is missing. An empty string "" is a blank string with the length of 0.

You can add the null check also

AND (email != "" OR email IS NOT NULL)

How can I change Mac OS's default Java VM returned from /usr/libexec/java_home

It's pretty simple, if you don't mind rolling up your sleeves... /Library/Java/Home is the default for JAVA_HOME, and it's just a link that points to one of:

  • /System/Library/Java/JavaVirtualMachines/1.?.?.jdk/Contents/Home
  • /Library/Java/JavaVirtualMachines/jdk1.?.?_??.jdk/Contents/Home

So I wanted to change my default JVM/JDK version without changing the contents of JAVA_HOME... /Library/Java/Home is the standard location for the current JVM/JDK and that's what I wanted to preserve... it seems to me to be the easiest way to change things with the least side effects.

It's actually really simple. In order to change which version of java you see with java -version, all you have to do is some version of this:

cd /Library/Java
sudo rm Home
sudo ln -s /Library/Java/JavaVirtualMachines/jdk1.8.0_60.jdk/Contents/Home ./Home

I haven't taken the time but a very simple shell script that makes use of /usr/libexec/java_home and ln to repoint the above symlink should be stupid easy to create...

Once you've changed where /Library/Java/Home is pointed... you get the correct result:

cerebro:~ magneto$ java -version
java version "1.8.0_60"
Java(TM) SE Runtime Environment (build 1.8.0_60-b27) Java HotSpot(TM)
64-Bit Server VM (build 25.60-b23, mixed mode)

Catch paste input

For cross platform compatibility, it should handle oninput and onpropertychange events:

$ (something).bind ("input propertychange", function (e) {
    // check for paste as in example above and
    // do something
})

Changing variable names with Python for loops

Definitely should use a dict using the "group" + str(i) key as described in the accepted solution but I wanted to share a solution using exec. Its a way to parse strings into commands & execute them dynamically. It would allow to create these scalar variable names as per your requirement instead of using a dict. This might help in regards what not to do, and just because you can doesn't mean you should. Its a good solution only if using scalar variables is a hard requirement:

l = locals()
for i in xrange(3):
    exec("group" + str(i) + "= self.getGroup(selected, header + i)")

Another example where this could work using a Django model example. The exec alternative solution is commented out and the better way of handling such a case using the dict attribute makes more sense:

Class A(models.Model):

    ....

    def __getitem__(self, item):  # a.__getitem__('id')
        #exec("attrb = self." + item)
        #return attrb
        return self.__dict__[item]

It might make more sense to extend from a dictionary in the first place to get setattr and getattr functions.

A situation which involves parsing, for example generating & executing python commands dynamically, exec is what you want :) More on exec here.

C/C++ check if one bit is set in, i.e. int variable

fast and best macro

#define get_bit_status()    ( YOUR_VAR  &   ( 1 << BITX ) )

.
.

if (get_rx_pin_status() == ( 1 << BITX ))
{
    do();
}

no module named zlib

My objective was to create a new Django project from the command line in Ubuntu, like so:

django-admin.py startproject mysite

I have python2.7.5 installed. I got this error:

ImportError: No module named zlib

For hours I could not find a solution, until now!

Here is a link to the solution -

http://doc.biblissima-condorcet.fr/loris-setup-guide-ubuntu-debian

I followed and executed instruction in Section 1.1 and it is working perfectly! It is an easy solution.

Set Date in a single line

tl;dr

LocalDate.of( 2015 , Month.JUNE , 7 )  // Using handy `Month` enum. 

…or…

LocalDate.of( 2015 , 6 , 7 )  // Sensible numbering, 1-12 for January to December. 

java.time

The java.time framework built into Java 8 and later supplants the troublesome old classes, java.util.Date/.Calendar.

The java.time classes use immutable objects. So they are inherently thread-safe. You will have none of the thread-safety problems mentioned on the other answers.

LocalDate

This framework included a class for date-only objects without any time-of-day or time zone, LocalDate. Note that a time zone (ZoneId) is necessary to determine a date.

LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );

You can instantiate for a specific date. Note that month number is a sensible range of 1-12 unlike the old classes.

LocalDate localDate = LocalDate.of( 2015 , 6 , 7 );

Or use the enum, Month.

LocalDate localDate = LocalDate.of( 2015 , Month.JUNE , 7 );

Convert

Best to avoid the old date-time classes. But if you must, you can convert. Call new methods added to the old classes to facilitate conversions.

In this case we need to specify a time-of-day to go along with our date-only value, to be combined for a java.util.Date object. First moment of the day likely makes sense. Let java.time determine the time of that first moment as it is not always 00:00:00.0.

We also need to specify a time zone, as the date varies by time zone.

ZoneId zoneId = zoneId.of( "America/Montreal" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );

An Instant is a basic class in java.time, representing a moment on the timeline in UTC. Feed an Instant to static method on Date to convert.

Instant instant = zdt.toInstant();
java.util.Date utilDate = java.util.Date.from( instant );

About java.time

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

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

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

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

Where to obtain the java.time classes?

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

C# HttpClient 4.5 multipart/form-data upload

This is an example of how to post string and file stream with HTTPClient using MultipartFormDataContent. The Content-Disposition and Content-Type need to be specified for each HTTPContent:

Here's my example. Hope it helps:

private static void Upload()
{
    using (var client = new HttpClient())
    {
        client.DefaultRequestHeaders.Add("User-Agent", "CBS Brightcove API Service");

        using (var content = new MultipartFormDataContent())
        {
            var path = @"C:\B2BAssetRoot\files\596086\596086.1.mp4";

            string assetName = Path.GetFileName(path);

            var request = new HTTPBrightCoveRequest()
                {
                    Method = "create_video",
                    Parameters = new Params()
                        {
                            CreateMultipleRenditions = "true",
                            EncodeTo = EncodeTo.Mp4.ToString().ToUpper(),
                            Token = "x8sLalfXacgn-4CzhTBm7uaCxVAPjvKqTf1oXpwLVYYoCkejZUsYtg..",
                            Video = new Video()
                                {
                                    Name = assetName,
                                    ReferenceId = Guid.NewGuid().ToString(),
                                    ShortDescription = assetName
                                }
                        }
                };

            //Content-Disposition: form-data; name="json"
            var stringContent = new StringContent(JsonConvert.SerializeObject(request));
            stringContent.Headers.Add("Content-Disposition", "form-data; name=\"json\"");
            content.Add(stringContent, "json");

            FileStream fs = File.OpenRead(path);

            var streamContent = new StreamContent(fs);
            streamContent.Headers.Add("Content-Type", "application/octet-stream");
            //Content-Disposition: form-data; name="file"; filename="C:\B2BAssetRoot\files\596090\596090.1.mp4";
            streamContent.Headers.Add("Content-Disposition", "form-data; name=\"file\"; filename=\"" + Path.GetFileName(path) + "\"");
            content.Add(streamContent, "file", Path.GetFileName(path));

            //content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");

            Task<HttpResponseMessage> message = client.PostAsync("http://api.brightcove.com/services/post", content);

            var input = message.Result.Content.ReadAsStringAsync();
            Console.WriteLine(input.Result);
            Console.Read();
        }
    }
}

How to get the number of characters in a string

If you need to take grapheme clusters into account, use regexp or unicode module. Counting the number of code points(runes) or bytes also is needed for validaiton since the length of grapheme cluster is unlimited. If you want to eliminate extremely long sequences, check if the sequences conform to stream-safe text format.

package main

import (
    "regexp"
    "unicode"
    "strings"
)

func main() {

    str := "\u0308" + "a\u0308" + "o\u0308" + "u\u0308"
    str2 := "a" + strings.Repeat("\u0308", 1000)

    println(4 == GraphemeCountInString(str))
    println(4 == GraphemeCountInString2(str))

    println(1 == GraphemeCountInString(str2))
    println(1 == GraphemeCountInString2(str2))

    println(true == IsStreamSafeString(str))
    println(false == IsStreamSafeString(str2))
}


func GraphemeCountInString(str string) int {
    re := regexp.MustCompile("\\PM\\pM*|.")
    return len(re.FindAllString(str, -1))
}

func GraphemeCountInString2(str string) int {

    length := 0
    checked := false
    index := 0

    for _, c := range str {

        if !unicode.Is(unicode.M, c) {
            length++

            if checked == false {
                checked = true
            }

        } else if checked == false {
            length++
        }

        index++
    }

    return length
}

func IsStreamSafeString(str string) bool {
    re := regexp.MustCompile("\\PM\\pM{30,}") 
    return !re.MatchString(str) 
}

Android turn On/Off WiFi HotSpot programmatically

For Android 8.0, there is a new API to handle Hotspots. As far as I know, the old way using reflection doesn't work anymore. Please refer to:

Android Developers https://developer.android.com/reference/android/net/wifi/WifiManager.html#startLocalOnlyHotspot(android.net.wifi.WifiManager.LocalOnlyHotspotCallback,%20android.os.Handler)

void startLocalOnlyHotspot (WifiManager.LocalOnlyHotspotCallback callback, 
                Handler handler)

Request a local only hotspot that an application can use to communicate between co-located devices connected to the created WiFi hotspot. The network created by this method will not have Internet access.

Stack Overflow
How to turn on/off wifi hotspot programmatically in Android 8.0 (Oreo)

onStarted(WifiManager.LocalOnlyHotspotReservation reservation) method will be called if hotspot is turned on.. Using WifiManager.LocalOnlyHotspotReservation reference you call close() method to turn off hotspot.

How can I make visible an invisible control with jquery? (hide and show not work)

You can't do this with jQuery, visible="false" in asp.net means the control isn't rendered into the page. If you want the control to go to the client, you need to do style="display: none;" so it's actually in the HTML, otherwise there's literally nothing for the client to show, since the element wasn't in the HTML your server sent.

If you remove the visible attribute and add the style attribute you can then use jQuery to show it, like this:

$("#elementID").show();

Old Answer (before patrick's catch)

To change visibility, you need to use .css(), like this:

$("#elem").css('visibility', 'visible');

Unless you need to have the element occupy page space though, use display: none; instead of visibility: hidden; in your CSS, then just do:

$("#elem").show();

The .show() and .hide() functions deal with display instead of visibility, like most of the jQuery functions :)

AngularJs directive not updating another directive's scope

Just wondering why you are using 2 directives?

It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.

Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).

It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.

Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.

How to add a color overlay to a background image?

background-image takes multiple values.

so a combination of just 1 color linear-gradient and css blend modes will do the trick.

.testclass {
    background-image: url("../images/image.jpg"), linear-gradient(rgba(0,0,0,0.5),rgba(0,0,0,0.5));
    background-blend-mode: overlay;
}

note that there is no support on IE/Edge for CSS blend-modes at all.

Jenkins fails when running "service start jenkins"

You just need to install Java. It did work after installing Java version 8, using this command : sudo apt install openjdk-8-jre-headless

PHP parse/syntax errors; and how to solve them

Unexpected [

These days, the unexpected [ array bracket is commonly seen on outdated PHP versions. The short array syntax is available since PHP >= 5.4. Older installations only support array().

$php53 = array(1, 2, 3);
$php54 = [1, 2, 3];
         ?

Array function result dereferencing is likewise not available for older PHP versions:

$result = get_whatever()["key"];
                      ?

Reference - What does this error mean in PHP? - "Syntax error, unexpected \[" shows the most common and practical workarounds.

Though, you're always better off just upgrading your PHP installation. For shared webhosting plans, first research if e.g. SetHandler php56-fcgi can be used to enable a newer runtime.

See also:

BTW, there are also preprocessors and PHP 5.4 syntax down-converters if you're really clingy with older + slower PHP versions.

Other causes for Unexpected [ syntax errors

If it's not the PHP version mismatch, then it's oftentimes a plain typo or newcomer syntax mistake:

  • You can't use array property declarations/expressions in classes, not even in PHP 7.

    protected $var["x"] = "Nope";
                  ?
    
  • Confusing [ with opening curly braces { or parentheses ( is a common oversight.

    foreach [$a as $b)
            ?
    

    Or even:

    function foobar[$a, $b, $c] {
                   ?
    
  • Or trying to dereference constants (before PHP 5.6) as arrays:

    $var = const[123];
           ?
    

    At least PHP interprets that const as a constant name.

    If you meant to access an array variable (which is the typical cause here), then add the leading $ sigil - so it becomes a $varname.

  • You are trying to use the global keyword on a member of an associative array. This is not valid syntax:

    global $var['key'];
    


Unexpected ] closing square bracket

This is somewhat rarer, but there are also syntax accidents with the terminating array ] bracket.

  • Again mismatches with ) parentheses or } curly braces are common:

    function foobar($a, $b, $c] {
                              ?
    
  • Or trying to end an array where there isn't one:

    $var = 2];
    

    Which often occurs in multi-line and nested array declarations.

    $array = [1,[2,3],4,[5,6[7,[8],[9,10]],11],12]],15];
                                                 ?
    

    If so, use your IDE for bracket matching to find any premature ] array closure. At the very least use more spacing and newlines to narrow it down.

MySQL > Table doesn't exist. But it does (or it should)

I had this problem after upgrading WAMP but having no database backup.

This worked for me:

  1. Stop new WAMP

  2. Copy over database directories you need and ibdata1 file from old WAMP installation

  3. Delete ib_logfile0 and ib_logfile1

  4. Start WAMP

You should now be able to make backups of your databases. However after your server restarts again you will still have problems. So now reinstall WAMP and import your databases.

How to remove "Server name" items from history of SQL Server Management Studio

For Windows Vista and SQL Server 2005,

Delete this file, or open it with the Notepad and clear the server names that you want Clear from the history

%UserProfile%\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat

MySQL set current date in a DATETIME field on insert

Using Now() is not a good idea. It only save the current time and date. It will not update the the current date and time, when you update your data. If you want to add the time once, The default value =Now() is best option. If you want to use timestamp. and want to update the this value, each time that row is updated. Then, trigger is best option to use.

  1. http://www.mysqltutorial.org/sql-triggers.aspx
  2. http://www.tutorialspoint.com/plsql/plsql_triggers.htm

These two toturial will help to implement the trigger.

How to execute a command prompt command from python

Try adding a call to proc.stdin.flush() after writing to the pipe and see if things start behaving more as you expect. Explicitly flushing the pipe means you don't need to worry about exactly how the buffering is set up.

Also, don't forget to include a "\n" at the end of your command or your child shell will sit there at the prompt waiting for completion of the command entry.

I wrote about using Popen to manipulate an external shell instance in more detail at: Running three commands in the same process with Python

As was the case in that question, this trick can be valuable if you need to maintain shell state across multiple out-of-process invocations on a Windows machine.

What is the difference between functional and non-functional requirements?

functional requirements are the main things that the user expects from the software for example if the application is a banking application that application should be able to create a new account, update the account, delete an account, etc. functional requirements are detailed and are specified in the system design

Non-functional requirement are not straight forward the requirement of the system rather it is related to usability( in some way ) for example for a banking application a major non-functional requirement will be available the application should be available 24/7 with no downtime if possible.

Command to get latest Git commit hash from a branch

In a comment you wrote

i want to show that there is a difference in local and github repo

As already mentioned in another answer, you should do a git fetch origin first. Then, if the remote is ahead of your current branch, you can list all commits between your local branch and the remote with

git log master..origin/master --stat

If your local branch is ahead:

git log origin/master..master --stat

--stat shows a list of changed files as well.

If you want to explicitly list the additions and deletions, use git diff:

git diff master origin/master

(How) can I count the items in an enum?

I really do not see any way to really get to the number of values in an enumeration in C++. Any of the before mention solution work as long as you do not define the value of your enumerations if you define you value that you might run into situations where you either create arrays too big or too small

enum example{ test1 = -2, test2 = -1, test3 = 0, test4 = 1, test5 = 2 }

in this about examples the result would create a array of 3 items when you need an array of 5 items

enum example2{ test1 , test2 , test3 , test4 , test5 = 301 }

in this about examples the result would create a array of 301 items when you need an array of 5 items

The best way to solve this problem in the general case would be to iterate through your enumerations but that is not in the standard yet as far as I know

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

Create an array of strings

Another solution to this old question is the new container string array, introduced in Matlab 2016b. From what I read in the official Matlab docs, this container resembles a cell-array and most of the array-related functions should work out of the box. For your case, new solution would be:

a=repmat('Some text', 10, 1);

This solution resembles a Rich C's solution applied to string array.

Make DateTimePicker work as TimePicker only in WinForms

You want to set its 'Format' property to be time and add a spin button control to it:

yourDateTimeControl.Format = DateTimePickerFormat.Time;
yourDateTimeControl.ShowUpDown = true;

How to remove title bar from the android activity?

In your Android Manifest file make sure that the activity is using this (or a) theme (that is based on) @style/Theme.AppCompat.NoActionBar This removes the ActionBar completely, but won't make your activity fullscreen. If you want to make your activity fullscreen only use this theme

@android:style/Theme.NoTitleBar.Fullscreen

Or you could change

this.requestWindowFeature(Window.FEATURE_NO_TITLE);

to

requestWindowFeature(Window.FEATURE_NO_TITLE);
 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);

This is what I use to get fullscreen at runtime

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                mDecorView = getWindow().getDecorView();
                mDecorView.setSystemUiVisibility(
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                                | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                                | View.SYSTEM_UI_FLAG_IMMERSIVE);
            }

To exit fullscreen I use this

mDecorView = getWindow().getDecorView();
mDecorView.setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);

How to check if a file is empty in Bash?

@geedoubleya answer is my favorite.

However, I do prefer this

if [[ -f diff.txt && -s diff.txt ]]
then
  rm -f empty.txt
  touch full.txt
elif [[ -f diff.txt && ! -s diff.txt ]]
then
  rm -f full.txt
  touch empty.txt
else
  echo "File diff.txt does not exist"
fi

Bootstrap Alert Auto Close

C# Controller:

var result = await _roleManager.CreateAsync(identityRole);
   if (result.Succeeded == true)
       TempData["roleCreateAlert"] = "Added record successfully";

Razor Page:

@if (TempData["roleCreateAlert"] != null)
{
    <div class="alert alert-success">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
        <p>@TempData["roleCreateAlert"]</p>
    </div>
}

Any Alert Auto Close:

<script type="text/javascript">
    $(".alert").delay(5000).slideUp(200, function () {
        $(this).alert('close');
    });
</script>

Git command to checkout any branch and overwrite local changes

Couple of points:

  • I believe git stash + git stash drop could be replaced with git reset --hard
  • ... or, even shorter, add -f to checkout command:

    git checkout -f -b $branch
    

    That will discard any local changes, just as if git reset --hard was used prior to checkout.

As for the main question: instead of pulling in the last step, you could just merge the appropriate branch from the remote into your local branch: git merge $branch origin/$branch, I believe it does not hit the remote. If that is the case, it removes the need for credensials and hence, addresses your biggest concern.

clear table jquery

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

Add alternating row color to SQL Server Reporting services report

I tried all these solutions on a Grouped Tablix with row spaces and none worked across the entire report. The result was duplicate colored rows and other solutions resulted in alternating columns!

Here is the function I wrote that worked for me using a Column Count:

Private bOddRow As Boolean
Private cellCount as Integer

Function AlternateColorByColumnCount(ByVal OddColor As String, ByVal EvenColor As String, ByVal ColCount As Integer) As String

if cellCount = ColCount Then 
bOddRow = Not bOddRow
cellCount = 0
End if 

cellCount  = cellCount  + 1

if bOddRow Then
 Return OddColor
Else
 Return EvenColor
End If

End Function

For a 7 Column Tablix I use this expression for Row (of Cells) Backcolour:

=Code.AlternateColorByColumnCount("LightGrey","White", 7)

Declaration of Methods should be Compatible with Parent Methods in PHP

I faced this problem while trying to extend an existing class from GitHub. I'm gonna try to explain myself, first writing the class as I though it should be, and then the class as it is now.

What I though

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

What I've finally done

namespace mycompany\CutreApi;

use \vendor\AwesomeApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function whatever(): ClassOfVendor
   {
        return new \mycompany\CutreApi\ClassOfVendor();
   }
}

So seems that this errror raises also when you're using a method that return a namespaced class, and you try to return the same class but with other namespace. Fortunately I have found this solution, but I do not fully understand the benefit of this feature in php 7.2, for me it is normal to rewrite existing class methods as you need them, including the redefinition of input parameters and / or even behavior of the method.

One downside of the previous aproach, is that IDE's could not recognise the new methods implemented in \mycompany\CutreApi\ClassOfVendor(). So, for now, I will go with this implementation.

Currently done

namespace mycompany\CutreApi;

use mycompany\CutreApi\ClassOfVendor;

class CutreApi extends \vendor\AwesomeApi\AwesomeApi
{
   public function getWhatever(): ClassOfVendor
   {
        return new ClassOfVendor();
   }
}

So, instead of trying to use "whatever" method, I wrote a new one called "getWhatever". In fact both of them are doing the same, just returning a class, but with diferents namespaces as I've described before.

Hope this can help someone.

MVC If statement in View

You only need to prefix an if statement with @ if you're not already inside a razor code block.

Edit: You have a couple of things wrong with your code right now.

You're declaring nmb, but never actually doing anything with the value. So you need figure out what that's supposed to actually be doing. In order to fix your code, you need to make a couple of tiny changes:

@if (ViewBag.Articles != null)
{
    int nmb = 0;
    foreach (var item in ViewBag.Articles)
    {
        if (nmb % 3 == 0)
        {
            @:<div class="row"> 
        }

        <a href="@Url.Action("Article", "Programming", new { id = item.id })">
            <div class="tasks">
                <div class="col-md-4">
                    <div class="task important">
                        <h4>@item.Title</h4>
                        <div class="tmeta">
                            <i class="icon-calendar"></i>
                                @item.DateAdded - Pregleda:@item.Click
                            <i class="icon-pushpin"></i> Authorrr
                        </div>
                    </div>
                </div>
            </div>
        </a>
        if (nmb % 3 == 0)
        {
            @:</div>
        }
    }
}

The important part here is the @:. It's a short-hand of <text></text>, which is used to force the razor engine to render text.

One other thing, the HTML standard specifies that a tags can only contain inline elements, and right now, you're putting a div, which is a block-level element, inside an a.

Why shouldn't I use PyPy over CPython if PyPy is 6.3 times faster?

To make this simple: PyPy provides the speed that's lacked by CPython but sacrifices its compatibility. Most people, however, choose Python for its flexibility and its "battery-included" feature (high compatibility), not for its speed (it's still preferred though).

Save PHP variables to a text file

Okay, so I needed a solution to this, and I borrowed heavily from the answers to this question and made a library: https://github.com/rahuldottech/varDx (Licensed under the MIT license).

It uses serialize() and unserialize() and writes data to a file. It can read and write multiple objects/variables/whatever to and from the same file.

Usage:

<?php
require 'varDx.php';
$dx = new \varDx\cDX; //create an object
$dx->def('file.dat'); //define data file
$val1 = "this is a string";
$dx->write('data1', $val1); //writes key to file
echo $dx->read('data1'); //returns key value from file

See the github page for more information. It has functions to read, write, check, modify and delete data.

How to convert XML to java.util.Map and vice versa

I used the approach with the custom converter:

public static class MapEntryConverter implements Converter {

    public boolean canConvert(Class clazz) {
        return AbstractMap.class.isAssignableFrom(clazz);
    }

    public void marshal(Object value, HierarchicalStreamWriter writer, MarshallingContext context) {

        AbstractMap map = (AbstractMap) value;
        for (Object obj : map.entrySet()) {
            Entry entry = (Entry) obj;
            writer.startNode(entry.getKey().toString());
            context.convertAnother(entry.getValue());
            writer.endNode();
        }
    }

    public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
        // dunno, read manual and do it yourself ;)
    }

}

But i changed the the serialization of the maps value to delegate to the MarshallingContext. This should improve the solution to work for composite map values and nested maps as well.

Making custom right-click context menus for my web-app

I know this question is very old, but just came up with the same problem and solved it myself, so I'm answering in case anyone finds this through google as I did. I based my solution on @Andrew's one, but basically modified everything afterwards.

EDIT: seeing how popular this has been lately, I decided to update also the styles to make it look more like 2014 and less like windows 95. I fixed the bugs @Quantico and @Trengot spotted so now it's a more solid answer.

EDIT 2: I set it up with StackSnippets as they're a really cool new feature. I leave the good jsfiddle here for reference thought (click on the 4th panel to see them work).

New Stack Snippet:

_x000D_
_x000D_
// JAVASCRIPT (jQuery)_x000D_
_x000D_
// Trigger action when the contexmenu is about to be shown_x000D_
$(document).bind("contextmenu", function (event) {_x000D_
    _x000D_
    // Avoid the real one_x000D_
    event.preventDefault();_x000D_
    _x000D_
    // Show contextmenu_x000D_
    $(".custom-menu").finish().toggle(100)._x000D_
    _x000D_
    // In the right position (the mouse)_x000D_
    css({_x000D_
        top: event.pageY + "px",_x000D_
        left: event.pageX + "px"_x000D_
    });_x000D_
});_x000D_
_x000D_
_x000D_
// If the document is clicked somewhere_x000D_
$(document).bind("mousedown", function (e) {_x000D_
    _x000D_
    // If the clicked element is not the menu_x000D_
    if (!$(e.target).parents(".custom-menu").length > 0) {_x000D_
        _x000D_
        // Hide it_x000D_
        $(".custom-menu").hide(100);_x000D_
    }_x000D_
});_x000D_
_x000D_
_x000D_
// If the menu element is clicked_x000D_
$(".custom-menu li").click(function(){_x000D_
    _x000D_
    // This is the triggered action name_x000D_
    switch($(this).attr("data-action")) {_x000D_
        _x000D_
        // A case for each action. Your actions here_x000D_
        case "first": alert("first"); break;_x000D_
        case "second": alert("second"); break;_x000D_
        case "third": alert("third"); break;_x000D_
    }_x000D_
  _x000D_
    // Hide it AFTER the action was triggered_x000D_
    $(".custom-menu").hide(100);_x000D_
  });
_x000D_
/* CSS3 */_x000D_
_x000D_
/* The whole thing */_x000D_
.custom-menu {_x000D_
    display: none;_x000D_
    z-index: 1000;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
    border: 1px solid #CCC;_x000D_
    white-space: nowrap;_x000D_
    font-family: sans-serif;_x000D_
    background: #FFF;_x000D_
    color: #333;_x000D_
    border-radius: 5px;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
/* Each of the items in the list */_x000D_
.custom-menu li {_x000D_
    padding: 8px 12px;_x000D_
    cursor: pointer;_x000D_
    list-style-type: none;_x000D_
    transition: all .3s ease;_x000D_
    user-select: none;_x000D_
}_x000D_
_x000D_
.custom-menu li:hover {_x000D_
    background-color: #DEF;_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.js"></script>_x000D_
_x000D_
<ul class='custom-menu'>_x000D_
  <li data-action="first">First thing</li>_x000D_
  <li data-action="second">Second thing</li>_x000D_
  <li data-action="third">Third thing</li>_x000D_
</ul>_x000D_
_x000D_
<!-- Not needed, only for making it clickable on StackOverflow -->_x000D_
Right click me
_x000D_
_x000D_
_x000D_

Note: you might see some small bugs (dropdown far from the cursor, etc), please make sure that it works in the jsfiddle, as that's more similar to your webpage than StackSnippets might be.

Good Hash Function for Strings

This function provided by Nick is good but if you use new String(byte[] bytes) to make the transformation to String, it failed. You can use this function to do that.

private static final char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

public static String byteArray2Hex(byte[] bytes) {
    StringBuffer sb = new StringBuffer(bytes.length * 2);
    for(final byte b : bytes) {
        sb.append(hex[(b & 0xF0) >> 4]);
        sb.append(hex[b & 0x0F]);
    }
    return sb.toString();
}

public static String getStringFromSHA256(String stringToEncrypt) throws NoSuchAlgorithmException {
    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    messageDigest.update(stringToEncrypt.getBytes());
    return byteArray2Hex(messageDigest.digest());
}

May be this can help somebody

How to capitalize first letter of each word, like a 2-word city?

The JavaScript function:

String.prototype.capitalize = function(){
       return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){ return p1+p2.toUpperCase(); } );
      };

To use this function:

capitalizedString = someString.toLowerCase().capitalize();

Also, this would work on multiple words string.

To make sure the converted City name is injected into the database, lowercased and first letter capitalized, then you would need to use JavaScript before you send it over to server side. CSS simply styles, but the actual data would remain pre-styled. Take a look at this jsfiddle example and compare the alert message vs the styled output.

Pass parameter to EventHandler

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

Edit: you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

The R Language Definition is handy for answering these types of questions:

R has three basic indexing operators, with syntax displayed by the following examples

    x[i]
    x[i, j]
    x[[i]]
    x[[i, j]]
    x$a
    x$"a"

For vectors and matrices the [[ forms are rarely used, although they have some slight semantic differences from the [ form (e.g. it drops any names or dimnames attribute, and that partial matching is used for character indices). When indexing multi-dimensional structures with a single index, x[[i]] or x[i] will return the ith sequential element of x.

For lists, one generally uses [[ to select any single element, whereas [ returns a list of the selected elements.

The [[ form allows only a single element to be selected using integer or character indices, whereas [ allows indexing by vectors. Note though that for a list, the index can be a vector and each element of the vector is applied in turn to the list, the selected component, the selected component of that component, and so on. The result is still a single element.

res.sendFile absolute path

you can use send instead of sendFile so you wont face with error! this works will help you!

fs.readFile('public/index1.html',(err,data)=>{
if(err){
  consol.log(err);
}else {
res.setHeader('Content-Type', 'application/pdf');

for telling browser that your response is type of PDF

res.setHeader('Content-Disposition', 'attachment; filename='your_file_name_for_client.pdf');

if you want that file open immediately on the same page after user download it.write 'inline' instead attachment in above code.

res.send(data)

How to align an input tag to the center without specifying the width?

you can use this two simple line code :

_x000D_
_x000D_
    display: block;
    margin:auto;
_x000D_
_x000D_
_x000D_

What is the difference between "JPG" / "JPEG" / "PNG" / "BMP" / "GIF" / "TIFF" Image?

These names refers to different ways to encode pixel image data (JPG and JPEG are the same thing, and TIFF may just enclose a jpeg with some additional metadata).

These image formats may use different compression algorithms, different color representations, different capability in carrying additional data other than the image itself, and so on.

For web applications, I'd say jpeg or gif is good enough. Jpeg is used more often due to its higher compression ratio, and gif is typically used for light weight animation where a flash (or something similar) is an over kill, or places where transparent background is desired. PNG can be used too, but I don't have much experience with that. BMP and TIFF probably are not good candidates for web applications.

How can I find the link URL by link text with XPath?

Should be something similar to:

//a[text()='text_i_want_to_find']/@href

JQuery: Change value of hidden input field

It's simple as:

$('#action').val("1");

#action is hidden input field id.

What MIME type should I use for CSV?

You should use "text/csv" according to RFC 4180.