Programs & Examples On #Function handle

In Matlab, a function handle is a mechanism provided to allow for indirect calling of a function. Serves like a "pointer to function"

Window vs Page vs UserControl for WPF navigation?

  • Window is like Windows.Forms.Form, so just a new window
  • Page is, according to online documentation:

    Encapsulates a page of content that can be navigated to and hosted by Windows Internet Explorer, NavigationWindow, and Frame.

    So you basically use this if going you visualize some HTML content

  • UserControl is for cases when you want to create some reusable component (but not standalone one) to use it in multiple different Windows

Unable to negotiate with XX.XXX.XX.XX: no matching host key type found. Their offer: ssh-dss

If you're like me, and would rather not make this security hole system or user-wide, then you can add a config option to any git repos that need this by running this command in those repos. (note only works with git version >= 2.10, released 2016-09-04)

git config core.sshCommand 'ssh -oHostKeyAlgorithms=+ssh-dss'

This only works after the repo is setup however. If you're not comfortable adding a remote manually (and just want to clone) then you can run the clone like this:

GIT_SSH_COMMAND='ssh -oHostKeyAlgorithms=+ssh-dss' git clone ssh://user@host/path-to-repository

then run the first command to make it permanent.

If you don't have the latest, and still would like to keep the hole as local as possible I recommend putting

export GIT_SSH_COMMAND='ssh -oHostKeyAlgorithms=+ssh-dss'

in a file somewhere, say git_ssh_allow_dsa_keys.sh, and sourceing it when needed.

Is there an exponent operator in C#?

For what it's worth I do miss the ^ operator when raising a power of 2 to define a binary constant. Can't use Math.Pow() there, but shifting an unsigned int of 1 to the left by the exponent's value works. When I needed to define a constant of (2^24)-1:

public static int Phase_count = 24;
public static uint PatternDecimal_Max = ((uint)1 << Phase_count) - 1;

Remember the types must be (uint) << (int).

VB.NET - Click Submit Button on Webbrowser page

  Private Sub bt_continue_Click(sender As Object, e As EventArgs) Handles bt_continue.Click
    wb_apple.Document.GetElementById("phoneNumber").Focus()
    wb_apple.Document.GetElementById("phoneNumber").InnerText = tb_phonenumber.Text
    wb_apple.Document.GetElementById("reservationCode").Focus()
    wb_apple.Document.GetElementById("reservationCode").InnerText = tb_regcode.Text
    'SendKeys.Send("{Tab}{Tab}{Tab}")
    'For Each Element As HtmlElement In wb_apple.Document.GetElementsByTagName("a")
    'If Element.OuterHtml.Contains("iReserve.sms.submitButtonLabel") Then
    'Element.InvokeMember("click")
    'Exit For
    ' End If
    'Next Element
    wb_apple.Document.GetElementById("smsPageForm").Focus()
    wb_apple.Document.GetElementById("smsPageForm").InvokeMember("submit")

End Sub

Fastest method of screen capturing on Windows

EDIT: I can see that this is listed under your first edit link as "the GDI way". This is still a decent way to go even with the performance advisory on that site, you can get to 30fps easily I would think.

From this comment (I have no experience doing this, I'm just referencing someone who does):

HDC hdc = GetDC(NULL); // get the desktop device context
HDC hDest = CreateCompatibleDC(hdc); // create a device context to use yourself

// get the height and width of the screen
int height = GetSystemMetrics(SM_CYVIRTUALSCREEN);
int width = GetSystemMetrics(SM_CXVIRTUALSCREEN);

// create a bitmap
HBITMAP hbDesktop = CreateCompatibleBitmap( hdc, width, height);

// use the previously created device context with the bitmap
SelectObject(hDest, hbDesktop);

// copy from the desktop device context to the bitmap device context
// call this once per 'frame'
BitBlt(hDest, 0,0, width, height, hdc, 0, 0, SRCCOPY);

// after the recording is done, release the desktop context you got..
ReleaseDC(NULL, hdc);

// ..delete the bitmap you were using to capture frames..
DeleteObject(hbDesktop);

// ..and delete the context you created
DeleteDC(hDest);

I'm not saying this is the fastest, but the BitBlt operation is generally very fast if you're copying between compatible device contexts.

For reference, Open Broadcaster Software implements something like this as part of their "dc_capture" method, although rather than creating the destination context hDest using CreateCompatibleDC they use an IDXGISurface1, which works with DirectX 10+. If there is no support for this they fall back to CreateCompatibleDC.

To change it to use a specific application, you need to change the first line to GetDC(game) where game is the handle of the game's window, and then set the right height and width of the game's window too.

Once you have the pixels in hDest/hbDesktop, you still need to save it to a file, but if you're doing screen capture then I would think you would want to buffer a certain number of them in memory and save to the video file in chunks, so I will not point to code for saving a static image to disk.

Visual Studio "Could not copy" .... during build

For me it was the Avast antivirus that wont let visual studio to write/read/execute file. So I had to add Visual studio 2010/2012 folder to antivirus exclusion list. And right after that baam... it works.

pandas: to_numeric for multiple columns

df.loc[:,'col':] = df.loc[:,'col':].apply(pd.to_numeric, errors = 'coerce')

How to monitor the memory usage of Node.js?

The built-in process module has a method memoryUsage that offers insight in the memory usage of the current Node.js process. Here is an example from in Node v0.12.2 on a 64-bit system:

$ node --expose-gc
> process.memoryUsage();  // Initial usage
{ rss: 19853312, heapTotal: 9751808, heapUsed: 4535648 }
> gc();                   // Force a GC for the baseline.
undefined
> process.memoryUsage();  // Baseline memory usage.
{ rss: 22269952, heapTotal: 11803648, heapUsed: 4530208 }
> var a = new Array(1e7); // Allocate memory for 10m items in an array
undefined
> process.memoryUsage();  // Memory after allocating so many items
{ rss: 102535168, heapTotal: 91823104, heapUsed: 85246576 }
> a = null;               // Allow the array to be garbage-collected
null
> gc();                   // Force GC (requires node --expose-gc)
undefined
> process.memoryUsage();  // Memory usage after GC
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4528072 }
> process.memoryUsage();  // Memory usage after idling
{ rss: 23293952, heapTotal: 11803648, heapUsed: 4753376 }

In this simple example, you can see that allocating an array of 10M elements consumers approximately 80MB (take a look at heapUsed).
If you look at V8's source code (Array::New, Heap::AllocateRawFixedArray, FixedArray::SizeFor), then you'll see that the memory used by an array is a fixed value plus the length multiplied by the size of a pointer. The latter is 8 bytes on a 64-bit system, which confirms that observed memory difference of 8 x 10 = 80MB makes sense.

How do I configure HikariCP in my Spring Boot app in my application.properties files?

Here is the good news. HikariCP is the default connection pool now with Spring Boot 2.0.0.

Spring Boot 2.0.0 Release Notes

The default database pooling technology in Spring Boot 2.0 has been switched from Tomcat Pool to HikariCP. We’ve found that Hakari offers superior performance, and many of our users prefer it over Tomcat Pool.

html5 - canvas element - Multiple layers

No, however, you could layer multiple <canvas> elements on top of each other and accomplish something similar.

<div style="position: relative;">
 <canvas id="layer1" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 0;"></canvas>
 <canvas id="layer2" width="100" height="100" 
   style="position: absolute; left: 0; top: 0; z-index: 1;"></canvas>
</div>

Draw your first layer on the layer1 canvas, and the second layer on the layer2 canvas. Then when you clearRect on the top layer, whatever's on the lower canvas will show through.

Get the IP Address of local computer

Also, note that "the local IP" might not be a particularly unique thing. If you are on several physical networks (wired+wireless+bluetooth, for example, or a server with lots of Ethernet cards, etc.), or have TAP/TUN interfaces setup, your machine can easily have a whole host of interfaces.

unable to install pg gem

Regardless of what OS you are running, look at the logs file of the "Makefile" to see what is going on, instead of blindly installing stuff.

In my case, MAC OS, the log file is here:

/Users/za/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-15/2.3.0-static/pg-1.0.0/mkmf.log

The logs indicated that the make file could not be created because of the following:

Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers

Inside the mkmf.log, you will see that it could not find required libraries, to finish the build.

checking for pg_config... no
Can't find the 'libpq-fe.h header
blah blah

After running "brew install postgresql", I can see all required libraries being there:

za:myapp za$ cat /Users/za/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-15/2.3.0-static/pg-1.0.0/mkmf.log | grep yes
find_executable: checking for pg_config... -------------------- yes
find_header: checking for libpq-fe.h... -------------------- yes
find_header: checking for libpq/libpq-fs.h... -------------------- yes
find_header: checking for pg_config_manual.h... -------------------- yes
have_library: checking for PQconnectdb() in -lpq... -------------------- yes
have_func: checking for PQsetSingleRowMode()... -------------------- yes
have_func: checking for PQconninfo()... -------------------- yes
have_func: checking for PQsslAttribute()... -------------------- yes
have_func: checking for PQencryptPasswordConn()... -------------------- yes
have_const: checking for PG_DIAG_TABLE_NAME in libpq-fe.h... -------------------- yes
have_header: checking for unistd.h... -------------------- yes
have_header: checking for inttypes.h... -------------------- yes
checking for C99 variable length arrays... -------------------- yes

Construct a manual legend for a complicated plot

You need to map attributes to aesthetics (colours within the aes statement) to produce a legend.

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h, fill = "BAR"),colour="#333333")+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols) + scale_fill_manual(name="Bar",values=cols) +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

I understand where Roland is coming from, but since this is only 3 attributes, and complications arise from superimposing bars and error bars this may be reasonable to leave the data in wide format like it is. It could be slightly reduced in complexity by using geom_pointrange.


To change the background color for the error bars legend in the original, add + theme(legend.key = element_rect(fill = "white",colour = "white")) to the plot specification. To merge different legends, you typically need to have a consistent mapping for all elements, but it is currently producing an artifact of a black background for me. I thought guide = guide_legend(fill = NULL,colour = NULL) would set the background to null for the legend, but it did not. Perhaps worth another question.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, guide = guide_legend(fill = NULL,colour = NULL)) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here


To get rid of the black background in the legend, you need to use the override.aes argument to the guide_legend. The purpose of this is to let you specify a particular aspect of the legend which may not be being assigned correctly.

ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR", colour="BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1"),size=1.0) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=3) +           #red
  geom_errorbar(aes(ymin=d, ymax=e, colour="LINE1"), width=0.1, size=.8) + 
  geom_line(aes(y=c,group=1,colour="LINE2"),size=1.0) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=3) +           #blue
  geom_errorbar(aes(ymin=f, ymax=g,colour="LINE2"), width=0.1, size=.8) + 
  scale_colour_manual(name="Error Bars",values=cols, 
                      guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

enter image description here

How to set the height and the width of a textfield in Java?

package myguo;
import javax.swing.*;

public class MyGuo {

    JFrame f;
    JButton bt1 , bt2 ;
    JTextField t1,t2;
    JLabel l1,l2;

    MyGuo(){

        f=new JFrame("LOG IN FORM");
        f.setLocation(500,300);
        f.setSize(600,500);
        f.setLayout(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        l1=new JLabel("NAME");
        l1.setBounds(50,70,80,30);

        l2=new JLabel("PASSWORD");
        l2.setBounds(50,100,80,30);

        t1=new JTextField();
        t1.setBounds(140, 70, 200,30);

         t2=new JTextField();
        t2.setBounds(140, 110, 200,30);

        bt1 =new JButton("LOG IN");
        bt1.setBounds(150,150,80,30);

        bt2 =new JButton("CLEAR");
        bt2.setBounds(235,150,80,30);

         f.add(l1);
        f.add(l2);
         f.add(t1);
         f.add(t2);
         f.add(bt1);
         f.add(bt2);

    f.setVisible(true);

    }
    public static void main(String[] args) {
        MyGuo myGuo = new MyGuo();
}
}

Failed to open the HAX device! HAX is not working and emulator runs in emulation mode emulator

I think you are trying to run an emulator based on x86. I got the same error when I just download the HAXM under Extras category of Android SDK Manager. Actually, you need install it. Go to the directory of extras and run the installation of HAXM. Hope this will solve your problem.

How to Set Opacity (Alpha) for View in Android

What I would suggest you do is create a custom ARGB color in your colors.xml file such as :

<resources>
<color name="translucent_black">#80000000</color>
</resources>

then set your button background to that color :

android:background="@android:color/translucent_black"

Another thing you can do if you want to play around with the shape of the button is to create a Shape drawable resource where you set up the properties what the button should look like :

file: res/drawable/rounded_corner_box.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <gradient
        android:startColor="#80000000"
        android:endColor="#80FFFFFF"
        android:angle="45"/>
    <padding android:left="7dp"
        android:top="7dp"
        android:right="7dp"
        android:bottom="7dp" />
    <corners android:radius="8dp" />
</shape>

Then use that as the button background :

    android:background="@drawable/rounded_corner_box"

Match at every second occurrence

If you're using C#, you can either get all the matches at once (i.e. use Regex.Matches(), which returns a MatchCollection, and check the index of the item: index % 2 != 0).

If you want to find the occurrence to replace it, use one of the overloads of Regex.Replace() that uses a MatchEvaluator (e.g. Regex.Replace(String, String, MatchEvaluator). Here's the code:

using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "abcdabcd";

            // Replace *second* a with m

            string replacedString = Regex.Replace(
                input,
                "a",
                new SecondOccuranceFinder("m").MatchEvaluator);

            Console.WriteLine(replacedString);
            Console.Read();

        }

        class SecondOccuranceFinder
        {
            public SecondOccuranceFinder(string replaceWith)
            {
                _replaceWith = replaceWith;
                _matchEvaluator = new MatchEvaluator(IsSecondOccurance);
            }

            private string _replaceWith;

            private MatchEvaluator _matchEvaluator;
            public MatchEvaluator MatchEvaluator
            {
                get
                {
                    return _matchEvaluator;
                }
            }

            private int _matchIndex;
            public string IsSecondOccurance(Match m)
            {
                _matchIndex++;
                if (_matchIndex % 2 == 0)
                    return _replaceWith;
                else
                    return m.Value;
            }
        }
    }
}

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

Using local makefile for CLion instead of CMake

Newest version has better support literally for any generated Makefiles, through the compiledb

Three steps:

  1. install compiledb

    pip install compiledb
    
  2. run a dry make

    compiledb -n make 
    

    (do the autogen, configure if needed)

  3. there will be a compile_commands.json file generated open the project and you will see CLion will load info from the json file. If you your CLion still try to find CMakeLists.txt and cannot read compile_commands.json, try to remove the entire folder, re-download the source files, and redo step 1,2,3

Orignal post: Working with Makefiles in CLion using Compilation DB

How do I limit the number of results returned from grep?

