Programs & Examples On #Linker errors

An error received when combining individually compiled object files into executable code.

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

What is an undefined reference/unresolved external symbol error and how do I fix it?

Missing "extern" in const variable declarations/definitions (C++ only)

For people coming from C it might be a surprise that in C++ global constvariables have internal (or static) linkage. In C this was not the case, as all global variables are implicitly extern (i.e. when the static keyword is missing).

Example:

// file1.cpp
const int test = 5;    // in C++ same as "static const int test = 5"
int test2 = 5;

// file2.cpp
extern const int test;
extern int test2;

void foo()
{
 int x = test;   // linker error in C++ , no error in C
 int y = test2;  // no problem
}

correct would be to use a header file and include it in file2.cpp and file1.cpp

extern const int test;
extern int test2;

Alternatively one could declare the const variable in file1.cpp with explicit extern

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

Multiple definition of ... linker error

Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)

Undefined reference to `sin`

You have compiled your code with references to the correct math.h header file, but when you attempted to link it, you forgot the option to include the math library. As a result, you can compile your .o object files, but not build your executable.

As Paul has already mentioned add "-lm" to link with the math library in the step where you are attempting to generate your executable.

In the comment, linuxD asks:

Why for sin() in <math.h>, do we need -lm option explicitly; but, not for printf() in <stdio.h>?

Because both these functions are implemented as part of the "Single UNIX Specification". This history of this standard is interesting, and is known by many names (IEEE Std 1003.1, X/Open Portability Guide, POSIX, Spec 1170).

This standard, specifically separates out the "Standard C library" routines from the "Standard C Mathematical Library" routines (page 277). The pertinent passage is copied below:

Standard C Library

The Standard C library is automatically searched by cc to resolve external references. This library supports all of the interfaces of the Base System, as defined in Volume 1, except for the Math Routines.

Standard C Mathematical Library

This library supports the Base System math routines, as defined in Volume 1. The cc option -lm is used to search this library.

The reasoning behind this separation was influenced by a number of factors:

  1. The UNIX wars led to increasing divergence from the original AT&T UNIX offering.
  2. The number of UNIX platforms added difficulty in developing software for the operating system.
  3. An attempt to define the lowest common denominator for software developers was launched, called 1988 POSIX.
  4. Software developers programmed against the POSIX standard to provide their software on "POSIX compliant systems" in order to reach more platforms.
  5. UNIX customers demanded "POSIX compliant" UNIX systems to run the software.

The pressures that fed into the decision to put -lm in a different library probably included, but are not limited to:

  1. It seems like a good way to keep the size of libc down, as many applications don't use functions embedded in the math library.
  2. It provides flexibility in math library implementation, where some math libraries rely on larger embedded lookup tables while others may rely on smaller lookup tables (computing solutions).
  3. For truly size constrained applications, it permits reimplementations of the math library in a non-standard way (like pulling out just sin() and putting it in a custom built library.

In any case, it is now part of the standard to not be automatically included as part of the C language, and that's why you must add -lm.

Duplicate Symbols for Architecture arm64

From the errors, it would appear that the FacebookSDK.framework already includes the Bolts.framework classes. Try removing the additional Bolts.framework from the project.

Trying to include a library, but keep getting 'undefined reference to' messages

Yes, It is required to add libraries after the source files/objects files. This command will solve the problem:

gcc -static -L/usr/lib -I/usr/lib main.c -ltommath

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

Because you didn't tell the linker about location of math library. Compile with gcc test.c -o test -lm

Undefined reference to sqrt (or other mathematical functions)

I had the same issue, but I simply solved it by adding -lm after the command that runs my code. Example. gcc code.c -lm

Undefined reference to 'vtable for xxx'

The first set of errors, for the missing vtable, are caused because you do not implement takeaway::textualGame(); instead you implement a non-member function, textualGame(). I think that adding the missing takeaway:: will fix that.

The cause of the last error is that you're calling a virtual function, initialData(), from the constructor of gameCore. At this stage, virtual functions are dispatched according to the type currently being constructed (gameCore), not the most derived class (takeaway). This particular function is pure virtual, and so calling it here gives undefined behaviour.

Two possible solutions:

  • Move the initialisation code for gameCore out of the constructor and into a separate initialisation function, which must be called after the object is fully constructed; or
  • Separate gameCore into two classes: an abstract interface to be implemented by takeaway, and a concrete class containing the state. Construct takeaway first, and then pass it (via a reference to the interface class) to the constructor of the concrete class.

I would recommend the second, as it is a move towards smaller classes and looser coupling, and it will be harder to use the classes incorrectly. The first is more error-prone, as there is no way be sure that the initialisation function is called correctly.

One final point: the destructor of a base class should usually either be virtual (to allow polymorphic deletion) or protected (to prevent invalid polymorphic deletion).

C error: undefined reference to function, but it IS defined

I think the problem is that when you're trying to compile testpoint.c, it includes point.h but it doesn't know about point.c. Since point.c has the definition for create, not having point.c will cause the compilation to fail.

I'm not familiar with MinGW, but you need to tell the compiler to look for point.c. For example with gcc you might do this:

gcc point.c testpoint.c

As others have pointed out, you also need to remove one of your main functions, since you can only have one.

Exiting from python Command Line

"exit" is a valid variable name that can be used in your Python program. You wouldn't want to exit the interpreter when you're just trying to see the value of that variable.

T-SQL string replace in Update

If anyone cares, for NTEXT, use the following format:

SELECT CAST(REPLACE(CAST([ColumnValue] AS NVARCHAR(MAX)),'find','replace') AS NTEXT) 
    FROM [DataTable]

Android: Proper Way to use onBackPressed() with Toast

I just had this issue and solved it by adding the following method:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case android.R.id.home:
             // click on 'up' button in the action bar, handle it here
             return true;

        default:
            return super.onOptionsItemSelected(item);
    }
}    

How to reset AUTO_INCREMENT in MySQL?

As of MySQL 5.6 the approach below works faster due to online DDL (note algorithm=inplace):

alter table tablename auto_increment=1, algorithm=inplace;

Twig: in_array or similar possible within if statement?

Try this

{% if var in ['foo', 'bar', 'beer'] %}
    ...
{% endif %}

How can I encode a string to Base64 in Swift?

Swift 4.2

"abcd1234".data(using: .utf8)?.base64EncodedString()

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

In addition to Lion's answer i can say that you better use if(CollectionUtils.isNotEmpty(test)){...} This also checks for null, so no manual check is not needed.

http://localhost:50070 does not work HADOOP

After installing and configuring Hadoop, you can quickly run the command netstat -tulpn

to find the ports open. In the new version of Hadoop 3.1.3 the ports are as follows:-

localhost:8042 Hadoop, localhost:9870 HDFS, localhost:8088 YARN

How do you make an anchor link non-clickable or disabled?

The easyest way

In your html:

<a id="foo" disabled="true">xxxxx<a>

In your js:

$('#foo').attr("disabled", false);

If you use it as attribute works perfectly

How to change heatmap.2 color range in R?

I think you need to set symbreaks = FALSE That should allow for asymmetrical color scales.

Android M Permissions: onRequestPermissionsResult() not being called

for kotlin users, here my extension to check and validate permissions without override onRequestPermissionResult

 * @param permissionToValidate (request and check currently permission)
 *
 * @return recursive boolean validation callback (no need OnRequestPermissionResult)
 *
 * */
internal fun Activity.validatePermission(
    permissionToValidate: String,
    recursiveCall: (() -> Boolean) = { false }
): Boolean {
    val permission = ContextCompat.checkSelfPermission(
        this,
        permissionToValidate
    )

    if (permission != PackageManager.PERMISSION_GRANTED) {
        if (recursiveCall()) {
            return false
        }

        ActivityCompat.requestPermissions(
            this,
            arrayOf(permissionToValidate),
            110
        )
        return this.validatePermission(permissionToValidate) { true }
    }

    return true

}

How can I change the text color with jQuery?

Place the following in your jQuery mouseover event handler:

$(this).css('color', 'red');

To set both color and size at the same time:

$(this).css({ 'color': 'red', 'font-size': '150%' });

You can set any CSS attribute using the .css() jQuery function.

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

How to install XNA game studio on Visual Studio 2012?

There seems to be some confusion over how to get this set up for the Express version specifically. Using the Windows Desktop (WD) version of VS Express 2012, I followed the instructions in Steve B's and Rick Martin's answers with the modifications below.

  • In step 2 rather than copying to "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\Extensions\Microsoft\XNA Game Studio 4.0", copy to "C:\Program Files (x86)\Microsoft Visual Studio 11.0\Common7\IDE\WDExpressExtensions\Microsoft\XNA Game Studio 4.0"
  • In step 4, after making the changes also add the line <Edition>WDExpress</Edition> (you should be able to see where it makes sense)
  • In step 5, replace devenv.exe with WDExpress.exe
  • In Rick Martin's step, replace "%LocalAppData%\Microsoft\VisualStudio\11.0\Extensions" with "%LocalAppData%\Microsoft\WDExpress\11.0\Extensions"

I haven't done a lot of work since then, but I did manage to create a new game project and it seems fine so far.

How to change the href for a hyperlink using jQuery

Use the attr method on your lookup. You can switch out any attribute with a new value.

$("a.mylink").attr("href", "http://cupcream.com");

How to clone ArrayList and also clone its contents?

Java 8 provides a new way to call the copy constructor or clone method on the element dogs elegantly and compactly: Streams, lambdas and collectors.

Copy constructor:

List<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toList());

The expression Dog::new is called a method reference. It creates a function object which calls a constructor on Dog which takes another dog as argument.

Clone method[1]:

List<Dog> clonedDogs = dogs.stream().map(d -> d.clone()).collect(toList());

Getting an ArrayList as the result

Or, if you have to get an ArrayList back (in case you want to modify it later):

ArrayList<Dog> clonedDogs = dogs.stream().map(Dog::new).collect(toCollection(ArrayList::new));

Update the list in place

If you don't need to keep the original content of the dogs list you can instead use the replaceAll method and update the list in place:

dogs.replaceAll(Dog::new);

All examples assume import static java.util.stream.Collectors.*;.


Collector for ArrayLists

The collector from the last example can be made into a util method. Since this is such a common thing to do I personally like it to be short and pretty. Like this:

ArrayList<Dog> clonedDogs = dogs.stream().map(d -> d.clone()).collect(toArrayList());

public static <T> Collector<T, ?, ArrayList<T>> toArrayList() {
    return Collectors.toCollection(ArrayList::new);
}

[1] Note on CloneNotSupportedException:

For this solution to work the clone method of Dog must not declare that it throws CloneNotSupportedException. The reason is that the argument to map is not allowed to throw any checked exceptions.

