Programs & Examples On #Htonl

Understanding INADDR_ANY for socket programming

  1. bind() of INADDR_ANY does NOT "generate a random IP". It binds the socket to all available interfaces.

  2. For a server, you typically want to bind to all interfaces - not just "localhost".

  3. If you wish to bind your socket to localhost only, the syntax would be my_sockaddress.sin_addr.s_addr = inet_addr("127.0.0.1");, then call bind(my_socket, (SOCKADDR *) &my_sockaddr, ...).

  4. As it happens, INADDR_ANY is a constant that happens to equal "zero":

    http://www.castaglia.org/proftpd/doc/devel-guide/src/include/inet.h.html

    # define INADDR_ANY ((unsigned long int) 0x00000000)
    ...
    # define INADDR_NONE    0xffffffff
    ...
    # define INPORT_ANY 0
    ...
    
  5. If you're not already familiar with it, I urge you to check out Beej's Guide to Sockets Programming:

    http://beej.us/guide/bgnet/

Since people are still reading this, an additional note:

man (7) ip:

When a process wants to receive new incoming packets or connections, it should bind a socket to a local interface address using bind(2).

In this case, only one IP socket may be bound to any given local (address, port) pair. When INADDR_ANY is specified in the bind call, the socket will be bound to all local interfaces.

When listen(2) is called on an unbound socket, the socket is automatically bound to a random free port with the local address set to INADDR_ANY.

When connect(2) is called on an unbound socket, the socket is automatically bound to a random free port or to a usable shared port with the local address set to INADDR_ANY...

There are several special addresses: INADDR_LOOPBACK (127.0.0.1) always refers to the local host via the loopback device; INADDR_ANY (0.0.0.0) means any address for binding...

Also:

bind() — Bind a name to a socket:

If the (sin_addr.s_addr) field is set to the constant INADDR_ANY, as defined in netinet/in.h, the caller is requesting that the socket be bound to all network interfaces on the host. Subsequently, UDP packets and TCP connections from all interfaces (which match the bound name) are routed to the application. This becomes important when a server offers a service to multiple networks. By leaving the address unspecified, the server can accept all UDP packets and TCP connection requests made for its port, regardless of the network interface on which the requests arrived.

How do I print uint32_t and uint16_t variables value?

The macros defined in <inttypes.h> are the most correct way to print values of types uint32_t, uint16_t, and so forth -- but they're not the only way.

Personally, I find those macros difficult to remember and awkward to use. (Given the syntax of a printf format string, that's probably unavoidable; I'm not claiming I could have come up with a better system.)

An alternative is to cast the values to a predefined type and use the format for that type.

Types int and unsigned int are guaranteed by the language to be at least 16 bits wide, and therefore to be able to hold any converted value of type int16_t or uint16_t, respectively. Similarly, long and unsigned long are at least 32 bits wide, and long long and unsigned long long are at least 64 bits wide.

For example, I might write your program like this (with a few additional tweaks):

#include <stdio.h>
#include <stdint.h>
#include <netinet/in.h>  

int main(void)
{
    uint32_t a=12, a1;
    uint16_t b=1, b1;
    a1 = htonl(a);
    printf("%lu---------%lu\n", (unsigned long)a, (unsigned long)a1);
    b1 = htons(b);
    printf("%u-----%u\n", (unsigned)b, (unsigned)b1);
    return 0;
}

One advantage of this approach is that it can work even with pre-C99 implementations that don't support <inttypes.h>. Such an implementation most likely wouldn't have <stdint.h> either, but the technique is useful for other integer types.

Can't find bundle for base name

java.util.MissingResourceException: Can't find bundle for base name
    org.jfree.chart.LocalizationBundle, locale en_US

To the point, the exception message tells in detail that you need to have either of the following files in the classpath:

/org/jfree/chart/LocalizationBundle.properties

or

/org/jfree/chart/LocalizationBundle_en.properties

or

/org/jfree/chart/LocalizationBundle_en_US.properties

Also see the official Java tutorial about resourcebundles for more information.

But as this is actually a 3rd party managed properties file, you shouldn't create one yourself. It should be already available in the JFreeChart JAR file. So ensure that you have it available in the classpath during runtime. Also ensure that you're using the right version, the location of the propertiesfile inside the package tree might have changed per JFreeChart version.

When executing a JAR file, you can use the -cp argument to specify the classpath. E.g.:

java -jar -cp c:/path/to/jfreechart.jar yourfile.jar

Alternatively you can specify the classpath as class-path entry in the JAR's manifest file. You can use in there relative paths which are relative to the JAR file itself. Do not use the %CLASSPATH% environment variable, it's ignored by JAR's and everything else which aren't executed with java.exe without -cp, -classpath and -jar arguments.

How to center the text in a JLabel?

The following constructor, JLabel(String, int), allow you to specify the horizontal alignment of the label.

JLabel label = new JLabel("The Label", SwingConstants.CENTER);

@import vs #import - iOS 7

Nice answer you can find in book Learning Cocoa with Objective-C (ISBN: 978-1-491-90139-7)

Modules are a new means of including and linking files and libraries into your projects. To understand how modules work and what benefits they have, it is important to look back into the history of Objective-C and the #import statement Whenever you want to include a file for use, you will generally have some code that looks like this:

#import "someFile.h"

Or in the case of frameworks:

#import <SomeLibrary/SomeFile.h>

Because Objective-C is a superset of the C programming language, the #import state- ment is a minor refinement upon C’s #include statement. The #include statement is very simple; it copies everything it finds in the included file into your code during compilation. This can sometimes cause significant problems. For example, imagine you have two header files: SomeFileA.h and SomeFileB.h; SomeFileA.h includes SomeFileB.h, and SomeFileB.h includes SomeFileA.h. This creates a loop, and can confuse the coimpiler. To deal with this, C programmers have to write guards against this type of event from occurring.

When using #import, you don’t need to worry about this issue or write header guards to avoid it. However, #import is still just a glorified copy-and-paste action, causing slow compilation time among a host of other smaller but still very dangerous issues (such as an included file overriding something you have declared elsewhere in your own code.)

Modules are an attempt to get around this. They are no longer a copy-and-paste into source code, but a serialised representation of the included files that can be imported into your source code only when and where they’re needed. By using modules, code will generally compile faster, and be safer than using either #include or #import.

Returning to the previous example of importing a framework:

#import <SomeLibrary/SomeFile.h>

To import this library as a module, the code would be changed to:

@import SomeLibrary;

This has the added bonus of Xcode linking the SomeLibrary framework into the project automatically. Modules also allow you to only include the components you really need into your project. For example, if you want to use the AwesomeObject component in the AwesomeLibrary framework, normally you would have to import everything just to use the one piece. However, using modules, you can just import the specific object you want to use:

@import AwesomeLibrary.AwesomeObject;

For all new projects made in Xcode 5, modules are enabled by default. If you want to use modules in older projects (and you really should) they will have to be enabled in the project’s build settings. Once you do that, you can use both #import and @import statements in your code together without any concern.

Unable to resolve host "<URL here>" No address associated with host name

Check you have:

1- Access to Internet connectivity.

2- The permission for internet is present in the manifest.

3- The url host is valid and registered in a trusted domain name server.

Interface vs Base class

Regarding C#, in some senses interfaces and abstract classes can be interchangeable. However, the differences are: i) interfaces cannot implement code; ii) because of this, interfaces cannot call further up the stack to subclass; and iii) only can abstract class may be inherited on a class, whereas multiple interfaces may be implemented on a class.

Difference between CLOB and BLOB from DB2 and Oracle Perspective?

They can be considered as equivalent. The limits in size are the same:

  • Maximum length of CLOB (in bytes or OCTETS)) 2 147 483 647
  • Maximum length of BLOB (in bytes) 2 147 483 647

There is also the DBCLOBs, for double byte characters.

References:

How to split a string to 2 strings in C

#include <string.h>

char *token;
char line[] = "SEVERAL WORDS";
char *search = " ";


// Token will point to "SEVERAL".
token = strtok(line, search);


// Token will point to "WORDS".
token = strtok(NULL, search);

Update

Note that on some operating systems, strtok man page mentions:

This interface is obsoleted by strsep(3).

An example with strsep is shown below:

char* token;
char* string;
char* tofree;

string = strdup("abc,def,ghi");

if (string != NULL) {

  tofree = string;

  while ((token = strsep(&string, ",")) != NULL)
  {
    printf("%s\n", token);
  }

  free(tofree);
}

Multiple simultaneous downloads using Wget?

I strongly suggest to use httrack.

ex: httrack -v -w http://example.com/

It will do a mirror with 8 simultaneous connections as default. Httrack has a tons of options where to play. Have a look.

Segmentation Fault - C

char *s  does not have some memory allocated . You need to allocate it manually in your case . You can do it as follows
s = (char *)malloc(100) ;

This would not lead to segmentation fault error as you will not be refering to an unknown location anymore

Pass multiple parameters in Html.BeginForm MVC

There are two options here.

  1. a hidden field within the form, or
  2. Add it to the route values parameter in the begin form method.

Edit

@Html.Hidden("clubid", ViewBag.Club.id)