Another option is just using head:

grep ...parameters... yourfile | head

This won't require searching the entire file - it will stop when the first ten matching lines are found. Another advantage with this approach is that will return no more than 10 lines even if you are using grep with the -o option.

For example if the file contains the following lines:

112233
223344
123123

Then this is the difference in the output:

$ grep -o '1.' yourfile | head -n2
11
12

$ grep -m2 -o '1.'
11
12
12

Using head returns only 2 results as desired, whereas -m2 returns 3.

Unable to start the mysql server in ubuntu

Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

sudo apt --reinstall install mysql-server

How to set default value for column of new created table from select statement in 11g

The reason is that CTAS (Create table as select) does not copy any metadata from the source to the target table, namely

  • no primary key
  • no foreign keys
  • no grants
  • no indexes
  • ...

To achieve what you want, I'd either

  • use dbms_metadata.get_ddl to get the complete table structure, replace the table name with the new name, execute this statement, and do an INSERT afterward to copy the data
  • or keep using CTAS, extract the not null constraints for the source table from user_constraints and add them to the target table afterwards

Error: "an object reference is required for the non-static field, method or property..."

Change your signatures to private static bool siprimo(long a) and private static long volteado(long a) and see where that gets you.

Generating (pseudo)random alpha-numeric strings

You can use the following code. It is similar to existing functions except that you can force special character count:

function random_string() {
    // 8 characters: 7 lower-case alphabets and 1 digit
    $character_sets = [
        ["count" => 7, "characters" => "abcdefghijklmnopqrstuvwxyz"],
        ["count" => 1, "characters" => "0123456789"]
    ];
    $temp_array = array();
    foreach ($character_sets as $character_set) {
        for ($i = 0; $i < $character_set["count"]; $i++) {
            $random = random_int(0, strlen($character_set["characters"]) - 1);
            $temp_array[] = $character_set["characters"][$random];
        }
    }
    shuffle($temp_array);
    return implode("", $temp_array);
}

Writing a dictionary to a text file?

import json

with open('tokenler.json', 'w') as file:
     file.write(json.dumps(mydict, ensure_ascii=False))

Android Fragment onAttach() deprecated

Activity is a context so if you can simply check the context is an Activity and cast it if necessary.

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    Activity a;

    if (context instanceof Activity){
        a=(Activity) context;
    }

}

Update: Some are claiming that the new Context override is never called. I have done some tests and cannot find a scenario where this is true and according to the source code, it should never be true. In all cases I tested, both pre and post SDK23, both the Activity and the Context versions of onAttach were called. If you can find a scenario where this is not the case, I would suggest you create a sample project illustrating the issue and report it to the Android team.

Update 2: I only ever use the Android Support Library fragments as bugs get fixed faster there. It seems the above issue where the overrides do not get called correctly only comes to light if you use the framework fragments.

Get installed applications in a system

Might I suggest you take a look at WMI (Windows Management Instrumentation). If you add the System.Management reference to your C# project, you'll gain access to the class `ManagementObjectSearcher', which you will probably find useful.

There are various WMI Classes for Installed Applications, but if it was installed with Windows Installer, then the Win32_Product class is probably best suited to you.

ManagementObjectSearcher s = new ManagementObjectSearcher("SELECT * FROM Win32_Product");

Given URL is not allowed by the Application configuration

For me it was the "Single Sign On" (can be seen at the bottome of the screenshot in phwd's answer) setting that was turned off.

Android WebView not loading URL

Use this it should help.

 var currentUrl = "google.com" 
 var partOfUrl = currentUrl.substring(0, currentUrl.length-2)

 webView.setWebViewClient(object: WebViewClient() {

 override fun onLoadResource(WebView view, String url) {
 //call loadUrl() method  here 
 // also check if url contains partOfUrl, if not load it differently.
 if(url.contains(partOfUrl, true)) {
     //it should work if you reach inside this if scope.
 } else if(!(currentUrl.startWith("w", true))) {
     webView.loadurl("www.$currentUrl")

 } else if(!(currentUrl.startWith("h", true))) {
     webView.loadurl("https://$currentUrl")

 } else { 
   //...
 }
 }

 override fun onReceivedSslError(view: WebView?, handler: SslErrorHandler?, error: SslError?) {
  // you can call again loadUrl from here too if there is any error.
}
 // You should also override other override method for error such as
 // onReceiveError to see how all these methods are called one after another and how
// they behave while debugging with break point. 
} 

jQuery.each - Getting li elements inside an ul

Given an answer as high voted and views. I did find the answer with mixed of here and other links.

I have a scenario where all patient-related menu is disabled if a patient is not selected. (Refer link - how to disable a li tag using JavaScript)

//css
.disabled{
    pointer-events:none;
    opacity:0.4;
}
// jqvery
$("li a").addClass('disabled');
// remove .disabled when you are done

So rather than write long code, I found an interesting solution via CSS.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
 var PatientId ; _x000D_
 //var PatientId =1;  //remove to test enable i.e. patient selected_x000D_
 if (typeof PatientId == "undefined" || PatientId == "" || PatientId == 0 || PatientId == null) {_x000D_
  console.log(PatientId);_x000D_
  $("#dvHeaderSubMenu a").each(function () {   _x000D_
   $(this).addClass('disabled');_x000D_
  });  _x000D_
  return;_x000D_
 }_x000D_
})
_x000D_
.disabled{_x000D_
    pointer-events:none;_x000D_
    opacity:0.4;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dvHeaderSubMenu">_x000D_
     <ul class="m-nav m-nav--inline pull-right nav-sub">_x000D_
      <li class="m-nav__item">_x000D_
       <a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
        <i class="m-nav__link-icon fa fa-tachometer"></i>_x000D_
        Overview_x000D_
       </a>_x000D_
      </li>_x000D_
_x000D_
      <li class="m-nav__item active">_x000D_
       <a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
        <i class="m-nav__link-icon fa fa-user"></i>_x000D_
        Personal_x000D_
       </a>_x000D_
      </li>_x000D_
            <li class="m-nav__item m-dropdown m-dropdown--inline m-dropdown--arrow" data-dropdown-toggle="hover">_x000D_
       <a href="#" class="m-dropdown__toggle dropdown-toggle" onclick="console.log('PatientMenu Clicked')">_x000D_
        <i class="m-nav__link-icon flaticon-medical-8"></i>_x000D_
        Insurance Claim_x000D_
       </a>_x000D_
       <div class="m-dropdown__wrapper">_x000D_
        <span class="m-dropdown__arrow m-dropdown__arrow--left"></span>_x000D_
        _x000D_
           <ul class="m-nav">_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')" >_x000D_
              <i class="m-nav__link-icon flaticon-toothbrush-1"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Primary_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
              <i class="m-nav__link-icon flaticon-interface"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Secondary_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
              <i class="m-nav__link-icon flaticon-healthy"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Medical_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
           </ul>_x000D_
          _x000D_
       _x000D_
      </li>_x000D_
     </ul>            _x000D_
</div>
_x000D_
_x000D_
_x000D_

sizing div based on window width

Viewport units for CSS

1vw = 1% of viewport width
1vh = 1% of viewport height

This way, you don't have to write many different media queries or javascript.

If you prefer JS

window.innerWidth;
window.innerHeight;

How to correctly catch change/focusOut event on text input in React.js?

You'd need to be careful as onBlur has some caveats in IE11 (How to use relatedTarget (or equivalent) in IE?, https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/relatedTarget).

There is, however, no way to use onFocusOut in React as far as I can tell. See the issue on their github https://github.com/facebook/react/issues/6410 if you need more information.

How to tell if tensorflow is using gpu acceleration from inside python shell?

Tensorflow 2.1

A simple calculation that can be verified with nvidia-smi for memory usage on the GPU.

import tensorflow as tf 

c1 = []
n = 10

def matpow(M, n):
    if n < 1: #Abstract cases where n < 1
        return M
    else:
        return tf.matmul(M, matpow(M, n-1))

with tf.device('/gpu:0'):
    a = tf.Variable(tf.random.uniform(shape=(10000, 10000)), name="a")
    b = tf.Variable(tf.random.uniform(shape=(10000, 10000)), name="b")
    c1.append(matpow(a, n))
    c1.append(matpow(b, n))

Horizontal scroll css?

I figured it this way:

* { padding: 0; margin: 0 }
body { height: 100%; white-space: nowrap }
html { height: 100% }

.red { background: red }
.blue { background: blue }
.yellow { background: yellow }

.header { width: 100%; height: 10%; position: fixed }
.wrapper { width: 1000%; height: 100%; background: green }
.page { width: 10%; height: 100%; float: left }

<div class="header red"></div>
<div class="wrapper">
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
    <div class="page yellow"></div>
    <div class="page blue"></div>
</div>

I have the wrapper at 1000% and ten pages at 10% each. I set mine up to still have "pages" with each being 100% of the window (color coded). You can do eight pages with an 800% wrapper. I guess you can leave out the colors and have on continues page. I also set up a fixed header, but that's not necessary. Hope this helps.

CASE statement in SQLite query

The syntax is wrong in this clause (and similar ones)

    CASE lkey WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

It's either

    CASE WHEN [condition] THEN [expression] ELSE [expression] END

or

    CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END

So in your case it would read:

    CASE WHEN lkey > 5 THEN
        lkey + 2
    ELSE
        lkey
    END

Check out the documentation (The CASE expression):

http://www.sqlite.org/lang_expr.html

How to send PUT, DELETE HTTP request in HttpURLConnection?

I agree with @adietisheim and the rest of people that suggest HttpClient.

I spent time trying to make a simple call to rest service with HttpURLConnection and it hadn't convinced me and after that I tried with HttpClient and it was really more easy, understandable and nice.

An example of code to make a put http call is as follows:

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpPut putRequest = new HttpPut(URI);

StringEntity input = new StringEntity(XML);
input.setContentType(CONTENT_TYPE);

putRequest.setEntity(input);
HttpResponse response = httpClient.execute(putRequest);

onMeasure custom view explanation

onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent situation than a wrap_content situation). These constraints are packaged up into the MeasureSpec values that are passed into the method. Here is a rough correlation of the mode values:

  • EXACTLY means the layout_width or layout_height value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent is used, to set the size exactly to the parent view (this is layout dependent in the framework).
  • AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
  • UNSPECIFIED typically means the layout_width or layout_height value was set to wrap_content with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.

The contract that exists with onMeasure() is that setMeasuredDimension() MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View, which is why it is safe to call super instead if that fits your use case.

Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content in both directions, your view may not show up at all because the framework doesn't know how large it is!

Generally, if you are overriding View and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int desiredWidth = 100;
    int desiredHeight = 100;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        //Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        //Be whatever you want
        width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        //Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        //Be whatever you want
        height = desiredHeight;
    }

    //MUST CALL THIS
    setMeasuredDimension(width, height);
}

Hope that Helps.

what is the difference between const_iterator and iterator?

Performance wise there is no difference. The only purpose of having const_iterator over iterator is to manage the accessesibility of the container on which the respective iterator runs. You can understand it more clearly with an example:

std::vector<int> integers{ 3, 4, 56, 6, 778 };

If we were to read & write the members of a container we will use iterator:

for( std::vector<int>::iterator it = integers.begin() ; it != integers.end() ; ++it )
       {*it = 4;  std::cout << *it << std::endl; }

If we were to only read the members of the container integers you might wanna use const_iterator which doesn't allow to write or modify members of container.

for( std::vector<int>::const_iterator it = integers.begin() ; it != integers.end() ; ++it )
       { cout << *it << endl; }

NOTE: if you try to modify the content using *it in second case you will get an error because its read-only.

COUNT DISTINCT with CONDITIONS

This may work:

SELECT Count(tag) AS 'Tag Count'
FROM Table
GROUP BY tag

and

SELECT Count(tag) AS 'Negative Tag Count'
FROM Table
WHERE entryID > 0
GROUP BY tag

PHP is not recognized as an internal or external command in command prompt

Set "C:\xampp\php" in your PATH Environment Variable. Then restart CMD prompt.

How to downgrade or install an older version of Cocoapods

Note that your pod specs will remain, and are located at ~/.cocoapods/ . This directory may also need to be removed if you want a completely fresh install.

They can be removed using pod spec remove SPEC_NAME then pod setup

It may help to do pod spec remove master then pod setup

How do I select an entire row which has the largest ID in the table?

Try with this

 SELECT top 1  id, Col2,  row_number() over (order by id desc)  FROM Table

Generating a unique machine id

You should look into using the MAC address on the network card (if it exists). Those are usually unique but can be fabricated. I've used software that generates its license file based on your network adapter MAC address, so it's considered a fairly reliable way to distinguish between computers.

How to crop an image using C#?

use bmp.SetResolution(image.HorizontalResolution, image .VerticalResolution);

this may be necessary to do even if you implement best answer here especially if your image is real great and resolutions are not exactly 96.0

My test example:

    static Bitmap LoadImage()
    {
        return (Bitmap)Bitmap.FromFile( @"e:\Tests\d_bigImage.bmp" ); // here is large image 9222x9222 pixels and 95.96 dpi resolutions
    }

    static void TestBigImagePartDrawing()
    {
        using( var absentRectangleImage = LoadImage() )
        {
            using( var currentTile = new Bitmap( 256, 256 ) )
            {
                currentTile.SetResolution(absentRectangleImage.HorizontalResolution, absentRectangleImage.VerticalResolution);

                using( var currentTileGraphics = Graphics.FromImage( currentTile ) )
                {
                    currentTileGraphics.Clear( Color.Black );
                    var absentRectangleArea = new Rectangle( 3, 8963, 256, 256 );
                    currentTileGraphics.DrawImage( absentRectangleImage, 0, 0, absentRectangleArea, GraphicsUnit.Pixel );
                }

                currentTile.Save(@"e:\Tests\Tile.bmp");
            }
        }
    }

How to prevent "The play() request was interrupted by a call to pause()" error?

The cleanest and simplest solution:

var p = video.play();
if (p !== undefined) p.catch(function(){});

Redirect to external URL with return in laravel

You can use Redirect::away($url)

JavaScript DOM remove element

Using Node.removeChild() does the job for you, simply use something like this:

var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);

In DOM 4, the remove method applied, but there is a poor browser support according to W3C:

The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.

But you can use remove method if you using jQuery...

$('#left-section').remove(); //using remove method in jQuery

Also in new frameworks like you can use conditions to remove an element, for example *ngIf in Angular and in React, rendering different views, depends on the conditions...

Unique on a dataframe with only selected columns

Ok, if it doesn't matter which value in the non-duplicated column you select, this should be pretty easy:

dat <- data.frame(id=c(1,1,3),id2=c(1,1,4),somevalue=c("x","y","z"))
> dat[!duplicated(dat[,c('id','id2')]),]
  id id2 somevalue
1  1   1         x
3  3   4         z