Like this:

    // Note: Method is public and returns Dog, not Object
    @Override
    public Dog clone() /* Note: No throws clause here */ { ...

This should not be a big problem however, since that is the best practice anyway. (Effectice Java for example gives this advice.)

Thanks to Gustavo for noting this.


PS:

If you find it prettier you can instead use the method reference syntax to do exactly the same thing:

List<Dog> clonedDogs = dogs.stream().map(Dog::clone).collect(toList());

How to filter an array from all elements of another array

There are many answers for your question, but I don't see anyone using lambda expresion:

var array = [1,2,3,4];
var anotherOne = [2,4];
var filteredArray = array.filter(x => anotherOne.indexOf(x) < 0);

How to run a program without an operating system?

I wrote a c++ program based on Win32 to write an assembly to the boot sector of a pen-drive. When the computer is booted from the pen-drive it executes the code successfully - have a look here C++ Program to write to the boot sector of a USB Pendrive

This program is a few lines that should be compiled on a compiler with windows compilation configured - such as a visual studio compiler - any available version.

How to round a floating point number up to a certain decimal place?

If you want to round, 8.84 is the incorrect answer. 8.833333333333 rounded is 8.83 not 8.84. If you want to always round up, then you can use math.ceil. Do both in a combination with string formatting, because rounding a float number itself doesn't make sense.

"%.2f" % (math.ceil(x * 100) / 100)

Resize background image in div using css

With the background-size property in those browsers which support this very new feature of CSS.

Reading a plain text file in Java

The most simple way to read data from a file in Java is making use of the File class to read the file and the Scanner class to read the content of the file.

public static void main(String args[])throws Exception
{
   File f = new File("input.txt");
   takeInputIn2DArray(f);
}

public static void takeInputIn2DArray(File f) throws Exception
{
    Scanner s = new Scanner(f);
    int a[][] = new int[20][20];
    for(int i=0; i<20; i++)
    {
        for(int j=0; j<20; j++)
        {
            a[i][j] = s.nextInt();
        }
    }
}

PS: Don't forget to import java.util.*; for Scanner to work.

Multiple "style" attributes in a "span" tag: what's supposed to happen?

Separate your rules with a semi colon in a single declaration:

<span style="color:blue;font-style:italic">Test</span>

How to execute cmd commands via Java

Try this link

You do not use "cd" to change the directory from which to run your commands. You need the full path of the executable you want to run.

Also, listing the contents of a directory is easier to do with the File/Directory classes

How to assign pointer address manually in C programming language?

Like this:

void * p = (void *)0x28ff44;

Or if you want it as a char *:

char * p = (char *)0x28ff44;

...etc.

If you're pointing to something you really, really aren't meant to change, add a const:

const void * p = (const void *)0x28ff44;
const char * p = (const char *)0x28ff44;

...since I figure this must be some kind of "well-known address" and those are typically (though by no means always) read-only.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Use the Bootstrap Customizer to generate a version of Bootstrap that has a taller navbar. The value you want to change is @navbar-height in the Navbar section.

Inspect your current implementation to see how tall your navbar is with the 50px brand image, and use that calculated height in the Customizer.

How to programmatically add controls to a form in VB.NET

Dim numberOfButtons As Integer
Dim buttons() as Button

Private Sub MyForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Redim buttons(numberOfbuttons)
    for counter as integer = 0 to numberOfbuttons
        With buttons(counter)
           .Size = (10, 10)
           .Visible = False
           .Location = (55, 33 + counter*13)
           .Text = "Button "+(counter+1).ToString ' or some name from an array you pass from main
           'any other property
        End With
        '
    next
End Sub

If you want to check which of the textboxes have information, or which radio button was clicked, you can iterate through a loop in an OK button.

If you want to be able to click individual array items and have them respond to events, add in the Form_load loop the following:

AddHandler buttons(counter).Clicked AddressOf All_Buttons_Clicked 

then create

Private Sub All_Buttons_Clicked(ByVal sender As System.Object, ByVal e As System.EventArgs)
     'some code here, can check to see which checkbox was changed, which button was clicked, by number or text
End Sub

when you call: objectYouCall.numberOfButtons = initial_value_from_main_program

response_yes_or_no_or_other = objectYouCall.ShowDialog()

For radio buttons, textboxes, same story, different ending.

.Net HttpWebRequest.GetResponse() raises exception when http status code 400 (bad request) is returned

It would be nice if there were some way of turning off "throw on non-success code" but if you catch WebException you can at least use the response:

using System;
using System.IO;
using System.Web;
using System.Net;

public class Test
{
    static void Main()
    {
        WebRequest request = WebRequest.Create("http://csharpindepth.com/asd");
        try
        {
            using (WebResponse response = request.GetResponse())
            {
                Console.WriteLine("Won't get here");
            }
        }
        catch (WebException e)
        {
            using (WebResponse response = e.Response)
            {
                HttpWebResponse httpResponse = (HttpWebResponse) response;
                Console.WriteLine("Error code: {0}", httpResponse.StatusCode);
                using (Stream data = response.GetResponseStream())
                using (var reader = new StreamReader(data))
                {
                    string text = reader.ReadToEnd();
                    Console.WriteLine(text);
                }
            }
        }
    }
}

You might like to encapsulate the "get me a response even if it's not a success code" bit in a separate method. (I'd suggest you still throw if there isn't a response, e.g. if you couldn't connect.)

If the error response may be large (which is unusual) you may want to tweak HttpWebRequest.DefaultMaximumErrorResponseLength to make sure you get the whole error.

Escape double quote character in XML

New, improved answer to an old, frequently asked question...

When to escape double quote in XML

Double quote (") may appear without escaping:

  • In XML textual content:

    <NoEscapeNeeded>He said, "Don't quote me."</NoEscapeNeeded>
    
  • In XML attributes delimited by single quotes ('):

    <NoEscapeNeeded name='Pete "Maverick" Mitchell'/>
    

    Note: switching to single quotes (') also requires no escaping:

    <NoEscapeNeeded name="Pete 'Maverick' Mitchell"/>
    

Double quote (") must be escaped:

  • In XML attributes delimited by double quotes:

    <EscapeNeeded name="Pete &quot;Maverick&quot; Mitchell"/>
    

Bottom line

Double quote (") must be escaped as &quot; in XML only in very limited contexts.

How do I convert a org.w3c.dom.Document object to a String?

A Scala version based on Zaz's answer.

  case class DocumentEx(document: Document) {
    def toXmlString(pretty: Boolean = false):Try[String] = {
      getStringFromDocument(document, pretty)
    }
  }

  implicit def documentToDocumentEx(document: Document):DocumentEx = {
    DocumentEx(document)
  }

  def getStringFromDocument(doc: Document, pretty:Boolean): Try[String] = {
    try
    {
      val domSource= new DOMSource(doc)
      val writer = new StringWriter()
      val result = new StreamResult(writer)
      val tf = TransformerFactory.newInstance()
      val transformer = tf.newTransformer()
      if (pretty)
        transformer.setOutputProperty(OutputKeys.INDENT, "yes")
      transformer.transform(domSource, result)
      Success(writer.toString);
    }
    catch {
      case ex: TransformerException =>
        Failure(ex)
    }
  }

With that, you can do either doc.toXmlString() or call the getStringFromDocument(doc) function.

Fine control over the font size in Seaborn plots for academic papers

You are right. This is a badly documented issue. But you can change the font size parameter (by opposition to font scale) directly after building the plot. Check the following example:

import seaborn as sns
tips = sns.load_dataset("tips")

b = sns.boxplot(x=tips["total_bill"])
b.axes.set_title("Title",fontsize=50)
b.set_xlabel("X Label",fontsize=30)
b.set_ylabel("Y Label",fontsize=20)
b.tick_params(labelsize=5)
sns.plt.show()

, which results in this:

Different font sizes for different labels

To make it consistent in between plots I think you just need to make sure the DPI is the same. By the way it' also a possibility to customize a bit the rc dictionaries since "font.size" parameter exists but I'm not too sure how to do that.

NOTE: And also I don't really understand why they changed the name of the font size variables for axis labels and ticks. Seems a bit un-intuitive.

Purge or recreate a Ruby on Rails database

You can use db:reset - for run db:drop and db:setup or db:migrate:reset - which runs db:drop, db:create and db:migrate.

dependent at you want to use exist schema.rb

Assigning more than one class for one event

Have you tried this:

 function doSomething() {
     if ($(this).hasClass('clickedTag')){
         // code here
     } else {
         // and here
     }
 }

 $('.tag1, .tag2').click(doSomething);

How to run multiple Python versions on Windows

One easy way for this is that you can use

py -3.8 -m pip install virtualenv here -3.8 goes with your [version number]

After installing the virtualenv, you can create the virtual environment of your application using

py -3.8 -m virtualenv [your env name]

then cd to venv, enter activate

This would activate the python version you like. Just change the version number to use a different python version.

AngularJS: Basic example to use authentication in Single Page Application

I answered a similar question here: AngularJS Authentication + RESTful API


I've written an AngularJS module for UserApp that supports protected/public routes, rerouting on login/logout, heartbeats for status checks, stores the session token in a cookie, events, etc.

You could either:

  1. Modify the module and attach it to your own API, or
  2. Use the module together with UserApp (a cloud-based user management API)

https://github.com/userapp-io/userapp-angular

If you use UserApp, you won't have to write any server-side code for the user stuff (more than validating a token). Take the course on Codecademy to try it out.

Here's some examples of how it works:

  • How to specify which routes that should be public, and which route that is the login form:

    $routeProvider.when('/login', {templateUrl: 'partials/login.html', public: true, login: true});
    $routeProvider.when('/signup', {templateUrl: 'partials/signup.html', public: true});
    $routeProvider.when('/home', {templateUrl: 'partials/home.html'});
    

    The .otherwise() route should be set to where you want your users to be redirected after login. Example:

    $routeProvider.otherwise({redirectTo: '/home'});

  • Login form with error handling:

    <form ua-login ua-error="error-msg">
        <input name="login" placeholder="Username"><br>
        <input name="password" placeholder="Password" type="password"><br>
        <button type="submit">Log in</button>
        <p id="error-msg"></p>
    </form>
    
  • Signup form with error handling:

    <form ua-signup ua-error="error-msg">
      <input name="first_name" placeholder="Your name"><br>
      <input name="login" ua-is-email placeholder="Email"><br>
      <input name="password" placeholder="Password" type="password"><br>
      <button type="submit">Create account</button>
      <p id="error-msg"></p>
    </form>
    
  • Log out link:

    <a href="#" ua-logout>Log Out</a>

    (Ends the session and redirects to the login route)

  • Access user properties:

    User properties are accessed using the user service, e.g: user.current.email

    Or in the template: <span>{{ user.email }}</span>

  • Hide elements that should only be visible when logged in:

    <div ng-show="user.authorized">Welcome {{ user.first_name }}!</div>

  • Show an element based on permissions:

    <div ua-has-permission="admin">You are an admin</div>

And to authenticate to your back-end services, just use user.token() to get the session token and send it with the AJAX request. At the back-end, use the UserApp API (if you use UserApp) to check if the token is valid or not.

If you need any help, just let me know!

how to open .mat file without using MATLAB?

Download Notepad++ (notepad-plus-plus.org) it opens nearly any file format and recognizes breaks, comments and does all the same color coding as the original language formatting.

Handling very large numbers in Python

python supports arbitrarily large integers naturally:

example:

>>> 10**1000
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

You could even get, for example of a huge integer value, fib(4000000).

But still it does not (for now) supports an arbitrarily large float !!

If you need one big, large, float then check up on the decimal Module. There are examples of use on these foruns: OverflowError: (34, 'Result too large')

Another reference: http://docs.python.org/2/library/decimal.html

You can even using the gmpy module if you need a speed-up (which is likely to be of your interest): Handling big numbers in code

Another reference: https://code.google.com/p/gmpy/

Peak signal detection in realtime timeseries data

One approach is to detect peaks based on the following observation:

  • Time t is a peak if (y(t) > y(t-1)) && (y(t) > y(t+1))

It avoids false positives by waiting until the uptrend is over. It is not exactly "real-time" in the sense that it will miss the peak by one dt. sensitivity can be controlled by requiring a margin for comparison. There is a trade off between noisy detection and time delay of detection. You can enrich the model by adding more parameters:

  • peak if (y(t) - y(t-dt) > m) && (y(t) - y(t+dt) > m)

where dt and m are parameters to control sensitivity vs time-delay

This is what you get with the mentioned algorithm: enter image description here

here is the code to reproduce the plot in python:

import numpy as np
import matplotlib.pyplot as plt
input = np.array([ 1. ,  1. ,  1. ,  1. ,  1. ,  1. ,  1. ,  1.1,  1. ,  0.8,  0.9,
    1. ,  1.2,  0.9,  1. ,  1. ,  1.1,  1.2,  1. ,  1.5,  1. ,  3. ,
    2. ,  5. ,  3. ,  2. ,  1. ,  1. ,  1. ,  0.9,  1. ,  1. ,  3. ,
    2.6,  4. ,  3. ,  3.2,  2. ,  1. ,  1. ,  1. ,  1. ,  1. ])
signal = (input > np.roll(input,1)) & (input > np.roll(input,-1))
plt.plot(input)
plt.plot(signal.nonzero()[0], input[signal], 'ro')
plt.show()

By setting m = 0.5, you can get a cleaner signal with only one false positive: enter image description here

Simplest way to detect keypresses in javascript

With plain Javascript, the simplest is:

document.onkeypress = function (e) {
    e = e || window.event;
    // use e.keyCode
};

But with this, you can only bind one handler for the event.

In addition, you could use the following to be able to potentially bind multiple handlers to the same event:

addEvent(document, "keypress", function (e) {
    e = e || window.event;
    // use e.keyCode
});

function addEvent(element, eventName, callback) {
    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    } else {
        element["on" + eventName] = callback;
    }
}

In either case, keyCode isn't consistent across browsers, so there's more to check for and figure out. Notice the e = e || window.event - that's a normal problem with Internet Explorer, putting the event in window.event instead of passing it to the callback.

References:

With jQuery:

$(document).on("keypress", function (e) {
    // use e.which
});

Reference:

Other than jQuery being a "large" library, jQuery really helps with inconsistencies between browsers, especially with window events...and that can't be denied. Hopefully it's obvious that the jQuery code I provided for your example is much more elegant and shorter, yet accomplishes what you want in a consistent way. You should be able to trust that e (the event) and e.which (the key code, for knowing which key was pressed) are accurate. In plain Javascript, it's a little harder to know unless you do everything that the jQuery library internally does.

Note there is a keydown event, that is different than keypress. You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown

As for suggesting what to use, I would definitely suggest using jQuery if you're up for learning the framework. At the same time, I would say that you should learn Javascript's syntax, methods, features, and how to interact with the DOM. Once you understand how it works and what's happening, you should be more comfortable working with jQuery. To me, jQuery makes things more consistent and is more concise. In the end, it's Javascript, and wraps the language.

Another example of jQuery being very useful is with AJAX. Browsers are inconsistent with how AJAX requests are handled, so jQuery abstracts that so you don't have to worry.

Here's something that might help decide:

How to add parameters to a HTTP GET request in Android?

I use a List of NameValuePair and URLEncodedUtils to create the url string I want.

protected String addLocationToUrl(String url){
    if(!url.endsWith("?"))
        url += "?";

    List<NameValuePair> params = new LinkedList<NameValuePair>();

    if (lat != 0.0 && lon != 0.0){
        params.add(new BasicNameValuePair("lat", String.valueOf(lat)));
        params.add(new BasicNameValuePair("lon", String.valueOf(lon)));
    }

    if (address != null && address.getPostalCode() != null)
        params.add(new BasicNameValuePair("postalCode", address.getPostalCode()));
    if (address != null && address.getCountryCode() != null)
        params.add(new BasicNameValuePair("country",address.getCountryCode()));

    params.add(new BasicNameValuePair("user", agent.uniqueId));

    String paramString = URLEncodedUtils.format(params, "utf-8");

    url += paramString;
    return url;
}

Search all tables, all columns for a specific value SQL Server

I've just updated my blog post to correct the error in the script that you were having Jeff, you can see the updated script here: Search all fields in SQL Server Database

As requested, here's the script in case you want it but I'd recommend reviewing the blog post as I do update it from time to time

DECLARE @SearchStr nvarchar(100)
SET @SearchStr = '## YOUR STRING HERE ##'
 
 
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Updated and tested by Tim Gaunt
-- http://www.thesitedoctor.co.uk
-- http://blogs.thesitedoctor.co.uk/tim/2010/02/19/Search+Every+Table+And+Field+In+A+SQL+Server+Database+Updated.aspx
-- Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010
-- Date modified: 03rd March 2011 19:00 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
 
SET NOCOUNT ON
 
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
 
WHILE @TableName IS NOT NULL
 
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
 
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
         
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )
 
        IF @ColumnName IS NOT NULL
         
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END   
END
 
SELECT ColumnName, ColumnValue FROM #Results
 
DROP TABLE #Results

Format Float to n decimal places

Of note, use of DecimalFormat constructor is discouraged. The javadoc for this class states:

In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat.

https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html

So what you need to do is (for instance):

NumberFormat formatter = NumberFormat.getInstance(Locale.US);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
formatter.setRoundingMode(RoundingMode.HALF_UP); 
Float formatedFloat = new Float(formatter.format(floatValue));

Xampp-mysql - "Table doesn't exist in engine" #1932

Copy the ib_logfileXX and ibdata file from old mysql/data folder to the new mysql data folder and it will fix the issue

Disable scrolling in all mobile devices

use this in style

body
{
overflow:hidden;
width:100%;
}

Use this in head tag

<meta name="viewport" content="user-scalable=no, width=device-width, initial-scale=1.0" />
<meta name="apple-mobile-web-app-capable" content="yes" />

How to lock orientation of one view controller to portrait mode only in Swift

Here is a simple way that works for me with Swift 4.2 (iOS 12.2), put this in a UIViewController for which you want to disable shouldAutorotate:

override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
    return .portrait
}

The .portrait part tells it in which orientation(s) to remain, you can change this as you like. Choices are: .portrait, .all, .allButUpsideDown, .landscape, .landscapeLeft, .landscapeRight, .portraitUpsideDown.

Bootstrap 3 unable to display glyphicon properly

I had the same problem using a local apache server. This solved my problem:

http://www.ifusio.com/blog/firefox-issue-with-twitter-bootstrap-glyphicons

For Amazon s3 you need to edit your CORS configuration:

<CORSConfiguration>
    <CORSRule>
        <AllowedOrigin>*</AllowedOrigin>
        <AllowedMethod>GET</AllowedMethod>
        <MaxAgeSeconds>3000</MaxAgeSeconds>
        <AllowedHeader>Authorization</AllowedHeader>
    </CORSRule>
</CORSConfiguration>

Vagrant error : Failed to mount folders in Linux guest

Your log complains about not finding exportfs: sudo: /usr/bin/exportfs: command not found

The exportfs makes local directories available for NFS clients to mount.

What's the difference between ConcurrentHashMap and Collections.synchronizedMap(Map)?

In general, if you want to use the ConcurrentHashMap make sure you are ready to miss 'updates'
(i.e. printing contents of the HashMap does not ensure it will print the up-to-date Map) and use APIs like CyclicBarrier to ensure consistency across your program's lifecycle.

Using OR in SQLAlchemy

or_() function can be useful in case of unknown number of OR query components.

For example, let's assume that we are creating a REST service with few optional filters, that should return record if any of filters return true. On the other side, if parameter was not defined in a request, our query shouldn't change. Without or_() function we must do something like this:

query = Book.query
if filter.title and filter.author:
    query = query.filter((Book.title.ilike(filter.title))|(Book.author.ilike(filter.author)))
else if filter.title:
    query = query.filter(Book.title.ilike(filter.title))
else if filter.author:
    query = query.filter(Book.author.ilike(filter.author))

With or_() function it can be rewritten to:

query = Book.query
not_null_filters = []
if filter.title:
    not_null_filters.append(Book.title.ilike(filter.title))
if filter.author:
    not_null_filters.append(Book.author.ilike(filter.author))

if len(not_null_filters) > 0:
    query = query.filter(or_(*not_null_filters))

How do you check if a JavaScript Object is a DOM Object?

Each DOMElement.constructor returns function HTML...Element() or [Object HTML...Element] so...

function isDOM(getElem){
    if(getElem===null||typeof getElem==="undefined") return false;
    var c = getElem.constructor.toString();
    var html = c.search("HTML")!==-1;
    var element = c.search("Element")!==-1;
    return html&&element;
}

SQL time difference between two dates result in hh:mm:ss

I like the idea of making this into a function so it becomes re-useable and your queries become much easier to read:

--get the difference between two datetimes in the format: 'h:m:s'
CREATE FUNCTION getDateDiff(@startDate DATETIME, @endDate DATETIME)
RETURNS VARCHAR(10)
AS BEGIN
    DECLARE @seconds INT = DATEDIFF(s, @startDate, @endDate)
    DECLARE @difference VARCHAR(10) =
    CONVERT(VARCHAR(4), @seconds / 3600) + ':' +
    CONVERT(VARCHAR(2), @seconds % 3600 / 60) + ':' +
    CONVERT(VARCHAR(2), @seconds % 60)
    RETURN @difference
END

Usage:

DECLARE @StartDate DATETIME = '10/01/2012 08:40:18.000'
DECLARE @endDate DATETIME = '10/04/2012 09:52:48.000'

SELECT dbo.getDateDiff(@startDate, @endDate) AS DateDifference

Result:

    DateDifference
1   73:12:30

It's also easier to read the result if you add padding so the format is always hh:mm:ss. For example, here's how you would do that in SQL Server 2012 or later:

--get the difference between two datetimes in the format: 'hh:mm:ss'
CREATE FUNCTION getDateDiff(@startDate DATETIME, @endDate DATETIME)
RETURNS VARCHAR(10)
AS BEGIN
    DECLARE @seconds INT = DATEDIFF(s, @startDate, @endDate)
    DECLARE @difference VARCHAR(10) =
    FORMAT(@seconds / 3600, '00') + ':' +
    FORMAT(@seconds % 3600 / 60, '00') + ':' +
    FORMAT(@seconds % 60, '00')
    RETURN @difference
END

Note that this will not clip the hour if it is more than 2 digits long. So 1 hour would show up as 01:00:00 and 100 hours would show up as 100:00:00

define a List like List<int,string>?

With the new ValueTuple from C# 7 (VS 2017 and above), there is a new solution:

List<(int,string)> mylist= new List<(int,string)>();

Which creates a list of ValueTuple type. If you're targeting .Net Framework 4.7+ or .Net Core, it's native, otherwise you have to get the ValueTuple package from nuget.

It's a struct opposing to Tuple, which is a class. It also has the advantage over the Tuple class that you could create a named tuple, like this:

var mylist = new List<(int myInt, string myString)>();

That way you can access like mylist[0].myInt and mylist[0].myString

Automating running command on Linux from Windows using PuTTY

Putty usually comes with the "plink" utility.
This is essentially the "ssh" command line command implemented as a windows .exe.
It pretty well documented in the putty manual under "Using the command line tool plink".

You just need to wrap a command like:

plink root@myserver /etc/backups/do-backup.sh

in a .bat script.

You can also use common shell constructs, like semicolons to execute multiple commands. e.g:

plink read@myhost ls -lrt /home/read/files;/etc/backups/do-backup.sh

Best way to compare dates in Android

Calendar toDayCalendar = Calendar.getInstance();
Date date1 = toDayCalendar.getTime();


Calendar tomorrowCalendar = Calendar.getInstance();
tomorrowCalendar.add(Calendar.DAY_OF_MONTH,1);
Date date2 = tomorrowCalendar.getTime();

// date1 is a present date and date2 is tomorrow date

if ( date1.compareTo(date2) < 0 ) {

  //  0 comes when two date are same,
  //  1 comes when date1 is higher then date2
  // -1 comes when date1 is lower then date2

 }

Clear icon inside input text

According to MDN, <input type="search" /> is currently supported in all modern browsers:

input type=search

_x000D_
_x000D_
<input type="search" value="Clear this." />
_x000D_
_x000D_
_x000D_


However, if you want different behavior that is consistent across browsers here are some light-weight alternatives that only require JavaScript:

Option 1 - Always display the 'x': (example here)

_x000D_
_x000D_
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
  el.addEventListener('click', function(e) {
    e.target.previousElementSibling.value = '';
  });
});
_x000D_
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input > [data-clear-input] {
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
_x000D_
<p>Always display the 'x':</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>
_x000D_
_x000D_
_x000D_

Option 2 - Only display the 'x' when hovering over the field: (example here)

_x000D_
_x000D_
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input>[data-clear-input]'), function(el) {
  el.addEventListener('click', function(e) {
    e.target.previousElementSibling.value = '';
  });
});
_x000D_
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input:hover > [data-clear-input] {
  display: block;
}
.clearable-input > [data-clear-input] {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
_x000D_
<p>Only display the 'x' when hovering over the field:</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>
_x000D_
_x000D_
_x000D_

Option 3 - Only display the 'x' if the input element has a value: (example here)

_x000D_
_x000D_
Array.prototype.forEach.call(document.querySelectorAll('.clearable-input'), function(el) {
  var input = el.querySelector('input');

  conditionallyHideClearIcon();
  input.addEventListener('input', conditionallyHideClearIcon);
  el.querySelector('[data-clear-input]').addEventListener('click', function(e) {
    input.value = '';
    conditionallyHideClearIcon();
  });

  function conditionallyHideClearIcon(e) {
    var target = (e && e.target) || input;
    target.nextElementSibling.style.display = target.value ? 'block' : 'none';
  }
});
_x000D_
.clearable-input {
  position: relative;
  display: inline-block;
}
.clearable-input > input {
  padding-right: 1.4em;
}
.clearable-input >[data-clear-input] {
  display: none;
  position: absolute;
  top: 0;
  right: 0;
  font-weight: bold;
  font-size: 1.4em;
  padding: 0 0.2em;
  line-height: 1em;
  cursor: pointer;
}
.clearable-input > input::-ms-clear {
  display: none;
}
_x000D_
<p>Only display the 'x' if the `input` element has a value:</p>

<div class="clearable-input">
  <input type="text" />
  <span data-clear-input>&times;</span>
</div>

<div class="clearable-input">
  <input type="text" value="Clear this." />
  <span data-clear-input>&times;</span>
</div>
_x000D_
_x000D_
_x000D_

Dynamically update values of a chartjs chart

So simple, Just replace the chart canvas element.

$('#canvas').replaceWith(' id="canvas" height="200px" width="368px">');

Using {% url ??? %} in django templates

Make sure (django 1.5 and beyond) that you put the url name in quotes, and if your url takes parameters they should be outside of the quotes (I spent hours figuring out this mistake!).

{% url 'namespace:view_name' arg1=value1 arg2=value2 as the_url %}
<a href="{{ the_url }}"> link_name </a>

Multiple select in Visual Studio?

in visual 2019, Open Options to show all enter image description here

and multi select: keep Ctrl + Alt then click position you want or, keep Shift + Alt then click position to multi select multi line from start to end line clicked

Use .corr to get the correlation between two columns

When you call this:

data = Top15[['Citable docs per Capita','Energy Supply per Capita']]
correlation = data.corr(method='pearson')

Since, DataFrame.corr() function performs pair-wise correlations, you have four pair from two variables. So, basically you are getting diagonal values as auto correlation (correlation with itself, two values since you have two variables), and other two values as cross correlations of one vs another and vice versa.

Either perform correlation between two series to get a single value:

from scipy.stats.stats import pearsonr
docs_col = Top15['Citable docs per Capita'].values
energy_col = Top15['Energy Supply per Capita'].values
corr , _ = pearsonr(docs_col, energy_col)

or, if you want a single value from the same function (DataFrame's corr):

single_value = correlation[0][1] 

Hope this helps.

Reload child component when variables on parent component changes. Angular2

On Angular to update a component including its template, there is a straight forward solution to this, having an @Input property on your ChildComponent and add to your @Component decorator changeDetection: ChangeDetectionStrategy.OnPush as follows:

import { ChangeDetectionStrategy } from '@angular/core';

@Component({
    selector: 'master',
    templateUrl: templateUrl,
    styleUrls:[styleUrl1],
    changeDetection: ChangeDetectionStrategy.OnPush    
})

export class ChildComponent{
  @Input() data: MyData;
}

This will do all the work of check if Input data have changed and re-render the component

Algorithm to generate all possible permutations of a list?

You can't really talk about solving a permultation problem in recursion without posting an implementation in a (dialect of) language that pioneered the idea. So, for the sake of completeness, here is one of the ways that can be done in Scheme.

(define (permof wd)
  (cond ((null? wd) '())
        ((null? (cdr wd)) (list wd))
        (else
         (let splice ([l '()] [m (car wd)] [r (cdr wd)])
           (append
            (map (lambda (x) (cons m x)) (permof (append l r)))
            (if (null? r)
                '()
                (splice (cons m l) (car r) (cdr r))))))))

calling (permof (list "foo" "bar" "baz")) we'll get:

'(("foo" "bar" "baz")
  ("foo" "baz" "bar")
  ("bar" "foo" "baz")
  ("bar" "baz" "foo")
  ("baz" "bar" "foo")
  ("baz" "foo" "bar"))

I won't go into the algorithm details because it's been explained enough in other posts. The idea is the same.

However, recursive problems tend to be much harder to model and think about in destructive medium like Python, C, and Java, while in Lisp or ML it can be concisely expressed.

Create Carriage Return in PHP String?

Fragment PHP (in console Cloud9):

echo "\n";
echo "1: first_srt=1\nsecnd_srt=2\n";
echo "\n";
echo '2: first_srt=1\nsecnd_srt=2\n';
echo "\n";
echo "==============\n";
echo "\n";

resulting output:

  1: first_srt=1
  secnd_srt=2

  2: first_srt=1\nsecnd_srt=2\n
  ==============

Difference between 1 and 2: " versus '

How can I pass POST parameters in a URL?

You can make a link perform an Ajax post request when it's clicked.

In jQuery:

$('a').click(function(e) {
    var $this = $(this);
    e.preventDefault();
    $.post('url', {'user': 'something', 'foo': 'bar'}, function() {
        window.location = $this.attr('href');
    });
});

You could also make the link submit a POST form with JavaScript:

<form action="url" method="post">
    <input type="hidden" name="user" value="something" />
    <a href="#">CLick</a>
</form>

<script>
    $('a').click(function(e) {
        e.preventDefault();
        $(this).parents('form').submit();
    });
</script>

SQL Server 2005 Setting a variable to the result of a select query

-- Sql Server 2005 Management studio


use Master
go
DECLARE @MyVar bigint
SET @myvar = (SELECT count(*) FROM spt_values);
SELECT @myvar

Result: 2346 (in my db)

-- Note: @myvar = @Myvar

The OutputPath property is not set for this project

I got this problem after adding a new platform to my project. In my case .csproj file was under Perforce source control and was read-only. I checked it out but VS didn't catch the change until I restarted it.

Cannot lower case button text in android studio

This is fixable in the application code by setting the button's TransformationMethod null, e.g.

mButton.setTransformationMethod(null);

Is there a difference between x++ and ++x in java?

If it's like many other languages you may want to have a simple try:

i = 0;
if (0 == i++) // if true, increment happened after equality check
if (2 == ++i) // if true, increment happened before equality check

If the above doesn't happen like that, they may be equivalent

How do you print in a Go test using the "testing" package?

For example,

package verbose

import (
    "fmt"
    "testing"
)

func TestPrintSomething(t *testing.T) {
    fmt.Println("Say hi")
    t.Log("Say bye")
}

go test -v
=== RUN TestPrintSomething
Say hi
--- PASS: TestPrintSomething (0.00 seconds)
    v_test.go:10: Say bye
PASS
ok      so/v    0.002s

Command go

Description of testing flags

-v
Verbose output: log all tests as they are run. Also print all
text from Log and Logf calls even if the test succeeds.

Package testing

func (*T) Log

func (c *T) Log(args ...interface{})

Log formats its arguments using default formatting, analogous to Println, and records the text in the error log. For tests, the text will be printed only if the test fails or the -test.v flag is set. For benchmarks, the text is always printed to avoid having performance depend on the value of the -test.v flag.

How do you get/set media volume (not ringtone volume) in Android?

AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float percent = 0.7f;
int seventyVolume = (int) (maxVolume*percent);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, seventyVolume, 0);

How to manage Angular2 "expression has changed after it was checked" exception when a component property depends on current datetime

TL;DR

ngAfterViewInit() {
    setTimeout(() => {
        this.dateNow = new Date();
    });
}

Although this is a workaround, sometimes it's really hard to solve this issue in any nicer way, so don't blame yourself if you are using this approach. That's okay.

Examples: The initial issue [link], Solved with setTimeout() [link]


How to avoid

In general this error usually happens after you add somewhere (even in parent/child components) ngAfterViewInit. So first question is to ask yourself - can I live without ngAfterViewInit? Perhaps you move the code somewhere ( ngAfterViewChecked might be an alternative).

Example: [link]


Also

Also async stuff in ngAfterViewInit that affects DOM might cause this. Also can be solved via setTimeout or by adding the delay(0) operator in the pipe:

ngAfterViewInit() {
  this.foo$
    .pipe(delay(0)) //"delay" here is an alternative to setTimeout()
    .subscribe();
}

Example: [link]


Nice Reading

Good article about how to debug this and why it happens: link

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How do I revert to a previous package in Anaconda?

I had to use the install function instead:

conda install pandas=0.13.1

Select multiple columns in data.table by their numeric indices

It's a bit verbose, but i've gotten used to using the hidden .SD variable.

b<-data.table(a=1,b=2,c=3,d=4)
b[,.SD,.SDcols=c(1:2)]

It's a bit of a hassle, but you don't lose out on other data.table features (I don't think), so you should still be able to use other important functions like join tables etc.

grep using a character vector with multiple patterns

Take away the spaces. So do:

matches <- unique(grep("A1|A9|A6", myfile$Letter, value=TRUE, fixed=TRUE))

Forward host port to docker container

Your docker host exposes an adapter to all the containers. Assuming you are on recent ubuntu, you can run

ip addr

This will give you a list of network adapters, one of which will look something like

3: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP
link/ether 22:23:6b:28:6b:e0 brd ff:ff:ff:ff:ff:ff
inet 172.17.42.1/16 scope global docker0
inet6 fe80::a402:65ff:fe86:bba6/64 scope link
   valid_lft forever preferred_lft forever

You will need to tell rabbit/mongo to bind to that IP (172.17.42.1). After that, you should be able to open connections to 172.17.42.1 from within your containers.

SQL how to increase or decrease one for a int column in one command

To answer the first:

UPDATE Orders SET Quantity = Quantity + 1 WHERE ...

To answer the second:

There are several ways to do this. Since you did not specify a database, I will assume MySQL.

  1. INSERT INTO table SET x=1, y=2 ON DUPLICATE KEY UPDATE x=x+1, y=y+2
  2. REPLACE INTO table SET x=1, y=2

They both can handle your question. However, the first syntax allows for more flexibility to update the record rather than just replace it (as the second one does).

Keep in mind that for both to exist, there has to be a UNIQUE key defined...

Oracle SQL query for Date format

you can use this command by getting your data. this will extract your data...

select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';

Callback when DOM is loaded in react.js

The below is what I came up with to wait for when the DOM is ready before trying to get a class using document.getElementsByClassName. I called this function from the componentDidMount() lifecycle method.

     changeIcon() {
            if (
                document.getElementsByClassName('YOURCLASSNAME')
                    .length > 0 &&
                document.getElementsByClassName('YOURCLASSNAME').length > 0
            ) {
                document.getElementsByClassName(
                    'YOURCLASSNAME'
                )[0].className = 'YOUR-NEW-CLASSNAME';
                document.getElementsByClassName(
                    'YOUR-OTHER-EXISTING-CLASSNAME'
                )[0].style.display = 'block';
            } else {
                setTimeout(this.changeIcon, 500);
            }
     }

Where to change default pdf page width and font size in jspdf.debug.js?

My case was to print horizontal (landscape) summary section - so:

}).then((canvas) => {
  const img = canvas.toDataURL('image/jpg');
  new jsPDF({
        orientation: 'l', // landscape
        unit: 'pt', // points, pixels won't work properly
        format: [canvas.width, canvas.height] // set needed dimensions for any element
  });
  pdf.addImage(img, 'JPEG', 0, 0, canvas.width, canvas.height);
  pdf.save('your-filename.pdf');
});

Android - Share on Facebook, Twitter, Mail, ecc

I think the following code will help....

public void btnShareClick(View v) {
    // shareBtnFlag = 1;
    Dialog d = new Dialog(DrawAppActivity.this);
    d.requestWindowFeature(d.getWindow().FEATURE_NO_TITLE);
    d.setCancelable(true);

    d.setContentView(R.layout.sharing);

    final Button btnFacebook = (Button) d.findViewById(R.id.btnFacebook);
    final Button btnEmail = (Button) d.findViewById(R.id.btnEmail);

    btnEmail.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            if (!btnEmail.isSelected()) {
                btnEmail.setSelected(true);
            } else {
                btnEmail.setSelected(false);
            }
            saveBtnFlag = 1;
            // Check if email id is available-------------
            AccountManager manager = AccountManager
                    .get(DrawAppActivity.this);
            Account[] accounts = manager.getAccountsByType("com.google");
            Account account = CommonFunctions.getAccount(manager);
            if (account.name != null) {
                emailSendingTask eTask = new emailSendingTask();
                eTask.execute();
                if (CommonFunctions.createDirIfNotExists(getResources()
                        .getString(R.string.path)))

                {
                    tempImageSaving(
                            getResources().getString(R.string.path),
                            getCurrentImage());
                }

                Intent sendIntent;
                sendIntent = new Intent(Intent.ACTION_SEND);
                sendIntent.setType("application/octet-stream");
                sendIntent.setType("image/jpeg");
                sendIntent.putExtra(Intent.EXTRA_EMAIL,
                        new String[] { account.name });
                sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Drawing App");
                sendIntent.putExtra(Intent.EXTRA_TEXT, "Check This Image");
                sendIntent.putExtra(Intent.EXTRA_STREAM,
                        Uri.parse("file://" + tempPath.getPath()));

                List<ResolveInfo> list = getPackageManager()
                        .queryIntentActivities(sendIntent,
                                PackageManager.MATCH_DEFAULT_ONLY);

                if (list.size() != 0) {

                    startActivity(Intent.createChooser(sendIntent,
                            "Send Email Using:"));

                }

                else {
                    AlertDialog.Builder confirm = new AlertDialog.Builder(
                            DrawAppActivity.this);
                    confirm.setTitle(R.string.app_name);
                    confirm.setMessage("No Email Sending App Available");
                    confirm.setPositiveButton("Set Account",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    dialog.dismiss();
                                }
                            });
                    confirm.show();
                }
            } else {
                AlertDialog.Builder confirm = new AlertDialog.Builder(
                        DrawAppActivity.this);
                confirm.setTitle(R.string.app_name);
                confirm.setMessage("No Email Account Available!");
                confirm.setPositiveButton("Set Account",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {
                                Intent i = new Intent(
                                        Settings.ACTION_SYNC_SETTINGS);
                                startActivity(i);
                                dialog.dismiss();
                            }
                        });
                confirm.setNegativeButton("Cancel",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                    int which) {

                                dialog.dismiss();
                            }
                        });
                confirm.show();
            }
        }

    });

    btnFacebook.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
            if (!btnFacebook.isSelected()) {
                btnFacebook.setSelected(true);
            } else {
                btnFacebook.setSelected(false);
            }
            saveBtnFlag = 1;
            // if (connection.isInternetOn()) {

            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {
                getCurrentImage();
                Intent i = new Intent(DrawAppActivity.this,
                        FaceBookAuthentication.class);
                i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
                startActivity(i);
            }

            else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);
            }
        }
    });
    d.show();

}

