Programs & Examples On #Pushdown automaton

A pushdown automaton (PDA) is a finite-state automaton with added stack based memory. It is a mathematical description of an algorithm for parsing context-free languages.

How to Add Incremental Numbers to a New Column Using Pandas

For a pandas DataFrame whose index starts at 0 and increments by 1 (i.e., the default values) you can just do:

df.insert(0, 'New_ID', df.index + 880)

if you want New_ID to be the first column. Otherwise this if you don't mind it being at the end:

df['New_ID'] = df.index + 880

How to programmatically click a button in WPF?

if you want to call click event:

SomeButton.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));

And if you want the button looks like it is pressed:

typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(SomeButton, new object[] { true });

and unpressed after that:

typeof(Button).GetMethod("set_IsPressed", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(SomeButton, new object[] { false });

or use the ToggleButton

Does java.util.List.isEmpty() check if the list itself is null?

I would recommend using Apache Commons Collections

http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/CollectionUtils.html#isEmpty(java.util.Collection)

which implements it quite ok and well documented:

/**
 * Null-safe check if the specified collection is empty.
 * <p>
 * Null returns true.
 * 
 * @param coll  the collection to check, may be null
 * @return true if empty or null
 * @since Commons Collections 3.2
 */
public static boolean isEmpty(Collection coll) {
    return (coll == null || coll.isEmpty());
}

How can you program if you're blind?

This blog post has some information about how the Visual Studio team is making their product accessible:

Visual Studio Core Team's Accessibility Lab Tour Activity

Many programmers use Emacspeak:

Emacspeak --The Complete Audio Desktop

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

Neither of the suggestions here were helpful for me. So I had to debug primefaces and found the reason of the problem was:

java.lang.IllegalStateException: No multipart config for servlet fileUpload

Then I have added section into my faces servlet in the web.xml. So that has fixed the problem:

<servlet>
    <servlet-name>main</servlet-name>

        <servlet-class>org.apache.myfaces.webapp.MyFacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
        <multipart-config>
            <location>/tmp</location>
            <max-file-size>20848820</max-file-size>
            <max-request-size>418018841</max-request-size>
            <file-size-threshold>1048576</file-size-threshold>
        </multipart-config>
    </servlet>

Unexpected character encountered while parsing value

Possibly you are not passing JSON to DeserializeObject.

It looks like from File.WriteAllText(tmpfile,... that type of tmpfile is string that contain path to a file. JsonConvert.DeserializeObject takes JSON value, not file path - so it fails trying to convert something like @"c:\temp\fooo" - which is clearly not JSON.

Android. WebView and loadData

WebView.loadData() is not working properly at all. What I had to do was:

String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
myWebView.loadData(header+myHtmlString, "text/html", "UTF-8");

I think in your case you should replace UTF-8 with latin1 or ISO-8859-1 both in header and in WebView.loadData().

And, to give a full answer, here is the official list of encodings: http://www.iana.org/assignments/character-sets

I update my answer to be more inclusive:

To use WebView.loadData() with non latin1 encodings you have to encode html content. Previous example was not correctly working in Android 4+, so I have modified it to look as follows:

WebSettings settings = myWebView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) {
    String base64 = Base64.encodeToString(htmlString.getBytes(), Base64.DEFAULT);
    myWebView.loadData(base64, "text/html; charset=utf-8", "base64");
} else {
    String header = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>";
    myWebView.loadData(header + htmlString, "text/html; charset=UTF-8", null);

}

But later I have switched to WebView.loadDataWithBaseURL() and the code became very clean and not depending on Android version:

WebSettings settings = myWebView.getSettings();
settings.setDefaultTextEncodingName("utf-8");
myWebView.loadDataWithBaseURL(null, htmlString, "text/html", "utf-8", null);

For some reason these functions have completely different implementation.

Error 1053 the service did not respond to the start or control request in a timely fashion

I'm shooting blind here, but I've very often found that long delays in service startups are directly or indirectly caused by network function timeouts, often when attemting to contact a domain controller when looking up account SIDs - which happens very often indirectly via GetMachineAccountSid() whether you realize it or not, since that function is called by the RPC subsystem.

For an example on how to debug in such situations, see The Case of the Process Startup Delays on Mark Russinovich's blog.

How to call a method after bean initialization is complete?

There are three different approaches to consider, as described in the reference

Use init-method attribute

Pros:

  • Does not require bean to implement an interface.

Cons:

  • No immediate indication this method is required after construction to ensure the bean is correctly configured.

Implement InitializingBean

Pros:

  • No need to specify init-method, or turn on component scanning / annotation processing.
  • Appropriate for beans supplied with a library, where we don't want the application using this library to concern itself with bean lifecycle.

Cons:

  • More invasive than the init-method approach.

Use JSR-250 @PostConstruct lifecyle annotation

Pros:

  • Useful when using component scanning to autodetect beans.
  • Makes it clear that a specific method is to be used for initialisation. Intent is closer to the code.

Cons:

  • Initialisation no longer centrally specified in configuration.
  • You must remember to turn on annotation processing (which can sometimes be forgotten)

How to get position of a certain element in strings vector, to use it as an index in ints vector?

To get a position of an element in a vector knowing an iterator pointing to the element, simply subtract v.begin() from the iterator:

ptrdiff_t pos = find(Names.begin(), Names.end(), old_name_) - Names.begin();

Now you need to check pos against Names.size() to see if it is out of bounds or not:

if(pos >= Names.size()) {
    //old_name_ not found
}

vector iterators behave in ways similar to array pointers; most of what you know about pointer arithmetic can be applied to vector iterators as well.

Starting with C++11 you can use std::distance in place of subtraction for both iterators and pointers:

ptrdiff_t pos = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_));

C - freeing structs

You can't free types that aren't dynamically allocated. Although arrays are syntactically similar (int* x = malloc(sizeof(int) * 4) can be used in the same way that int x[4] is), calling free(firstName) would likely cause an error for the latter.

For example, take this code:

int x;
free(&x);

free() is a function which takes in a pointer. &x is a pointer. This code may compile, even though it simply won't work.

If we pretend that all memory is allocated in the same way, x is "allocated" at the definition, "freed" at the second line, and then "freed" again after the end of the scope. You can't free the same resource twice; it'll give you an error.

This isn't even mentioning the fact that for certain reasons, you may be unable to free the memory at x without closing the program.

tl;dr: Just free the struct and you'll be fine. Don't call free on arrays; only call it on dynamically allocated memory.

How to disable a ts rule for a specific line?

@ts-expect-error

TS 3.9 introduces a new magic comment. @ts-expect-error will:

  • have same functionality as @ts-ignore
  • trigger an error, if actually no compiler error has been suppressed (= indicates useless flag)
if (false) {
  // @ts-expect-error: Let's ignore a single compiler error like this unreachable code 
  console.log("hello"); // compiles
}

// If @ts-expect-error didn't suppress anything at all, we now get a nice warning 
let flag = true;
// ...
if (flag) {
  // @ts-expect-error
  // ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
  console.log("hello"); 
}

Alternatives

@ts-ignore and @ts-expect-error can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:

? Use any type

// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;

// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;

? Augment JQueryStatic interface

// ./global.d.ts
interface JQueryStatic {
  summernote: any;
}

// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works

In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js and use --allowJs with checkJs: false.

Adding git branch on the Bash command prompt

I have tried a small script in python that goes in a bin folder.... 'gitprompt' file

#!/usr/bin/env python
import subprocess, os
s = os.path.join(os.getcwd(), '.git')
def cut(cmd):
    ret=''
    half=0
    record = False
    for c in cmd:
        if c == "\n":
            if not (record):
                pass
            else:
                break
        if (record) and c!="\n":
            ret = ret + c
        if c=='*':
            half=0.5
        if c==' ':
            if half == 0.5:
                half = 1
        if half == 1:
            record = True
    return ret
if (os.path.isdir(s)):
    out = subprocess.check_output("git branch",shell=True)
    print cut(out)
else:
    print "-"

Make it executable and stuff

Then adjust the bash prompt accordingly like :

\u:\w--[$(gitprompt)] \$ 

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

I my case, I solved this issue going to the Publish tab in the project properties and then select the Application Files button. Then just:

Note: Before you apply this solution, make sure that you have already (as I did), checked all your solution's projects and found no references to stdole.dll assembly.

1 - Located stdole.dll file;

2 - Changed its Publish status to Exclude

3 - After that you need to republish your application.

This issue happened on a Visual Studio 2012, after its migration from Visual Studio 2010.

Hope it helps.

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

What is tail call optimization?

Note first of all that not all languages support it.

TCO applys to a special case of recursion. The gist of it is, if the last thing you do in a function is call itself (e.g. it is calling itself from the "tail" position), this can be optimized by the compiler to act like iteration instead of standard recursion.

You see, normally during recursion, the runtime needs to keep track of all the recursive calls, so that when one returns it can resume at the previous call and so on. (Try manually writing out the result of a recursive call to get a visual idea of how this works.) Keeping track of all the calls takes up space, which gets significant when the function calls itself a lot. But with TCO, it can just say "go back to the beginning, only this time change the parameter values to these new ones." It can do that because nothing after the recursive call refers to those values.

Is Tomcat running?

If tomcat is installed locally, type the following url in a browser window: { localhost:8080 }

This will display Tomcat home page with the following message.

If you're seeing this, you've successfully installed Tomcat. Congratulations!

If tomcat is installed on a separate server, you can type replace localhost by a valid hostname or Iess where tomcat is installed.

The above applies for a standard installation wherein tomcat uses the default port 8080

Bootstrap: how do I change the width of the container?

Set your own content container class with 1000px width property and then use container-fluid boostrap class instead of container.

Works but might not be the best solution.

Understanding the map function

map isn't particularly pythonic. I would recommend using list comprehensions instead:

map(f, iterable)

is basically equivalent to:

[f(x) for x in iterable]

map on its own can't do a Cartesian product, because the length of its output list is always the same as its input list. You can trivially do a Cartesian product with a list comprehension though:

[(a, b) for a in iterable_a for b in iterable_b]

The syntax is a little confusing -- that's basically equivalent to:

result = []
for a in iterable_a:
    for b in iterable_b:
        result.append((a, b))

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

-Using application initalization feature -requesting wrong pages (.asp) because of config inheritance

500.21 will occur on the first user connection only. Subsequent connections work.

Resolved by correcting the applicationInitialization url collection on the .NET website.

Starting Docker as Daemon on Ubuntu

I had the same problem, and it was caused by line for insecured registry in: /etc/default/docker

How to use sed to remove all double quotes within a file

Are you sure you need to use sed? How about:

tr -d "\""

Calling a javascript function in another js file

Use cache if your server allows it to improve speed.

var extern =(url)=> {           // load extern javascript
    let scr = $.extend({}, {
        dataType: 'script',
        cache: true,
        url: url
    });
    return $.ajax(scr);
}
function ext(file, func) {
    extern(file).done(func);    // calls a function from an extern javascript file
}

And then use it like this:

ext('somefile.js',()=>              
    myFunc(args)
);  

Optionally, make a prototype of it to have it more flexible. So that you don't have to define the file every time, if you call a function or if you want to fetch code from multiple files.

How to change a package name in Eclipse?

I have tried this and quite Simple process:

Created a new Package with required name--> Moved all my classes to this new package (Right click on previous package --> Refractor--> Move)

limit text length in php and provide 'Read more' link

$num_words = 101;
$words = array();
$words = explode(" ", $original_string, $num_words);
$shown_string = "";

if(count($words) == 101){
   $words[100] = " ... ";
}

$shown_string = implode(" ", $words);

Formatting struct timespec

The following will return an ISO8601 and RFC3339-compliant UTC timestamp, including nanoseconds.

It uses strftime(), which works with struct timespec just as well as with struct timeval because all it cares about is the number of seconds, which both provide. Nanoseconds are then appended (careful to pad with zeros!) as well as the UTC suffix 'Z'.

Example output: 2021-01-19T04:50:01.435561072Z

#include <stdio.h>
#include <time.h>
#include <sys/time.h>

int utc_system_timestamp(char[]);

int main(void) {
    char buf[31];
    utc_system_timestamp(buf);
    printf("%s\n", buf);
}

// Allocate exactly 31 bytes for buf
int utc_system_timestamp(char buf[]) {
        const int bufsize = 31;
        struct timespec now;
        struct tm tm;
        int retval = clock_gettime(CLOCK_REALTIME, &now);
        gmtime_r(&now.tv_sec, &tm);
        strftime(buf, bufsize, "%Y-%m-%dT%H:%M:%S.", &tm);
        sprintf(buf, "%s%09luZ", buf, now.tv_nsec);
        return retval;
}

Switch to selected tab by name in Jquery-UI Tabs

The following piece worked for me

$($("#tabs")[0]).tabs({selected: 1});

Hope, this helps!

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

Does HTTP use UDP?

From RFC 2616:

HTTP communication usually takes place over TCP/IP connections. The default port is TCP 80, but other ports can be used. This does not preclude HTTP from being implemented on top of any other protocol on the Internet, or on other networks. HTTP only presumes a reliable transport; any protocol that provides such guarantees can be used; the mapping of the HTTP/1.1 request and response structures onto the transport data units of the protocol in question is outside the scope of this specification.

So although it doesn't explicitly say so, UDP is not used because it is not a "reliable transport".

EDIT - more recently, the QUIC protocol (which is more strictly a pseudo-transport or a session layer protocol) does use UDP for carrying HTTP/2.0 traffic and much of Google's traffic already uses this protocol. It's currently progressing towards standardisation as HTTP/3.

jQuery UI DatePicker - Change Date Format

I am using jquery for datepicker.These jqueries are used for that

<script src="jqueryCalendar/jquery-1.6.2.min.js"></script>
<script src="jqueryCalendar/jquery-ui-1.8.15.custom.min.js"></script>
<link rel="stylesheet" href="jqueryCalendar/jqueryCalendar.css">

Then you follow this code,

<script>
     jQuery(function() {
     jQuery( "#date" ).datepicker({ dateFormat: 'dd/mm/yy' });
                });
</script>

SQL Server - Create a copy of a database table and place it in the same database?

This is another option:

select top 0 * into <new_table> from <original_table>

How do you find the row count for all your tables in Postgres

I don't remember the URL from where I collected this. But hope this should help you:

CREATE TYPE table_count AS (table_name TEXT, num_rows INTEGER); 

CREATE OR REPLACE FUNCTION count_em_all () RETURNS SETOF table_count  AS '
DECLARE 
    the_count RECORD; 
    t_name RECORD; 
    r table_count%ROWTYPE; 

BEGIN
    FOR t_name IN 
        SELECT 
            c.relname
        FROM
            pg_catalog.pg_class c LEFT JOIN pg_namespace n ON n.oid = c.relnamespace
        WHERE 
            c.relkind = ''r''
            AND n.nspname = ''public'' 
        ORDER BY 1 
        LOOP
            FOR the_count IN EXECUTE ''SELECT COUNT(*) AS "count" FROM '' || t_name.relname 
            LOOP 
            END LOOP; 

            r.table_name := t_name.relname; 
            r.num_rows := the_count.count; 
            RETURN NEXT r; 
        END LOOP; 
        RETURN; 
