Programs & Examples On #Timedelay

How can I make a time delay in Python?

The Tkinter library in the Python standard library is an interactive tool which you can import. Basically, you can create buttons and boxes and popups and stuff that appear as windows which you manipulate with code.

If you use Tkinter, do not use time.sleep(), because it will muck up your program. This happened to me. Instead, use root.after() and replace the values for however many seconds, with a milliseconds. For example, time.sleep(1) is equivalent to root.after(1000) in Tkinter.

Otherwise, time.sleep(), which many answers have pointed out, which is the way to go.

implement time delay in c

Write this code :

void delay(int x)
{   int i=0,j=0;
    for(i=0;i<x;i++){for(j=0;j<200000;j++){}}
}

int main()
{
    int i,num;

    while(1) {

    delay(500);

    printf("Host name");
    printf("\n");}

}

Timing Delays in VBA

I used the answer of Steve Mallory, but I am affraid the timer never or at least sometimes does not go to 86400 nor 0 (zero) sharp (MS Access 2013). So I modified the code. I changed the midnight condition to "If Timer >= 86399 Then" and added the break of the loop "Exit Do" as follows:

Public Function Pause(NumberOfSeconds As Variant)
    On Error GoTo Error_GoTo

    Dim PauseTime As Variant
    Dim Start As Variant
    Dim Elapsed As Variant

    PauseTime = NumberOfSeconds
    Start = Timer
    Elapsed = 0
    Do While Timer < Start + PauseTime
        Elapsed = Elapsed + 1
        If Timer >= 86399
            ' Crossing midnight
            ' PauseTime = PauseTime - Elapsed
            ' Start = 0
            ' Elapsed = 0
            Exit Do
        End If
        DoEvents
    Loop

Exit_GoTo:
    On Error GoTo 0
    Exit Function
Error_GoTo:
    Debug.Print Err.Number, Err.Description, Erl
    GoTo Exit_GoTo
End Function

How to create a sleep/delay in nodejs that is Blocking?

Node is asynchronous by nature, and that's what's great about it, so you really shouldn't be blocking the thread, but as this seems to be for a project controlling LED's, I'll post a workaraound anyway, even if it's not a very good one and shouldn't be used (seriously).

A while loop will block the thread, so you can create your own sleep function

function sleep(time, callback) {
    var stop = new Date().getTime();
    while(new Date().getTime() < stop + time) {
        ;
    }
    callback();
}

to be used as

sleep(1000, function() {
   // executes after one second, and blocks the thread
});

I think this is the only way to block the thread (in principle), keeping it busy in a loop, as Node doesn't have any blocking functionality built in, as it would sorta defeat the purpose of the async behaviour.

Redirecting a request using servlets and the "setHeader" method not working

As you can see, the response is still HTTP/1.1 200 OK. To indicate a redirect, you need to send back a 302 status code:

response.setStatus(HttpServletResponse.SC_FOUND); // SC_FOUND = 302

What is the best alternative IDE to Visual Studio

I still like Source Insight a lot, but I'm hesitant to recommend it anymore as I'm not sure anybody's still maintaining it. They released a very minor update back in March but haven't had a major release in years. And there seems to be no web community presence. It's a shame because I still like its auto-completion-friendly file open and symbol browsing panels (as well as syntax formatting) better than anything else I've ever used.

PHP PDO: charset, set names?

I test this code and

$db=new PDO('mysql:host=localhost;dbname=cwDB','root','',
array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$sql="select * from products  ";
$stmt=$db->prepare($sql);
$stmt->execute();
while($result=$stmt->fetch(PDO::FETCH_ASSOC)){                  
    $id=$result['id'];
}

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Try this:

jsonResponse = json.loads(response.decode('utf-8'))

URL string format for connecting to Oracle database with JDBC

if you are using oracle 10g expree Edition then:
1. for loading class use DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); 2. for connecting to database use Connection conn = DriverManager.getConnection("jdbc:oracle:thin:username/password@localhost:1521:xe");

Basic HTTP and Bearer Token Authentication

curl --anyauth

Tells curl to figure out authentication method by itself, and use the most secure one the remote site claims to support. This is done by first doing a request and checking the response- headers, thus possibly inducing an extra network round-trip. This is used instead of setting a specific authentication method, which you can do with --basic, --digest, --ntlm, and --negotiate.

Where are include files stored - Ubuntu Linux, GCC

gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo" and #include <zap> will search on your system, I recommend:

$ touch a.c
$ gcc -v -E a.c
 ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"

This is one way to see the search lists for included files, including (if any) directories into which #include "..." will look but #include <...> won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ... here;-) on any system on which gcc runs properly.

Linq on DataTable: select specific column into datatable, not whole table

Here I get only three specific columns from mainDataTable and use the filter

DataTable checkedParams = mainDataTable.Select("checked = true").CopyToDataTable()
.DefaultView.ToTable(false, "lagerID", "reservePeriod", "discount");

Is there a simple JavaScript slider?

HTML 5 with Webforms 2 provides an <input type="range"> which will make the browser generate a native slider for you. Unfortunately all browsers doesn't have support for this, however google has implemented all Webforms 2 controls with js. IIRC the js is intelligent enough to know if the browser has implemented the control, and triggers only if there is no native implementation.

From my point of view it should be considered best practice to use the browsers native controls when possible.

bootstrap 3 wrap text content within div for horizontal alignment

Add the following style to your h3 elements:

word-wrap: break-word;

This will cause the long URLs in them to wrap. The default setting for word-wrap is normal, which will wrap only at a limited set of split tokens (e.g. whitespaces, hyphens), which are not present in a URL.

Vertically align text within input field of fixed-height without display: table or padding?

input[type=text]
{
   height: 15px; 
   line-height: 15px;
}

this is correct way to set vertical-middle position.

How do I create a chart with multiple series using different X values for each series?

You need to use the Scatter chart type instead of Line. That will allow you to define separate X values for each series.

Wait for shell command to complete

This is what I use to have VB wait for process to complete before continuing. I did not write this and do not take credit.

It was offered in some other open forum and works very well for me:

The following declarations are needed for the RunShell subroutine:

Option Explicit

Private Declare Function OpenProcess Lib "kernel32" (ByVal dwDesiredAccess As Long, ByVal bInheritHandle As Long, ByVal dwProcessId As Long) As Long

Private Declare Function GetExitCodeProcess Lib "kernel32" (ByVal hProcess As Long, lpExitCode As Long) As Long

Private Declare Function CloseHandle Lib "kernel32" (ByVal hObject As Long) As Long

Private Const PROCESS_QUERY_INFORMATION = &H400

Private Const STATUS_PENDING = &H103&

'then in your subroutine where you need to shell:

RunShell (path and filename or command, as quoted text)

DateTime.ToString() format that can be used in a filename or extension?

I have a similar situation but I want a consistent way to be able to use DateTime.Parse from the filename as well, so I went with

DateTime.Now.ToString("s").Replace(":", ".") // <-- 2016-10-25T16.50.35

When I want to parse, I can simply reverse the Replace call. This way I don't have to type in any yymmdd stuff or guess what formats DateTime.Parse allows.

How do I sort a Set to a List in Java?

Here's how you can do it with Java 8's Streams:

mySet.stream().sorted().collect(Collectors.toList());

or with a custom comparator:

mySet.stream().sorted(myComparator).collect(Collectors.toList());

How to delete large data of table in SQL without log?

If you are willing (and able) to implement partitioning, that is an effective technique for removing large quantities of data with little run-time overhead. Not cost-effective for a once-off exercise, though.

How to keep onItemSelected from firing off on a newly instantiated Spinner?

I got a very simple answer , 100% sure it works:

boolean Touched=false; // this a a global variable

public void changetouchvalue()
{
   Touched=true;
}

// this code is written just before onItemSelectedListener

 spinner.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            System.out.println("Real touch felt.");
            changetouchvalue();
            return false;
        }
    });

//inside your spinner.SetonItemSelectedListener , you have a function named OnItemSelected iside that function write the following code

if(Touched)
{
 // the code u want to do in touch event
}

How to find common elements from multiple vectors?

A good answer already, but there are a couple of other ways to do this:

unique(c[c%in%a[a%in%b]])

or,

tst <- c(unique(a),unique(b),unique(c))
tst <- tst[duplicated(tst)]
tst[duplicated(tst)]

You can obviously omit the unique calls if you know that there are no repeated values within a, b or c.

Decreasing height of bootstrap 3.0 navbar

If you guys are generating your stylesheets with LESS/SASS and are importing Bootstrap there, I've found that overriding the @navbar-height variable lets your set the height of the navbar, which is originally defined in the variables.less file.

enter image description here

How do I conditionally apply CSS styles in AngularJS?

See the following example

<!DOCTYPE html>
    <html ng-app>
    <head>
    <title>Demo Changing CSS Classes Conditionally with Angular</title>
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
    <script src="res/js/controllers.js"></script>

    <style>

    .checkboxList {
        border:1px solid #000;
        background-color:#fff;
        color:#000;
        width:300px;
        height: 100px;
        overflow-y: scroll;
    }

    .uncheckedClass {
       background-color:#eeeeee;
       color:black;
    }
    .checkedClass {
        background-color:#3ab44a;
        color:white;
    }
    </style>

    </head>
    <body ng-controller="TeamListCtrl">
    <b>Teams</b>
    <div id="teamCheckboxList" class="checkboxList">

    <div class="uncheckedClass" ng-repeat="team in teams" ng-class="{'checkedClass': team.isChecked, 'uncheckedClass': !team.isChecked}">

    <label>
    <input type="checkbox" ng-model="team.isChecked" />
    <span>{{team.name}}</span>
    </label>
    </div>
    </div>
    </body>
    </html>

In bash, how to store a return value in a variable?

Something like this could be used, and still maintaining meanings of return (to return control signals) and echo (to return information) and logging statements (to print debug/info messages).

v_verbose=1
v_verbose_f=""         # verbose file name
FLAG_BGPID=""

e_verbose() {
        if [[ $v_verbose -ge 0 ]]; then
                v_verbose_f=$(tempfile)
                tail -f $v_verbose_f &
                FLAG_BGPID="$!"
        fi
}

d_verbose() {
        if [[ x"$FLAG_BGPID" != "x" ]]; then
                kill $FLAG_BGPID > /dev/null
                FLAG_BGPID=""
                rm -f $v_verbose_f > /dev/null
        fi
}

init() {
        e_verbose

        trap cleanup SIGINT SIGQUIT SIGKILL SIGSTOP SIGTERM SIGHUP SIGTSTP
}

cleanup() {
        d_verbose
}

init

fun1() {
    echo "got $1" >> $v_verbose_f
    echo "got $2" >> $v_verbose_f
    echo "$(( $1 + $2 ))"
    return 0
}

a=$(fun1 10 20)
if [[ $? -eq 0 ]]; then
    echo ">>sum: $a"
else
    echo "error: $?"
fi
cleanup

In here, I'm redirecting debug messages to separate file, that is watched by tail, and if there is any changes then printing the change, trap is used to make sure that background process always ends.

This behavior can also be achieved using redirection to /dev/stderr, But difference can be seen at the time of piping output of one command to input of other command.

Merging Cells in Excel using C#

using Excel = Microsoft.Office.Interop.Excel;
// Your code...
yourWorksheet.Range[yourWorksheet.Cells[rowBegin,colBegin], yourWorksheet.Cells[yourWorksheet.rowEnd, colEnd]].Merge();

Row and Col start at 1.

Angular2 Error: There is no directive with "exportAs" set to "ngForm"

If you are getting this instead:

Error: Template parse errors:

There is no directive with "exportAs" set to "ngModel"

Which was reported as a bug in github, then likely it is not a bug since you might:

  1. have a syntax error (e.g. an extra bracket: [(ngModel)]]=), OR
  2. be mixing Reactive forms directives, such as formControlName, with the ngModel directive. This "has been deprecated in Angular v6 and will be removed in Angular v7", since this mixes both form strategies, making it:
  • seem like the actual ngModel directive is being used, but in fact it's an input/output property named ngModel on the reactive form directive that simply approximates (some of) its behavior. Specifically, it allows getting/setting the value and intercepting value events. However, some of ngModel's other features - like delaying updates withngModelOptions or exporting the directive - simply don't work (...)

  • this pattern mixes template-driven and reactive forms strategies, which we generally don't recommend because it doesn't take advantage of the full benefits of either strategy. (...)

  • To update your code before v7, you'll want to decide whether to stick with reactive form directives (and get/set values using reactive forms patterns) or switch over to template-driven directives.

When you have an input like this:

<input formControlName="first" [(ngModel)]="value">

It will show a warning about mixed form strategies in the browser's console:

It looks like you're using ngModel on the same form field as formControlName.

However, if you add the ngModel as a value in a reference variable, example:

<input formControlName="first" #firstIn="ngModel" [(ngModel)]="value">

The error above is then triggered and no warning about strategy mixing is shown.

how to get right offset of an element? - jQuery

Getting the anchor point of a div/table (left) = $("#whatever").offset().left; - ok!

Getting the anchor point of a div/table (right) you can use the code below.

 $("#whatever").width();

MIME types missing in IIS 7 for ASP.NET - 404.17

There are two reasons you might get this message:

  1. ASP.Net is not configured. For this run from Administrator command %FrameworkDir%\%FrameworkVersion%\aspnet_regiis -i. Read the message carefully. On Windows8/IIS8 it may say that this is no longer supported and you may have to use Turn Windows Features On/Off dialog in Install/Uninstall a Program in Control Panel.
  2. Another reason this may happen is because your App Pool is not configured correctly. For example, you created website for WordPress and you also want to throw in few aspx files in there, WordPress creates app pool that says don't run CLR stuff. To fix this just open up App Pool and enable CLR.