or

 @using(Html.BeginForm("action", "controller",
                       new { clubid = @Viewbag.Club.id }, FormMethod.Post, null)

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

After wrestling with this problem today my opinion is this: BEGIN...END brackets code just like {....} does in C languages, e.g. code blocks for if...else and loops

GO is (must be) used when succeeding statements rely on an object defined by a previous statement. USE database is a good example above, but the following will also bite you:

alter table foo add bar varchar(8);
-- if you don't put GO here then the following line will error as it doesn't know what bar is.
update foo set bar = 'bacon';
-- need a GO here to tell the interpreter to execute this statement, otherwise the Parser will lump it together with all successive statements.

It seems to me the problem is this: the SQL Server SQL Parser, unlike the Oracle one, is unable to realise that you're defining a new symbol on the first line and that it's ok to reference in the following lines. It doesn't "see" the symbol until it encounters a GO token which tells it to execute the preceding SQL since the last GO, at which point the symbol is applied to the database and becomes visible to the parser.

Why it doesn't just treat the semi-colon as a semantic break and apply statements individually I don't know and wish it would. Only bonus I can see is that you can put a print() statement just before the GO and if any of the statements fail the print won't execute. Lot of trouble for a minor gain though.

Which is the fastest algorithm to find prime numbers?

A very fast implementation of the Sieve of Atkin is Dan Bernstein's primegen. This sieve is more efficient than the Sieve of Eratosthenes. His page has some benchmark information.

How to change target build on Android project?

Another way on the command line if you are using ant is to use the android.bat script (Windows) or android script (Mac). It's in $SDK_DIR/tools.

If you say,

android.bat update project --path .  --target "android-8"

it will regenerate your build.xml, AndroidManifest.xml, etc.

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

How can I create an object and add attributes to it?

Which objects are you using? Just tried that with a sample class and it worked fine:

class MyClass:
  i = 123456
  def f(self):
    return "hello world"

b = MyClass()
b.c = MyClass()
setattr(b.c, 'test', 123)
b.c.test

And I got 123 as the answer.

The only situation where I see this failing is if you're trying a setattr on a builtin object.

Update: From the comment this is a repetition of: Why can't you add attributes to object in python?

How to obtain values of request variables using Python and Flask

Adding more to Jason's more generalized way of retrieving the POST data or GET data

from flask_restful import reqparse

def parse_arg_from_requests(arg, **kwargs):
    parse = reqparse.RequestParser()
    parse.add_argument(arg, **kwargs)
    args = parse.parse_args()
    return args[arg]

form_field_value = parse_arg_from_requests('FormFieldValue')

mysql SELECT IF statement with OR

IF(compliment IN('set','Y',1), 'Y', 'N') AS customer_compliment

Will do the job as Buttle Butkus suggested.

How can I make a "color map" plot in matlab?

gevang's answer is great. There's another way as well to do this directly by using pcolor. Code:

[X,Y] = meshgrid(-8:.5:8);
R = sqrt(X.^2 + Y.^2) + eps;
Z = sin(R)./R;
figure;
subplot(1,3,1);
pcolor(X,Y,Z); 
subplot(1,3,2);
pcolor(X,Y,Z); shading flat;
subplot(1,3,3);
pcolor(X,Y,Z); shading interp;

Output:

enter image description here

Also, pcolor is flat too, as show here (pcolor is the 2d base; the 3d figure above it is generated using mesh):

enter image description here

gcc warning" 'will be initialized after'

If you're seeing errors from library headers and you're using GCC, then you can disable warnings by including the headers using -isystem instead of -I.

Similar features exist in clang.

If you're using CMake, you can specify SYSTEM for include_directories.

How to darken an image on mouseover?

Put a black, semitransparent, div on top of it.

Backbone.js fetch with parameters

You can also set processData to true:

collection.fetch({ 
    data: { page: 1 },
    processData: true
});

Jquery will auto process data object into param string,

but in Backbone.sync function, Backbone turn the processData off because Backbone will use other method to process data in POST,UPDATE...

in Backbone source:

if (params.type !== 'GET' && !Backbone.emulateJSON) {
    params.processData = false;
}

"You tried to execute a query that does not include the specified aggregate function"

GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.

How to increase the clickable area of a <a> tag button?

For me the padding solution wasn't good, as I was using border on the button, and would've been hard to put modify the markup to create an overlay for the touch area.

So what I did, is I just used the :before pseudo tag, and created an overlay, which was perfect in my case, as the click event propagated the same way.

button.my-button:before {
    content: '';
    position: absolute;
    width: 26px;
    height: 26px;
    top: -6px;
    left: -5px;
}

Div Background Image Z-Index Issue

To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:

Add to your footer and header this CSS:

position: relative; 

EDITED:

Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...

Remove From the #backstretch:

z-index: -999999;

Read a little bit about Z-Index here!

How do I determine height and scrolling position of window in jQuery?

From jQuery Docs:

const height = $(window).height();
const scrollTop = $(window).scrollTop();

http://api.jquery.com/scrollTop/
http://api.jquery.com/height/

Press TAB and then ENTER key in Selenium WebDriver

Using Java:

private WebDriver driver = new FirefoxDriver();
WebElement element = driver.findElement(By.id("<ElementID>"));//Enter ID for the element. You can use Name, xpath, cssSelector whatever you like
element.sendKeys(Keys.TAB);
element.sendKeys(Keys.ENTER);

Using C#:

private IWebDriver driver = new FirefoxDriver();
IWebElement element = driver.FindElement(By.Name("q"));
element.SendKeys(Keys.Tab);
element.SendKeys(Keys.Enter);

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

SQL Server Restore Error - Access is Denied

In my case - I had to double check the Backup path of the database from where I was restoring. I had previously restored it from a different path when I did it the first time. I fixed the Backup path to use the backup path I used the first time and it worked!

Is there Java HashMap equivalent in PHP?

Depending on what you want you might be interested in the SPL Object Storage class.

http://php.net/manual/en/class.splobjectstorage.php

It lets you use objects as keys, has an interface to count, get the hash and other goodies.

$s = new SplObjectStorage;
$o1 = new stdClass;
$o2 = new stdClass;
$o2->foo = 'bar';

$s[$o1] = 'baz';
$s[$o2] = 'bingo';

echo $s[$o1]; // 'baz'
echo $s[$o2]; // 'bingo'

Insert Data Into Tables Linked by Foreign Key

You can do it in one sql statement for existing customers, 3 statements for new ones. All you have to do is be an optimist and act as though the customer already exists:

insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

If the customer does not exist, you'll get an sql exception which text will be something like:

null value in column "customer_id" violates not-null constraint

(providing you made customer_id non-nullable, which I'm sure you did). When that exception occurs, insert the customer into the customer table and redo the insert into the order table:

insert into customer(name) values ('John');
insert into "order" (customer_id, price) values \
((select customer_id from customer where name = 'John'), 12.34);

Unless your business is growing at a rate that will make "where to put all the money" your only real problem, most of your inserts will be for existing customers. So, most of the time, the exception won't occur and you'll be done in one statement.

How to run docker-compose up -d at system start up?

When we use crontab or the deprecated /etc/rc.local file, we need a delay (e.g. sleep 10, depending on the machine) to make sure that system services are available. Usually, systemd (or upstart) is used to manage which services start when the system boots. You can try use the similar configuration for this:

# /etc/systemd/system/docker-compose-app.service

[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service

[Service]
Type=oneshot
RemainAfterExit=yes
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up -d
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0

[Install]
WantedBy=multi-user.target

Or, if you want run without the -d flag:

# /etc/systemd/system/docker-compose-app.service

[Unit]
Description=Docker Compose Application Service
Requires=docker.service
After=docker.service

[Service]
WorkingDirectory=/srv/docker
ExecStart=/usr/local/bin/docker-compose up
ExecStop=/usr/local/bin/docker-compose down
TimeoutStartSec=0
Restart=on-failure
StartLimitIntervalSec=60
StartLimitBurst=3

[Install]
WantedBy=multi-user.target

Change the WorkingDirectory parameter with your dockerized project path. And enable the service to start automatically:

systemctl enable docker-compose-app

How to add days to the current date?

Add Days in Date in SQL

 DECLARE @NEWDOB DATE=null
 
 SET @NEWDOB= (SELECT DOB, DATEADD(dd,45,DOB)AS NEWDOB FROM tbl_Employees)

Google Maps: how to get country, state/province/region, city given a lat/long value?

I found the GeoCoder javascript a little buggy when I included it in my jsp files.

You can also try this:



    var lat = "43.7667855" ;
    var long = "-79.2157321" ;
    var url = "https://maps.googleapis.com/maps/api/geocode/json?latlng="
       +lat+","+long+"&sensor=false";
    $.get(url).success(function(data) {
       var loc1 = data.results[0];
       var county, city;
         $.each(loc1, function(k1,v1) {
            if (k1 == "address_components") {
               for (var i = 0; i < v1.length; i++) {
                  for (k2 in v1[i]) {
                     if (k2 == "types") {
                        var types = v1[i][k2];
                        if (types[0] =="sublocality_level_1") {
                            county = v1[i].long_name;
                            //alert ("county: " + county);
                        } 
                        if (types[0] =="locality") {
                           city = v1[i].long_name;
                           //alert ("city: " + city);
                       } 
                     }

                  }          

               }

            }

         });
         $('#city').html(city); 
    }); 

Pass C# ASP.NET array to Javascript array

In the page file:

<script type="text/javascript">
    var a = eval('[<% =string.Join(", ", numbers) %>]');
</script>

while in code behind:

public int[] numbers = WhatEverGetTheArray();

Not equal <> != operator on NULL

We use

SELECT * FROM MyTable WHERE ISNULL(MyColumn, ' ') = ' ';

to return all rows where MyColumn is NULL or all rows where MyColumn is an empty string. To many an "end user", the NULL vs. empty string issue is a distinction without a need and point of confusion.

Installing a plain plugin jar in Eclipse 3.5

in Eclipse 4.4.1

  1. copy jar in "C:\eclipse\plugins"
  2. edit file "C:\eclipse\configuration\org.eclipse.equinox.simpleconfigurator\bundles.info"
  3. add jar info. example: com.soft4soft.resort.jdt,2.4.4,file:plugins\com.soft4soft.resort.jdt_2.4.4.jar,4,false
  4. restart Eclipse.

How should I pass an int into stringWithFormat?

Is the snippet you posted just a sample to show what you are trying to do?

The reason I ask is that you've named a method increment, but you seem to be using that to set the value of a text label, rather than incrementing a value.

If you are trying to do something more complicated - such as setting an integer value and having the label display this value, you could consider using bindings. e.g

You declare a property count and your increment action sets this value to whatever, and then in IB, you bind the label's text to the value of count. As long as you follow Key Value Coding (KVC) with count, you don't have to write any code to update the label's display. And from a design perspective you've got looser coupling.

React Native: Possible unhandled promise rejection

You should add the catch() to the end of the Api call. When your code hits the catch() it doesn't return anything, so data is undefined when you try to use setState() on it. The error message actually tells you this too :)

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

To complement the above answers, here is a small working example of a program that prints the current time and date, including milliseconds.

import java.text.SimpleDateFormat;
import java.util.Date;

public class test {
    public static void main(String argv[]){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date now = new Date();
        String strDate = sdf.format(now);
        System.out.println(strDate);
    }
}

Python - Count elements in list

You can get element count of list by following two ways:

>>> l = ['a','b','c']
>>> len(l)
3

>>> l.__len__() 
3

ASP.NET Web Site or ASP.NET Web Application?

I recommend you watch the video Web Application Projects & Web Deployment Projects on the ASP.NET website which explains the difference in great detail, it was quite helpful to me.

By the way, don't get confused by the title, a great part of the video explains the difference between website projects and web application projects and why Microsoft re-introduced Web application projects in Visual studio 2005 (as you probably already know, it originally shipped with only website projects then web application projects were added in SP1). A great video I highly recommend for anyone who wants to know the difference.

break statement in "if else" - java

Because your else isn't attached to anything. The if without braces only encompasses the single statement that immediately follows it.

if (choice==5)
{
    System.out.println("End of Game\n Thank you for playing with us!");
    break;
}
else
{
   System.out.println("Not a valid choice!\n Please try again...\n");
}

Not using braces is generally viewed as a bad practice because it can lead to the exact problems you encountered.

In addition, using a switch here would make more sense.

int choice;
boolean keepGoing = true;
while(keepGoing)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch(choice)
    {
        case 1: 
            playGame();
            break;
        case 2: 
            loadGame();
            break;
        // your other cases
        // ...
        case 5: 
            System.out.println("End of Game\n Thank you for playing with us!");
            keepGoing = false;
            break;
        default:
            System.out.println("Not a valid choice!\n Please try again...\n");
     }
 }         

Note that instead of an infinite for loop I used a while(boolean), making it easy to exit the loop. Another approach would be using break with labels.

How to programmatically empty browser cache?

There's no way a browser will let you clear its cache. It would be a huge security issue if that were possible. This could be very easily abused - the minute a browser supports such a "feature" will be the minute I uninstall it from my computer.

What you can do is to tell it not to cache your page, by sending the appropriate headers or using these meta tags:

<meta http-equiv='cache-control' content='no-cache'>
<meta http-equiv='expires' content='0'>
<meta http-equiv='pragma' content='no-cache'>

You might also want to consider turning off auto-complete on form fields, although I'm afraid there's a standard way to do it (see this question).

Regardless, I would like to point out that if you are working with sensitive data you should be using SSL. If you aren't using SSL, anyone with access to the network can sniff network traffic and easily see what your user is seeing.

Using SSL also makes some browsers not use caching unless explicitly told to. See this question.

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

You have to execute your query and add single quote to $email in the query beacuse it's a string, and remove the is_resource($query) $query is a string, the $result will be the resource

$query = "SELECT `email` FROM `tblUser` WHERE `email` = '$email'";
$result = mysqli_query($link,$query); //$link is the connection

if(mysqli_num_rows($result) > 0 ){....}

UPDATE

Base in your edit just change:

if(is_resource($query) && mysqli_num_rows($query) > 0 ){
        $query = mysqli_fetch_assoc($query);
        echo $email . " email exists " .  $query["email"] . "\n";

By

if(is_resource($result) && mysqli_num_rows($result) == 1 ){
        $row = mysqli_fetch_assoc($result);
         echo $email . " email exists " .  $row["email"] . "\n";

and you will be fine

UPDATE 2

A better way should be have a Store Procedure that execute the following SQL passing the Email as Parameter

SELECT IF( EXISTS (
                  SELECT *
                  FROM `Table`
                  WHERE `email` = @Email)
          , 1, 0) as `Exist`

and retrieve the value in php

Pseudocodigo:

 $query = Call MYSQL_SP($EMAIL);
 $result = mysqli_query($conn,$query);
 $row = mysqli_fetch_array($result)
 $exist = ($row['Exist']==1)? 'the email exist' : 'the email doesnt exist';

json_decode to array

Please try this

<?php
$json_string = 'http://www.domain.com/jsondata.json';

$jsondata = file_get_contents($json_string);
$obj = json_decode($jsondata, true);
echo "<pre>"; print_r($obj['Result']);
?>

Developing C# on Linux

Mono is a runtime environment that can run .NET applications and that works on both Windows and Linux. It includes a C# compiler.

As an IDE, you could use MonoDevelop, and I suppose there's something available for Eclipse, too.

Note that WinForms support on Mono is there, but somewhat lacking. Generally, Mono developers seem to prefer different GUI toolkits such as Gtk#.

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

For me changing compile to implementation fixed it

Before

compile 'androidx.recyclerview:recyclerview:1.0.0'
compile 'androidx.cardview:cardview:1.0.0'
//Retrofit Dependencies
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

After

implementation 'androidx.recyclerview:recyclerview:1.0.0'
implementation 'androidx.cardview:cardview:1.0.0'
//Retrofit Dependencies
implementation 'com.squareup.retrofit2:retrofit:2.1.0'
implementation 'com.squareup.retrofit2:converter-gson:2.1.0'

How to determine the number of days in a month in SQL Server?

Most elegant solution: works for any @DATE

DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,@DATE),0)))

Throw it in a function or just use it inline. This answers the original question without all the extra junk in the other answers.

examples for dates from other answers:

SELECT DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,'1/31/2009'),0))) Returns 31

SELECT DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,'2404-feb-15'),0))) Returns 29

SELECT DAY(DATEADD(DD,-1,DATEADD(MM,DATEDIFF(MM,-1,'2011-12-22'),0))) Returns 31

Your password does not satisfy the current policy requirements