END;
' LANGUAGE plpgsql; 

Executing select count_em_all(); should get you row count of all your tables.

What is a semaphore?

A hardware or software flag. In multi tasking systems , a semaphore is as variable with a value that indicates the status of a common resource.A process needing the resource checks the semaphore to determine the resources status and then decides how to proceed.

Possible reasons for timeout when trying to access EC2 instance

Check out this help page on AWS docs:

http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html#TroubleshootingInstancesConnectionTimeout You will probably find your solution there. for me this part did the fix:

[EC2-VPC] Check the route table for the subnet. You need a route that sends all traffic destined outside the VPC to the Internet gateway for the VPC.

  • Open the Amazon VPC console at https://console.aws.amazon.com/vpc/.

  • In the navigation pane, choose Internet Gateways. Verify that there is an Internet gateway attached to your VPC. Otherwise, choose Create Internet Gateway and follow the directions to create an Internet gateway, select the Internet gateway, and then choose Attach to VPC and follow the directions to attach it to your VPC.

  • In the navigation pane, choose Subnets, and then select your subnet.

  • On the Route Table tab, verify that there is a route with 0.0.0.0/0 as the destination and the Internet gateway for your VPC as the target. Otherwise, choose the ID of the route table (rtb-xxxxxxxx) to navigate to the Routes tab for the route table, choose Edit, Add another route, enter 0.0.0.0/0 in Destination, select your Internet gateway from Target, and then choose Save.

But I suggest you check out all the options the link above covers , you may find there the one or more issues that you got.

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

The code below solved it for me:

@Override
public void onDestroyView() {
    if (getView() != null) {
        ViewGroup parent = (ViewGroup) getView().getParent();
        parent.removeAllViews();
    }
    super.onDestroyView();
}

Note: The error was from my fragment class and by overriding the onDestroy method like this, I could solve it.

Switch statement: must default be the last case?

Chiming in with another example: This can be useful if "default" is an unexpected case, and you want to log the error but also do something sensible. Example from some of my own code:

  switch (style)
  {
  default:
    MSPUB_DEBUG_MSG(("Couldn't match dash style, using solid line.\n"));
  case SOLID:
    return Dash(0, RECT_DOT);
  case DASH_SYS:
  {
    Dash ret(shapeLineWidth, dotStyle);
    ret.m_dots.push_back(Dot(1, 3 * shapeLineWidth));
    return ret;
  }
  // more cases follow
  }

Sound effects in JavaScript / HTML5

_x000D_
_x000D_
var AudioContextFunc = window.AudioContext || window.webkitAudioContext;_x000D_
var audioContext = new AudioContextFunc();_x000D_
var player=new WebAudioFontPlayer();_x000D_
var instrumVox,instrumApplause;_x000D_
var drumClap,drumLowTom,drumHighTom,drumSnare,drumKick,drumCrash;_x000D_
loadDrum(21,function(s){drumClap=s;});_x000D_
loadDrum(30,function(s){drumLowTom=s;});_x000D_
loadDrum(50,function(s){drumHighTom=s;});_x000D_
loadDrum(15,function(s){drumSnare=s;});_x000D_
loadDrum(5,function(s){drumKick=s;});_x000D_
loadDrum(70,function(s){drumCrash=s;});_x000D_
loadInstrument(594,function(s){instrumVox=s;});_x000D_
loadInstrument(1367,function(s){instrumApplause=s;});_x000D_
function loadDrum(n,callback){_x000D_
  var info=player.loader.drumInfo(n);_x000D_
  player.loader.startLoad(audioContext, info.url, info.variable);_x000D_
  player.loader.waitLoad(function () {callback(window[info.variable])});_x000D_
}_x000D_
function loadInstrument(n,callback){_x000D_
  var info=player.loader.instrumentInfo(n);_x000D_
  player.loader.startLoad(audioContext, info.url, info.variable);_x000D_
  player.loader.waitLoad(function () {callback(window[info.variable])});_x000D_
}_x000D_
function uhoh(){_x000D_
  var when=audioContext.currentTime;_x000D_
  var b=0.1;_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, instrumVox, when+b*0, 60, b*1);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, instrumVox, when+b*3, 56, b*4);_x000D_
}_x000D_
function applause(){_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, instrumApplause, audioContext.currentTime, 54, 3);_x000D_
}_x000D_
function badumtss(){_x000D_
  var when=audioContext.currentTime;_x000D_
  var b=0.11;_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumSnare, when+b*0, drumSnare.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumLowTom, when+b*0, drumLowTom.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumSnare, when+b*1, drumSnare.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumHighTom, when+b*1, drumHighTom.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumSnare, when+b*3, drumSnare.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumKick, when+b*3, drumKick.zones[0].keyRangeLow, 3.5);_x000D_
  player.queueWaveTable(audioContext, audioContext.destination, drumCrash, when+b*3, drumCrash.zones[0].keyRangeLow, 3.5);_x000D_
}
_x000D_
<script src='https://surikov.github.io/webaudiofont/npm/dist/WebAudioFontPlayer.js'></script>_x000D_
<button onclick='badumtss();'>badumtss</button>_x000D_
<button onclick='uhoh();'>uhoh</button>_x000D_
<button onclick='applause();'>applause</button>_x000D_
<br/><a href='https://github.com/surikov/webaudiofont'>More sounds</a>
_x000D_
_x000D_
_x000D_

Why I am Getting Error 'Channel is unrecoverably broken and will be disposed!'

It's obvious this creeps up due to many issues. For me, I was posting several OneTimeWorkRequest, each accessing a single room database, and inserting into a single table.

Making the DAO functions suspended, and calling them within the coroutine scope of the worker fixed this for me.

Log to the base 2 in python

>>> def log2( x ):
...     return math.log( x ) / math.log( 2 )
... 
>>> log2( 2 )
1.0
>>> log2( 4 )
2.0
>>> log2( 8 )
3.0
>>> log2( 2.4 )
1.2630344058337937
>>> 

Confused by python file mode "w+"

I suspect there are two ways to handle what I think you'r trying to achieve.

1) which is obvious, is open the file for reading only, read it into memory then open the file with t, then write your changes.

2) use the low level file handling routines:

# Open file in RW , create if it doesn't exist. *Don't* pass O_TRUNC
 fd = os.open(filename, os.O_RDWR | os.O_CREAT)

Hope this helps..

How to increase the distance between table columns in HTML?

Set the width of the <td>s to 50px and then add your <td> + another fake <td>

Fiddle.

_x000D_
_x000D_
table tr td:empty {_x000D_
  width: 50px;_x000D_
}_x000D_
  _x000D_
table tr td {_x000D_
  padding-top: 10px;_x000D_
  padding-bottom: 10px;_x000D_
}
_x000D_
<table>_x000D_
  <tr>_x000D_
    <td>First Column</td>_x000D_
    <td></td>_x000D_
    <td>Second Column</td>_x000D_
    <td></td>_x000D_
    <td>Third Column</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Code Explained:

The first CSS rule checks for empty td's and give them a width of 50px then the second rule give the padding of top and bottom to all the td's.

How to add row of data to Jtable from values received from jtextfield and comboboxes

you can use this code as template please customize it as per your requirement.

DefaultTableModel model = new DefaultTableModel();
List<String> list = new ArrayList<String>();

list.add(textField.getText());
list.add(comboBox.getSelectedItem());

model.addRow(list.toArray());

table.setModel(model);

here DefaultTableModel is used to add rows in JTable, you can get more info here.

Java SE 6 vs. JRE 1.6 vs. JDK 1.6 - What do these mean?

  • JDK - Java Development Kit
  • JRE - Java Runtime Environment
  • Java SE - Java Standard Edition

SE defines a set of capabilities and functionalities; there are more complex editions (Enterprise Edition – EE) and simpler ones (Micro Edition – ME – for mobile environments).

The JDK includes the compiler and other tools needed to develop Java applications; JRE does not. So, to run a Java application someone else provides, you need JRE; to develop a Java application, you need JDK.

Edited: As Chris Marasti-Georg pointed out in a comment, you can find out lots of information at Sun's Java web site, and in particular from the Java SE section, (2nd option, Java SE Development Kit (JDK) 6 Update 10).


Edited 2011-04-06: The world turns, and Java is now managed by Oracle, which bought Sun. Later this year, the sun.com domain is supposed to go dark. The new page (based on a redirect) is this Java page at the Oracle Tech Network. (See also java.com.)


Edited 2013-01-11: And the world keeps on turning (2012-12-21 notwithstanding), and lo and behold, JRE 6 is about to reach its end of support. Oracle says no more public updates to Java 6 after February 2013.

Within a given version of Java, this answer remains valid. JDK is the Java Development Kit, JRE is the Java Runtime Environment, Java SE is the standard edition, and so on. But the version 6 (1.6) is becoming antiquated.

Edited 2015-04-29: And with another couple of revolutions around the sun, the time has come for the end of support for Java SE 7, too. In April 2015, Oracle affirmed that it was no longer providing public updates to Java SE 7. The tentative end of public updates for Java SE 8 is March 2017, but that end date is subject to change (later, not earlier).

Comment out HTML and PHP together

I found the following solution pretty effective if you need to comment a lot of nested HTML + PHP code.

Wrap all the content in this:

<?php
    if(false){
?>

Here goes your PHP + HTML code

<?php
    }
?>

ReferenceError: document is not defined (in plain JavaScript)

try: window.document......

var body = window.document.getElementsByTagName("body")[0];

How to ensure that there is a delay before a service is started in systemd?

Combining the answers from @Ortomala Lokni and @rogerdpack, another alternative is to have the dependent service monitor when the first one has started / done the thing you're waiting for.

For example, here's how I am making the fail2ban service wait for Docker to open port 443 (so that fail2ban's iptables entries take priority over Docker's):

[Service]
ExecStartPre=/bin/bash -c '(while ! nc -z -v -w1 localhost 443 > /dev/null; do echo "Waiting for port 443 to open..."; sleep 2; done); sleep 2'

Simply replace nc -z -v -w1 localhost 443 with a command that fails (non-zero exit code) while the first service is starting and succeeds once it is up.

For the Cassandra case, the ideal would be a command that only returns 0 when the cluster is available.

onchange equivalent in angular2

You can use:

<input (input)="saverange()>

How to embed small icon in UILabel

You can do this with iOS 7's text attachments, which are part of TextKit. Some sample code:

NSTextAttachment *attachment = [[NSTextAttachment alloc] init];
attachment.image = [UIImage imageNamed:@"MyIcon.png"];

NSAttributedString *attachmentString = [NSAttributedString attributedStringWithAttachment:attachment];

NSMutableAttributedString *myString= [[NSMutableAttributedString alloc] initWithString:@"My label text"];
[myString appendAttributedString:attachmentString];

myLabel.attributedText = myString;

How to remove the last element added into the List?

You can use List<T>.RemoveAt method:

rows.RemoveAt(rows.Count -1);

How to test if a string is basically an integer in quotes using Ruby

Well, here's the easy way:

class String
  def is_integer?
    self.to_i.to_s == self
  end
end

>> "12".is_integer?
=> true
>> "blah".is_integer?
=> false

I don't agree with the solutions that provoke an exception to convert the string - exceptions are not control flow, and you might as well do it the right way. That said, my solution above doesn't deal with non-base-10 integers. So here's the way to do with without resorting to exceptions:

  class String
    def integer? 
      [                          # In descending order of likeliness:
        /^[-+]?[1-9]([0-9]*)?$/, # decimal
        /^0[0-7]+$/,             # octal
        /^0x[0-9A-Fa-f]+$/,      # hexadecimal
        /^0b[01]+$/              # binary
      ].each do |match_pattern|
        return true if self =~ match_pattern
      end
      return false
    end
  end

Composer: Command Not Found

First I did alias setup on bash / zsh profile.

alias composer="php /usr/local/bin/composer.phar"

Then I moved composer.phar to /usr/local/bin/

cd /usr/local/bin
mv composer.phar composer

Then made composer executable by running

sudo chmod +x composer

How to print all key and values from HashMap in Android?

Kotlin Answer

for ((key, value) in map.entries) {
    // do something with `key`
    // so something with `value`
}

You may find other solutions that include filterValues. Just keep in mind that retrieving a Key value using filterValues will include braces [].

val key = map.filterValues {it = position}.keys

Anaconda site-packages

You should find installed packages in :

anaconda's directory / lib / site_packages

That's where i found mine.

bash script read all the files in directory

A simple loop should be working:

for file in /var/*
do
    #whatever you need with "$file"
done

See bash filename expansion

How to call javascript function on page load in asp.net

Calling JavaScript function on code behind i.e. On Page_Load

ClientScript.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

If you have UpdatePanel there then try like this

ScriptManager.RegisterStartupScript(GetType(), "Javascript", "javascript:FUNCTIONNAME(); ", true);

View Blog Article : How to Call javascript function from code behind in asp.net c#

AngularJS - Value attribute on an input text box is ignored when there is a ng-model used?

Vojta described the "Angular way", but if you really need to make this work, @urbanek recently posted a workaround using ng-init:

<input type="text" ng-model="rootFolders" ng-init="rootFolders='Bob'" value="Bob">

https://groups.google.com/d/msg/angular/Hn3eztNHFXw/wk3HyOl9fhcJ

Remove innerHTML from div

jQuery Data is a different concept than HTML. removeData is not for removing element content, it's for removing data items you've previously stored.

Just do

divToUpdate.html("");

or

divToUpdate.empty();

SQLSTATE[HY000] [1698] Access denied for user 'root'@'localhost'

Turns out you can't use the root user in 5.7 anymore without becoming a sudoer. That means you can't just run mysql -u root anymore and have to do sudo mysql -u root instead.

That also means that it will no longer work if you're using the root user in a GUI (or supposedly any non-command line application). To make it work you'll have to create a new user with the required privileges and use that instead.

See this answer for more details.

What are Maven goals and phases and what is their difference?

The chosen answer is great, but still I would like to add something small to the topic. An illustration.

It clearly demonstrates how the different phases binded to different plugins and the goals that those plugins expose.

So, let's examine a case of running something like mvn compile:

  • It's a phase which execute the compiler plugin with compile goal
  • Compiler plugin got different goals. For mvn compile it's mapped to a specific goal, the compile goal.
  • It's the same as running mvn compiler:compile

Therefore, phase is made up of plugin goals.

enter image description here

Link to the reference

How do I print a double value with full precision using cout?

Use std::setprecision:

std::cout << std::setprecision (15) << 3.14159265358979 << std::endl;

Jquery/Ajax Form Submission (enctype="multipart/form-data" ). Why does 'contentType:False' cause undefined index in PHP?

contentType option to false is used for multipart/form-data forms that pass files.

When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multipart/form-data, one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.


To try and fix your issue:

Use jQuery's .serialize() method which creates a text string in standard URL-encoded notation.

You need to pass un-encoded data when using contentType: false.

Try using new FormData instead of .serialize():

  var formData = new FormData($(this)[0]);

See for yourself the difference of how your formData is passed to your php page by using console.log().

  var formData = new FormData($(this)[0]);
  console.log(formData);

  var formDataSerialized = $(this).serialize();
  console.log(formDataSerialized);

Can I have an onclick effect in CSS?

Warning! Particularly simple answer below! :)

You actually can have a change that persists (such as a block/popup that appears and stays visible after a click) with only CSS (and without using the checkbox hack) despite what many of the (otherwise correct) answers here claim, as long as you only need persistence during the hover.

So take a look at Bojangles and TylerH's answers if those work for you, but if you want a simple and CSS only answer that will keep a block visible after being clicked on (and even can have the block disappear with a followup click), then see this solution.

I had a similar situation, I needed a popup div with onClick where I couldn't add any JS or change the markup/HTML (a truly CSS solution) and this is possible with some caveats. You can't use the :target trick that can create a nice popup unless you can change the HTML (to add an 'id') so that was out.

In my case the popup div was contained inside the other div, and I wanted the popup to appear on top of the other div, and this can be done using a combination of :active and :hover:

/* Outer div - needs to be relative so we can use absolute positioning */
.clickToShowInfo {
    position: relative;
}
/* When clicking outer div, make inner div visible */
.clickToShowInfo:active .info { display: block; }
/* And hold by staying visible on hover */
.info:hover {
    display: block;
}
/* General settings for popup */
.info {
    position: absolute;
    top: -5;
    display: none;
    z-index: 100;
    background-color: white;
    width: 200px;
    height: 200px;
}