public void tempImageSaving(String tmpPath, byte[] image) {
    Random rand = new Random();

    tempfile = new File(Environment.getExternalStorageDirectory(), tmpPath);
    if (!tempfile.exists()) {
        tempfile.mkdirs();
    }

    tempPath = new File(tempfile.getPath(), "DrawApp" + rand.nextInt()
            + ".jpg");
    try {
        FileOutputStream fos1 = new FileOutputStream(tempPath.getPath());
        fos1.write(image);

        fos1.flush();
        fos1.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    sendBroadcast(new Intent(
            Intent.ACTION_MEDIA_MOUNTED,
            Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}

public byte[] getCurrentImage() {

    Bitmap b = drawingSurface.getBitmap();
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    b.compress(Bitmap.CompressFormat.PNG, 100, stream);

    byteArray = stream.toByteArray();

    return byteArray;
}

private class emailSendingTask extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(DrawAppActivity.this);
        progressDialog.setTitle(R.string.app_name);
        progressDialog.setMessage("Saving..Please Wait..");
        // progressDialog.setIcon(R.drawable.icon);
        progressDialog.show();

    }

    @Override
    protected String doInBackground(String... urls) {

        String response = "";
        try {

            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {

                response = "Yes";

            } else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return response;

    }

    @Override
    protected void onPostExecute(String result) {

        if (result.contains("Yes")) {
            getCurrentImage();

        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://"
                        + Environment.getExternalStorageDirectory())));

        progressDialog.cancel();
    }
}