Inside the duplicated call, I'm simply passing only those columns from dat that I don't want duplicates of. This code will automatically always select the first of any ambiguous values. (In this case, x.)

sh: react-scripts: command not found after running npm start

In package.json, I changed

"start": "react-scripts start"

to

"start": "NODE_ENV=production node_modules/react-scripts/bin/react-scripts.js start"

I hope this solves the problem for some people. Although the other solutions above seem not to work for me.

Find element's index in pandas Series

you can use Series.idxmax()

>>> import pandas as pd
>>> myseries = pd.Series([1,4,0,7,5], index=[0,1,2,3,4])
>>> myseries.idxmax()
3
>>> 

Find and replace strings in vim on multiple lines

In vim if you are confused which all lines will be affected, Use below

 :%s/foo/bar/gc  

Change each 'foo' to 'bar', but ask for confirmation first. Press 'y' for yes and 'n' for no. Dont forget to save after that

:wq

Awaiting multiple Tasks with different results

Forward Warning

Just a quick headsup to those visiting this and other similar threads looking for a way to parallelize EntityFramework using async+await+task tool-set: The pattern shown here is sound, however, when it comes to the special snowflake of EF you will not achieve parallel execution unless and until you use a separate (new) db-context-instance inside each and every *Async() call involved.

This sort of thing is necessary due to inherent design limitations of ef-db-contexts which forbid running multiple queries in parallel in the same ef-db-context instance.


Capitalizing on the answers already given, this is the way to make sure that you collect all values even in the case that one or more of the tasks results in an exception:

  public async Task<string> Foobar() {
    async Task<string> Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
        return DoSomething(await a, await b, await c);
    }

    using (var carTask = BuyCarAsync())
    using (var catTask = FeedCatAsync())
    using (var houseTask = SellHouseAsync())
    {
        if (carTask.Status == TaskStatus.RanToCompletion //triple
            && catTask.Status == TaskStatus.RanToCompletion //cache
            && houseTask.Status == TaskStatus.RanToCompletion) { //hits
            return Task.FromResult(DoSomething(catTask.Result, carTask.Result, houseTask.Result)); //fast-track
        }

        cat = await catTask;
        car = await carTask;
        house = await houseTask;
        //or Task.AwaitAll(carTask, catTask, houseTask);
        //or await Task.WhenAll(carTask, catTask, houseTask);
        //it depends on how you like exception handling better

        return Awaited(catTask, carTask, houseTask);
   }
 }

An alternative implementation that has more or less the same performance characteristics could be:

 public async Task<string> Foobar() {
    using (var carTask = BuyCarAsync())
    using (var catTask = FeedCatAsync())
    using (var houseTask = SellHouseAsync())
    {
        cat = catTask.Status == TaskStatus.RanToCompletion ? catTask.Result : (await catTask);
        car = carTask.Status == TaskStatus.RanToCompletion ? carTask.Result : (await carTask);
        house = houseTask.Status == TaskStatus.RanToCompletion ? houseTask.Result : (await houseTask);

        return DoSomething(cat, car, house);
     }
 }

How to Store Historical Data

Supporting historical data directly within an operational system will make your application much more complex than it would otherwise be. Generally, I would not recommend doing it unless you have a hard requirement to manipulate historical versions of a record within the system.

If you look closely, most requirements for historical data fall into one of two categories:

  • Audit logging: This is better off done with audit tables. It's fairly easy to write a tool that generates scripts to create audit log tables and triggers by reading metadata from the system data dictionary. This type of tool can be used to retrofit audit logging onto most systems. You can also use this subsystem for changed data capture if you want to implement a data warehouse (see below).

  • Historical reporting: Reporting on historical state, 'as-at' positions or analytical reporting over time. It may be possible to fulfil simple historical reporting requirements by quering audit logging tables of the sort described above. If you have more complex requirements then it may be more economical to implement a data mart for the reporting than to try and integrate history directly into the operational system.

    Slowly changing dimensions are by far the simplest mechanism for tracking and querying historical state and much of the history tracking can be automated. Generic handlers aren't that hard to write. Generally, historical reporting does not have to use up-to-the-minute data, so a batched refresh mechanism is normally fine. This keeps your core and reporting system architecture relatively simple.

If your requirements fall into one of these two categories, you are probably better off not storing historical data in your operational system. Separating the historical functionality into another subsystem will probably be less effort overall and produce transactional and audit/reporting databases that work much better for their intended purpose.

How to solve "The directory is not empty" error when running rmdir command in a batch script?

What worked for me is the following. I appears like the RMDir command will issue “The directory is not empty” nearly all the time...

:Cleanup_Temporary_Files_and_Folders

Erase /F /S /Q C:\MyDir

RMDir /S /Q C:\MyDir
If  Exist  C:\MyDir  GoTo Cleanup_Temporary_Files_and_Folders

What does AND 0xFF do?

The danger of the second expression comes if the type of byte1 is char. In that case, some implementations can have it signed char, which will result in sign extension when evaluating.

signed char byte1 = 0x80;
signed char byte2 = 0x10;

unsigned short value1 = ((byte2 << 8) | (byte1 & 0xFF));
unsigned short value2 = ((byte2 << 8) | byte1);

printf("value1=%hu %hx\n", value1, value1);
printf("value2=%hu %hx\n", value2, value2);

will print

value1=4224 1080     right
value2=65408 ff80    wrong!!

I tried it on gcc v3.4.6 on Solaris SPARC 64 bit and the result is the same with byte1 and byte2 declared as char.

TL;DR

The masking is to avoid implicit sign extension.

EDIT: I checked, it's the same behaviour in C++.

EDIT2: As requested explanation of sign extension. Sign extension is a consequence of the way C evaluates expressions. There is a rule in C called promotion rule. C will implicitly cast all small types to int before doing the evaluation. Let's see what happens to our expression:

unsigned short value2 = ((byte2 << 8) | byte1);

byte1 is a variable containing bit pattern 0xFF. If char is unsigned that value is interpreted as 255, if it is signed it is -128. When doing the calculation, C will extend the value to an int size (16 or 32 bits generally). This means that if the variable is unsigned and we will keep the value 255, the bit-pattern of that value as int will be 0x000000FF. If it is signed we want the value -128 which bit pattern is 0xFFFFFFFF. The sign was extended to the size of the tempory used to do the calculation. And thus oring the temporary will yield the wrong result.

On x86 assembly it is done with the movsx instruction (movzx for the zero extend). Other CPU's had other instructions for that (6809 had SEX).

Set a border around a StackPanel.

You set DockPanel.Dock="Top" to the StackPanel, but the StackPanel is not a child of the DockPanel... the Border is. Your docking property is being ignored.

If you move DockPanel.Dock="Top" to the Border instead, both of your problems will be fixed :)

How do I calculate someone's age in Java?

With Java 8, we can calculate a person age with one line of code:

public int calCAge(int year, int month,int days){             
    return LocalDate.now().minus(Period.of(year, month, days)).getYear();         
}

Difference between System.DateTime.Now and System.DateTime.Today

DateTime.Now.ToShortDateString() will display only the date part

Select records from NOW() -1 Day

Sure you can:

SELECT * FROM table
WHERE DateStamp > DATE_ADD(NOW(), INTERVAL -1 DAY)

How do I make an HTML button not reload the page

I can't comment yet, so I'm posting this as an answer. Best way to avoid reload is how @user2868288 said: using the onsubmit on the form tag.

From all the other possibilities mentioned here, it's the only way which allows the new HTML5 browser data input validation to be triggered (<button> won't do it nor the jQuery/JS handlers) and allows your jQuery/AJAX dynamic info to be appended on the page. For example:

<form id="frmData" onsubmit="return false">
 <input type="email" id="txtEmail" name="input_email" required="" placeholder="Enter a valid e-mail" spellcheck="false"/>
 <input type="tel" id="txtTel" name="input_tel" required="" placeholder="Enter your telephone number" spellcheck="false"/>
 <input type="submit" id="btnSubmit" value="Send Info"/>
</form>
<script type="text/javascript">
  $(document).ready(function(){
    $('#btnSubmit').click(function() {
        var tel = $("#txtTel").val();
        var email = $("#txtEmail").val();
        $.post("scripts/contact.php", {
            tel1: tel,
            email1: email
        })
        .done(function(data) {
            $('#lblEstatus').append(data); // Appends status
            if (data == "Received") {
                $("#btnSubmit").attr('disabled', 'disabled'); // Disable doubleclickers.
            }
        })
        .fail(function(xhr, textStatus, errorThrown) { 
            $('#lblEstatus').append("Error. Try later."); 
        });
     });
   }); 
</script>

Deleting all records in a database table

To delete via SQL

Item.delete_all # accepts optional conditions

To delete by calling each model's destroy method (expensive but ensures callbacks are called)

Item.destroy_all # accepts optional conditions

All here

Initializing IEnumerable<string> In C#

public static IEnumerable<string> GetData()
{
    yield return "1";
    yield return "2";
    yield return "3";
}

IEnumerable<string> m_oEnum = GetData();

Windows cannot find 'http:/.127.0.0.1:%HTTPPORT%/apex/f?p=4950'. Make sure you typed the name correctly, and then try again

Try out this url it is work for me

http://127.0.0.1:8080/apex/f?p=4950:1:1615033681376854

  1. Windows->Services and restarted some of services(OracleJobSchedulerXE,OracleMTSRecoveryService,OracleServiceXE,OracleXEClrAgent,OracleXETNSListener) and it works for me.enter image description here

How to get the current plugin directory in WordPress?

$full_path = WP_PLUGIN_URL . '/'. str_replace( basename( __FILE__ ), "", plugin_basename(__FILE__) );
  • WP_PLUGIN_URL – the url of the plugins directory
  • WP_PLUGIN_DIR – the server path to the plugins directory

This link may help: http://codex.wordpress.org/Determining_Plugin_and_Content_Directories.

Convert dateTime to ISO format yyyy-mm-dd hh:mm:ss in C#

There is no standard format for the readable 8601 format. You can use a custom format:

theDate.ToString("yyyy-MM-dd HH':'mm':'ss")

(The standard format "s" will give you a "T" between the date and the time, not a space.)

CSS media queries for screen sizes

Put it all in one document and use this:

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
  /* Styles */
}

/* iPhone 4 - 5s ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
  /* Styles */
}

/* iPhone 6 ----------- */
@media
only screen and (max-device-width: 667px) 
only screen and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ ----------- */
@media
only screen and (min-device-width : 414px) 
only screen and (-webkit-device-pixel-ratio: 3) {
  /*** You've spent way too much on a phone ***/
}

/* Samsung Galaxy S7 Edge ----------- */
@media only screen
and (-webkit-min-device-pixel-ratio: 3),
and (min-resolution: 192dpi)and (max-width:640px) {
 /* Styles */
}

Source: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

At this point, I would definitely consider using em values instead of pixels. For more information, check this post: https://zellwk.com/blog/media-query-units/.

Swift error : signal SIGABRT how to solve it

You get a SIGABRT error whenever you have a disconnected outlet. Click on your view controller in the storyboard and go to connections in the side panel (the arrow symbol). See if you have an extra outlet there, a duplicate, or an extra one that's not connected. If it's not that then maybe you haven't connected your outlets to your code correctly.

Just remember that SIGABRT happens when you are trying to call an outlet (button, view, textfield, etc) that isn't there.

Create a rounded button / button with border-radius in Flutter

RaisedButton(
          child: Text("Button"),
          onPressed: (){},
          shape: RoundedRectangleBorder(borderRadius: new BorderRadius.circular(30.0),
          side: BorderSide(color: Colors.red))
        )

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

React passing parameter via onclick event using ES6 syntax

I am using React-Bootstrap. The onSelect trigger for dropdowns were not allowing me to pass data. Just the event. So remember you can just set any values as attributes and pick them up from the function using javascript. Picking up those attributes you set in that event target.

    let currentTarget = event.target;
    let currentId = currentTarget.getAttribute('data-id');
    let currentValue = currentTarget.getAttribute('data-value');

check if a number already exist in a list in python

If you want your numbers in ascending order you can add them into a set and then sort the set into an ascending list.

s = set()
if number1 not in s:
  s.add(number1)
if number2 not in s:
  s.add(number2)
...
s = sorted(s)  #Now a list in ascending order

How to make <input type="file"/> accept only these types?

Use accept attribute with the MIME_type as values

<input type="file" accept="image/gif, image/jpeg" />

How to POST using HTTPclient content type = application/x-www-form-urlencoded

 var params= new Dictionary<string, string>();
 var url ="Please enter URLhere"; 
 params.Add("key1", "value1");
 params.Add("key2", "value2");

 using (HttpClient client = new HttpClient())
  {
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

HttpResponseMessage response = client.PostAsync(url, new FormUrlEncodedContent(dict)).Result;
              var tokne= response.Content.ReadAsStringAsync().Result;
}

//Get response as expected

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

Python readlines() usage and efficient practice for reading

Read line by line, not the whole file:

for line in open(file_name, 'rb'):
    # process line here

Even better use with for automatically closing the file:

with open(file_name, 'rb') as f:
    for line in f:
        # process line here

The above will read the file object using an iterator, one line at a time.

Pygame Drawing a Rectangle

Have you tried this:

PyGame Drawing Basics

Taken from the site:

pygame.draw.rect(screen, color, (x,y,width,height), thickness) draws a rectangle (x,y,width,height) is a Python tuple x,y are the coordinates of the upper left hand corner width, height are the width and height of the rectangle thickness is the thickness of the line. If it is zero, the rectangle is filled

What range of values can integer types store in C++

In C++, now int and other data is stored using 2's compliment method. That means the range is:

-2147483648 to 2147483647

or -2^31 to 2^31-1

1 bit is reserved for 0 so positive value is one less than 2^(31)

How can I run an EXE program from a Windows Service using C#?

You should check this MSDN article and download the .docx file and read it carefully , it was very helpful for me.