Example (as well as one that allows clicking on the popup to make it disappear) at:

http://davesource.com/Solutions/20150324.CSS-Only-Click-to-Popup-Div/

I've also inserted a code snippet example below, but the positioning in the stackoverflow sandbox is weird so I had to put the 'click here' text after the innerDiv, which isn't normally needed.

_x000D_
_x000D_
/* Outer div - needs to be relative so we can use absolute positioning */_x000D_
 .clickToShowInfo {_x000D_
  position: relative;_x000D_
 }_x000D_
 /* When clicking outer div, make inner div visible */_x000D_
 .clickToShowInfo:active .info { visibility: visible; }_x000D_
 /* And hold by staying visible on hover */_x000D_
 .info:hover {_x000D_
  visibility: visible;_x000D_
 }_x000D_
 /* General settings for popup */_x000D_
 .info {_x000D_
  position: absolute;_x000D_
  top: -10;_x000D_
  visibility: hidden;_x000D_
  z-index: 100;_x000D_
  background-color: white;_x000D_
  box-shadow: 5px 5px 2px #aaa;_x000D_
  border: 1px solid grey;_x000D_
  padding: 8px;_x000D_
  width: 220px;_x000D_
  height: 200px;_x000D_
 }_x000D_
 /* If we want clicking on the popup to close, use this */_x000D_
 .info:active {_x000D_
  visibility: hidden; /* Doesn't work because DCEvent is :active as well */_x000D_
  height: 0px;_x000D_
  width: 0px;_x000D_
  left: -1000px;_x000D_
  top: -1000px;_x000D_
 }
_x000D_
<p />_x000D_
<div class="clickToShowInfo">_x000D_
 <div class="info">_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua_x000D_
 </div>_x000D_
 Click here to show info_x000D_
</div>_x000D_
<p />
_x000D_
_x000D_
_x000D_

How to vertically align <li> elements in <ul>?

Here's a good one:

Set line-height equal to whatever the height is; works like a charm!

E.g:

li {
    height: 30px;
    line-height: 30px;
}

Oracle: is there a tool to trace queries, like Profiler for sql server?

This is an Oracle doc explaining how to trace SQL queries, including a couple of tools (SQL Trace and tkprof)

link

What is a 'workspace' in Visual Studio Code?

The title and subsequent question in the OP seem to boil down to:

  1. What is a workspace in VS Code?
  2. How do workspace settings work?

Short answer:

A workspace is a virtual collection of folders opened simultaneously in VSCode and defined in a .code-workspace file. Opening this file will open the collection of folders automatically. This is called a "multi-root" workspace.

The .code-workspace file also defines workspace settings that are used by the instance of VSCode where the workspace is opened.

When a workspace is not defined, i.e. you open a folder on its own, you can create "workspace settings" that are saved in a .vscode\settings.json file in the root of that folder structure.


In more detail:

VSCode uses the word "workspace" a little ambiguously in places. The first use to consider is in what is calls a multi-root workspace.

A multi-root workspace is a set of folders (the "roots") that are opened collectively in an instance of VSCode. There is no need for these folders to share parent folders; indeed that is the point since VSCode normally uses a single folder in the Explorer side-bar.

A multi-root workspace is defined by a .code-workspace (JSON) file which contains both the list of folders to be included in the workspace and VSCode settings.

Regarding those workspace settings...

When you open File > Preferences > Settings the settings editor is shown. At the very least you should see a USER SETTINGS tab. These are the VSCode settings that are universal for your user account on your local machine. In Windows these are saved in %APPDATA%\Code\User\settings.json.

Individual folders (often each of the "root" folders in a workspace) might have a .vscode folder with their own settings.json file. When opened individually, i.e. not as part of a workspace, the content of these settings.json files is presented under the WORKSPACE SETTINGS tab, and ALL the settings in that file are used by the running VSCode instance.

When opening a multi-root workspace things behave differently. Firstly, the WORKSPACE SETTINGS tab shows the options set in the .code-workspace file. Secondly, any folder with a settings.json file will appear under a new FOLDER SETTINGS tab. Be aware that, when in a multi-root workspace, only a limited number of settings from each folder's settings.json are used. I suggest you open the link above to read further.

How to make div background color transparent in CSS

The problem with opacity is that it will also affect the content, when often you do not want this to happen.

If you just want your element to be transparent, it's really as easy as :

background-color: transparent;

But if you want it to be in colors, you can use:

background-color: rgba(255, 0, 0, 0.4);

Or define a background image (1px by 1px) saved with the right alpha.
(To do so, use Gimp, Paint.Net or any other image software that allows you to do that.
Just create a new image, delete the background and put a semi-transparent color in it, then save it in png.)

As said by René, the best thing to do would be to mix both, with the rgba first and the 1px by 1px image as a fallback if the browser doesn't support alpha :

background: url('img/red_transparent_background.png');
background: rgba(255, 0, 0, 0.4);

See also : http://www.w3schools.com/cssref/css_colors_legal.asp.

Demo : My JSFiddle

Mock a constructor with parameter

Mockito has limitations testing final, static, and private methods.

with jMockit testing library, you can do few stuff very easy and straight-forward as below:

Mock constructor of a java.io.File class:

new MockUp<File>(){
    @Mock
    public void $init(String pathname){
        System.out.println(pathname);
        // or do whatever you want
    }
};
  • the public constructor name should be replaced with $init
  • arguments and exceptions thrown remains same
  • return type should be defined as void

Mock a static method:

  • remove static from the method mock signature
  • method signature remains same otherwise

Find Java classes implementing an interface

If you were asking from the perspective of working this out with a running program then you need to look to the java.lang.* package. If you get a Class object, you can use the isAssignableFrom method to check if it is an interface of another Class.

There isn't a simple built in way of searching for these, tools like Eclipse build an index of this information.

If you don't have a specific list of Class objects to test you can look to the ClassLoader object, use the getPackages() method and build your own package hierarchy iterator.

Just a warning though that these methods and classes can be quite slow.

Calculating distance between two points, using latitude longitude?

Note: this solution only works for short distances.

I tried to use dommer's posted formula for an application and found it did well for long distances but in my data I was using all very short distances, and dommer's post did very poorly. I needed speed, and the more complex geo calcs worked well but were too slow. So, in the case that you need speed and all the calculations you're making are short (maybe < 100m or so). I found this little approximation to work great. it assumes the world is flat mind you, so don't use it for long distances, it works by approximating the distance of a single Latitude and Longitude at the given Latitude and returning the Pythagorean distance in meters.

public class FlatEarthDist {
    //returns distance in meters
    public static double distance(double lat1, double lng1, 
                                      double lat2, double lng2){
     double a = (lat1-lat2)*FlatEarthDist.distPerLat(lat1);
     double b = (lng1-lng2)*FlatEarthDist.distPerLng(lat1);
     return Math.sqrt(a*a+b*b);
    }

    private static double distPerLng(double lat){
      return 0.0003121092*Math.pow(lat, 4)
             +0.0101182384*Math.pow(lat, 3)
                 -17.2385140059*lat*lat
             +5.5485277537*lat+111301.967182595;
    }

    private static double distPerLat(double lat){
            return -0.000000487305676*Math.pow(lat, 4)
                -0.0033668574*Math.pow(lat, 3)
                +0.4601181791*lat*lat
                -1.4558127346*lat+110579.25662316;
    }
}

Creating for loop until list.length

You could learn about Python loops here: http://en.wikibooks.org/wiki/Python_Programming/Loops

You have to know that Python doesn't have { and } for start and end of loop, instead it depends on tab chars you enter in first of line, I mean line indents.

So you can do loop inside loop with double tab (indent)

An example of double loop is like this:

onetoten = range(1,11)
tentotwenty = range(10,21)
for count in onetoten:
    for count2 in tentotwenty
        print(count2)

c++ exception : throwing std::string

A few principles:

  1. you have a std::exception base class, you should have your exceptions derive from it. That way general exception handler still have some information.

  2. Don't throw pointers but object, that way memory is handled for you.

Example:

struct MyException : public std::exception
{
   std::string s;
   MyException(std::string ss) : s(ss) {}
   ~MyException() throw () {} // Updated
   const char* what() const throw() { return s.c_str(); }
};

And then use it in your code:

void Foo::Bar(){
  if(!QueryPerformanceTimer(&m_baz)){
    throw MyException("it's the end of the world!");
  }
}

void Foo::Caller(){
  try{
    this->Bar();// should throw
  }catch(MyException& caught){
    std::cout<<"Got "<<caught.what()<<std::endl;
  }
}

EC2 instance types's exact network performance?

Almost everything in EC2 is multi-tenant. What the network performance indicates is what priority you will have compared with other instances sharing the same infrastructure.

If you need a guaranteed level of bandwidth, then EC2 will likely not work well for you.

What is your favorite C programming trick?

Declaring array's of pointer to functions for implementing finite state machines.

int (* fsm[])(void) = { ... }

The most pleasing advantage is that it is simple to force each stimulus/state to check all code paths.

In an embedded system, I'll often map an ISR to point to such a table and revector it as needed (outside the ISR).

SQL Server: Filter output of sp_who2

Extension of the first and best answer... I have created a stored procedure on the master database that you can then pass parameters to .. such as the name of the database:

USE master
GO

CREATE PROCEDURE sp_who_db
(
    @sDBName varchar(200)   = null,
    @sStatus varchar(200)   = null,
    @sCommand varchar(200)  = null,
    @nCPUTime int           = null
)
AS
DECLARE @Table TABLE
(
    SPID INT,
    Status VARCHAR(MAX),
    LOGIN VARCHAR(MAX),
    HostName VARCHAR(MAX),
    BlkBy VARCHAR(MAX),
    DBName VARCHAR(MAX),
    Command VARCHAR(MAX),
    CPUTime INT,
    DiskIO INT,
    LastBatch VARCHAR(MAX),
    ProgramName VARCHAR(MAX),
    SPID_1 INT,
    REQUESTID INT
)

INSERT INTO @Table EXEC sp_who2

SELECT  *
    FROM    @Table
    WHERE   (@sDBName IS NULL OR DBName = @sDBName)
    AND     (@sStatus IS NULL OR Status = @sStatus)
    AND     (@sCommand IS NULL OR Command = @sCommand)
    AND     (@nCPUTime IS NULL OR CPUTime > @nCPUTime)
GO 

I might extend it to add an order by parameter or even a kill paramatmer so it kills all connections to a particular data

bash: pip: command not found

Check out How to Install Pip article article for more information.

As of 2019,

Download get-pip.py provided by https://pip.pypa.io using the following command:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

Run get-pip.py using the following command:
sudo python get-pip.py

After you done installing, run this command to check if pip is installed.
pip --version

Remove get-pip.py file after installing pip.
rm get-pip.py

Pip website

dropzone.js - how to do something after ALL files are uploaded

I was trying to work with that solutions but it doesn't work. But later I was realize that the function it wasn't declared so I watch in to the dropzone.com page and take the example to call events. So finally work on my site. For those like me who don't understand JavaScript very well, I leave you the example.

<script type="text/javascript" src="/js/dropzone.js"></script>
<script type="text/javascript">
// This example uses jQuery so it creates the Dropzone, only when the DOM has
// loaded.

// Disabling autoDiscover, otherwise Dropzone will try to attach twice.
Dropzone.autoDiscover = false;
// or disable for specific dropzone:
// Dropzone.options.myDropzone = false;

$(function() {
  // Now that the DOM is fully loaded, create the dropzone, and setup the
  // event listeners
  var myDropzone = new Dropzone(".dropzone");

  myDropzone.on("queuecomplete", function(file, res) {
      if (myDropzone.files[0].status != Dropzone.SUCCESS ) {
          alert('yea baby');
      } else {
          alert('cry baby');

      }
  });
});
</script>

how to check if item is selected from a comboBox in C#

if (comboBox1.SelectedIndex == -1)
{
    //Done
}

It Works,, Try it

PHP - auto refreshing page

This works with Firefox Quantum 60+ and Chrome v72 (2019)

//set a header to instruct the browser to call the page every 30 sec
header("Refresh: 30;");

It does not seem to be NECESSARY to pass the page url as well as the refresh period in order to (re)call the same page. I haven't tried this with Safari/Opera or IE/Edge.

angular2: how to copy object into another object

Object.assign will only work in single level of object reference.

To do a copy in any depth use as below:

let x = {'a':'a','b':{'c':'c'}};
let y = JSON.parse(JSON.stringify(x));

If want to use any library instead then go with the loadash.js library.

How to source virtualenv activate in a Bash script

Here is the script that I use often. Run it as $ source script_name

#!/bin/bash -x
PWD=`pwd`
/usr/local/bin/virtualenv --python=python3 venv
echo $PWD
activate () {
    . $PWD/venv/bin/activate
}

activate

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

I found the issue. This is a firewall message and an error was occurring in the VB script due to wrong data in database, but the error was not logged/caught properly.

How can I control Chromedriver open window size?

Ruby version:

caps = Selenium::WebDriver::Remote::Capabilities.chrome("chromeOptions" => {"args"=> ["--window-size=1280,960"]})

url = "http://localhost:9515"  # if you are using local chrome or url = Browserstack/ saucelabs hub url if you are using cloud service providers.

 Selenium::WebDriver.for(:remote, :url => url, :desired_capabilities => caps)

resize chrome is buggy in latest chromedrivers , it fails intermittanly with this failure message.

                        unknown error: cannot get automation extension