private class ImageSavingTask extends AsyncTask<String, Void, String> {
    @Override
    protected void onPreExecute() {
        progressDialog = new ProgressDialog(DrawAppActivity.this);
        progressDialog.setTitle(R.string.app_name);
        progressDialog.setMessage("Saving..Please Wait..");
        // progressDialog.setIcon(R.drawable.icon);
        progressDialog.show();

    }

    @Override
    protected String doInBackground(String... urls) {

        String response = "";
        try {

            if (android.os.Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED)) {

                response = "Yes";

            } else {
                ShowAlertMessage.showDialog(DrawAppActivity.this,
                        R.string.app_name, R.string.Sd_card,
                        R.string.button_retry);

            }

        } catch (Exception e) {

            e.printStackTrace();
        }

        return response;

    }

    @Override
    protected void onPostExecute(String result) {

        if (result.contains("Yes")) {
            getCurrentImage();

            if (CommonFunctions.createDirIfNotExists(getResources()
                    .getString(R.string.path)))

            {
                saveImageInSdCard(getResources().getString(R.string.path),
                        getCurrentImage());
            }
        }
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
                Uri.parse("file://"
                        + Environment.getExternalStorageDirectory())));

        progressDialog.cancel();
    }
}

For facebook application use facebook SDK

How do I access the HTTP request header fields via JavaScript?

I would imagine Google grabs some data server-side - remember, when a page loads into your browser that has Google Analytics code within it, your browser makes a request to Google's servers; Google can obtain data in that way as well as through the JavaScript embedded in the page.

Tried to Load Angular More Than Once

Seems like nobody has mentioned this anywhere so here is what triggered it for me: I had the ng-view directive on my body. Changing it like so

<body layout="column">
<div ng-view></div>
...
</body>

stopped the error.

Get each line from textarea

It works for me:

if (isset($_POST['MyTextAreaName'])){
    $array=explode( "\r\n", $_POST['MyTextAreaName'] );

now, my $array will have all the lines I need

    for ($i = 0; $i <= count($array); $i++) 
    {
        echo (trim($array[$i]) . "<br/>");
    }

(make sure to close the if block with another curly brace)

}

SaveFileDialog setting default path and file type?

Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                DefaultExt = "*.xml",
                Filter = "BIN Files (*.bin)|*.bin",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            };

            var result = saveFileDialog.ShowDialog();
            if (result != null && result == true)
            {
                // Save the file here
            }

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

It didn't work for me either. I changed

CUSTOM_ELEMENTS_SCHEMA

for

NO_ERRORS_SCHEMA

which was suggested in this article: https://scotch.io/tutorials/angular-2-transclusion-using-ng-content

Now it works.

Getting the HTTP Referrer in ASP.NET

Use the Request.UrlReferrer property.

Underneath the scenes it is just checking the ServerVariables("HTTP_REFERER") property.

How do I modify fields inside the new PostgreSQL JSON datatype?

To build upon @pozs's answers, here are a couple more PostgreSQL functions which may be useful to some. (Requires PostgreSQL 9.3+)

Delete By Key: Deletes a value from JSON structure by key.

CREATE OR REPLACE FUNCTION "json_object_del_key"(
  "json"          json,
  "key_to_del"    TEXT
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_to_del") IS NULL THEN "json"
  ELSE (SELECT concat('{', string_agg(to_json("key") || ':' || "value", ','), '}')
          FROM (SELECT *
                  FROM json_each("json")
                 WHERE "key" <> "key_to_del"
               ) AS "fields")::json
END
$function$;

Recursive Delete By Key: Deletes a value from JSON structure by key-path. (requires @pozs's json_object_set_key function)

CREATE OR REPLACE FUNCTION "json_object_del_path"(
  "json"          json,
  "key_path"      TEXT[]
)
  RETURNS json
  LANGUAGE sql
  IMMUTABLE
  STRICT
AS $function$
SELECT CASE
  WHEN ("json" -> "key_path"[l] ) IS NULL THEN "json"
  ELSE
     CASE COALESCE(array_length("key_path", 1), 0)
         WHEN 0 THEN "json"
         WHEN 1 THEN "json_object_del_key"("json", "key_path"[l])
         ELSE "json_object_set_key"(
           "json",
           "key_path"[l],
           "json_object_del_path"(
             COALESCE(NULLIF(("json" -> "key_path"[l])::text, 'null'), '{}')::json,
             "key_path"[l+1:u]
           )
         )
       END
    END
  FROM array_lower("key_path", 1) l,
       array_upper("key_path", 1) u
$function$;

Usage examples:

s1=# SELECT json_object_del_key ('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 'foo'),
            json_object_del_path('{"hello":[7,3,1],"foo":{"mofu":"fuwa", "moe":"kyun"}}',
                                 '{"foo","moe"}');

 json_object_del_key |          json_object_del_path
---------------------+-----------------------------------------
 {"hello":[7,3,1]}   | {"hello":[7,3,1],"foo":{"mofu":"fuwa"}}

jQuery prevent change for select

If you simply want to prevent interaction with the select altogether when my_condition is true, you could always just capture the mousedown event and do your event prevent there:

var my_condition = true;

$("#my_select").mousedown(function(e){
  if(my_condition)
  {
     e.preventDefault();
     alert("Because my_condition is true, you cannot make this change.");
  }
});

This will prevent any change event from ever occurring while my_condition is true.

Toggle visibility property of div

It's better if you check visibility like this: if($('#video-over').is(':visible'))

How to change port number for apache in WAMP

Change port number for Xampp Go to the file C:\xampp\apache\conf\httpd.conf

#Listen 12.34.56.78:80
Listen 80

Change 80 to 82

as

#Listen 12.34.56.78:82
Listen 82

now your url will be

http://localhost:82

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

For people that find this question by searching for the error message, you can also see this error if you make a mistake in your @JsonProperty annotations such that you annotate a List-typed property with the name of a single-valued field:

@JsonProperty("someSingleValuedField") // Oops, should have been "someMultiValuedField"
public List<String> getMyField() { // deserialization fails - single value into List
  return myField;
}

Convert columns to string in Pandas

Using .apply() with a lambda conversion function also works in this case:

total_rows['ColumnID'] = total_rows['ColumnID'].apply(lambda x: str(x))

For entire dataframes you can use .applymap(). (but in any case probably .astype() is faster)

JavaScript: SyntaxError: missing ) after argument list

You got an extra } to many as seen below:

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        } // <-- REMOVE THIS :)
    }, false);
};