However this is a class which works fine for my case :

    [StructLayout(LayoutKind.Sequential)]
    internal struct PROCESS_INFORMATION
    {
        public IntPtr hProcess;
        public IntPtr hThread;
        public uint dwProcessId;
        public uint dwThreadId;
    }
    
    [StructLayout(LayoutKind.Sequential)]
    internal struct SECURITY_ATTRIBUTES
    {
        public uint nLength;
        public IntPtr lpSecurityDescriptor;
        public bool bInheritHandle;
    }


    [StructLayout(LayoutKind.Sequential)]
    public struct STARTUPINFO
    {
        public uint cb;
        public string lpReserved;
        public string lpDesktop;
        public string lpTitle;
        public uint dwX;
        public uint dwY;
        public uint dwXSize;
        public uint dwYSize;
        public uint dwXCountChars;
        public uint dwYCountChars;
        public uint dwFillAttribute;
        public uint dwFlags;
        public short wShowWindow;
        public short cbReserved2;
        public IntPtr lpReserved2;
        public IntPtr hStdInput;
        public IntPtr hStdOutput;
        public IntPtr hStdError;

    }

    internal enum SECURITY_IMPERSONATION_LEVEL
    {
        SecurityAnonymous,
        SecurityIdentification,
        SecurityImpersonation,
        SecurityDelegation
    }

    internal enum TOKEN_TYPE
    {
        TokenPrimary = 1,
        TokenImpersonation
    }

    public static class ProcessAsUser
    {

        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool CreateProcessAsUser(
            IntPtr hToken,
            string lpApplicationName,
            string lpCommandLine,
            ref SECURITY_ATTRIBUTES lpProcessAttributes,
            ref SECURITY_ATTRIBUTES lpThreadAttributes,
            bool bInheritHandles,
            uint dwCreationFlags,
            IntPtr lpEnvironment,
            string lpCurrentDirectory,
            ref STARTUPINFO lpStartupInfo,
            out PROCESS_INFORMATION lpProcessInformation);


        [DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx", SetLastError = true)]
        private static extern bool DuplicateTokenEx(
            IntPtr hExistingToken,
            uint dwDesiredAccess,
            ref SECURITY_ATTRIBUTES lpThreadAttributes,
            Int32 ImpersonationLevel,
            Int32 dwTokenType,
            ref IntPtr phNewToken);


        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool OpenProcessToken(
            IntPtr ProcessHandle,
            UInt32 DesiredAccess,
            ref IntPtr TokenHandle);

        [DllImport("userenv.dll", SetLastError = true)]
        private static extern bool CreateEnvironmentBlock(
                ref IntPtr lpEnvironment,
                IntPtr hToken,
                bool bInherit);


        [DllImport("userenv.dll", SetLastError = true)]
        private static extern bool DestroyEnvironmentBlock(
                IntPtr lpEnvironment);

        [DllImport("kernel32.dll", SetLastError = true)]
        private static extern bool CloseHandle(
            IntPtr hObject);

        private const short SW_SHOW = 5;
        private const uint TOKEN_QUERY = 0x0008;
        private const uint TOKEN_DUPLICATE = 0x0002;
        private const uint TOKEN_ASSIGN_PRIMARY = 0x0001;
        private const int GENERIC_ALL_ACCESS = 0x10000000;
        private const int STARTF_USESHOWWINDOW = 0x00000001;
        private const int STARTF_FORCEONFEEDBACK = 0x00000040;
        private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;


        private static bool LaunchProcessAsUser(string cmdLine, IntPtr token, IntPtr envBlock)
        {
            bool result = false;


            PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
            SECURITY_ATTRIBUTES saProcess = new SECURITY_ATTRIBUTES();
            SECURITY_ATTRIBUTES saThread = new SECURITY_ATTRIBUTES();
            saProcess.nLength = (uint)Marshal.SizeOf(saProcess);
            saThread.nLength = (uint)Marshal.SizeOf(saThread);

            STARTUPINFO si = new STARTUPINFO();
            si.cb = (uint)Marshal.SizeOf(si);


            //if this member is NULL, the new process inherits the desktop
            //and window station of its parent process. If this member is
            //an empty string, the process does not inherit the desktop and
            //window station of its parent process; instead, the system
            //determines if a new desktop and window station need to be created.
            //If the impersonated user already has a desktop, the system uses the
            //existing desktop.

            si.lpDesktop = @"WinSta0\Default"; //Modify as needed
            si.dwFlags = STARTF_USESHOWWINDOW | STARTF_FORCEONFEEDBACK;
            si.wShowWindow = SW_SHOW;
            //Set other si properties as required.

            result = CreateProcessAsUser(
                token,
                null,
                cmdLine,
                ref saProcess,
                ref saThread,
                false,
                CREATE_UNICODE_ENVIRONMENT,
                envBlock,
                null,
                ref si,
                out pi);


            if (result == false)
            {
                int error = Marshal.GetLastWin32Error();
                string message = String.Format("CreateProcessAsUser Error: {0}", error);
                FilesUtilities.WriteLog(message,FilesUtilities.ErrorType.Info);

            }

            return result;
        }


        private static IntPtr GetPrimaryToken(int processId)
        {
            IntPtr token = IntPtr.Zero;
            IntPtr primaryToken = IntPtr.Zero;
            bool retVal = false;
            Process p = null;

            try
            {
                p = Process.GetProcessById(processId);
            }

            catch (ArgumentException)
            {

                string details = String.Format("ProcessID {0} Not Available", processId);
                FilesUtilities.WriteLog(details, FilesUtilities.ErrorType.Info);
                throw;
            }


            //Gets impersonation token
            retVal = OpenProcessToken(p.Handle, TOKEN_DUPLICATE, ref token);
            if (retVal == true)
            {

                SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
                sa.nLength = (uint)Marshal.SizeOf(sa);

                //Convert the impersonation token into Primary token
                retVal = DuplicateTokenEx(
                    token,
                    TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_QUERY,
                    ref sa,
                    (int)SECURITY_IMPERSONATION_LEVEL.SecurityIdentification,
                    (int)TOKEN_TYPE.TokenPrimary,
                    ref primaryToken);

                //Close the Token that was previously opened.
                CloseHandle(token);
                if (retVal == false)
                {
                    string message = String.Format("DuplicateTokenEx Error: {0}", Marshal.GetLastWin32Error());
                    FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

                }

            }

            else
            {

                string message = String.Format("OpenProcessToken Error: {0}", Marshal.GetLastWin32Error());
                FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

            }

            //We'll Close this token after it is used.
            return primaryToken;

        }

        private static IntPtr GetEnvironmentBlock(IntPtr token)
        {

            IntPtr envBlock = IntPtr.Zero;
            bool retVal = CreateEnvironmentBlock(ref envBlock, token, false);
            if (retVal == false)
            {

                //Environment Block, things like common paths to My Documents etc.
                //Will not be created if "false"
                //It should not adversley affect CreateProcessAsUser.

                string message = String.Format("CreateEnvironmentBlock Error: {0}", Marshal.GetLastWin32Error());
                FilesUtilities.WriteLog(message, FilesUtilities.ErrorType.Info);

            }
            return envBlock;
        }

        public static bool Launch(string appCmdLine /*,int processId*/)
        {

            bool ret = false;

            //Either specify the processID explicitly
            //Or try to get it from a process owned by the user.
            //In this case assuming there is only one explorer.exe

            Process[] ps = Process.GetProcessesByName("explorer");
            int processId = -1;//=processId
            if (ps.Length > 0)
            {
                processId = ps[0].Id;
            }

            if (processId > 1)
            {
                IntPtr token = GetPrimaryToken(processId);

                if (token != IntPtr.Zero)
                {

                    IntPtr envBlock = GetEnvironmentBlock(token);
                    ret = LaunchProcessAsUser(appCmdLine, token, envBlock);
                    if (envBlock != IntPtr.Zero)
                        DestroyEnvironmentBlock(envBlock);

                    CloseHandle(token);
                }

            }
            return ret;
        }

    }

And to execute , simply call like this :

string szCmdline = "AbsolutePathToYourExe\\ExeNameWithoutExtension";
ProcessAsUser.Launch(szCmdline);

How to convert string to float?

Use atof() or strtof()* instead:

printf("float value : %4.8f\n" ,atof(s)); 
printf("float value : %4.8f\n" ,strtof(s, NULL)); 

http://www.cplusplus.com/reference/clibrary/cstdlib/atof/
http://www.cplusplus.com/reference/cstdlib/strtof/

  • atoll() is meant for integers.
  • atof()/strtof() is for floats.

The reason why you only get 4.00 with atoll() is because it stops parsing when it finds the first non-digit.

*Note that strtof() requires C99 or C++11.

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

I tried all of the above solutions and it still wouldn't work, until I found that the web.config compilation element was referencing version 2.0.0.0 of WebMatrix.Data and WebMatrix.WebData. Changing the version of those entries in the web.config to 3.0.0.0 helped me.

How can I count the rows with data in an Excel sheet?

If you want a simple one liner that will do it all for you (assuming by no value you mean a blank cell):

=(ROWS(A:A) + ROWS(B:B) + ROWS(C:C)) - COUNTIF(A:C, "")

If by no value you mean the cell contains a 0

=(ROWS(A:A) + ROWS(B:B) + ROWS(C:C)) - COUNTIF(A:C, 0)

The formula works by first summing up all the rows that are in columns A, B, and C (if you need to count more rows, just increase the columns in the range. E.g. ROWS(A:A) + ROWS(B:B) + ROWS(C:C) + ROWS(D:D) + ... + ROWS(Z:Z)).

Then the formula counts the number of values in the same range that are blank (or 0 in the second example).

Last, the formula subtracts the total number of cells with no value from the total number of rows. This leaves you with the number of cells in each row that contain a value

Setting up Vim for Python

Some time ago I installed Valloric/YouCompleteMe and I find it really awesome. It provides you completion for file paths, function names, methods, variable names... Together with davidhalter/jedi-vim it makes vim great for python programming (the only thing missing now is a linter).

UNIX export command

export is a built-in command of the bash shell and other Bourne shell variants. It is used to mark a shell variable for export to child processes.

Dropping Unique constraint from MySQL table

You can DROP a unique constraint from a table using phpMyAdmin as requested as shown in the table below. A unique constraint has been placed on the Wingspan field. The name of the constraint is the same as the field name, in this instance.

alt text

Adding a dictionary to another

You can loop through all the Animals using foreach and put it into NewAnimals.

How can I pass a parameter to a setTimeout() callback?

setTimeout is part of the DOM defined by WHAT WG.

https://html.spec.whatwg.org/multipage/timers-and-user-prompts.html

The method you want is:—

handle = self.setTimeout( handler [, timeout [, arguments... ] ] )

Schedules a timeout to run handler after timeout milliseconds. Any arguments are passed straight through to the handler.

setTimeout(postinsql, 4000, topicId);

Apparently, extra arguments are supported in IE10. Alternatively, you can use setTimeout(postinsql.bind(null, topicId), 4000);, however passing extra arguments is simpler, and that's preferable.

Historical factoid: In days of VBScript, in JScript, setTimeout's third parameter was the language, as a string, defaulting to "JScript" but with the option to use "VBScript". https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa741500(v%3Dvs.85)

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

Gradle - Could not find or load main class

In my build.gradle, I resolved this issue by creating a task and then specifying the "mainClassName" as follows:

task(runSimpleXYZProgram, group: 'algorithms', description: 'Description of what your program does', dependsOn: 'classes', type: JavaExec) {
    mainClassName = 'your.entire.package.classContainingYourMainMethod'
}

Angular.js How to change an elements css class on click and to remove all others

I only change/remove the class:

   function removeClass() {
                    var element = angular.element('#nameInput');
          element.removeClass('nameClass');
   };

When and why do I need to use cin.ignore() in C++?

Ignore is exactly what the name implies.

It doesn't "throw away" something you don't need instead, it ignores the amount of characters you specify when you call it, up to the char you specify as a breakpoint.

It works with both input and output buffers.

Essentially, for std::cin statements you use ignore before you do a getline call, because when a user inputs something with std::cin, they hit enter and a '\n' char gets into the cin buffer. Then if you use getline, it gets the newline char instead of the string you want. So you do a std::cin.ignore(1000,'\n') and that should clear the buffer up to the string that you want. (The 1000 is put there to skip over a specific amount of chars before the specified break point, in this case, the \n newline character.)

How to disable gradle 'offline mode' in android studio?

@mikepenz has the right one.

You could just hit SHIFT+COMMAND+A (if you're using OSX and 1.4 android studio) and enter OFFLINE in the search box.

Then you'll see what mike have shown you.

Just deselect offline.

Open URL in new window with JavaScript

Just use window.open() function? The third parameter lets you specify window size.

Example

var strWindowFeatures = "location=yes,height=570,width=520,scrollbars=yes,status=yes";
var URL = "https://www.linkedin.com/cws/share?mini=true&amp;url=" + location.href;
var win = window.open(URL, "_blank", strWindowFeatures);

Decoding UTF-8 strings in Python

You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

Because you do not provide any context or code for your question it is not possible to give a direct answer.

I suggest you study how unicode and character encoding is done in Python:

http://docs.python.org/2/howto/unicode.html

How to find list of possible words from a letter matrix [Boggle Solver]

I spent 3 months working on a solution to the 10 best point dense 5x5 Boggle boards problem.

The problem is now solved and laid out with full disclosure on 5 web pages. Please contact me with questions.

The board analysis algorithm uses an explicit stack to pseudo-recursively traverse the board squares through a Directed Acyclic Word Graph with direct child information, and a time stamp tracking mechanism. This may very well be the world's most advanced lexicon data structure.

The scheme evaluates some 10,000 very good boards per second on a quad core. (9500+ points)

Parent Web Page:

DeepSearch.c - http://www.pathcom.com/~vadco/deep.html

Component Web Pages:

Optimal Scoreboard - http://www.pathcom.com/~vadco/binary.html

Advanced Lexicon Structure - http://www.pathcom.com/~vadco/adtdawg.html

Board Analysis Algorithm - http://www.pathcom.com/~vadco/guns.html

Parallel Batch Processing - http://www.pathcom.com/~vadco/parallel.html

- This comprehensive body of work will only interest a person who demands the very best.

Detect if Android device has Internet connection

I have modified THelper's answer slightly, to use a known hack that Android already uses to check if the connected WiFi network has Internet access. This is a lot more efficient over grabbing the entire Google home page. See here and here for more info.

public static boolean hasInternetAccess(Context context) {
    if (isNetworkAvailable(context)) {
        try {
            HttpURLConnection urlc = (HttpURLConnection) 
                (new URL("http://clients3.google.com/generate_204")
                .openConnection());
            urlc.setRequestProperty("User-Agent", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500); 
            urlc.connect();
            return (urlc.getResponseCode() == 204 &&
                        urlc.getContentLength() == 0);
        } catch (IOException e) {
            Log.e(TAG, "Error checking internet connection", e);
        }
    } else {
        Log.d(TAG, "No network available!");
    }
    return false;
}

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

How to change a table name using an SQL query?

rename table name :

RENAME TABLE old_tableName TO new_tableName;

for example:

RENAME TABLE company_name TO company_master;

sklearn: Found arrays with inconsistent numbers of samples when calling LinearRegression.fit()

I think the "X" argument of regr.fit needs to be a matrix, so the following should work.

regr = LinearRegression()
regr.fit(df2.iloc[1:1000, [5]].values, df2.iloc[1:1000, 2].values)

Maven plugins can not be found in IntelliJ

If you have red squiggles underneath the project in the Maven plugin, try clicking the "Reimport All Maven Projects" button (looks like a refresh symbol).

Reimport all Maven Projects

How to run the Python program forever?

I have a small script interruptableloop.py that runs the code at an interval (default 1sec), it pumps out a message to the screen while it's running, and traps an interrupt signal that you can send with CTL-C:

#!/usr/bin/python3
from interruptableLoop import InterruptableLoop

loop=InterruptableLoop(intervalSecs=1) # redundant argument
while loop.ShouldContinue():
   # some python code that I want 
   # to keep on running
   pass

When you run the script and then interrupt it you see this output, (the periods pump out on every pass of the loop):

[py36]$ ./interruptexample.py
CTL-C to stop   (or $kill -s SIGINT pid)
......^C
Exiting at  2018-07-28 14:58:40.359331

interruptableLoop.py:

"""
    Use to create a permanent loop that can be stopped ...

    ... from same terminal where process was started and is running in foreground: 
        CTL-C

    ... from same user account but through a different terminal 
        $ kill -2 <pid> 
        or $ kill -s SIGINT <pid>

"""
import signal
import time
from datetime import datetime as dtt
__all__=["InterruptableLoop",]
class InterruptableLoop:
    def __init__(self,intervalSecs=1,printStatus=True):
        self.intervalSecs=intervalSecs
        self.shouldContinue=True
        self.printStatus=printStatus
        self.interrupted=False
        if self.printStatus:
            print ("CTL-C to stop\t(or $kill -s SIGINT pid)")
        signal.signal(signal.SIGINT, self._StopRunning)
        signal.signal(signal.SIGQUIT, self._Abort)
        signal.signal(signal.SIGTERM, self._Abort)

    def _StopRunning(self, signal, frame):
        self.shouldContinue = False

    def _Abort(self, signal, frame):
        raise 

    def ShouldContinue(self):
        time.sleep(self.intervalSecs)
        if self.shouldContinue and self.printStatus: 
            print( ".",end="",flush=True)
        elif not self.shouldContinue and self.printStatus:
            print ("Exiting at ",dtt.now())
        return self.shouldContinue

Angularjs prevent form submission when input validation fails

I know this is an old thread but I thought I'd also make a contribution. My solution being similar to the post already marked as an answer. Some inline JavaScript checks does the trick.

ng-click="form.$invalid ? alert('Please correct the form') : saveTask(task)"

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

Opposite of append in jquery

The opposite of .append() is .prepend().

From the jQuery documentation for prepend…

The .prepend() method inserts the specified content as the first child of each element in the jQuery collection (To insert it as the last child, use .append()).

I realize this doesn’t answer the OP’s specific case. But it does answer the question heading. :) And it’s the first hit on Google for “jquery opposite append”.

htaccess - How to force the client's browser to clear the cache?

You can tell the browser never cache your site by pasting following code in the header

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />

And to prevent js, css cache, you could use tool to minify and obfuscate the scripts which should generate a random file name every time. That would force the browser to reload them from server too.

Hopefully, that helps.

How can I get customer details from an order in WooCommerce?

I did manage to figure it out:

$order_meta    = get_post_meta($order_id);
$email         = $order_meta["_shipping_email"][0] ?: $order_meta["_billing_email"][0];

I do know know for sure if the shipping email is part of the metadata, but if so I would rather have it than the billing email - at least for my purposes.

CSS "and" and "or"

To select properties a AND b of a X element:

X[a][b]

To select properties a OR b of a X element:

X[a],X[b]

How to style the parent element when hovering a child element?

I know it is an old question, but I just managed to do so without a pseudo child (but a pseudo wrapper).

If you set the parent to be with no pointer-events, and then a child div with pointer-events set to auto, it works:)
Note that <img> tag (for example) doesn't do the trick.
Also remember to set pointer-events to auto for other children which have their own event listener, or otherwise they will lose their click functionality.