from timeout: cannot determine loading status
from timeout: Timed out receiving message from renderer: -65.294
  (Session info: chrome=56.0.2924.76)
  (Driver info: chromedriver=2.28.455517 (2c6d2707d8ea850c862f04ac066724273981e88f)

And resizeTo via javascript also not supported for chrome started via selenium webdriver. So the last option was using command line switches.

How to detect a remote side socket close?

Since the answers deviate I decided to test this and post the result - including the test example.

The server here just writes data to a client and does not expect any input.

The server:

ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
  out.println("output");
  if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
  System.out.println(clientSocket.isConnected());
  System.out.println(clientSocket.getInputStream().read());
        // thread sleep ...
  // break condition , close sockets and the like ...
}
  • clientSocket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!
  • getInputStream().read()
    • makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
    • returns -1 if the client disconnected
  • out.checkError() is true as soon as the client is disconnected so I recommend this

Angular 5 - Copy to clipboard

Modified version of jockeisorby's answer that fixes the event handler not being properly removed.

copyToClipboard(item): void {
    let listener = (e: ClipboardEvent) => {
        e.clipboardData.setData('text/plain', (item));
        e.preventDefault();
    };

    document.addEventListener('copy', listener);
    document.execCommand('copy');
    document.removeEventListener('copy', listener);
}

How do I launch a Git Bash window with particular working directory using a script?

I might given a wrong direction, but, I like this trick.

Using Windows Explorer, pointing to any directory you want, type "cmd" in the address bar it will open Windows command prompt in that directory.

If you have the "Git" directory in your path, in the same way, you can type "git-bash" in the address bar and a Git Shell will open in that directory.

Windows command to convert Unix line endings?

Here's a simple unix2dos.bat file that preserves blank lines and exclamation points:

@echo off
setlocal DisableDelayedExpansion
for /f "tokens=1,* delims=:" %%k in ('findstr /n "^" %1') do echo.%%l

The output goes to standard out, so redirect unix2dos.bat output to a file if so desired.

It avoids the pitfalls of other previously proposed for /f batch loop solutions by:
1) Working with delayed expansion off, to avoid eating up exclamation marks.
2) Using the for /f tokenizer itself to remove the line number from the findstr /n output lines.
(Using findstr /n is necessary to also get blank lines: They would be dropped if for /f read directly from the input file.)

But, as Jeb pointed out in a comment below, the above solution has one drawback the others don't: It drops colons at the beginning of lines.

So 2020-04-06 update just for fun, here's another 1-liner based on findstr.exe, that seems to work fine without the above drawbacks:

@echo off
setlocal DisableDelayedExpansion
for /f "tokens=* delims=0123456789" %%l in ('findstr /n "^" %1') do echo%%l

The additional tricks are:
3) Use digits 0-9 as delimiters, so that tokens=* skips the initial line number.
4) Use the colon, inserted by findstr /n after the line number, as the token separator after the echo command.

I'll leave it to Jeb to explain if there are corner cases where echo:something might fail :-)
All I can say is that this last version successfully restored line endings on my huge batch library, so exceptions, if any, must be quite rare!

Where can I get Google developer key

If you are only calling APIs that do not require user data, such as the Google Custom Search API, then API keys might be simpler to use than OAuth 2.0 access tokens. However, if your application already uses an OAuth 2.0 access token, then there is no need to generate an API key as well. Google ignores passed API keys if a passed OAuth 2.0 access token is already associated with the corresponding project.

Note: You must use either an OAuth 2.0 access token or an API key for all requests to Google APIs represented in the Google Developers Console. Not all APIs require authorized calls. To learn whether authorization is required for a specific call, see your API documentation.

Reference: https://developers.google.com/console/help/new/?hl=en_US#credentials-access-security-and-identity

Can a table row expand and close?

jQuery

$(function() {
    $("td[colspan=3]").find("div").hide();
    $("tr").click(function(event) {
        var $target = $(event.target);
        $target.closest("tr").next().find("div").slideToggle();                
    });
});

HTML

<table>
    <thead>
        <tr>
            <th>one</th><th>two</th><th>three</th>
        </tr>
    </thead>
    <tbody>

        <tr>
            <td><p>data<p></td><td>data</td><td>data</td>
        </tr>
        <tr>
            <td colspan="3">
                <div>
                    <table>
                            <tr>
                                <td>data</td><td>data</td>
                            </tr>
                    </table>
                </div>
            </td>
        </tr>
    </tbody>
</table>

This is much like a previous example above. I found when trying to implement that example that if the table row to be expanded was clicked while it was not expanded it would disappear, and it would no longer be expandable

To fix that I simply removed the ability to click the expandable element for slide up and made it so that you can only toggle using the above table row.

I also made some minor changes to HTML and corresponding jQuery.

NOTE: I would have just made a comment but am not allowed to yet therefore the long post. Just wanted to post this as it took me a bit to figure out what was happening to the disappearing table row.

Credit to Peter Ajtai

A button to start php script, how?

What exactly do you mean by "starts my php script"? What kind of PHP script? One to generate an HTML response for an end-user, or one that simply performs some kind of data processing task? If you are familiar with using the tag and how it interacts with PHP, then you should only need to POST to your target PHP script using an button of type "submit". If you are not familiar with forms, take a look here.

How to save and load cookies using Python + Selenium WebDriver

Based on the answer by Eduard Florinescu, but with newer code and the missing imports added:

$ cat work-auth.py
#!/usr/bin/python3

# Setup:
# sudo apt-get install chromium-chromedriver
# sudo -H python3 -m pip install selenium

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
chrome_options.add_argument("user-data-dir=chrome-data")
driver.get('https://www.somedomainthatrequireslogin.com')
time.sleep(30)  # Time to enter credentials
driver.quit()

$ cat work.py
#!/usr/bin/python3

import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('/usr/bin/chromedriver',options=chrome_options)
driver.get('https://www.somedomainthatrequireslogin.com')  # Already authenticated
time.sleep(10)
driver.quit()

Emulating a do-while loop in Bash

This implementation:

  • Has no code duplication
  • Doesn't require extra functions()
  • Doesn't depend on the return value of code in the "while" section of the loop:
do=true
while $do || conditions; do
  do=false
  # your code ...
done

It works with a read loop, too, skipping the first read:

do=true
while $do || read foo; do
  do=false

  # your code ...
  echo $foo
done

Why shouldn't I use mysql_* functions in PHP?

It's possible to define almost all mysql_* functions using mysqli or PDO. Just include them on top of your old PHP application, and it will work on PHP7. My solution here.

<?php

define('MYSQL_LINK', 'dbl');
$GLOBALS[MYSQL_LINK] = null;

function mysql_link($link=null) {
    return ($link === null) ? $GLOBALS[MYSQL_LINK] : $link;
}

function mysql_connect($host, $user, $pass) {
    $GLOBALS[MYSQL_LINK] = mysqli_connect($host, $user, $pass);
    return $GLOBALS[MYSQL_LINK];
}

function mysql_pconnect($host, $user, $pass) {
    return mysql_connect($host, $user, $pass);
}

function mysql_select_db($db, $link=null) {
    $link = mysql_link($link);
    return mysqli_select_db($link, $db);
}

function mysql_close($link=null) {
    $link = mysql_link($link);
    return mysqli_close($link);
}

function mysql_error($link=null) {
    $link = mysql_link($link);
    return mysqli_error($link);
}

function mysql_errno($link=null) {
    $link = mysql_link($link);
    return mysqli_errno($link);
}

function mysql_ping($link=null) {
    $link = mysql_link($link);
    return mysqli_ping($link);
}

function mysql_stat($link=null) {
    $link = mysql_link($link);
    return mysqli_stat($link);
}

function mysql_affected_rows($link=null) {
    $link = mysql_link($link);
    return mysqli_affected_rows($link);
}

function mysql_client_encoding($link=null) {
    $link = mysql_link($link);
    return mysqli_character_set_name($link);
}

function mysql_thread_id($link=null) {
    $link = mysql_link($link);
    return mysqli_thread_id($link);
}

function mysql_escape_string($string) {
    return mysql_real_escape_string($string);
}

function mysql_real_escape_string($string, $link=null) {
    $link = mysql_link($link);
    return mysqli_real_escape_string($link, $string);
}

function mysql_query($sql, $link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, $sql);
}

function mysql_unbuffered_query($sql, $link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, $sql, MYSQLI_USE_RESULT);
}

function mysql_set_charset($charset, $link=null){
    $link = mysql_link($link);
    return mysqli_set_charset($link, $charset);
}

function mysql_get_host_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_host_info($link);
}

function mysql_get_proto_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_proto_info($link);
}
function mysql_get_server_info($link=null) {
    $link = mysql_link($link);
    return mysqli_get_server_info($link);
}

function mysql_info($link=null) {
    $link = mysql_link($link);
    return mysqli_info($link);
}

function mysql_get_client_info() {
    $link = mysql_link();
    return mysqli_get_client_info($link);
}

function mysql_create_db($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "CREATE DATABASE `$db`");
}

function mysql_drop_db($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "DROP DATABASE `$db`");
}

function mysql_list_dbs($link=null) {
    $link = mysql_link($link);
    return mysqli_query($link, "SHOW DATABASES");
}

function mysql_list_fields($db, $table, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    $table = str_replace('`', '', mysqli_real_escape_string($link, $table));
    return mysqli_query($link, "SHOW COLUMNS FROM `$db`.`$table`");
}

function mysql_list_tables($db, $link=null) {
    $link = mysql_link($link);
    $db = str_replace('`', '', mysqli_real_escape_string($link, $db));
    return mysqli_query($link, "SHOW TABLES FROM `$db`");
}

function mysql_db_query($db, $sql, $link=null) {
    $link = mysql_link($link);
    mysqli_select_db($link, $db);
    return mysqli_query($link, $sql);
}

function mysql_fetch_row($qlink) {
    return mysqli_fetch_row($qlink);
}

function mysql_fetch_assoc($qlink) {
    return mysqli_fetch_assoc($qlink);
}

function mysql_fetch_array($qlink, $result=MYSQLI_BOTH) {
    return mysqli_fetch_array($qlink, $result);
}

function mysql_fetch_lengths($qlink) {
    return mysqli_fetch_lengths($qlink);
}

function mysql_insert_id($qlink) {
    return mysqli_insert_id($qlink);
}

function mysql_num_rows($qlink) {
    return mysqli_num_rows($qlink);
}

function mysql_num_fields($qlink) {
    return mysqli_num_fields($qlink);
}

function mysql_data_seek($qlink, $row) {
    return mysqli_data_seek($qlink, $row);
}

function mysql_field_seek($qlink, $offset) {
    return mysqli_field_seek($qlink, $offset);
}

function mysql_fetch_object($qlink, $class="stdClass", array $params=null) {
    return ($params === null)
        ? mysqli_fetch_object($qlink, $class)
        : mysqli_fetch_object($qlink, $class, $params);
}

function mysql_db_name($qlink, $row, $field='Database') {
    mysqli_data_seek($qlink, $row);
    $db = mysqli_fetch_assoc($qlink);
    return $db[$field];
}

function mysql_fetch_field($qlink, $offset=null) {
    if ($offset !== null)
        mysqli_field_seek($qlink, $offset);
    return mysqli_fetch_field($qlink);
}

function mysql_result($qlink, $offset, $field=0) {
    if ($offset !== null)
        mysqli_field_seek($qlink, $offset);
    $row = mysqli_fetch_array($qlink);
    return (!is_array($row) || !isset($row[$field]))
        ? false
        : $row[$field];
}

function mysql_field_len($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    return is_object($field) ? $field->length : false;
}

function mysql_field_name($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    if (!is_object($field))
        return false;
    return empty($field->orgname) ? $field->name : $field->orgname;
}

function mysql_field_table($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    if (!is_object($field))
        return false;
    return empty($field->orgtable) ? $field->table : $field->orgtable;
}

function mysql_field_type($qlink, $offset) {
    $field = mysqli_fetch_field_direct($qlink, $offset);
    return is_object($field) ? $field->type : false;
}

function mysql_free_result($qlink) {
    try {
        mysqli_free_result($qlink);
    } catch (Exception $e) {
        return false;
    }
    return true;
}

Use underscore inside Angular controllers

I have implemented @satchmorun's suggestion here: https://github.com/andresesfm/angular-underscore-module

To use it:

  1. Make sure you have included underscore.js in your project

    <script src="bower_components/underscore/underscore.js">
    
  2. Get it:

    bower install angular-underscore-module
    
  3. Add angular-underscore-module.js to your main file (index.html)

    <script src="bower_components/angular-underscore-module/angular-underscore-module.js"></script>
    
  4. Add the module as a dependency in your App definition

    var myapp = angular.module('MyApp', ['underscore'])
    
  5. To use, add as an injected dependency to your Controller/Service and it is ready to use

    angular.module('MyApp').controller('MyCtrl', function ($scope, _) {
    ...
    //Use underscore
    _.each(...);
    ...
    

Getting number of days in a month

  • int days = DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month);


if you want to find days in this year and present month then this is best

Python wildcard search in string

Do you mean any specific syntax for wildcards? Usually * stands for "one or many" characters and ? stands for one.

The simplest way probably is to translate a wildcard expression into a regular expression, then use that for filtering the results.

How to make a script wait for a pressed key?

On my linux box, I use the following code. This is similar to code I've seen elsewhere (in the old python FAQs for instance) but that code spins in a tight loop where this code doesn't and there are lots of odd corner cases that code doesn't account for that this code does.

def read_single_keypress():
    """Waits for a single keypress on stdin.

    This is a silly function to call if you need to do it a lot because it has
    to store stdin's current setup, setup stdin for reading single keystrokes
    then read the single keystroke then revert stdin back after reading the
    keystroke.

    Returns a tuple of characters of the key that was pressed - on Linux, 
    pressing keys like up arrow results in a sequence of characters. Returns 
    ('\x03',) on KeyboardInterrupt which can happen when a signal gets
    handled.

    """
    import termios, fcntl, sys, os
    fd = sys.stdin.fileno()
    # save old state
    flags_save = fcntl.fcntl(fd, fcntl.F_GETFL)
    attrs_save = termios.tcgetattr(fd)
    # make raw - the way to do this comes from the termios(3) man page.
    attrs = list(attrs_save) # copy the stored version to update
    # iflag
    attrs[0] &= ~(termios.IGNBRK | termios.BRKINT | termios.PARMRK
                  | termios.ISTRIP | termios.INLCR | termios. IGNCR
                  | termios.ICRNL | termios.IXON )
    # oflag
    attrs[1] &= ~termios.OPOST
    # cflag
    attrs[2] &= ~(termios.CSIZE | termios. PARENB)
    attrs[2] |= termios.CS8
    # lflag
    attrs[3] &= ~(termios.ECHONL | termios.ECHO | termios.ICANON
                  | termios.ISIG | termios.IEXTEN)
    termios.tcsetattr(fd, termios.TCSANOW, attrs)
    # turn off non-blocking
    fcntl.fcntl(fd, fcntl.F_SETFL, flags_save & ~os.O_NONBLOCK)
    # read a single keystroke
    ret = []
    try:
        ret.append(sys.stdin.read(1)) # returns a single character
        fcntl.fcntl(fd, fcntl.F_SETFL, flags_save | os.O_NONBLOCK)
        c = sys.stdin.read(1) # returns a single character
        while len(c) > 0:
            ret.append(c)
            c = sys.stdin.read(1)
    except KeyboardInterrupt:
        ret.append('\x03')
    finally:
        # restore old state
        termios.tcsetattr(fd, termios.TCSAFLUSH, attrs_save)
        fcntl.fcntl(fd, fcntl.F_SETFL, flags_save)
    return tuple(ret)

HTTP Error 404.3-Not Found in IIS 7.5

I was having trouble accessing wcf service hosted locally in IIS. Running aspnet_regiis.exe -i wasn't working.

However, I fortunately came across the following:

Rahul's blog

which informs that servicemodelreg also needs to be run:

Run Visual Studio 2008 Command Prompt as “Administrator”. Navigate to C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation. Run this command servicemodelreg –i.

How do you create a custom AuthorizeAttribute in ASP.NET Core?

You can create your own AuthorizationHandler that will find custom attributes on your Controllers and Actions, and pass them to the HandleRequirementAsync method.

public abstract class AttributeAuthorizationHandler<TRequirement, TAttribute> : AuthorizationHandler<TRequirement> where TRequirement : IAuthorizationRequirement where TAttribute : Attribute
{
    protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement)
    {
        var attributes = new List<TAttribute>();

        var action = (context.Resource as AuthorizationFilterContext)?.ActionDescriptor as ControllerActionDescriptor;
        if (action != null)
        {
            attributes.AddRange(GetAttributes(action.ControllerTypeInfo.UnderlyingSystemType));
            attributes.AddRange(GetAttributes(action.MethodInfo));
        }

        return HandleRequirementAsync(context, requirement, attributes);
    }

    protected abstract Task HandleRequirementAsync(AuthorizationHandlerContext context, TRequirement requirement, IEnumerable<TAttribute> attributes);

    private static IEnumerable<TAttribute> GetAttributes(MemberInfo memberInfo)
    {
        return memberInfo.GetCustomAttributes(typeof(TAttribute), false).Cast<TAttribute>();
    }
}