A very good tool for those things is jsFiddle. I have created a fiddle with your invalid code and when clicking the TidyUp button it formats your code which makes it clearer if there are any possible mistakes with missing braces.


DEMO - Your code in a fiddle, have a play :)


Android, canvas: How do I clear (delete contents of) a canvas (= bitmaps), living in a surfaceView?

How do I clear (or redraw) the WHOLE canvas for a new layout (= try at the game) ?

Just call Canvas.drawColor(Color.BLACK), or whatever color you want to clear your Canvas with.

And: how can I update just a part of the screen ?

There is no such method that just update a "part of the screen" since Android OS is redrawing every pixel when updating the screen. But, when you're not clearing old drawings on your Canvas, the old drawings are still on the surface and that is probably one way to "update just a part" of the screen.

So, if you want to "update a part of the screen", just avoid calling Canvas.drawColor() method.

SQL Server - Convert date field to UTC

Unless I missed something above (possible), all of the methods above are flawed in that they don't take the overlap when switching from daylight savings (say EDT) to standard time (say EST) into account. A (very verbose) example:

[1] EDT 2016-11-06 00:59 - UTC 2016-11-06 04:59
[2] EDT 2016-11-06 01:00 - UTC 2016-11-06 05:00
[3] EDT 2016-11-06 01:30 - UTC 2016-11-06 05:30
[4] EDT 2016-11-06 01:59 - UTC 2016-11-06 05:59
[5] EST 2016-11-06 01:00 - UTC 2016-11-06 06:00
[6] EST 2016-11-06 01:30 - UTC 2016-11-06 06:30
[7] EST 2016-11-06 01:59 - UTC 2016-11-06 06:59
[8] EST 2016-11-06 02:00 - UTC 2016-11-06 07:00