In my opinion setting the "validate_password_policy" to "low" or uninstalling the "validate password plugin" is not the right thing to do. You must never compromise with security of your database (unless you don't really care). I am wondering why people are even suggesting these options when you simply can pick a good password.

To overcome this problem, I executed following command in mysql: SHOW VARIABLES LIKE 'validate_password%' as suggested by @JNevill. My "validate_password_policy" was set to Medium, along with other things. Here is the screenshot of its execution: Validate Password Policy

The result is self explanatory. For a valid password (when Password policy is set to medium):

  • Password must be at least 8 characters long
  • Mixed case count is 1 (At least 1 letter in small and 1 letter in caps)
  • Number count is 1
  • Minimum special Character count is 1

So a valid password must obey the policy. Examples of valid password for above rules maybe:

  • Student123@
  • NINZAcoder$100
  • demoPass#00

You can pick any combination as long as it satisfies the policy.

For other "validate_password_policy" you can simply look the values for different options and pick your password accordingly (I haven't tried for "STRONG").

https://dev.mysql.com/doc/refman/5.6/en/validate-password-options-variables.html

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

"The semaphore timeout period has expired" error for USB connection

Too many big files all in one go. Windows barfs. Essentially the copying took too long because you asked too much of the computer and the file locking was locked too long and set a flag off, the flag is a semaphore error.

The computer stuffed itself and choked on it. I saw the RAM memory here get progressively filled with a Cache in RAM. Then when filled the subsystem ground to a halt with a semaphore error.

I have a workaround; copy or transfer fewer files not one humongous block. Break it down into sets of blocks and send across the files one at a time, maybe a few at a time, but not never the lot.

References:

https://appuals.com/how-to-fix-the-semaphore-timeout-period-has-expired-0x80070079/

https://www-01.ibm.com/support/docview.wss?uid=swg21094630

How to add Headers on RESTful call using Jersey Client API

ClientResponse response = webResource
                               .queryParams(queryParams) //
                               .header("Content-Type", "application/json") //
                               .header("id", "123") //
                               .get(ClientResponse.class) //
;

Kill some processes by .exe file name

If you have the process ID (PID) you can kill this process as follow:

Process processToKill = Process.GetProcessById(pid);
processToKill.Kill();

How do I expand the output display to see more columns of a pandas DataFrame?

pd.options.display.max_columns = 100

You can specify the numbers of columns as per your requirement in max_columns.

When is a timestamp (auto) updated?

Adding where to find UPDATE CURRENT_TIMESTAMP because for new people this is a confusion.

Most people will use phpmyadmin or something like it.

Default value you select CURRENT_TIMESTAMP

Attributes (a different drop down) you select UPDATE CURRENT_TIMESTAMP

Any way to clear python's IDLE window?

There is no need to write your own function to do this! Python has a built in clear function.

Type the following in the command prompt:

shell.clear()

If using IPython for Windows, it's

cls()

Is it possible to animate scrollTop with jQuery?

the cross browser code is:

$(window).scrollTop(300); 

it is without animation but works everywhere

How to read file from res/raw by name

With the help of the given links I was able to solve the problem myself. The correct way is to get the resource ID with

getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
                             "raw", getPackageName());

To get it as a InputStream

InputStream ins = getResources().openRawResource(
            getResources().getIdentifier("FILENAME_WITHOUT_EXTENSION",
            "raw", getPackageName()));

Hide/encrypt password in bash file to stop accidentally seeing it

There's a more convenient way to store passwords in a script but you will have to encrypt and obfuscate the script so that it cannot be read. In order to successfully encrypt and obfuscate a shell script and actually have that script be executable, try copying and pasting it here:

http://www.kinglazy.com/shell-script-encryption-kinglazy-shieldx.htm

On the above page, all you have to do is submit your script and give the script a proper name, then hit the download button. A zip file will be generated for you. Right click on the download link and copy the URL you're provided. Then, go to your UNIX box and perform the following steps.

Installation:

1. wget link-to-the-zip-file
2. unzip the-newly-downloaded-zip-file
3. cd /tmp/KingLazySHIELD
4. ./install.sh /var/tmp/KINGLAZY/SHIELDX-(your-script-name) /home/(your-username) -force

What the above install command will do for you is:

  1. Install the encrypted version of your script in the directory /var/tmp/KINGLAZY/SHIELDX-(your-script-name).
  2. It'll place a link to this encrypted script in whichever directory you specify in replacement of /home/(your-username) - that way, it allows you to easily access the script without having to type the absolute path.
  3. Ensures NO ONE can modify the script - Any attempts to modify the encrypted script will render it inoperable...until those attempts are stopped or removed. It can even be configured to notify you whenever someone tries to do anything with the script other than run it...i.e. hacking or modification attempts.
  4. Ensures absolutely NO ONE can make copies of it. No one can copy your script to a secluded location and try to screw around with it to see how it works. All copies of the script must be links to the original location which you specified during install (step 4).

NOTE:

This does not work for interactive scripts that prompts and waits on the user for a response. The values that are expected from the user should be hard-coded into the script. The encryption ensures no one can actually see those values so you need not worry about that.

RELATION:

The solution provided in this post answers your problem in the sense that it encrypts the actual script containing the password that you wanted to have encrypted. You get to leave the password as is (unencrypted) but the script that the password is in is so deeply obfuscated and encrypted that you can rest assured no one will be able to see it. And if attempts are made to try to pry into the script, you will receive email notifications about them.

How to get method parameter names?

Here is something I think will work for what you want, using a decorator.

class LogWrappedFunction(object):
    def __init__(self, function):
        self.function = function

    def logAndCall(self, *arguments, **namedArguments):
        print "Calling %s with arguments %s and named arguments %s" %\
                      (self.function.func_name, arguments, namedArguments)
        self.function.__call__(*arguments, **namedArguments)

def logwrap(function):
    return LogWrappedFunction(function).logAndCall

@logwrap
def doSomething(spam, eggs, foo, bar):
    print "Doing something totally awesome with %s and %s." % (spam, eggs)


doSomething("beans","rice", foo="wiggity", bar="wack")

Run it, it will yield the following output:

C:\scripts>python decoratorExample.py
Calling doSomething with arguments ('beans', 'rice') and named arguments {'foo':
 'wiggity', 'bar': 'wack'}
Doing something totally awesome with beans and rice.

Android: Go back to previous activity

Try Activity#finish(). This is more or less what the back button does by default.

How can I tell if a DOM element is visible in the current viewport?

Now most browsers support getBoundingClientRect method, which has become the best practice. Using an old answer is very slow, not accurate and has several bugs.

The solution selected as correct is almost never precise. You can read more about its bugs.


This solution was tested on Internet Explorer 7 (and later), iOS 5 (and later) Safari, Android 2.0 (Eclair) and later, BlackBerry, Opera Mobile, and Internet Explorer Mobile 9.


function isElementInViewport (el) {

    // Special bonus for those using jQuery
    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }

    var rect = el.getBoundingClientRect();

    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /* or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /* or $(window).width() */
    );
}

How to use:

You can be sure that the function given above returns correct answer at the moment of time when it is called, but what about tracking element's visibility as an event?

Place the following code at the bottom of your <body> tag:

function onVisibilityChange(el, callback) {
    var old_visible;
    return function () {
        var visible = isElementInViewport(el);
        if (visible != old_visible) {
            old_visible = visible;
            if (typeof callback == 'function') {
                callback();
            }
        }
    }
}

var handler = onVisibilityChange(el, function() {
    /* Your code go here */
});


// jQuery
$(window).on('DOMContentLoaded load resize scroll', handler);

/* // Non-jQuery
if (window.addEventListener) {
    addEventListener('DOMContentLoaded', handler, false);
    addEventListener('load', handler, false);
    addEventListener('scroll', handler, false);
    addEventListener('resize', handler, false);
} else if (window.attachEvent)  {
    attachEvent('onDOMContentLoaded', handler); // Internet Explorer 9+ :(
    attachEvent('onload', handler);
    attachEvent('onscroll', handler);
    attachEvent('onresize', handler);
}
*/

If you do any DOM modifications, they can change your element's visibility of course.

Guidelines and common pitfalls:

Maybe you need to track page zoom / mobile device pinch? jQuery should handle zoom/pinch cross browser, otherwise first or second link should help you.

If you modify DOM, it can affect the element's visibility. You should take control over that and call handler() manually. Unfortunately, we don't have any cross browser onrepaint event. On the other hand that allows us to make optimizations and perform re-check only on DOM modifications that can change an element's visibility.

Never Ever use it inside jQuery $(document).ready() only, because there is no warranty CSS has been applied in this moment. Your code can work locally with your CSS on a hard drive, but once put on a remote server it will fail.

After DOMContentLoaded is fired, styles are applied, but the images are not loaded yet. So, we should add window.onload event listener.

We can't catch zoom/pinch event yet.

The last resort could be the following code:

/* TODO: this looks like a very bad code */
setInterval(handler, 600);

You can use the awesome feature pageVisibiliy of the HTML5 API if you care if the tab with your web page is active and visible.

TODO: this method does not handle two situations:

Import / Export database with SQL Server Server Management Studio

Another solutions is - Backing Up and Restoring Database

Back Up the System Database

To back up the system database using Microsoft SQL Server Management Studio Express, follow the steps below:

  1. Download and install Microsoft SQL Server 2008 Management Studio Express from the Microsoft web site: http://www.microsoft.com/en-us/download/details.aspx?id=7593

  2. After Microsoft SQL Server Management Studio Express has been installed, launch the application to connect to the system database. The "Connect to Server" dialog box displays. In the "Server name:" field, enter the name of the Webtrends server on which the system database is installed. In the "Authentication:" field select "Windows Authentication" if logged into the Windows machine using the Webtrends service account or an account with rights to make changes to the system database. Otherwise, select "SQL Server Authentication" from the drop-down menu and enter the credentials for a SQL Server account which has the needed rights. Click "Connect" to connect to the database.

  3. Expand "Databases", right-click on "wt_sched" and select "Tasks" > "Back Up..." from the context menu. The "Back Up Database" dialog box displays. Under the "Source" section, ensure the "wt_sched" is selected for the "Database:" and "Backup type:" is "Full." Under "Backup set" provide a name, description and expiration date as needed and then select "Add..." under the "Destination" section and designate the file name and path where the backup will be saved. It may be necessary to select the "Overwrite all existing backup sets" option in the Options section if a backup already exists and is to be overwritten.
  4. Select "OK" to complete the backup process.

  5. Repeat the above steps for the "wtMaster" part of the database.

Restore the System Database

To restore the system database using Microsoft SQL Server Management Studio, follow the steps below:

  1. If you haven't already, download and install Microsoft SQL Server 2008 Management Studio Express from the Microsoft web site: http://www.microsoft.com/en-us/download/details.aspx?id=7593

  2. After Microsoft SQL Server Management Studio has been installed, launch the application to connect to the system database. The "Connect to Server" dialog box displays. In the "Server type:" field, select "Database Engine" (default). In the "Server name:" field, select "\WTSYSTEMDB" where is the name of the Webtrends server where the database is located. WTSYSTEMDB is the name of the database instance in a default installation. In the "Authentication:" field select "Windows Authentication" if logged into the Windows machine using the Webtrends service account or an account with rights to make changes to the system database. Otherwise, select "SQL Server Authentication" from the drop-down menu and enter the credentials for a SQL Server account which has the needed rights. Click "Connect" to connect to the database.

  3. Expand "Databases", right-click on "wt_sched" and select "Delete" from the context menu. Make sure "Delete backup and restore history information for databases" check-box is checked.

  4. Select "OK" to complete the deletion process.

  5. Repeat the above steps for the "wtMaster" part of the database.

  6. Right click on "Databases" and select "Restore Database..." from the context menu. In the "To database:" field type in "wt_sched". Select the "From device:" radio button. Click on the ellipse (...) to the right of the "From device:" text field. Click the "Add" button. Navigate to and select the backup file for "wt_sched". Select "OK" on the "Locate Backup File" form. Select "OK" on the "Specify Backup" form. Check the check-box in the restore column next to "wt_sched-Full Database Backup". Select "OK" on the "Restore Database" form.

  7. Repeat step 6 for the "wtMaster" part of the database.

Courtesy - http://kb.webtrends.com/articles/How_To/Backing-Up-and-Restoring-the-System-Database-using-MS-SQL-Management-Studio

EventListener Enter Key

Are you trying to submit a form?

Listen to the submit event instead.

This will handle click and enter.

If you must use enter key...

document.querySelector('#txtSearch').addEventListener('keypress', function (e) {
    if (e.key === 'Enter') {
      // code for enter
    }
});

How to remove all duplicate items from a list

This should do it for you:

new_list = list(set(old_list))

set will automatically remove duplicates. list will cast it back to a list.

How can I pass a parameter to a t-sql script?

Two options save vijay.sql

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||to_char(sysdate,'YYYYMMDD')||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

The above will generate table names automatically based on sysdate. If you still need to pass as variable, then save vijay.sql as

declare
begin
execute immediate 
'CREATE TABLE DMS_POP_WKLY_REFRESH_'||&1||' NOLOGGING PARALLEL AS
SELECT wk.*,bbc.distance_km ,NVL(bbc.tactical_broadband_offer,0) tactical_broadband_offer ,
       sel.tactical_select_executive_flag,
       sel.agent_name,
       res.DMS_RESIGN_CAMPAIGN_CODE,
       pclub.tactical_select_flag
FROM   spineowner.pop_wkly_refresh_20100201 wk,
       dms_bb_coverage_102009 bbc,
       dms_select_executive_group sel,
       DMS_RESIGN_CAMPAIGN_26052009 res,
       DMS_PRIORITY_CLUB pclub
WHERE  wk.mpn = bbc.mpn(+)
AND    wk.mpn = sel.mpn (+)
AND    wk.mpn = res.mpn (+)
AND    wk.mpn = pclub.mpn (+)'
end;
/

and then run as sqlplus -s username/password @vijay.sql '20100101'

Error when trying vagrant up

Check the following entry in your Vagrantfile

Every Vagrant development environment requires a box.
You can search for boxes at https://vagrantcloud.com/search.
  config.vm.box = "base"

This is the default file setting which is created with vagrant init command. But what you need to do is do initialise vagrant environment with an OS box. For instance $vagrant init centos/7. And the Vagrantfile will look something like this:

Every Vagrant development environment requires a box.
You can search for boxes at https://vagrantcloud.com/search.
  config.vm.box = "centos/7"

This will resolve the error of not found base when doing a vagrant up.

Convert XML to JSON (and back) using Javascript

I think this is the best one: Converting between XML and JSON

Be sure to read the accompanying article on the xml.com O'Reilly site, which goes into details of the problems with these conversions, which I think you will find enlightening. The fact that O'Reilly is hosting the article should indicate that Stefan's solution has merit.

How do I change the IntelliJ IDEA default JDK?

I am using IntelliJ 2020.3.1 and the File > Other Settings... menu option has disappeared. I went to Settings in the usual way and searched for "jdk". Under Build, Execution, Deployment > Build Tools > Maven > Importing I found the the setting that will solve my specific issue:

JDK for importer.

IntelliJ 2020.3 Settings dialog

How to find a hash key containing a matching value

According to ruby doc http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-key key(value) is the method to find the key on the base of value.

ROLE = {"customer" => 1, "designer" => 2, "admin" => 100}
ROLE.key(2)

it will return the "designer".

How to put comments in Django templates

Comment tags are documented at https://docs.djangoproject.com/en/stable/ref/templates/builtins/#std:templatetag-comment

{% comment %} this is a comment {% endcomment %}

Single line comments are documented at https://docs.djangoproject.com/en/stable/topics/templates/#comments