Then you can use it for any custom attributes you need on your controllers or actions. For example to add permission requirements. Just create your custom attribute.

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public class PermissionAttribute : AuthorizeAttribute
{
    public string Name { get; }

    public PermissionAttribute(string name) : base("Permission")
    {
        Name = name;
    }
}

Then create a Requirement to add to your Policy

public class PermissionAuthorizationRequirement : IAuthorizationRequirement
{
    //Add any custom requirement properties if you have them
}

Then create the AuthorizationHandler for your custom attribute, inheriting the AttributeAuthorizationHandler that we created earlier. It will be passed an IEnumerable for all your custom attributes in the HandleRequirementsAsync method, accumulated from your Controller and Action.

public class PermissionAuthorizationHandler : AttributeAuthorizationHandler<PermissionAuthorizationRequirement, PermissionAttribute>
{
    protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, PermissionAuthorizationRequirement requirement, IEnumerable<PermissionAttribute> attributes)
    {
        foreach (var permissionAttribute in attributes)
        {
            if (!await AuthorizeAsync(context.User, permissionAttribute.Name))
            {
                return;
            }
        }

        context.Succeed(requirement);
    }

    private Task<bool> AuthorizeAsync(ClaimsPrincipal user, string permission)
    {
        //Implement your custom user permission logic here
    }
}

And finally, in your Startup.cs ConfigureServices method, add your custom AuthorizationHandler to the services, and add your Policy.

        services.AddSingleton<IAuthorizationHandler, PermissionAuthorizationHandler>();

        services.AddAuthorization(options =>
        {
            options.AddPolicy("Permission", policyBuilder =>
            {
                policyBuilder.Requirements.Add(new PermissionAuthorizationRequirement());
            });
        });

Now you can simply decorate your Controllers and Actions with your custom attribute.

[Permission("AccessCustomers")]
public class CustomersController
{
    [Permission("AddCustomer")]
    IActionResult AddCustomer([FromBody] Customer customer)
    {
        //Add customer
    }
}

Spring Security exclude url patterns in security annotation configurartion

specifying the "antMatcher" before "authorizeRequests()" like below will restrict the authenticaiton to only those URLs specified in "antMatcher"

http.csrf().disable() .antMatcher("/apiurlneedsauth/**").authorizeRequests().

syntax for creating a dictionary into another dictionary in python

Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?

Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.

To re-reference the values of one dictionary into another, you can use dict.update:

>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}

A change to a value that's present in both dictionaries will be visible in both:

>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}

This is the same as copying the value over or making a new dictionary with it, i.e.

>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']

Enum Naming Convention - Plural

The situation never really applies to plural.

An enum shows an attribute of something or another. I'll give an example:

enum Humour
{
  Irony,
  Sarcasm,
  Slapstick,
  Nothing
}

You can have one type, but try think of it in the multiple, rather than plural:

Humour.Irony | Humour.Sarcasm

Rather than

Humours { Irony, Sarcasm }

You have a sense of humour, you don't have a sense of humours.

getting the X/Y coordinates of a mouse click on an image with jQuery

note! there is a difference between e.clientX & e.clientY and e.pageX and e.pageY

try them both out and make sure you are using the proper one. clientX and clientY change based on scrolling position

PHP Fatal error: Call to undefined function json_decode()

The same issue with 7.1

apt-get install php7.1-json sudo nano /etc/php/7.1/mods-available/json.ini

  • Add json.so to the new file
  • Add the appropriate sym link under conf.d
  • Restart apache2 service (if needed)

What is simplest way to read a file into String?

Another alternative approach is:

How do I create a Java string from the contents of a file?

Other option is to use utilities provided open source libraries
http://commons.apache.org/io/api-1.4/index.html?org/apache/commons/io/IOUtils.html

Why java doesn't provide such a common util API ?
a) to keep the APIs generic so that encoding, buffering etc is handled by the programmer.
b) make programmers do some work and write/share opensource util libraries :D ;-)

How to generate gcc debug symbol outside the build target?

No answer so far mentions eu-strip --strip-debug -f <out.debug> <input>.

  • This is provided by elfutils package.
  • The result will be that <input> file has been stripped of debug symbols which are now all in <out.debug>.

Regular expression to extract numbers from a string

we can use \b as a word boundary and then; \b\d+\b

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

Try below code,

$cookieFile = "cookies.txt";
if(!file_exists($cookieFile)) {
    $fh = fopen($cookieFile, "w");
    fwrite($fh, "");
    fclose($fh);
}


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $apiCall);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); // Cookie aware
curl_setopt($ch, CURLOPT_VERBOSE, true);
if(!curl_exec($ch)){
    die('Error: "' . curl_error($ch) . '" - Code: ' . curl_errno($ch));
}
else{
    $response = curl_exec($ch); 
}
curl_close($ch);
$result = json_decode($response, true);

echo '<pre>';
var_dump($result);
echo'</pre>';

I hope this will help you.

Best regards, Dasitha.

Rails: Adding an index after adding column

You can run another migration, just for the index:

class AddIndexToTable < ActiveRecord::Migration
  def change
    add_index :table, :user_id
  end
end

convert 12-hour hh:mm AM/PM to 24-hour hh:mm

This will help :

 function getTwentyFourHourTime(amPmString) { 
        var d = new Date("1/1/2013 " + amPmString); 
        return d.getHours() + ':' + d.getMinutes(); 
    }

Example :

getTwentyFourHourTime("8:45 PM"); // "20:45"
getTwentyFourHourTime("8:45 AM"); // "8:45"

Update : Note : There should be a space for timestring between "Time" and "am/pm".

How do I encrypt and decrypt a string in python?

Take a look at PyCrypto. It supports Python 3.2 and does exactly what you want.

From their pip website:

>>> from Crypto.Cipher import AES
>>> obj = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
>>> message = "The answer is no"
>>> ciphertext = obj.encrypt(message)
>>> ciphertext
'\xd6\x83\x8dd!VT\x92\xaa`A\x05\xe0\x9b\x8b\xf1'
>>> obj2 = AES.new('This is a key123', AES.MODE_CFB, 'This is an IV456')
>>> obj2.decrypt(ciphertext)
'The answer is no'

If you want to encrypt a message of an arbitrary size use AES.MODE_CFB instead of AES.MODE_CBC.

How to get form input array into PHP array

They are already in arrays: $name is an array, as is $email

So all you need to do is add a bit of processing to attack both arrays:

$name = $_POST['name'];
$email = $_POST['account'];

foreach( $name as $key => $n ) {
  print "The name is ".$n." and email is ".$email[$key].", thank you\n";
}

To handle more inputs, just extend the pattern:

$name = $_POST['name'];
$email = $_POST['account'];
$location = $_POST['location'];

foreach( $name as $key => $n ) {
  print "The name is ".$n.", email is ".$email[$key].
        ", and location is ".$location[$key].". Thank you\n";
}

URL to load resources from the classpath in Java

Inspire by @Stephen https://stackoverflow.com/a/1769454/980442 and http://docstore.mik.ua/orelly/java/exp/ch09_06.htm

To use

new URL("classpath:org/my/package/resource.extension").openConnection()

just create this class into sun.net.www.protocol.classpath package and run it into Oracle JVM implementation to work like a charm.

package sun.net.www.protocol.classpath;

import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;

public class Handler extends URLStreamHandler {

    @Override
    protected URLConnection openConnection(URL u) throws IOException {
        return Thread.currentThread().getContextClassLoader().getResource(u.getPath()).openConnection();
    }
}

In case you are using another JVM implementation set the java.protocol.handler.pkgs=sun.net.www.protocol system property.

FYI: http://docs.oracle.com/javase/7/docs/api/java/net/URL.html#URL(java.lang.String,%20java.lang.String,%20int,%20java.lang.String)

Hibernate - Batch update returned unexpected row count from update: 0 actual row count: 0 expected: 1

One of the case

SessionFactory sf=new Configuration().configure().buildSessionFactory();
Session session=sf.openSession();

UserDetails user=new UserDetails();

session.beginTransaction();
user.setUserName("update user agian");
user.setUserId(12);
session.saveOrUpdate(user);
session.getTransaction().commit();
System.out.println("user::"+user.getUserName());

sf.close();

How to convert NSData to byte array in iPhone?

The signature of -[NSData bytes] is - (const void *)bytes. You can't assign a pointer to an array on the stack. If you want to copy the buffer managed by the NSData object into the array, use -[NSData getBytes:]. If you want to do it without copying, then don't allocate an array; just declare a pointer variable and let NSData manage the memory for you.

Adding click event for a button created dynamically using jQuery

Question 1: Use .delegate on the div to bind a click handler to the button.

Question 2: Use $(this).val() or this.value (the latter would be faster) inside of the click handler. this will refer to the button.

$("#pg_menu_content").on('click', '#btn_a', function () {
  alert($(this).val());
});

$div = $('<div data-role="fieldcontain"/>');
$("<input type='button' value='Dynamic Button' id='btn_a' />").appendTo($div.clone()).appendTo('#pg_menu_content');

How to download a file using a Java REST service and a data stream

"How can I directly (without saving the file on 2nd server) download the file from 1st server to client's machine?"

Just use the Client API and get the InputStream from the response

Client client = ClientBuilder.newClient();
String url = "...";
final InputStream responseStream = client.target(url).request().get(InputStream.class);

There are two flavors to get the InputStream. You can also use

Response response = client.target(url).request().get();
InputStream is = (InputStream)response.getEntity();

Which one is the more efficient? I'm not sure, but the returned InputStreams are different classes, so you may want to look into that if you care to.

From 2nd server I can get a ByteArrayOutputStream to get the file from 1st server, can I pass this stream further to the client using the REST service?

So most of the answers you'll see in the link provided by @GradyGCooper seem to favor the use of StreamingOutput. An example implementation might be something like

final InputStream responseStream = client.target(url).request().get(InputStream.class);
System.out.println(responseStream.getClass());
StreamingOutput output = new StreamingOutput() {
    @Override
    public void write(OutputStream out) throws IOException, WebApplicationException {  
        int length;
        byte[] buffer = new byte[1024];
        while((length = responseStream.read(buffer)) != -1) {
            out.write(buffer, 0, length);
        }
        out.flush();
        responseStream.close();
    }   
};
return Response.ok(output).header(
        "Content-Disposition", "attachment, filename=\"...\"").build();

But if we look at the source code for StreamingOutputProvider, you'll see in the writeTo, that it simply writes the data from one stream to another. So with our implementation above, we have to write twice.

How can we get only one write? Simple return the InputStream as the Response

final InputStream responseStream = client.target(url).request().get(InputStream.class);
return Response.ok(responseStream).header(
        "Content-Disposition", "attachment, filename=\"...\"").build();

If we look at the source code for InputStreamProvider, it simply delegates to ReadWriter.writeTo(in, out), which simply does what we did above in the StreamingOutput implementation

 public static void writeTo(InputStream in, OutputStream out) throws IOException {
    int read;
    final byte[] data = new byte[BUFFER_SIZE];
    while ((read = in.read(data)) != -1) {
        out.write(data, 0, read);
    }
}

Asides:

  • Client objects are expensive resources. You may want to reuse the same Client for request. You can extract a WebTarget from the client for each request.

    WebTarget target = client.target(url);
    InputStream is = target.request().get(InputStream.class);
    

    I think the WebTarget can even be shared. I can't find anything in the Jersey 2.x documentation (only because it is a larger document, and I'm too lazy to scan through it right now :-), but in the Jersey 1.x documentation, it says the Client and WebResource (which is equivalent to WebTarget in 2.x) can be shared between threads. So I'm guessing Jersey 2.x would be the same. but you may want to confirm for yourself.

  • You don't have to make use of the Client API. A download can be easily achieved with the java.net package APIs. But since you're already using Jersey, it doesn't hurt to use its APIs

  • The above is assuming Jersey 2.x. For Jersey 1.x, a simple Google search should get you a bunch of hits for working with the API (or the documentation I linked to above)


UPDATE

I'm such a dufus. While the OP and I are contemplating ways to turn a ByteArrayOutputStream to an InputStream, I missed the simplest solution, which is simply to write a MessageBodyWriter for the ByteArrayOutputStream

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

@Provider
public class OutputStreamWriter implements MessageBodyWriter<ByteArrayOutputStream> {

    @Override
    public boolean isWriteable(Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return ByteArrayOutputStream.class == type;
    }

    @Override
    public long getSize(ByteArrayOutputStream t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType) {
        return -1;
    }