Simple hour offsets based on date and time won't cut it. If you don't know if the local time was recorded in EDT or EST between 01:00 and 01:59, you won't have a clue! Let's use 01:30 for example: if you find later times in the range 01:31 through 01:59 BEFORE it, you won't know if the 01:30 you're looking at is [3 or [6. In this case, you can get the correct UTC time with a bit of coding be looking at previous entries (not fun in SQL), and this is the BEST case...

Say you have the following local times recorded, and didn't dedicate a bit to indicate EDT or EST:

                     UTC time         UTC time         UTC time
                     if [2] and [3]   if [2] and [3]   if [2] before
local time           before switch    after switch     and [3] after
[1] 2016-11-06 00:43     04:43         04:43           04:43
[2] 2016-11-06 01:15     05:15         06:15           05:15
[3] 2016-11-06 01:45     05:45         06:45           06:45
[4] 2016-11-06 03:25     07:25         07:25           07:25

Times [2] and [3] may be in the 5 AM timeframe, the 6 AM timeframe, or one in the 5 AM and the other in the 6 AM timeframe . . . In other words: you are hosed, and must throw out all readings between 01:00:00 and 01:59:59. In this circumstance, there is absolutely no way to resolve the actual UTC time!

Convert seconds to hh:mm:ss in Python

Not being a Python person, but the easiest without any libraries is just:

total   = 3800
seconds = total % 60
total   = total - seconds
hours   = total / 3600
total   = total - (hours * 3600)
mins    = total / 60

Why do I get access denied to data folder when using adb?

$ adb shell

$ cd /data

$ ls

opendir failed, Permission denied


You should do this:

$ adb shell

$ cd /data

shell@android:/data $ run-as com.your.package 

shell@android:/data/data/com.your.package $ ls

OK!

Multiple left joins on multiple tables in one query

This kind of query should work - after rewriting with explicit JOIN syntax:

SELECT something
FROM   master      parent
JOIN   master      child ON child.parent_id = parent.id
LEFT   JOIN second parentdata ON parentdata.id = parent.secondary_id
LEFT   JOIN second childdata ON childdata.id = child.secondary_id
WHERE  parent.parent_id = 'rootID'

The tripping wire here is that an explicit JOIN binds before "old style" CROSS JOIN with comma (,). I quote the manual here:

In any case JOIN binds more tightly than the commas separating FROM-list items.

After rewriting the first, all joins are applied left-to-right (logically - Postgres is free to rearrange tables in the query plan otherwise) and it works.

Just to make my point, this would work, too:

SELECT something
FROM   master parent
LEFT   JOIN second parentdata ON parentdata.id = parent.secondary_id
,      master child
LEFT   JOIN second childdata ON childdata.id = child.secondary_id
WHERE  child.parent_id = parent.id
AND    parent.parent_id = 'rootID'

But explicit JOIN syntax is generally preferable, as your case illustrates once again.

And be aware that multiple (LEFT) JOIN can multiply rows:

Convert date field into text in Excel

You can use TEXT like this as part of a concatenation

=TEXT(A1,"dd-mmm-yy") & " other string"

enter image description here

One liner for If string is not null or empty else

This may help:

public string NonBlankValueOf(string strTestString)
{
    return String.IsNullOrEmpty(strTestString)? "0": strTestString;
}

alter the size of column in table containing data

Case 1 : Yes, this works fine.

Case 2 : This will fail with the error ORA-01441 : cannot decrease column length because some value is too big.

Share and enjoy.

What are the differences between Mustache.js and Handlebars.js?

I feel that one of the mentioned cons for "Handlebars" isnt' really valid anymore.

Handlebars.java now allows us to share the same template languages for both client and server which is a big win for large projects with 1000+ components that require serverside rendering for SEO

Take a look at https://github.com/jknack/handlebars.java

Declare a variable as Decimal

To declare a variable as a Decimal, first declare it as a Variant and then convert to Decimal with CDec. The type would be Variant/Decimal in the watch window:

enter image description here

Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.

In the example below, we see that the expression:

0.1 + 0.11 = 0.21

is either True or False, depending on whether the collectibles (0.1,0.11) are declared as Double or as Decimal:

Public Sub TestMe()

    Dim preciseA As Variant: preciseA = CDec(0.1)
    Dim preciseB As Variant: preciseB = CDec(0.11)

    Dim notPreciseA As Double: notPreciseA = 0.1
    Dim notPreciseB As Double: notPreciseB = 0.11

    Debug.Print preciseA + preciseB
    Debug.Print preciseA + preciseB = 0.21 'True

    Debug.Print notPreciseA + notPreciseB
    Debug.Print notPreciseA + notPreciseB = 0.21 'False

End Sub

enter image description here

Javascript: getFullyear() is not a function

You are overwriting the start date object with the value of a DOM Element with an id of Startdate.

This should work:

var start = new Date(document.getElementById('Stardate').value);

var y = start.getFullYear();

How to submit a form on enter when the textarea has focus?

<form id="myform">
    <input type="textbox" id="field"/>
    <input type="button" value="submit">
</form>

<script>
    $(function () {
        $("#field").keyup(function (event) {
            if (event.which === 13) {
                document.myform.submit();
            }
        }
    });
</script>

How to make a Qt Widget grow with the window size?

In Designer, activate the centralWidget and assign a layout, e.g. horizontal or vertical layout. Then your QFormLayout will automatically resize.

Image of Designer

Always make sure, that all widgets have a layout! Otherwise, automatic resizing will break with that widget!

See also

Controls insist on being too large, and won't resize, in QtDesigner

Is there a simple way to use button to navigate page as a link does in angularjs

With bootstrap you can use

<a href="#/new-page.html" class="btn btn-primary">
    Click
</a>

What is the best way to delete a component with CLI

I needed to delete an Angular 6 directive whose spec file was erroneous. Even after deleting the offending files, removing all references to it and rebuilding the app, TS was still reporting the same error. What worked for me was restarting Visual Studio - this cleared the error and all traces of the old unwanted directive.

How to read file with async/await properly?

To keep it succint and retain all functionality of fs:

const fs = require('fs');
const fsPromises = fs.promises;

async function loadMonoCounter() {
    const data = await fsPromises.readFile('monolitic.txt', 'binary');
    return new Buffer(data);
}

Importing fs and fs.promises separately will give access to the entire fs API while also keeping it more readable... So that something like the next example is easily accomplished.

// the 'next example'
fsPromises.access('monolitic.txt', fs.constants.R_OK | fs.constants.W_OK)
    .then(() => console.log('can access'))
    .catch(() => console.error('cannot access'));

SQL Delete Records within a specific Range

if you use Sql Server

delete from Table where id between 79 and 296

After your edit : you now clarified that you want :

ID (>79 AND < 296)

So use this :

delete from Table where id > 79 and id < 296

Method to Add new or update existing item in Dictionary

The only problem could be if one day

map[key] = value

will transform to -

map[key]++;

and that will cause a KeyNotFoundException.

Cannot read property 'push' of undefined when combining arrays

order is an Object, not an Array().

push() is for arrays.

Refer to this post

Try this though(but your subobjects have to be Arrays()):

var order = new Array();

// initialize order; n = index
order[n] = new Array();

// and then you can perform push()
order[n].push(some_value);

Or you can just use order as an array of non-array objects:

var order = new Array();

order.push(a[n]);

Check existence of directory and create if doesn't exist

The use of file.exists() to test for the existence of the directory is a problem in the original post. If subDir included the name of an existing file (rather than just a path), file.exists() would return TRUE, but the call to setwd() would fail because you can't set the working directory to point at a file.

I would recommend the use of file_test(op="-d", subDir), which will return "TRUE" if subDir is an existing directory, but FALSE if subDir is an existing file or a non-existent file or directory. Similarly, checking for a file can be accomplished with op="-f".

Additionally, as described in another comment, the working directory is part of the R environment and should be controlled by the user, not a script. Scripts should, ideally, not change the R environment. To address this problem, I might use options() to store a globally available directory where I wanted all of my output.

So, consider the following solution, where someUniqueTag is just a programmer-defined prefix for the option name, which makes it unlikely that an option with the same name already exists. (For instance, if you were developing a package called "filer", you might use filer.mainDir and filer.subDir).

The following code would be used to set options that are available for use later in other scripts (thus avoiding the use of setwd() in a script), and to create the folder if necessary:

mainDir = "c:/path/to/main/dir"
subDir = "outputDirectory"

options(someUniqueTag.mainDir = mainDir)
options(someUniqueTag.subDir = "subDir")

if (!file_test("-d", file.path(mainDir, subDir)){
  if(file_test("-f", file.path(mainDir, subDir)) {
    stop("Path can't be created because a file with that name already exists.")
  } else {
    dir.create(file.path(mainDir, subDir))
  }
}

Then, in any subsequent script that needed to manipulate a file in subDir, you might use something like:

mainDir = getOption(someUniqueTag.mainDir)
subDir = getOption(someUniqueTag.subDir)
filename = "fileToBeCreated.txt"
file.create(file.path(mainDir, subDir, filename))

This solution leaves the working directory under the control of the user.

How do you run a script on login in *nix?

Place it in your bash profile:

~/.bash_profile

MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

A key is just a normal index. A way over simplification is to think of it like a card catalog at a library. It points MySQL in the right direction.

A unique key is also used for improved searching speed, but it has the constraint that there can be no duplicated items (there are no two x and y where x is not y and x == y).

The manual explains it as follows:

A UNIQUE index creates a constraint such that all values in the index must be distinct. An error occurs if you try to add a new row with a key value that matches an existing row. This constraint does not apply to NULL values except for the BDB storage engine. For other engines, a UNIQUE index permits multiple NULL values for columns that can contain NULL. If you specify a prefix value for a column in a UNIQUE index, the column values must be unique within the prefix.

A primary key is a 'special' unique key. It basically is a unique key, except that it's used to identify something.

The manual explains how indexes are used in general: here.

In MSSQL, the concepts are similar. There are indexes, unique constraints and primary keys.

Untested, but I believe the MSSQL equivalent is:

CREATE TABLE tmp (
  id int NOT NULL PRIMARY KEY IDENTITY,
  uid varchar(255) NOT NULL CONSTRAINT uid_unique UNIQUE,
  name varchar(255) NOT NULL,
  tag int NOT NULL DEFAULT 0,
  description varchar(255),
);

CREATE INDEX idx_name ON tmp (name);
CREATE INDEX idx_tag ON tmp (tag);

Edit: the code above is tested to be correct; however, I suspect that there's a much better syntax for doing it. Been a while since I've used SQL server, and apparently I've forgotten quite a bit :).

Interfaces — What's the point?

Consider you can't use multiple inheritance in C#, and then look at your question again.

Python can't find module in the same folder

If you are sure that all the modules, files you're trying to import are in the same folder and they should be picked directly just by giving the name and not the reference path then your editor or terminal should have opened the main folder where all the files/modules are present.

Either, try running from Terminal, make sure first you go to the correct directory.

cd path to the root folder where all the modules are

python script.py

Or if running [F5] from the editor i.e VsCode then open the complete folder there and not the individual files.

How to specify a port number in SQL Server connection string?

The correct SQL connection string for SQL with specify port is use comma between ip address and port number like following pattern: xxx.xxx.xxx.xxx,yyyy

How to delete Tkinter widgets from a window?

You can use forget method on the widget

from tkinter import *

root = Tk()

b = Button(root, text="Delete me", command=b.forget)
b.pack()

b['command'] = b.forget

root.mainloop()

How to convert a string with comma-delimited items to a list in Python?

Using functional Python:

text=filter(lambda x:x!=',',map(str,text))

Can't create handler inside thread that has not called Looper.prepare()

that's what i did.

new Handler(Looper.getMainLooper()).post(new Runnable() {
    @Override
    public void run() {
        Toast(...);
    }
});

Visual components are "locked" to changes from outside threads. So, since the toast shows stuff on the main screen that is managed by the main thread, you need to run this code on that thread. Hope that helps:)

Get product id and product type in magento?

IN MAGENTO query in the database and fetch the result like. product id, product name and manufracturer with out using the product flat table use the eav catalog_product_entity and its attribute table product_id product_name manufacturer 1 | PRODUCTA | NOKIA 2 | PRODUCTB | SAMSUNG

Passing a dictionary to a function as keyword parameters

Here ya go - works just any other iterable:

d = {'param' : 'test'}

def f(dictionary):
    for key in dictionary:
        print key

f(d)

twitter bootstrap typeahead ajax example

I've augmented the original typeahead Bootstrap plugin with ajax capabilities. Very easy to use:

$("#ajax-typeahead").typeahead({
     ajax: "/path/to/source"
});

Here's the github repo: Ajax-Typeahead

SQL - Query to get server's IP address

A simpler way to get the machine name without the \InstanceName is:

SELECT SERVERPROPERTY('MachineName')

How do you create a temporary table in an Oracle database?

CREATE GLOBAL TEMPORARY TABLE Table_name
    (startdate DATE,
     enddate DATE,
     class CHAR(20))
  ON COMMIT DELETE ROWS;

Create unique constraint with null columns

You can store favourites with no associated menu in a separate table:

CREATE TABLE FavoriteWithoutMenu
(
  FavoriteWithoutMenuId uuid NOT NULL, --Primary key
  UserId uuid NOT NULL,
  RecipeId uuid NOT NULL,
  UNIQUE KEY (UserId, RecipeId)
)

Setting dynamic scope variables in AngularJs - scope.<some_string>

The solution I have found is to use $parse.

"Converts Angular expression into a function."

If anyone has a better one please add a new answer to the question!

Here is the example:

var the_string = 'life.meaning';

// Get the model
var model = $parse(the_string);

// Assigns a value to it
model.assign($scope, 42);

// Apply it to the scope
// $scope.$apply(); <- According to comments, this is no longer needed

console.log($scope.life.meaning);  // logs 42

How to use orderby with 2 fields in linq?

MyList.OrderBy(x => x.StartDate).ThenByDescending(x => x.EndDate);

Note that you can use as well the Descending keyword in the OrderBy (in case you need). So another possible answer is:

MyList.OrderByDescending(x => x.StartDate).ThenByDescending(x => x.EndDate);

PowerShell Script to Find and Replace for all Files with a Specific Extension

PowerShell is a good choice ;) It is very easy to enumerate files in given directory, read them and process.

The script could look like this:

Get-ChildItem C:\Projects *.config -recurse |
    Foreach-Object {
        $c = ($_ | Get-Content) 
        $c = $c -replace '<add key="Environment" value="Dev"/>','<add key="Environment" value="Demo"/>'
        [IO.File]::WriteAllText($_.FullName, ($c -join "`r`n"))
    }

I split the code to more lines to be readable for you. Note that you could use Set-Content instead of [IO.File]::WriteAllText, but it adds new line at the end. With WriteAllText you can avoid it.

Otherwise the code could look like this: $c | Set-Content $_.FullName.

How to reset radiobuttons in jQuery so that none is checked

<div id="radio">
<input type="radio" id="radio1" name="radio"/><label for="radio1">Bar Chart</label>
<input type="radio" id="radio2" name="radio"/><label for="radio2">Pie Chart</label>
<input type="radio" id="radio3" name="radio"/><label for="radio3">Datapoint Chart</label>
</div>

$('#radio input').removeAttr('checked');
// Refresh the jQuery UI buttonset.                  
$( "#radio" ).buttonset('refresh');

Volatile Vs Atomic

The effect of the volatile keyword is approximately that each individual read or write operation on that variable is atomic.

Notably, however, an operation that requires more than one read/write -- such as i++, which is equivalent to i = i + 1, which does one read and one write -- is not atomic, since another thread may write to i between the read and the write.

The Atomic classes, like AtomicInteger and AtomicReference, provide a wider variety of operations atomically, specifically including increment for AtomicInteger.

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

Answered provided by Tom Saleeba is very helpful. Today I also struggled with the same error

Apr 28, 2015 7:53:27 PM org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

I followed the suggestion and added the logging.properties file. And below was my reason of failure:

java.lang.IllegalStateException: Cannot set web app root system property when WAR file is not expanded

The root cause of the issue was a listener (Log4jConfigListener) that I added into the web.xml. And as per the link SEVERE: Exception org.springframework.web.util.Log4jConfigListener , this listener cannot be added within a WAR that is not expanded.

It may be helpful for someone to know that this was happening on OpenShift JBoss gear.

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

You are probably targeting a server without built-in JSTL support (e.g. some version of Tomcat.) You will need to provision your own JSTL tag library.

error TS1086: An accessor cannot be declared in an ambient context in Angular 9

These issue arise generally due to mismatch between @ngx-translate/core version and Angular .Before installing check compatible version of corresponding ngx_trnalsate/Core, @ngx-translate/http-loader and Angular at https://www.npmjs.com/package/@ngx-translate/core

Eg: For Angular 6.X versions,

npm install @ngx-translate/core@10 @ngx-translate/http-loader@3 rxjs --save

Like as above, follow below command and rest of code part is common for all versions(Note: Version can obtain from( https://www.npmjs.com/package/@ngx-translate/core)

npm install @ngx-translate/core@version @ngx-translate/http-loader@version rxjs --save

READ_EXTERNAL_STORAGE permission for Android

I also had a similar error log and here's what I did-

  1. In onCreate method we request a Dialog Box for checking permissions

    ActivityCompat.requestPermissions(MainActivity.this,
    new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
    
  2. Method to check for the result

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case 1: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // permission granted and now can proceed
             mymethod(); //a sample method called
    
            } else {
    
                // permission denied, boo! Disable the
                // functionality that depends on this permission.
                Toast.makeText(MainActivity.this, "Permission denied to read your External storage", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        // add other cases for more permissions
        }
    }
    

The official documentation to Requesting Runtime Permissions

How can I remove the gloss on a select element in Safari on Mac?

Sorry to pile on to an old item. I found partial answers to my questions here but had to do some work so I wanted to share my results for the next person.

I ended up using the same approach as the other contributors, but with a few tweaks to fix the following

  1. Long text was covering the arrows in the other solutions
  2. The image being used was a somewhat old and ugly up/down combo arrow.

The below will give you a working solution with the above issues fixed. Note: I used a white arrow for my use case, you may need to change the color of the arrow for yours.

here's a preview:

select with white arrow

select{    
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgaWQ9IkxheWVyXzEiICAgZGF0YS1uYW1lPSJMYXllciAxIiAgIHZpZXdCb3g9IjAgMCA0Ljk1IDEwIiAgIHZlcnNpb249IjEuMSIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxIHIxMzcyNSIgICBzb2RpcG9kaTpkb2NuYW1lPSJkb3dubG9hZC5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE0MjAyIj4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgIDwvY2M6V29yaz4gICAgPC9yZGY6UkRGPiAgPC9tZXRhZGF0YT4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTkyMCIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9IjEwMjciICAgICBpZD0ibmFtZWR2aWV3NDIwMCIgICAgIHNob3dncmlkPSJmYWxzZSIgICAgIGlua3NjYXBlOnpvb209Ijg0LjMiICAgICBpbmtzY2FwZTpjeD0iMi40NzQ5OTk5IiAgICAgaW5rc2NhcGU6Y3k9IjUiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMTkyMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyNyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjEiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJMYXllcl8xIiAvPiAgPGRlZnMgICAgIGlkPSJkZWZzNDE5MCI+ICAgIDxzdHlsZSAgICAgICBpZD0ic3R5bGU0MTkyIj4uY2xzLTJ7ZmlsbDojNDQ0O308L3N0eWxlPiAgPC9kZWZzPiAgPHRpdGxlICAgICBpZD0idGl0bGU0MTk0Ij5hcnJvd3M8L3RpdGxlPiAgPHBvbHlnb24gICAgIGNsYXNzPSJjbHMtMiIgICAgIHBvaW50cz0iMy41NCA1LjMzIDIuNDggNi44MiAxLjQxIDUuMzMgMy41NCA1LjMzIiAgICAgaWQ9InBvbHlnb240MTk4IiAgICAgc3R5bGU9ImZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MSIgLz48L3N2Zz4=) no-repeat 101% 50%;
  padding-right:20px;
}

HTML/CSS: how to put text both right and left aligned in a paragraph

I have used this in the past:

html

January<span class="right">2014</span>

Css

.right {
    margin-left:100%;
}

Demonstration

in iPhone App How to detect the screen resolution of the device

Use it in App Delegate: I am using storyboard

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {

    CGSize iOSDeviceScreenSize = [[UIScreen mainScreen] bounds].size;

    //----------------HERE WE SETUP FOR IPHONE 4/4s/iPod----------------------

    if(iOSDeviceScreenSize.height == 480){          

        UIStoryboard *iPhone35Storyboard = [UIStoryboard storyboardWithName:@"iPhone" bundle:nil];

        // Instantiate the initial view controller object from the storyboard
        UIViewController *initialViewController = [iPhone35Storyboard instantiateInitialViewController];

        // Instantiate a UIWindow object and initialize it with the screen size of the iOS device
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

        // Set the initial view controller to be the root view controller of the window object
        self.window.rootViewController  = initialViewController;

        // Set the window object to be the key window and show it
        [self.window makeKeyAndVisible];

        iphone=@"4";

        NSLog(@"iPhone 4: %f", iOSDeviceScreenSize.height);

    }

    //----------------HERE WE SETUP FOR IPHONE 5----------------------

    if(iOSDeviceScreenSize.height == 568){

        // Instantiate a new storyboard object using the storyboard file named Storyboard_iPhone4
        UIStoryboard *iPhone4Storyboard = [UIStoryboard storyboardWithName:@"iPhone5" bundle:nil];

        // Instantiate the initial view controller object from the storyboard
        UIViewController *initialViewController = [iPhone4Storyboard instantiateInitialViewController];

        // Instantiate a UIWindow object and initialize it with the screen size of the iOS device
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

        // Set the initial view controller to be the root view controller of the window object
        self.window.rootViewController  = initialViewController;

        // Set the window object to be the key window and show it
        [self.window makeKeyAndVisible];

         NSLog(@"iPhone 5: %f", iOSDeviceScreenSize.height);
        iphone=@"5";
    }

} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    // NSLog(@"wqweqe");
    storyboard = [UIStoryboard storyboardWithName:@"iPad" bundle:nil];

}

 return YES;
 }

Specify system property to Maven project

properties-maven-plugin plugin may help:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>properties-maven-plugin</artifactId>
    <version>1.0.0</version>
    <executions>
        <execution>
            <goals>
                <goal>set-system-properties</goal>
            </goals>
            <configuration>
                <properties>
                    <property>
                        <name>my.property.name</name>
                        <value>my.property.value</value>
                    </property>
                </properties>
            </configuration>
        </execution>
    </executions>
</plugin>

How to generate and manually insert a uniqueidentifier in sql server?

Kindly check Column ApplicationId datatype in Table aspnet_Users , ApplicationId column datatype should be uniqueidentifier .

*Your parameter order is passed wrongly , Parameter @id should be passed as first argument, but in your script it is placed in second argument..*

So error is raised..

Please refere sample script:

DECLARE @id uniqueidentifier
SET @id = NEWID()
Create Table #temp1(AppId uniqueidentifier)

insert into #temp1 values(@id)

Select * from #temp1

Drop Table #temp1

Trying to start a service on boot on Android

I faced with this problem if i leave the empty constructor in the receiver class. After the removing the empty contsructor onRreceive methos started working fine.

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

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

Example interface --

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

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

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

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

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

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

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

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

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

then you can create and execute your call --

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

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

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

Android Studio: Module won't show up in "Edit Configuration"

I finally figure out why the module is not showed up when I add configuration for AndroidTests for a com.android.library module.

If you include your library module in your application's build.gradle like this:

compile project(':yourlibrary')

Since for library module it is compiled with release mode by default, you can't run Android Tests for it, that's why it won't show up in the module list. I fixed it with following modification:

Add following configuration to the build.gradle of your library module:

     publishNonDefault true

By make following changes, you can debug compile your library by editing the build.gradle of your application module like following:

-    compile project(':yourlibrary')
+    debugCompile project(path: ':yourlibrary', configuration: 'debug')
+    releaseCompile project(path: ':yourlibrary', configuration: 'release')

Then sync it and you'll find it shows in the list.

Make column fixed position in bootstrap

Use .col instead of col-lg-3 :

<div class="row">
   <div class="col">
      Fixed content
   </div>
   <div class="col-lg-9">
      Normal scrollable content
   </div>
</div>

Matching an optional substring in a regex

(\d+)\s+(\(.*?\))?\s?Z

Note the escaped parentheses, and the ? (zero or once) quantifiers. Any of the groups you don't want to capture can be (?: non-capture groups).

I agree about the spaces. \s is a better option there. I also changed the quantifier to insure there are digits at the beginning. As far as newlines, that would depend on context: if the file is parsed line by line it won't be a problem. Another option is to anchor the start and end of the line (add a ^ at the front and a $ at the end).

How do I UPDATE from a SELECT in SQL Server?

The following example uses a derived table, a SELECT statement after the FROM clause, to return the old and new values for further updates:

UPDATE x
SET    x.col1 = x.newCol1,
       x.col2 = x.newCol2
FROM   (SELECT t.col1,
               t2.col1 AS newCol1,
               t.col2,
               t2.col2 AS newCol2
        FROM   [table] t
               JOIN other_table t2
                 ON t.ID = t2.ID) x

How to debug Spring Boot application with Eclipse?

Please see http://java.dzone.com/articles/how-debug-remote-java-applicat to enable the remote debugging. If you are using tomcat to run your application, start tomcat with remote debug parameters or you can start tomcat with JPDA support by using following command.

Windows

<tomcat bin dir>/startup.bat jpda

*nix

<tomcat bin dir>/startup.sh jpda

this will enable remote debugging on port 8000

how to remove only one style property with jquery

You can also replace "-moz-user-select:none" with "-moz-user-select:inherit". This will inherit the style value from any parent style or from the default style if no parent style was defined.

Streaming video from Android camera to server

I have hosted an open-source project to enable Android phone to IP camera:

http://code.google.com/p/ipcamera-for-android

Raw video data is fetched from LocalSocket, and the MDAT MOOV of MP4 was checked first before streaming. The live video is packed in FLV format, and can be played via Flash video player with a build in web server :)

What is function overloading and overriding in php?

Although overloading paradigm is not fully supported by PHP the same (or very similar) effect can be achieved with default parameter(s) (as somebody mentioned before).

If you define your function like this:

function f($p=0)
{
  if($p)
  {
    //implement functionality #1 here
  }
  else
  {
    //implement functionality #2 here
  }
}

When you call this function like:

f();

you'll get one functionality (#1), but if you call it with parameter like:

f(1);

you'll get another functionality (#2). That's the effect of overloading - different functionality depending on function's input parameter(s).

I know, somebody will ask now what functionality one will get if he/she calls this function as f(0).

What is setup.py?

setup.py is Python's answer to a multi-platform installer and make file.

If you’re familiar with command line installations, then make && make install translates to python setup.py build && python setup.py install.

Some packages are pure Python, and are only byte compiled. Others may contain native code, which will require a native compiler (like gcc or cl) and a Python interfacing module (like swig or pyrex).

How does the stack work in assembly language?

The Concept

First think of the whole thing as if you were the person who invented it. Like this:

First think of an array and how it is implemented at the low level --> it is basically just a set of contiguous memory locations (memory locations that are next to each other). Now that you have that mental image in your head, think of the fact that you can access ANY of those memory locations and delete it at your will as you remove or add data in your array. Now think of that same array but instead of the possibility to delete any location you decide that you will delete only the LAST location as you remove or add data in your array. Now your new idea to manipulate the data in that array in that way is called LIFO which means Last In First Out. Your idea is very good because it makes it easier to keep track of the content of that array without having to use a sorting algorithm every time you remove something from it. Also, to know at all times what the address of the last object in the array is, you dedicate one Register in the Cpu to keep track of it. Now, the way that register keeps track of it is so that every time you remove or add something to your array you also decrement or increment the value of the address in your register by the amount of objects you removed or added from the array (by the amount of address space they occupied). You also want to make sure that that amount by which you decrement or increment that register is fixed to one amount (like 4 memory locations ie. 4 bytes) per object, again, to make it easier to keep track and also to make it possible to use that register with some loop constructs because loops use fixed incrementation per iteration (eg. to loop trough your array with a loop you construct the loop to increment your register by 4 each iteration, which would not be possible if your array has objects of different sizes in it). Lastly, you choose to call this new data structure a "Stack", because it reminds you of a stack of plates in a restaurant where they always remove or add a plate on the top of that stack.

The Implementation

As you can see a stack is nothing more than an array of contiguous memory locations where you decided how to manipulate it. Because of that you can see that you don't need to even use the special instructions and registers to control the stack. You can implement it yourself with the basic mov, add and sub instructions and using general purpose registers instead the ESP and EBP like this:

mov edx, 0FFFFFFFFh

; --> this will be the start address of your stack, furthest away from your code and data, it will also serve as that register that keeps track of the last object in the stack that i explained earlier. You call it the "stack pointer", so you choose the register EDX to be what ESP is normally used for.

sub edx, 4

mov [edx], dword ptr [someVar]

; --> these two instructions will decrement your stack pointer by 4 memory locations and copy the 4 bytes starting at [someVar] memory location to the memory location that EDX now points to, just like a PUSH instruction decrements the ESP, only here you did it manually and you used EDX. So the PUSH instruction is basically just a shorter opcode that actually does this with ESP.

mov eax, dword ptr [edx]

add edx, 4

; --> and here we do the opposite, we first copy the 4 bytes starting at the memory location that EDX now points to into the register EAX (arbitrarily chosen here, we could have copied it anywhere we wanted). And then we increment our stack pointer EDX by 4 memory locations. This is what the POP instruction does.

Now you can see that the instructions PUSH and POP and the registers ESP ans EBP were just added by Intel to make the above concept of the "stack" data structure easier to write and read. There are still some RISC (Reduced Instruction Set) Cpu-s that don't have the PUSH ans POP instructions and dedicated registers for stack manipulation, and while writing assembly programs for those Cpu-s you have to implement the stack by yourself just like i showed you.

How to set width of a div in percent in JavaScript?

testjs2

    $(document).ready(function() { 
      $("#form1").validate({ 
        rules: { 
          name: "required", //simple rule, converted to {required:true} 
          email: { //compound rule 
          required: true, 
          email: true 
        }, 
        url: { 
          url: true 
        }, 
        comment: { 
          required: true 
        } 
        }, 
        messages: { 
          comment: "Please enter a comment." 
        } 
      }); 
    }); 

    function()
    {
    var ok=confirm('Click "OK" to go to yahoo, "CANCEL" to go to hotmail')
    if (ok)
    location="http://www.yahoo.com"
    else
    location="http://www.hotmail.com"
    }

    function changeWidth(){
    var e1 = document.getElementById("e1");
    e1.style.width = 400;
} 

  </script> 

  <style type="text/css"> 
    * { font-family: Verdana; font-size: 11px; line-height: 14px; } 
    .submit { margin-left: 125px; margin-top: 10px;} 
    .label { display: block; float: left; width: 120px; text-align: right; margin-right: 5px; } 
    .form-row { padding: 5px 0; clear: both; width: 700px; } 
    .label.error { width: 250px; display: block; float: left; color: red; padding-left: 10px; } 
    .input[type=text], textarea { width: 250px; float: left; } 
    .textarea { height: 50px; } 
  </style> 

  </head> 
  <body> 

    <form id="form1" method="post" action=""> 
      <div class="form-row"><span class="label">Name *</span><input type="text" name="name" /></div> 
      <div class="form-row"><span class="label">E-Mail *</span><input type="text" name="email" /></div> 
      <div class="form-row"><span class="label">URL </span><input type="text" name="url" /></div> 
      <div class="form-row"><span class="label">Your comment *</span><textarea name="comment" ></textarea></div> 
      <div class="form-row"><input class="submit" type="submit" value="Submit"></div> 
      <input type="button" value="change width" onclick="changeWidth()"/>
      <div id="e1" style="width:20px;height:20px; background-color:#096"></div>
    </form> 



  </body> 
</html> 

String formatting: % vs. .format vs. string literal

But one thing is that also if you have nested curly-braces, won't work for format but % will work.

Example:

>>> '{{0}, {1}}'.format(1,2)
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    '{{0}, {1}}'.format(1,2)
ValueError: Single '}' encountered in format string
>>> '{%s, %s}'%(1,2)
'{1, 2}'
>>> 

JPA Query.getResultList() - use in a generic way

I had the same problem and a simple solution that I found was:

List<Object[]> results = query.getResultList();
for (Object[] result: results) {
    SomeClass something = (SomeClass)result[1];
    something.doSomething;
}

I know this is defenitly not the most elegant solution nor is it best practice but it works, at least for me.

What is the best way to implement a "timer"?

It's not clear what type of application you're going to develop (desktop, web, console...)

The general answer, if you're developing Windows.Forms application, is use of

System.Windows.Forms.Timer class. The benefit of this is that it runs on UI thread, so it's simple just define it, subscribe to its Tick event and run your code on every 15 second.

If you do something else then windows forms (it's not clear from the question), you can choose System.Timers.Timer, but this one runs on other thread, so if you are going to act on some UI elements from the its Elapsed event, you have to manage it with "invoking" access.

Select DISTINCT individual columns in django?

It's quite simple actually if you're using PostgreSQL, just use distinct(columns) (documentation).

Productorder.objects.all().distinct('category')

Note that this feature has been included in Django since 1.4

How do I prompt for Yes/No/Cancel input in a Linux shell script?

inquire ()  {
  echo  -n "$1 [y/n]? "
  read answer
  finish="-1"
  while [ "$finish" = '-1' ]
  do
    finish="1"
    if [ "$answer" = '' ];
    then
      answer=""
    else
      case $answer in
        y | Y | yes | YES ) answer="y";;
        n | N | no | NO ) answer="n";;
        *) finish="-1";
           echo -n 'Invalid response -- please reenter:';
           read answer;;
       esac
    fi
  done
}