_x000D_
_x000D_
div.parent {  _x000D_
    pointer-events: none;_x000D_
}_x000D_
_x000D_
div.child {_x000D_
    pointer-events: auto;_x000D_
}_x000D_
_x000D_
div.parent:hover {_x000D_
    background: yellow;_x000D_
}    
_x000D_
<div class="parent">_x000D_
  parent - you can hover over here and it won't trigger_x000D_
  <div class="child">hover over the child instead!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Edit:
As Shadow Wizard kindly noted: it's worth to mention this won't work for IE10 and below. (Old versions of FF and Chrome too, see here)

Problems with a PHP shell script: "Could not open input file"

I landed up on this page when searching for a solution for “Could not open input file” error. Here's my 2 cents for this error.

I faced this same error while because I was using parameters in my php file path like this:

/usr/bin/php -q /home/**/public_html/cron/job.php?id=1234

But I found out that this is not the proper way to do it. The proper way of sending parameters is like this:

/usr/bin/php -q /home/**/public_html/cron/job.php id=1234

Just replace the "?" with a space " ".

Bootstrap: adding gaps between divs

Adding a padding between the divs to simulate a gap might be a hack, but why not use something Bootstrap provides. It's called offsets. But again, you can define a class in your custom.css (you shouldn't edit the core stylesheet anyway) file and add something like .gap. However, .col-md-offset-* does the job most of the times for me, allowing me to precisely leave a gap between the divs.

As for vertical spacing, unfortunately, there isn't anything set built-in like that in Bootstrap 3, so you will have to invent your own custom class to do that. I'd usually do something like .top-buffer { margin-top:20px; }. This does the trick, and obviously, it doesn't have to be 20px, it can be anything you like.

How to convert any date format to yyyy-MM-dd

Try this code:

 lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");

Checking if output of a command contains a certain string in a shell script

Testing $? is an anti-pattern.

if ./somecommand | grep -q 'string'; then
  echo "matched"
fi

Disabled UIButton not faded or grey

It looks like the following code works fine. But in some cases, this doesn't work.

sendButton.enabled = NO;
sendButton.alpha = 0.5;

If the above code doesn't work, please wrap it in Main Thread. so

dispatch_async(dispatch_get_main_queue(), ^{
    sendButton.enabled = NO;
    sendButton.alpha = 0.5
});

if you go with swift, like this

DispatchQueue.main.async {
    sendButton.isEnabled = false
    sendButton.alpha = 0.5
}

In addition, if you customized UIButton, add this to the Button class.

override var isEnabled: Bool {
    didSet {
        DispatchQueue.main.async {
            if self.isEnabled {
                self.alpha = 1.0
            }
            else {
                self.alpha = 0.5
            }
        }
    }
}

Thank you and enjoy coding!!!

How do you cast a List of supertypes to a List of subtypes?

I think you are casting in the wrong direction though... if the method returns a list of TestA objects, then it really isn't safe to cast them to TestB.

Basically you are asking the compiler to let you perform TestB operations on a type TestA that does not support them.

Executing another application from Java

I assume that you know how to execute the command using the ProcessBuilder.

Executing a command from Java always should read the stdout and stderr streams from the process. Otherwise it can happen that the buffer is full and the process cannot continue because writing its stdout or stderr blocks.

REST API - why use PUT DELETE POST GET?

You asked:

wouldn't it be easier to just accept JSON object through normal $_POST and then respond in JSON as well

From the Wikipedia on REST:

RESTful applications maximize the use of the pre-existing, well-defined interface and other built-in capabilities provided by the chosen network protocol, and minimize the addition of new application-specific features on top of it

From what (little) I've seen, I believe this is usually accomplished by maximizing the use of existing HTTP verbs, and designing a URL scheme for your service that is as powerful and self-evident as possible.

Custom data protocols (even if they are built on top of standard ones, such as SOAP or JSON) are discouraged, and should be minimized to best conform to the REST ideology.

SOAP RPC over HTTP, on the other hand, encourages each application designer to define a new and arbitrary vocabulary of nouns and verbs (for example getUsers(), savePurchaseOrder(...)), usually overlaid onto the HTTP 'POST' verb. This disregards many of HTTP's existing capabilities such as authentication, caching and content type negotiation, and may leave the application designer re-inventing many of these features within the new vocabulary.

The actual objects you are working with can be in any format. The idea is to reuse as much of HTTP as possible to expose your operations the user wants to perform on those resource (queries, state management/mutation, deletion).

You asked:

Am I missing something?

There is a lot more to know about REST and the URI syntax/HTTP verbs themselves. For example, some of the verbs are idempotent, others aren't. I didn't see anything about this in your question, so I didn't bother trying to dive into it. The other answers and Wikipedia both have a lot of good information.

Also, there is a lot to learn about the various network technologies built on top of HTTP that you can take advantage of if you're using a truly restful API. I'd start with authentication.

How does one use glide to download an image into a bitmap?

It looks like overriding the Target class or one of the implementations like BitmapImageViewTarget and overriding the setResource method to capture the bitmap might be the way to go...

This is untested. :-)

    Glide.with(context)
         .load("http://goo.gl/h8qOq7")
         .asBitmap()
         .into(new BitmapImageViewTarget(imageView) {
                     @Override
                     protected void setResource(Bitmap resource) {
                         // Do bitmap magic here
                         super.setResource(resource);
                     }
         });

Bash command line and input limit

Ok, Denizens. So I have accepted the command line length limits as gospel for quite some time. So, what to do with one's assumptions? Naturally- check them.

I have a Fedora 22 machine at my disposal (meaning: Linux with bash4). I have created a directory with 500,000 inodes (files) in it each of 18 characters long. The command line length is 9,500,000 characters. Created thus:

seq 1 500000 | while read digit; do
    touch $(printf "abigfilename%06d\n" $digit);
done

And we note:

$ getconf ARG_MAX
2097152

Note however I can do this:

$ echo * > /dev/null

But this fails:

$ /bin/echo * > /dev/null
bash: /bin/echo: Argument list too long

I can run a for loop:

$ for f in *; do :; done

which is another shell builtin.

Careful reading of the documentation for ARG_MAX states, Maximum length of argument to the exec functions. This means: Without calling exec, there is no ARG_MAX limitation. So it would explain why shell builtins are not restricted by ARG_MAX.

And indeed, I can ls my directory if my argument list is 109948 files long, or about 2,089,000 characters (give or take). Once I add one more 18-character filename file, though, then I get an Argument list too long error. So ARG_MAX is working as advertised: the exec is failing with more than ARG_MAX characters on the argument list- including, it should be noted, the environment data.

Using AES encryption in C#

You can use password from text box like key... With this code you can encrypt/decrypt text, picture, word document, pdf....

 public class Rijndael
{
    private byte[] key;
    private readonly byte[] vector = { 255, 64, 191, 111, 23, 3, 113, 119, 231, 121, 252, 112, 79, 32, 114, 156 };

    ICryptoTransform EnkValue, DekValue;

    public Rijndael(byte[] key)
    {
        this.key = key;
        RijndaelManaged rm = new RijndaelManaged();
        rm.Padding = PaddingMode.PKCS7;
        EnkValue = rm.CreateEncryptor(key, vector);
        DekValue = rm.CreateDecryptor(key, vector);
    }

    public byte[] Encrypt(byte[] byte)
    {

        byte[] enkByte= byte;
        byte[] enkNewByte;
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, EnkValue, CryptoStreamMode.Write))
            {
                cs.Write(enkByte, 0, enkByte.Length);
                cs.FlushFinalBlock();

                ms.Position = 0;
                enkNewByte= new byte[ms.Length];
                ms.Read(enkNewByte, 0, enkNewByte.Length);
            }
        }
        return enkNeyByte;
    }

    public byte[] Dekrypt(byte[] enkByte)
    {
        byte[] dekByte;
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, DekValue, CryptoStreamMode.Write))
            {
                cs.Write(enkByte, 0, enkByte.Length);
                cs.FlushFinalBlock();

                ms.Position = 0;
                dekByte= new byte[ms.Length];
                ms.Read(dekByte, 0, dekByte.Length);
            }
        }
        return dekByte;
    }
}

Convert password from text box to byte array...

private byte[] ConvertPasswordToByte(string password)
    {
        byte[] key = new byte[32];
        for (int i = 0; i < passwprd.Length; i++)
        {
            key[i] = Convert.ToByte(passwprd[i]);
        }
        return key;
    }

What is the max size of VARCHAR2 in PL/SQL and SQL?