    @Override
    public void writeTo(ByteArrayOutputStream t, Class<?> type, Type genericType,
            Annotation[] annotations, MediaType mediaType,
            MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
            throws IOException, WebApplicationException {
        t.writeTo(entityStream);
    }
}

Then we can simply return the ByteArrayOutputStream in the response

return Response.ok(baos).build();

D'OH!

UPDATE 2

Here are the tests I used (

Resource class

@Path("test")
public class TestResource {

    final String path = "some_150_mb_file";

    @GET
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response doTest() throws Exception {
        InputStream is = new FileInputStream(path);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        byte[] buffer = new byte[4096];
        while ((len = is.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, len);
        }
        System.out.println("Server size: " + baos.size());
        return Response.ok(baos).build();
    }
}

Client test

public class Main {
    public static void main(String[] args) throws Exception {
        Client client = ClientBuilder.newClient();
        String url = "http://localhost:8080/api/test";
        Response response = client.target(url).request().get();
        String location = "some_location";
        FileOutputStream out = new FileOutputStream(location);
        InputStream is = (InputStream)response.getEntity();
        int len = 0;
        byte[] buffer = new byte[4096];
        while((len = is.read(buffer)) != -1) {
            out.write(buffer, 0, len);
        }
        out.flush();
        out.close();
        is.close();
    }
}

UPDATE 3

So the final solution for this particular use case was for the OP to simply pass the OutputStream from the StreamingOutput's write method. Seems the third-party API, required a OutputStream as an argument.

StreamingOutput output = new StreamingOutput() {
    @Override
    public void write(OutputStream out) {
        thirdPartyApi.downloadFile(.., .., .., out);
    }
}
return Response.ok(output).build();

Not quite sure, but seems the reading/writing within the resource method, using ByteArrayOutputStream`, realized something into memory.

The point of the downloadFile method accepting an OutputStream is so that it can write the result directly to the OutputStream provided. For instance a FileOutputStream, if you wrote it to file, while the download is coming in, it would get directly streamed to the file.

It's not meant for us to keep a reference to the OutputStream, as you were trying to do with the baos, which is where the memory realization comes in.

So with the way that works, we are writing directly to the response stream provided for us. The method write doesn't actually get called until the writeTo method (in the MessageBodyWriter), where the OutputStream is passed to it.

You can get a better picture looking at the MessageBodyWriter I wrote. Basically in the writeTo method, replace the ByteArrayOutputStream with StreamingOutput, then inside the method, call streamingOutput.write(entityStream). You can see the link I provided in the earlier part of the answer, where I link to the StreamingOutputProvider. This is exactly what happens

curl error 18 - transfer closed with outstanding read data remaining

I got this error when my server process got an exception midway during generating the response and simply closed the connection without saying goodbye. curl still expected data from the connection and complained (rightfully).

delete all from table

You can also use truncate.

truncate table table_name;

bootstrap responsive table content wrapping

Add your new class "tableresp" with table-responisve class and then add below code in your js file

$(".tableresp").on('click', '.dropdown-toggle', function(event) {

    if ($('.dropdown-menu').length) {
        var elm = $('.dropdown-menu'),
            docHeight = $(document).height(),
            docWidth = $(document).width(),
            btn_offset = $(this).offset(),
            btn_width = $(this).outerWidth(),
            btn_height = $(this).outerHeight(),
            elm_width = elm.outerWidth(),
            elm_height = elm.outerHeight(),
            table_offset = $(".tableresp").offset(),
            table_width = $(".tableresp").width(),
            table_height = $(".tableresp").height(),

            tableoffright = table_width + table_offset.left,
            tableoffbottom = table_height + table_offset.top,
            rem_tablewidth = docWidth - tableoffright,
            rem_tableheight = docHeight - tableoffbottom,
            elm_offsetleft = btn_offset.left,
            elm_offsetright = btn_offset.left + btn_width,
            elm_offsettop = btn_offset.top + btn_height,
            btn_offsetbottom = elm_offsettop,

            left_edge = (elm_offsetleft - table_offset.left) < elm_width,
            top_edge = btn_offset.top < elm_height,
            right_edge = (table_width - elm_offsetleft) < elm_width,
            bottom_edge = (tableoffbottom - btn_offsetbottom) < elm_height;

        console.log(tableoffbottom);
        console.log(btn_offsetbottom);
        console.log(bottom_edge);
        console.log((tableoffbottom - btn_offsetbottom) + "|| " + elm_height);


        var table_offset_bottom = docHeight - (table_offset.top + table_height);

        var touchTableBottom = (btn_offset.top + btn_height + (elm_height * 2)) - table_offset.top;

        var bottomedge = touchTableBottom > table_offset_bottom;

        if (left_edge) {
            $(this).addClass('left-edge');
        } else {
            $('.dropdown-menu').removeClass('left-edge');
        }
        if (bottom_edge) {
            $(this).parent().addClass('dropup');
        } else {
            $(this).parent().removeClass('dropup');
        }

    }
});
var table_smallheight = $('.tableresp'),
    positioning = table_smallheight.parent();

if (table_smallheight.height() < 320) {
    positioning.addClass('positioning');
    $('.tableresp .dropdown,.tableresp .adropup').css('position', 'static');

} else {
    positioning.removeClass('positioning');
    $('.tableresp .dropdown,.tableresp .dropup').css('position', 'relative');

}

How do I check if an object's type is a particular subclass in C++?

You really shouldn't. If your program needs to know what class an object is, that usually indicates a design flaw. See if you can get the behavior you want using virtual functions. Also, more information about what you are trying to do would help.

I am assuming you have a situation like this:

class Base;
class A : public Base {...};
class B : public Base {...};

void foo(Base *p)
{
  if(/* p is A */) /* do X */
  else /* do Y */
}

If this is what you have, then try to do something like this:

class Base
{
  virtual void bar() = 0;
};

class A : public Base
{
  void bar() {/* do X */}
};

class B : public Base
{
  void bar() {/* do Y */}
};

void foo(Base *p)
{
  p->bar();
}

Edit: Since the debate about this answer still goes on after so many years, I thought I should throw in some references. If you have a pointer or reference to a base class, and your code needs to know the derived class of the object, then it violates Liskov substitution principle. Uncle Bob calls this an "anathema to Object Oriented Design".

How do I put hint in a asp:textbox

The placeholder attribute

You're looking for the placeholder attribute. Use it like any other attribute inside your ASP.net control:

<asp:textbox id="txtWithHint" placeholder="hint" runat="server"/>

Don't bother about your IDE (i.e. Visual Studio) maybe not knowing the attribute. Attributes which are not registered with ASP.net are passed through and rendered as is. So the above code (basically) renders to:

<input type="text" placeholder="hint"/>

Using placeholder in resources

A fine way of applying the hint to the control is using resources. This way you may have localized hints. Let's say you have an index.aspx file, your App_LocalResources/index.aspx.resx file contains

<data name="WithHint.placeholder">
    <value>hint</value>
</data>

and your control looks like

<asp:textbox id="txtWithHint" meta:resourcekey="WithHint" runat="server"/>

the rendered result will look the same as the one in the chapter above.

Add attribute in code behind

Like any other attribute you can add the placeholder to the AttributeCollection:

txtWithHint.Attributes.Add("placeholder", "hint");

How do I install PyCrypto on Windows?

So I install MinGW and tack that on the install line as the compiler of choice. But then I get the error "RuntimeError: chmod error".

This error "RuntimeError: chmod error" occurs because the install script didn't find the chmod command.

How in the world do I get around this?

Solution

You only need to add the MSYS binaries to the PATH and re-run the install script.

(N.B: Note that MinGW comes with MSYS so )

Example

For example, if we are in folder C:\<..>\pycrypto-2.6.1\dist\pycrypto-2.6.1>

C:\.....>set PATH=C:\MinGW\msys\1.0\bin;%PATH%
C:\.....>python setup.py install

Optional: you might need to clean before you re-run the script:

`C:\<..>\pycrypto-2.6.1\dist\pycrypto-2.6.1> python setup.py clean`

Define static method in source-file with declaration in header-file in C++

Keywords static and virtual should not be repeated in the definition. They should only be used in the class declaration.

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

It should be noted that primitive types must have a value. If you used Objects (ie Integer), you could initialize value to null and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

Looping through a Scripting.Dictionary using index/item number

According to the documentation of the Item property:

Sets or returns an item for a specified key in a Dictionary object.

In your case, you don't have an item whose key is 1 so doing:

s = d.Item(i)

actually creates a new key / value pair in your dictionary, and the value is empty because you have not used the optional newItem argument.

The Dictionary also has the Items method which allows looping over the indices:

a = d.Items
For i = 0 To d.Count - 1
    s = a(i)
Next i

Forcing label to flow inline with input that they label

<style>
.nowrap {
    white-space: nowrap;
}
</style>

...

<label for="id1" class="nowrap">label1:
    <input type="text" id="id1"/>
</label>

Wrap your inputs within the label tag

SHA-1 fingerprint of keystore certificate

First there is same .jar file that in fb-sdk android-support-v4.jar.
Then generate SHA1 key using:

PackageInfo info;
try {

    info = getPackageManager().getPackageInfo(
        "com.example.worldmission", PackageManager.GET_SIGNATURES);

    for (Signature signature : info.signatures) {
        MessageDigest md;
        md = MessageDigest.getInstance("SHA");
        md.update(signature.toByteArray());
        String something = new String(Base64.encode(md.digest(), 0));
        Log.e("Hash key", something);
        System.out.println("Hash key" + something);
    }

} catch (NameNotFoundException e1) {
    Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
    Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
    Log.e("exception", e.toString());
}

How can I show data using a modal when clicking a table row (using bootstrap)?

One thing you can do is get rid of all those onclick attributes and do it the right way with bootstrap. You don't need to open them manually; you can specify the trigger and even subscribe to events before the modal opens so that you can do your operations and populate data in it.

I am just going to show as a static example which you can accommodate in your real world.

On each of your <tr>'s add a data attribute for id (i.e. data-id) with the corresponding id value and specify a data-target, which is a selector you specify, so that when clicked, bootstrap will select that element as modal dialog and show it. And then you need to add another attribute data-toggle=modal to make this a trigger for modal.

  <tr data-toggle="modal" data-id="1" data-target="#orderModal">
            <td>1</td>
            <td>24234234</td>
            <td>A</td>
  </tr>
  <tr data-toggle="modal" data-id="2" data-target="#orderModal">
            <td>2</td>
            <td>24234234</td>
            <td>A</td>
        </tr>
  <tr data-toggle="modal" data-id="3" data-target="#orderModal">
            <td>3</td>
            <td>24234234</td>
            <td>A</td>
  </tr>

And now in the javascript just set up the modal just once and event listen to its events so you can do your work.

$(function(){
    $('#orderModal').modal({
        keyboard: true,
        backdrop: "static",
        show:false,

    }).on('show', function(){ //subscribe to show method
          var getIdFromRow = $(event.target).closest('tr').data('id'); //get the id from tr
        //make your ajax call populate items or what even you need
        $(this).find('#orderDetails').html($('<b> Order Id selected: ' + getIdFromRow  + '</b>'))
    });
});

Demo

Do not use inline click attributes any more. Use event bindings instead with vanilla js or using jquery.

Alternative ways here:

Demo2 or Demo3

What is the default boolean value in C#?

Basically local variables aren't automatically initialized. Hence using them without initializing would result in an exception.

Only the following variables are automatically initialized to their default values:

  • Static variables
  • Instance variables of class and struct instances
  • Array elements

The default values are as follows (assigned in default constructor of a class):

  • The default value of a variable of reference type is null.
  • For integer types, the default value is 0
  • For char, the default value is `\u0000'
  • For float, the default value is 0.0f
  • For double, the default value is 0.0d
  • For decimal, the default value is 0.0m
  • For bool, the default value is false
  • For an enum type, the default value is 0
  • For a struct type, the default value is obtained by setting all value type fields to their default values

As far as later parts of your question are conerned:

  • The reason why all variables which are not automatically initialized to default values should be initialized is a restriction imposed by compiler.
  • private bool foo = false; This is indeed redundant since this is an instance variable of a class. Hence this would be initialized to false in the default constructor. Hence no need to set this to false yourself.

Error inflating when extending a class

@Tim - Both the constructors are not required, only the ViewClassName(Context context, AttributeSet attrs ) constructor is necessary. I found this out the painful way, after hours and hours of wasted time.

I am very new to Android development, but I am making a wild guess here, that it maybe due to the fact that since we are adding the custom View class in the XML file, we are setting several attributes to it in the XML, which needs to be processed at the time of instantiation. Someone far more knowledgeable than me will be able to shed clearer light on this matter though.

Paritition array into N chunks with Numpy

Just some examples on usage of array_split, split, hsplit and vsplit:

n [9]: a = np.random.randint(0,10,[4,4])

In [10]: a
Out[10]: 
array([[2, 2, 7, 1],
       [5, 0, 3, 1],
       [2, 9, 8, 8],
       [5, 7, 7, 6]])

Some examples on using array_split:
If you give an array or list as second argument you basically give the indices (before) which to 'cut'

# split rows into 0|1 2|3
In [4]: np.array_split(a, [1,3])
Out[4]:                                                                                                                       
[array([[2, 2, 7, 1]]),                                                                                                       
 array([[5, 0, 3, 1],                                                                                                         
       [2, 9, 8, 8]]),                                                                                                        
 array([[5, 7, 7, 6]])]

# split columns into 0| 1 2 3
In [5]: np.array_split(a, [1], axis=1)                                                                                           
Out[5]:                                                                                                                       
[array([[2],                                                                                                                  
       [5],                                                                                                                   
       [2],                                                                                                                   
       [5]]),                                                                                                                 
 array([[2, 7, 1],                                                                                                            
       [0, 3, 1],
       [9, 8, 8],
       [7, 7, 6]])]

An integer as second arg. specifies the number of equal chunks:

In [6]: np.array_split(a, 2, axis=1)
Out[6]: 
[array([[2, 2],
       [5, 0],
       [2, 9],
       [5, 7]]),
 array([[7, 1],
       [3, 1],
       [8, 8],
       [7, 6]])]

split works the same but raises an exception if an equal split is not possible

In addition to array_split you can use shortcuts vsplit and hsplit.
vsplit and hsplit are pretty much self-explanatry:

In [11]: np.vsplit(a, 2)
Out[11]: 
[array([[2, 2, 7, 1],
       [5, 0, 3, 1]]),
 array([[2, 9, 8, 8],
       [5, 7, 7, 6]])]

In [12]: np.hsplit(a, 2)
Out[12]: 
[array([[2, 2],
       [5, 0],
       [2, 9],
       [5, 7]]),
 array([[7, 1],
       [3, 1],
       [8, 8],
       [7, 6]])]

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

That div.cell solution didn't actually work on my IPython, however luckily someone suggested a working solution for new IPythons:

Create a file ~/.ipython/profile_default/static/custom/custom.css (iPython) or ~/.jupyter/custom/custom.css (Jupyter) with content

.container { width:100% !important; }

Then restart iPython/Jupyter notebooks. Note that this will affect all notebooks.

How can I view array structure in JavaScript with alert()?

EDIT: Firefox and Google Chrome now have a built-in JSON object, so you can just say alert(JSON.stringify(myArray)) without needing to use a jQuery plugin. This is not part of the Javascript language spec, so you shouldn't rely on the JSON object being present in all browsers, but for debugging purposes it's incredibly useful.

I tend to use the jQuery-json plugin as follows:

alert( $.toJSON(myArray) );

This prints the array in a format like

[5, 6, 7, 11]

However, for debugging your Javascript code, I highly recommend Firebug It actually comes with a Javascript console, so you can type out Javascript code for any page and see the results. Things like arrays are already printed in the human-readable form used above.

Firebug also has a debugger, as well as screens for helping you view and debug your HTML and CSS.

Accessing MP3 metadata with Python

What you're after is the ID3 module. It's very simple and will give you exactly what you need. Just copy the ID3.py file into your site-packages directory and you'll be able to do something like the following:

from ID3 import *
try:
  id3info = ID3('file.mp3')
  print id3info
  # Change the tags
  id3info['TITLE'] = "Green Eggs and Ham"
  id3info['ARTIST'] = "Dr. Seuss"
  for k, v in id3info.items():
    print k, ":", v
except InvalidTagError, message:
  print "Invalid ID3 tag:", message

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

You can get rid of the first line. You don't need import java.lang.*;

Just change your 5th line to:

public static void main(String [] args) throws Exception

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

On many devices (such as the iPhone), it prevents the user from using the browser's zoom. If you have a map and the browser does the zooming, then the user will see a big ol' pixelated image with huge pixelated labels. The idea is that the user should use the zooming provided by Google Maps. Not sure about any interaction with your plugin, but that's what it's there for.

More recently, as @ehfeng notes in his answer, Chrome for Android (and perhaps others) have taken advantage of the fact that there's no native browser zooming on pages with a viewport tag set like that. This allows them to get rid of the dreaded 300ms delay on touch events that the browser takes to wait and see if your single touch will end up being a double touch. (Think "single click" and "double click".) However, when this question was originally asked (in 2011), this wasn't true in any mobile browser. It's just added awesomeness that fortuitously arose more recently.

Java Date - Insert into database

You should be using java.sql.Timestamp instead of java.util.Date. Also using a PreparedStatement will save you worrying about the formatting.

"Failed to install the following Android SDK packages as some licences have not been accepted" error

use android-28 with build-tools at version 28.0.3; or build-tools at version 26.0.3.

or try this: yes | sudo sdkmanager --licenses

Pass variable to function in jquery AJAX success callback

I'm doing it this way:

    function f(data,d){
    console.log(d);
    console.log(data);
}
$.ajax({
    url:u,
    success:function(data){ f(data,d);  }
});

How to import csv file in PHP?

If you use composer, you can try CsvFileLoader

How can I declare a global variable in Angular 2 / Typescript?

I don't know the best way, but the easiest way if you want to define a global variable inside of a component is to use window variable to write like this:

window.GlobalVariable = "what ever!"

you don't need to pass it to bootstrap or import it other places, and it is globally accessibly to all JS (not only angular 2 components).

How do you add CSS with Javascript?

YUI just recently added a utility specifically for this. See stylesheet.js here.

How to map a composite key with JPA and Hibernate?

Assuming you have the following database tables:

Database tables

First, you need to create the @Embeddable holding the composite identifier:

@Embeddable
public class EmployeeId implements Serializable {
 
    @Column(name = "company_id")
    private Long companyId;
 
    @Column(name = "employee_number")
    private Long employeeNumber;
 
    public EmployeeId() {
    }
 
    public EmployeeId(Long companyId, Long employeeId) {
        this.companyId = companyId;
        this.employeeNumber = employeeId;
    }
 
    public Long getCompanyId() {
        return companyId;
    }
 
    public Long getEmployeeNumber() {
        return employeeNumber;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof EmployeeId)) return false;
        EmployeeId that = (EmployeeId) o;
        return Objects.equals(getCompanyId(), that.getCompanyId()) &&
                Objects.equals(getEmployeeNumber(), that.getEmployeeNumber());
    }
 