... other stuff

inquire "Install now?"

...

535-5.7.8 Username and Password not accepted

Goto config/initializers/setup_mail.rb Check whether the configuration there matches the configuration written in the development.rb file.It should look like the following in both files:

config.action_mailer.smtp_settings = {
     :address =>"[email protected]",
     :port => 587,
     :domain => "gmail.com",
     :user_name => "[email protected]",
     :password => "********",
     :authentication => 'plain',
     :enable_starttls_auto => true,
     :openssl_verify_mode => 'none' 
     } 

This will most certainly solve your problem.

Change the spacing of tick marks on the axis of a plot?

And if you don't want R to add decimals or zeros, you can stop it from drawing the x axis or the y axis or both using ...axt. Then, you can add your own ticks and labels:

plot(x, y, xaxt="n")
plot(x, y, yaxt="n")
axis(1 or 2, at=c(1, 5, 10), labels=c("First", "Second", "Third"))

How to know whether refresh button or browser back button is clicked in Firefox

var keyCode = evt.keyCode;
if (keyCode==8)
alert('you pressed backspace');

if(keyCode==116)
alert('you pressed f5 to reload page')

How to get the file-path of the currently executing javascript code

Within the script:

var scripts = document.getElementsByTagName("script"),
    src = scripts[scripts.length-1].src;

This works because the browser loads and executes scripts in order, so while your script is executing, the document it was included in is sure to have your script element as the last one on the page. This code of course must be 'global' to the script, so save src somewhere where you can use it later. Avoid leaking global variables by wrapping it in:

(function() { ... })();

file_get_contents behind a proxy?

Use stream_context_set_default function. It is much easier to use as you can directly use file_get_contents or similar functions without passing any additional parameters

This blog post explains how to use it. Here is the code from that page.

<?php
// Edit the four values below
$PROXY_HOST = "proxy.example.com"; // Proxy server address
$PROXY_PORT = "1234";    // Proxy server port
$PROXY_USER = "LOGIN";    // Username
$PROXY_PASS = "PASSWORD";   // Password
// Username and Password are required only if your proxy server needs basic authentication

$auth = base64_encode("$PROXY_USER:$PROXY_PASS");
stream_context_set_default(
 array(
  'http' => array(
   'proxy' => "tcp://$PROXY_HOST:$PROXY_PORT",
   'request_fulluri' => true,
   'header' => "Proxy-Authorization: Basic $auth"
   // Remove the 'header' option if proxy authentication is not required
  )
 )
);

$url = "http://www.pirob.com/";

print_r( get_headers($url) );

echo file_get_contents($url);
?>

Filter values only if not null using lambda in Java8

Leveraging the power of java.util.Optional#map():

List<Car> requiredCars = cars.stream()
  .filter (car -> 
    Optional.ofNullable(car)
      .map(Car::getName)
      .map(name -> name.startsWith("M"))
      .orElse(false) // what to do if either car or getName() yields null? false will filter out the element
    )
  .collect(Collectors.toList())
;

How to run sql script using SQL Server Management Studio?

Found this in another thread that helped me: Use xp_cmdshell and sqlcmd Is it possible to execute a text file from SQL query? - by Gulzar Nazim

EXEC xp_cmdshell  'sqlcmd -S ' + @DBServerName + ' -d  ' + @DBName + ' -i ' + @FilePathName

How do I find the width & height of a terminal window?

yes = | head -n$(($(tput lines) * $COLUMNS)) | tr -d '\n'

How do I set up HttpContent for my HttpClient PostAsync second parameter?

This is answered in some of the answers to Can't find how to use HttpContent as well as in this blog post.

In summary, you can't directly set up an instance of HttpContent because it is an abstract class. You need to use one the classes derived from it depending on your need. Most likely StringContent, which lets you set the string value of the response, the encoding, and the media type in the constructor. See: http://msdn.microsoft.com/en-us/library/system.net.http.stringcontent.aspx

Hashing a dictionary?

You can use the maps library to do this. Specifically, maps.FrozenMap

import maps
fm = maps.FrozenMap(my_dict)
hash(fm)

To install maps, just do:

pip install maps

It handles the nested dict case too:

import maps
fm = maps.FrozenMap.recurse(my_dict)
hash(fm)

Disclaimer: I am the author of the maps library.

How can I change the color of AlertDialog title and the color of the line under it

If you don't want a "library" for that, you can use this badly hack:

((ViewGroup)((ViewGroup)getDialog().getWindow().getDecorView()).getChildAt(0)) //ie LinearLayout containing all the dialog (title, titleDivider, content)
.getChildAt(1) // ie the view titleDivider
.setBackgroundColor(getResources().getColor(R.color.yourBeautifulColor));

This was tested and work on 4.x; not tested under, but if my memory is good it should work for 2.x and 3.x

Is there a way to create key-value pairs in Bash script?

In bash, we use

declare -A name_of_dictonary_variable

so that Bash understands it is a dictionary.

For e.g. you want to create sounds dictionary then,

declare -A sounds

sounds[dog]="Bark"

sounds[wolf]="Howl"

where dog and wolf are "keys", and Bark and Howl are "values".

You can access all values using : echo ${sounds[@]} OR echo ${sounds[*]}

You can access all keys only using: echo ${!sounds[@]}

And if you want any value for a particular key, you can use:

${sounds[dog]}

this will give you value (Bark) for key (Dog).

What is a stack trace, and how can I use it to debug my application errors?

I am posting this answer so the topmost answer (when sorted by activity) is not one that is just plain wrong.

What is a Stacktrace?

A stacktrace is a very helpful debugging tool. It shows the call stack (meaning, the stack of functions that were called up to that point) at the time an uncaught exception was thrown (or the time the stacktrace was generated manually). This is very useful because it doesn't only show you where the error happened, but also how the program ended up in that place of the code. This leads over to the next question:

What is an Exception?

An Exception is what the runtime environment uses to tell you that an error occurred. Popular examples are NullPointerException, IndexOutOfBoundsException or ArithmeticException. Each of these are caused when you try to do something that is not possible. For example, a NullPointerException will be thrown when you try to dereference a Null-object:

Object a = null;
a.toString();                 //this line throws a NullPointerException

Object[] b = new Object[5];
System.out.println(b[10]);    //this line throws an IndexOutOfBoundsException,
                              //because b is only 5 elements long
int ia = 5;
int ib = 0;
ia = ia/ib;                   //this line throws an  ArithmeticException with the 
                              //message "/ by 0", because you are trying to
                              //divide by 0, which is not possible.

How should I deal with Stacktraces/Exceptions?

At first, find out what is causing the Exception. Try googleing the name of the exception to find out, what is the cause of that exception. Most of the time it will be caused by incorrect code. In the given examples above, all of the exceptions are caused by incorrect code. So for the NullPointerException example you could make sure that a is never null at that time. You could, for example, initialise a or include a check like this one:

if (a!=null) {
    a.toString();
}

This way, the offending line is not executed if a==null. Same goes for the other examples.

Sometimes you can't make sure that you don't get an exception. For example, if you are using a network connection in your program, you cannot stop the computer from loosing it's internet connection (e.g. you can't stop the user from disconnecting the computer's network connection). In this case the network library will probably throw an exception. Now you should catch the exception and handle it. This means, in the example with the network connection, you should try to reopen the connection or notify the user or something like that. Also, whenever you use catch, always catch only the exception you want to catch, do not use broad catch statements like catch (Exception e) that would catch all exceptions. This is very important, because otherwise you might accidentally catch the wrong exception and react in the wrong way.