{# this won't be rendered #}

Styling text input caret

Here are some vendors you might me looking for

::-webkit-input-placeholder {color: tomato}
::-moz-placeholder          {color: tomato;} /* Firefox 19+ */
:-moz-placeholder           {color: tomato;} /* Firefox 18- */
:-ms-input-placeholder      {color: tomato;}

You can also style different states, such as focus

:focus::-webkit-input-placeholder {color: transparent}
:focus::-moz-placeholder          {color: transparent}
:focus:-moz-placeholder           {color: transparent}
:focus:-ms-input-placeholder      {color: transparent}

You can also do certain transitions on it, like

::-VENDOR-input-placeholder       {text-indent: 0px;   transition: text-indent 0.3s ease;}
:focus::-VENDOR-input-placeholder  {text-indent: 500px; transition: text-indent 0.3s ease;}

how to install tensorflow on anaconda python 3.6

conda create -n tensorflow_gpuenv tensorflow-gpu

Or

type the command pip install c:.*.whl in command prompt (cmd).

How to create a DateTime equal to 15 minutes ago?

 datetime.datetime.now() - datetime.timedelta(minutes=15)

JAVA_HOME and PATH are set but java -version still shows the old one

If you want to use JDKs downloaded from Oracle's site, what worked for me (using Mint) is using update-alternatives:

  1. I downloaded the JDK and extracted it just anywhere, for example in /home/aqeel/development/jdk/jdk1.6.0_35
  2. I ran:

    sudo update-alternatives --install /usr/bin/java java /home/aqeel/development/jdk/jdk1.6.0_35/bin/java 1
    

    Now you can execute sudo update-alternatives --config java and choose your java version.

  3. This doesn't set the JAVA_HOME variable, which I wanted configured, so I just added it to my ~/.bashrc, including an export JAVA_HOME="/home/aqeel/development/jdk/jdk1.6.0_35" statement

Now, I had two JDKs downloaded (let's say the second has been extracted to /home/aqeel/development/jdk/jdk-10.0.1).

How can we change the JAVA_HOME dynamically based on the current java being used?

My solution is not very elegant, I'm pretty sure there are better options out there, but anyway:

  1. To change the JAVA_HOME dynamically based on the chosen java alternative, I added this snippet to the ~/.bashrc:

    export JAVA_HOME=$(update-alternatives --query java | grep Value: | awk -F'Value: ' '{print $2}' | awk -F'/bin/java' '{print $1}')
    

Finally (this is out of the scope) if you have to change the java version constantly, you might want to consider:

  1. Adding an alias to your ~./bash_aliases:

    alias change-java="sudo update-alternatives --config java"
    

(You might have to create the file and maybe uncomment the section related to this in ~/.bashrc)

HTML Tags in Javascript Alert() method

You can add HTML into an alert string, but it will not render as HTML. It will just be displayed as a plain string. Simple answer: no.

What are the best JVM settings for Eclipse?

Eclipse Ganymede 3.4.2 settings


For more recent settings, see Eclipse Galileo 3.5 settings above.


JDK

The best JVM setting always, in my opinion, includes the latest JDK you can find (so for now, jdk1.6.0_b07 up to b16, except b14 and b15)

eclipse.ini

Even with those pretty low memory settings, I can run large java projects (along with a web server) on my old (2002) desktop with 2Go RAM.

-showlocation
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-framework
plugins\org.eclipse.osgi_3.4.2.R34x_v20080826-1230.jar
-vm
jdk1.6.0_10\jre\bin\client\jvm.dll
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms128m
-Xmx384m
-Xss2m
-XX:PermSize=128m
-XX:MaxPermSize=128m
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+UseConcMarkSweepGC
-XX:+CMSIncrementalMode
-XX:+CMSIncrementalPacing
-XX:CompileThreshold=5
-Dcom.sun.management.jmxremote

See GKelly's SO answer and Piotr Gabryanczyk's blog entry for more details about the new options.

Monitoring

You can also consider launching:

C:\[jdk1.6.0_0x path]\bin\jconsole.exe

As said in a previous question about memory consumption.

Which MySQL datatype to use for an IP address?

You have two possibilities (for an IPv4 address) :

  • a varchar(15), if your want to store the IP address as a string
    • 192.128.0.15 for instance
  • an integer (4 bytes), if you convert the IP address to an integer
    • 3229614095 for the IP I used before


The second solution will require less space in the database, and is probably a better choice, even if it implies a bit of manipulations when storing and retrieving the data (converting it from/to a string).

About those manipulations, see the ip2long() and long2ip() functions, on the PHP-side, or inet_aton() and inet_ntoa() on the MySQL-side.

Adding a HTTP header to the Angular HttpClient doesn't send the header, why?

First, you need to add HttpHeaders with HttpClient

import { HttpClient,HttpHeaders  } from '@angular/common/http';

your constructor should be like this.

constructor(private http: HttpClient) { }

then you can use like this

   let header = new HttpHeaders({ "Authorization": "Bearer "+token});

   const requestOptions = {  headers: header};                                                                                                                                                                            

    return this.http.get<any>(url, requestOptions)
        .toPromise()
        .then(data=> {
            //...
            return data;
    });

How to create a drop shadow only on one side of an element?

Another idea based on the answer of @theengineear where I will use inset instead of polygon. It's easier since it works the same way as margin or padding. I will also rely on CSS variable to easily define all the different cases.

_x000D_
_x000D_
.shadow {
  box-shadow: 0 0 8px 5px rgba(200, 0, 0, 0.5);
  clip-path:inset(var(--t,0) var(--r,0) var(--b,0) var(--l,0))
}

.top { --t:-100%; }
.right { --r:-100%;}
.bottom { --b:-100%; }
.left { --l:-100%;}


/* layout for example */

.box {
  display: inline-block;
  vertical-align: top;
  background: #338484;
  color: #fff;
  width: 4em;
  height: 2em;
  margin: 1em;
  padding: 1em;
}
_x000D_
<div class="box">none</div>
<div class="box shadow top right left bottom">all</div>
<div class="box shadow top">top</div>
<div class="box shadow right">right</div>
<div class="box shadow bottom">bottom</div>
<div class="box shadow left">left</div>
<div class="box shadow bottom right">bottom right</div>
<div class="box shadow bottom top">top bottom</div>
<div class="box shadow left top right">top left right</div>
<div class="box shadow left right"> left right</div>
_x000D_
_x000D_
_x000D_

Removing viewcontrollers from navigation stack

// removing the viewcontrollers by class names from stack and then dismissing the current view.

 self.navigationController?.viewControllers.removeAll(where: { (vc) -> Bool in
      if vc.isKind(of: ViewController.self) || vc.isKind(of: ViewController2.self) 
       {
        return true
        } 
     else 
        {
         return false
         }
        })
self.navigationController?.popViewController(animated: false)
self.dismiss(animated: true, completion: nil)

How do you compare two version Strings in Java?

@alex's post on Kotlin

class Version(inputVersion: String) : Comparable<Version> {

        var version: String
            private set

        override fun compareTo(other: Version) =
            (split() to other.split()).let {(thisParts, thatParts)->
                val length = max(thisParts.size, thatParts.size)
                for (i in 0 until length) {
                    val thisPart = if (i < thisParts.size) thisParts[i].toInt() else 0
                    val thatPart = if (i < thatParts.size) thatParts[i].toInt() else 0
                    if (thisPart < thatPart) return -1
                    if (thisPart > thatPart) return 1
                }
                 0
            }

        init {
            require(inputVersion.matches("[0-9]+(\\.[0-9]+)*".toRegex())) { "Invalid version format" }
            version = inputVersion
        }
    }

    fun Version.split() = version.split(".").toTypedArray()

usage:

Version("1.2.4").compareTo(Version("0.0.5")) //return 1

Why does writeObject throw java.io.NotSerializableException and how do I fix it?

java.io.NotSerializableException can occur when you serialize an inner class instance because:

serializing such an inner class instance will result in serialization of its associated outer class instance as well

Serialization of inner classes (i.e., nested classes that are not static member classes), including local and anonymous classes, is strongly discouraged

Ref: The Serializable Interface

Checkout another branch when there are uncommitted changes on the current branch

I have faced the same question recently. What I understand is, if the branch you are checking in has a file which you modified and it happens to be also modified and committed by that branch. Then git will stop you from switching to the branch to keep your change safe before you commit or stash.

The value violated the integrity constraints for the column

As a slight alternative to @FazianMubasher's answer, instead of allowing NULL for the specified column (which may for many reasons not be possible), you could also add a Conditional Split Task to branch NULL values to an error file, or just to ignore them:

enter image description here

enter image description here

Calling other function in the same controller?

Yes. Problem is in wrong notation. Use:

$this->sendRequest($uri)

Instead. Or

self::staticMethod()

for static methods. Also read this for getting idea of OOP - http://www.php.net/manual/en/language.oop5.basic.php

x86 Assembly on a Mac

As stated before, don't use syscall. You can use standard C library calls though, but be aware that the stack MUST be 16 byte aligned per Apple's IA32 function call ABI.

If you don't align the stack, your program will crash in __dyld_misaligned_stack_error when you make a call into any of the libraries or frameworks.

The following snippet assembles and runs on my system:

; File: hello.asm
; Build: nasm -f macho hello.asm && gcc -o hello hello.o

SECTION .rodata
hello.msg db 'Hello, World!',0x0a,0x00

SECTION .text

extern _printf ; could also use _puts...
GLOBAL _main

; aligns esp to 16 bytes in preparation for calling a C library function
; arg is number of bytes to pad for function arguments, this should be a multiple of 16
; unless you are using push/pop to load args
%macro clib_prolog 1
    mov ebx, esp        ; remember current esp
    and esp, 0xFFFFFFF0 ; align to next 16 byte boundary (could be zero offset!)
    sub esp, 12         ; skip ahead 12 so we can store original esp
    push ebx            ; store esp (16 bytes aligned again)
    sub esp, %1         ; pad for arguments (make conditional?)
%endmacro

; arg must match most recent call to clib_prolog
%macro clib_epilog 1
    add esp, %1         ; remove arg padding
    pop ebx             ; get original esp
    mov esp, ebx        ; restore
%endmacro

_main:
    ; set up stack frame
    push ebp
    mov ebp, esp
    push ebx

    clib_prolog 16
    mov dword [esp], hello.msg
    call _printf
    ; can make more clib calls here...
    clib_epilog 16

    ; tear down stack frame
    pop ebx
    mov esp, ebp
    pop ebp
    mov eax, 0          ; set return code
    ret

Sys is undefined

This is going to sound stupid but I had a similar problem with a site being developed in VS2010 and hosted in the VS Dev Server. The page in question had a scriptmanager to create the connection to a wcf service. I added an extra method to the service and this error started appearing.

What fixed it for me was changing from 'Auto-assign Port' to 'Specific port' with a different port number in the oroject Web settings.

I wish I knew why...

How to specify multiple return types using type-hints

Python 3.10 (use |): Example for a function which takes a single argument that is either an int or str and returns either an int or str:

def func(arg: int | str) -> int | str:
              ^^^^^^^^^     ^^^^^^^^^ 
             type of arg   return type

Python 3.5 - 3.9 (use typing.Union):

from typing import Union
def func(arg: Union[int, str]) -> Union[int, str]:
              ^^^^^^^^^^^^^^^     ^^^^^^^^^^^^^^^ 
                type of arg         return type

For the special case of X | None you can use Optional[X].

How do I center an SVG in a div?

None of these answers worked for me. This is how I did it.

position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);

How to download source in ZIP format from GitHub?

In chrome, if you hover your cursor on Download ZIP it will give you the link at the bottom of the browser

enter image description here

How to Git stash pop specific stash in 1.8.3?

First check the list:-

git stash list

copy the index you wanted to pop from the stash list

git stash pop stash@{index_number}

eg.:

git stash pop stash@{1}

Get random sample from list while maintaining ordering of items?

Maybe you can just generate the sample of indices and then collect the items from your list.

randIndex = random.sample(range(len(mylist)), sample_size)
randIndex.sort()
rand = [mylist[i] for i in randIndex]

Call asynchronous method in constructor?

A quick way to execute some time-consuming operation in any constructor is by creating an action and run them asynchronously.

new Action( async() => await InitializeThingsAsync())();

Running this piece of code will neither block your UI nor leave you with any loose threads. And if you need to update any UI (considering you are not using MVVM approach), you can use the Dispatcher to do so as many have suggested.

A Note: This option only provides you a way to start an execution of a method from the constructor if you don't have any init or onload or navigated overrides. Most likely this will keep on running even after the construction has been completed. Hence the result of this method call may NOT be available in the constructor itself.

Jquery/Ajax call with timer

If you want to set something on a timer, you can use JavaScript's setTimeout or setInterval methods:

setTimeout ( expression, timeout );
setInterval ( expression, interval );

Where expression is a function and timeout and interval are integers in milliseconds. setTimeout runs the timer once and runs the expression once whereas setInterval will run the expression every time the interval passes.

So in your case it would work something like this:

setInterval(function() {
    //call $.ajax here
}, 5000); //5 seconds

As far as the Ajax goes, see jQuery's ajax() method. If you run an interval, there is nothing stopping you from calling the same ajax() from other places in your code.


If what you want is for an interval to run every 30 seconds until a user initiates a form submission...and then create a new interval after that, that is also possible:

setInterval() returns an integer which is the ID of the interval.

var id = setInterval(function() {
    //call $.ajax here
}, 30000); // 30 seconds

If you store that ID in a variable, you can then call clearInterval(id) which will stop the progression.

Then you can reinstantiate the setInterval() call after you've completed your ajax form submission.

String replacement in Objective-C

NSString *stringreplace=[yourString stringByReplacingOccurrencesOfString:@"search" withString:@"new_string"];

How to set OnClickListener on a RadioButton in Android?

RadioGroup radioGroup = (RadioGroup) findViewById(R.id.yourRadioGroup);     
    radioGroup.setOnClickListener(v -> {
                        // get selected radio button from radioGroup
                        int selectedId = radioGroup.getCheckedRadioButtonId();
                        // find the radiobutton by returned id
                        radioButton =  findViewById(selectedId);
                        String slectedValue=radioButton.getText()          
        });

No shadow by default on Toolbar?

In my situation elevation doesn't work well because I haven't given any background to the toolbar. Try giving background color to the toolbar then set elevation and it will work well.

Why is ZoneOffset.UTC != ZoneId.of("UTC")?

The answer comes from the javadoc of ZoneId (emphasis mine) ...

A ZoneId is used to identify the rules used to convert between an Instant and a LocalDateTime. There are two distinct types of ID:

  • Fixed offsets - a fully resolved offset from UTC/Greenwich, that uses the same offset for all local date-times
  • Geographical regions - an area where a specific set of rules for finding the offset from UTC/Greenwich apply

Most fixed offsets are represented by ZoneOffset. Calling normalized() on any ZoneId will ensure that a fixed offset ID will be represented as a ZoneOffset.

... and from the javadoc of ZoneId#of (emphasis mine):

This method parses the ID producing a ZoneId or ZoneOffset. A ZoneOffset is returned if the ID is 'Z', or starts with '+' or '-'.

The argument id is specified as "UTC", therefore it will return a ZoneId with an offset, which also presented in the string form:

System.out.println(now.withZoneSameInstant(ZoneOffset.UTC));
System.out.println(now.withZoneSameInstant(ZoneId.of("UTC")));

Outputs:

2017-03-10T08:06:28.045Z
2017-03-10T08:06:28.045Z[UTC]

As you use the equals method for comparison, you check for object equivalence. Because of the described difference, the result of the evaluation is false.

When the normalized() method is used as proposed in the documentation, the comparison using equals will return true, as normalized() will return the corresponding ZoneOffset:

Normalizes the time-zone ID, returning a ZoneOffset where possible.

now.withZoneSameInstant(ZoneOffset.UTC)
    .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())); // true