    @Override
    public int hashCode() {
        return Objects.hash(getCompanyId(), getEmployeeNumber());
    }
}

With this in place, we can map the Employee entity which uses the composite identifier by annotating it with @EmbeddedId:

@Entity(name = "Employee")
@Table(name = "employee")
public class Employee {
 
    @EmbeddedId
    private EmployeeId id;
 
    private String name;
 
    public EmployeeId getId() {
        return id;
    }
 
    public void setId(EmployeeId id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}

The Phone entity which has a @ManyToOne association to Employee, needs to reference the composite identifier from the parent class via two @JoinColumnmappings:

@Entity(name = "Phone")
@Table(name = "phone")
public class Phone {
 
    @Id
    @Column(name = "`number`")
    private String number;
 
    @ManyToOne
    @JoinColumns({
        @JoinColumn(
            name = "company_id",
            referencedColumnName = "company_id"),
        @JoinColumn(
            name = "employee_number",
            referencedColumnName = "employee_number")
    })
    private Employee employee;
 
    public Employee getEmployee() {
        return employee;
    }
 
    public void setEmployee(Employee employee) {
        this.employee = employee;
    }
 
    public String getNumber() {
        return number;
    }
 
    public void setNumber(String number) {
        this.number = number;
    }
}

Sass - Converting Hex to RGBa for background opacity

SASS has a built-in rgba() function to evaluate values.

rgba($color, $alpha)

E.g.

rgba(#00aaff, 0.5) => rgba(0, 170, 255, 0.5)

An example using your own variables:

$my-color: #00aaff;
$my-opacity: 0.5;

.my-element {
  color: rgba($my-color, $my-opacity);
}

Outputs:

.my-element {
  color: rgba(0, 170, 255, 0.5);
}

Install IPA with iTunes 12

From iTunes 12.7 apple removes App Store, So we unable to for find App option

We have another way to install iOS app using iTunes 12.7 as below

1)drag and drop your .app file to iTunes.

2)It will create .ipa file, you can find that at ~/Music/iTunes/iTunes Media/Mobile Applications/

3)connect the device you want to install that app.

4)drag .ipa file from finder to iTunes on my Device section as shown in below section. enter image description here

Empty or Null value display in SSRS text boxes

I couldn't get IsNothing() to behave and I didn't want to create dummy rows in my dataset (e.g. for a given list of customers create a dummy order per month displayed) and noticed that null values were displaying as -247192.

Lo and behold using that worked to suppress it (at least until MSFT changes SSRS for the better from 08R2) so forgive me but:

=iif(Fields!Sales_Diff.Value = -247192,"",Fields!Sales_Diff.Value)

Call a REST API in PHP

as @Christoph Winkler mentioned this is a base class for achieving it:

curl_helper.php

// This class has all the necessary code for making API calls thru curl library

class CurlHelper {

// This method will perform an action/method thru HTTP/API calls
// Parameter description:
// Method= POST, PUT, GET etc
// Data= array("param" => "value") ==> index.php?param=value
public static function perform_http_request($method, $url, $data = false)
{
    $curl = curl_init();

    switch ($method)
    {
        case "POST":
            curl_setopt($curl, CURLOPT_POST, 1);

            if ($data)
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            break;
        case "PUT":
            curl_setopt($curl, CURLOPT_PUT, 1);
            break;
        default:
            if ($data)
                $url = sprintf("%s?%s", $url, http_build_query($data));
    }

    // Optional Authentication:
    //curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
    //curl_setopt($curl, CURLOPT_USERPWD, "username:password");

    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $result = curl_exec($curl);

    curl_close($curl);

    return $result;
}

}

Then you can always include the file and use it e.g.: any.php

    require_once("curl_helper.php");
    ...
    $action = "GET";
    $url = "api.server.com/model"
    echo "Trying to reach ...";
    echo $url;
    $parameters = array("param" => "value");
    $result = CurlHelper::perform_http_request($action, $url, $parameters);
    echo print_r($result)

WooCommerce: Finding the products in database

Bulk add new categories to Woo:

Insert category id, name, url key

INSERT INTO wp_terms 
VALUES
  (57, 'Apples', 'fruit-apples', '0'),
  (58, 'Bananas', 'fruit-bananas', '0');

Set the term values as catergories

INSERT INTO wp_term_taxonomy 
VALUES
  (57, 57, 'product_cat', '', 17, 0),
  (58, 58, 'product_cat', '', 17, 0)

17 - is parent category, if there is one

key here is to make sure the wp_term_taxonomy table term_taxonomy_id, term_id are equal to wp_term table's term_id

After doing the steps above go to wordpress admin and save any existing category. This will update the DB to include your bulk added categories

Package opencv was not found in the pkg-config search path

I installed opencv following the steps on https://docs.opencv.org/trunk/d7/d9f/tutorial_linux_install.html

Except on Step 2, use: cmake -D CMAKE_BUILD_TYPE=Release -D OPENCV_GENERATE_PKGCONFIG=YES -D CMAKE_INSTALL_PREFIX=/path/to/opencv/ ..

Then locate the opencv4.pc file, mine was in opencv/build/unix-install/

Now run: $ export PKG_CONFIG_PATH=/path/to/the/file

working with negative numbers in python

How about something like that? (Uses no abs() nor mulitiplication)
Notes:

  • the abs() function is only used for the optimization trick. This snippet can either be removed or recoded.
  • the logic is less efficient since we're testing the sign of a and b with each iteration (price to pay to avoid both abs() and multiplication operator)

def multiply_by_addition(a, b):
""" School exercise: multiplies integers a and b, by successive additions.
"""
   if abs(a) > abs(b):
      a, b = b, a     # optimize by reducing number of iterations
   total = 0
   while a != 0:
      if a > 0:
         a -= 1
         total += b
      else:
         a += 1
         total -= b
   return total

multiply_by_addition(2,3)
6
multiply_by_addition(4,3)
12
multiply_by_addition(-4,3)
-12
multiply_by_addition(4,-3)
-12
multiply_by_addition(-4,-3)
12

Truncate a SQLite table if it exists?

Unfortunately, we do not have a "TRUNCATE TABLE" command in SQLite, but you can use SQLite's DELETE command to delete the complete data from an existing table, though it is recommended to use the DROP TABLE command to drop the complete table and re-create it once again.

PHP - Debugging Curl

You can enable the CURLOPT_VERBOSE option and log that information to a (temporary) CURLOPT_STDERR:

// CURLOPT_VERBOSE: TRUE to output verbose information. Writes output to STDERR, 
// or the file specified using CURLOPT_STDERR.
curl_setopt($handle, CURLOPT_VERBOSE, true);

$verbose = fopen('php://temp', 'w+');
curl_setopt($handle, CURLOPT_STDERR, $verbose);

You can then read it after curl has done the request:

$result = curl_exec($handle);
if ($result === FALSE) {
    printf("cUrl error (#%d): %s<br>\n", curl_errno($handle),
           htmlspecialchars(curl_error($handle)));
}

rewind($verbose);
$verboseLog = stream_get_contents($verbose);

echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";

(I originally answered similar but more extended in a related question.)

More information like metrics about the last request is available via curl_getinfo. This information can be useful for debugging curl requests, too. A usage example, I would normally wrap that into a function:

$version = curl_version();
extract(curl_getinfo($handle));
$metrics = <<<EOD
URL....: $url
Code...: $http_code ($redirect_count redirect(s) in $redirect_time secs)
Content: $content_type Size: $download_content_length (Own: $size_download) Filetime: $filetime
Time...: $total_time Start @ $starttransfer_time (DNS: $namelookup_time Connect: $connect_time Request: $pretransfer_time)
Speed..: Down: $speed_download (avg.) Up: $speed_upload (avg.)
Curl...: v{$version['version']}
EOD;

Angular 4 setting selected option in Dropdown

To preselect an option when the form is initialized, the value of the select element must be set to an element attribute of the array you are iterating over and setting the value of option to. Which is the key attribute in this case.

From your example.

<select [id]="question.key" [formControlName]="question.key">
  <option *ngFor="let opt of question.options" [value]="opt.key"</option>
</select>

You are iterating over 'options' to create the select options. So the value of select must be set to the key attribute of an item in options(the one you want to display on initialization). This will display the default of select as the option whose value matches the value you set for select.

You can achieve this by setting the value of the select element in the onInit method like so.

ngOnInit(): void{
    myForm : new FormGroup({
       ...
       question.key : new FormControl(null)
    })
    // Get desired initial value to display on <select>
    desiredValue = question.options.find(opt => opt === initialValue)
    this.myForm.get(question.key).setValue(desiredValue.key)
}

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

How to debug heap corruption errors?

I have also faced this issue. In my case, I allocated for x size memory and appended the data for x+n size. So, when freeing it shown heap overflow. Just make sure your allocated memory sufficient and check for how many bytes added in the memory.

using favicon with css

There is no explicit way to change the favicon globally using CSS that I know of. But you can use a simple trick to change it on the fly.

First just name, or rename, the favicon to "favicon.ico" or something similar that will be easy to remember, or is relevant for the site you're working on. Then add the link to the favicon in the head as you usually would. Then when you drop in a new favicon just make sure it's in the same directory as the old one, and that it has the same name, and there you go!

It's not a very elegant solution, and it requires some effort. But dropping in a new favicon in one place is far easier than doing a find and replace of all the links, or worse, changing them manually. At least this way doesn't involve messing with the code.

Of course dropping in a new favicon with the same name will delete the old one, so make sure to backup the old favicon in case of disaster, or if you ever want to go back to the old design.

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

Powder's comment may go undetected like I missed it so many times,. So with the hope of making it more visible, I will re-iterate his point.

Sometimes using image = array(img).reshape(a,b,c,d) will reshape alright but from experience, my kernel crashes every time I try to use the new dimension in an operation. The safest to use is

np.expand_dims(img, axis=0)

It works perfect every time. I just can't explain why. This link has a great explanation and examples regarding its usage.

How can I get city name from a latitude and longitude point?

Here is a complete sample:

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation API with Google Maps API</title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <script>
      function displayLocation(latitude,longitude){
        var request = new XMLHttpRequest();

        var method = 'GET';
        var url = 'http://maps.googleapis.com/maps/api/geocode/json?latlng='+latitude+','+longitude+'&sensor=true';
        var async = true;

        request.open(method, url, async);
        request.onreadystatechange = function(){
          if(request.readyState == 4 && request.status == 200){
            var data = JSON.parse(request.responseText);
            var address = data.results[0];
            document.write(address.formatted_address);
          }
        };
        request.send();
      };

      var successCallback = function(position){
        var x = position.coords.latitude;
        var y = position.coords.longitude;
        displayLocation(x,y);
      };

      var errorCallback = function(error){
        var errorMessage = 'Unknown error';
        switch(error.code) {
          case 1:
            errorMessage = 'Permission denied';
            break;
          case 2:
            errorMessage = 'Position unavailable';
            break;
          case 3:
            errorMessage = 'Timeout';
            break;
        }
        document.write(errorMessage);
      };

      var options = {
        enableHighAccuracy: true,
        timeout: 1000,
        maximumAge: 0
      };

      navigator.geolocation.getCurrentPosition(successCallback,errorCallback,options);
    </script>
  </body>
</html>

delete a column with awk or sed

Try using cut... its fast and easy

First you have repeated spaces, you can squeeze those down to a single space between columns if thats what you want with tr -s ' '

If each column already has just one delimiter between it, you can use cut -d ' ' -f-2 to print fields (columns) <= 2.

for example if your data is in a file input.txt you can do one of the following:

cat input.txt | tr -s ' ' | cut -d ' ' -f-2

Or if you better reason about this problem by removing the 3rd column you can write the following

cat input.txt | tr -s ' ' | cut -d ' ' --complement -f3

cut is pretty powerful, you can also extract ranges of bytes, or characters, in addition to columns

excerpt from the man page on the syntax of how to specify the list range

Each LIST is made up of one range, or many ranges separated by commas.
Selected input is written in the same order that it is read, and is
written exactly once. Each range is one of:

  N     N'th byte, character or field, counted from 1
  N-    from N'th byte, character or field, to end of line
  N-M   from N'th to M'th (included) byte, character or field
  -M    from first to M'th (included) byte, character or field