try {
    Socket x = new Socket("1.1.1.1", 6789);
    x.getInputStream().read()
} catch (IOException e) {
    System.err.println("Connection could not be established, please try again later!")
}

Why should I not use catch (Exception e)?

Let's use a small example to show why you should not just catch all exceptions:

int mult(Integer a,Integer b) {
    try {
        int result = a/b
        return result;
    } catch (Exception e) {
        System.err.println("Error: Division by zero!");
        return 0;
    }
}

What this code is trying to do is to catch the ArithmeticException caused by a possible division by 0. But it also catches a possible NullPointerException that is thrown if a or b are null. This means, you might get a NullPointerException but you'll treat it as an ArithmeticException and probably do the wrong thing. In the best case you still miss that there was a NullPointerException. Stuff like that makes debugging much harder, so don't do that.

TLDR

  1. Figure out what is the cause of the exception and fix it, so that it doesn't throw the exception at all.
  2. If 1. is not possible, catch the specific exception and handle it.

    • Never just add a try/catch and then just ignore the exception! Don't do that!
    • Never use catch (Exception e), always catch specific Exceptions. That will save you a lot of headaches.

taking input of a string word by word

getline is storing the entire line at once, which is not what you want. A simple fix is to have three variables and use cin to get them all. C++ will parse automatically at the spaces.

#include <iostream>
using namespace std;

int main() {
    string a, b, c;
    cin >> a >> b >> c;
    //now you have your three words
    return 0;
}

I don't know what particular "operation" you're talking about, so I can't help you there, but if it's changing characters, read up on string and indices. The C++ documentation is great. As for using namespace std; versus std:: and other libraries, there's already been a lot said. Try these questions on StackOverflow to start.

Extract code country from phone number [libphonenumber]

If the string containing the phone number will always start this way (+33 or another country code) you should use regex to parse and get the country code and then use the library to get the country associated to the number.

Add disabled attribute to input element using Javascript

Working code from my sources:

HTML WORLD

<select name="select_from" disabled>...</select>

JS WORLD

var from = jQuery('select[name=select_from]');

//add disabled
from.attr('disabled', 'disabled');



//remove it
from.removeAttr("disabled");

How to convert DateTime to a number with a precision greater than days in T-SQL?

Well, I would do it like this:

select datediff(minute,'1990-1-1',datetime)

where '1990-1-1' is an arbitrary base datetime.

Firefox "ssl_error_no_cypher_overlap" error

The first thing I would check is the config for mod_nss. It is the odd one out, for it is yours and there is none in the world like it :-) Whereas if there was some huge bug in Firefox or mod_nss itself, I guess you'd have found out about it by now in your google quest. The fact that you've fiddled with the config (e.g. disabling SSL3, and various other random tweaks), is also suspicious.

I'd back track to a very vanilla mod_nss config and see if that works. Then change things systematically towards your current config until you can reproduce the problem. By the sound of it the source of the error is somewhere in the cipher spec config of mod_nss and the related protocol negotiation stuff. So maybe you inadvertently changed something there when trying to turn off SSLv3 (incidentally, why disable SSL3? Normally people disable V2?).

One other thing to check is that you're on the latest mod_nss and it's not a known bug in that. The fact that it manages to start the session and then fails later is interesting - it suggests that maybe it is trying to renegotiate the session and failing to negotiate ciphers at that point. So it might be the symmetric ciphers. Or it could simply be an implementation bug in your version of mod_nss that somehow garbles the protocol.

One other idea, and this is a wild guess, is the browser is trying to resume a session which was negotiated with SSLv3 before you disabled it, and something breaks when trying to resume that session when V3 is turned off, or maybe mod_nss just doesn't implement it right.

The java/tomcat stuff seems like a red herring as unless I've misunderstood your description, none of that is involved in the SSL handshake/protocol.

Access XAMPP Localhost from Internet

First, you need to configure your computer to get a static IP from your router. Instructions for how to do this can be found: here

For example, let's say you picked the IP address 192.168.1.102. After the above step is completed, you should be able to get to the website on your local machine by going to both http://localhost and http://192.168.1.102, since your computer will now always have that IP address on your network.

If you look up your IP address (such as http://www.ip-adress.com/), the IP you see is actually the IP of your router. When your friend accesses your website, you'll give him this IP. However, you need to tell your router that when it gets a request for a webpage, forward that request to your server. This is done through port forwarding.

Two examples of how to do this can be found here and here, although the exact screens you see will vary depending on the manufacturer of your router (Google for exact instructions, if needed).

For the Linksys router I have, I enter http://192.168.1.1/, enter my username/password, Applications & Gaming tab > Port Range Forward. Enter the application name (whatever you want to call it), start port (80), end port (80), protocol (TCP), ip address (using the above example, you would enter 192.168.1.102, which is the static IP you assigned your server), and be sure to check to enable the forwarding. Restart your router and the changes should take effect.

Having done all that, your friend should now be able to access your webpage by going to his web browser on his machine and entering http://IP.address.of.your.computer (the same one you see when you go here ).

As mentioned earlier, the IP address assigned to you by your ISP will eventually change whether you sign offline or not. I strongly recommend using DynDns, which is absolutely free. You can choose a hostname at their domain (such as cuga.kicks-ass.net) and your friend can then always access your website by simply going to http://cuga.kicks-ass.net in his browser. Here is their site again: DynDns

I hope this helps.

html select only one checkbox in a group

The Code snippet below demonstrates a simple approach for selecting only one checkbox in a group.


_x000D_
_x000D_
  <!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body>
    <h3>Demonstration of Checkbox Toggle</h3>
    <p>
        <span><b>Letters:</b></span>
        A<input type="checkbox" name="A" >
        B<input type="checkbox" name="B" >
        C<input type="checkbox" name="C" >
        D<input type="checkbox" name="D" >
    </p>
    <p>
        <span><b>Numbers:</b></span>
        1<input type="checkbox" name="1" >
        2<input type="checkbox" name="2" >
        3<input type="checkbox" name="3" >
    </p>
     <p>
        <span><b>Birds:</b></span>
        Scarlet Ibis<input type="checkbox" name="Scarlet Ibis" >
        Cocrico <input type="checkbox" name="Cocrico" >
        hummingbird <input type="checkbox" name="hummingbird" >
    </p>
</body>

<script>
    $(function()
    {
        function toggle(choices,name) 
        {
            if(choices.includes(name))
            {
                for( i=0;i<choices.length;i++)
                {
                if(name !=choices[i])
                    $('input[name="' + choices[i] + '"]').not(this).prop('checked', false); 
                }
            }
        }
        $('input[type="checkbox"]').on('change', function() 
        {
            var letters = ["A","B","C","D"];
            var numbers = ["1", "2", "3"];
            var birds = ["Scarlet Ibis", "Cocrico", "hummingbird"];
            
            toggle(letters,this.name);
            toggle(numbers,this.name);
            toggle(birds,this.name);
        });

    });
</script>
</html>
_x000D_
_x000D_
_x000D_

Java: splitting a comma-separated string but ignoring commas in quotes

Rather than use lookahead and other crazy regex, just pull out the quotes first. That is, for every quote grouping, replace that grouping with __IDENTIFIER_1 or some other indicator, and map that grouping to a map of string,string.

After you split on comma, replace all mapped identifiers with the original string values.

PHP mySQL - Insert new record into table with auto-increment on primary key

$query = "INSERT INTO myTable VALUES (NULL,'Fname', 'Lname', 'Website')";

Just leaving the value of the AI primary key NULL will assign an auto incremented value.

How to convert image file data in a byte array to a Bitmap?

The answer of Uttam didnt work for me. I just got null when I do:

Bitmap bitmap = BitmapFactory.decodeByteArray(bitmapdata, 0, bitmapdata.length);

In my case, bitmapdata only has the buffer of the pixels, so it is imposible for the function decodeByteArray to guess which the width, the height and the color bits use. So I tried this and it worked:

//Create bitmap with width, height, and 4 bytes color (RGBA)    
Bitmap bmp = Bitmap.createBitmap(imageWidth, imageHeight, Bitmap.Config.ARGB_8888);
ByteBuffer buffer = ByteBuffer.wrap(bitmapdata);
bmp.copyPixelsFromBuffer(buffer);

Check https://developer.android.com/reference/android/graphics/Bitmap.Config.html for different color options

How does Python's super() work with multiple inheritance?

Consider calling super().Foo() called from a sub-class. The Method Resolution Order (MRO) method is the order in which method calls are resolved.

Case 1: Single Inheritance

In this, super().Foo() will be searched up in the hierarchy and will consider the closest implementation, if found, else raise an Exception. The "is a" relationship will always be True in between any visited sub-class and its super class up in the hierarchy. But this story isn't the same always in Multiple Inheritance.

Case 2: Multiple Inheritance

Here, while searching for super().Foo() implementation, every visited class in the hierarchy may or may not have is a relation. Consider following examples:

class A(object): pass
class B(object): pass
class C(A): pass
class D(A): pass
class E(C, D): pass
class F(B): pass
class G(B): pass
class H(F, G): pass
class I(E, H): pass

Here, I is the lowest class in the hierarchy. Hierarchy diagram and MRO for I will be

enter image description here

(Red numbers showing the MRO)

MRO is I E C D A H F G B object

Note that a class X will be visited only if all its sub-classes, which inherit from it, have been visited(i.e., you should never visit a class that has an arrow coming into it from a class below that you have not yet visited).

Here, note that after visiting class C , D is visited although C and D DO NOT have is a relationship between them(but both have with A). This is where super() differs from single inheritance.

Consider a slightly more complicated example:

enter image description here

(Red numbers showing the MRO)

MRO is I E C H D A F G B object

In this case we proceed from I to E to C. The next step up would be A, but we have yet to visit D, a subclass of A. We cannot visit D, however, because we have yet to visit H, a subclass of D. The leaves H as the next class to visit. Remember, we attempt to go up in hierarchy, if possible, so we visit its leftmost superclass, D. After D we visit A, but we cannot go up to object because we have yet to visit F, G, and B. These classes, in order, round out the MRO for I.

Note that no class can appear more than once in MRO.

This is how super() looks up in the hierarchy of inheritance.

Credits for resources: Richard L Halterman Fundamentals of Python Programming

Using CSS to affect div style inside iframe

probably not the way you are thinking. the iframe would have to <link> in the css file too. AND you can't do it even with javascript if it's on a different domain.

How to read a single char from the console in Java (as the user types it)?

What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes.

Now, with respect to Java... see Non blocking console input in Python and Java. Excerpt:

If your program must be console based, you have to switch your terminal out of line mode into character mode, and remember to restore it before your program quits. There is no portable way to do this across operating systems.

One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using jCurses.

Onclick javascript to make browser go back to previous page?

Works for me everytime

<a href="javascript:history.go(-1)">
    <button type="button">
        Back
    </button>
</a>

How can I rename a conda environment?

conda create --name new_name --copy --clone old_name is better

I use conda create --name new_name --clone old_name which is without --copy but encountered pip breaks...

the following url may help Installing tensorflow in cloned conda environment breaks conda environment it was cloned from

Grep characters before and after match?

grep -E -o ".{0,5}test_pattern.{0,5}" test.txt 

This will match up to 5 characters before and after your pattern. The -o switch tells grep to only show the match and -E to use an extended regular expression. Make sure to put the quotes around your expression, else it might be interpreted by the shell.

How to start MySQL with --skip-grant-tables?

if you are running on Apple MacBook OSX then:

  1. Stop your MySQL server (if it is already running).
  2. Find your MySQL configuration file, my.cnf. (For me it was placed @ /Applications/XAMPP/xamppfiles/etc. You can just search if you can't find it).
  3. Open my.cnf file in any text editor.
  4. Add "skip-grant-tables" (without quotes) at the end of [mysqld] section and save the file.
  5. Now start your MySQL server. It'll start with skip-grant-tables option.

Do what you want now!!

PS: Please remove skip-grant-tables from my.cnf file once you are done with whatsoever you want to do ELSE MySQL server will always run without access grants.

PHP array delete by value (not key)

Well, deleting an element from array is basically just set difference with one element.

array_diff( [312, 401, 15, 401, 3], [401] ) // removing 401 returns [312, 15, 3]

It generalizes nicely, you can remove as many elements as you like at the same time, if you want.

Disclaimer: Note that my solution produces a new copy of the array while keeping the old one intact in contrast to the accepted answer which mutates. Pick the one you need.

Basic Python client socket example

Here is the simplest python socket example.

Server side:

import socket

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('localhost', 8089))
serversocket.listen(5) # become a server socket, maximum 5 connections

while True:
    connection, address = serversocket.accept()
    buf = connection.recv(64)
    if len(buf) > 0:
        print buf
        break

Client Side:

import socket

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('localhost', 8089))
clientsocket.send('hello')
  • First run the SocketServer.py, and make sure the server is ready to listen/receive sth
  • Then the client send info to the server;
  • After the server received sth, it terminates

Goal Seek Macro with Goal as a Formula

I think your issue is that Range("H18") doesn't contain a formula. Also, you could make your code more efficient by eliminating x. Instead, change your code to

Range("H18").GoalSeek Goal:=Range("H32").Value, ChangingCell:=Range("G18")

How to simulate a button click using code?

If you do not use the sender argument, why not refactor the button handler implementation to separate function, and call it from wherever you want (from the button handler and from the other place).

Anyway, it is a better and cleaner design - a code that needs to be called on button handler AND from some other places deserves to be refactored to own function. Plus it will help you separate UI handling from application logic code. You will also have a nice name to the function, not just onDateSelectedButtonClick().

'tuple' object does not support item assignment

The second line should have been pixels[0], with an S. You probably have a tuple named pixel, and tuples are immutable. Construct new pixels instead:

image = Image.open('balloon.jpg')

pixels = [(pix[0] + 20,) + pix[1:] for pix in image.getdata()]

image.putdate(pixels)

How to use the PRINT statement to track execution as stored procedure is running?

I'm sure you can use RAISERROR ... WITH NOWAIT

If you use severity 10 it's not an error. This also provides some handy formatting eg %s, %i and you can use state too to track where you are.

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

How do I stretch a background image to cover the entire HTML element?

In short you can try this....

<div data-role="page" style="background:url('backgrnd.png'); background-repeat: no-repeat; background-size: 100% 100%;" >

Where I have used few css and js...

<link rel="stylesheet" href="css/jquery.mobile-1.0.1.min.css" />
<script src="js/jquery-1.7.1.min.js"></script>
<script src="js/jquery.mobile-1.0.1.min.js"></script>

And it is working fine for me.