As the documentation states, if you use "Z" or "+0" as input id, of will return the ZoneOffset directly and there is no need to call normalized():

now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("Z"))); //true
now.withZoneSameInstant(ZoneOffset.UTC).equals(now.withZoneSameInstant(ZoneId.of("+0"))); //true

To check if they store the same date time, you can use the isEqual method instead:

now.withZoneSameInstant(ZoneOffset.UTC)
    .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))); // true

Sample

System.out.println("equals - ZoneId.of(\"UTC\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC"))));
System.out.println("equals - ZoneId.of(\"UTC\").normalized(): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("UTC").normalized())));
System.out.println("equals - ZoneId.of(\"Z\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("Z"))));
System.out.println("equals - ZoneId.of(\"+0\"): " + nowZoneOffset
        .equals(now.withZoneSameInstant(ZoneId.of("+0"))));
System.out.println("isEqual - ZoneId.of(\"UTC\"): "+ nowZoneOffset
        .isEqual(now.withZoneSameInstant(ZoneId.of("UTC"))));

Output:

equals - ZoneId.of("UTC"): false
equals - ZoneId.of("UTC").normalized(): true
equals - ZoneId.of("Z"): true
equals - ZoneId.of("+0"): true
isEqual - ZoneId.of("UTC"): true

How to use Scanner to accept only valid int as input

What you could do is also to take the next token as a String, converts this string to a char array and test that each character in the array is a digit.

I think that's correct, if you don't want to deal with the exceptions.

event.preventDefault() function not working in IE

return false in your listener should work in all browsers.

$('orderNowForm').addEvent('submit', function () {
    // your code
    return false;
}

How to exclude a directory in find . command

The -path -prune approach also works with wildcards in the path. Here is a find statement that will find the directories for a git server serving multiple git repositiories leaving out the git internal directories:

find . -type d \
   -not \( -path */objects -prune \) \
   -not \( -path */branches -prune \) \
   -not \( -path */refs -prune \) \
   -not \( -path */logs -prune \) \
   -not \( -path */.git -prune \) \
   -not \( -path */info -prune \) \
   -not \( -path */hooks -prune \)  

How to read one single line of csv data in Python?

Just for reference, a for loop can be used after getting the first row to get the rest of the file:

with open('file.csv', newline='') as f:
    reader = csv.reader(f)
    row1 = next(reader)  # gets the first line
    for row in reader:
        print(row)       # prints rows 2 and onward

Android set bitmap to Imageview

this code works with me

 ImageView carView = (ImageView) v.findViewById(R.id.car_icon);

                            byte[] decodedString = Base64.decode(picture, Base64.NO_WRAP);
                            InputStream input=new ByteArrayInputStream(decodedString);
                            Bitmap ext_pic = BitmapFactory.decodeStream(input);
                            carView.setImageBitmap(ext_pic);

How to return value from function which has Observable subscription inside?

While the previous answers may work in a fashion, I think that using BehaviorSubject is the correct way if you want to continue using observables.

Example:

    this.store.subscribe(
        (data:any) => {
            myService.myBehaviorSubject.next(data)
        }
    )

In the Service:

let myBehaviorSubject = new BehaviorSubjet(value);

In component.ts:

this.myService.myBehaviorSubject.subscribe(data => this.myData = data)

I hope this helps!

Set Content-Type to application/json in jsp file

You can do via Page directive.

For example:

<%@ page language="java" contentType="application/json; charset=UTF-8"
    pageEncoding="UTF-8"%>
  • contentType="mimeType [ ;charset=characterSet ]" | "text/html;charset=ISO-8859-1"

The MIME type and character encoding the JSP file uses for the response it sends to the client. You can use any MIME type or character set that are valid for the JSP container. The default MIME type is text/html, and the default character set is ISO-8859-1.

How can I export Excel files using JavaScript?

If you can generate the Excel file on the server, that is probably the best way. With Excel you can add formatting and get the output to look better. Several Excel options have already been mentioned. If you have a PHP backend, you might consider phpExcel.

If you are trying to do everything on the client in javascript, I don't think Excel is an option. You could create a CSV file and create a data URL to allow the user to download it.

I created a JSFiddle to demonstrate: http://jsfiddle.net/5KRf6/3/

This javascript (assuming you are using jQuery) will take the values out of input boxes in a table and build a CSV formatted string:

var csv = "";
$("table").find("tr").each(function () {
    var sep = "";
    $(this).find("input").each(function () {
        csv += sep + $(this).val();
        sep = ",";
    });
    csv += "\n";
});

If you wish, you can drop the data into a tag on the page (in my case a tag with an id of "csv"):

$("#csv").text(csv);

You can generate a URL to that text with this code:

window.URL = window.URL || window.webkiURL;
var blob = new Blob([csv]);
var blobURL = window.URL.createObjectURL(blob);

Finally, this will add a link to download that data:

$("#downloadLink").html("");
$("<a></a>").
attr("href", blobURL).
attr("download", "data.csv").
text("Download Data").
appendTo('#downloadLink');

Reading an image file in C/C++

Try out the CImg library. The tutorial will help you get familiarized. Once you have a CImg object, the data() function will give you access to the 2D pixel buffer array.

How to check if string input is a number?

Here is a simple function that checks input for INT and RANGE. Here, returns 'True' if input is integer between 1-100, 'False' otherwise

def validate(userInput):

    try:
        val = int(userInput)
        if val > 0 and val < 101:
            valid = True
        else:
            valid = False

    except Exception:
        valid = False

    return valid

Disable all gcc warnings

-w is the GCC-wide option to disable warning messages.

How can I pair socks from a pile efficiently?

This question is actually deeply philosophical. At heart it's about whether the power of people to solve problems (the "wetware" of our brains) is equivalent to what can be accomplished by algorithms.

An obvious algorithm for sock sorting is:

Let N be the set of socks that are still unpaired, initially empty
for each sock s taken from the dryer
  if s matches a sock t in N
    remove t from N, bundle s and t together, and throw them in the basket
  else
    add s to N

Now the computer science in this problem is all about the steps

  1. "if s pairs with a sock t in N". How quickly can we "remember" what we've seen so far?
  2. "remove t from N" and "add s to N". How expensive is keeping track of what we've seen so far?

Human beings will use various strategies to effect these. Human memory is associative, something like a hash table where feature sets of stored values are paired with the corresponding values themselves. For example, the concept of "red car" maps to all the red cars a person is capable of remembering. Someone with a perfect memory has a perfect mapping. Most people are imperfect in this regard (and most others). The associative map has a limited capacity. Mappings may bleep out of existence under various circumstances (one beer too many), be recorded in error ("I though her name was Betty, not Nettie"), or never be overwritten even though we observe that the truth has changed ("dad's car" evokes "orange Firebird" when we actually knew he'd traded that in for the red Camaro).

In the case of socks, perfect recall means looking at a sock s always produces the memory of its sibling t, including enough information (where it is on the ironing board) to locate t in constant time. A person with photographic memory accomplishes both 1 and 2 in constant time without fail.

Someone with less than perfect memory might use a few commonsense equivalence classes based on features within his capability to track: size (papa, mama, baby), color (greenish, redish, etc.), pattern (argyle, plain, etc.), style (footie, knee-high, etc.). So the ironing board would be divided into sections for the categories. This usually allows the category to be located in constant time by memory, but then a linear search through the category "bucket" is needed.

Someone with no memory or imagination at all (sorry) will just keep the socks in one pile and do a linear search of the whole pile.

A neat freak might use numeric labels for pairs as someone suggested. This opens the door to a total ordering, which allows the human to use exactly the same algorithms we might with a CPU: binary search, trees, hashes, etc.

So the "best" algorithm depends on the qualities of the wetware/hardware/software that is running it and our willingness to "cheat" by imposing a total order on pairs. Certainly a "best" meta-algorithm is to hire the worlds best sock-sorter: a person or machine that can aquire and quickly store a huge set N of sock attribute sets in a 1-1 associative memory with constant time lookup, insert, and delete. Both people and machines like this can be procured. If you have one, you can pair all the socks in O(N) time for N pairs, which is optimal. The total order tags allow you to use standard hashing to get the same result with either a human or hardware computer.

Ping a site in Python?

Here's a short snippet using subprocess. The check_call method either returns 0 for success, or raises an exception. This way, I don't have to parse the output of ping. I'm using shlex to split the command line arguments.

  import subprocess
  import shlex

  command_line = "ping -c 1 www.google.comsldjkflksj"
  args = shlex.split(command_line)
  try:
      subprocess.check_call(args,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
      print "Website is there."
  except subprocess.CalledProcessError:
      print "Couldn't get a ping."

iOS Launching Settings -> Restrictions URL Scheme

Yep, saw this (and many more), even implemented it in a test application. Really need to get the definitive word from Apple, but the community consensus opinion is Apple disallowed it in 5.1 after it was publicly "discovered/published", so applications containing it won't be accepted.

08/01/12 Update: Asked Apple through my developer account if there is a way to programmatically launch the WiFi Settings dialog. Here is the response:

"Our engineers have reviewed your request and have concluded that there is no supported way to achieve the desired functionality given the currently shipping system configurations."

HTML5 record audio to file

This is a simple JavaScript sound recorder and editor. You can try it.

https://www.danieldemmel.me/JSSoundRecorder/

Can download from here

https://github.com/daaain/JSSoundRecorder

How to delete all data from solr and hbase

From the command line use:

 bin/post -c core_name -type text/xml -out yes -d $'<delete><query>*:*</query></delete>'

How to make a vertical SeekBar in Android?

Try this

import android.content.Context;
import android.graphics.Canvas;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.SeekBar;

/**
 * Implementation of an easy vertical SeekBar, based on the normal SeekBar.
 */
public class VerticalSeekBar extends SeekBar {
    /**
     * The angle by which the SeekBar view should be rotated.
     */
    private static final int ROTATION_ANGLE = -90;

    /**
     * A change listener registrating start and stop of tracking. Need an own listener because the listener in SeekBar
     * is private.
     */
    private OnSeekBarChangeListener mOnSeekBarChangeListener;

    /**
     * Standard constructor to be implemented for all views.
     *
     * @param context The Context the view is running in, through which it can access the current theme, resources, etc.
     * @see android.view.View#View(Context)
     */
    public VerticalSeekBar(final Context context) {
        super(context);
    }

    /**
     * Standard constructor to be implemented for all views.
     *
     * @param context The Context the view is running in, through which it can access the current theme, resources, etc.
     * @param attrs   The attributes of the XML tag that is inflating the view.
     * @see android.view.View#View(Context, AttributeSet)
     */
    public VerticalSeekBar(final Context context, final AttributeSet attrs) {
        super(context, attrs);
    }

    /**
     * Standard constructor to be implemented for all views.
     *
     * @param context  The Context the view is running in, through which it can access the current theme, resources, etc.
     * @param attrs    The attributes of the XML tag that is inflating the view.
     * @param defStyle An attribute in the current theme that contains a reference to a style resource that supplies default
     *                 values for the view. Can be 0 to not look for defaults.
     * @see android.view.View#View(Context, AttributeSet, int)
     */
    public VerticalSeekBar(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    protected final void onSizeChanged(final int width, final int height, final int oldWidth, final int oldHeight) {
        super.onSizeChanged(height, width, oldHeight, oldWidth);
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    protected final synchronized void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec) {
        super.onMeasure(heightMeasureSpec, widthMeasureSpec);
        setMeasuredDimension(getMeasuredHeight(), getMeasuredWidth());
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    protected final void onDraw(@NonNull final Canvas c) {
        c.rotate(ROTATION_ANGLE);
        c.translate(-getHeight(), 0);

        super.onDraw(c);
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    public final void setOnSeekBarChangeListener(final OnSeekBarChangeListener listener) {
        // Do not use super for the listener, as this would not set the fromUser flag properly
        mOnSeekBarChangeListener = listener;
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    public final boolean onTouchEvent(@NonNull final MotionEvent event) {
        if (!isEnabled()) {
            return false;
        }

        switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            setProgressInternally(getMax() - (int) (getMax() * event.getY() / getHeight()), true);
            if (mOnSeekBarChangeListener != null) {
                mOnSeekBarChangeListener.onStartTrackingTouch(this);
            }
            break;

        case MotionEvent.ACTION_MOVE:
            setProgressInternally(getMax() - (int) (getMax() * event.getY() / getHeight()), true);
            break;

        case MotionEvent.ACTION_UP:
            setProgressInternally(getMax() - (int) (getMax() * event.getY() / getHeight()), true);
            if (mOnSeekBarChangeListener != null) {
                mOnSeekBarChangeListener.onStopTrackingTouch(this);
            }
            break;

        case MotionEvent.ACTION_CANCEL:
            if (mOnSeekBarChangeListener != null) {
                mOnSeekBarChangeListener.onStopTrackingTouch(this);
            }
            break;

        default:
            break;
        }

        return true;
    }

    /**
     * Set the progress by the user. (Unfortunately, Seekbar.setProgressInternally(int, boolean) is not accessible.)
     *
     * @param progress the progress.
     * @param fromUser flag indicating if the change was done by the user.
     */
    public final void setProgressInternally(final int progress, final boolean fromUser) {
        if (progress != getProgress()) {
            super.setProgress(progress);
            if (mOnSeekBarChangeListener != null) {
                mOnSeekBarChangeListener.onProgressChanged(this, progress, fromUser);
            }
        }
        onSizeChanged(getWidth(), getHeight(), 0, 0);
    }

    /*
     * (non-Javadoc) ${see_to_overridden}
     */
    @Override
    public final void setProgress(final int progress) {
        setProgressInternally(progress, false);
    }
}

Using stored procedure output parameters in C#

Before changing stored procedure please check what is the output of your current one. In SQL Server Management run following:

DECLARE @NewId int
EXEC    @return_value = [dbo].[usp_InsertContract]
            N'Gary',
            @NewId OUTPUT
SELECT  @NewId

See what it returns. This may give you some hints of why your out param is not filled.

PHP UML Generator

Here's how I did it (directly from code to PDF drawing without manual drawing of anything):

  1. Use BOUML for "reverse engineering PHP code" [sic] to extract the class model (BOUML is available from "universe" repository of Ubuntu). I seriously recommend BOUML for this step because it's really fast compared to many other programs I have tried. In addition, it seems that BOUML seems to extract the model correctly (for the parts that BOUML even tries to extract).
  2. Use BOUML to export model as XMI 1.4 file
  3. Use ArgoUML to import said XMI file (you can use webstart version for this step)
  4. Export XMI from ArgoUML (I don't know which XMI version/variant the output is but it is not the same result as the output from BOUML. The argouml-graphviz cannot handle XMI file directly from BOUML).
  5. Use argouml-graphviz to convert ArgoUML exported XMI file to dot format (you may need to use saxon instead of xsltproc to get it work due to use of XSLT2)
  6. Use dot or fdp or sfdp to render the class diagram.

Here's an example of suitable command line for using fdp to output PDF diagram (assuming that dot file generated by argouml-graphviz XLST processing is saved as xmi-model.dot):

fdp -Tpdf -Gmaxiter=1000 -Gmindist=0.5 -Gpackmode=node \
  -Eweight=0.05 -Elen=1.0 -Eminlen=1.0 -Gsplines=true \
  -Goverlap=false xmi-model.dot -oxmi-model.pdf

As an alternative you could try PHP_UML or php2xmi instead of BOUML for doing the "reverse engineering" part. I haven't yet tried that.

(I'm using the phrase "reverse engineering" because it seems that UML people are using those words when they mean extracting class and method information from the source code. I would personally interpret those words as extracting information from executable binary file or captured raw wire data.)

If you prefer drawing the class diagram by hand (instead of using computer to do all the drawing), you can use either BOUML or ArgoUML for the drawing. Using the "reverse engineered" data via BOUML will help in that case.

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Html.Partial: returns MvcHtmlString and slow

Html.RenderPartial: directly render/write on output stream and returns void and it's very fast in comparison to Html.Partial

Get Number of Rows returned by ResultSet in Java

You may think JDBC is a rich API and ResultSet has got so many methods then why not just a getCount() method? Well, For many databases e.g. Oracle, MySQL and SQL Server, ResultSet is a streaming API, this means that it does not load (or maybe even fetch) all the rows from the database server. By iterating to the end of the ResultSet you may add significantly to the time taken to execute in certain cases.

Btw, if you have to there are a couple of ways to do it e.g. by using ResultSet.last() and ResultSet.getRow() method, that's not the best way to do it but it works if you absolutely need it.

Though, getting the column count from a ResultSet is easy in Java. The JDBC API provides a ResultSetMetaData class which contains methods to return the number of columns returned by a query and hold by ResultSet.

Specify the from user when sending email using the mail command

echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -- -f [email protected] -F "Elvis Presley"

or

echo "This is the main body of the mail" | mail -s "Subject of the Email" [email protected] -aFrom:"Elvis Presley<[email protected]>"

Could not load file or assembly "System.Net.Http, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

The only way that cleanly solved this issue for me (.NET 4.6.1) was to not only add a Nuget reference to System.Net.Http V4.3.4 for the project that actually used System.Net.Http, but also to the startup project (a test project in my case).

(Which is strange, because the correct System.Net.Http.dll existed in the bin directory of the test project and the .config assemblyBingings looked OK, too.)

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

Place this line before the closing script tag,writing from memory:

window.onload  = GetTimeZoneOffset;

i think the question is how to call the javascript function on pageload

What is the first character in the sort order used by Windows Explorer?

The first visible character is '!' according to ASCII table.And the last one is '~' So "!file.doc" or "~file.doc' will be the top one depending your ranking order. You can check the ascii table here: http://www.asciitable.com/

Edit: This answer is based on the opinion of the author and not facts.

In Objective-C, how do I test the object type?

Simple, [yourobject class] it will return the class name of yourobject.

MessageBox with YesNoCancel - No & Cancel triggers same event

The way I use a yes/no prompt is:

If MsgBox("Are you sure?", MsgBoxStyle.YesNo) <> MsgBoxResults.Yes Then
    Exit Sub
End If

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Compare a string using sh shell

eq is used to compare integers use equal '=' instead , example:

if [ 'AAA' = 'ABC' ];
then 
    echo "the same" 
else 
    echo "not the same"
fi

good luck

get next and previous day with PHP

Php script -1****its to Next Date

<?php

$currentdate=date('Y-m-d');


$date_arr=explode('-',$currentdate);


$next_date=
Date("Y-m-d",mktime(0,0,0,$date_arr[1],$date_arr[2]+1,$date_arr[0]));



echo $next_date;
?>**

**Php script -1****its to Next year**


<?php

$currentdate=date('Y-m-d');


$date_arr=explode('-',$currentdate);


$next_date=
Date("Y-m-d",mktime(0,0,0,$date_arr[1],$date_arr[2],$date_arr[0]+1));



echo $next_date;
?>

DataGridView changing cell background color

If you are still intrested in why this didn't work for you at first:

The reason you don't see changes you've made to the cell's style is because you do these changes before the form was shown, and so they are disregarded.

Changing cell styles in the events suggested here will do the job, but they are called multiple times causing your style changes to happen more times than you wish, and so aren't very efficient.

To solve this, either change the style after the point in your code in which the form is shown, or subscribe to the Shown event, and place your changes there (this is event is called significantly less than the other events suggested).

null terminating a string

'\0' is the way to go. It's a character, which is what's wanted in a string and has the null value.

When we say null terminated string in C/C++, it really means 'zero terminated string'. The NULL macro isn't intended for use in terminating strings.

PHP read and write JSON from file

When you want to create json format it had to be in this format for it to read:

[ 
  {
    "":"",
    "":[
     {
       "":"",
       "":""
     }
    ]
  }
]

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

Today i also face this type of problem during visual studio 2015 Community installation. As i have 64bit OS. I used https://www.microsoft.com/en-us/download/details.aspx?id=49093 link to update KB2999226 mannualy.

Try It. Good luck.

How to Select a substring in Oracle SQL up to a specific character?

Remember this if all your Strings in the column do not have an underscore (...or else if null value will be the output):

SELECT COALESCE
(SUBSTR("STRING_COLUMN" , 0, INSTR("STRING_COLUMN", '_')-1), 
"STRING_COLUMN") 
AS OUTPUT FROM DUAL

What is the difference between using constructor vs getInitialState in React / React Native?

The big difference is start from where they are coming from, so constructor is the constructor of your class in JavaScript, on the other side, getInitialState is part of the lifecycle of React . The constructor method is a special method for creating and initializing an object created with a class.

Split pandas dataframe in two if it has more than 10 rows

You can use the DataFrame head and tail methods as syntactic sugar instead of slicing/loc here. I use a split size of 3; for your example use headSize=10

def split(df, headSize) :
    hd = df.head(headSize)
    tl = df.tail(len(df)-headSize)
    return hd, tl

df = pd.DataFrame({    'A':[2,4,6,8,10,2,4,6,8,10],
                       'B':[10,-10,0,20,-10,10,-10,0,20,-10],
                       'C':[4,12,8,0,0,4,12,8,0,0],
                      'D':[9,10,0,1,3,np.nan,np.nan,np.nan,np.nan,np.nan]})

# Split dataframe into top 3 rows (first) and the rest (second)
first, second = split(df, 3)

Android - drawable with rounded corners at the top only

In my case below code

    <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="10dp" android:bottom="-10dp"
        >

        <shape android:shape="rectangle">
            <solid android:color="@color/maincolor" />

            <corners
                android:topLeftRadius="10dp"
                android:topRightRadius="10dp"
                android:bottomLeftRadius="0dp"
                android:bottomRightRadius="0dp"
            />
        </shape>

    </item>
    </layer-list>

In Python how should I test if a variable is None, True or False

I believe that throwing an exception is a better idea for your situation. An alternative will be the simulation method to return a tuple. The first item will be the status and the second one the result:

result = simulate(open("myfile"))
if not result[0]:
  print "error parsing stream"
else:
  ret= result[1]

JavaScript closure inside loops – simple practical example

Here's a simple solution that uses forEach (works back to IE9):

_x000D_
_x000D_
var funcs = [];_x000D_
[0,1,2].forEach(function(i) {          // let's create 3 functions_x000D_
    funcs[i] = function() {            // and store them in funcs_x000D_
        console.log("My value: " + i); // each should log its value._x000D_
    };_x000D_
})_x000D_
for (var j = 0; j < 3; j++) {_x000D_
    funcs[j]();                        // and now let's run each one to see_x000D_
}
_x000D_
_x000D_
_x000D_

Prints:

My value: 0
My value: 1
My value: 2

ASP.NET Web Api: The requested resource does not support http method 'GET'

My issue was as simple as having a null reference that didn't show up in the returned message, I had to debug my API to see it.

TypeError: 'float' object is not callable

There is an operator missing, likely a *:

-3.7 need_something_here (prof[x])

The "is not callable" occurs because the parenthesis -- and lack of operator which would have switched the parenthesis into precedence operators -- make Python try to call the result of -3.7 (a float) as a function, which is not allowed.

The parenthesis are also not needed in this case, the following may be sufficient/correct:

-3.7 * prof[x]

As Legolas points out, there are other things which may need to be addressed:

2.25 * (1 - math.pow(math.e, (-3.7(prof[x])/2.25))) * (math.e, (0/2.25)))
                                  ^-- op missing
                                                    extra parenthesis --^
               valid but questionable float*tuple --^
                                     expression yields 0.0 always --^

javascript regular expression to not match a word

function test(string) {
    return ! string.match(/abc|def/);
}

How to get am pm from the date time string using moment js

You are using the wrong format tokens when parsing your input. You should use ddd for an abbreviation of the name of day of the week, DD for day of the month, MMM for an abbreviation of the month's name, YYYY for the year, hh for the 1-12 hour, mm for minutes and A for AM/PM. See moment(String, String) docs.

Here is a working live sample:

_x000D_
_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Add new column with foreign key constraint in one command

In Oracle :

ALTER TABLE one ADD two_id INTEGER CONSTRAINT Fk_two_id REFERENCES two(id);

What is the proper way to test if a parameter is empty in a batch file?

To sum things up:

set str=%~1
if not defined str ( echo Empty string )

This code will output "Empty string" if %1 is either "" or " or empty. Added it to the accepted answer that's currently incorrect.

Matplotlib color according to class labels

A simple solution is to assign color for each class. This way, we can control how each color is for each class. For example:

arr1 = [1, 2, 3, 4, 5]
arr2 = [2, 3, 3, 4, 4]
labl = [0, 1, 1, 0, 0]
color= ['red' if l == 0 else 'green' for l in labl]
plt.scatter(arr1, arr2, color=color)

Source file 'Properties\AssemblyInfo.cs' could not be found

I got the error using TFS, my AssemblyInfo wasn't mapped in the branch I was working on.

SQLAlchemy default DateTime

Calculate timestamps within your DB, not your client

For sanity, you probably want to have all datetimes calculated by your DB server, rather than the application server. Calculating the timestamp in the application can lead to problems because network latency is variable, clients experience slightly different clock drift, and different programming languages occasionally calculate time slightly differently.

SQLAlchemy allows you to do this by passing func.now() or func.current_timestamp() (they are aliases of each other) which tells the DB to calculate the timestamp itself.

Use SQLALchemy's server_default

Additionally, for a default where you're already telling the DB to calculate the value, it's generally better to use server_default instead of default. This tells SQLAlchemy to pass the default value as part of the CREATE TABLE statement.

For example, if you write an ad hoc script against this table, using server_default means you won't need to worry about manually adding a timestamp call to your script--the database will set it automatically.

Understanding SQLAlchemy's onupdate/server_onupdate

SQLAlchemy also supports onupdate so that anytime the row is updated it inserts a new timestamp. Again, best to tell the DB to calculate the timestamp itself:

from sqlalchemy.sql import func

time_created = Column(DateTime(timezone=True), server_default=func.now())
time_updated = Column(DateTime(timezone=True), onupdate=func.now())

There is a server_onupdate parameter, but unlike server_default, it doesn't actually set anything serverside. It just tells SQLalchemy that your database will change the column when an update happens (perhaps you created a trigger on the column ), so SQLAlchemy will ask for the return value so it can update the corresponding object.

One other potential gotcha:

You might be surprised to notice that if you make a bunch of changes within a single transaction, they all have the same timestamp. That's because the SQL standard specifies that CURRENT_TIMESTAMP returns values based on the start of the transaction.

PostgreSQL provides the non-SQL-standard statement_timestamp() and clock_timestamp() which do change within a transaction. Docs here: https://www.postgresql.org/docs/current/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT

UTC timestamp

If you want to use UTC timestamps, a stub of implementation for func.utcnow() is provided in SQLAlchemy documentation. You need to provide appropriate driver-specific functions on your own though.

How do you create a UIImage View Programmatically - Swift

This answer is update to Swift 3.

This is how you can add an image view programmatically where you can control the constraints.

Class ViewController: UIViewController {

    let someImageView: UIImageView = {
       let theImageView = UIImageView()
       theImageView.image = UIImage(named: "yourImage.png")
       theImageView.translatesAutoresizingMaskIntoConstraints = false //You need to call this property so the image is added to your view
       return theImageView
    }()

    override func viewDidLoad() {
       super.viewDidLoad()

       view.addSubview(someImageView) //This add it the view controller without constraints
       someImageViewConstraints() //This function is outside the viewDidLoad function that controls the constraints
    }

    // do not forget the `.isActive = true` after every constraint
    func someImageViewConstraints() {
        someImageView.widthAnchor.constraint(equalToConstant: 180).isActive = true
        someImageView.heightAnchor.constraint(equalToConstant: 180).isActive = true
        someImageView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
        someImageView.centerYAnchor.constraint(equalTo: view.centerYAnchor, constant: 28).isActive = true
    }

}

Find a class somewhere inside dozens of JAR files?

I've always used this on Windows and its worked exceptionally well.

findstr /s /m /c:"package/classname" *.jar, where

findstr.exe comes standard with Windows and the params:

  • /s = recursively
  • /m = print only the filename if there is a match
  • /c = literal string (in this case your package name + class names separated by '/')

Hope this helps someone.

How to pass an object from one activity to another on Android

One option could be letting your custom class implement the Serializable interface and then you can pass object instances in the intent extra using the putExtra(Serializable..) variant of the Intent#putExtra() method.

Pseudocode:

//To pass:
intent.putExtra("MyClass", obj);

// To retrieve object in second Activity
getIntent().getSerializableExtra("MyClass");

Note: Make sure each nested class of your main custom class has implemented Serializable interface to avoid any serialization exceptions. For example:

class MainClass implements Serializable {

    public MainClass() {}

    public static class ChildClass implements Serializable {

        public ChildClass() {}
    }
}

Error TF30063: You are not authorized to access ... \DefaultCollection

The TFS Preview login apparently uses Internet Explorer and thus might conflict with other MS Accounts you are using. Fully clearing the IE cache seems to work for me. After the cache clearing, I get to the correct login screen and may enter my credentials as needed.

Event on a disabled input

I find another solution:

<input type="text" class="disabled" name="test" value="test" />

Class "disabled" immitate disabled element by opacity:

<style type="text/css">
    input.disabled {
        opacity: 0.5;
    }
</style>

And then cancel the event if element is disabled and remove class:

$(document).on('click','input.disabled',function(event) {
    event.preventDefault();
    $(this).removeClass('disabled');
});

Return multiple values in JavaScript?

A very common way to return multiple values in javascript is using an object literals, so something like:

const myFunction = () => {
  const firstName = "Alireza", 
        familyName = "Dezfoolian",
        age = 35;
  return { firstName, familyName, age};
}

and get the values like this:

myFunction().firstName; //Alireza
myFunction().familyName; //Dezfoolian
myFunction().age; //age

or even a shorter way:

const {firstName, familyName, age} = myFunction();

and get them individually like:

firstName; //Alireza
familyName; //Dezfoolian
age; //35

How to choose the id generation strategy when using JPA and Hibernate

The API Doc are very clear on this.

All generators implement the interface org.hibernate.id.IdentifierGenerator. This is a very simple interface. Some applications can choose to provide their own specialized implementations, however, Hibernate provides a range of built-in implementations. The shortcut names for the built-in generators are as follows:

increment

generates identifiers of type long, short or int that are unique only when no other process is inserting data into the same table. Do not use in a cluster.

identity

supports identity columns in DB2, MySQL, MS SQL Server, Sybase and HypersonicSQL. The returned identifier is of type long, short or int.

sequence

uses a sequence in DB2, PostgreSQL, Oracle, SAP DB, McKoi or a generator in Interbase. The returned identifier is of type long, short or int

hilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a table and column (by default hibernate_unique_key and next_hi respectively) as a source of hi values. The hi/lo algorithm generates identifiers that are unique only for a particular database.

seqhilo

uses a hi/lo algorithm to efficiently generate identifiers of type long, short or int, given a named database sequence.

uuid

uses a 128-bit UUID algorithm to generate identifiers of type string that are unique within a network (the IP address is used). The UUID is encoded as a string of 32 hexadecimal digits in length.

guid

uses a database-generated GUID string on MS SQL Server and MySQL.

native

selects identity, sequence or hilo depending upon the capabilities of the underlying database.

assigned

lets the application assign an identifier to the object before save() is called. This is the default strategy if no element is specified.

select

retrieves a primary key, assigned by a database trigger, by selecting the row by some unique key and retrieving the primary key value.

foreign

uses the identifier of another associated object. It is usually used in conjunction with a primary key association.

sequence-identity

a specialized sequence generation strategy that utilizes a database sequence for the actual value generation, but combines this with JDBC3 getGeneratedKeys to return the generated identifier value as part of the insert statement execution. This strategy is only supported on Oracle 10g drivers targeted for JDK 1.4. Comments on these insert statements are disabled due to a bug in the Oracle drivers.

If you are building a simple application with not much concurrent users, you can go for increment, identity, hilo etc.. These are simple to configure and did not need much coding inside the db.

You should choose sequence or guid depending on your database. These are safe and better because the id generation will happen inside the database.

Update: Recently we had an an issue with idendity where primitive type (int) this was fixed by using warapper type (Integer) instead.

Margin-Top not working for span element?

span is an inline element that doesn't support vertical margins. Put the margin on the outer div instead.

Convert varchar into datetime in SQL Server

This seems the easiest way..

SELECT REPLACE(CONVERT(CHAR(10), GETDATE(), 110),'-','')

How to deal with floating point number precision in JavaScript?

Threw this together based on @SheetJs's answer, which I liked:

_x000D_
_x000D_
  getCorrectionFactor(numberToCheck: number): number {_x000D_
    var correctionFactor: number = 1;_x000D_
    _x000D_
    if (!Number.isInteger(numberToCheck)) {_x000D_
      while (!Number.isInteger(numberToCheck)) {_x000D_
        correctionFactor *= 10;_x000D_
        numberToCheck *= correctionFactor;_x000D_
      }_x000D_
    }_x000D_
_x000D_
    return correctionFactor;_x000D_
  }
_x000D_
_x000D_
_x000D_

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

Choosing a file in Python with simple Dialog

How about using tkinter?

from Tkinter import Tk     # from tkinter import Tk for Python 3.x
from tkinter.filedialog import askopenfilename

Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
filename = askopenfilename() # show an "Open" dialog box and return the path to the selected file
print(filename)

Done!

Grant execute permission for a user on all stored procedures in database?

This is a solution that means that as you add new stored procedures to the schema, users can execute them without having to call grant execute on the new stored procedure:

IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'asp_net')
DROP USER asp_net
GO

IF  EXISTS (SELECT * FROM sys.database_principals 
WHERE name = N'db_execproc' AND type = 'R')
DROP ROLE [db_execproc]
GO

--Create a database role....
CREATE ROLE [db_execproc] AUTHORIZATION [dbo]
GO

--...with EXECUTE permission at the schema level...
GRANT EXECUTE ON SCHEMA::dbo TO db_execproc;
GO

--http://www.patrickkeisler.com/2012/10/grant-execute-permission-on-all-stored.html
--Any stored procedures that are created in the dbo schema can be 
--executed by users who are members of the db_execproc database role

--...add a user e.g. for the NETWORK SERVICE login that asp.net uses
CREATE USER asp_net 
FOR LOGIN [NT AUTHORITY\NETWORK SERVICE] 
WITH DEFAULT_SCHEMA=[dbo]
GO

--...and add them to the roles you need
EXEC sp_addrolemember N'db_execproc', 'asp_net';
EXEC sp_addrolemember N'db_datareader', 'asp_net';
EXEC sp_addrolemember N'db_datawriter', 'asp_net';
GO

Reference: Grant Execute Permission on All Stored Procedures

Java associative-array

Use ArrayList < Map < String, String > >

Here a code sample :

ArrayList<Map<String, String>> products = new ArrayList<Map<String, String>>();
while (iterator.hasNext()) {
         Map<String, String> product = new HashMap<String, String>();
         Element currentProduct = iterator.next();
         product.put("id",currentProduct.get("id"));
         product.put("name" , currentProduct.get("name") );
         products.add(product );
}
System.out.println("products : " + products);

Output :

products : [{id=0001, name=prod1}, {id=0002, name=prod2}]

Fastest way to remove non-numeric characters from a VARCHAR in SQL Server

I know it is late to the game, but here is a function that I created for T-SQL that quickly removes non-numeric characters. Of note, I have a schema "String" that I put utility functions for strings into...

CREATE FUNCTION String.ComparablePhone( @string nvarchar(32) ) RETURNS bigint AS
BEGIN
    DECLARE @out bigint;

-- 1. table of unique characters to be kept
    DECLARE @keepers table ( chr nchar(1) not null primary key );
    INSERT INTO @keepers ( chr ) VALUES (N'0'),(N'1'),(N'2'),(N'3'),(N'4'),(N'5'),(N'6'),(N'7'),(N'8'),(N'9');

-- 2. Identify the characters in the string to remove
    WITH found ( id, position ) AS
    (
        SELECT 
            ROW_NUMBER() OVER (ORDER BY (n1+n10) DESC), -- since we are using stuff, for the position to continue to be accurate, start from the greatest position and work towards the smallest
            (n1+n10)
        FROM 
            (SELECT 0 AS n1 UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) AS d1,
            (SELECT 0 AS n10 UNION SELECT 10 UNION SELECT 20 UNION SELECT 30) AS d10
        WHERE
            (n1+n10) BETWEEN 1 AND len(@string)
            AND substring(@string, (n1+n10), 1) NOT IN (SELECT chr FROM @keepers)
    )
-- 3. Use stuff to snuff out the identified characters
    SELECT 
        @string = stuff( @string, position, 1, '' )
    FROM 
        found
    ORDER BY
        id ASC; -- important to process the removals in order, see ROW_NUMBER() above

-- 4. Try and convert the results to a bigint   
    IF len(@string) = 0
        RETURN NULL; -- an empty string converts to 0

    RETURN convert(bigint,@string); 
END

Then to use it to compare for inserting, something like this;

INSERT INTO Contacts ( phone, first_name, last_name )
SELECT i.phone, i.first_name, i.last_name
FROM Imported AS i
LEFT JOIN Contacts AS c ON String.ComparablePhone(c.phone) = String.ComparablePhone(i.phone)
WHERE c.phone IS NULL -- Exclude those that already exist

How to set full calendar to a specific start date when it's initialized for the 1st time?

This can be used in v5.3.2 to goto a date after initialization

calendar.gotoDate( '2020-09-12' );

eg on datepicker change

var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
     ...
     initialDate: '2020-09-02',
     ...
});    

$(".date-picker").change(function(){
     var date = $(this).val();
     calendar.gotoDate( date );
});

Why maven settings.xml file is not there?

You can verify where your Setting.xml is by pressing shortcut Ctrl+3, you will see Quick Access on top right side of Eclipse, then search setting.xml in searchbox. If you got setting.xml it will show up in search. Click that, and it will open the window showing directory path wherever it is stored. Your Maven Global Settings should be as such:

Global Setting C:\maven\apache-maven-3.5.0\conf\settings.xml
User Setting %userprofile%\\.m2\setting.xml
You can use global setting usually and leave the second option user setting untouched. Store your setting.xml in Global Setting

What is the boundary in multipart/form-data?

The exact answer to the question is: yes, you can use an arbitrary value for the boundary parameter, given it does not exceed 70 bytes in length and consists only of 7-bit US-ASCII (printable) characters.

If you are using one of multipart/* content types, you are actually required to specify the boundary parameter in the Content-Type header, otherwise the server (in the case of an HTTP request) will not be able to parse the payload.

You probably also want to set the charset parameter to UTF-8 in your Content-Type header, unless you can be absolutely sure that only US-ASCII charset will be used in the payload data.

A few relevant excerpts from the RFC2046:

  • 4.1.2. Charset Parameter:

    Unlike some other parameter values, the values of the charset parameter are NOT case sensitive. The default character set, which must be assumed in the absence of a charset parameter, is US-ASCII.

  • 5.1. Multipart Media Type

    As stated in the definition of the Content-Transfer-Encoding field [RFC 2045], no encoding other than "7bit", "8bit", or "binary" is permitted for entities of type "multipart". The "multipart" boundary delimiters and header fields are always represented as 7bit US-ASCII in any case (though the header fields may encode non-US-ASCII header text as per RFC 2047) and data within the body parts can be encoded on a part-by-part basis, with Content-Transfer-Encoding fields for each appropriate body part.

    The Content-Type field for multipart entities requires one parameter, "boundary". The boundary delimiter line is then defined as a line consisting entirely of two hyphen characters ("-", decimal value 45) followed by the boundary parameter value from the Content-Type header field, optional linear whitespace, and a terminating CRLF.

    Boundary delimiters must not appear within the encapsulated material, and must be no longer than 70 characters, not counting the two leading hyphens.

    The boundary delimiter line following the last body part is a distinguished delimiter that indicates that no further body parts will follow. Such a delimiter line is identical to the previous delimiter lines, with the addition of two more hyphens after the boundary parameter value.

Here is an example using an arbitrary boundary:

Content-Type: multipart/form-data; charset=utf-8; boundary="another cool boundary"

--another cool boundary
Content-Disposition: form-data; name="foo"

bar
--another cool boundary
Content-Disposition: form-data; name="baz"

quux
--another cool boundary--

How do I find duplicate values in a table in Oracle?

You don't need to even have the count in the returned columns if you don't need to know the actual number of duplicates. e.g.

SELECT column_name
FROM table
GROUP BY column_name
HAVING COUNT(*) > 1

Running script upon login mac

  1. Create your shell script as login.sh in your $HOME folder.

  2. Paste the following one-line script into Script Editor:

    do shell script "$HOME/login.sh"

  3. Then save it as an application.

  4. Finally add the application to your login items.

If you want to make the script output visual, you can swap step 2 for this:

tell application "Terminal"
  activate
  do script "$HOME/login.sh"
end tell

If multiple commands are needed something like this can be used:

tell application "Terminal"
  activate
  do script "cd $HOME"
  do script "./login.sh" in window 1
end tell

NSRange from Swift Range?

func formatAttributedStringWithHighlights(text: String, highlightedSubString: String?, formattingAttributes: [String: AnyObject]) -> NSAttributedString {
    let mutableString = NSMutableAttributedString(string: text)

    let text = text as NSString         // convert to NSString be we need NSRange
    if let highlightedSubString = highlightedSubString {
        let highlightedSubStringRange = text.rangeOfString(highlightedSubString) // find first occurence
        if highlightedSubStringRange.length > 0 {       // check for not found
            mutableString.setAttributes(formattingAttributes, range: highlightedSubStringRange)
        }
    }

    return mutableString
}

java.sql.SQLException: Exhausted Resultset

If you reset the result set to the top, using rs.absolute(1) you won't get exhaused result set.

while (rs.next) {
    System.out.println(rs.getString(1));
}
rs.absolute(1);
System.out.println(rs.getString(1));

You can also use rs.first() instead of rs.absolute(1), it does the same.

Sum the digits of a number

def digitsum(n):
    result = 0
    for i in range(len(str(n))):
        result = result + int(str(n)[i:i+1])
    return(result)

"result" is initialized with 0.

Inside the for loop, the number(n) is converted into a string to be split with loop index(i) and get each digit. ---> str(n)[i:i+1]

This sliced digit is converted back to an integer ----> int(str(n)[i:i+1])

And hence added to result.

Can Android do peer-to-peer ad-hoc networking?

my friend and I are currently developing a java library implementing the AODV protocol (multihop routing suitable for mobile networks), in our bachelor thesis. The final 'product' includes a easy way to create/join an adhoc network on several android devices and an interface through the library, to send and receive messages. Unfortunately each type of phone such as hero, nexsus one... have a phonedepended way for createing a adhoc network so currently we are only supporting a few phones).

this means that once this project is finished, people with rooted phones can implement their distributed applications (file sharing, games, ...) by simply including the library .jar file in their android projects.

it's all open source by the way

http://code.google.com/p/adhoc-on-android/

Get counts of all tables in a schema

Get counts of all tables in a schema and order by desc

select 'with tmp(table_name, row_number) as (' from dual 
union all 
select 'select '''||table_name||''',count(*) from '||table_name||' union  ' from USER_TABLES 
union all
select 'select '''',0 from dual) select table_name,row_number from tmp order by row_number desc ;' from dual;

Copy the entire result and execute

How do I parse command line arguments in Java?

This is Google's command line parsing library open-sourced as part of the Bazel project. Personally I think it's the best one out there, and far easier than Apache CLI.

https://github.com/pcj/google-options

Installation

Bazel

maven_jar(
    name = "com_github_pcj_google_options",
    artifact = "com.github.pcj:google-options:jar:1.0.0",
    sha1 = "85d54fe6771e5ff0d54827b0a3315c3e12fdd0c7",
)

Gradle

dependencies {
  compile 'com.github.pcj:google-options:1.0.0'
}

Maven

<dependency>
  <groupId>com.github.pcj</groupId>
  <artifactId>google-options</artifactId>
  <version>1.0.0</version>
</dependency>

Usage

Create a class that extends OptionsBase and defines your @Option(s).

package example;

import com.google.devtools.common.options.Option;
import com.google.devtools.common.options.OptionsBase;

import java.util.List;

/**
 * Command-line options definition for example server.
 */
public class ServerOptions extends OptionsBase {

  @Option(
      name = "help",
      abbrev = 'h',
      help = "Prints usage info.",
      defaultValue = "true"
    )
  public boolean help;

  @Option(
      name = "host",
      abbrev = 'o',
      help = "The server host.",
      category = "startup",
      defaultValue = ""
  )
  public String host;

  @Option(
    name = "port",
    abbrev = 'p',
    help = "The server port.",
    category = "startup",
    defaultValue = "8080"
    )
    public int port;

  @Option(
    name = "dir",
    abbrev = 'd',
    help = "Name of directory to serve static files.",
    category = "startup",
    allowMultiple = true,
    defaultValue = ""
    )
    public List<String> dirs;

}

Parse the arguments and use them.

package example;

import com.google.devtools.common.options.OptionsParser;
import java.util.Collections;

public class Server {

  public static void main(String[] args) {
    OptionsParser parser = OptionsParser.newOptionsParser(ServerOptions.class);
    parser.parseAndExitUponError(args);
    ServerOptions options = parser.getOptions(ServerOptions.class);
    if (options.host.isEmpty() || options.port < 0 || options.dirs.isEmpty()) {
      printUsage(parser);
      return;
    }

    System.out.format("Starting server at %s:%d...\n", options.host, options.port);
    for (String dirname : options.dirs) {
      System.out.format("\\--> Serving static files at <%s>\n", dirname);
    }
  }

  private static void printUsage(OptionsParser parser) {
    System.out.println("Usage: java -jar server.jar OPTIONS");
    System.out.println(parser.describeOptions(Collections.<String, String>emptyMap(),
                                              OptionsParser.HelpVerbosity.LONG));
  }

}

https://github.com/pcj/google-options

How to convert a python numpy array to an RGB image with Opencv 2.4?

The size of your image is not sufficient to see in a naked eye. So please try to use atleast 50x50

import cv2 as cv
import numpy as np

black_screen = np.zeros([50,50,3])

black_screen[:, :, 2] = np.ones([50,50])*64/255.0
cv.imshow("Simple_black", black_screen)
cv.waitKey(0)
cv.displayAllWindows()

"Cannot verify access to path (C:\inetpub\wwwroot)", when adding a virtual directory

I think the best solution to this problem can be found here: IIS_IUSRS and IUSR permissions in IIS8 This a good workaround but it does not work when you access the webserver over the Internet.

Setting background images in JFrame

import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

class BackgroundImageJFrame extends JFrame
{

    JButton b1;
    JLabel l1;

    public BackgroundImageJFrame() {

        setSize(400,400);
        setVisible(true);

        setLayout(new BorderLayout());

        JLabel background=new JLabel(new ImageIcon("C:\\Users\\Computer\\Downloads\\colorful_design.png"));

        add(background);

        background.setLayout(new FlowLayout());

        l1=new JLabel("Here is a button");
        b1=new JButton("I am a button");

        background.add(l1);
        background.add(b1);
    }

    public static void main(String args[]) 
    {
        new BackgroundImageJFrame();
    }
}

check out the below link

http://java-demos.blogspot.in/2012/09/setting-background-image-in-jframe.html

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

In XML, xmlns declares a Namespace. In fact, when you do:

<LinearLayout android:id>
</LinearLayout>

Instead of calling android:id, the xml will use http://schemas.android.com/apk/res/android:id to be unique. Generally this page doesn't exist (it's a URI, not a URL), but sometimes it is a URL that explains the used namespace.

The namespace has pretty much the same uses as the package name in a Java application.

Here is an explanation.

Uniform Resource Identifier (URI)

A Uniform Resource Identifier (URI) is a string of characters which identifies an Internet Resource.

The most common URI is the Uniform Resource Locator (URL) which identifies an Internet domain address. Another, not so common type of URI is the Universal Resource Name (URN).

In our examples we will only use URLs.

Nesting queries in SQL

The way I see it, the only place for a nested query would be in the WHERE clause, so e.g.

SELECT country.name, country.headofstate
FROM country 
WHERE country.headofstate LIKE 'A%' AND 
country.id in (SELECT country_id FROM city WHERE population > 100000)

Apart from that, I have to agree with Adrian on: why the heck should you use nested queries?

Typescript: React event types

I have the following in a types.ts file for html input, select, and textarea:

export type InputChangeEventHandler = React.ChangeEventHandler<HTMLInputElement>
export type TextareaChangeEventHandler = React.ChangeEventHandler<HTMLTextAreaElement>
export type SelectChangeEventHandler = React.ChangeEventHandler<HTMLSelectElement>

Then import them:

import { InputChangeEventHandler } from '../types'

Then use them:


const updateName: InputChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}
const updateBio: TextareaChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}
const updateSize: SelectChangeEventHandler = (event) => {
  // Do something with `event.currentTarget.value`
}

Then apply the functions on your markup (replacing ... with other necessary props):

<input onChange={updateName} ... />
<textarea onChange={updateName} ... />
<select onChange={updateSize} ... >
  // ...
</select>

Responsive web design is working on desktop but not on mobile device

You are probably missing the viewport meta tag in the html head:

 <meta name="viewport" content="width=device-width, initial-scale=1">

Without it the device assumes and sets the viewport to full size.

More info here.

How do I format a Microsoft JSON date?

You can use this to get a date from JSON:

var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));

And then you can use a JavaScript Date Format script (1.2 KB when minified and gzipped) to display it as you want.

Why I cannot cout a string?

You need to include

#include <string>
#include <iostream>

Insert Unicode character into JavaScript

I'm guessing that you actually want Omega to be a string containing an uppercase omega? In that case, you can write:

var Omega = '\u03A9';

(Because Ω is the Unicode character with codepoint U+03A9; that is, 03A9 is 937, except written as four hexadecimal digits.)

How to check if String is null

You can use the null coalescing double question marks to test for nulls in a string or other nullable value type:

textBox1.Text = s ?? "Is null";

The operator '??' asks if the value of 's' is null and if not it returns 's'; if it is null it returns the value on the right of the operator.

More info here: https://msdn.microsoft.com/en-us/library/ms173224.aspx

And also worth noting there's a null-conditional operator ?. and ?[ introduced in C# 6.0 (and VB) in VS2015

textBox1.Text = customer?.orders?[0].description ?? "n/a";

This returns "n/a" if description is null, or if the order is null, or if the customer is null, else it returns the value of description.

More info here: https://msdn.microsoft.com/en-us/library/dn986595.aspx

Access: Move to next record until EOF

To loop from current record to the end:

While Me.CurrentRecord < Me.Recordset.RecordCount
    ' ... do something to current record
    ' ...

    DoCmd.GoToRecord Record:=acNext
Wend

To check if it is possible to go to next record:

If Me.CurrentRecord < Me.Recordset.RecordCount Then
    ' ...
End If

How to see full absolute path of a symlink

realpath <path to the symlink file> should do the trick.

DateTimePicker time picker in 24 hour but displaying in 12hr?

I know it's been quite some time since the question was asked. However, if it helps anyone this worked for me.

 $(function() {
    $('.datetimepicker').datetimepicker({
        format: 'MM-DD-YYYY HH:mm '
    });
});

Trusting all certificates with okHttp

Following method is deprecated

sslSocketFactory(SSLSocketFactory sslSocketFactory)

Consider updating it to

sslSocketFactory(SSLSocketFactory sslSocketFactory, X509TrustManager trustManager)

from jquery $.ajax to angular $http

The AngularJS way of calling $http would look like:

$http({
    url: "http://example.appspot.com/rest/app",
    method: "POST",
    data: {"foo":"bar"}
}).then(function successCallback(response) {
        // this callback will be called asynchronously
        // when the response is available
        $scope.data = response.data;
    }, function errorCallback(response) {
        // called asynchronously if an error occurs
        // or server returns response with an error status.
        $scope.error = response.statusText;
});

or could be written even simpler using shortcut methods:

$http.post("http://example.appspot.com/rest/app", {"foo":"bar"})
.then(successCallback, errorCallback);

There are number of things to notice:

  • AngularJS version is more concise (especially using .post() method)
  • AngularJS will take care of converting JS objects into JSON string and setting headers (those are customizable)
  • Callback functions are named success and error respectively (also please note parameters of each callback) - Deprecated in angular v1.5
  • use then function instead.
  • More info of then usage can be found here

The above is just a quick example and some pointers, be sure to check AngularJS documentation for more: http://docs.angularjs.org/api/ng.$http

How to insert a data table into SQL Server database table?

    //best way to deal with this is sqlbulkcopy 
    //but if you dont like it you can do it like this
    //read current sql table in an adapter
    //add rows of datatable , I have mentioned a simple way of it
    //and finally updating changes

    Dim cnn As New SqlConnection("connection string")        
    cnn.Open()
    Dim cmd As New SqlCommand("select * from  sql_server_table", cnn)
    Dim da As New SqlDataAdapter(cmd)       
    Dim ds As New DataSet()
    da.Fill(ds, "sql_server_table")
    Dim cb As New SqlCommandBuilder(da)        

    //for each datatable row
    ds.Tables("sql_server_table").Rows.Add(COl1, COl2)

    da.Update(ds, "sql_server_table")

What does "dereferencing" a pointer mean?

In simple words, dereferencing means accessing the value from a certain memory location against which that pointer is pointing.

Best way to work with dates in Android SQLite

I prefer this. This is not the best way, but a fast solution.

//Building the table includes:
StringBuilder query= new StringBuilder();
query.append("CREATE TABLE "+TABLE_NAME+ " (");
query.append(COLUMN_ID+"int primary key autoincrement,");
query.append(COLUMN_CREATION_DATE+" DATE)");

//Inserting the data includes this:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
values.put(COLUMN_CREATION_DATE,dateFormat.format(reactionGame.getCreationDate())); 

// Fetching the data includes this:
try {
   java.util.Date creationDate = dateFormat.parse(cursor.getString(0);
   YourObject.setCreationDate(creationDate));
} catch (Exception e) {
   YourObject.setCreationDate(null);
}

Apache and IIS side by side (both listening to port 80) on windows2003

That's not quite true. E.g. for HTTP Windows supports URL based port sharing, allowing multiple processes to use the same IP address and Port.

What's the easiest way to call a function every 5 seconds in jQuery?

A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:

function myTimer() {
    console.log(' each 1 second...');
}

var myVar = setInterval(myTimer, 1000);

call this line to stop the loop:

 clearInterval(myVar);

How to do a FULL OUTER JOIN in MySQL?

I fix the response, and works include all rows (based on response of Pavle Lekic)

    (
    SELECT a.* FROM tablea a
    LEFT JOIN tableb b ON a.`key` = b.key
    WHERE b.`key` is null
    )
    UNION ALL
    (
    SELECT a.* FROM tablea a
    LEFT JOIN tableb b ON a.`key` = b.key
    where  a.`key` = b.`key`
    )
    UNION ALL
    (
    SELECT b.* FROM tablea a
    right JOIN tableb b ON b.`key` = a.key
    WHERE a.`key` is null
    );