Calculating percentile of dataset column

table_ages <- subset(infert, select=c("age"))
summary(table_ages)
#            age       
#  Min.   :21.00  
#  1st Qu.:28.00  
#  Median :31.00  
#  Mean   :31.50  
#  3rd Qu.:35.25  
#  Max.   :44.00  

This is probably what they're looking for. summary(...) applied to a numeric returns the min, max, mean, median, and 25th and 75th percentile of the data.

Note that

summary(infert$age)
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#   21.00   28.00   31.00   31.50   35.25   44.00 

The numbers are the same but the format is different. This is because table_ages is a data frame with one column (ages), whereas infert$age is a numeric vector. Try typing summary(infert).

How to pass arguments and redirect stdin from a file to program run in gdb?

Wouldn't it be nice to just type debug in front of any command to be able to debug it with gdb on shell level?

Below it this function. It even works with following:

"$program" "$@" < <(in) 1> >(out) 2> >(two) 3> >(three)

This is a call where you cannot control anything, everything is variable, can contain spaces, linefeeds and shell metacharacters. In this example, in, out, two, and three are arbitrary other commands which consume or produce data which must not be harmed.

Following bash function invokes gdb nearly cleanly in such an environment [Gist]:

debug()
{
  1000<&0 1001>&1 1002>&2 \
  0</dev/tty 1>/dev/tty 2>&0 \
  /usr/bin/gdb -q -nx -nw \
  -ex 'set exec-wrapper /bin/bash -c "exec 0<&1000 1>&1001 2>&1002 \"\$@\"" exec' \
  -ex r \
  --args "$@";
}

Example on how to apply this: Just type debug in front:

Before:

p=($'\n' $'I\'am\'evil' "  yay  ")
"b u g" "${p[@]}" < <(in) 1> >(out) 2> >(two) 3> >(three)

After:

p=($'\n' $'I\'am\'evil' "  yay  ")
debug "b u g" "${p[@]}" < <(in) 1> >(out) 2> >(two) 3> >(three)

That's it. Now it's an absolute no-brainer to debug with gdb. Except for a few details or more:

  • gdb does not quit automatically and hence keeps the IO redirection open until you exit gdb. But I call this a feature.

  • You cannot easily pass argv0 to the program like with exec -a arg0 command args. Following should do this trick: After exec-wrapper change "exec to "exec -a \"\${DEBUG_ARG0:-\$1}\".

  • There are FDs above 1000 open, which are normally closed. If this is a problem, change 0<&1000 1>&1001 2>&1002 to read 0<&1000 1>&1001 2>&1002 1000<&- 1001>&- 1002>&-

  • You cannot run two debuggers in parallel. There also might be issues, if some other command consumes /dev/tty (or STDIN). To fix that, replace /dev/tty with "${DEBUGTTY:-/dev/tty}". In some other TTY type tty; sleep inf and then use the printed TTY (i. E. /dev/pts/60) for debugging, as in DEBUGTTY=/dev/pts/60 debug command arg... That's the Power of Shell, get used to it!

Function explained:

  • 1000<&0 1001>&1 1002>&2 moves away the first 3 FDs
    • This assumes, that FDs 1000, 1001 and 1002 are free
  • 0</dev/tty 1>/dev/tty 2>&0 restores the first 3 FDs to point to your current TTY. So you can control gdb.
  • /usr/bin/gdb -q -nx -nw runs gdb invokes gdb on shell
  • -ex 'set exec-wrapper /bin/bash -c "exec 0<&1000 1>&1001 2>&1002 \"\$@\"" creates a startup wrapper, which restores the first 3 FDs which were saved to 1000 and above
  • -ex r starts the program using the exec-wrapper
  • --args "$@" passes the arguments as given

Wasn't that easy?

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

After placing the jar file in desired location, you need to add the jar file by right click on

Project --> properties --> Java Build Path --> Libraries --> Add Jar.

How to read a text file in project's root directory?

You can have it embedded (build action set to Resource) as well, this is how to retrieve it from there:

private static UnmanagedMemoryStream GetResourceStream(string resName)
{
    var assembly = Assembly.GetExecutingAssembly();
    var strResources = assembly.GetName().Name + ".g.resources";
    var rStream = assembly.GetManifestResourceStream(strResources);
    var resourceReader = new ResourceReader(rStream);
    var items = resourceReader.OfType<DictionaryEntry>();
    var stream = items.First(x => (x.Key as string) == resName.ToLower()).Value;
    return (UnmanagedMemoryStream)stream;
}

private void Button1_Click(object sender, RoutedEventArgs e)
{
    string resName = "Test.txt";
    var file = GetResourceStream(resName);
    using (var reader = new StreamReader(file))
    {
        var line = reader.ReadLine();
        MessageBox.Show(line);
    }
}

(Some code taken from this answer by Charles)

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

check for jar(mysql-connector-java-bin) in your classpath download from here

Python Error: "ValueError: need more than 1 value to unpack"

You should run your code in a following manner in order get your output,

python file_name.py user_name

Passing data through intent using Serializable

You need to create a Bundle and then use putSerializable:

List<Thumbnail> all_thumbs = new ArrayList<Thumbnail>();
all_thumbs.add(new Thumbnail(string,bitmap));
Intent intent = new Intent(getApplicationContext(),SomeClass.class);

Bundle extras = new Bundle();

extras.putSerializable("value",all_thumbs);
intent.putExtras(extras);

Python SQL query string formatting

You can use inspect.cleandoc to nicely format your printed SQL statement.

This works very well with your option 2.

Note: the print("-"*40) is only to demonstrate the superflous blank lines if you do not use cleandoc.

from inspect import cleandoc
def query():
    sql = """
        select field1, field2, field3, field4
        from table
        where condition1=1
        and condition2=2
    """

    print("-"*40)
    print(sql)
    print("-"*40)
    print(cleandoc(sql))
    print("-"*40)

query()

Output:

----------------------------------------

        select field1, field2, field3, field4
        from table
        where condition1=1
        and condition2=2

----------------------------------------
select field1, field2, field3, field4
from table
where condition1=1
and condition2=2
----------------------------------------

From the docs:

inspect.cleandoc(doc)

Clean up indentation from docstrings that are indented to line up with blocks of code.

All leading whitespace is removed from the first line. Any leading whitespace that can be uniformly removed from the second line onwards is removed. Empty lines at the beginning and end are subsequently removed. Also, all tabs are expanded to spaces.

What is the best way to remove the first element from an array?

Simplest way is probably as follows - you basically need to construct a new array that is one element smaller, then copy the elements you want to keep to the right positions.

int n=oldArray.length-1;
String[] newArray=new String[n];
System.arraycopy(oldArray,1,newArray,0,n);

Note that if you find yourself doing this kind of operation frequently, it could be a sign that you should actually be using a different kind of data structure, e.g. a linked list. Constructing a new array every time is an O(n) operation, which could get expensive if your array is large. A linked list would give you O(1) removal of the first element.

An alternative idea is not to remove the first item at all, but just increment an integer that points to the first index that is in use. Users of the array will need to take this offset into account, but this can be an efficient approach. The Java String class actually uses this method internally when creating substrings.

CSS for the "down arrow" on a <select> element?

This will change inputs, select etc to the old style grey not sure if you can manipulate after that: In <head> put:

<meta http-equiv="MSThemeCompatible" content="NO">

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

Swift 2.0

// Checking if app is running iOS 8
    if application.respondsToSelector("isRegisteredForRemoteNotifications") {

        print("registerApplicationForPushNotifications - iOS 8")

        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: [.Alert, .Badge, .Sound], categories: nil));
        application.registerForRemoteNotifications()

    } else {
        // Register for Push Notifications before iOS 8
        print("registerApplicationForPushNotifications - <iOS 8")
        application.registerForRemoteNotificationTypes([UIRemoteNotificationType.Alert, UIRemoteNotificationType.Badge, UIRemoteNotificationType.Sound])

    }

How do you plot bar charts in gnuplot?

I recommend Derek Bruening's bar graph generator Perl script. Available at http://www.burningcutlery.com/derek/bargraph/

ExecutorService that interrupts tasks after a timeout

What about this alternative idea :

  • two have two executors :
    • one for :
      • submitting the task, without caring about the timeout of the task
      • adding the Future resulted and the time when it should end to an internal structure
    • one for executing an internal job which is checking the internal structure if some tasks are timeout and if they have to be cancelled.

Small sample is here :

public class AlternativeExecutorService 
{

private final CopyOnWriteArrayList<ListenableFutureTask> futureQueue       = new CopyOnWriteArrayList();
private final ScheduledThreadPoolExecutor                scheduledExecutor = new ScheduledThreadPoolExecutor(1); // used for internal cleaning job
private final ListeningExecutorService                   threadExecutor    = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(5)); // used for
private ScheduledFuture scheduledFuture;
private static final long INTERNAL_JOB_CLEANUP_FREQUENCY = 1000L;

public AlternativeExecutorService()
{
    scheduledFuture = scheduledExecutor.scheduleAtFixedRate(new TimeoutManagerJob(), 0, INTERNAL_JOB_CLEANUP_FREQUENCY, TimeUnit.MILLISECONDS);
}

public void pushTask(OwnTask task)
{
    ListenableFuture<Void> future = threadExecutor.submit(task);  // -> create your Callable
    futureQueue.add(new ListenableFutureTask(future, task, getCurrentMillisecondsTime())); // -> store the time when the task should end
}

public void shutdownInternalScheduledExecutor()
{
    scheduledFuture.cancel(true);
    scheduledExecutor.shutdownNow();
}

long getCurrentMillisecondsTime()
{
    return Calendar.getInstance().get(Calendar.MILLISECOND);
}

class ListenableFutureTask
{
    private final ListenableFuture<Void> future;
    private final OwnTask                task;
    private final long                   milliSecEndTime;

    private ListenableFutureTask(ListenableFuture<Void> future, OwnTask task, long milliSecStartTime)
    {
        this.future = future;
        this.task = task;
        this.milliSecEndTime = milliSecStartTime + task.getTimeUnit().convert(task.getTimeoutDuration(), TimeUnit.MILLISECONDS);
    }

    ListenableFuture<Void> getFuture()
    {
        return future;
    }

    OwnTask getTask()
    {
        return task;
    }

    long getMilliSecEndTime()
    {
        return milliSecEndTime;
    }
}

class TimeoutManagerJob implements Runnable
{
    CopyOnWriteArrayList<ListenableFutureTask> getCopyOnWriteArrayList()
    {
        return futureQueue;
    }

    @Override
    public void run()
    {
        long currentMileSecValue = getCurrentMillisecondsTime();
        for (ListenableFutureTask futureTask : futureQueue)
        {
            consumeFuture(futureTask, currentMileSecValue);
        }
    }

    private void consumeFuture(ListenableFutureTask futureTask, long currentMileSecValue)
    {
        ListenableFuture<Void> future = futureTask.getFuture();
        boolean isTimeout = futureTask.getMilliSecEndTime() >= currentMileSecValue;
        if (isTimeout)
        {
            if (!future.isDone())
            {
                future.cancel(true);
            }
            futureQueue.remove(futureTask);
        }
    }
}

class OwnTask implements Callable<Void>
{
    private long     timeoutDuration;
    private TimeUnit timeUnit;

    OwnTask(long timeoutDuration, TimeUnit timeUnit)
    {
        this.timeoutDuration = timeoutDuration;
        this.timeUnit = timeUnit;
    }

    @Override
    public Void call() throws Exception
    {
        // do logic
        return null;
    }

    public long getTimeoutDuration()
    {
        return timeoutDuration;
    }

    public TimeUnit getTimeUnit()
    {
        return timeUnit;
    }
}
}

Why did a network-related or instance-specific error occur while establishing a connection to SQL Server?

I had same problem regarding that i.e A network-related or instance-specific error occurred while establishing a connection to SQL Server.

I was using SQL Server 2005 (.\sqlexpress)` and worked fine but suddenly services stopped and gave me error.

I solved it like this,

Start -> Search Box - > Sql Configuration Manager -> SQL Server 2005 Services >and just Change Your SQL Server (SQLEXPRESS) State to Running by right clicking that service Sate.

How to customize the back button on ActionBar

I used back.png image in the project menifest.xml file. it is fine working in project.

<activity
        android:name=".YourActivity"
         android:icon="@drawable/back"
        android:label="@string/app_name" >
    </activity>

.aspx vs .ashx MAIN difference

For folks that have programmed in nodeJs before, particularly using expressJS. I think of .ashx as a middleware that calls the next function. While .aspx will be the controller that actually responds to the request either around res.redirect, res.send or whatever.

Find a row in dataGridView based on column and value

Or you can use like this. This may be faster.

int iFindNo = 14;
int j = dataGridView1.Rows.Count-1;
int iRowIndex = -1;
for (int i = 0; i < Convert.ToInt32(dataGridView1.Rows.Count/2) +1; i++)
{
    if (Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value) == iFindNo)
    {
        iRowIndex = i;
        break;
    }
    if (Convert.ToInt32(dataGridView1.Rows[j].Cells[0].Value) == iFindNo)
    {
        iRowIndex = j;
        break;
    }
    j--;
}
if (iRowIndex != -1)
    MessageBox.Show("Index is " + iRowIndex.ToString());
else
    MessageBox.Show("Index not found." );

Selenium Finding elements by class name in python

By.CLASS_NAME was not yet mentioned:

from selenium.webdriver.common.by import By

driver.find_element(By.CLASS_NAME, "content")

This is the list of attributes which can be used as locators in By:

CLASS_NAME
CSS_SELECTOR
ID
LINK_TEXT
NAME
PARTIAL_LINK_TEXT
TAG_NAME
XPATH

AngularJS format JSON string output

If you want to format the JSON and also do some syntax highlighting, you can use the ng-prettyjson directive. See the npm package.

Here is how to use it: <pre pretty-json="jsonObject"></pre>

Why should I use a container div in HTML?

div tags are used to style the webpage so that it look visually appealing for the users or audience of the website. using container-div in html will make the website look more professional and attractive and therefore more people will want to explore your page.

MySQL trigger if condition exists

I think you mean to update it back to the OLD password, when the NEW one is not supplied.

DROP TRIGGER IF EXISTS upd_user;

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '') THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

However, this means a user can never blank out a password.


If the password field (already encrypted) is being sent back in the update to mySQL, then it will not be null or blank, and MySQL will attempt to redo the Password() function on it. To detect this, use this code instead

DELIMITER $$

    CREATE TRIGGER upd_user BEFORE UPDATE ON `user`
    FOR EACH ROW BEGIN
      IF (NEW.password IS NULL OR NEW.password = '' OR NEW.password = OLD.password) THEN
            SET NEW.password = OLD.password;
      ELSE
            SET NEW.password = Password(NEW.Password);
      END IF;
    END$$

DELIMITER ;

how to get request path with express req object

It should be:

req.url

express 3.1.x

How to do a JUnit assert on a message in a logger

What I have done if all I want to do is see that some string was logged (as opposed to verifying exact log statements which is just too brittle) is to redirect StdOut to a buffer, do a contains, then reset StdOut:

PrintStream original = System.out;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
System.setOut(new PrintStream(buffer));

// Do something that logs

assertTrue(buffer.toString().contains(myMessage));
System.setOut(original);

Finding the path of the program that will execute from the command line in Windows

Use the where command. The first result in the list is the one that will execute.

C:\> where notepad
C:\Windows\System32\notepad.exe
C:\Windows\notepad.exe

According to this blog post, where.exe is included with Windows Server 2003 and later, so this should just work with Vista, Win 7, et al.

On Linux, the equivalent is the which command, e.g. which ssh.

ASP.NET MVC Ajax Error handling

I did a quick solution because I was short of time and it worked ok. Although I think the better option is use an Exception Filter, maybe my solution can help in the case that a simple solution is needed.

I did the following. In the controller method I returned a JsonResult with a property "Success" inside the Data:

    [HttpPut]
    public JsonResult UpdateEmployeeConfig(EmployeConfig employeToSave) 
    {
        if (!ModelState.IsValid)
        {
            return new JsonResult
            {
                Data = new { ErrorMessage = "Model is not valid", Success = false },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }
        try
        {
            MyDbContext db = new MyDbContext();

            db.Entry(employeToSave).State = EntityState.Modified;
            db.SaveChanges();

            DTO.EmployeConfig user = (DTO.EmployeConfig)Session["EmployeLoggin"];

            if (employeToSave.Id == user.Id)
            {
                user.Company = employeToSave.Company;
                user.Language = employeToSave.Language;
                user.Money = employeToSave.Money;
                user.CostCenter = employeToSave.CostCenter;

                Session["EmployeLoggin"] = user;
            }
        }
        catch (Exception ex) 
        {
            return new JsonResult
            {
                Data = new { ErrorMessage = ex.Message, Success = false },
                ContentEncoding = System.Text.Encoding.UTF8,
                JsonRequestBehavior = JsonRequestBehavior.DenyGet
            };
        }

        return new JsonResult() { Data = new { Success = true }, };
    }

Later in the ajax call I just asked for this property to know if I had an exception:

$.ajax({
    url: 'UpdateEmployeeConfig',
    type: 'PUT',
    data: JSON.stringify(EmployeConfig),
    contentType: "application/json;charset=utf-8",
    success: function (data) {
        if (data.Success) {
            //This is for the example. Please do something prettier for the user, :)
            alert('All was really ok');                                           
        }
        else {
            alert('Oups.. we had errors: ' + data.ErrorMessage);
        }
    },
    error: function (request, status, error) {
       alert('oh, errors here. The call to the server is not working.')
    }
});

Hope this helps. Happy code! :P

Truncate number to two decimal places without rounding

Convert the number into a string, match the number up to the second decimal place:

_x000D_
_x000D_
function calc(theform) {_x000D_
    var num = theform.original.value, rounded = theform.rounded_x000D_
    var with2Decimals = num.toString().match(/^-?\d+(?:\.\d{0,2})?/)[0]_x000D_
    rounded.value = with2Decimals_x000D_
}
_x000D_
<form onsubmit="return calc(this)">_x000D_
Original number: <input name="original" type="text" onkeyup="calc(form)" onchange="calc(form)" />_x000D_
<br />"Rounded" number: <input name="rounded" type="text" placeholder="readonly" readonly>_x000D_
</form>
_x000D_
_x000D_
_x000D_

The toFixed method fails in some cases unlike toString, so be very careful with it.

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

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

Here is why the original expression didn't work.

From man bash:

Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces.

So, brace expansion is something done early as a purely textual macro operation, before parameter expansion.

Shells are highly optimized hybrids between macro processors and more formal programming languages. In order to optimize the typical use cases, the language is made rather more complex and some limitations are accepted.

Recommendation

I would suggest sticking with Posix1 features. This means using for i in <list>; do, if the list is already known, otherwise, use while or seq, as in:

#!/bin/sh

limit=4

i=1; while [ $i -le $limit ]; do
  echo $i
  i=$(($i + 1))
done
# Or -----------------------
for i in $(seq 1 $limit); do
  echo $i
done


1. Bash is a great shell and I use it interactively, but I don't put bash-isms into my scripts. Scripts might need a faster shell, a more secure one, a more embedded-style one. They might need to run on whatever is installed as /bin/sh, and then there are all the usual pro-standards arguments. Remember shellshock, aka bashdoor?

Create an Android GPS tracking application

The source code for the Android mobile application open-gpstracker which you appreciated is available here.

You can checkout the code using SVN client application or via Git:

Debugging the source code will surely help you.

How do I set the selected item in a drop down box

If you have a big drop down. it's much easier to use jQuery with PHP.

This is how to do it:

<script>
$(document).ready(function () {
    $('select[name="country"]').val('<?=$data[0]['Country']?>');
});
</script>

Easy way to write contents of a Java InputStream to an OutputStream

Another possible candidate are the Guava I/O utilities:

http://code.google.com/p/guava-libraries/wiki/IOExplained

I thought I'd use these since Guava is already immensely useful in my project, rather than adding yet another library for one function.

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Pure CSS animation visibility with delay

Use animation-delay:

div {
    width: 100px;
    height: 100px;
    background: red;
    opacity: 0;

    animation: fadeIn 3s;
    animation-delay: 5s;
    animation-fill-mode: forwards;
}

@keyframes fadeIn {
    from { opacity: 0; }
    to { opacity: 1; }
}

Fiddle

Can Android Studio be used to run standard Java projects?

To run a java file in Android ensure your class has the main method. In Android Studio 3.5 just right click inside the file and select "Run 'Filename.main()'" or click on "Run" on the menu and select "Run Filename" from the resulting drop-down menu.

Storing Images in DB - Yea or Nay?

If this is web-based application then there could be advantages to storing the images on a third-party storage delivery network, such as Amazon's S3 or the Nirvanix platform.

RegEx for Javascript to allow only alphanumeric

Alphanumeric with case sensitive:

if (/^[a-zA-Z0-9]+$/.test("SoS007")) {
  alert("match")
}

Saving awk output to variable

variable=$(ps -ef | awk '/[p]ort 10/ {print $12}')

The [p] is a neat trick to remove the search from showing from ps

@Jeremy If you post the output of ps -ef | grep "port 10", and what you need from the line, it would be more easy to help you getting correct syntax

How to remove the querystring and get only the url?

best solution:

echo parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

No need to include your http://domain.com in your if you're submitting a form to the same domain.

jquery toggle slide from left to right and back

See this: Demo

$('#cat_icon,.panel_title').click(function () {
   $('#categories,#cat_icon').stop().slideToggle('slow');
});

Update : To slide from left to right: Demo2

Note: Second one uses jquery-ui also

Send Message in C#

It doesn't sound like a good idea to use send message. I think you should try to work around the problem that the DLLs can't reference each other...

Is there a typescript List<> and/or Map<> class/library?

It's very easy to write that yourself, and that way you have more control over things.. As the other answers say, TypeScript is not aimed at adding runtime types or functionality.

Map:

class Map<T> {
    private items: { [key: string]: T };

    constructor() {
        this.items = {};
    }

    add(key: string, value: T): void {
        this.items[key] = value;
    }

    has(key: string): boolean {
        return key in this.items;
    }

    get(key: string): T {
        return this.items[key];
    }
}

List:

class List<T> {
    private items: Array<T>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(value);
    }

    get(index: number): T {
        return this.items[index];
    }
}

I haven't tested (or even tried to compile) this code, but it should give you a starting point.. you can of course then change what ever you want and add the functionality that YOU need...

As for your "special needs" from the List, I see no reason why to implement a linked list, since the javascript array lets you add and remove items.
Here's a modified version of the List to handle the get prev/next from the element itself:

class ListItem<T> {
    private list: List<T>;
    private index: number;

    public value: T;

    constructor(list: List<T>, value: T, index: number) {
        this.list = list;
        this.index = index;
        this.value = value;
    }

    prev(): ListItem<T> {
        return this.list.get(this.index - 1);
    }

    next(): ListItem<T> {
        return this.list.get(this.index + 1);   
    }
}

class List<T> {
    private items: Array<ListItem<T>>;

    constructor() {
        this.items = [];
    }

    size(): number {
        return this.items.length;
    }

    add(value: T): void {
        this.items.push(new ListItem<T>(this, value, this.size()));
    }

    get(index: number): ListItem<T> {
        return this.items[index];
    }
}

Here too you're looking at untested code..

Hope this helps.


Edit - as this answer still gets some attention

Javascript has a native Map object so there's no need to create your own:

let map = new Map();
map.set("key1", "value1");
console.log(map.get("key1")); // value1

What is the string length of a GUID?

36, and the GUID will only use 0-9A-F (hexidecimal!).

12345678-1234-1234-1234-123456789012

That's 36 characters in any GUID--they are of constant length. You can read a bit more about the intricacies of GUIDs here.

You will need two more in length if you want to store the braces.

Note: 36 is the string length with the dashes in between. They are actually 16-byte numbers.

printf \t option

That's something controlled by your terminal, not by printf.

printf simply sends a \t to the output stream (which can be a tty, a file etc), it doesn't send a number of spaces.

Ansible - Save registered variable to file

A local action will run once for each remote host (in parallel). If you want a unique file per host, make sure to put the inventory_hostname as part of the file name.

- local_action: copy content={{ foo_result }} dest=/path/to/destination/{{ inventory_hostname }}file

If you instead want a single file with all host's information, one way is to have a serial task (don't want to append in parallel) and then append to the file with a module (lineinfile is capable, or could pipe with a shell command)

- hosts: web_servers
  serial: 1
  tasks:
  - local_action: lineinfile line={{ foo_result }} path=/path/to/destination/file

Alternatively, you can add a second play/role/task to the playbook which runs against only local host. Then access the variable from each of the hosts where the registration command ran inside a template Access Other Hosts Variables Docs Template Module Docs

RadioGroup: How to check programmatically

I use this code piece while working with indexes for radio group:

radioGroup.check(radioGroup.getChildAt(index).getId());

Pass Additional ViewData to a Strongly-Typed Partial View

RenderPartial takes another parameter that is simply a ViewDataDictionary. You're almost there, just call it like this:

Html.RenderPartial(
      "ProductImageForm", 
       image, 
       new ViewDataDictionary { { "index", index } }
); 

Note that this will override the default ViewData that all your other Views have by default. If you are adding anything to ViewData, it will not be in this new dictionary that you're passing to your partial view.

Google Maps how to Show city or an Area outline

I have try twitter geo api, failed.

Google map api, failed, so far, no way you can get city limit by any api.

twitter api geo endpoint will NOT give you city boundary,

what they provide you is ONLY bounding box with 5 point(lat, long)

this is what I get from twitter api geo for San Francisco enter image description here

Combine multiple results in a subquery into a single comma-separated value

Even this will serve the purpose

Sample data

declare @t table(id int, name varchar(20),somecolumn varchar(MAX))
insert into @t
    select 1,'ABC','X' union all
    select 1,'ABC','Y' union all
    select 1,'ABC','Z' union all
    select 2,'MNO','R' union all
    select 2,'MNO','S'

Query:

SELECT ID,Name,
    STUFF((SELECT ',' + CAST(T2.SomeColumn AS VARCHAR(MAX))
     FROM @T T2 WHERE T1.id = T2.id AND T1.name = T2.name
     FOR XML PATH('')),1,1,'') SOMECOLUMN
FROM @T T1
GROUP BY id,Name

Output:

ID  Name    SomeColumn
1   ABC     X,Y,Z
2   MNO     R,S

Converting string to date in mongodb

In my case I have succeed with the following solution for converting field ClockInTime from ClockTime collection from string to Date type:

db.ClockTime.find().forEach(function(doc) { 
    doc.ClockInTime=new Date(doc.ClockInTime);
    db.ClockTime.save(doc); 
    })

How to get milliseconds from LocalDateTime in Java 8

You can try this:

long diff = LocalDateTime.now().atZone(ZoneOffset.UTC).toInstant().toEpochMilli();

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

Add Validate Connection=true to your connection string.

Look at this blog to find more about.

DETAILS: After OracleConnection.Close() the real database connection does not terminate. The connection object is put back in connection pool. The use of connection pool is implicit by ODP.NET. If you create a new connection you get one of the pool. If this connection is "yet open" the OracleConnection.Open() method does not really creates a new connection. If the real connection is broken (for any reason) you get a failure on first select, update, insert or delete.

With Validate Connection the real connection is validated in Open() method.

Insert array into MySQL database with PHP

There are a number of different ways... I will give you an example of one using prepared statements:

$prep = array();
foreach($insData as $k => $v ) {
    $prep[':'.$k] = $v;
}
$sth = $db->prepare("INSERT INTO table ( " . implode(', ',array_keys($insData)) . ") VALUES (" . implode(', ',array_keys($prep)) . ")");
$res = $sth->execute($prep);

I'm cheating here and assuming the keys in your first array are the column names in the SQL table. I'm also assuming you have PDO available. More can be found at http://php.net/manual/en/book.pdo.php

Add views in UIStackView programmatically

For the accepted answer when you try to hide any view inside stack view, the constraint works not correct.

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. 
    Try this: 
        (1) look at each constraint and try to figure out which you don't expect; 
        (2) find the code that added the unwanted constraint or constraints and fix it. 
(
    "<NSLayoutConstraint:0x618000086e50 UIView:0x7fc11c4051c0.height == 120   (active)>",
    "<NSLayoutConstraint:0x610000084fb0 'UISV-hiding' UIView:0x7fc11c4051c0.height == 0   (active)>"
)

Reason is when hide the view in stackView it will set the height to 0 to animate it.

Solution change the constraint priority as below.

import UIKit

class ViewController: UIViewController {

    let stackView = UIStackView()
    let a = UIView()
    let b = UIView()

    override func viewDidLoad() {
        super.viewDidLoad()

        a.backgroundColor = UIColor.red
        a.widthAnchor.constraint(equalToConstant: 200).isActive = true
        let aHeight = a.heightAnchor.constraint(equalToConstant: 120)
        aHeight.isActive = true
        aHeight.priority = 999

        let bHeight = b.heightAnchor.constraint(equalToConstant: 120)
        bHeight.isActive = true
        bHeight.priority = 999
        b.backgroundColor = UIColor.green
        b.widthAnchor.constraint(equalToConstant: 200).isActive = true

        view.addSubview(stackView)
        stackView.backgroundColor = UIColor.blue
        stackView.addArrangedSubview(a)
        stackView.addArrangedSubview(b)
        stackView.axis = .vertical
        stackView.distribution = .equalSpacing
        stackView.translatesAutoresizingMaskIntoConstraints = false
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    // Just add a button in xib file or storyboard and add connect this action.
    @IBAction func test(_ sender: Any) {
        a.isHidden = !a.isHidden
    }

}

Export result set on Dbeaver to CSV

Is there a reason you couldn't select your results and right click and choose Advanced Copy -> Advanced Copy? I'm on a Mac and this is how I always copy results to the clipboard for pasting.

TSQL DATETIME ISO 8601

Gosh, NO!!! You're asking for a world of hurt if you store formatted dates in SQL Server. Always store your dates and times and one of the SQL Server "date/time" datatypes (DATETIME, DATE, TIME, DATETIME2, whatever). Let the front end code resolve the method of display and only store formatted dates when you're building a staging table to build a file from. If you absolutely must display ISO date/time formats from SQL Server, only do it at display time. I can't emphasize enough... do NOT store formatted dates/times in SQL Server.

{Edit}. The reasons for this are many but the most obvious are that, even with a nice ISO format (which is sortable), all future date calculations and searches (search for all rows in a given month, for example) will require at least an implicit conversion (which takes extra time) and if the stored formatted date isn't the format that you currently need, you'll need to first convert it to a date and then to the format you want.

The same holds true for front end code. If you store a formatted date (which is text), it requires the same gyrations to display the local date format defined either by windows or the app.

My recommendation is to always store the date/time as a DATETIME or other temporal datatype and only format the date at display time.

Can I scale a div's height proportionally to its width using CSS?

One way usefull when you work with images, but can be used as workaround otherwise:

<html>
<head>
</head>
<style>
    #someContainer {
        width:50%;
        position: relative;
    }
    #par {
        width: 100%;
        background-color:red;
    }
    #image {
        width: 100%;
        visibility: hidden;
    }
    #myContent {
        position:absolute;
    }
</style>
<div id="someContainer">
    <div id="par">
        <div id="myContent">
            <p>
            Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
            </p>    
        </div>
        <img src="yourImage" id="image"/>
    </div>
</div>
</html>

To use replace yourImage with your image url. You use image with width / height ratio you desire.

div id="myContent" is here as example of workaround where myContent will overlay over image.

This works like: Parent div will adopt to the height of image, image height will adopt to width of parent. However image is hidden.

How to embed matplotlib in pyqt - for Dummies

It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg. FigureCanvasQTAgg and NavigationToolbar2QT are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure, Navigation and a single button that draws some random data. I've added comments to explain things.

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import random

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.clear()

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

Edit:

Updated to reflect comments and API changes.

  • NavigationToolbar2QTAgg changed with NavigationToolbar2QT
  • Directly import Figure instead of pyplot
  • Replace deprecated ax.hold(False) with ax.clear()

How do you hide the Address bar in Google Chrome for Chrome Apps?

Hitting F11 may work for you.(Full-screen mode)

It appears that the hiding the address bar without going full screen is no longer an option:http://productforums.google.com/forum/#!topic/chrome/d7LfleRNX7M

open program minimized via command prompt

I tried this commands in my PC.It is working fine....

To open notepad in minimized mode:

start /min "" "C:\Windows\notepad.exe"

To open MS word in minimized mode:

start /min "" "C:\Program Files\Microsoft Office\Office14\WINWORD.EXE"

Rounded corners for <input type='text' /> using border-radius.htc for IE

That won't work in IE<9 though, however, you can make IEs support that using:

CSS3Pie

PIE makes Internet Explorer 6-8 capable of rendering several of the most useful CSS3 decoration features.

How to run test cases in a specified file?

in intelliJ IDEA go-lang plugin (and i assume in jetbrains Gogland) you can just set the test kind to file under run > edit configurations

screenshot create go test on go file

Why use a ReentrantLock if one can use synchronized(this)?

A ReentrantLock is unstructured, unlike synchronized constructs -- i.e. you don't need to use a block structure for locking and can even hold a lock across methods. An example:

private ReentrantLock lock;

public void foo() {
  ...
  lock.lock();
  ...
}

public void bar() {
  ...
  lock.unlock();
  ...
}

Such flow is impossible to represent via a single monitor in a synchronized construct.


Aside from that, ReentrantLock supports lock polling and interruptible lock waits that support time-out. ReentrantLock also has support for configurable fairness policy, allowing more flexible thread scheduling.

The constructor for this class accepts an optional fairness parameter. When set true, under contention, locks favor granting access to the longest-waiting thread. Otherwise this lock does not guarantee any particular access order. Programs using fair locks accessed by many threads may display lower overall throughput (i.e., are slower; often much slower) than those using the default setting, but have smaller variances in times to obtain locks and guarantee lack of starvation. Note however, that fairness of locks does not guarantee fairness of thread scheduling. Thus, one of many threads using a fair lock may obtain it multiple times in succession while other active threads are not progressing and not currently holding the lock. Also note that the untimed tryLock method does not honor the fairness setting. It will succeed if the lock is available even if other threads are waiting.


ReentrantLock may also be more scalable, performing much better under higher contention. You can read more about this here.

This claim has been contested, however; see the following comment:

In the reentrant lock test, a new lock is created each time, thus there is no exclusive locking and the resulting data is invalid. Also, the IBM link offers no source code for the underlying benchmark so its impossible to characterize whether the test was even conducted correctly.


When should you use ReentrantLocks? According to that developerWorks article...

The answer is pretty simple -- use it when you actually need something it provides that synchronized doesn't, like timed lock waits, interruptible lock waits, non-block-structured locks, multiple condition variables, or lock polling. ReentrantLock also has scalability benefits, and you should use it if you actually have a situation that exhibits high contention, but remember that the vast majority of synchronized blocks hardly ever exhibit any contention, let alone high contention. I would advise developing with synchronization until synchronization has proven to be inadequate, rather than simply assuming "the performance will be better" if you use ReentrantLock. Remember, these are advanced tools for advanced users. (And truly advanced users tend to prefer the simplest tools they can find until they're convinced the simple tools are inadequate.) As always, make it right first, and then worry about whether or not you have to make it faster.


One final aspect that's gonna become more relevant in the near future has to do with Java 15 and Project Loom. In the (new) world of virtual threads, the underlying scheduler would be able to work much better with ReentrantLock than it's able to do with synchronized, that's true at least in the initial Java 15 release but may be optimized later.

In the current Loom implementation, a virtual thread can be pinned in two situations: when there is a native frame on the stack — when Java code calls into native code (JNI) that then calls back into Java — and when inside a synchronized block or method. In those cases, blocking the virtual thread will block the physical thread that carries it. Once the native call completes or the monitor released (the synchronized block/method is exited) the thread is unpinned.

If you have a common I/O operation guarded by a synchronized, replace the monitor with a ReentrantLock to let your application benefit fully from Loom’s scalability boost even before we fix pinning by monitors (or, better yet, use the higher-performance StampedLock if you can).

What is the difference between JDK and JRE?

JVM, JRE, JDK - these are all the backbone of Java language. Each component work separately. JDK and JRE physically exist but JVM is an abstract machine that means it does not physically exist.

JVM is the subsystem of JDK and JRE which is used to check the intermediate code known as "bytecode". It first loads the "class file" (having .c extension) generated by the Java compiler (javac) through JVM subsystem classloader and classified memory location (class area, stack, heap and pc registers) according to their use. Then it checks all the bytecode to ensure that it is returned in Java and all memory accessibility access by the network. The interpreter's work starts after that where it checks the whole program line by line. The results are finally shown in the console/browser/application through JRE (Java Runtime Environment) which runtime facilities.

JRE is also a subsystem of JDK which provides runtime facilities like JVM, classes, executable files like .jar file, etc.

JDK stands for Java Development Kit. It contains all necessary components used in Java programming such as class, method, swing, AWT, package, Java (interpreter), javac (compiler), appletviewer (applet application viewer), etc. To conclude, it contains every file required for developing applications, whether standalone or web-based.

How to get an IFrame to be responsive in iOS Safari?

For me CSS solutions didn't work. But setting the width programmatically does the job. On iframe load set the width programmatically:

 $('iframe').width('100%');

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)
lst

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

How to access Spring MVC model object in javascript file?

I recently faced the same need. So I tried Aurand's way but it seems the code is missing ${}. So the code inside SomeJsp.jsp <head></head>is:

<script>
  var model=[];
  model.paramOne="${model.paramOne}";
  model.paramTwo="${model.paramTwo}";
  model.paramThree="${model.paramThree}";
</script>

Note that you can't asssign using var model = ${model} as it will assign a java object reference. So to access this in external JS:

$(document).ready(function() {
   alert(model.paramOne);
});

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

How to call a MySQL stored procedure from within PHP code?

You can call a stored procedure using the following syntax:

$result = mysql_query('CALL getNodeChildren(2)');

Why do I get "Procedure expects parameter '@statement' of type 'ntext/nchar/nvarchar'." when I try to use sp_executesql?

I had missed another tiny detail: I forgot the brackets "(100)" behind NVARCHAR.

batch file to list folders within a folder to one level

I tried this command to display the list of files in the directory.

dir /s /b > List.txt

In the file it displays the list below.

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppMgr.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\XmppSDK.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Plantronics

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\SennheiserJabberPlugin.dll

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco

C:\Program Files (x86)\Cisco Systems\Cisco Jabber\accessories\Logitech\LogiUCPluginForCisco\lucpcisco.dll

What is want to do is only to display sub-directory not the full directory path.

Just like this:

Cisco Jabber\XmppMgr.dll Cisco Jabber\XmppSDK.dll

Cisco Jabber\accessories\JabraJabberPlugin.dll

Cisco Jabber\accessories\Logitech

Cisco Jabber\accessories\Plantronics

Cisco Jabber\accessories\SennheiserJabberPlugin.dll

How do you detect the clearing of a "search" HTML5 input?

It doesn't seem like you can access this in browser. The search input is a Webkit HTML wrapper for the Cocoa NSSearchField. The cancel button seems to be contained within the browser client code with no external reference available from the wrapper.

Sources:

Looks like you'll have to figure it out through mouse position on click with something like:

$('input[type=search]').bind('click', function(e) {
  var $earch = $(this);
  var offset = $earch.offset();

  if (e.pageX > offset.left + $earch.width() - 16) { // X button 16px wide?
    // your code here
  }
});

How do you deploy Angular apps?

With Angular CLI, you can use the following command:

ng build --prod

It generates a dist folder with all you need to deploy the application.

If you have no practice with web servers, I recommend you to use Angular to Cloud. You just need to compress the dist folder as zip file and upload it in the platform.

IOError: [Errno 22] invalid mode ('r') or filename: 'c:\\Python27\test.txt'

always use 'r' to get a raw string when you want to avoid escape.

test_file=open(r'c:\Python27\test.txt','r')

Python: TypeError: object of type 'NoneType' has no len()

shuffle(names) is an in-place operation. Drop the assignment.

This function returns None and that's why you have the error:

TypeError: object of type 'NoneType' has no len()

Quicksort: Choosing the pivot

It is easier to break the quicksort into three sections doing this

  1. Exchange or swap data element function
  2. The partition function
  3. Processing the partitions

It is only slightly more inefficent than one long function but is alot easier to understand.

Code follows:

/* This selects what the data type in the array to be sorted is */

#define DATATYPE long

/* This is the swap function .. your job is to swap data in x & y .. how depends on
data type .. the example works for normal numerical data types .. like long I chose
above */

void swap (DATATYPE *x, DATATYPE *y){  
  DATATYPE Temp;

  Temp = *x;        // Hold current x value
  *x = *y;          // Transfer y to x
  *y = Temp;        // Set y to the held old x value
};


/* This is the partition code */

int partition (DATATYPE list[], int l, int h){

  int i;
  int p;          // pivot element index
  int firsthigh;  // divider position for pivot element

  // Random pivot example shown for median   p = (l+h)/2 would be used
  p = l + (short)(rand() % (int)(h - l + 1)); // Random partition point

  swap(&list[p], &list[h]);                   // Swap the values
  firsthigh = l;                                  // Hold first high value
  for (i = l; i < h; i++)
    if(list[i] < list[h]) {                 // Value at i is less than h
      swap(&list[i], &list[firsthigh]);   // So swap the value
      firsthigh++;                        // Incement first high
    }
  swap(&list[h], &list[firsthigh]);           // Swap h and first high values
  return(firsthigh);                          // Return first high
};



/* Finally the body sort */

void quicksort(DATATYPE list[], int l, int h){

  int p;                                      // index of partition 
  if ((h - l) > 0) {
    p = partition(list, l, h);              // Partition list 
    quicksort(list, l, p - 1);        // Sort lower partion
    quicksort(list, p + 1, h);              // Sort upper partition
  };
};

Android Studio gradle takes too long to build

In Android Studio, above Version 3.6, There is a new location to toggle Gradle's offline mode To enable or disable Gradle's offline mode.

To enable or disable Gradle's offline mode, select View > Tool Windows > Gradle from the menu. In the top bar of the Gradle window, click Toggle Offline Mode (near settings icon).

enter image description here

It's a little bit confusing on the icon, anyway offline mode is enabled when the toggle button is highlighted. :)

How to reload current page in ReactJS?

Since React eventually boils down to plain old JavaScript, you can really place it anywhere! For instance, you could place it on a componentDidMount() in a React class.

For you edit, you may want to try something like this:

class Component extends React.Component {
  constructor(props) {
    super(props);
    this.onAddBucket = this.onAddBucket.bind(this);
  }
  componentWillMount() {
    this.setState({
      buckets: {},
    })
  }
  componentDidMount() {
    this.onAddBucket();
  }
  onAddBucket() {
    let self = this;
    let getToken = localStorage.getItem('myToken');
    var apiBaseUrl = "...";
    let input = {
      "name" :  this.state.fields["bucket_name"]
    }
    axios.defaults.headers.common['Authorization'] = getToken;
    axios.post(apiBaseUrl+'...',input)
    .then(function (response) {
      if (response.data.status == 200) {
        this.setState({
          buckets: this.state.buckets.concat(response.data.buckets),
        });
      } else {
        alert(response.data.message);
      }
    })
    .catch(function (error) {
      console.log(error);
    });
  }
  render() {
    return (
      {this.state.bucket}
    );
  }
}

How can you tell when a layout has been drawn?

When onMeasure is called the view gets its measured width/height. After this, you can call layout.getMeasuredHeight().

How to install mongoDB on windows?

Pretty good documentation is provided on the MongoDB website

Install MongoDB

  1. Determine which MongoDB build you need.

    There are three builds of MongoDB for Windows:

    MongoDB for Windows Server 2008 R2 edition (i.e. 2008R2) runs only on Windows Server 2008 R2, Windows 7 64-bit, and newer versions of Windows. This build takes advantage of recent enhancements to the Windows Platform and cannot operate on older versions of Windows.

    MongoDB for Windows 64-bit runs on any 64-bit version of Windows newer than Windows XP, including Windows Server 2008 R2 and Windows 7 64-bit.

    MongoDB for Windows 32-bit runs on any 32-bit version of Windows newer than Windows XP. 32-bit versions of MongoDB are only intended for older systems and for use in testing and development systems. 32-bit versions of MongoDB only support databases smaller than 2GB.

    To find which version of Windows you are running, enter the following command in the Command Prompt:

    wmic os get osarchitecture
    
  2. Download MongoDB for Windows.

    Download the latest production release of MongoDB from the MongoDB downloads page. Ensure you download the correct version of MongoDB for your Windows system. The 64-bit versions of MongoDB does not work with 32-bit Windows.

  3. Install the downloaded file.

    In Windows Explorer, locate the downloaded MongoDB msi file, which typically is located in the default Downloads folder. Double-click the msi file. A set of screens will appear to guide you through the installation process.

  4. Move the MongoDB folder to another location (optional).

    To move the MongoDB folder, you must issue the move command as an Administrator. For example, to move the folder to C:\mongodb:

    Select Start Menu > All Programs > Accessories.

    Right-click Command Prompt and select Run as Administrator from the popup menu.

    Issue the following commands:

    cd \
    move C:\mongodb-win32-* C:\mongodb
    

    MongoDB is self-contained and does not have any other system dependencies. You can run MongoDB from any folder you choose. You may install MongoDB in any folder (e.g. D:\test\mongodb)

Run MongoDB

Warning:

Do not make mongod.exe visible on public networks without running in “Secure Mode” with the auth setting. MongoDB is designed to be run in trusted environments, and the database does not enable “Secure Mode” by default.

  1. Set up the MongoDB environment.

    MongoDB requires a data directory to store all data. MongoDB’s default data directory path is \data\db. Create this folder using the following commands from a Command Prompt:

    md \data\db
    

    You can specify an alternate path for data files using the --dbpath option to mongod.exe, for example:

    C:\mongodb\bin\mongod.exe --dbpath d:\test\mongodb\data
    

    If your path includes spaces, enclose the entire path in double quotes, for example:

    C:\mongodb\bin\mongod.exe --dbpath "d:\test\mongo db data"
    
  2. Start MongoDB.

    To start MongoDB, run mongod.exe. For example, from the Command Prompt:

    C:\Program Files\MongoDB\bin\mongod.exe
    

    This starts the main MongoDB database process. The waiting for connections message in the console output indicates that the mongod.exe process is running successfully.

    Depending on the security level of your system, Windows may pop up a Security Alert dialog box about blocking “some features” of C:\Program Files\MongoDB\bin\mongod.exe from communicating on networks. All users should select Private Networks, such as my home or work network and click Allow access. For additional information on security and MongoDB, please see the Security Documentation.

  3. Connect to MongoDB.

    To connect to MongoDB through the mongo.exe shell, open another Command Prompt. When connecting, specify the data directory if necessary. This step provides several example connection commands.

    If your MongoDB installation uses the default data directory, connect without specifying the data directory:

    C:\mongodb\bin\mongo.exe
    

    If you installation uses a different data directory, specify the directory when connecting, as in this example:

    C:\mongodb\bin\mongod.exe --dbpath d:\test\mongodb\data
    

    If your path includes spaces, enclose the entire path in double quotes. For example:

    C:\mongodb\bin\mongod.exe --dbpath "d:\test\mongo db data"
    

    If you want to develop applications using .NET, see the documentation of C# and MongoDB for more information.

  4. Begin using MongoDB.

    To begin using MongoDB, see Getting Started with MongoDB. Also consider the Production Notes document before deploying MongoDB in a production environment.

    Later, to stop MongoDB, press Control+C in the terminal where the mongod instance is running.

Configure a Windows Service for MongoDB

Note:

There is a known issue for MongoDB 2.6.0, SERVER-13515, which prevents the use of the instructions in this section. For MongoDB 2.6.0, use Manually Create a Windows Service for MongoDB to create a Windows Service for MongoDB instead.

  1. Configure directories and files.

    Create a configuration file and a directory path for MongoDB log output (logpath):

    Create a specific directory for MongoDB log files:

    md "C:\Program Files\MongoDB\log"
    

    In the Command Prompt, create a configuration file for the logpath option for MongoDB:

    echo logpath=C:\Program Files\MongoDB\log\mongo.log > "C:\Program Files\MongoDB\mongod.cfg"
    
  2. Run the MongoDB service.

    Run all of the following commands in Command Prompt with “Administrative Privileges:”

    Install the MongoDB service. For --install to succeed, you must specify the logpath run-time option.

    "C:\Program Files\MongoDB\bin\mongod.exe" --config "C:\Program Files\MongoDB\mongod.cfg" --install
    

    Modify the path to the mongod.cfg file as needed.

    To use an alternate dbpath, specify the path in the configuration file (e.g. C:\Program Files\MongoDB\mongod.cfg) or on the command line with the --dbpath option.

    If the dbpath directory does not exist, mongod.exe will not start. The default value for dbpath is \data\db.

    If needed, you can install services for multiple instances of mongod.exe or mongos.exe. Install each service with a unique --serviceName and --serviceDisplayName. Use multiple instances only when sufficient system resources exist and your system design requires it.

  3. Stop or remove the MongoDB service as needed.

    To stop the MongoDB service use the following command:

    net stop MongoDB
    

    To remove the MongoDB service use the following command:

    "C:\Program Files\MongoDB\bin\mongod.exe" --remove
    

Manually Create a Windows Service for MongoDB

The following procedure assumes you have installed MongoDB using the MSI installer, with the default path C:\Program Files\MongoDB 2.6 Standard.

If you have installed in an alternative directory, you will need to adjust the paths as appropriate.

  1. Open an Administrator command prompt.

    Windows 7 / Vista / Server 2008 (and R2)

    Press Win + R, then type cmd, then press Ctrl + Shift + Enter.

    Windows 8

    Press Win + X, then press A.

    Execute the remaining steps from the Administrator command prompt.

  2. Create directories.

    Create directories for your database and log files:

    mkdir c:\data\db
    mkdir c:\data\log
    
  3. Create a configuration file.

    Create a configuration file. This file can include any of the configuration options for mongod, but must include a valid setting for logpath:

    The following creates a configuration file, specifying both the logpath and the dbpath settings in the configuration file:

    echo logpath=c:\data\log\mongod.log> "C:\Program Files\MongoDB 2.6 Standard\mongod.cfg"
    echo dbpath=c:\data\db>> "C:\Program Files\MongoDB 2.6 Standard\mongod.cfg"
    
  4. Create the MongoDB service.

    Create the MongoDB service.

    sc.exe create MongoDB binPath= "\"C:\Program Files\MongoDB 2.6 Standard\bin\mongod.exe\" --service --config=\"C:\Program Files\MongoDB 2.6 Standard\mongod.cfg\"" DisplayName= "MongoDB 2.6 Standard" start= "auto"
    

    sc.exe requires a space between “=” and the configuration values (eg “binPath=”), and a “” to escape double quotes.

    If successfully created, the following log message will display:

    [SC] CreateService SUCCESS
    
  5. Start the MongoDB service.

    net start MongoDB
    
  6. Stop or remove the MongoDB service as needed.

    To stop the MongoDB service, use the following command:

    net stop MongoDB
    

    To remove the MongoDB service, first stop the service and then run the following command:

    sc.exe delete MongoDB
    

How to copy a file to a remote server in Python using SCP or SSH?

You can call the scp bash command (it copies files over SSH) with subprocess.run:

import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "[email protected]:/path/to/foo.bar"])

If you're creating the file that you want to send in the same Python program, you'll want to call subprocess.run command outside the with block you're using to open the file (or call .close() on the file first if you're not using a with block), so you know it's flushed to disk from Python.

You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password).

Get the current date and time

DateTimePicker1.value = Format(Date.Now)

Why does JSHint throw a warning if I am using const?

In a new version of Dreamweaver to solve this error

  • Go to Edit->Preference->Linting
  • And the go-to js Edit rule set and past

    "jshintConfig":{ "esversion": 6 }

How can I get my Twitter Bootstrap buttons to right align?

<ul>
    <li class="span4">One <input class="btn btn-small" value="test"></li>
    <li class="span4">Two <input class="btn btn-small" value="test2"></li>
</ul>

One way would be to apply this style to your list items in order to keep them inline

or

<ul>
    <li>One <input class="btn" value="test"></li>
    <li>Two <input class="btn" value="test2"></li>
</ul>

in CSS

li {
    line-height: 20px;
    margin: 5px;
    padding: 2px;
}

Button Listener for button in fragment in android

    //sure run it i will also test it
//we make a class that extends with the fragment
    public class Example_3_1 extends Fragment  implements OnClickListener
    {
       View vi;
        EditText t;
        EditText t1;
        Button bu;
 // that are by defult function of fragment extend class
     @Override
       public View onCreateView(LayoutInflater inflater,ViewGroup container,BundlesavedInstanceState) 
       {        
           vi=inflater.inflate(R.layout.example_3_1, container, false);// load the xml file 
           bu=(Button) vi.findViewById(R.id.button1);// get button id from example_3_1 xml file
           bu.setOnClickListener(this); //on button appay click listner
           t=(EditText) vi.findViewById(R.id.editText1);// id get from example_3_1 xml file
           t1=(EditText) vi.findViewById(R.id.editText2);
          return vi; // return the view object,that set the xml file  example_3_1 xml file
       }
       @Override
       public void onClick(View v)//on button click that called
       {

          switch(v.getId())// on run time get id what button os click and get id
          {
          case R.id.button1:        // it mean if button1 click then this work
           t.setText("UMTien");     //set text 
           t1.setText("programming");
           break;
          }
    }     }

Is it possible to preview stash contents in git?

I'm a fan of gitk's graphical UI to visualize git repos. You can view the last item stashed with:

gitk stash

You can also use view any of your stashed changes (as listed by git stash list). For example:

gitk stash@{2}

In the below screenshot, you can see the stash as a commit in the upper-left, when and where it came from in commit history, the list of files modified on the bottom right, and the line-by-line diff in the lower-left. All while the stash is still tucked away.

gitk viewing a stash

How do I reflect over the members of dynamic object?

Requires Newtonsoft Json.Net

A little late, but I came up with this. It gives you just the keys and then you can use those on the dynamic:

public List<string> GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
{
    JObject attributesAsJObject = dynamicToGetPropertiesFor;
    Dictionary<string, object> values = attributesAsJObject.ToObject<Dictionary<string, object>>();
    List<string> toReturn = new List<string>();
    foreach (string key in values.Keys)
    {
        toReturn.Add(key);                
    }
    return toReturn;
}

Then you simply foreach like this:

foreach(string propertyName in GetPropertyKeysForDynamic(dynamicToGetPropertiesFor))
{
    dynamic/object/string propertyValue = dynamicToGetPropertiesFor[propertyName];
    // And
    dynamicToGetPropertiesFor[propertyName] = "Your Value"; // Or an object value
}

Choosing to get the value as a string or some other object, or do another dynamic and use the lookup again.

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

c++ string array initialization

In C++11 you can. A note beforehand: Don't new the array, there's no need for that.

First, string[] strArray is a syntax error, that should either be string* strArray or string strArray[]. And I assume that it's just for the sake of the example that you don't pass any size parameter.

#include <string>

void foo(std::string* strArray, unsigned size){
  // do stuff...
}

template<class T>
using alias = T;

int main(){
  foo(alias<std::string[]>{"hi", "there"}, 2);
}

Note that it would be better if you didn't need to pass the array size as an extra parameter, and thankfully there is a way: Templates!

template<unsigned N>
void foo(int const (&arr)[N]){
  // ...
}

Note that this will only match stack arrays, like int x[5] = .... Or temporary ones, created by the use of alias above.

int main(){
  foo(alias<int[]>{1, 2, 3});
}

What's the proper way to install pip, virtualenv, and distribute for Python?

There is no problem to do sudo python setup.py install, if you're sure it's what you want to do.

The difference is that it will use the site-packages directory of your OS as a destination for .py files to be copied.

so, if you want pip to be accessible os wide, that's probably the way to go. I do not say that others way are bad, but this is probably fair enough.

How can I debug git/git-shell related problems?

Have you tried adding the verbose (-v) operator when you clone?

git clone -v git://git.kernel.org/pub/scm/.../linux-2.6 my2.6

How to get browser width using JavaScript code?

From W3schools and its cross browser back to the dark ages of IE!

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var w = window.innerWidth
|| document.documentElement.clientWidth
|| document.body.clientWidth;

var h = window.innerHeight
|| document.documentElement.clientHeight
|| document.body.clientHeight;

var x = document.getElementById("demo");
x.innerHTML = "Browser inner window width: " + w + ", height: " + h + ".";

alert("Browser inner window width: " + w + ", height: " + h + ".");

</script>

</body>
</html>

How to install ia32-libs in Ubuntu 14.04 LTS (Trusty Tahr)

The best answer I have ever seen is How to run 32-bit applications on Ubuntu 64-bit?

sudo dpkg --add-architecture i386
sudo apt-get update
sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386
sudo ./adb

How can I force input to uppercase in an ASP.NET textbox?

You can intercept the key press events, cancel the lowercase ones, and append their uppercase versions to the input:

window.onload = function () {
    var input = document.getElementById("test");

    input.onkeypress = function () {
        // So that things work both on Firefox and Internet Explorer.
        var evt = arguments[0] || event;
        var char = String.fromCharCode(evt.which || evt.keyCode);

        // Is it a lowercase character?
        if (/[a-z]/.test(char)) {
            // Append its uppercase version
            input.value += char.toUpperCase();

            // Cancel the original event
            evt.cancelBubble = true;
            return false;
        }
    }
};

This works in both Firefox and Internet Explorer. You can see it in action here.

How to declare a variable in a PostgreSQL query

Using a Temp Table outside of pl/PgSQL

Outside of using pl/pgsql or other pl/* language as suggested, this is the only other possibility I could think of.

begin;
select 5::int as var into temp table myvar;
select *
  from somewhere s, myvar v
 where s.something = v.var;
commit;

two divs the same line, one dynamic width, one fixed

HTML:

<div id="parent">
  <div class="right"></div>
  <div class="left"></div>
</div>

(div.right needs to be before div.left in the HTML markup)

CSS:

.right {
float:right;
width:200px;
}

Serialize and Deserialize Json and Json Array in Unity

you have to add [System.Serializable] to PlayerItem class ,like this:

using System;
[System.Serializable]
public class PlayerItem   {
    public string playerId;
    public string playerLoc;
    public string playerNick;
}

How do I find out what type each object is in a ArrayList<Object>?

Instanceof works if you don't depend on specific classes, but also keep in mind that you can have nulls in the list, so obj.getClass() will fail, but instanceof always returns false on null.

Python POST binary data

This has nothing to do with a malformed upload. The HTTP error clearly specifies 401 unauthorized, and tells you the CSRF token is invalid. Try sending a valid CSRF token with the upload.

More about csrf tokens here:

What is a CSRF token ? What is its importance and how does it work?

How to append output to the end of a text file

I'd suggest you do two things:

  1. Use >> in your shell script to append contents to particular file. The filename can be fixed or using some pattern.
  2. Setup a hourly cronjob to trigger the shell script

How to set ObjectId as a data type in mongoose

The solution provided by @dex worked for me. But I want to add something else that also worked for me: Use

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: [{
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }]
})

if what you want to create is an Array reference. But if what you want is an Object reference, which is what I think you might be looking for anyway, remove the brackets from the value prop, like this:

let UserSchema = new Schema({
   username: {
     type: String
   },
   events: {
     type: ObjectId,
     ref: 'Event' // Reference to some EventSchema
   }
})

Look at the 2 snippets well. In the second case, the value prop of key events does not have brackets over the object def.

Convert Time DataType into AM PM Format:

    select right(convert(varchar(20),getdate(),100),7)

How to validate a url in Python? (Malformed or not)

All of the above solutions recognize a string like "http://www.google.com/path,www.yahoo.com/path" as valid. This solution always works as it should

import re

# URL-link validation
ip_middle_octet = u"(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5]))"
ip_last_octet = u"(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))"

URL_PATTERN = re.compile(
                        u"^"
                        # protocol identifier
                        u"(?:(?:https?|ftp|rtsp|rtp|mmp)://)"
                        # user:pass authentication
                        u"(?:\S+(?::\S*)?@)?"
                        u"(?:"
                        u"(?P<private_ip>"
                        # IP address exclusion
                        # private & local networks
                        u"(?:localhost)|"
                        u"(?:(?:10|127)" + ip_middle_octet + u"{2}" + ip_last_octet + u")|"
                        u"(?:(?:169\.254|192\.168)" + ip_middle_octet + ip_last_octet + u")|"
                        u"(?:172\.(?:1[6-9]|2\d|3[0-1])" + ip_middle_octet + ip_last_octet + u"))"
                        u"|"
                        # IP address dotted notation octets
                        # excludes loopback network 0.0.0.0
                        # excludes reserved space >= 224.0.0.0
                        # excludes network & broadcast addresses
                        # (first & last IP address of each class)
                        u"(?P<public_ip>"
                        u"(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])"
                        u"" + ip_middle_octet + u"{2}"
                        u"" + ip_last_octet + u")"
                        u"|"
                        # host name
                        u"(?:(?:[a-z\u00a1-\uffff0-9_-]-?)*[a-z\u00a1-\uffff0-9_-]+)"
                        # domain name
                        u"(?:\.(?:[a-z\u00a1-\uffff0-9_-]-?)*[a-z\u00a1-\uffff0-9_-]+)*"
                        # TLD identifier
                        u"(?:\.(?:[a-z\u00a1-\uffff]{2,}))"
                        u")"
                        # port number
                        u"(?::\d{2,5})?"
                        # resource path
                        u"(?:/\S*)?"
                        # query string
                        u"(?:\?\S*)?"
                        u"$",
                        re.UNICODE | re.IGNORECASE
                       )
def url_validate(url):   
    """ URL string validation
    """                                                                                                                                                      
    return re.compile(URL_PATTERN).match(url)

ORA-01653: unable to extend table by in tablespace ORA-06512

You could also turn on autoextend for the whole database using this command:

ALTER DATABASE DATAFILE 'C:\ORACLEXE\APP\ORACLE\ORADATA\XE\SYSTEM.DBF'
AUTOEXTEND ON NEXT 1M MAXSIZE 1024M;

Just change the filepath to point to your system.dbf file.

Credit Here

Check if a parameter is null or empty in a stored procedure

You can try this:-

IF NULLIF(ISNULL(@PreviousStartDate,''),'') IS NULL
SET @PreviousStartdate = '01/01/2010'

How do I redirect in expressjs while passing some context?

There are a few ways of passing data around to different routes. The most correct answer is, of course, query strings. You'll need to ensure that the values are properly encodeURIComponent and decodeURIComponent.

app.get('/category', function(req, res) {
  var string = encodeURIComponent('something that would break');
  res.redirect('/?valid=' + string);
});

You can snag that in your other route by getting the parameters sent by using req.query.

app.get('/', function(req, res) {
  var passedVariable = req.query.valid;
  // Do something with variable
});

For more dynamic way you can use the url core module to generate the query string for you:

const url = require('url');    
app.get('/category', function(req, res) {
    res.redirect(url.format({
       pathname:"/",
       query: {
          "a": 1,
          "b": 2,
          "valid":"your string here"
        }
     }));
 });

So if you want to redirect all req query string variables you can simply do

res.redirect(url.format({
       pathname:"/",
       query:req.query,
     });
 });

And if you are using Node >= 7.x you can also use the querystring core module

const querystring = require('querystring');    
app.get('/category', function(req, res) {
      const query = querystring.stringify({
          "a": 1,
          "b": 2,
          "valid":"your string here"
      });
      res.redirect('/?' + query);
 });

Another way of doing it is by setting something up in the session. You can read how to set it up here, but to set and access variables is something like this:

app.get('/category', function(req, res) {
  req.session.valid = true;
  res.redirect('/');
});

And later on after the redirect...

app.get('/', function(req, res) {
  var passedVariable = req.session.valid;
  req.session.valid = null; // resets session variable
  // Do something
});

There is also the option of using an old feature of Express, req.flash. Doing so in newer versions of Express will require you to use another library. Essentially it allows you to set up variables that will show up and reset the next time you go to a page. It's handy for showing errors to users, but again it's been removed by default. EDIT: Found a library that adds this functionality.

Hopefully that will give you a general idea how to pass information around in an Express application.

How to manually deploy artifacts in Nexus Repository Manager OSS 3

For Windows:

mvn deploy:deploy-file -DgroupId=joda-time -DartifactId=joda-time -Dversion=2.7 -Dpackaging=jar -Dfile=joda-time-2.7.jar 
-DgeneratePom=true -DrepositoryId=[Your ID] -Durl=[YourURL]

.NET Events - What are object sender & EventArgs e?

The sender is the control that the action is for (say OnClick, it's the button).

The EventArgs are arguments that the implementor of this event may find useful. With OnClick it contains nothing good, but in some events, like say in a GridView 'SelectedIndexChanged', it will contain the new index, or some other useful data.

What Chris is saying is you can do this:

protected void someButton_Click (object sender, EventArgs ea)
{
    Button someButton = sender as Button;
    if(someButton != null)
    {
        someButton.Text = "I was clicked!";
    }
}

Is it possible to program iPhone in C++

Having some experience of this, you can indeed use C++ code for your "core" code, but you have to use objective-C for anything iPhone specific.

Don't try to force Objective-C to act like C++. At first it will seem to you this is possible, but the resulting code really won't work well with Cocoa, and you will get very confused as to what is going on. Take the time to learn properly, without any C++ around, how to build GUIs and iPhone applications, then link in your C++ base.

How to embed a YouTube channel into a webpage

Seems like the accepted answer does not work anymore. I found the correct method from another post: https://stackoverflow.com/a/46811403/6368026

Now you should use:

http://www.youtube.com/embed/videoseries?list=USERID And the USERID is your youtube user id with 'UU' appended.

For example, if your user id is TlQ5niAIDsLdEHpQKQsupg then you should put UUTlQ5niAIDsLdEHpQKQsupg. If you only have the channel id (which you can find in your channel URL) then just replace the first two characters (UC) with UU.

So in the end you would have an URL like this:

http://www.youtube.com/embed/videoseries?list=UUTlQ5niAIDsLdEHpQKQsupg

Installing NumPy and SciPy on 64-bit Windows (with Pip)

Follow these steps:

  1. Open CMD as administrator
  2. Enter this command : cd..
  3. cd..
  4. cd Program Files\Python38\Scripts
  5. Download the package you want and put it in Python38\Scripts folder.
  6. pip install packagename.whl
  7. Done

You can write your python version instead of "38"

Configure Flask dev server to be visible across the network

Create file .flaskenv in the project root directory.

The parameters in this file are typically:

FLASK_APP=app.py
FLASK_ENV=development
FLASK_RUN_HOST=[dev-host-ip]
FLASK_RUN_PORT=5000

If you have a virtual environment, activate it and do a pip install python-dotenv .

This package is going to use the .flaskenv file, and declarations inside it will be automatically imported across terminal sessions.

Then you can do flask run

Difference between h:button and h:commandButton

This is taken from the book - The Complete Reference by Ed Burns & Chris Schalk

h:commandButton vs h:button

What’s the difference between h:commandButton|h:commandLink and h:button|h:link ?

The latter two components were introduced in 2.0 to enable bookmarkable JSF pages, when used in concert with the View Parameters feature.

There are 3 main differences between h:button|h:link and h:commandButton|h:commandLink.

First, h:button|h:link causes the browser to issue an HTTP GET request, while h:commandButton|h:commandLink does a form POST. This means that any components in the page that have values entered by the user, such as text fields, checkboxes, etc., will not automatically be submitted to the server when using h:button|h:link. To cause values to be submitted with h:button|h:link, extra action has to be taken, using the “View Parameters” feature.

The second main difference between the two kinds of components is that h:button|h:link has an outcome attribute to describe where to go next while h:commandButton|h:commandLink uses an action attribute for this purpose. This is because the former does not result in an ActionEvent in the event system, while the latter does.

Finally, and most important to the complete understanding of this feature, the h:button|h:link components cause the navigation system to be asked to derive the outcome during the rendering of the page, and the answer to this question is encoded in the markup of the page. In contrast, the h:commandButton|h:commandLink components cause the navigation system to be asked to derive the outcome on the POSTBACK from the page. This is a difference in timing. Rendering always happens before POSTBACK.

How to sleep the thread in node.js without affecting other threads?

When working with async functions or observables provided by 3rd party libraries, for example Cloud firestore, I've found functions the waitFor method shown below (TypeScript, but you get the idea...) to be helpful when you need to wait on some process to complete, but you don't want to have to embed callbacks within callbacks within callbacks nor risk an infinite loop.

This method is sort of similar to a while (!condition) sleep loop, but yields asynchronously and performs a test on the completion condition at regular intervals till true or timeout.

export const sleep = (ms: number) => {
    return new Promise(resolve => setTimeout(resolve, ms))
}
/**
 * Wait until the condition tested in a function returns true, or until 
 * a timeout is exceeded.
 * @param interval The frenequency with which the boolean function contained in condition is called.
 * @param timeout  The maximum time to allow for booleanFunction to return true
 * @param booleanFunction:  A completion function to evaluate after each interval. waitFor will return true as soon as the completion function returns true.   
 */
export const waitFor = async function (interval: number, timeout: number,
    booleanFunction: Function): Promise<boolean> {
    let elapsed = 1;
    if (booleanFunction()) return true;
    while (elapsed < timeout) {
        elapsed += interval;
        await sleep(interval);
        if (booleanFunction()) {
            return true;
        }
    }
    return false;
}

The say you have a long running process on your backend you want to complete before some other task is undertaken. For example if you have a function that totals a list of accounts, but you want to refresh the accounts from the backend before you calculate, you can do something like this:

async recalcAccountTotals() : number {
     this.accountService.refresh();   //start the async process.
     if (this.accounts.dirty) {
           let updateResult = await waitFor(100,2000,()=> {return !(this.accounts.dirty)})
     }
 if(!updateResult) { 
      console.error("Account refresh timed out, recalc aborted");
      return NaN;
    }
 return ... //calculate the account total. 
}

How can I find the number of days between two Date objects in Ruby?

all of these steered me to the correct result, but I wound up doing

DateTime.now.mjd - DateTime.parse("01-01-1995").mjd

How to insert spaces/tabs in text using HTML/CSS

To insert tab space between two words/sentences I usually use

&emsp; and &ensp;

Hide options in a select list using jQuery

I implemented a solution using a function that filters a combobox (<select>) based on custom data- attributes. This solution supports:

  • Having an <option> to show when the filter would leave the select empty.
  • Respects existing selected attributes.
  • <option> elements without the data-filter attribute are left untouched.

Tested with jQuery 2.1.4 and Firefox, Chrome, Safari and IE 10+.

This is the example HTML:

<select id="myCombobox">
  <option data-filter="1" value="AAA">Option 1</option>
  <option data-filter="1" value="BBB">Option 2</option>
  <option data-filter="2" value="CCC">Option 3</option>
  <option data-filter="2" value="DDD">Option 4</option>
  <option data-filter="3" value="EEE">Option 5</option>
  <option data-filter="3" value="FFF">Option 6</option>
  <option data-filter-emptyvalue disabled>No Options</option>
</select>

The jQuery code for the filtering:

function filterCombobox(selectObject, filterValue, autoSelect) {

  var fullData = selectObject.data("filterdata-values");
  var emptyValue = selectObject.data("filterdata-emptyvalue");

  // Initialize if first time.
  if (!fullData) {
    fullData = selectObject.find("option[data-filter]").detach();
    selectObject.data("filterdata-values", fullData);
    emptyValue = selectObject.find("option[data-filter-emptyvalue]").detach();
    selectObject.data("filterdata-emptyvalue", emptyValue);
    selectObject.addClass("filtered");
  }
  else {
    // Remove elements from DOM
    selectObject.find("option[data-filter]").remove();
    selectObject.find("option[data-filter-emptyvalue]").remove();
  }

  // Get filtered elements.
  var toEnable = fullData.filter("option[data-filter][data-filter='" + filterValue + "']");

  // Attach elements to DOM
  selectObject.append(toEnable);

  // If toEnable is empty, show empty option.
  if (toEnable.length == 0) {
    selectObject.append(emptyValue);
  }

  // Select First Occurrence
  if (autoSelect) {
    var obj = selectObject.find("option[selected]");
    selectObject.val(obj.length == 0 ? toEnable.val() : obj.val());
  }
}

To use it, you just call the function with the value you want to keep.

filterCombobox($("#myCombobox"), 2, true);

Then the resulting select will be:

<select id="myCombobox">
  <option data-filter="2" value="CCC">Option 3</option>
  <option data-filter="2" value="DDD">Option 4</option>
</select>

The original elements are stored by the data() function, so subsequent calls will add and remove the correct elements.

ImportError: no module named win32api

I had an identical problem, which I solved by restarting my Python editor and shell. I had installed pywin32 but the new modules were not picked up until the restarts.

If you've already done that, do a search in your Python installation for win32api and you should find win32api.pyd under ${PYTHON_HOME}\Lib\site-packages\win32.

The preferred way of creating a new element with jQuery

According to the documentation for 3.4, It is preferred to use attributes with attr() method.

$('<div></div>').attr(
  {
    id: 'some dynanmic|static id',
    "class": 'some dynanmic|static class'
  }
).click(function() {
  $( "span", this ).addClass( "bar" ); // example from the docs
});

How do I scroll to an element within an overflowed Div?

I write these 2 functions to make my life easier:

function scrollToTop(elem, parent, speed) {
    var scrollOffset = parent.scrollTop() + elem.offset().top;
    parent.animate({scrollTop:scrollOffset}, speed);
    // parent.scrollTop(scrollOffset, speed);
}

function scrollToCenter(elem, parent, speed) {
    var elOffset = elem.offset().top;
    var elHeight = elem.height();
    var parentViewTop = parent.offset().top;
    var parentHeight = parent.innerHeight();
    var offset;

    if (elHeight >= parentHeight) {
        offset = elOffset;
    } else {
        margin = (parentHeight - elHeight)/2;
        offset = elOffset - margin;
    }

    var scrollOffset = parent.scrollTop() + offset - parentViewTop;

    parent.animate({scrollTop:scrollOffset}, speed);
    // parent.scrollTop(scrollOffset, speed);
}

And use them:

scrollToTop($innerListItem, $parentDiv, 200);
// or
scrollToCenter($innerListItem, $parentDiv, 200);

fork and exec in bash

Use the ampersand just like you would from the shell.

#!/usr/bin/bash
function_to_fork() {
   ...
}

function_to_fork &
# ... execution continues in parent process ...

Call removeView() on the child's parent first

What I was doing wrong so I got this error is I wasn't instantiating dynamic layout and adding childs to it so got this error

How to view AndroidManifest.xml from APK file?

This is an old thread, but I thought I would mention, of your phone has root, you can view it directly on your phone using the root explorer app. You don't even have to extract it to see.

Unlink of file Failed. Should I try again?

As mentioned in the above answers, yes file must be used maybe by other java processes, simple way to get rid-off this is, just kill all java processes then execute git pull I did this, it works for me.

For windows kill all java processes:

taskkill /F /IM java.exe

For Linux kill all java processes:

kill -9 `pidof java`

how to replace an entire column on Pandas.DataFrame

If you don't mind getting a new data frame object returned as opposed to updating the original Pandas .assign() will avoid SettingWithCopyWarning. Your example:

df = df.assign(B=df1['E'])

TypeError: method() takes 1 positional argument but 2 were given

Pass cls parameter into @classmethod to resolve this problem.

@classmethod
def test(cls):
    return ''

Calling other function in the same controller?

To call a function inside a same controller in any laravel version follow as bellow

$role = $this->sendRequest('parameter');
// sendRequest is a public function

How to get a list column names and datatypes of a table in PostgreSQL?

    SELECT DISTINCT
        ROW_NUMBER () OVER (ORDER BY pgc.relname , a.attnum) as rowid , 
        pgc.relname as table_name ,
        a.attnum as attr,
        a.attname as name,
        format_type(a.atttypid, a.atttypmod) as typ,
        a.attnotnull as notnull, 
        com.description as comment,
        coalesce(i.indisprimary,false) as primary_key,
        def.adsrc as default
    FROM pg_attribute a 
    JOIN pg_class pgc ON pgc.oid = a.attrelid
    LEFT JOIN pg_index i ON 
        (pgc.oid = i.indrelid AND i.indkey[0] = a.attnum)
    LEFT JOIN pg_description com on 
        (pgc.oid = com.objoid AND a.attnum = com.objsubid)
    LEFT JOIN pg_attrdef def ON 
        (a.attrelid = def.adrelid AND a.attnum = def.adnum)
    LEFT JOIN pg_catalog.pg_namespace n ON n.oid = pgc.relnamespace

    WHERE 1=1 
        AND pgc.relkind IN ('r','')
        AND n.nspname <> 'pg_catalog'
        AND n.nspname <> 'information_schema'
        AND n.nspname !~ '^pg_toast'

    AND a.attnum > 0 AND pgc.oid = a.attrelid
    AND pg_table_is_visible(pgc.oid)
    AND NOT a.attisdropped
    ORDER BY rowid
    ;

How do I add an existing Solution to GitHub from Visual Studio 2013

None of the answers were specific to my problem, so here's how I did it.

This is for Visual Studio 2015 and I had already made a repository on Github.com

If you already have your repository URL copy it and then in visual studio:

  • Go to Team Explorer
  • Click the "Sync" button
  • It should have 3 options listed with "get started" links.
  • I chose the "get started" link against "publish to remote repository", which it the bottom one
  • A yellow box will appear asking for the URL. Just paste the URL there and click publish.

How to define Singleton in TypeScript

Singleton classes in TypeScript are generally an anti-pattern. You can simply use namespaces instead.

Useless singleton pattern

class Singleton {
    /* ... lots of singleton logic ... */
    public someMethod() { ... }
}

// Using
var x = Singleton.getInstance();
x.someMethod();

Namespace equivalent

export namespace Singleton {
    export function someMethod() { ... }
}
// Usage
import { SingletonInstance } from "path/to/Singleton";

SingletonInstance.someMethod();
var x = SingletonInstance; // If you need to alias it for some reason

How to coerce a list object to type 'double'

You can also use list subsetting to select the element you want to convert. It would be useful if your list had more than 1 element.

as.numeric(a[[1]])

Vuex - Computed property "name" was assigned to but it has no setter

It should be like this.

In your Component

computed: {
        ...mapGetters({
                nameFromStore: 'name'
            }),
        name: {
           get(){
             return this.nameFromStore
           },
           set(newName){
             return newName
           } 
        }
    }

In your store

export const store = new Vuex.Store({
         state:{
             name : "Stackoverflow"
         },
         getters: {
                 name: (state) => {
                     return state.name;
                 }
         }
}

How to add http:// if it doesn't exist in the URL

Simply check if there is a protocol (delineated by "://") and add "http://" if there isn't.

if (false === strpos($url, '://')) {
    $url = 'http://' . $url;
}

Note: This may be a simple and straightforward solution, but Jack's answer using parse_url is almost as simple and much more robust. You should probably use that one.

The default XML namespace of the project must be the MSBuild XML namespace

I was getting the same messages while I was running just msbuild from powershell.

dotnet msbuild "./project.csproj" worked for me.

What is "Linting"?

Apart from what others have mentioned, I would like to add that, Linting will run through your source code to find

 -  formatting discrepancy 
 -  non-adherence to coding standards and conventions 
 -  pinpointing possible logical errors in your program

Running a Lint program over your source code, helps to ensure that source code is legible, readable, less polluted and easier to maintain.

How to change the height of a div dynamically based on another div using css?

By specifying the positions we can achieve this,

.div1 {
  width:300px;
  height: auto;
  background-color: grey;  
  border:1px solid;
  position:relative;
  overflow:auto;
}
.div2 {
  width:150px;
  height:auto;
  background-color: #F4A460;  
  float:left;
}
.div3 {
  width:150px;
  height:100%;
  position:absolute;
  right:0px;
  background-color: #FFFFE0;  
  float:right;
}

but it is not possible to achieve this using float.

T-SQL Subquery Max(Date) and Joins

For MySQL, please find the below query:

select * from (select PartID, max(Pricedate) max_pricedate from MyPrices group bu partid) as a 
    inner join MyParts b on
    (a.partid = b.partid and a.max_pricedate = b.pricedate)

Inside the subquery it fetches max pricedate for every partyid of MyPrices then, inner joining with MyParts using partid and the max_pricedate

Open a URL in a new tab (and not a new window)

enter image description here

I researched a lot of information about how to open new tab and stay on the same tab. I have found one small trick to do it. Lets assume you have url which you need to open - newUrl and old url - currentUrl, which you need to stay on after new tab opened. JS code will look something like next:

// init urls
let newUrl = 'http://example.com';
let currentUrl = window.location.href;
// open window with url of current page, you will be automatically moved 
// by browser to a new opened tab. It will look like your page is reloaded
// and you will stay on same page but with new page opened
window.open(currentUrl , '_blank');
// on your current tab will be opened new url
location.href = newUrl;

How to align entire html body to the center?

EDIT

As of today with flexbox, you could

body {
  display:flex; flex-direction:column; justify-content:center;
  min-height:100vh;
}

PREVIOUS ANSWER

html, body {height:100%;}
html {display:table; width:100%;}
body {display:table-cell; text-align:center; vertical-align:middle;}

Is there a way to run Bash scripts on Windows?

If your looking for something a little more native, you can use getGnuWin32 to install all of the unix command line tools that have been ported. That plus winBash gives you most of a working unix environment. Add console2 for a better terminal emulator and you almost can't tell your on windows!

Cygwin is a better toolkit overall, but I have found myself running into suprise problems because of the divide between it and windows. None of these solutions are as good as a native linux system though.

You may want to look into using virtualbox to create a linux VM with your distro of choice. Set it up to share a folder with the host os, and you can use a true linux development environment, and share with windows. Just watch out for those EOL markers, they get ya every time.

Nested lists python

n = [[1, 2, 3], [4, 5, 6, 7, 8, 9]]
def flatten(lists):
  results = []
  for numbers in lists:
    for numbers2 in numbers:
        results.append(numbers2) 
  return results
print flatten(n)

Output: n = [1,2,3,4,5,6,7,8,9]

Function to convert timestamp to human date in javascript

why not simply

new Date (timestamp);

A date is a date, the formatting of it is a different matter.

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

For me in windows server 2012 R2 I solved it by removing the duplicates from web.config file i found this line duplicated twice i removed one line and kept the other line

<add name="CrystalImageHandler.aspx_GET" verb="GET" path="CrystalImageHandler.aspx" type="CrystalDecisions.Web.CrystalImageHandler, CrystalDecisions.Web, Version=13.0.4000.0, Culture=neutral, PublicKeyToken=692fbea5521e1304" preCondition="integratedMode"/></handlers><validation validateIntegratedModeConfiguration="false"/>

Have Excel formulas that return 0, make the result blank

You can create your own user defined functions in a module within Excel such as (from memory, so may need some debugging, and the syntax may vary among Excel versions as well):

Public Function ZeroToBlank (x As Integer) As String
    If x = 0 then
        ZeroToBlank = ""
    Else
        ZeroToBlank = CStr(x)
    End If
End Function

You can then simply insert =ZeroToBlank (Index (a,b,c)) into your cell.

There's a nice tutorial on just this subject here.

The basic steps are:

  • Open the VB editor within Excel by using Tools -> Macro -> Visual Basic Editor.
  • Create a new module with Insert -> Module.
  • Enter the above function into that module.
  • In the cells where you want to call that function, enter the formula
         =ZeroToBlank (<<whatever>>)
    where <<whatever>> is the value you wish to use blank for if it's zero.
  • Note that this function returns a string so, if you want it to look like a number, you may want to right justify the cells.

Note that there may be minor variations depending on which version of Excel you have. My version of Excel is 2002 which admittedly is pretty old, but it still does everything I need of it.

Make Bootstrap's Carousel both center AND responsive?

Now (on Boostrap 3 and 4) its simply :

.carousel-inner img {
  margin: auto;
}

Program to find largest and second largest number in array

You can do it best in one pass.

largest and largest2 are set to INT_MIN on entry. Then step through the array. If largest is smaller than the number, largest2 becomes largest, then largest becomes the new number (or smaller than or equal if you want to allow duplicates). If largest is greater then the new number, test largest2.

Note that this algorithm scales to finding the top three or four in an array, before it become too cumbersome and it's better to just sort.

how to realize countifs function (excel) in R

Given a dataset

df <- data.frame( sex = c('M', 'M', 'F', 'F', 'M'), 
                  occupation = c('analyst', 'dentist', 'dentist', 'analyst', 'cook') )

you can subset rows

df[df$sex == 'M',] # To get all males
df[df$occupation == 'analyst',] # All analysts

etc.

If you want to get number of rows, just call the function nrow such as

nrow(df[df$sex == 'M',])

How to delete last character in a string in C#?

build it with string.Join instead:

var parameters = sl.SelProds.Select(x=>"productID="+x.prodID).ToArray();
paramstr = string.Join("&", parameters);

string.Join takes a seperator ("&") and and array of strings (parameters), and inserts the seperator between each element of the array.

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

Angular js init ng-model from default values

I have a simple approach, because i have some heavy validations and masks in my forms. So, i used jquery to get my value again and fire the event "change" to validations:

$('#myidelement').val('123');
$('#myidelement').trigger( "change");

Regex to match alphanumeric and spaces

There appear to be two problems.

  1. You're using the ^ outside a [] which matches the start of the line
  2. You're not using a * or + which means you will only match a single character.

I think you want the following regex @"([^a-zA-Z0-9\s])+"

Jasmine.js comparing arrays

You can compare an array like the below mentioned if the array has some values

it('should check if the array are equal', function() {
        var mockArr = [1, 2, 3];
        expect(mockArr ).toEqual([1, 2, 3]);
 });

But if the array that is returned from some function has more than 1 elements and all are zero then verify by using

expect(mockArray[0]).toBe(0);

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

How to change the Text color of Menu item in Android?

Simply add this to your theme

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="android:itemTextAppearance">@style/AppTheme.ItemTextStyle</item>
</style>

<style name="AppTheme.ItemTextStyle" parent="@android:style/TextAppearance.Widget.IconMenu.Item">
        <item name="android:textColor">@color/orange_500</item>
</style>

Tested on API 21

How can I get Android Wifi Scan Results into a list?

In addition for the accepted answer you'll need the following permissions into your AndroidManifest to get it working:

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

How to overcome the CORS issue in ReactJS

Temporary solve this issue by a chrome plugin called CORS. Btw backend server have to send proper header to front end requests.

transform object to array with lodash

Transforming object to array with plain JavaScript's(ECMAScript-2016) Object.values:

_x000D_
_x000D_
var obj = {_x000D_
    22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[]}},_x000D_
    12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[]}}_x000D_
}_x000D_
_x000D_
var values = Object.values(obj)_x000D_
_x000D_
console.log(values);
_x000D_
_x000D_
_x000D_

If you also want to keep the keys use Object.entries and Array#map like this:

_x000D_
_x000D_
var obj = {_x000D_
    22: {name:"John", id:22, friends:[5,31,55], works:{books:[], films:[]}},_x000D_
    12: {name:"Ivan", id:12, friends:[2,44,12], works:{books:[], films:[]}}_x000D_
}_x000D_
_x000D_
var values = Object.entries(obj).map(([k, v]) => ({[k]: v}))_x000D_
_x000D_
console.log(values);
_x000D_
_x000D_
_x000D_

Install windows service without InstallUtil.exe

This Problem is due to Security, Better open Developer Command prompt for VS 2012 in RUN AS ADMINISTRATOR and install your Service, it fix your problem surely.

ImportError: No module named psycopg2

Use psycopg2-binary instead of psycopg2.

pip install psycopg2-binary

Or you will get the warning below:

UserWarning: The psycopg2 wheel package will be renamed from release 2.8; in order to keep installing from binary please use "pip install psycopg2-binary" instead. For details see: http://initd.org/psycopg/docs/install.html#binary-install-from-pypi.

Reference: Psycopg 2.7.4 released | Psycopg

curl.h no such file or directory

Instead of downloading curl, down libcurl.

curl is just the application, libcurl is what you need for your C++ program

http://packages.ubuntu.com/quantal/curl

What is the Regular Expression For "Not Whitespace and Not a hyphen"

In Java:

    String regex = "[^-\\s]";

    System.out.println("-".matches(regex)); // prints "false"
    System.out.println(" ".matches(regex)); // prints "false"
    System.out.println("+".matches(regex)); // prints "true"

The regex [^-\s] works as expected. [^\s-] also works.

See also

How to get the path of running java program

Use

System.getProperty("java.class.path")

see http://docs.oracle.com/javase/tutorial/essential/environment/sysprop.html

You can also split it into it's elements easily

String classpath = System.getProperty("java.class.path");
String[] classpathEntries = classpath.split(File.pathSeparator);

Kill process by name?

import os, signal

def check_kill_process(pstring):
    for line in os.popen("ps ax | grep " + pstring + " | grep -v grep"):
        fields = line.split()
        pid = fields[0]
        os.kill(int(pid), signal.SIGKILL)

How to split a string in Haskell?

There is a package for this called split.

cabal install split

Use it like this:

ghci> import Data.List.Split
ghci> splitOn "," "my,comma,separated,list"
["my","comma","separated","list"]

It comes with a lot of other functions for splitting on matching delimiters or having several delimiters.

Remove all HTMLtags in a string (with the jquery text() function)

I created this test case: http://jsfiddle.net/ccQnK/1/ , I used the Javascript replace function with regular expressions to get the results that you want.

$(document).ready(function() {
    var myContent = '<div id="test">Hello <span>world!</span></div>';
    alert(myContent.replace(/(<([^>]+)>)/ig,""));
});

OracleCommand SQL Parameters Binding

You need to use something like this:

 OracleCommand oraCommand = new OracleCommand("SELECT fullname FROM sup_sys.user_profile
                       WHERE domain_user_name = :userName", db);

More can be found in this MSDN article: http://msdn.microsoft.com/en-us/library/system.data.oracleclient.oraclecommand.parameters%28v=vs.100%29.aspx

It is advised you use the : character instead of @ for Oracle.

How do I add an existing directory tree to a project in Visual Studio?

I think I found a way to do this with the Compile Include=".\Code***.cs" What I wanted is to include code recursively under my Code folder.

Here is the project file sample.

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="15.0" DefaultTargets="BuildTarget">
    <PropertyGroup>
        <OutputType>Library</OutputType>
    </PropertyGroup>
    <PropertyGroup>
        <StartupObject />
    </PropertyGroup>
    <PropertyGroup>
        <RootNamespace>Autogen</RootNamespace>
    </PropertyGroup>
    <ItemGroup>
        <Compile Remove="@(Compile)" />
        <Compile Include=".\Code\**\*.cs" />
    </ItemGroup>
    <Target Name="BuildTarget">
        <Message Text="Build selected" Importance="high"/>
    </Target>
</Project>

Differences between INDEX, PRIMARY, UNIQUE, FULLTEXT in MySQL?

All of these are kinds of indices.

primary: must be unique, is an index, is (likely) the physical index, can be only one per table.

unique: as it says. You can't have more than one row with a tuple of this value. Note that since a unique key can be over more than one column, this doesn't necessarily mean that each individual column in the index is unique, but that each combination of values across these columns is unique.

index: if it's not primary or unique, it doesn't constrain values inserted into the table, but it does allow them to be looked up more efficiently.

fulltext: a more specialized form of indexing that allows full text search. Think of it as (essentially) creating an "index" for each "word" in the specified column.

How do I Convert DateTime.now to UTC in Ruby?

Try this, works in Ruby:

DateTime.now.to_time.utc

Getting HTML elements by their attribute names

Just another answer

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    function(el) {return el.getAttribute('property') == 'v.name';}
);

In future

Array.prototype.filter.call(
    document.getElementsByTagName('span'),
    (el) => el.getAttribute('property') == 'v.name'
)

3rd party edit

Intro

  • The call() method calls a function with a given this value and arguments provided individually.

  • The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Given this html markup

<span property="a">apple - no match</span>
<span property="v:name">onion - match</span>
<span property="b">root - match</span>
<span property="v:name">tomato - match</span>
<br />
<button onclick="findSpan()">find span</button>

you can use this javascript

function findSpan(){

    var spans = document.getElementsByTagName('span');
    var spansV = Array.prototype.filter.call(
         spans,
         function(el) {return el.getAttribute('property') == 'v:name';}
    );
    return spansV;
}

See demo

Babel command not found

This worked for me inside package.json as an npm script but it does seem to take to long grabbing the packages even though I have them as dev dependancies. It also seems too long.

"babel": "npx -p @babel/cli -p @babel/core babel --version"

What end up solving it was much simpler but funny too

npm install

I thought I ran that already but I guess somethings needed to be rebuilt. Then just:

"babel": "babel --version"

grep for special characters in Unix

Try vi with the -b option, this will show special end of line characters (I typically use it to see windows line endings in a txt file on a unix OS)

But if you want a scripted solution obviously vi wont work so you can try the -f or -e options with grep and pipe the result into sed or awk. From grep man page:

Matcher Selection -E, --extended-regexp Interpret PATTERN as an extended regular expression (ERE, see below). (-E is specified by POSIX.)

   -F, --fixed-strings
          Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.  (-F is specified
          by POSIX.)