See the official documentation (http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements001.htm#i54330)

Variable-length character string having maximum length size bytes or characters. Maximum size is 4000 bytes or characters, and minimum is 1 byte or 1 character. You must specify size for VARCHAR2. BYTE indicates that the column will have byte length semantics; CHAR indicates that the column will have character semantics.

But in Oracle Databast 12c maybe 32767 (http://docs.oracle.com/database/121/SQLRF/sql_elements001.htm#SQLRF30020)

Variable-length character string having maximum length size bytes or characters. You must specify size for VARCHAR2. Minimum size is 1 byte or 1 character. Maximum size is: 32767 bytes or characters if MAX_STRING_SIZE = EXTENDED 4000 bytes or characters if MAX_STRING_SIZE = STANDARD

Installing Tomcat 7 as Service on Windows Server 2008

I have spent a couple of hours looking for the magic configuration to get Tomcat 7 running as a service on Windows Server 2008... no luck.

I do have a solution though.

My install of Tomcat 7 works just fine if I just jump into a console window and run...

C:\apache-tomcat-7.0.26\bin\start.bat

At this point another console window pops up and tails the logs (tail meaning show the server logs as they happen).

SOLUTION

Run the start.bat file as a Scheduled Task.

  1. Start Menu > Accessories > System Tools > Task Scheduler

  2. In the Actions Window: Create Basic Task...

  3. Name the task something like "Start Tomcat 7" or something that makes sense a year from now.

  4. Click Next >

  5. Trigger should be set to "When the computer starts"

  6. Click Next >

  7. Action should be set to "Start a program"

  8. Click Next >

  9. Program/script: should be set to the location of the startup.bat file.

  10. Click Next >

  11. Click Finish

  12. IF YOUR SERVER IS NOT BEING USED: Reboot your server to test this functionality

How do I write a Windows batch script to copy the newest file from a directory?

Bash:

 find -type f -printf "%T@ %p \n" \
     | sort  \
     | tail -n 1  \
     | sed -r "s/^\S+\s//;s/\s*$//" \
     | xargs -iSTR cp STR newestfile

where "newestfile" will become the newestfile

alternatively, you could do newdir/STR or just newdir

Breakdown:

  1. list all files in {time} {file} format.
  2. sort them by time
  3. get the last one
  4. cut off the time, and whitespace from the start/end
  5. copy resulting value

Important

After running this once, the newest file will be whatever you just copied :p ( assuming they're both in the same search scope that is ). So you may have to adjust which filenumber you copy if you want this to work more than once.

How to convert string to long

import org.apache.commons.lang.math.NumberUtils;

This will handle null

NumberUtils.createLong(String)

Collision Detection between two images in Java

Use a rectangle to surround each player and enemy, the height and width of the rectangles should correspond to the object you're surrounding, imagine it being in a box only big enough to fit it.

Now, you move these rectangles the same as you do the objects, so they have a 'bounding box'

I'm not sure if Java has this, but it might have a method on the rectangle object called .intersects() so you'd do if(rectangle1.intersectS(rectangle2) to check to see if an object has collided with another.

Otherwise you can get the x and y co-ordinates of the boxes and using the height/width of them detect whether they've intersected yourself.

Anyway, you can use that to either do an event on intersection (make one explode, or whatever) or prevent the movement from being drawn. (revert to previous co-ordinates)

edit: here we go

boolean

intersects(Rectangle r) Determines whether or not this Rectangle and the specified Rectangle intersect.

So I would do (and don't paste this code, it most likely won't work, not done java for a long time and I didn't do graphics when I did use it.)

Rectangle rect1 = new Rectangle(player.x, player.y, player.width, player.height);

Rectangle rect2 = new Rectangle(enemy.x, enemy.y, enemy.width, enemy.height);

//detects when the two rectangles hit
if(rect1.intersects(rect2))
{

System.out.println("game over, g");
}

obviously you'd need to fit that in somewhere.

How to convert NSNumber to NSString

//An example of implementation :
// we set the score of one player to a value
[Game getCurrent].scorePlayer1 = [NSNumber numberWithInteger:1];
// We copy the value in a NSNumber
NSNumber *aNumber = [Game getCurrent].scorePlayer1;
// Conversion of the NSNumber aNumber to a String with stringValue
NSString *StringScorePlayer1 = [aNumber stringValue];

How to connect a Windows Mobile PDA to Windows 10

I have managed to get my PDA working properly with Windows 10.

For transparency when I posted the original question I had upgraded a Windows 8.1 PC to Windows 10, I have since moved to using a different PC that had a clean Windows 10 installation.

These are the steps I followed to solve the problem:

How to enable GZIP compression in IIS 7.5

Global Gzip in HttpModule

If you don't have access to shared hosting - the final IIS instance. You can create a HttpModule that gets added this code to every HttpApplication.Begin_Request event:-

HttpContext context = HttpContext.Current;
context.Response.Filter = new GZipStream(context.Response.Filter, CompressionMode.Compress);
HttpContext.Current.Response.AppendHeader("Content-encoding", "gzip");
HttpContext.Current.Response.Cache.VaryByHeaders["Accept-encoding"] = true;

Gradle version 2.2 is required. Current version is 2.10

The android studio and Gradle version looks like very bad managed. And there's tons of version in-capability issues. And the error message is mostly clueless. For this particular issue. The closest answer is from "Jitendra Singh". Change the version to:

 classpath 'com.android.tools.build:gradle:2.0.0'

But in my case: Android studio 2.2 RC, I still get another error:

Could not find matching constructor for: com.android.build.gradle.internal.LibraryTaskManager(org.gradle.api.internal.project.DefaultProject_Decorated, com.android.builder.core.AndroidBuilder, android.databinding.tool.DataBindingBuilder, com.android.build.gradle.LibraryExtension_Decorated, com.android.build.gradle.internal.SdkHandler, com.android.build.gradle.internal.DependencyManager, org.gradle.tooling.provider.model.internal.DefaultToolingModelBuilderRegistry)

So I went to the maven central to find the latest com.android.tools.build:gradle version which is 2.1.3 for now. So after change to

buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.1.3'
    }
}

Solved my problem eventually.

DATEDIFF function in Oracle

You can simply subtract two dates. You have to cast it first, using to_date:

select to_date('2000-01-01', 'yyyy-MM-dd')
       - to_date('2000-01-02', 'yyyy-MM-dd')
       datediff
from   dual
;

The result is in days, to the difference of these two dates is -1 (you could swap the two dates if you like). If you like to have it in hours, just multiply the result with 24.

How to view method information in Android Studio?

If you need only Parameter info then:

On Mac, it's assigned to Command+P

On Windows, it's assigned to Ctrl+P

If you need document info then:

On Mac, it's assigned to Command+Q

On Windows, it's assigned to Ctrl+Q

Start a fragment via Intent within a Fragment

Try this it may help you:

private void changeFragment(Fragment targetFragment){

    getSupportFragmentManager()
         .beginTransaction()
         .replace(R.id.main_fragment, targetFragment, "fragment")
         .setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
         .commit();

}

How to remove all options from a dropdown using jQuery / JavaScript

Other approach for Vanilla JavaScript:

for(var o of document.querySelectorAll('#models > option')) {
  o.remove()
}

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

mailto using javascript

I've simply used this javascript code (using jquery but it's not strictly necessary) :

    $( "#button" ).on( "click", function(event) {
         $(this).attr('href', 'mailto:[email protected]?subject=hello');
    });

When users click on the link, we replace the href attribute of the clicked element.

Be careful don't prevent the default comportment (event.preventDefault), we must let do it because we have just replaced the href where to go

I think robots can't see it, the address is protected from spams.

ggplot combining two plots from different data.frames

The only working solution for me, was to define the data object in the geom_line instead of the base object, ggplot.

Like this:

ggplot() + 
geom_line(data=Data1, aes(x=A, y=B), color='green') + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

instead of

ggplot(data=Data1, aes(x=A, y=B), color='green') + 
geom_line() + 
geom_line(data=Data2, aes(x=C, y=D), color='red')

More info here

NodeJS w/Express Error: Cannot GET /

You need to add a return to the index.html file.

app.use(express.static(path.join(__dirname, 'build')));

app.get('*', function(req, res) {res.sendFile(path.join(__dirname + '/build/index.html')); });

How to get primary key column in Oracle?

Same as the answer from 'Richie' but a bit more concise.

  1. Query for user constraints only

    SELECT column_name FROM all_cons_columns WHERE constraint_name = (
      SELECT constraint_name FROM user_constraints 
      WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
    );
    
  2. Query for all constraints

    SELECT column_name FROM all_cons_columns WHERE constraint_name = (
      SELECT constraint_name FROM all_constraints 
      WHERE UPPER(table_name) = UPPER('tableName') AND CONSTRAINT_TYPE = 'P'
    );
    

Is jQuery $.browser Deprecated?

From the official documentation at http://api.jquery.com/jQuery.browser/:

This property was removed in jQuery 1.9 and is available only through the jQuery.migrate plugin.

You can use for example jquery-migrate-1.4.1.js to keep your existing code or plugins that use $.browser still working while you find a way to totally get rid of $.browser from your code in the future.

How can I join on a stored procedure?

Here's a terrible idea for you.

Use an alias, create a new linked server from your server to its own alias.

Now you can do:

select a.SomeColumns, b.OtherColumns
from LocalDb.dbo.LocalTable a
inner join (select * from openquery([AliasToThisServer],'
exec LocalDb.dbo.LocalStoredProcedure
') ) b
on a.Id = b.Id

string.IsNullOrEmpty(string) vs. string.IsNullOrWhiteSpace(string)

Here is the actual implementation of both methods ( decompiled using dotPeek)

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
    public static bool IsNullOrEmpty(string value)
    {
      if (value != null)
        return value.Length == 0;
      else
        return true;
    }

    /// <summary>
    /// Indicates whether a specified string is null, empty, or consists only of white-space characters.
    /// </summary>
    /// 
    /// <returns>
    /// true if the <paramref name="value"/> parameter is null or <see cref="F:System.String.Empty"/>, or if <paramref name="value"/> consists exclusively of white-space characters.
    /// </returns>
    /// <param name="value">The string to test.</param>
    public static bool IsNullOrWhiteSpace(string value)
    {
      if (value == null)
        return true;
      for (int index = 0; index < value.Length; ++index)
      {
        if (!char.IsWhiteSpace(value[index]))
          return false;
      }
      return true;
    }

What is the difference between a static method and a non-static method?

Static methods are useful if you have only one instance (situation, circumstance) where you're going to use the method, and you don't need multiple copies (objects). For example, if you're writing a method that logs onto one and only one web site, downloads the weather data, and then returns the values, you could write it as static because you can hard code all the necessary data within the method and you're not going to have multiple instances or copies. You can then access the method statically using one of the following:

MyClass.myMethod();
this.myMethod();
myMethod();

Non-static methods are used if you're going to use your method to create multiple copies. For example, if you want to download the weather data from Boston, Miami, and Los Angeles, and if you can do so from within your method without having to individually customize the code for each separate location, you then access the method non-statically:

MyClass boston = new MyClassConstructor(); 
boston.myMethod("bostonURL");

MyClass miami = new MyClassConstructor(); 
miami.myMethod("miamiURL");

MyClass losAngeles = new MyClassConstructor();
losAngeles.myMethod("losAngelesURL");

In the above example, Java creates three separate objects and memory locations from the same method that you can individually access with the "boston", "miami", or "losAngeles" reference. You can't access any of the above statically, because MyClass.myMethod(); is a generic reference to the method, not to the individual objects that the non-static reference created.

If you run into a situation where the way you access each location, or the way the data is returned, is sufficiently different that you can't write a "one size fits all" method without jumping through a lot of hoops, you can better accomplish your goal by writing three separate static methods, one for each location.

Python Remove last 3 characters of a string

I try to avoid regular expressions, but this appears to work:

string = re.sub("\s","",(string.lower()))[:-3]

Testing if value is a function

// This should be a function, because in certain JavaScript engines (V8, for
// example, try block kills many optimizations).
function isFunction(func) {
    // For some reason, function constructor doesn't accept anonymous functions.
    // Also, this check finds callable objects that aren't function (such as,
    // regular expressions in old WebKit versions), as according to EcmaScript
    // specification, any callable object should have typeof set to function.
    if (typeof func === 'function')
        return true

    // If the function isn't a string, it's probably good idea to return false,
    // as eval cannot process values that aren't strings.
    if (typeof func !== 'string')
        return false

    // So, the value is a string. Try creating a function, in order to detect
    // syntax error.
    try {
        // Create a function with string func, in order to detect whatever it's
        // an actual function. Unlike examples with eval, it should be actually
        // safe to use with any string (provided you don't call returned value).
        Function(func)
        return true
    }
    catch (e) {
        // While usually only SyntaxError could be thrown (unless somebody
        // modified definition of something used in this function, like
        // SyntaxError or Function, it's better to prepare for unexpected.
        if (!(e instanceof SyntaxError)) {
            throw e
        }

        return false
    }
}

Make anchor link go some pixels above where it's linked to

Put this in style :

.hash_link_tag{margin-top: -50px; position: absolute;}

and use this class in separate div tag before the links, example:

<div class="hash_link_tag" id="link1"></div> 
<a href="#link1">Link1</a>

or use this php code for echo link tag:

function HashLinkTag($id)
{
    echo "<div id='$id' class='hash_link_tag'></div>";
}

Multiple input in JOptionPane.showInputDialog

Yes. You know that you can put any Object into the Object parameter of most JOptionPane.showXXX methods, and often that Object happens to be a JPanel.

In your situation, perhaps you could use a JPanel that has several JTextFields in it:

import javax.swing.*;

public class JOptionPaneMultiInput {
   public static void main(String[] args) {
      JTextField xField = new JTextField(5);
      JTextField yField = new JTextField(5);

      JPanel myPanel = new JPanel();
      myPanel.add(new JLabel("x:"));
      myPanel.add(xField);
      myPanel.add(Box.createHorizontalStrut(15)); // a spacer
      myPanel.add(new JLabel("y:"));
      myPanel.add(yField);

      int result = JOptionPane.showConfirmDialog(null, myPanel, 
               "Please Enter X and Y Values", JOptionPane.OK_CANCEL_OPTION);
      if (result == JOptionPane.OK_OPTION) {
         System.out.println("x value: " + xField.getText());
         System.out.println("y value: " + yField.getText());
      }
   }
}

jQuery click events not working in iOS

Recently when working on a web app for a client, I noticed that any click events added to a non-anchor element didn't work on the iPad or iPhone. All desktop and other mobile devices worked fine - but as the Apple products are the most popular mobile devices, it was important to get it fixed.

Turns out that any non-anchor element assigned a click handler in jQuery must either have an onClick attribute (can be empty like below):

onClick=""

OR

The element css needs to have the following declaration:

cursor:pointer

Strange, but that's what it took to get things working again!
source:http://www.mitch-solutions.com/blog/17-ipad-jquery-live-click-events-not-working

How To Format A Block of Code Within a Presentation?

An on-line syntax highlighter:

http://markup.su/highlighter/

or

http://hilite.me/

Just copy and paste into your document.

ImportError: No module named pandas

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

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

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

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

Change text color with Javascript?

<div id="about">About Snakelane</div>

<input type="image" src="http://www.blakechris.com/snakelane/assets/about.png" onclick="init()" id="btn">
<script>
var about;   
function init() { 
    about = document.getElementById("about");
    about.style.color = 'blue';
}

How can I run multiple npm scripts in parallel?

If you replace the double ampersand with a single ampersand, the scripts will run concurrently.

How to append text to an existing file in Java?

For JDK version >= 7

You can utilise this simple method which appends the given content to the specified file:

void appendToFile(String filePath, String content) {
  try (FileWriter fw = new FileWriter(filePath, true)) {
    fw.write(content + System.lineSeparator());
  } catch (IOException e) { 
    // TODO handle exception
  }
}

We are constructing a FileWriter object in append mode.

Run CSS3 animation only once (at page loading)

It can be done with a little bit of extra overhead.

Simply wrap your link in a div, and separate the animation.

the html ..

<div class="animateOnce">
    <a class="animateOnHover">me!</a>
</div>

.. and the css ..

.animateOnce {
    animation: splash 1s normal forwards ease-in-out;
}

.animateOnHover:hover {
    animation: hover 1s infinite alternate ease-in-out;
}

CSS - make div's inherit a height

The Problem

When an element is floated, its parent no longer contains it because the float is removed from the flow. The floated element is out of the natural flow, so all block elements will render as if the floated element is not even there, so a parent container will not fully expand to hold the floated child element.

Take a look at the following article to get a better idea of how the CSS Float property works:

The Mystery Of The CSS Float Property


A Potential Solution

Now, I think the following article resembles what you're trying to do. Take a look at it and see if you can solve your problem.

Equal Height Columns with Cross-Browser CSS

I hope this helps.

How to close TCP and UDP ports via windows command line

you can use program like tcpview from sysinternal. I guess it can help you a lot on both monitoring and killing unwanted connection.

Can I draw rectangle in XML?

create resource file in drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#3b5998" />
<cornersandroid:radius="15dp"/>

Network usage top/htop on Linux

iptraf is my favorite. It has a nice ncurses interface, and options for filtering, etc.

enter image description here

How to run a jar file in a linux commandline

Under linux there's a package called binfmt-support that allows you to run directly your jar without typing java -jar:

sudo apt-get install binfmt-support
chmod u+x my-jar.jar
./my-jar.jar # there you go!

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

For me, it worked as given below:

<div ng-repeat="product in products | filter: { color: 'red'||'blue' }">

<div ng-repeat="product in products | filter: { color: 'red'} | filter: { color:'blue' }">

R color scatter plot points based on values

Also it'd work to just specify ifelse() twice:

plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))

NVIDIA-SMI has failed because it couldn't communicate with the NVIDIA driver

I am working with a AWS DeepAMI P2 instance and suddenly I found that Nvidia-driver command doesn't working and GPU is not found torch or tensorflow library. Then I have resolved the problem in the following way,

Run nvcc --version if it doesn't work

Then run the following

apt install nvidia-cuda-toolkit

Hopefully that will solve the problem.

Hiding axis text in matplotlib plots

When using the object oriented API, the Axes object has two useful methods for removing the axis text, set_xticklabels() and set_xticks().

Say you create a plot using

fig, ax = plt.subplots(1)
ax.plot(x, y)

If you simply want to remove the tick labels, you could use

ax.set_xticklabels([])

or to remove the ticks completely, you could use

ax.set_xticks([])

These methods are useful for specifying exactly where you want the ticks and how you want them labeled. Passing an empty list results in no ticks, or no labels, respectively.

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

Even I got the same issue and my mistake was that I didn't download python MSI file. You will get it here: https://www.python.org/downloads/

Once you download the msi, run the setup and that will solve the problem. After that you can go to File->Settings->Project Settings->Project Interpreter->Python Interpreters

and select the python.exe file. (This file will be available at c:\Python34) Select the python.exe file. That's it.

JQuery show/hide when hover

('.cat').hover(
  function () {
    $(this).show();
  }, 
  function () {
    $(this).hide();
  }
);

It's the same for the others.

For the smooth fade in you can use fadeIn and fadeOut

C# Foreach statement does not contain public definition for GetEnumerator

In foreach loop instead of carBootSaleList use carBootSaleList.data.

You probably do not need answer anymore, but it could help someone.

HashSet vs LinkedHashSet

HashSet:

The underlined data structure is Hashtable. Duplicate objects are not allowed.insertion order is not preserved and it is based on hash code of objects. Null insertion is possible(only once). It implements Serializable, Clonable but not RandomAccess interface. HashSet is best choose if frequent operation is search operation.

In HashSet duplicates are not allowed.if users are trying to insert duplicates when we won't get any compile or runtime exceptions. add method returns simply false.

Constructors:

HashSet h=new HashSet(); creates an empty HashSet object with default initial capacity 16 and default fill ratio(Load factor) is 0.75 .

HashSet h=new HashSet(int initialCapacity); creates an empty HashSet object with specified initialCapacity and default fill ration is 0.75.

HashSet h=new HashSet(int initialCapacity, float fillRatio);

HashSet h=new HashSet(Collection c); creates an equivalent HashSet object for the given collection. This constructor meant for inter conversion between collection object.

LinkedHashSet:

It is a child class of HashSet. it is exactly same as HashSet including(Constructors and Methods) except the following differences.

Differences HashSet:

  1. The underlined data structure is Hashtable.
  2. Insertion order is not preserved.
  3. introduced 1.2 version.

LinkedHashSet:

  1. The underlined data structure is a combination of LinkedList and Hashtable.
  2. Insertion order is preserved.
  3. Indroduced in 1.4 version.

PHP call Class method / function

As th function is not using $this at all, you can add a static keyword just after public and then call

Functions::filter($_GET['params']);

Avoiding the creation of an object just for one method call

What is jQuery Unobtrusive Validation?

For clarification, here is a more detailed example demonstrating Form Validation using jQuery Validation Unobtrusive.

Both use the following JavaScript with jQuery:

  $("#commentForm").validate({
    submitHandler: function(form) {
      // some other code
      // maybe disabling submit button
      // then:
      alert("This is a valid form!");
//      form.submit();
    }
  });

The main differences between the two plugins are the attributes used for each approach.

jQuery Validation

Simply use the following attributes:

  • Set required if required
  • Set type for proper formatting (email, etc.)
  • Set other attributes such as size (min length, etc.)

Here's the form...

<form id="commentForm">
  <label for="form-name">Name (required, at least 2 characters)</label>
  <input id="form-name" type="text" name="form-name" class="form-control" minlength="2" required>
  <input type="submit" value="Submit">
</form>

jQuery Validation Unobtrusive

The following data attributes are needed:

  • data-msg-required="This is required."
  • data-rule-required="true/false"

Here's the form...

<form id="commentForm">
  <label for="form-x-name">Name (required, at least 2 characters)</label>
  <input id="form-x-name" type="text" name="name" minlength="2" class="form-control" data-msg-required="Name is required." data-rule-required="true">
  <input type="submit" value="Submit">
</form>

Based on either of these examples, if the form fields that are required have been filled, and they meet the additional attribute criteria, then a message will pop up notifying that all form fields are validated. Otherwise, there will be text near the offending form fields that indicates the error.

References: - jQuery Validation: https://jqueryvalidation.org/documentation/

Adjust plot title (main) position

To summarize and explain visually how it works. Code construction is as follows:

par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)

explanation:

par(mar = c(low, left, top, right)) - margins of the graph area.

title("text" - title text
      adj  = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
      line = positive values move title text up, negative - down)

enter image description here

Time calculation in php (add 10 hours)?

strtotime() gives you a number back that represents a time in seconds. To increment it, add the corresponding number of seconds you want to add. 10 hours = 60*60*10 = 36000, so...

$date = date('h:i:s A', strtotime($today)+36000); // $today is today date

Edit: I had assumed you had a string time in $today - if you're just using the current time, even simpler:

$date = date('h:i:s A', time()+36000); // time() returns a time in seconds already

Intel's HAXM equivalent for AMD on Windows OS

Posting a new answer since it is (almost) 2020.

The Android Emulator still only supports HAXM or WHPX on windows. And you may even call it a day already with the latter.

But if you don't like it, there is now work in progress AMD-V support for the former by one of the PS4 emulator developers: https://github.com/jarveson/haxm/tree/svm

How do I disable Git Credential Manager for Windows?

Another option I had to use with VSTS:

git config credential.modalprompt false --global

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

The most condensed version:

public String getNameFromURI(Uri uri) {
    Cursor c = getContentResolver().query(uri, null, null, null, null);
    c.moveToFirst();
    return c.getString(c.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}

Java File - Open A File And Write To It

Please Search Google given to the world by Larry Page and Sergey Brin.

BufferedWriter out = null;

try {
    FileWriter fstream = new FileWriter("out.txt", true); //true tells to append data.
    out = new BufferedWriter(fstream);
    out.write("\nsue");
}

catch (IOException e) {
    System.err.println("Error: " + e.getMessage());
}

finally {
    if(out != null) {
        out.close();
    }
}

Allow multi-line in EditText view in Android?

<EditText
                android:hint="Address"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_weight="1"
                android:inputType="textMultiLine|textNoSuggestions"
                android:id="@+id/edittxtAddress"
                android:layout_marginLeft="@dimen/textsize2"
                android:textColor="@android:color/white"
                android:scrollbars="vertical"
                android:minLines="2"
            android:textStyle="normal" />

and in Activity to remove "\n" is user press nextline

String editStr= edittxtAddress.getText().toString().trim();

 MyString= editStr.replaceAll("\n"," ");

Unix command-line JSON parser?

You can use this command-line parser (which you could put into a bash alias if you like), using modules built into the Perl core:

perl -MData::Dumper -MJSON::PP=from_json -ne'print Dumper(from_json($_))'

jQuery Mobile: document ready vs. page events

jQuery Mobile 1.4 Update:

My original article was intended for old way of page handling, basically everything before jQuery Mobile 1.4. Old way of handling is now deprecated and it will stay active until (including) jQuery Mobile 1.5, so you can still use everything mentioned below, at least until next year and jQuery Mobile 1.6.

Old events, including pageinit don't exist any more, they are replaced with pagecontainer widget. Pageinit is erased completely and you can use pagecreate instead, that event stayed the same and its not going to be changed.

If you are interested in new way of page event handling take a look here, in any other case feel free to continue with this article. You should read this answer even if you are using jQuery Mobile 1.4 +, it goes beyond page events so you will probably find a lot of useful information.

Older content:

This article can also be found as a part of my blog HERE.

$(document).on('pageinit') vs $(document).ready()

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate. Because of this $(document).ready() will trigger before your first page is loaded and every code intended for page manipulation will be executed after a page refresh. This can be a very subtle bug. On some systems it may appear that it works fine, but on others it may cause erratic, difficult to repeat weirdness to occur.

Classic jQuery syntax:

$(document).ready(function() {

});

To solve this problem (and trust me this is a problem) jQuery Mobile developers created page events. In a nutshell page events are events triggered in a particular point of page execution. One of those page events is a pageinit event and we can use it like this:

$(document).on('pageinit', function() {

});

We can go even further and use a page id instead of document selector. Let's say we have jQuery Mobile page with an id index:

<div data-role="page" id="index">
    <div data-theme="a" data-role="header">
        <h3>
            First Page
        </h3>
        <a href="#second" class="ui-btn-right">Next</a>
    </div>

    <div data-role="content">
        <a href="#" data-role="button" id="test-button">Test button</a>
    </div>

    <div data-theme="a" data-role="footer" data-position="fixed">

    </div>
</div>

To execute code that will only available to the index page we could use this syntax:

$('#index').on('pageinit', function() {

});

Pageinit event will be executed every time page is about be be loaded and shown for the first time. It will not trigger again unless page is manually refreshed or Ajax page loading is turned off. In case you want code to execute every time you visit a page it is better to use pagebeforeshow event.

Here's a working example: http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem.

Few more notes on this question. No matter if you are using 1 html multiple pages or multiple HTML files paradigm it is advised to separate all of your custom JavaScript page handling into a single separate JavaScript file. This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobile application.

There's also another special jQuery Mobile event and it is called mobileinit. When jQuery Mobile starts, it triggers a mobileinit event on the document object. To override default settings, bind them to mobileinit. One of a good examples of mobileinit usage is turning off Ajax page loading, or changing default Ajax loader behavior.

$(document).on("mobileinit", function(){
  //apply overrides here
});

Page events transition order

First all events can be found here: http://api.jquerymobile.com/category/events/

Lets say we have a page A and a page B, this is a unload/load order:

  1. page B - event pagebeforecreate

  2. page B - event pagecreate

  3. page B - event pageinit

  4. page A - event pagebeforehide

  5. page A - event pageremove

  6. page A - event pagehide

  7. page B - event pagebeforeshow

  8. page B - event pageshow

For better page events understanding read this:

  • pagebeforeload, pageload and pageloadfailed are fired when an external page is loaded
  • pagebeforechange, pagechange and pagechangefailed are page change events. These events are fired when a user is navigating between pages in the applications.
  • pagebeforeshow, pagebeforehide, pageshow and pagehide are page transition events. These events are fired before, during and after a transition and are named.
  • pagebeforecreate, pagecreate and pageinit are for page initialization.
  • pageremove can be fired and then handled when a page is removed from the DOM

Page loading jsFiddle example: http://jsfiddle.net/Gajotres/QGnft/

If AJAX is not enabled, some events may not fire.

Prevent page transition

If for some reason page transition needs to be prevented on some condition it can be done with this code:

$(document).on('pagebeforechange', function(e, data){
    var to = data.toPage,
        from = data.options.fromPage;

    if (typeof to  === 'string') {
        var u = $.mobile.path.parseUrl(to);
        to = u.hash || '#' + u.pathname.substring(1);
        if (from) from = '#' + from.attr('id');

        if (from === '#index' && to === '#second') {
            alert('Can not transition from #index to #second!');
            e.preventDefault();
            e.stopPropagation();

            // remove active status on a button, if transition was triggered with a button
            $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus ui-btn');;
        }
    }
});

This example will work in any case because it will trigger at a begging of every page transition and what is most important it will prevent page change before page transition can occur.

Here's a working example:

Prevent multiple event binding/triggering

jQuery Mobile works in a different way than classic web applications. Depending on how you managed to bind your events each time you visit some page it will bind events over and over. This is not an error, it is simply how jQuery Mobile handles its pages. For example, take a look at this code snippet:

$(document).on('pagebeforeshow','#index' ,function(e,data){
    $(document).on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/CCfL4/

Each time you visit page #index click event will is going to be bound to button #test-button. Test it by moving from page 1 to page 2 and back several times. There are few ways to prevent this problem:

Solution 1

Best solution would be to use pageinit to bind events. If you take a look at an official documentation you will find out that pageinit will trigger ONLY once, just like document ready, so there's no way events will be bound again. This is best solution because you don't have processing overhead like when removing events with off method.

Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/

This working solution is made on a basis of a previous problematic example.

Solution 2

Remove event before you bind it:

$(document).on('pagebeforeshow', '#index', function(){
    $(document).off('click', '#test-button').on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/

Solution 3

Use a jQuery Filter selector, like this:

$('#carousel div:Event(!click)').each(function(){
    //If click is not bind to #carousel div do something
});

Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/

In a nutshell, if speed is your main concern then Solution 2 is much better than Solution 1.

Solution 4

A new one, probably an easiest of them all.

$(document).on('pagebeforeshow', '#index', function(){
    $(document).on('click', '#test-button',function(e) {
        if(e.handled !== true) // This will prevent event triggering more than once
        {
            alert('Clicked');
            e.handled = true;
        }
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/

Tnx to the sholsinger for this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/

pageChange event quirks - triggering twice

Sometimes pagechange event can trigger twice and it does not have anything to do with the problem mentioned before.

The reason the pagebeforechange event occurs twice is due to the recursive call in changePage when toPage is not a jQuery enhanced DOM object. This recursion is dangerous, as the developer is allowed to change the toPage within the event. If the developer consistently sets toPage to a string, within the pagebeforechange event handler, regardless of whether or not it was an object an infinite recursive loop will result. The pageload event passes the new page as the page property of the data object (This should be added to the documentation, it's not listed currently). The pageload event could therefore be used to access the loaded page.

In few words this is happening because you are sending additional parameters through pageChange.

Example:

<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="#care-plan-view?id=9e273f31-2672-47fd-9baa-6c35f093a800&amp;name=Sat"><h3>Sat</h3></a>

To fix this problem use any page event listed in Page events transition order.

Page Change Times

As mentioned, when you change from one jQuery Mobile page to another, typically either through clicking on a link to another jQuery Mobile page that already exists in the DOM, or by manually calling $.mobile.changePage, several events and subsequent actions occur. At a high level the following actions occur:

  • A page change process is begun
  • A new page is loaded
  • The content for that page is “enhanced” (styled)
  • A transition (slide/pop/etc) from the existing page to the new page occurs

This is a average page transition benchmark:

Page load and processing: 3 ms

Page enhance: 45 ms

Transition: 604 ms

Total time: 670 ms

*These values are in milliseconds.

So as you can see a transition event is eating almost 90% of execution time.

Data/Parameters manipulation between page transitions

It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.

Reference: https://stackoverflow.com/a/13932240/1848600

Solution 1:

You can pass values with changePage:

$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });

And read them like this:

$(document).on('pagebeforeshow', "#index", function (event, data) {
    var parameters = $(this).data("url").split("?")[1];;
    parameter = parameters.replace("parameter=","");
    alert(parameter);
});

Example:

index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
    <script>_x000D_
        $(document).on('pagebeforeshow', "#index",function () {_x000D_
            $(document).on('click', "#changePage",function () {_x000D_
                $.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });_x000D_
            });_x000D_
        });_x000D_
_x000D_
        $(document).on('pagebeforeshow', "#second",function () {_x000D_
            var parameters = $(this).data("url").split("?")[1];;_x000D_
            parameter = parameters.replace("parameter=","");_x000D_
            alert(parameter);_x000D_
        });_x000D_
    </script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="index">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                First Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
          <a data-role="button" id="changePage">Test</a>_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

second.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="second">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                Second Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Solution 2:

Or you can create a persistent JavaScript object for a storage purpose. As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

var storeObject = {
    firstname : '',
    lastname : ''
}

Example: http://jsfiddle.net/Gajotres/9KKbx/

Solution 3:

You can also access data from the previous page like this:

$(document).on('pagebeforeshow', '#index',function (e, data) {
    alert(data.prevPage.attr('id'));
});

prevPage object holds a complete previous page.

Solution 4:

As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.

if(typeof(Storage)!=="undefined") {
    localStorage.firstname="Dragan";
    localStorage.lastname="Gaic";
}

Example: http://jsfiddle.net/Gajotres/J9NTr/

Probably best solution but it will fail in some versions of iOS 5.X. It is a well know error.

Don’t Use .live() / .bind() / .delegate()

I forgot to mention (and tnx andleer for reminding me) use on/off for event binding/unbinding, live/die and bind/unbind are deprecated.

The .live() method of jQuery was seen as a godsend when it was introduced to the API in version 1.3. In a typical jQuery app there can be a lot of DOM manipulation and it can become very tedious to hook and unhook as elements come and go. The .live() method made it possible to hook an event for the life of the app based on its selector. Great right? Wrong, the .live() method is extremely slow. The .live() method actually hooks its events to the document object, which means that the event must bubble up from the element that generated the event until it reaches the document. This can be amazingly time consuming.

It is now deprecated. The folks on the jQuery team no longer recommend its use and neither do I. Even though it can be tedious to hook and unhook events, your code will be much faster without the .live() method than with it.

Instead of .live() you should use .on(). .on() is about 2-3x faster than .live(). Take a look at this event binding benchmark: http://jsperf.com/jquery-live-vs-delegate-vs-on/34, everything will be clear from there.

Benchmarking:

There's an excellent script made for jQuery Mobile page events benchmarking. It can be found here: https://github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js. But before you do anything with it I advise you to remove its alert notification system (each “change page” is going to show you this data by halting the app) and change it to console.log function.

Basically this script will log all your page events and if you read this article carefully (page events descriptions) you will know how much time jQm spent of page enhancements, page transitions ....

Final notes

Always, and I mean always read official jQuery Mobile documentation. It will usually provide you with needed information, and unlike some other documentation this one is rather good, with enough explanations and code examples.

Changes:

  • 30.01.2013 - Added a new method of multiple event triggering prevention
  • 31.01.2013 - Added a better clarification for chapter Data/Parameters manipulation between page transitions
  • 03.02.2013 - Added new content/examples to the chapter Data/Parameters manipulation between page transitions
  • 22.05.2013 - Added a solution for page transition/change prevention and added links to the official page events API documentation
  • 18.05.2013 - Added another solution against multiple event binding

How do I copy a range of formula values and paste them to a specific range in another sheet?

How about if you're copying each column in a sheet to different sheets? Example: row B of mysheet to row B of sheet1, row C of mysheet to row B of sheet 2...

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

How do I push amended commit to the remote Git repository?

Short answer: Don't push amended commits to a public repo.

Long answer: A few Git commands, like git commit --amend and git rebase, actually rewrite the history graph. This is fine as long as you haven't published your changes, but once you do, you really shouldn't be mucking around with the history, because if someone already got your changes, then when they try to pull again, it might fail. Instead of amending a commit, you should just make a new commit with the changes.

However, if you really, really want to push an amended commit, you can do so like this:

$ git push origin +master:master

The leading + sign will force the push to occur, even if it doesn't result in a "fast-forward" commit. (A fast-forward commit occurs when the changes you are pushing are a direct descendant of the changes already in the public repo.)

Best IDE for HTML5, Javascript, CSS, Jquery support with GUI building tools

As per my personal experience Adobe edge is the best tool for HTML5. It's still in preview mode but you will download it free from Adobe site.

What is uintptr_t data type

There are already many good answers to the part "what is uintptr_t data type". I will try to address the "what it can be used for?" part in this post.

Primarily for bitwise operations on pointers. Remember that in C++ one cannot perform bitwise operations on pointers. For reasons see Why can't you do bitwise operations on pointer in C, and is there a way around this?

Thus in order to do bitwise operations on pointers one would need to cast pointers to type unitpr_t and then perform bitwise operations.

Here is an example of a function that I just wrote to do bitwise exclusive or of 2 pointers to store in a XOR linked list so that we can traverse in both directions like a doubly linked list but without the penalty of storing 2 pointers in each node.

 template <typename T>
 T* xor_ptrs(T* t1, T* t2)
 {
     return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(t1)^reinterpret_cast<uintptr_t>(t2));
  }

How do you access the value of an SQL count () query in a Java program

        <%
        try{
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
            Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/bala","bala","bala");
            if(con == null) System.out.print("not connected");
            Statement st = con.createStatement();
            String myStatement = "select count(*) as total from locations";
            ResultSet rs = st.executeQuery(myStatement);
            int num = 0;
            while(rs.next()){
                num = (rs.getInt(1));
            }

        }
        catch(Exception e){
            System.out.println(e);  
        }

        %>

How do I auto-submit an upload form when a file is selected?

The shortest solution is

<input type="file" name="file" onchange="javascript:document.getElementById('form').submit();" />

How do I manually create a file with a . (dot) prefix in Windows? For example, .htaccess

Use something like Notepad++ (or even Notepad), 'Save As', and enter the name .htaccess that way. I always found it weird, but it lets you do it from a program!

Setting up a websocket on Apache?

I can't answer all questions, but I will do my best.

As you already know, WS is only a persistent full-duplex TCP connection with framed messages where the initial handshaking is HTTP-like. You need some server that's listening for incoming WS requests and that binds a handler to them.

Now it might be possible with Apache HTTP Server, and I've seen some examples, but there's no official support and it gets complicated. What would Apache do? Where would be your handler? There's a module that forwards incoming WS requests to an external shared library, but this is not necessary with the other great tools to work with WS.

WS server trends now include: Autobahn (Python) and Socket.IO (Node.js = JavaScript on the server). The latter also supports other hackish "persistent" connections like long polling and all the COMET stuff. There are other little known WS server frameworks like Ratchet (PHP, if you're only familiar with that).

In any case, you will need to listen on a port, and of course that port cannot be the same as the Apache HTTP Server already running on your machine (default = 80). You could use something like 8080, but even if this particular one is a popular choice, some firewalls might still block it since it's not supposed to be Web traffic. This is why many people choose 443, which is the HTTP Secure port that, for obvious reasons, firewalls do not block. If you're not using SSL, you can use 80 for HTTP and 443 for WS. The WS server doesn't need to be secure; we're just using the port.

Edit: According to Iharob Al Asimi, the previous paragraph is wrong. I have no time to investigate this, so please see his work for more details.

About the protocol, as Wikipedia shows, it looks like this:

Client sends:

GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com

Server replies:

HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat

and keeps the connection alive. If you can implement this handshaking and the basic message framing (encapsulating each message with a small header describing it), then you can use any client-side language you want. JavaScript is only used in Web browsers because it's built-in.

As you can see, the default "request method" is an initial HTTP GET, although this is not really HTTP and looses everything in common with HTTP after this handshaking. I guess servers that do not support

Upgrade: websocket
Connection: Upgrade

will reply with an error or with a page content.

Good NumericUpDown equivalent in WPF?

The Extended WPF Toolkit has one: NumericUpDown enter image description here

How to make padding:auto work in CSS?

auto is not a valid value for padding property, the only thing you can do is take out padding: 0; from the * declaration, else simply assign padding to respective property block.

If you remove padding: 0; from * {} than browser will apply default styles to your elements which will give you unexpected cross browser positioning offsets by few pixels, so it is better to assign padding: 0; using * and than if you want to override the padding, simply use another rule like

.container p {
   padding: 5px;
}

Import error No module named skimage

For OSX: pip install scikit-image

and then run python to try following

from skimage.feature import corner_harris, corner_peaks

How to find which views are using a certain table in SQL Server (2008)?

This should do it:

SELECT * 
FROM   INFORMATION_SCHEMA.VIEWS 
WHERE  VIEW_DEFINITION like '%YourTableName%'

Error retrieving parent for item: No resource found that matches the given name 'android:TextAppearance.Material.Widget.Button.Borderless.Colored'

in my case i was using compile sdk 23 and build tools 25.0.0 just changed compile sdk to 25 and done..

Remove all whitespaces from NSString

This may help you if you are experiencing \u00a0 in stead of (whitespace). I had this problem when I was trying to extract Device Contact Phone Numbers. I needed to modify the phoneNumber string so it has no whitespace in it.

NSString* yourString = [yourString stringByReplacingOccurrencesOfString:@"\u00a0" withString:@""];

When yourString was the current phone number.

How can I make my flexbox layout take 100% vertical space?

set the wrapper to height 100%

.vwrapper {
  display: flex;
  flex-direction: column;

  flex-wrap: nowrap;
  justify-content: flex-start;
  align-items: stretch;
  align-content: stretch;

  height: 100%;
}

and set the 3rd row to flex-grow

#row3 {
   background-color: green;
   flex: 1 1 auto;
   display: flex;
}

demo

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

Alternatively you can install GNU date like so:

  1. install Homebrew: https://brew.sh/
  2. brew install coreutils
  3. add to your bash_profile: alias date="/usr/local/bin/gdate"
  4. date +%s 1547838127

Comments saying Mac has to be "different" simply reveal the commenter is ignorant of the history of UNIX. macOS is based on BSD UNIX, which is way older than Linux. Linux essentially was a copy of other UNIX systems, and Linux decided to be "different" by adopting GNU tools instead of BSD tools. GNU tools are more user friendly, but they're not usually found on any *BSD system (just the way it is).

Really, if you spend most of your time in Linux, but have a Mac desktop, you probably want to make the Mac work like Linux. There's no sense in trying to remember two different sets of options, or scripting for the mac's BSD version of Bash, unless you are writing a utility that you want to run on both BSD and GNU/Linux shells.

MySQL does not start when upgrading OSX to Yosemite or El Capitan

I usually start mysql server by typing

$ mysql.server start

without sudo. But in error I type sudo before the command. Now I have to remove the error file to start the server.

$ sudo rm /usr/local/var/mysql/`hostname`.err

Jackson JSON custom serialization for certain fields

You can create a custom serializer inline in the mixin. Then annotate a field with it. See example below that appends " - something else " to lang field. This is kind of hackish - if your serializer requires something like a repository or anything injected by spring, this is going to be a problem. Probably best to use a custom deserializer/serializer instead of a mixin.

package com.test;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonAutoDetect.Visibility;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.test.Argument;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//Serialize only fields explicitly mentioned by this mixin.
@JsonAutoDetect(
    fieldVisibility = Visibility.NONE,
    setterVisibility = Visibility.NONE,
    getterVisibility = Visibility.NONE,
    isGetterVisibility = Visibility.NONE,
    creatorVisibility = Visibility.NONE
)
@JsonPropertyOrder({"lang", "name", "value"})
public abstract class V2ArgumentMixin {

  @JsonProperty("name")
  private String name;

  @JsonSerialize(using = LangCustomSerializer.class, as=String.class)
  @JsonProperty("lang")
  private String lang;

  @JsonProperty("value")
  private Object value;


  
  public static class LangCustomSerializer extends JsonSerializer<String> {

    @Override
    public void serialize(String value,
                          JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider)
        throws IOException, JsonProcessingException {
      jsonGenerator.writeObject(value.toString() + "  - something else");
    }
  }
}

Invalid date in safari

I was facing a similar issue. Date.Parse("DATESTRING") was working on Chrome (Version 59.0.3071.115 ) but not of Safari (Version 10.1.1 (11603.2.5) )

Safari:

Date.parse("2017-01-22 11:57:00")
NaN

Chrome:

Date.parse("2017-01-22 11:57:00")
1485115020000

The solution that worked for me was replacing the space in the dateString with "T". ( example : dateString.replace(/ /g,"T") )

Safari:

Date.parse("2017-01-22T11:57:00")
1485086220000

Chrome:

Date.parse("2017-01-22T11:57:00")
1485115020000

Note that the response from Safari browser is 8hrs (28800000ms) less than the response seen in Chrome browser because Safari returned the response in local TZ (which is 8hrs behind UTC)

To get both the times in same TZ

Safari:

Date.parse("2017-01-22T11:57:00Z")
1485086220000

Chrome:

Date.parse("2017-01-22T11:57:00Z")
1485086220000

Fixing the order of facets in ggplot

Here's a solution that keeps things within a dplyr pipe chain. You sort the data in advance, and then using mutate_at to convert to a factor. I've modified the data slightly to show how this solution can be applied generally, given data that can be sensibly sorted:

# the data
temp <- data.frame(type=rep(c("T", "F", "P"), 4),
                    size=rep(c("50%", "100%", "200%", "150%"), each=3), # cannot sort this
                    size_num = rep(c(.5, 1, 2, 1.5), each=3), # can sort this
                    amount=c(48.4, 48.1, 46.8, 
                             25.9, 26.0, 24.9,
                             20.8, 21.5, 16.5,
                             21.1, 21.4, 20.1))

temp %>% 
  arrange(size_num) %>% # sort
  mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>% # convert to factor

  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)

You can apply this solution to arrange the bars within facets, too, though you can only choose a single, preferred order:

    temp %>% 
  arrange(size_num) %>%
  mutate_at(vars(size), funs(factor(., levels=unique(.)))) %>%
  arrange(desc(amount)) %>%
  mutate_at(vars(type), funs(factor(., levels=unique(.)))) %>%
  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)


  ggplot() + 
  geom_bar(aes(x = type, y=amount, fill=type), 
           position="dodge", stat="identity") + 
  facet_grid(~ size)