so you also could have said you want specific columns 1 and 2 with...

cat input.txt | tr -s ' ' | cut -d ' ' -f1,2

how to check for datatype in node js- specifically for integer

If you want to know if "1" ou 1 can be casted to a number, you can use this code :

if (isNaN(i*1)) {
     console.log('i is not a number'); 
}

Squash the first two commits in Git?

You could use rebase interactive to modify the last two commits before they've been pushed to a remote

git rebase HEAD^^ -i

How to get Client location using Google Maps API v3?

Try this :)

    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
    function initialize() {
        var loc = {};
        var geocoder = new google.maps.Geocoder();
        if(google.loader.ClientLocation) {
            loc.lat = google.loader.ClientLocation.latitude;
            loc.lng = google.loader.ClientLocation.longitude;

            var latlng = new google.maps.LatLng(loc.lat, loc.lng);
            geocoder.geocode({'latLng': latlng}, function(results, status) {
                if(status == google.maps.GeocoderStatus.OK) {
                    alert(results[0]['formatted_address']);
                };
            });
        }
    }

    google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});

    </script>

How to get a matplotlib Axes instance to plot to?

Use the gca ("get current axes") helper function:

ax = plt.gca()

Example:

import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

enter image description here

How do the post increment (i++) and pre increment (++i) operators work in Java?

pre-increment and post increment are equivalent if not in an expression

int j =0;
int r=0         
for(int v = 0; v<10; ++v) { 
          ++r;
          j++;
          System.out.println(j+" "+r);
  }  
 1 1  
 2 2  
 3 3       
 4 4
 5 5
 6 6
 7 7
 8 8
 9 9
10 10

How to extract a single value from JSON response?

Extract single value from JSON response Python

Try this

import json
import sys

#load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}

#dumps the json object into an element
json_str = json.dumps(data)

#load the json to a string
resp = json.loads(json_str)

#print the resp
print (resp)

#extract an element in the response
print (resp['test1'])

Rename computer and join to domain in one step with PowerShell

I was looking for the same thing today and finally got a way to do it. I was hinted that it was possible due to the use of sconfig, which ask you if you want to change the computer name after joining it to a domain. Here is my raw code line. It might be enhanced but to tired to think about it for now.

$strCompName = Read-host 'Name '
$strAdmin = read-host "Authorized user for this operation "
$strDomain = read-host "Name of the domain to be joined "
add-computer -DomainName $strDomain -Credential $strAdmin
Rename-computer -newname $strCompName -DomainCredential $strAdmin

character count using jquery

For length including white-space:

$("#id").val().length

For length without white-space:

$("#id").val().replace(/ /g,'').length

For removing only beginning and trailing white-space:

$.trim($("#test").val()).length

For example, the string " t e s t " would evaluate as:

//" t e s t "
$("#id").val(); 

//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7

Here is a demo using all of them.

Where is database .bak file saved from SQL Server Management Studio?

Set registry item for your server instance. For example:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.2\MSSQLServer\BackupDirectory

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

It's also easy to use Alien as a libc/msvcrt wrapper:

> luarocks install alien

Then from lua:

require 'alien'

if alien.platform == "windows" then
    -- untested!!
    libc = alien.load("msvcrt.dll")
else
    libc = alien.default
end 

usleep = libc.usleep
usleep:types('int', 'uint')

function sleep(ms)
    while ms > 1000 do
        usleep(1000)
        ms = ms - 1000
    end
    usleep(1000 * ms)
end

print('hello')
sleep(500)  -- sleep 500 ms
print('world')

Caveat lector: I haven't tried this on MSWindows; I don't even know if msvcrt has a usleep()

how to implement a long click listener on a listview

this should work

ListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                           int pos, long id) {
                // TODO Auto-generated method stub

                Toast.makeText(getContext(), "long clicked, "+"pos: " + pos, Toast.LENGTH_LONG).show();

                return true;
            }
        });

also don't forget to in your xml android:longClickable="true" or if you have a custom view add this to your custom view class youCustomView.setLongClickable(true);

here is the output of the code above enter image description here

Error after upgrading pip: cannot import name 'main'

I have the same problem and solved it. Here is my solution. First, when I run pip install something, the error came out like this:

Traceback (most recent call last):
  File "/usr/bin/pip3", line 9, in <module>
    from pip import main
ImportError: cannot import name 'main'

So, I cd into the file /usr/bin/ and cat pip3 to see the code in it. I see this in it:

#!/usr/bin/python3
# GENERATED BY DEBIAN
import sys
# Run the main entry point, similarly to how setuptools does it, but because
# we didn't install the actual entry point from setup.py, don't use the
# pkg_resources API.
from pip import main
if __name__ == '__main__':
    sys.exit(main())

And then I think that it was not in the installation path. So I cd into the python3-pip, like this:

cd /.local/lib/python3.5/site-packages/pip

P.S.: you have to cd into the right directions in your computer Then I cat the file to see the differences(you can use other operations to see the code):

cat __main__.py

And I saw this:

from __future__ import absolute_import
import os
import sys
# If we are running from a wheel, add the wheel to sys.path
# This allows the usage python pip-*.whl/pip install pip-*.whl
if __package__ == '':
    # __file__ is pip-*.whl/pip/__main__.py
    # first dirname call strips of '/__main__.py', second strips off '/pip'
    # Resulting path is the name of the wheel itself
    # Add that to sys.path so we can import pip
    path = os.path.dirname(os.path.dirname(__file__))
    sys.path.insert(0, path)

from pip._internal import main as _main  # isort:skip # noqa

if __name__ == '__main__':
    sys.exit(_main())

So, can you see the difference? I can figure out that I have to make the file the same as the file in /usr/bin/pip3

So, I copied the code in /.local/lib/python3.5/site-packages/pip to replace the code in /usr/bin/pip3 and the problem disappear!

P.S.: pip3 or pip have no difference in this problem. I will be happy if my solution solve your problem!

Load text file as strings using numpy.loadtxt()

Is it essential that you need a NumPy array? Otherwise you could speed things up by loading the data as a nested list.

def load(fname):
    ''' Load the file using std open'''
    f = open(fname,'r')

    data = []
    for line in f.readlines():
        data.append(line.replace('\n','').split(' '))

    f.close()

    return data

For a text file with 4000x4000 words this is about 10 times faster than loadtxt.

Swift: Sort array of objects alphabetically

*import Foundation
import CoreData


extension Messages {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Messages> {
        return NSFetchRequest<Messages>(entityName: "Messages")
    }

    @NSManaged public var text: String?
    @NSManaged public var date: Date?
    @NSManaged public var friends: Friends?

}

    //here arrMessage is the array you can sort this array as under bellow 

    var arrMessages = [Messages]()

    arrMessages.sort { (arrMessages1, arrMessages2) -> Bool in
               arrMessages1.date! > arrMessages2.date!
    }*

Get element type with jQuery

Use Nodename over tagName :

nodeName contains all functionalities of tagName, plus a few more. Therefore nodeName is always the better choice.

see DOM Core

How to make a form close when pressing the escape key?

Button cancelBTN = new Button();
cancelBTN.Size = new Size(0, 0);
cancelBTN.TabStop = false;
this.Controls.Add(cancelBTN);
this.CancelButton = cancelBTN;

How to jump back to NERDTree from file in tab?

Ctrl+ww cycle though all windows

Ctrl+wh takes you left a window

Ctrl+wj takes you down a window

Ctrl+wk takes you up a window

Ctrl+wl takes you right a window

String concatenation in Ruby

Since this is a path I'd probably use array and join:

source = [ROOT_DIR, project, 'App.config'] * '/'

Easy way to add drop down menu with 1 - 100 without doing 100 different options?

Not with plain HTML I'm afraid.

You could use some jQuery to do this though:

$(function(){
    var $select = $(".1-100");
    for (i=1;i<=100;i++){
        $select.append($('<option></option>').val(i).html(i))
    }
});?

-- SEE DEMO --

You can download jQuery here

Obtain smallest value from array in Javascript?

Here is a recursive way on how to do it using ternary operators both for the recursion and decision whether you came across a min number or not.

const findMin = (arr, min, i) => arr.length === i ? min :
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)

Code snippet:

_x000D_
_x000D_
const findMin = (arr, min, i) => arr.length === i ? min :_x000D_
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)_x000D_
  _x000D_
const arr = [5, 34, 2, 1, 6, 7, 9, 3];_x000D_
const min = findMin(arr, arr[0], 0)_x000D_
console.log(min);
_x000D_
_x000D_
_x000D_

Remove xticks in a matplotlib plot?

# remove all the ticks (both axes), and tick labels on the Y axis
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')

Are there any log file about Windows Services Status?

Under Windows 7, open the Event Viewer. You can do this the way Gishu suggested for XP, typing eventvwr from the command line, or by opening the Control Panel, selecting System and Security, then Administrative Tools and finally Event Viewer. It may require UAC approval or an admin password.

In the left pane, expand Windows Logs and then System. You can filter the logs with Filter Current Log... from the Actions pane on the right and selecting "Service Control Manager." Or, depending on why you want this information, you might just need to look through the Error entries.

enter image description here

The actual log entry pane (not shown) is pretty user-friendly and self-explanatory. You'll be looking for messages like the following:

"The Praxco Assistant service entered the stopped state."
"The Windows Image Acquisition (WIA) service entered the running state."
"The MySQL service terminated unexpectedly. It has done this 3 time(s)."

Python IndentationError unindent does not match any outer indentation level

You have mixed indentation formatting (spaces and tabs)

On Notepad++

Change Tab Settings to 4 spaces

Go to Settings -> Preferences -> Tab Settings -> Replace by spaces

Fix the current file mixed indentations

Select everything CTRL+A

Click TAB once, to add an indentation everywhere

Run SHIFT + TAB to remove the extra indentation, it will replace all TAB characters to 4 spaces.

Web.Config Debug/Release

If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

<connectionStrings xdt:Transform="Replace">
    <!-- production environment config --->
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>
....

Information for this answer are brought from this answer and this blog post.

notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).

How can I make a checkbox readonly? not disabled?

Make a fake checkbox with no name and value, force the value in an hidden field:

<input type="checkbox" disabled="disabled" checked="checked">
<input type="hidden" name="name" value="true">

Note: if you put name and value in the checkbox, it will be anyway overwritten by the input with the same name

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

I use this simple function, which returns true or false, to test for localStorage availablity:

isLocalStorageNameSupported = function() {
    var testKey = 'test', storage = window.sessionStorage;
    try {
        storage.setItem(testKey, '1');
        storage.removeItem(testKey);
        return true;
    } catch (error) {
        return false;
    }
}

Now you can test for localStorage.setItem() availability before using it. Example:

if ( isLocalStorageNameSupported() ) {
    // can use localStorage.setItem('item','value')
} else {
    // can't use localStorage.setItem('item','value')
}

Where to place and how to read configuration resource files in servlet based application?

Ex: In web.xml file the tag

<context-param>
        <param-name>chatpropertyfile</param-name>
        <!--  Name of the chat properties file. It contains the name and description                   of rooms.-->     
        <param-value>chat.properties</param-value>
    </context-param>

And chat.properties you can declare your properties like this

For Ex :

Jsp = Discussion about JSP can be made here.
Java = Talk about java and related technologies like J2EE.
ASP = Discuss about Active Server Pages related technologies like VBScript and JScript etc.
Web_Designing = Any discussion related to HTML, JavaScript, DHTML etc.
StartUp = Startup chat room. Chatter is added to this after he logs in.

How to create jar file with package structure?

Simply more than above -

  1. Keep your Java packaging contents inside a directory and make sure there is nothing inside except your Java packages and their corresponding Java classes.

  2. Open Command(If Windows) Prompt, reach to the containing directory path like below -

    C:> cd "C:\Users\UserABC\Downloads\Current Folder"

    C:\Users\UserABC\Downloads\Current Folder>jar cvf hello-world-1.0.1.jar .

CSS scale down image to fit in containing div, without specifing original size

This is an old question I know, but this is in the top five for several related Google searches. Here's the CSS-only solution without changing the images to background images:

width: auto;
height: auto;
max-width: MaxSize;
max-height: MaxSize;

"MaxSize" is a placeholder for whatever max-width and max-height you want to use, in pixels or percentage. auto will increase (or decrease) the width and height to occupy the space you specify with MaxSize. It will override any defaults for images you or the viewer's browser might have for images. I've found it's especially important on Android's Firefox. Pixels or percentages work for max size. With both the height and width set to auto, the aspect ratio of the original image will be retained.

If you want to fill the space entirely and don't mind the image being larger than its original size, change the two max-widths to min-width: 100% - this will make them completely occupy their space and maintain aspect ratio. You can see an example of this with a Twitter profile's background image.

Create Setup/MSI installer in Visual Studio 2017

Other answers posted here for this question did not work for me using the latest Visual Studio 2017 Enterprise edition (as of 2018-09-18).

Instead, I used this method:

  1. Close all but one instance of Visual Studio.
  2. In the running instance, access the menu Tools->Extensions and Updates.
  3. In that dialog, choose Online->Visual Studio Marketplace->Tools->Setup & Deployment.
  4. From the list that appears, select Microsoft Visual Studio 2017 Installer Projects.

Once installed, close and restart Visual Studio. Go to File->New Project and search for the word Installer. You'll know you have the correct templates installed if you see a list that looks something like this:

enter image description here

How do you divide each element in a list by an int?

The abstract version can be:

import numpy as np
myList = [10, 20, 30, 40, 50, 60, 70, 80, 90]
myInt = 10
newList  = np.divide(myList, myInt)

JavaScript: IIF like statement

Something like this:

for (/* stuff */)
{
    var x = '<option value="' + col + '" '
        + (col === 'screwdriver' ? 'selected' : '')
        + '>Very roomy</option>';
    // snip...
}

how to check the version of jar file?

Decompress the JAR file and look for the manifest file (META-INF\MANIFEST.MF). The manifest file of JAR file might contain a version number (but not always a version is specified).

How do I remove a comma off the end of a string?

rtrim ($string , ","); is the easiest way.

How do I add one month to current date in Java?

public class StringSplit {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        date(5, 3);
        date(5, 4);
    }

    public static String date(int month, int week) {
        LocalDate futureDate = LocalDate.now().plusMonths(month).plusWeeks(week);
        String Fudate = futureDate.toString();
        String[] arr = Fudate.split("-", 3);
        String a1 = arr[0];
        String a2 = arr[1];
        String a3 = arr[2];
        String date = a3 + "/" + a2 + "/" + a1;
        System.out.println(date);
        return date;
    }
}

Output:

10/03/2020
17/03/2020

How to select id with max date group by category in PostgreSQL?

This is a perfect use-case for DISTINCT ON - a Postgres specific extension of the standard DISTINCT:

SELECT DISTINCT ON (category)
       id  -- , category, date  -- any other column (expression) from the same row
FROM   tbl
ORDER  BY category, date DESC;

Careful with descending sort order. If the column can be NULL, you may want to add NULLS LAST:

DISTINCT ON is simple and fast. Detailed explanation in this related answer:

For big tables with many rows per category consider an alternative approach: