Programs & Examples On #Winghci

SQL Server error on update command - "A severe error occurred on the current command"

I was having the error in Hangfire where I did not have access to the internal workings of the library or was I able to trace what the primary cause was.

Building on @Remus Rusanu answer, I was able to have this fixed with the following script.

    --first set the database to single user mode
    ALTER DATABASE TransXSmartClientJob
    SET SINGLE_USER
    WITH ROLLBACK IMMEDIATE;
    GO

    -- Then try to repair
    DBCC CHECKDB(TransXSmartClientJob, REPAIR_REBUILD)

    -- when done, set the database back to multiple user mode
    ALTER DATABASE TransXSmartClientJob
    SET MULTI_USER;
    GO

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

How to create a sticky left sidebar menu using bootstrap 3?

I used this way in my code

$(function(){
    $('.block').affix();
})

JSON order mixed up

Not sure if I am late to the party but I found this nice example that overrides the JSONObject constructor and makes sure that the JSON data are output in the same way as they are added. Behind the scenes JSONObject uses the MAP and MAP does not guarantee the order hence we need to override it to make sure we are receiving our JSON as per our order.

If you add this to your JSONObject then the resulting JSON would be in the same order as you have created it.

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.LinkedHashMap;
import org.json.JSONObject;
import lombok.extern.java.Log;

@Log
public class JSONOrder {

    public static void main(String[] args) throws IOException {

        JSONObject jsontest = new JSONObject();
        try {
            Field changeMap = jsonEvent.getClass().getDeclaredField("map");
            changeMap.setAccessible(true);
            changeMap.set(jsonEvent, new LinkedHashMap<>());
            changeMap.setAccessible(false);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            log.info(e.getMessage());
        }
        jsontest.put("one", "I should be first");
        jsonEvent.put("two", "I should be second");
        jsonEvent.put("third", "I should be third");
        System.out.println(jsonEvent);
    }
}

How can I call a WordPress shortcode within a template?

Make sure to enable the use of shortcodes in text widgets.

// To enable the use, add this in your *functions.php* file:
add_filter( 'widget_text', 'do_shortcode' );

// and then you can use it in any PHP file:  
<?php echo do_shortcode('[YOUR-SHORTCODE-NAME/TAG]'); ?>

Check the documentation for more.

How to clear the logs properly for a Docker container?

You can't do this directly through a Docker command.

You can either limit the log's size, or use a script to delete logs related to a container. You can find scripts examples here (read from the bottom): Feature: Ability to clear log history #1083

Check out the logging section of the docker-compose file reference, where you can specify options (such as log rotation and log size limit) for some logging drivers.

How to display pandas DataFrame of floats using a format string for columns?

Similar to unutbu above, you could also use applymap as follows:

import pandas as pd
df = pd.DataFrame([123.4567, 234.5678, 345.6789, 456.7890],
                  index=['foo','bar','baz','quux'],
                  columns=['cost'])

df = df.applymap("${0:.2f}".format)

Easy way to pull latest of all git submodules

I did this by adapting gahooa's answer above:

Integrate it with a git [alias] ...

If your parent project has something like this in .gitmodules:

[submodule "opt/submodules/solarized"]
    path = opt/submodules/solarized
    url = [email protected]:altercation/solarized.git
[submodule "opt/submodules/intellij-colors-solarized"]
    path = opt/submodules/intellij-colors-solarized
    url = [email protected]:jkaving/intellij-colors-solarized.git

Add something like this inside your .gitconfig

[alias]
    updatesubs = "!sh -c \"git submodule init && git submodule update && git submodule status\" "

Then to update your submodules, run:

git updatesubs

I have an example of it in my environment setup repo.

CSS :selected pseudo class similar to :checked, but for <select> elements

Actually you can only style few CSS properties on :modified option elements. color does not work, background-color either, but you can set a background-image.

You can couple this with gradients to do the trick.

_x000D_
_x000D_
option:hover,_x000D_
option:focus,_x000D_
option:active,_x000D_
option:checked {_x000D_
  background: linear-gradient(#5A2569, #5A2569);_x000D_
}
_x000D_
<select>_x000D_
  <option>A</option>_x000D_
  <option>B</option>_x000D_
  <option>C</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Works on gecko/webkit.

How to set the Default Page in ASP.NET?

I prefer using the following method:

system.webServer>
  <defaultDocument>
    <files>
      <clear />
      <add value="CreateThing.aspx" />
    </files>
  </defaultDocument>
</system.webServer>

Java random numbers using a seed

If you're giving the same seed, that's normal. That's an important feature allowing tests.

Check this to understand pseudo random generation and seeds:

Pseudorandom number generator

A pseudorandom number generator (PRNG), also known as a deterministic random bit generator DRBG, is an algorithm for generating a sequence of numbers that approximates the properties of random numbers. The sequence is not truly random in that it is completely determined by a relatively small set of initial values, called the PRNG's state, which includes a truly random seed.

If you want to have different sequences (the usual case when not tuning or debugging the algorithm), you should call the zero argument constructor which uses the nanoTime to try to get a different seed every time. This Random instance should of course be kept outside of your method.

Your code should probably be like this:

private Random generator = new Random();
double randomGenerator() {
    return generator.nextDouble()*0.5;
}

Delete everything in a MongoDB database

I had the same problem, when I needed to reset all the collections but didn't want to loose any database users. Use the following line of code, if you would like to save the user configuration for the database:

use <whichever database>
db.getCollectionNames().forEach(function(c) { if (c.indexOf("system.") == -1) db[c].drop(); })

This code will go through all collection names from one database and drop those which do not start with "system.".

PHP, MySQL error: Column count doesn't match value count at row 1

You have 9 fields listed, but only 8 values. Try adding the method.

Should Jquery code go in header or footer?

For me jQuery is a little bit special. Maybe an exception to the norm. There are so many other scripts that rely on it, so its quite important that it loads early so the other scripts that come later will work as intended. As someone else pointed out even this page loads jQuery in the head section.

Using Thymeleaf when the value is null

You've done twice the checking when you create

${someObject.someProperty != null} ? ${someObject.someProperty}

You should do it clean and simple as below.

<td th:text="${someObject.someProperty} ? ${someObject.someProperty} : 'null value!'"></td>

How can I divide two integers to get a double?

You want to cast the numbers:

double num3 = (double)num1/(double)num2;

Note: If any of the arguments in C# is a double, a double divide is used which results in a double. So, the following would work too:

double num3 = (double)num1/num2;

For more information see:

Dot Net Perls

get and set in TypeScript

Based on example you show, you want to pass a data object and get a property of that object by get(). for this you need to use generic type, since data object is generic, can be any object.

export class Attributes<T> {
    constructor(private data: T) {}
    get = <K extends keyof T>(key: K): T[K] => {
      return this.data[key];
    };
    set = (update: T): void => {
      //   this is like spread operator. it will take this.data obj and will overwrite with the update obj
      // ins tsconfig.json change target to Es6 to be able to use Object.assign()
      Object.assign(this.data, update);
    };
    getAll(): T {
      return this.data;
    }
  }

< T > refers to generic type. let's initialize an instance

 const myAttributes=new Attributes({name:"something",age:32})

 myAttributes.get("name")="something"

Notice this syntax

<K extends keyof T>

in order to be able to use this we should be aware of 2 things:

1- in typestring strings can be a type.

2- all object properties in javascript essentially are strings.

when we use get(), type of argument that it is receiving is a property of object that passed to constructor and since object properties are strings and strings are allowed to be a type in typescript, we could use this <K extends keyof T>

login failed for user 'sa'. The user is not associated with a trusted SQL Server connection. (Microsoft SQL Server, Error: 18452) in sql 2008

I was stuck in same problem for many hours. I tried everything found on internet.

At last, I figured out a surprising solution : I had missed \SQLEXPRESS part of the Server name: MY-COMPUTER-NAME\SQLEXPRESS

I hope this helps someone who is stuck in similar kind of problem.

Preloading images with jQuery

Here's a tweaked version of the first response that actually loads the images into DOM and hides it by default.

function preload(arrayOfImages) {
    $(arrayOfImages).each(function () {
        $('<img />').attr('src',this).appendTo('body').css('display','none');
    });
}

Redis: Show database size/size for keys

How about redis-cli get KEYNAME | wc -c

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Distinct and Group By generally do the same kind of thing, for different purposes... They both create a 'working" table in memory based on the columns being Grouped on, (or selected in the Select Distinct clause) - and then populate that working table as the query reads data, adding a new "row" only when the values indicate the need to do so...

The only difference is that in the Group By there are additional "columns" in the working table for any calculated aggregate fields, like Sum(), Count(), Avg(), etc. that need to updated for each original row read. Distinct doesn't have to do this... In the special case where you Group By only to get distinct values, (And there are no aggregate columns in output), then it is probably exactly the same query plan.... It would be interesting to review the query execution plan for the two options and see what it did...

Certainly Distinct is the way to go for readability if that is what you are doing (When your purpose is to eliminate duplicate rows, and you are not calculating any aggregate columns)

Change form size at runtime in C#

If you want to manipulate the form programmatically the simplest solution is to keep a reference to it:

static Form myForm;

static void Main()
{
    myForm = new Form();
    Application.Run(myForm);
}

You can then use that to change the size (or what ever else you want to do) at run time. Though as Arrow points out you can't set the Width and Height directly but have to set the Size property.

Two values from one input in python?

For n number of inputs declare the variable as an empty list and use the same syntax to proceed:

>>> x=input('Enter value of a and b').split(",")
Enter value of a and b
1,2,3,4
>>> x
['1', '2', '3', '4']

Converting float to char*

Long after accept answer.

Use sprintf(), or related functions, as many others have answers suggested, but use a better format specifier.

Using "%.*e", code solves various issues:

  • The maximum buffer size needed is far more reasonable, like 18 for float (see below). With "%f", sprintf(buf, "%f", FLT_MAX); could need 47+. sprintf(buf, "%f", DBL_MAX); may need 317+

  • Using ".*" allows code to define the number of decimal places needed to distinguish a string version of float x and it next highest float. For deatils, see Printf width specifier to maintain precision of floating-point value

  • Using "%e" allows code to distinguish small floats from each other rather than all printing "0.000000" which is the result when |x| < 0.0000005.

Example usage

#include <float.h>
#define FLT_STRING_SIZE (1+1+1+(FLT_DECIMAL_DIG-1)+1+1+ 4   +1)
                     //  - d .  dddddddd           e - dddd \0

char buf[FLT_STRING_SIZE];
sprintf(buf, "%.*e", FLT_DECIMAL_DIG-1, some_float);

Ideas:
IMO, better to use 2x buffer size for scratch pads like buf[FLT_STRING_SIZE*2].
For added robustness, use snprintf().


As a 2nd alterative consider "%.*g". It is like "%f" for values exponentially near 1.0 and like "%e" for others.

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

CMake link to external library

arrowdodger's answer is correct and preferred on many occasions. I would simply like to add an alternative to his answer:

You could add an "imported" library target, instead of a link-directory. Something like:

# Your-external "mylib", add GLOBAL if the imported library is located in directories above the current.
add_library( mylib SHARED IMPORTED )
# You can define two import-locations: one for debug and one for release.
set_target_properties( mylib PROPERTIES IMPORTED_LOCATION ${CMAKE_BINARY_DIR}/res/mylib.so )

And then link as if this library was built by your project:

TARGET_LINK_LIBRARIES(GLBall mylib)

Such an approach would give you a little more flexibility: Take a look at the add_library( ) command and the many target-properties related to imported libraries.

I do not know if this will solve your problem with "updated versions of libs".

Construct a manual legend for a complicated plot

In case you were struggling to change linetypes, the following answer should be helpful. (This is an addition to the solution by Andy W.)

We will try to extend the learned pattern:

cols <- c("LINE1"="#f04546","LINE2"="#3591d1","BAR"="#62c76b")
line_types <- c("LINE1"=1,"LINE2"=3)
ggplot(data=data,aes(x=a)) + 
  geom_bar(stat="identity", aes(y=h,fill = "BAR"))+ #green
  geom_line(aes(y=b,group=1, colour="LINE1", linetype="LINE1"),size=0.5) +   #red
  geom_point(aes(y=b, colour="LINE1", fill="LINE1"),size=2) +           #red
  geom_line(aes(y=c,group=1,colour="LINE2", linetype="LINE2"),size=0.5) +   #blue 
  geom_point(aes(y=c,colour="LINE2", fill="LINE2"),size=2) +           #blue
  scale_colour_manual(name="Error Bars",values=cols, 
                  guide = guide_legend(override.aes=aes(fill=NA))) + 
  scale_linetype_manual(values=line_types)+
  scale_fill_manual(name="Bar",values=cols, guide="none") +
  ylab("Symptom severity") + xlab("PHQ-9 symptoms") +
  ylim(0,1.6) +
  theme_bw() +
  theme(axis.title.x = element_text(size = 15, vjust=-.2)) +
  theme(axis.title.y = element_text(size = 15, vjust=0.3))

However, what we get is the following result: manual without name

The problem is that the linetype is not merged in the main legend. Note that we did not give any name to the method scale_linetype_manual. The trick which works here is to give it the same name as what you used for naming scale_colour_manual. More specifically, if we change the corresponding line to the following we get the desired result:

scale_linetype_manual(name="Error Bars",values=line_types)

manual with the same name

Now, it is easy to change the size of the line with the same idea.

Note that the geom_bar has not colour property anymore. (I did not try to fix this issue.) Also, adding geom_errorbar with colour attribute spoils the result. It would be great if somebody can come up with a better solution which resolves these two issues as well.

Check a radio button with javascript

Today, in the year 2016, it is save to use document.querySelector without knowing the ID (especially if you have more than 2 radio buttons):

document.querySelector("input[name=main-categories]:checked").value

iPad/iPhone hover problem causes the user to double click a link

MacFreak's answer was extremely helpful to me. Here's some hands-on code in case it helps you.

PROBLEM - applying touchend means every time you scroll your finger over an element, it responds as if you've pressed it, even if you were just trying to scroll past.

I'm creating an effect with jQuery which fades up a line under some buttons to "highlight" the hovered button. I do not want this to mean you have to press the button twice on touch devices to follow the link.

Here are the buttons:

<a class="menu_button" href="#">
    <div class="menu_underline"></div>
</a>

I want the "menu_underline" div to fade up on mouseover and fade out on mouseout. BUT I want touch devices to be able to follow the link on one single click, not two.

SOLUTION - Here's the jQuery to make it work:

//Mouse Enter
$('.menu_button').bind('touchstart mouseenter', function(){
    $(this).find(".menu_underline").fadeIn();
});

//Mouse Out   
$('.menu_button').bind('mouseleave touchmove click', function(){
    $(this).find(".menu_underline").fadeOut();
});

Many thanks for your help on this MacFreak.

What does "fatal: bad revision" mean?

Why are you specifying myFile there?

Git revert reverts the commit(s) that you specify.

git revert HEAD~2

reverts the HEAD~2 commit

git revert HEAD~2 myfile

reverts HEAD~2 AND myFile

I take myFile is a file that you want to revert? In that case use

git checkout HEAD~2 -- myFile

Does calling clone() on an array also clone its contents?

1D array of primitives does copy elements when it is cloned. This tempts us to clone 2D array(Array of Arrays).

Remember that 2D array clone doesn't work due to shallow copy implementation of clone().

public static void main(String[] args) {
    int row1[] = {0,1,2,3};
    int row2[] =  row1.clone();
    row2[0] = 10;
    System.out.println(row1[0] == row2[0]); // prints false

    int table1[][]={{0,1,2,3},{11,12,13,14}};
    int table2[][] = table1.clone();
    table2[0][0] = 100;
    System.out.println(table1[0][0] == table2[0][0]); //prints true
}

What does the "at" (@) symbol do in Python?

What does the “at” (@) symbol do in Python?

@ symbol is a syntactic sugar python provides to utilize decorator,
to paraphrase the question, It's exactly about what does decorator do in Python?

Put it simple decorator allow you to modify a given function's definition without touch its innermost (it's closure).
It's the most case when you import wonderful package from third party. You can visualize it, you can use it, but you cannot touch its innermost and its heart.

Here is a quick example,
suppose I define a read_a_book function on Ipython

In [9]: def read_a_book():
   ...:     return "I am reading the book: "
   ...: 
In [10]: read_a_book()
Out[10]: 'I am reading the book: '

You see, I forgot to add a name to it.
How to solve such a problem? Of course, I could re-define the function as:

def read_a_book():
    return "I am reading the book: 'Python Cookbook'"

Nevertheless, what if I'm not allowed to manipulate the original function, or if there are thousands of such function to be handled.

Solve the problem by thinking different and define a new_function

def add_a_book(func):
    def wrapper():
        return func() + "Python Cookbook"
    return wrapper

Then employ it.

In [14]: read_a_book = add_a_book(read_a_book)
In [15]: read_a_book()
Out[15]: 'I am reading the book: Python Cookbook'

Tada, you see, I amended read_a_book without touching it inner closure. Nothing stops me equipped with decorator.

What's about @

@add_a_book
def read_a_book():
    return "I am reading the book: "
In [17]: read_a_book()
Out[17]: 'I am reading the book: Python Cookbook'

@add_a_book is a fancy and handy way to say read_a_book = add_a_book(read_a_book), it's a syntactic sugar, there's nothing more fancier about it.

splitting a string into an array in C++ without using vector

It is possible to turn the string into a stream by using the std::stringstream class (its constructor takes a string as parameter). Once it's built, you can use the >> operator on it (like on regular file based streams), which will extract, or tokenize word from it:

#include <iostream>
#include <sstream>

using namespace std;

int main(){
    string line = "test one two three.";
    string arr[4];
    int i = 0;
    stringstream ssin(line);
    while (ssin.good() && i < 4){
        ssin >> arr[i];
        ++i;
    }
    for(i = 0; i < 4; i++){
        cout << arr[i] << endl;
    }
}

How does strcmp() work?

The pseudo-code "implementation" of strcmp would go something like:

define strcmp (s1, s2):
    p1 = address of first character of str1
    p2 = address of first character of str2

    while contents of p1 not equal to null:
        if contents of p2 equal to null: 
            return 1

        if contents of p2 greater than contents of p1:
            return -1

        if contents of p1 greater than contents of p2:
            return 1

        advance p1
        advance p2

    if contents of p2 not equal to null:
        return -1

    return 0

That's basically it. Each character is compared in turn an a decision is made as to whether the first or second string is greater, based on that character.

Only if the characters are identical do you move to the next character and, if all the characters were identical, zero is returned.

Note that you may not necessarily get 1 and -1, the specs say that any positive or negative value will suffice, so you should always check the return value with < 0, > 0 or == 0.

Turning that into real C would be relatively simple:

int myStrCmp (const char *s1, const char *s2) {
    const unsigned char *p1 = (const unsigned char *)s1;
    const unsigned char *p2 = (const unsigned char *)s2;

    while (*p1 != '\0') {
        if (*p2 == '\0') return  1;
        if (*p2 > *p1)   return -1;
        if (*p1 > *p2)   return  1;

        p1++;
        p2++;
    }

    if (*p2 != '\0') return -1;

    return 0;
}

Also keep in mind that "greater" in the context of characters is not necessarily based on simple ASCII ordering for all string functions.

C has a concept called 'locales' which specify (among other things) collation, or ordering of the underlying character set and you may find, for example, that the characters a, á, à and ä are all considered identical. This will happen for functions like strcoll.

Windows batch files: .bat vs .cmd?

Still, on Windows 7, BAT files have also this difference : If you ever create files TEST.BAT and TEST.CMD in the same directory, and you run TEST in that directory, it'll run the BAT file.

C:\>echo %PATHEXT%
.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC

C:\Temp>echo echo bat > test.bat

C:\Temp>echo echo cmd > test.cmd

C:\Temp>test

C:\Temp>echo bat
bat

C:\Temp>

How to connect TFS in Visual Studio code

I know I'm a little late to the party, but I did want to throw some interjections. (I would have commented but not enough reputation points yet, so, here's a full answer).

This requires the latest version of VS Code, Azure Repo Extention, and Git to be installed.

Anyone looking to use the new VS Code (or using the preview like myself), when you go to the Settings (Still File -> Preferences -> Settings or CTRL+, ) you'll be looking under User Settings -> Extensions -> Azure Repos.

Azure_Repo_Settings

Then under Tfvc: Location you can paste the location of the executable.

Location_Settings

For 2017 it'll be

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

Or for 2019 (Preview)

C:\Program Files (x86)\Microsoft Visual Studio\2019\Preview\Common7\IDE\CommonExtensions\Microsoft\TeamFoundation\Team Explorer\TF.exe

After adding the location, I closed my VS Code (not sure if this was needed) and went my git repo to copy the git URL.

Git_URL

After that, went back into VS Code went to the Command Palette (View -> Command Palette or CTRL+Shift+P) typed Git: Clone pasted my repo:

Git_Repo

Selected the location for the repo to be stored. Next was an error that popped up. I proceeded to follow this video which walked me through clicking on the Team button with the exclamation mark on the bottom of your VS Code Screen

Team_Button

Then chose the new method of authentication

New_Method

Copy by using CTRL+C and then press enter. Your browser will launch a page where you'll enter the code you copied (CTRL+V).

Enter_Code_Screen

Click Continue

Continue_Button

Log in with your Microsoft Credentials and you should see a change on the bottom bar of VS Code.

Bottom_Bar

Cheers!

Can you have multiple $(document).ready(function(){ ... }); sections?

It's legal, but sometimes it cause undesired behaviour. As an Example I used the MagicSuggest library and added two MagicSuggest inputs in a page of my project and used seperate document ready functions for each initializations of inputs. The very first Input initialization worked, but not the second one and also not giving any error, Second Input didn't show up. So, I always recommend to use one Document Ready Function.

Get element type with jQuery

As Distdev alluded to, you still need to differentiate the input type. That is to say,

$(this).prev().prop('tagName');

will tell you input, but that doesn't differentiate between checkbox/text/radio. If it's an input, you can then use

$('#elementId').attr('type');

to tell you checkbox/text/radio, so you know what kind of control it is.

Convert date to day name e.g. Mon, Tue, Wed

This is what happens when you store your dates and times in a non-standard format. Working with them become problematic.

$datetime = DateTime::createFromFormat('YmdHi', '201308131830');
echo $datetime->format('D');

See it in action

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

Of course that works; when @item1 = N'', it IS NOT NULL.

You can define @item1 as NULL by default at the top of your stored procedure, and then not pass in a parameter.

Use CASE statement to check if column exists in table - SQL Server

SELECT *
FROM ...
WHERE EXISTS(SELECT 1 
        FROM sys.columns c
        WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
            AND c.name = 'ModifiedByUser'
    )

error: invalid type argument of ‘unary *’ (have ‘int’)

I have reformatted your code.

The error was situated in this line :

printf("%d", (**c));

To fix it, change to :

printf("%d", (*c));

The * retrieves the value from an address. The ** retrieves the value (an address in this case) of an other value from an address.

In addition, the () was optional.

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int *c = NULL;

    a = &b;
    c = &a;

    printf("%d", *c);

    return 0;
} 

EDIT :

The line :

c = &a;

must be replaced by :

c = a;

It means that the value of the pointer 'c' equals the value of the pointer 'a'. So, 'c' and 'a' points to the same address ('b'). The output is :

10

EDIT 2:

If you want to use a double * :

#include <stdio.h>

int main(void)
{
    int b = 10; 
    int *a = NULL;
    int **c = NULL;

    a = &b;
    c = &a;

    printf("%d", **c);

    return 0;
} 

Output:

10

File upload from <input type="file">

There is a slightly better way to access attached files. You could use template reference variable to get an instance of the input element.

Here is an example based on the first answer:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input type="file" #file (change)="onChange(file.files)"/>
    </div>
  `,
  providers: [ UploadService ]
})

export class AppComponent {
  onChange(files) {
    console.log(files);
  }
}

Here is an example app to demonstrate this in action.

Template reference variables might be useful, e.g. you could access them via @ViewChild directly in the controller.

Ubuntu says "bash: ./program Permission denied"

chmod u+x program_name. Then execute it.

If that does not work, copy the program from the USB device to a native volume on the system. Then chmod u+x program_name on the local copy and execute that.

Unix and Unix-like systems generally will not execute a program unless it is marked with permission to execute. The way you copied the file from one system to another (or mounted an external volume) may have turned off execute permission (as a safety feature). The command chmod u+x name adds permission for the user that owns the file to execute it.

That command only changes the permissions associated with the file; it does not change the security controls associated with the entire volume. If it is security controls on the volume that are interfering with execution (for example, a noexec option may be specified for a volume in the Unix fstab file, which says not to allow execute permission for files on the volume), then you can remount the volume with options to allow execution. However, copying the file to a local volume may be a quicker and easier solution.

How to write a PHP ternary operator

PHP 8 (Left-associative ternary operator change)

Left-associative ternary operator deprecation https://wiki.php.net/rfc/ternary_associativity. The ternary operator has some weird quirks in PHP. This RFC adds a deprecation warning for nested ternary statements. In PHP 8, this deprecation will be converted to a compile time error.

1 ? 2 : 3 ? 4 : 5;   // deprecated
(1 ? 2 : 3) ? 4 : 5; // ok

source: https://stitcher.io/blog/new-in-php-74#numeric-literal-separator-rfc

jQuery ui dialog change title after load-callback

An enhancement of the hacky idea by Nick Craver to put custom HTML in a jquery dialog title:

var newtitle= '<b>HTML TITLE</b>';
$(".selectorUsedToCreateTheDialog").parent().find("span.ui-dialog-title").html(newtitle);

ASP.NET MVC passing an ID in an ActionLink to the controller

Don't put the @ before the id

new { id = "1" }

The framework "translate" it in ?Lenght when there is a mismatch in the parameter/route

Clear contents of cells in VBA using column reference

You can access entire column as a range using the Worksheet.Columns object

Something like:

Worksheets(sheetname).Columns(1).ClearContents 

should clear contents of A column

There is also the Worksheet.Rows object if you need to do something similar for rows


The error you are receiving is likely due to a missing with block.

You can read about with blocks here: Microsoft Help

Render partial from different folder (not shared)

In my case I was using MvcMailer (https://github.com/smsohan/MvcMailer) and wanted to access a partial view from another folder, that wasn't in "Shared." The above solutions didn't work, but using a relative path did.

@Html.Partial("../MyViewFolder/Partials/_PartialView", Model.MyObject)

Creating a Menu in Python

def my_add_fn():
   print "SUM:%s"%sum(map(int,raw_input("Enter 2 numbers seperated by a space").split()))

def my_quit_fn():
   raise SystemExit

def invalid():
   print "INVALID CHOICE!"

menu = {"1":("Sum",my_add_fn),
        "2":("Quit",my_quit_fn)
       }
for key in sorted(menu.keys()):
     print key+":" + menu[key][0]

ans = raw_input("Make A Choice")
menu.get(ans,[None,invalid])[1]()

Add number of days to a date

I know this is an old question, but for PHP <5.3 you could try this:

$date = '05/07/2013';
$add_days = 7;
$date = date('Y-m-d',strtotime($date) + (24*3600*$add_days)); //my preferred method
//or
$date = date('Y-m-d',strtotime($date.' +'.$add_days.' days');

How to install Cmake C compiler and CXX compiler

Those errors :

"CMake Error: CMAKE_C_COMPILER not set, after EnableLanguage

CMake Error: CMAKE_CXX_COMPILER not set, after EnableLanguage"

means you haven't installed mingw32-base.

Go to http://sourceforge.net/projects/mingw/files/latest/download?source=files

and then make sure you select "mingw32-base"

Make sure you set up environment variables correctly in PATH section. "C:\MinGW\bin"

After that open CMake and Select Installation --> Delete Cache.

And click configure button again. I solved the problem this way, hope you solve the problem.

What is the recommended way to delete a large number of items from DynamoDB?

According to the DynamoDB documentation you could just delete the full table.

See below:

"Deleting an entire table is significantly more efficient than removing items one-by-one, which essentially doubles the write throughput as you do as many delete operations as put operations"

If you wish to delete only a subset of your data, then you could make separate tables for each month, year or similar. This way you could remove "last month" and keep the rest of your data intact.

This is how you delete a table in Java using the AWS SDK:

DeleteTableRequest deleteTableRequest = new DeleteTableRequest()
  .withTableName(tableName);
DeleteTableResult result = client.deleteTable(deleteTableRequest);

Difference between signed / unsigned char

There are three char types: (plain) char, signed char and unsigned char. Any char is usually an 8-bit integer* and in that sense, a signed and unsigned char have a useful meaning (generally equivalent to uint8_t and int8_t). When used as a character in the sense of text, use a char (also referred to as a plain char). This is typically a signed char but can be implemented either way by the compiler.

* Technically, a char can be any size as long as sizeof(char) is 1, but it is usually an 8-bit integer.

How to change scroll bar position with CSS?

Using CSS only:

Right/Left Flippiing: Working Fiddle

.Container
{
    height: 200px;
    overflow-x: auto;
}
.Content
{
    height: 300px;
}

.Flipped
{
    direction: rtl;
}
.Content
{
    direction: ltr;
}

Top/Bottom Flipping: Working Fiddle

.Container
{
    width: 200px;
    overflow-y: auto;
}
.Content
{
    width: 300px;
}

.Flipped, .Flipped .Content
{
    transform:rotateX(180deg);
    -ms-transform:rotateX(180deg); /* IE 9 */
    -webkit-transform:rotateX(180deg); /* Safari and Chrome */
}

How to get old Value with onchange() event in text box

You can do this: add oldvalue attribute to html element, add set oldvalue when user click. Then onchange event use oldvalue.

<input type="text" id="test" value ="ABS" onchange="onChangeTest(this)" onclick="setoldvalue(this)" oldvalue="">

<script>
function setoldvalue(element){
   element.setAttribute("oldvalue",this.value);
}

function onChangeTest(element){
   element.setAttribute("value",this.getAttribute("oldvalue"));
}
</script>

What are the alternatives now that the Google web search API has been deprecated?

I have just come across this from Common Crawl.

http://www.commoncrawl.org/

Might be the answer we are all looking for!!

How do I deal with "signed/unsigned mismatch" warnings (C4018)?

It's all in your things.size() type. It isn't int, but size_t (it exists in C++, not in C) which equals to some "usual" unsigned type, i.e. unsigned int for x86_32.

Operator "less" (<) cannot be applied to two operands of different sign. There's just no such opcodes, and standard doesn't specify, whether compiler can make implicit sign conversion. So it just treats signed number as unsigned and emits that warning.

It would be correct to write it like

for (size_t i = 0; i < things.size(); ++i) { /**/ }

or even faster

for (size_t i = 0, ilen = things.size(); i < ilen; ++i) { /**/ }

Android Webview gives net::ERR_CACHE_MISS message

I ran to a similar problem and that was just because of the extra spaces:

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

which when removed works fine:

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

find the array index of an object with a specific key value in underscore

The simplest solution is to use lodash:

  1. Install lodash:

npm install --save lodash

  1. Use method findIndex:

const _ = require('lodash');

findIndexByElementKeyValue = (elementKeyValue) => {
  return _.findIndex(array, arrayItem => arrayItem.keyelementKeyValue);
}

How to fix corrupted git repository?

This command worked for me:

$ git reset --mixed 

Search a string in a file and delete it from this file by Shell Script

Try the vim-way:

ex -s +"g/foo/d" -cwq file.txt

mongodb how to get max value from collections

The performance of the suggested answer is fine. According to the MongoDB documentation:

When a $sort immediately precedes a $limit, the optimizer can coalesce the $limit into the $sort. This allows the sort operation to only maintain the top n results as it progresses, where n is the specified limit, and MongoDB only needs to store n items in memory.

Changed in version 4.0.

So in the case of

db.collection.find().sort({age:-1}).limit(1)

we get only the highest element WITHOUT sorting the collection because of the mentioned optimization.

How to check if element is visible after scrolling?

This method will return true if any part of the element is visible on the page. It worked better in my case and may help someone else.

function isOnScreen(element) {
  var elementOffsetTop = element.offset().top;
  var elementHeight = element.height();

  var screenScrollTop = $(window).scrollTop();
  var screenHeight = $(window).height();

  var scrollIsAboveElement = elementOffsetTop + elementHeight - screenScrollTop >= 0;
  var elementIsVisibleOnScreen = screenScrollTop + screenHeight - elementOffsetTop >= 0;

  return scrollIsAboveElement && elementIsVisibleOnScreen;
}

How to get history on react-router v4?

If you are using redux and redux-thunk the best solution will be using react-router-redux

// then, in redux actions for example
import { push } from 'react-router-redux'

dispatch(push('/some/path'))

It's important to see the docs to do some configurations.

could not extract ResultSet in hibernate

The @JoinColumn annotation specifies the name of the column being used as the foreign key on the targeted entity.

On the Product class above, the name of the join column is set to ID_CATALOG.

@ManyToOne
@JoinColumn(name="ID_CATALOG")
private Catalog catalog;

However, the foreign key on the Product table is called catalog_id

`catalog_id` int(11) DEFAULT NULL,

You'll need to change either the column name on the table or the name you're using in the @JoinColumn so that they match. See http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/entity.html#entity-mapping-association

SQL join: selecting the last records in a one-to-many relationship

Try this, It will help.

I have used this in my project.

SELECT 
*
FROM
customer c
OUTER APPLY(SELECT top 1 * FROM purchase pi 
WHERE pi.customer_id = c.Id order by pi.Id desc) AS [LastPurchasePrice]

How to build & install GLFW 3 and use it in a Linux project

I solved it in this way

A pkg-config file describes all necessary compile-time and link-time flags and dependencies needed to use a library.

pkg-config --static --libs glfw3

shows me that

-L/usr/local/lib -lglfw3 -lrt -lXrandr -lXinerama -lXi -lXcursor -lGL -lm -ldl -lXrender -ldrm -lXdamage -lX11-xcb -lxcb-glx -lxcb-dri2 -lxcb-dri3 -lxcb-present -lxcb-sync -lxshmfence -lXxf86vm -lXfixes -lXext -lX11 -lpthread -lxcb -lXau -lXdmcp  

I don't know if all these libs are actually necessary for compiling but for me it works...

Android set height and width of Custom view programmatically

you can set the height and width of a view in a relative layout like this

ViewGroup.LayoutParams params = view.getLayoutParams();
params.height = 130;
view.setLayoutParams(params);

Make absolute positioned div expand parent div height

I came up with another solution, which I don't love but gets the job done.

Basically duplicate the child elements in such a way that the duplicates are not visible.

<div id="parent">
    <div class="width-calc">
        <div class="child1"></div>
        <div class="child2"></div>
    </div>

    <div class="child1"></div>
    <div class="child2"></div>
</div>

CSS:

.width-calc {
    height: 0;
    overflow: hidden;
}

If those child elements contain little markup, then the impact will be small.

Convert MFC CString to integer

i've written a function that extract numbers from string:

int SnirElgabsi::GetNumberFromCString(CString src, CString str, int length) {
   // get startIndex
   int startIndex = src.Find(str) + CString(str).GetLength();
   // cut the string
   CString toreturn = src.Mid(startIndex, length);
   // convert to number
   return _wtoi(toreturn); // atoi(toreturn)
}

Usage:

CString str = _T("digit:1, number:102");
int  digit = GetNumberFromCString(str, _T("digit:"), 1);
int number = GetNumberFromCString(str, _T("number:"), 3);

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

Why is setState in reactjs Async instead of Sync?

You can use the following wrap to make sync call

_x000D_
_x000D_
this.setState((state =>{_x000D_
  return{_x000D_
    something_x000D_
  }_x000D_
})
_x000D_
_x000D_
_x000D_

SQLite DateTime comparison

Below are the methods to compare the dates but before that we need to identify the format of date stored in DB

I have dates stored in MM/DD/YYYY HH:MM format so it has to be compared in that format

  1. Below query compares the convert the date into MM/DD/YYY format and get data from last five days till today. BETWEEN operator will help and you can simply specify start date AND end date.

    select * from myTable where myColumn BETWEEN strftime('%m/%d/%Y %H:%M', datetime('now','localtime'), '-5 day') AND strftime('%m/%d/%Y %H:%M',datetime('now','localtime')); 
    
  2. Below query will use greater than operator (>).

      select * from myTable where myColumn > strftime('%m/%d/%Y %H:%M', datetime('now','localtime'), '-5 day');  

All the computation I have done is using current time, you can change the format and date as per your need.

Hope this will help you

Summved

How to create a WPF Window without a border that can be resized via a grip only?

I was trying to create a borderless window with WindowStyle="None" but when I tested it, seems that appears a white bar in the top, after some research it appears to be a "Resize border", here is an image (I remarked in yellow):

The Challenge

After some research over the internet, and lots of difficult non xaml solutions, all the solutions that I found were code behind in C# and lots of code lines, I found indirectly the solution here: Maximum custom window loses drop shadow effect

<WindowChrome.WindowChrome>
    <WindowChrome 
        CaptionHeight="0"
        ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>

Note : You need to use .NET 4.5 framework, or if you are using an older version use WPFShell, just reference the shell and use Shell:WindowChrome.WindowChrome instead.

I used the WindowChrome property of Window, if you use this that white "resize border" disappears, but you need to define some properties to work correctly.

CaptionHeight: This is the height of the caption area (headerbar) that allows for the Aero snap, double clicking behaviour as a normal title bar does. Set this to 0 (zero) to make the buttons work.

ResizeBorderThickness: This is thickness at the edge of the window which is where you can resize the window. I put to 5 because i like that number, and because if you put zero its difficult to resize the window.

After using this short code the result is this:

The Solution

And now, the white border disappeared without using ResizeMode="NoResize" and AllowsTransparency="True", also it shows a shadow in the window.

Later I will explain how to make to work the buttons (I didn't used images for the buttons) easily with simple and short code, Im new and i think that I can post to codeproject, because here I didn't find the place to post the tutorial.

Maybe there is another solution (I know that there are hard and difficult solutions for noobs like me) but this works for my personal projects.

Here is the complete code

<Window x:Class="MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:Concursos"
    mc:Ignorable="d"
    Title="Concuros" Height="350" Width="525"
    WindowStyle="None"
    WindowState="Normal" 
    ResizeMode="CanResize"
    >
<WindowChrome.WindowChrome>
    <WindowChrome 
        CaptionHeight="0"
        ResizeBorderThickness="5" />
</WindowChrome.WindowChrome>

    <Grid>

    <Rectangle Fill="#D53736" HorizontalAlignment="Stretch" Height="35" VerticalAlignment="Top" PreviewMouseDown="Rectangle_PreviewMouseDown" />
    <Button x:Name="Btnclose" Content="r" HorizontalAlignment="Right" VerticalAlignment="Top" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
    <Button x:Name="Btnmax" Content="2" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,35,0" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>
    <Button x:Name="Btnmin" Content="0" HorizontalAlignment="Right" VerticalAlignment="Top" Margin="0,0,70,0" Width="35" Height="35" Style="{StaticResource TempBTNclose}"/>

</Grid>

Thank you!

How do I fix twitter-bootstrap on IE?

Please put the pages in localhost and try

What is the correct format to use for Date/Time in an XML file

What does the DTD have to say?

If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.

If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it. In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans. e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.

How to include JavaScript file or library in Chrome console?

If you're just starting out learning javascript & don't want to spend time creating an entire webpage just for embedding test scripts, just open Dev Tools in a new tab in Chrome Browser, and click on Console.

Then type out some test scripts: eg.

console.log('Aha!') 

Then press Enter after every line (to submit for execution by Chrome)

or load your own "external script file":

document.createElement('script').src = 'http://example.com/file.js';

Then call your functions:

console.log(file.function('?????'))

Tested in Google Chrome 85.0.4183.121

Python dictionary get multiple values

No-one has mentioned the map function, which allows a function to operate element-wise on a list:

mydictionary = {'a': 'apple', 'b': 'bear', 'c': 'castle'}
keys = ['b', 'c']

values = list( map(mydictionary.get, keys) )

# values = ['bear', 'castle']

Alternative to the HTML Bold tag

The answer by @Darryl Hein is correct despite one point - <b> is not recommended at all since XHTML, because it's not semantic.

<strong> means semantically highlighted text

font-weight: bold means visually highlighted text

<strong> can be css-tuned to not be bold, though it's a conventional default. It can be made red, or italic, or underlined (though all these possibilities are not really user-friendly). Use it for phrases / words in text, not because of visual design, but related to their meaning

font-weight: bold should be used for design-related bold parts, like headers, sub-headers, table header cells etc.

Passing a variable from one php include file to another: global vs. not

When including files in PHP, it acts like the code exists within the file they are being included from. Imagine copy and pasting the code from within each of your included files directly into your index.php. That is how PHP works with includes.

So, in your example, since you've set a variable called $name in your front.inc file, and then included both front.inc and end.inc in your index.php, you will be able to echo the variable $name anywhere after the include of front.inc within your index.php. Again, PHP processes your index.php as if the code from the two files you are including are part of the file.

When you place an echo within an included file, to a variable that is not defined within itself, you're not going to get a result because it is treated separately then any other included file.

In other words, to do the behavior you're expecting, you will need to define it as a global.

How can I stop .gitignore from appearing in the list of untracked files?

It is quite possible that an end user wants to have Git ignore the ".gitignore" file simply because the IDE specific folders created by Eclipse are probably not the same as NetBeans or another IDE. So to keep the source code IDE antagonistic it makes life easy to have a custom git ignore that isn't shared with the entire team as individual developers might be using different IDE's.

How can I concatenate a string within a loop in JSTL/JSP?

define a String variable using the JSP tags

<%!
String test = new String();
%>

then refer to that variable in your loop as

<c:forEach items="${myParams.items}" var="currentItem" varStatus="stat">
test+= whaterver_value
</c:forEach>

use mysql SUM() in a WHERE clause

In general, a condition in the WHERE clause of an SQL query can reference only a single row. The context of a WHERE clause is evaluated before any order has been defined by an ORDER BY clause, and there is no implicit order to an RDBMS table.

You can use a derived table to join each row to the group of rows with a lesser id value, and produce the sum of each sum group. Then test where the sum meets your criterion.

CREATE TABLE MyTable ( id INT PRIMARY KEY, cash INT );

INSERT INTO MyTable (id, cash) VALUES
  (1, 200), (2, 301), (3, 101), (4, 700);

SELECT s.*
FROM (
  SELECT t.id, SUM(prev.cash) AS cash_sum
  FROM MyTable t JOIN MyTable prev ON (t.id > prev.id)
  GROUP BY t.id) AS s
WHERE s.cash_sum >= 500
ORDER BY s.id
LIMIT 1;

Output:

+----+----------+
| id | cash_sum |
+----+----------+
|  3 |      501 |
+----+----------+

'"SDL.h" no such file or directory found' when compiling

the simplest idea is to add pkg-config --cflags --libs sdl2 while compiling the code.

g++ file.cpp `pkg-config --cflags --libs sdl2`

How can I remove an entry in global configuration with git config?

Open config file to edit :

git config --global --edit

Press Insert and remove the setting

and finally type :wq and Enter to save.

Apache default VirtualHost

The solution is:

NameVirtualHost *:80
Listen 80

(...)

<VirtualHost *:80>
    ServerName host1
    DocumentRoot /someDir
</VirtualHost>

<VirtualHost *:80>
    ServerName host2
    DocumentRoot /someOtherDir
</VirtualHost>

<VirtualHost *:80>
    ServerName aaaa.com
    DocumentRoot /defaultDir
</VirtualHost>

In my case, to work, I created a VirtualHost (n.e. VirtualHost per CNAME) called aaaa.com since I have different files for different VirtualHosts and knowing that Apache reads them in alphabetical order.

Add CSS3 transition expand/collapse

http://jsfiddle.net/Bq6eK/215/

I did not modify your code for this solution, I wrote my own instead. My solution isn't quite what you asked for, but maybe you could build on it with existing knowledge. I commented the code as well so you know what exactly I'm doing with the changes.

As a solution to "avoid setting the height in JavaScript", I just made 'maxHeight' a parameter in the JS function called toggleHeight. Now it can be set in the HTML for each div of class expandable.

I'll say this up front, I'm not super experienced with front-end languages, and there's an issue where I need to click the 'Show/hide' button twice initially before the animation starts. I suspect it's an issue with focus.

The other issue with my solution is that you can actually figure out what the hidden text is without pressing the show/hide button just by clicking in the div and dragging down, you can highlight the text that's not visible and paste it to a visible space.

My suggestion for a next step on top of what I've done is to make it so that the show/hide button changes dynamically. I think you can figure out how to do that with what you already seem to know about showing and hiding text with JS.

Java Best Practices to Prevent Cross Site Scripting

The normal practice is to HTML-escape any user-controlled data during redisplaying in JSP, not during processing the submitted data in servlet nor during storing in DB. In JSP you can use the JSTL (to install it, just drop jstl-1.2.jar in /WEB-INF/lib) <c:out> tag or fn:escapeXml function for this. E.g.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<p>Welcome <c:out value="${user.name}" /></p>

and

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
...
<input name="username" value="${fn:escapeXml(param.username)}">

That's it. No need for a blacklist. Note that user-controlled data covers everything which comes in by a HTTP request: the request parameters, body and headers(!!).

If you HTML-escape it during processing the submitted data and/or storing in DB as well, then it's all spread over the business code and/or in the database. That's only maintenance trouble and you will risk double-escapes or more when you do it at different places (e.g. & would become &amp;amp; instead of &amp; so that the enduser would literally see &amp; instead of & in view. The business code and DB are in turn not sensitive for XSS. Only the view is. You should then escape it only right there in view.

See also:

download a file from Spring boot rest service

I would suggest using a StreamingResponseBody since with it the application can write directly to the response (OutputStream) without holding up the Servlet container thread. It is a good approach if you are downloading a file very large.

@GetMapping("download")
public StreamingResponseBody downloadFile(HttpServletResponse response, @PathVariable Long fileId) {

    FileInfo fileInfo = fileService.findFileInfo(fileId);
    response.setContentType(fileInfo.getContentType());
    response.setHeader(
        HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + fileInfo.getFilename() + "\"");

    return outputStream -> {
        int bytesRead;
        byte[] buffer = new byte[BUFFER_SIZE];
        InputStream inputStream = fileInfo.getInputStream();
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
    };
}

Ps.: When using StreamingResponseBody, it is highly recommended to configure TaskExecutor used in Spring MVC for executing asynchronous requests. TaskExecutor is an interface that abstracts the execution of a Runnable.

More info: https://medium.com/swlh/streaming-data-with-spring-boot-restful-web-service-87522511c071

mysqldump Error 1045 Access denied despite correct passwords etc

I discovered a running apache process acessing the MYSQL causing this error. So I suggest to ensure that all processes which might interact with the DB are shutdown beforehand.

Scala: what is the best way to append an element to an Array?

val array2 = array :+ 4
//Array(1, 2, 3, 4)

Works also "reversed":

val array2 = 4 +: array
Array(4, 1, 2, 3)

There is also an "in-place" version:

var array = Array( 1, 2, 3 )
array +:= 4
//Array(4, 1, 2, 3)
array :+= 0
//Array(4, 1, 2, 3, 0)

Typescript export vs. default export

Default Export (export default)

// MyClass.ts -- using default export
export default class MyClass { /* ... */ }

The main difference is that you can only have one default export per file and you import it like so:

import MyClass from "./MyClass";

You can give it any name you like. For example this works fine:

import MyClassAlias from "./MyClass";

Named Export (export)

// MyClass.ts -- using named exports
export class MyClass { /* ... */ }
export class MyOtherClass { /* ... */ }

When you use a named export, you can have multiple exports per file and you need to import the exports surrounded in braces:

import { MyClass } from "./MyClass";

Note: Adding the braces will fix the error you're describing in your question and the name specified in the braces needs to match the name of the export.

Or say your file exported multiple classes, then you could import both like so:

import { MyClass, MyOtherClass } from "./MyClass";
// use MyClass and MyOtherClass

Or you could give either of them a different name in this file:

import { MyClass, MyOtherClass as MyOtherClassAlias } from "./MyClass";
// use MyClass and MyOtherClassAlias

Or you could import everything that's exported by using * as:

import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClasses.MyOtherClass here

Which to use?

In ES6, default exports are concise because their use case is more common; however, when I am working on code internal to a project in TypeScript, I prefer to use named exports instead of default exports almost all the time because it works very well with code refactoring. For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.

It also plays very nicely with barrel files (files that use namespace exports—export *—to export other files). An example of this is shown in the "example" section of this answer.

Note that my opinion on using named exports even when there is only one export is contrary to the TypeScript Handbook—see the "Red Flags" section. I believe this recommendation only applies when you are creating an API for other people to use and the code is not internal to your project. When I'm designing an API for people to use, I'll use a default export so people can do import myLibraryDefaultExport from "my-library-name";. If you disagree with me about doing this, I would love to hear your reasoning.

That said, find what you prefer! You could use one, the other, or both at the same time.

Additional Points

A default export is actually a named export with the name default, so if the file has a default export then you can also import by doing:

import { default as MyClass } from "./MyClass";

And take note these other ways to import exist: 

import MyDefaultExportedClass, { Class1, Class2 } from "./SomeFile";
import MyDefaultExportedClass, * as Classes from "./SomeFile";
import "./SomeFile"; // runs SomeFile.js without importing any exports

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

File URL "Not allowed to load local resource" in the Internet Browser

Follow the below steps,

  1. npm install -g http-server, install the http-server in angular project.
  2. Go to file location which needs to be accessed and open cmd prompt, use cmd http-server ./
  3. Access any of the paths with port number in browser(ex: 120.0.0.1:8080) 4.now in your angular application use the path "http://120.0.0.1:8080/filename" Worked fine for me

Java: convert seconds to minutes, hours and days

You can use the Java enum TimeUnit to perform your math and avoid any hard coded values. Then we can use String.format(String, Object...) and a pair of StringBuilder(s) as well as a DecimalFormat to build the requested output. Something like,

Scanner scanner = new Scanner(System.in);
System.out.println("Please enter a number of seconds:");
String str = scanner.nextLine().replace("\\,", "").trim();
long secondsIn = Long.parseLong(str);
long dayCount = TimeUnit.SECONDS.toDays(secondsIn);
long secondsCount = secondsIn - TimeUnit.DAYS.toSeconds(dayCount);
long hourCount = TimeUnit.SECONDS.toHours(secondsCount);
secondsCount -= TimeUnit.HOURS.toSeconds(hourCount);
long minutesCount = TimeUnit.SECONDS.toMinutes(secondsCount);
secondsCount -= TimeUnit.MINUTES.toSeconds(minutesCount);
StringBuilder sb = new StringBuilder();
sb.append(String.format("%d %s, ", dayCount, (dayCount == 1) ? "day"
        : "days"));
StringBuilder sb2 = new StringBuilder();
sb2.append(sb.toString());
sb2.append(String.format("%02d:%02d:%02d %s", hourCount, minutesCount,
        secondsCount, (hourCount == 1) ? "hour" : "hours"));
sb.append(String.format("%d %s, ", hourCount, (hourCount == 1) ? "hour"
        : "hours"));
sb.append(String.format("%d %s and ", minutesCount,
        (minutesCount == 1) ? "minute" : "minutes"));
sb.append(String.format("%d %s.", secondsCount,
        (secondsCount == 1) ? "second" : "seconds"));
System.out.printf("You entered %s seconds, which is %s (%s)%n",
        new DecimalFormat("#,###").format(secondsIn), sb, sb2);

Which, when I enter 500000 outputs the requested (manual line break added for post) -

You entered 500,000 seconds, which is 5 days, 18 hours, 
53 minutes and 20 seconds. (5 days, 18:53:20 hours)

jQuery.active function

This is a variable jQuery uses internally, but had no reason to hide, so it's there to use. Just a heads up, it becomes jquery.ajax.active next release. There's no documentation because it's exposed but not in the official API, lots of things are like this actually, like jQuery.cache (where all of jQuery.data() goes).

I'm guessing here by actual usage in the library, it seems to be there exclusively to support $.ajaxStart() and $.ajaxStop() (which I'll explain further), but they only care if it's 0 or not when a request starts or stops. But, since there's no reason to hide it, it's exposed to you can see the actual number of simultaneous AJAX requests currently going on.


When jQuery starts an AJAX request, this happens:

if ( s.global && ! jQuery.active++ ) {
  jQuery.event.trigger( "ajaxStart" );
}

This is what causes the $.ajaxStart() event to fire, the number of connections just went from 0 to 1 (jQuery.active++ isn't 0 after this one, and !0 == true), this means the first of the current simultaneous requests started. The same thing happens at the other end. When an AJAX request stops (because of a beforeSend abort via return false or an ajax call complete function runs):

if ( s.global && ! --jQuery.active ) {
  jQuery.event.trigger( "ajaxStop" );
}

This is what causes the $.ajaxStop() event to fire, the number of requests went down to 0, meaning the last simultaneous AJAX call finished. The other global AJAX handlers fire in there along the way as well.

Java array assignment (multiple values)

On declaration you can do the following.

float[] values = {0.1f, 0.2f, 0.3f};

When the field is already defined, try this.

values = new float[] {0.1f, 0.2f, 0.3f};

Be aware that also the second version creates a new array. If values was the only reference to an already existing field, it becomes eligible for garbage collection.

Crontab Day of the Week syntax

    :-) Sunday    |    0  ->  Sun
                  |  
        Monday    |    1  ->  Mon
       Tuesday    |    2  ->  Tue
     Wednesday    |    3  ->  Wed
      Thursday    |    4  ->  Thu
        Friday    |    5  ->  Fri
      Saturday    |    6  ->  Sat
                  |  
    :-) Sunday    |    7  ->  Sun

As you can see above, and as said before, the numbers 0 and 7 are both assigned to Sunday. There are also the English abbreviated days of the week listed, which can also be used in the crontab.

Examples of Number or Abbreviation Use

15 09 * * 5,6,0             command
15 09 * * 5,6,7             command
15 09 * * 5-7               command
15 09 * * Fri,Sat,Sun       command

The four examples do all the same and execute a command every Friday, Saturday, and Sunday at 9.15 o'clock.

In Detail

Having two numbers 0 and 7 for Sunday can be useful for writing weekday ranges starting with 0 or ending with 7. So you can write ranges starting with Sunday or ending with it, like 0-2 or 5-7 for example (ranges must start with the lower number and must end with the higher). The abbreviations cannot be used to define a weekday range.

How to run test methods in specific order in JUnit4?

If the order is important, you should make the order yourself.

@Test public void test1() { ... }
@Test public void test2() { test1(); ... }

In particular, you should list some or all possible order permutations to test, if necessary.

For example,

void test1(); 
void test2(); 
void test3(); 


@Test
public void testOrder1() { test1(); test3(); }

@Test(expected = Exception.class)
public void testOrder2() { test2(); test3(); test1(); }

@Test(expected = NullPointerException.class)
public void testOrder3() { test3(); test1(); test2(); }

Or, a full test of all permutations:

@Test
public void testAllOrders() {
    for (Object[] sample: permute(1, 2, 3)) {
        for (Object index: sample) {
            switch (((Integer) index).intValue()) {
                case 1: test1(); break; 
                case 2: test2(); break; 
                case 3: test3(); break; 
            }
        }
    }
}

Here, permute() is a simple function which iterates all possible permuations into a Collection of array.

Refresh a page using PHP

I've found two ways to refresh PHP content:

1. Using the HTML meta tag:

echo("<meta http-equiv='refresh' content='1'>"); //Refresh by HTTP 'meta'

2. Using PHP refresh rate:

$delay = 0; // Where 0 is an example of a time delay. You can use 5 for 5 seconds, for example!
header("Refresh: $delay;"); 

How to rename a table in SQL Server?

To rename a table in SQL Server, use the sp_rename command:

exec sp_rename 'schema.old_table_name', 'new_table_name'

How to make external HTTP requests with Node.js

I would combine node-http-proxy and express.

node-http-proxy will support a proxy inside your node.js web server via RoutingProxy (see the example called Proxy requests within another http server).

Inside your custom server logic you can do authentication using express. See the auth sample here for an example.

Combining those two examples should give you what you want.

Cannot read property 'push' of undefined when combining arrays

Generally, Push method is used to add elements at the end of an array.

Here, you have used the push method to an object and not an array which is 'order'.

Steps to debug...

Change the object into an empty array,

var order = [], stack = [];

Now you can use the push method for this array as usual.

To use push method to this 'order' array; you should not use the array index when calling push method to an array. Just use the name of the array only.

var order = [], stack = [];

for(var i = 0; i<a.length; i++){

   if(parseInt(a[i].daysleft) == 0){ 
     order.push(a[i]); 
   }

   if(parseInt(a[i].daysleft) > 0){ 
     order.push(a[i]); 
   }

   if(parseInt(a[i].daysleft) < 0){ 
     order.push(a[i]); 
   }
}

Pycharm: run only part of my Python file

You can set a breakpoint, and then just open the debug console. So, the first thing you need to turn on your debug console:

enter image description here

After you've enabled, set a break-point to where you want it to:

enter image description here

After you're done setting the break-point:

enter image description here

Once that has been completed:

enter image description here

How to put an image in div with CSS?

This answer by Jaap :

<div class="image"></div>?

and in CSS :

div.image {
   content:url(http://placehold.it/350x150);
}?

you can try it on this link : http://jsfiddle.net/XAh2d/

this is a link about css content http://css-tricks.com/css-content/

This has been tested on Chrome, firefox and Safari. (I'm on a mac, so if someone has the result on IE, tell me to add it)

How to insert text in a td with id, using JavaScript

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);

RESTful Authentication

That's the way to do that: Using OAuth 2.0 for Login.

You may use other authentication methods other then Google's as long as it supports OAuth.

How to copy a collection from one database to another in MongoDB

In my case, I had to use a subset of attributes from the old collection in my new collection. So I ended up choosing those attributes while calling insert on the new collection.

db.<sourceColl>.find().forEach(function(doc) { 
    db.<newColl>.insert({
        "new_field1":doc.field1,
        "new_field2":doc.field2,
        ....
    })
});`

How can I use a DLL file from Python?

For ease of use, ctypes is the way to go.

The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask.

import ctypes

# Load DLL into memory.

hllDll = ctypes.WinDLL ("c:\\PComm\\ehlapi32.dll")

# Set up prototype and parameters for the desired function call.
# HLLAPI

hllApiProto = ctypes.WINFUNCTYPE (
    ctypes.c_int,      # Return type.
    ctypes.c_void_p,   # Parameters 1 ...
    ctypes.c_void_p,
    ctypes.c_void_p,
    ctypes.c_void_p)   # ... thru 4.
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0),

# Actually map the call ("HLLAPI(...)") to a Python name.

hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)

# This is how you can actually call the DLL function.
# Set up the variables and call the Python name with them.

p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p (sessionVar)
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))

The ctypes stuff has all the C-type data types (int, char, short, void*, and so on) and can pass by value or reference. It can also return specific data types although my example doesn't do that (the HLL API returns values by modifying a variable passed by reference).


In terms of the specific example shown above, IBM's EHLLAPI is a fairly consistent interface.

All calls pass four void pointers (EHLLAPI sends the return code back through the fourth parameter, a pointer to an int so, while I specify int as the return type, I can safely ignore it) as per IBM's documentation here. In other words, the C variant of the function would be:

int hllApi (void *p1, void *p2, void *p3, void *p4)

This makes for a single, simple ctypes function able to do anything the EHLLAPI library provides, but it's likely that other libraries will need a separate ctypes function set up per library function.

The return value from WINFUNCTYPE is a function prototype but you still have to set up more parameter information (over and above the types). Each tuple in hllApiParams has a parameter "direction" (1 = input, 2 = output and so on), a parameter name and a default value - see the ctypes doco for details

Once you have the prototype and parameter information, you can create a Python "callable" hllApi with which to call the function. You simply create the needed variable (p1 through p4 in my case) and call the function with them.

git add only modified changes and ignore untracked files

Not sure if this is a feature or a bug but this worked for us:

git commit '' -m "Message"

Note the empty file list ''. Git interprets this to commit all modified tracked files, even if they are not staged, and ignore untracked files.

Convert String XML fragment to Document Node in Java

If you're using dom4j, you can just do:

Document document = DocumentHelper.parseText(text);

(dom4j now found here: https://github.com/dom4j/dom4j)

java.lang.ClassNotFoundException: org.eclipse.core.runtime.adaptor.EclipseStarter

I just went through this. If you want to manually move your Eclipse installation you need to find and edit relative references in the following files.

Relative to Eclipse install dir:

  • configuration/org.eclipse.equinox.source/source.info
  • configuration/org.eclipse.equinox.simpleconfigurator/bundles.info
  • configuration/config.ini
  • eclipse.ini

For me in all these files there was a ../ reference to a .p2 folder in my home directory. Found them all using a simple grep:

grep '../../../../' * -R

Then just hit it with sed or manually go change it. In my case I moved it up one folder so easy fix:

grep -rl '../../../../' * -R | xargs sed -i 's/..\/..\/..\/..\//..\/..\/..\//g'

Now Eclipse runs fine again.

How can I make SMTP authenticated in C#

To send a message through TLS/SSL, you need to set Ssl of the SmtpClient class to true.

string to = "[email protected]";
string from = "[email protected]";
MailMessage message = new MailMessage(from, to);
message.Subject = "Using the new SMTP client.";
message.Body = @"Using this new feature, you can send an e-mail message from an application very easily.";
SmtpClient client = new SmtpClient(server);
// Credentials are necessary if the server requires the client 
// to authenticate before it will send e-mail on the client's behalf.
client.UseDefaultCredentials = true;
client.EnableSsl = true;
client.Send(message);

Two divs side by side - Fluid display

Using this CSS for my current site. It works perfect!

#sides{
margin:0;
}
#left{
float:left;
width:75%;
overflow:hidden;
}
#right{
float:left;
width:25%;
overflow:hidden;
} 

On localhost, how do I pick a free port number?

Bind the socket to port 0. A random free port from 1024 to 65535 will be selected. You may retrieve the selected port with getsockname() right after bind().

How to test web service using command line curl

In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:

$ curl https://api.twitter.com/1/help/configuration.xml  | xmllint --format -
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool

Tested on Ubuntu 11.0.4/11.10.

Another issue is the desired content type. Twitter uses .xml/.json extension, but more idiomatic REST would require Accept header:

$ curl -H "Accept: application/json"

How to add RSA key to authorized_keys file?

mkdir -p ~/.ssh/

To overwrite authorized_keys

cat your_key > ~/.ssh/authorized_keys

To append to the end of authorized_keys

cat your_key >> ~/.ssh/authorized_keys

Get java.nio.file.Path object from java.io.File

As many have suggested, JRE v1.7 and above has File.toPath();

File yourFile = ...;
Path yourPath = yourFile.toPath();

On Oracle's jdk 1.7 documentation which is also mentioned in other posts above, the following equivalent code is described in the description for toPath() method, which may work for JRE v1.6;

File yourFile = ...;
Path yourPath = FileSystems.getDefault().getPath(yourFile.getPath());

Find current directory and file's directory

Current Working Directory: os.getcwd()

And the __file__ attribute can help you find out where the file you are executing is located. This SO post explains everything: How do I get the path of the current executed file in Python?

Vue.js redirection to another page

can try this too ...

router.push({ name: 'myRoute' })

How can I get a list of locally installed Python modules?

on windows, Enter this in cmd

c:\python\libs>python -m pip freeze

Difference between JE/JNE and JZ/JNZ

  je : Jump if equal:

  399  3fb:   64 48 33 0c 25 28 00    xor    %fs:0x28,%rcx
  400  402:   00 00
  401  404:   74 05                   je     40b <sims_get_counter+0x51>

Getting rid of bullet points from <ul>

I had the same extreme irritating problem myself since the script did not take any notice of my styelsheet. So I wrote:

<ul style="list-style-type: none;">

That did not work. So, in addition, I wrote:

<li style="list-style-type: none;">

Voila! it worked!

element with the max height from a set of elements

This might be helpful, in some way. Fixing some code from @diogo

$(window).on('load',function(){

// get the maxHeight using innerHeight() function
  var maxHeight = Math.max.apply(null, $("div.panel").map(function ()                                                        {
    return $(this).innerHeight();
  }).get());
  
// Set the height to all .panel elements
  $("div.panel").height( maxHeight );
  
});

How do I drop a foreign key constraint only if it exists in sql server?

The more simple solution is provided in Eric Isaacs's answer. However, it will find constraints on any table. If you want to target a foreign key constraint on a specific table, use this:

IF EXISTS (SELECT * 
  FROM sys.foreign_keys 
   WHERE object_id = OBJECT_ID(N'dbo.FK_TableName_TableName2')
   AND parent_object_id = OBJECT_ID(N'dbo.TableName')
)
  ALTER TABLE [dbo.TableName] DROP CONSTRAINT [FK_TableName_TableName2]

How to store an output of shell script to a variable in Unix?

You need to start the script with a preceding dot, this will put the exported variables in the current environment.

#!/bin/bash
...
export output="SUCCESS"

Then execute it like so

chmod +x /tmp/test.sh
. /tmp/test.sh

When you need the entire output and not just a single value, just put the output in a variable like the other answers indicate

Get User Selected Range

Selection is its own object within VBA. It functions much like a Range object.

Selection and Range do not share all the same properties and methods, though, so for ease of use it might make sense just to create a range and set it equal to the Selection, then you can deal with it programmatically like any other range.

Dim myRange as Range
Set myRange = Selection

For further reading, check out the MSDN article.

System.Data.SqlClient.SqlException: Login failed for user

Assuming you're intending to use Windows Authentication to impersonate the service account, you have to set up Windows Authentication in both IIS and ASP.NET.

In IIS, make sure that the Windows Authentication module is added and enabled. Also make sure your application pool is running under a domain account, not a local account.

In ASP.NET make sure the authentication mode attribute is set to "Windows"

<system.web>
    <authentication mode="Windows"/>
 </system.web>

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

Yeah, using a static object is by far the easiest way of doing this with custom non-serialisable objects.

Combine two pandas Data Frames (join on a common column)

In case anyone needs to try and merge two dataframes together on the index (instead of another column), this also works!

T1 and T2 are dataframes that have the same indices

import pandas as pd
T1 = pd.merge(T1, T2, on=T1.index, how='outer')

P.S. I had to use merge because append would fill NaNs in unnecessarily.

ng-if, not equal to?

Try below solution

ng-if="details.Payment[0].Status != '0'"

Use below condition(! prefix with true condition) instead of above

ng-if="!details.Payment[0].Status == '0'"

How to read data from a zip file without having to unzip the entire file

With .Net Framework 4.5 (using ZipArchive):

using (ZipArchive zip = ZipFile.Open(zipfile, ZipArchiveMode.Read))
    foreach (ZipArchiveEntry entry in zip.Entries)
        if(entry.Name == "myfile")
            entry.ExtractToFile("myfile");

Find "myfile" in zipfile and extract it.

Replace whitespaces with tabs in linux

Using Perl:

perl -p -i -e 's/ /\t/g' file.txt

Function not defined javascript

The actual problem is with your

showList function.

There is an extra ')' after 'visible'.

Remove that and it will work fine.

function showList()
{
  if (document.getElementById("favSports").style.visibility == "hidden") 
    {
       // document.getElementById("favSports").style.visibility = "visible");  
       // your code
       document.getElementById("favSports").style.visibility = "visible";
       // corrected code
    }
}

TSQL DATETIME ISO 8601

This

SELECT CONVERT(NVARCHAR(30), GETDATE(), 126)

will produce this

2009-05-01T14:18:12.430

And some more detail on this can be found at MSDN.

bash echo number of lines of file given in a bash variable without the file name

I normally use the 'back tick' feature of bash

export NUM_LINES=`wc -l filename`

Note the 'tick' is the 'back tick' e.g. ` not the normal single quote

In Oracle, is it possible to INSERT or UPDATE a record through a view?

Views in Oracle may be updateable under specific conditions. It can be tricky, and usually is not advisable.

From the Oracle 10g SQL Reference:

Notes on Updatable Views

An updatable view is one you can use to insert, update, or delete base table rows. You can create a view to be inherently updatable, or you can create an INSTEAD OF trigger on any view to make it updatable.

To learn whether and in what ways the columns of an inherently updatable view can be modified, query the USER_UPDATABLE_COLUMNS data dictionary view. The information displayed by this view is meaningful only for inherently updatable views. For a view to be inherently updatable, the following conditions must be met:

  • Each column in the view must map to a column of a single table. For example, if a view column maps to the output of a TABLE clause (an unnested collection), then the view is not inherently updatable.
  • The view must not contain any of the following constructs:
    • A set operator
    • a DISTINCT operator
    • An aggregate or analytic function
    • A GROUP BY, ORDER BY, MODEL, CONNECT BY, or START WITH clause
    • A collection expression in a SELECT list
    • A subquery in a SELECT list
    • A subquery designated WITH READ ONLY
    • Joins, with some exceptions, as documented in Oracle Database Administrator's Guide

In addition, if an inherently updatable view contains pseudocolumns or expressions, then you cannot update base table rows with an UPDATE statement that refers to any of these pseudocolumns or expressions.

If you want a join view to be updatable, then all of the following conditions must be true:

  • The DML statement must affect only one table underlying the join.
  • For an INSERT statement, the view must not be created WITH CHECK OPTION, and all columns into which values are inserted must come from a key-preserved table. A key-preserved table is one for which every primary key or unique key value in the base table is also unique in the join view.
  • For an UPDATE statement, all columns updated must be extracted from a key-preserved table. If the view was created WITH CHECK OPTION, then join columns and columns taken from tables that are referenced more than once in the view must be shielded from UPDATE.
  • For a DELETE statement, if the join results in more than one key-preserved table, then Oracle Database deletes from the first table named in the FROM clause, whether or not the view was created WITH CHECK OPTION.

Vue Js - Loop via v-for X times (in a range)

I had to add parseInt() to tell v-for it was looking at a number.

<li v-for="n in parseInt(count)" :key="n">{{n}}</li>

is it possible to get the MAC address for machine using nmap

if $ ping -c 1 192.168.x.x 

returns

1 packets transmitted, 1 received, 0% packet loss, time ###ms

then you could possibly return the MAC address with arping, but ARP only works on your local network, not across the internet.

$ arping -c 1 192.168.x.x

ARPING 192.168.x.x from 192.168.x.x wlan0
Unicast reply from 192.168.x.x [AA:BB:CC:##:##:##]  192.772ms
Sent 1 probes (1 broadcast(s))
Received 1 response(s)

finally you could use the AA:BB:CC with the colons removed to identify a device from its vendor ID, for example.

$ grep -i '709E29' /usr/local/share/nmap/nmap-mac-prefixes 
709E29 Sony Interactive Entertainment

Set active tab style with AngularJS

I agree with Rob's post about having a custom attribute in the controller. Apparently I don't have enough rep to comment. Here's the jsfiddle that was requested:

sample html

<div ng-controller="MyCtrl">
    <ul>
        <li ng-repeat="link in links" ng-class="{active: $route.current.activeNav == link.type}"> <a href="{{link.uri}}">{{link.name}}</a>

        </li>
    </ul>
</div>

sample app.js

angular.module('MyApp', []).config(['$routeProvider', function ($routeProvider) {
    $routeProvider.when('/a', {
        activeNav: 'a'
    })
        .when('/a/:id', {
        activeNav: 'a'
    })
        .when('/b', {
        activeNav: 'b'
    })
        .when('/c', {
        activeNav: 'c'
    });
}])
    .controller('MyCtrl', function ($scope, $route) {
    $scope.$route = $route;
    $scope.links = [{
        uri: '#/a',
        name: 'A',
        type: 'a'
    }, {
        uri: '#/b',
        name: 'B',
        type: 'b'
    }, {
        uri: '#/c',
        name: 'C',
        type: 'c'
    }, {
        uri: '#/a/detail',
        name: 'A Detail',
        type: 'a'
    }];
});

http://jsfiddle.net/HrdR6/

Why aren't programs written in Assembly more often?

If an average production program has say 100k lines of code, and each line is about 8-12 assembler instructions, that would be 1 million of assembler instructions.

Even if you could write all this by hand at a decent speed (remember, its 8 times more code that you have to write), what happens if you want to change some of the functionality? Understanding something you wrote a few weeks ago out of those 1 million instructions is a nightmare! There's no modules, no classes, no object-oriented design, no frameworks, no nothing. And the amount of similar looking code you have to write for even the simplest things is daunting at best.

Besides, you can't optimize your code nearly as well as a high level language. Where C for example performs an insane number of optimizations because you describe your intent, not only your code, in assembler you only write code, the assembler can't really perform any note-worthy optimizations on your code. What you write is what you get, and trust me, you can't reliably optimize 1 million instructions that you patch and patch as you write it.

How do I read any request header in PHP

This work if you have an Apache server

PHP Code:

$headers = apache_request_headers();

foreach ($headers as $header => $value) {
    echo "$header: $value <br />\n";
}

Result:

Accept: */*
Accept-Language: en-us
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0
Host: www.example.com
Connection: Keep-Alive

How to get Node.JS Express to listen only on localhost?

You are having this problem because you are attempting to console log app.address() before the connection has been made. You just have to be sure to console log after the connection is made, i.e. in a callback or after an event signaling that the connection has been made.

Fortunately, the 'listening' event is emitted by the server after the connection is made so just do this:

var express = require('express');
var http = require('http');

var app = express();
var server = http.createServer(app);

app.get('/', function(req, res) {
    res.send("Hello World!");
});

server.listen(3000, 'localhost');
server.on('listening', function() {
    console.log('Express server started on port %s at %s', server.address().port, server.address().address);
});

This works just fine in nodejs v0.6+ and Express v3.0+.

How to connect to SQL Server database from JavaScript in the browser?

This would be really bad to do because sharing your connection string opens up your website to so many vulnerabilities that you can't simply patch up, you have to use a different method if you want it to be secure. Otherwise you are opening up to a huge audience to take advantage of your site.

Applying Comic Sans Ms font style

The font may exist with different names, and not at all on some systems, so you need to use different variations and fallback to get the closest possible look on all systems:

font-family: "Comic Sans MS", "Comic Sans", cursive;

Be careful what you use this font for, though. Many consider it as ugly and overused, so it should not be use for something that should look professional.

How to add an Access-Control-Allow-Origin header

The accepted answer doesn't work for me unfortunately, since my site CSS files @import the font CSS files, and these are all stored on a Rackspace Cloud Files CDN.

Since the Apache headers are never generated (since my CSS is not on Apache), I had to do several things:

  1. Go to the Cloud Files UI and add a custom header (Access-Control-Allow-Origin with value *) for each font-awesome file
  2. Change the Content-Type of the woff and ttf files to font/woff and font/ttf respectively

See if you can get away with just #1, since the second requires a bit of command line work.

To add the custom header in #1:

  • view the cloud files container for the file
  • scroll down to the file
  • click the cog icon
  • click Edit Headers
  • select Access-Control-Allow-Origin
  • add the single character '*' (without the quotes)
  • hit enter
  • repeat for the other files

If you need to continue and do #2, then you'll need a command line with CURL

curl -D - --header "X-Auth-Key: your-auth-key-from-rackspace-cloud-control-panel" --header "X-Auth-User: your-cloud-username" https://auth.api.rackspacecloud.com/v1.0

From the results returned, extract the values for X-Auth-Token and X-Storage-Url

curl -X POST \
  -H "Content-Type: font/woff" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.woff

curl -X POST \
  -H "Content-Type: font/ttf" \
  --header "X-Auth-Token: returned-x-auth-token" returned-x-storage-url/name-of-your-container/fonts/fontawesome-webfont.ttf

Of course, this process only works if you're using the Rackspace CDN. Other CDNs may offer similar facilities to edit object headers and change content types, so maybe you'll get lucky (and post some extra info here).

Explaining Apache ZooKeeper

In a nutshell, ZooKeeper helps you build distributed applications.

How it works

You may describe ZooKeeper as a replicated synchronization service with eventual consistency. It is robust, since the persisted data is distributed between multiple nodes (this set of nodes is called an "ensemble") and one client connects to any of them (i.e., a specific "server"), migrating if one node fails; as long as a strict majority of nodes are working, the ensemble of ZooKeeper nodes is alive. In particular, a master node is dynamically chosen by consensus within the ensemble; if the master node fails, the role of master migrates to another node.

How writes are handled

The master is the authority for writes: in this way writes can be guaranteed to be persisted in-order, i.e., writes are linear. Each time a client writes to the ensemble, a majority of nodes persist the information: these nodes include the server for the client, and obviously the master. This means that each write makes the server up-to-date with the master. It also means, however, that you cannot have concurrent writes.

The guarantee of linear writes is the reason for the fact that ZooKeeper does not perform well for write-dominant workloads. In particular, it should not be used for interchange of large data, such as media. As long as your communication involves shared data, ZooKeeper helps you. When data could be written concurrently, ZooKeeper actually gets in the way, because it imposes a strict ordering of operations even if not strictly necessary from the perspective of the writers. Its ideal use is for coordination, where messages are exchanged between the clients.

How reads are handled

This is where ZooKeeper excels: reads are concurrent since they are served by the specific server that the client connects to. However, this is also the reason for the eventual consistency: the "view" of a client may be outdated, since the master updates the corresponding server with a bounded but undefined delay.

In detail

The replicated database of ZooKeeper comprises a tree of znodes, which are entities roughly representing file system nodes (think of them as directories). Each znode may be enriched by a byte array, which stores data. Also, each znode may have other znodes under it, practically forming an internal directory system.

Sequential znodes

Interestingly, the name of a znode can be sequential, meaning that the name the client provides when creating the znode is only a prefix: the full name is also given by a sequential number chosen by the ensemble. This is useful, for example, for synchronization purposes: if multiple clients want to get a lock on a resource, they can each concurrently create a sequential znode on a location: whoever gets the lowest number is entitled to the lock.

Ephemeral znodes

Also, a znode may be ephemeral: this means that it is destroyed as soon as the client that created it disconnects. This is mainly useful in order to know when a client fails, which may be relevant when the client itself has responsibilities that should be taken by a new client. Taking the example of the lock, as soon as the client having the lock disconnects, the other clients can check whether they are entitled to the lock.

Watches

The example related to client disconnection may be problematic if we needed to periodically poll the state of znodes. Fortunately, ZooKeeper offers an event system where a watch can be set on a znode. These watches may be set to trigger an event if the znode is specifically changed or removed or new children are created under it. This is clearly useful in combination with the sequential and ephemeral options for znodes.

Where and how to use it

A canonical example of Zookeeper usage is distributed-memory computation, where some data is shared between client nodes and must be accessed/updated in a very careful way to account for synchronization.

ZooKeeper offers the library to construct your synchronization primitives, while the ability to run a distributed server avoids the single-point-of-failure issue you have when using a centralized (broker-like) message repository.

ZooKeeper is feature-light, meaning that mechanisms such as leader election, locks, barriers, etc. are not already present, but can be written above the ZooKeeper primitives. If the C/Java API is too unwieldy for your purposes, you should rely on libraries built on ZooKeeper such as cages and especially curator.

Where to read more

Official documentation apart, which is pretty good, I suggest to read Chapter 14 of Hadoop: The Definitive Guide which has ~35 pages explaining essentially what ZooKeeper does, followed by an example of a configuration service.

open the file upload dialogue box onclick the image

<input type="file" id="imgupload" style="display:none"/>
<label for='imgupload'> <button id="OpenImgUpload">Image Upload</button></label>

On click of for= attribute will automatically focus on "file input" and upload dialog box will open

PHP convert string to hex and hex to string

Using @bill-shirley answer with a little addition

function str_to_hex($string) {
$hexstr = unpack('H*', $string);
return array_shift($hexstr);
}
function hex_to_str($string) {
return hex2bin("$string");
}

Usage:

  $str = "Go placidly amidst the noise";
  $hexstr = str_to_hex($str);// 476f20706c616369646c7920616d6964737420746865206e6f697365
  $strstr = hex_to_str($str);// Go placidly amidst the noise

Can I have multiple background images using CSS?

CSS3 allows this sort of thing and it looks like this:

body {
    background-image: url(images/bgtop.png), url(images/bg.png);
    background-repeat: repeat-x, repeat;
}

The current versions of all the major browsers now support it, however if you need to support IE8 or below, then the best way you can work around it is to have extra divs:

<body>
    <div id="bgTopDiv">
        content here
    </div>
</body>
body{
    background-image: url(images/bg.png);
}
#bgTopDiv{
    background-image: url(images/bgTop.png);
    background-repeat: repeat-x;
}

minimum double value in C/C++

In C, use

#include <float.h>

const double lowest_double = -DBL_MAX;

In C++pre-11, use

#include <limits>

const double lowest_double = -std::numeric_limits<double>::max();

In C++11 and onwards, use

#include <limits>

constexpr double lowest_double = std::numeric_limits<double>::lowest();

How do I retrieve a textbox value using JQuery?

You need to use the val() function to get the textbox value. text does not exist as a property only as a function and even then its not the correct function to use in this situation.

var from = $("input#fromAddress").val()

val() is the standard function for getting the value of an input.

Plotting power spectrum in python

Numpy has a convenience function, np.fft.fftfreq to compute the frequencies associated with FFT components:

from __future__ import division
import numpy as np
import matplotlib.pyplot as plt

data = np.random.rand(301) - 0.5
ps = np.abs(np.fft.fft(data))**2

time_step = 1 / 30
freqs = np.fft.fftfreq(data.size, time_step)
idx = np.argsort(freqs)

plt.plot(freqs[idx], ps[idx])

enter image description here

Note that the largest frequency you see in your case is not 30 Hz, but

In [7]: max(freqs)
Out[7]: 14.950166112956811

You never see the sampling frequency in a power spectrum. If you had had an even number of samples, then you would have reached the Nyquist frequency, 15 Hz in your case (although numpy would have calculated it as -15).

What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?

What Is It?

This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than or equal to the number of elements it contains.

When It Is Thrown

Given an array declared as:

byte[] array = new byte[4];

You can access this array from 0 to 3, values outside this range will cause IndexOutOfRangeException to be thrown. Remember this when you create and access an array.

Array Length
In C#, usually, arrays are 0-based. It means that first element has index 0 and last element has index Length - 1 (where Length is total number of items in the array) so this code doesn't work:

array[array.Length] = 0;

Moreover please note that if you have a multidimensional array then you can't use Array.Length for both dimension, you have to use Array.GetLength():

int[,] data = new int[10, 5];
for (int i=0; i < data.GetLength(0); ++i) {
    for (int j=0; j < data.GetLength(1); ++j) {
        data[i, j] = 1;
    }
}

Upper Bound Is Not Inclusive
In the following example we create a raw bidimensional array of Color. Each item represents a pixel, indices are from (0, 0) to (imageWidth - 1, imageHeight - 1).

Color[,] pixels = new Color[imageWidth, imageHeight];
for (int x = 0; x <= imageWidth; ++x) {
    for (int y = 0; y <= imageHeight; ++y) {
        pixels[x, y] = backgroundColor;
    }
}

This code will then fail because array is 0-based and last (bottom-right) pixel in the image is pixels[imageWidth - 1, imageHeight - 1]:

pixels[imageWidth, imageHeight] = Color.Black;

In another scenario you may get ArgumentOutOfRangeException for this code (for example if you're using GetPixel method on a Bitmap class).

Arrays Do Not Grow
An array is fast. Very fast in linear search compared to every other collection. It is because items are contiguous in memory so memory address can be calculated (and increment is just an addition). No need to follow a node list, simple math! You pay this with a limitation: they can't grow, if you need more elements you need to reallocate that array (this may take a relatively long time if old items must be copied to a new block). You resize them with Array.Resize<T>(), this example adds a new entry to an existing array:

Array.Resize(ref array, array.Length + 1);

Don't forget that valid indices are from 0 to Length - 1. If you simply try to assign an item at Length you'll get IndexOutOfRangeException (this behavior may confuse you if you think they may increase with a syntax similar to Insert method of other collections).

Special Arrays With Custom Lower Bound
First item in arrays has always index 0. This is not always true because you can create an array with a custom lower bound:

var array = Array.CreateInstance(typeof(byte), new int[] { 4 }, new int[] { 1 });

In that example, array indices are valid from 1 to 4. Of course, upper bound cannot be changed.

Wrong Arguments
If you access an array using unvalidated arguments (from user input or from function user) you may get this error:

private static string[] RomanNumbers =
    new string[] { "I", "II", "III", "IV", "V" };

public static string Romanize(int number)
{
    return RomanNumbers[number];
}

Unexpected Results
This exception may be thrown for another reason too: by convention, many search functions will return -1 (nullables has been introduced with .NET 2.0 and anyway it's also a well-known convention in use from many years) if they didn't find anything. Let's imagine you have an array of objects comparable with a string. You may think to write this code:

// Items comparable with a string
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
    myArray[Array.IndexOf(myArray, "Debug")]);

// Arbitrary objects
Console.WriteLine("First item equals to 'Debug' is '{0}'.",
    myArray[Array.FindIndex(myArray, x => x.Type == "Debug")]);

This will fail if no items in myArray will satisfy search condition because Array.IndexOf() will return -1 and then array access will throw.

Next example is a naive example to calculate occurrences of a given set of numbers (knowing maximum number and returning an array where item at index 0 represents number 0, items at index 1 represents number 1 and so on):

static int[] CountOccurences(int maximum, IEnumerable<int> numbers) {
    int[] result = new int[maximum + 1]; // Includes 0

    foreach (int number in numbers)
        ++result[number];

    return result;
}

Of course, it's a pretty terrible implementation but what I want to show is that it'll fail for negative numbers and numbers above maximum.

How it applies to List<T>?

Same cases as array - range of valid indexes - 0 (List's indexes always start with 0) to list.Count - accessing elements outside of this range will cause the exception.

Note that List<T> throws ArgumentOutOfRangeException for the same cases where arrays use IndexOutOfRangeException.

Unlike arrays, List<T> starts empty - so trying to access items of just created list lead to this exception.

var list = new List<int>();

Common case is to populate list with indexing (similar to Dictionary<int, T>) will cause exception:

list[0] = 42; // exception
list.Add(42); // correct

IDataReader and Columns
Imagine you're trying to read data from a database with this code:

using (var connection = CreateConnection()) {
    using (var command = connection.CreateCommand()) {
        command.CommandText = "SELECT MyColumn1, MyColumn2 FROM MyTable";

        using (var reader = command.ExecuteReader()) {
            while (reader.Read()) {
                ProcessData(reader.GetString(2)); // Throws!
            }
        }
    }
}

GetString() will throw IndexOutOfRangeException because you're dataset has only two columns but you're trying to get a value from 3rd one (indices are always 0-based).

Please note that this behavior is shared with most IDataReader implementations (SqlDataReader, OleDbDataReader and so on).

You can get the same exception also if you use the IDataReader overload of the indexer operator that takes a column name and pass an invalid column name.
Suppose for example that you have retrieved a column named Column1 but then you try to retrieve the value of that field with

 var data = dr["Colum1"];  // Missing the n in Column1.

This happens because the indexer operator is implemented trying to retrieve the index of a Colum1 field that doesn't exist. The GetOrdinal method will throw this exception when its internal helper code returns a -1 as the index of "Colum1".

Others
There is another (documented) case when this exception is thrown: if, in DataView, data column name being supplied to the DataViewSort property is not valid.

How to Avoid

In this example, let me assume, for simplicity, that arrays are always monodimensional and 0-based. If you want to be strict (or you're developing a library), you may need to replace 0 with GetLowerBound(0) and .Length with GetUpperBound(0) (of course if you have parameters of type System.Array, it doesn't apply for T[]). Please note that in this case, upper bound is inclusive then this code:

for (int i=0; i < array.Length; ++i) { }

Should be rewritten like this:

for (int i=array.GetLowerBound(0); i <= array.GetUpperBound(0); ++i) { }

Please note that this is not allowed (it'll throw InvalidCastException), that's why if your parameters are T[] you're safe about custom lower bound arrays:

void foo<T>(T[] array) { }

void test() {
    // This will throw InvalidCastException, cannot convert Int32[] to Int32[*]
    foo((int)Array.CreateInstance(typeof(int), new int[] { 1 }, new int[] { 1 }));
}

Validate Parameters
If index comes from a parameter you should always validate them (throwing appropriate ArgumentException or ArgumentOutOfRangeException). In the next example, wrong parameters may cause IndexOutOfRangeException, users of this function may expect this because they're passing an array but it's not always so obvious. I'd suggest to always validate parameters for public functions:

static void SetRange<T>(T[] array, int from, int length, Func<i, T> function)
{
    if (from < 0 || from>= array.Length)
        throw new ArgumentOutOfRangeException("from");

    if (length < 0)
        throw new ArgumentOutOfRangeException("length");

    if (from + length > array.Length)
        throw new ArgumentException("...");

    for (int i=from; i < from + length; ++i)
        array[i] = function(i);
}

If function is private you may simply replace if logic with Debug.Assert():

Debug.Assert(from >= 0 && from < array.Length);

Check Object State
Array index may not come directly from a parameter. It may be part of object state. In general is always a good practice to validate object state (by itself and with function parameters, if needed). You can use Debug.Assert(), throw a proper exception (more descriptive about the problem) or handle that like in this example:

class Table {
    public int SelectedIndex { get; set; }
    public Row[] Rows { get; set; }

    public Row SelectedRow {
        get {
            if (Rows == null)
                throw new InvalidOperationException("...");

            // No or wrong selection, here we just return null for
            // this case (it may be the reason we use this property
            // instead of direct access)
            if (SelectedIndex < 0 || SelectedIndex >= Rows.Length)
                return null;

            return Rows[SelectedIndex];
        }
}

Validate Return Values
In one of previous examples we directly used Array.IndexOf() return value. If we know it may fail then it's better to handle that case:

int index = myArray[Array.IndexOf(myArray, "Debug");
if (index != -1) { } else { }

How to Debug

In my opinion, most of the questions, here on SO, about this error can be simply avoided. The time you spend to write a proper question (with a small working example and a small explanation) could easily much more than the time you'll need to debug your code. First of all, read this Eric Lippert's blog post about debugging of small programs, I won't repeat his words here but it's absolutely a must read.

You have source code, you have exception message with a stack trace. Go there, pick right line number and you'll see:

array[index] = newValue;

You found your error, check how index increases. Is it right? Check how array is allocated, is coherent with how index increases? Is it right according to your specifications? If you answer yes to all these questions, then you'll find good help here on StackOverflow but please first check for that by yourself. You'll save your own time!

A good start point is to always use assertions and to validate inputs. You may even want to use code contracts. When something went wrong and you can't figure out what happens with a quick look at your code then you have to resort to an old friend: debugger. Just run your application in debug inside Visual Studio (or your favorite IDE), you'll see exactly which line throws this exception, which array is involved and which index you're trying to use. Really, 99% of the times you'll solve it by yourself in a few minutes.

If this happens in production then you'd better to add assertions in incriminated code, probably we won't see in your code what you can't see by yourself (but you can always bet).

The VB.NET side of the story

Everything that we have said in the C# answer is valid for VB.NET with the obvious syntax differences but there is an important point to consider when you deal with VB.NET arrays.

In VB.NET, arrays are declared setting the maximum valid index value for the array. It is not the count of the elements that we want to store in the array.

' declares an array with space for 5 integer 
' 4 is the maximum valid index starting from 0 to 4
Dim myArray(4) as Integer

So this loop will fill the array with 5 integers without causing any IndexOutOfRangeException

For i As Integer = 0 To 4
    myArray(i) = i
Next

The VB.NET rule

This exception means that you're trying to access a collection item by index, using an invalid index. An index is invalid when it's lower than the collection's lower bound or greater than equal to the number of elements it contains. the maximum allowed index defined in the array declaration

Checking on a thread / remove from list

you need to call thread.isAlive()to find out if the thread is still running

Calculate a Running Total in SQL Server

BEGIN TRAN
CREATE TABLE #Table (_Id INT IDENTITY(1,1) ,id INT ,    somedate VARCHAR(100) , somevalue INT)


INSERT INTO #Table ( id  ,    somedate  , somevalue  )
SELECT 45 , '01/Jan/09', 3 UNION ALL
SELECT 23 , '08/Jan/09', 5 UNION ALL
SELECT 12 , '02/Feb/09', 0 UNION ALL
SELECT 77 , '14/Feb/09', 7 UNION ALL
SELECT 39 , '20/Feb/09', 34 UNION ALL
SELECT 33 , '02/Mar/09', 6 

;WITH CTE ( _Id, id  ,  _somedate  , _somevalue ,_totvalue ) AS
(

 SELECT _Id , id  ,    somedate  , somevalue ,somevalue
 FROM #Table WHERE _id = 1
 UNION ALL
 SELECT #Table._Id , #Table.id  , somedate  , somevalue , somevalue + _totvalue
 FROM #Table,CTE 
 WHERE #Table._id > 1 AND CTE._Id = ( #Table._id-1 )
)

SELECT * FROM CTE

ROLLBACK TRAN

How to check SQL Server version

Following are possible ways to see the version:

Method 1: Connect to the instance of SQL Server, and then run the following query:

Select @@version

An example of the output of this query is as follows:

Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)   Mar 29 2009 
10:11:52   Copyright (c) 1988-2008 Microsoft Corporation  Express 
Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

Method 2: Connect to the server by using Object Explorer in SQL Server Management Studio. After Object Explorer is connected, it will show the version information in parentheses, together with the user name that is used to connect to the specific instance of SQL Server.

Method 3: Look at the first few lines of the Errorlog file for that instance. By default, the error log is located at Program Files\Microsoft SQL Server\MSSQL.n\MSSQL\LOG\ERRORLOG and ERRORLOG.n files. The entries may resemble the following:

2011-03-27 22:31:33.50 Server      Microsoft SQL Server 2008 (SP1) - 10.0.2531.0 (X64)                 Mar 29 2009 10:11:52                 Copyright (c) 1988-2008 Microsoft Corporation                Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7600: )

As you can see, this entry gives all the necessary information about the product, such as version, product level, 64-bit versus 32-bit, the edition of SQL Server, and the OS version on which SQL Server is running.

Method 4: Connect to the instance of SQL Server, and then run the following query:

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

Note This query works with any instance of SQL Server 2000 or of a later version

Java: get greatest common divisor

I used this method that I created when I was 14 years old.

    public static int gcd (int a, int b) {
        int s = 1;
        int ia = Math.abs(a);//<-- turns to absolute value
        int ib = Math.abs(b);
        if (a == b) {
            s = a;
        }else {
            while (ib != ia) {
                if (ib > ia) {
                    s = ib - ia;
                    ib = s;
                }else { 
                    s = ia - ib;
                    ia = s;
                }
            }
        }
        return s;
    }

Angularjs loading screen on ajax request

Include this in your "app.config":

 $httpProvider.interceptors.push('myHttpInterceptor');

And add this code:

app.factory('myHttpInterceptor', function ($q, $window,$rootScope) {
    $rootScope.ActiveAjaxConectionsWithouthNotifications = 0;
    var checker = function(parameters,status){
            //YOU CAN USE parameters.url TO IGNORE SOME URL
            if(status == "request"){
                $rootScope.ActiveAjaxConectionsWithouthNotifications+=1;
                $('#loading_view').show();
            }
            if(status == "response"){
                $rootScope.ActiveAjaxConectionsWithouthNotifications-=1;

            }
            if($rootScope.ActiveAjaxConectionsWithouthNotifications<=0){
                $rootScope.ActiveAjaxConectionsWithouthNotifications=0;
                $('#loading_view').hide();

            }


    };
return {
    'request': function(config) {
        checker(config,"request");
        return config;
    },
   'requestError': function(rejection) {
       checker(rejection.config,"request");
      return $q.reject(rejection);
    },
    'response': function(response) {
         checker(response.config,"response");
      return response;
    },
   'responseError': function(rejection) {
        checker(rejection.config,"response");
      return $q.reject(rejection);
    }
  };
});

How to check python anaconda version installed on Windows 10 PC?

If you want to check the python version in a particular cond environment you can also use conda list python

What is the difference between And and AndAlso in VB.NET?

Just for all those people who say side effects are evil: a place where having two side effects in one condition is good would be reading two file objects in tandem.

While File1.Seek_Next_Row() And File2.Seek_Next_Row()
    Str1 = File1.GetRow()
    Str2 = File2.GetRow()
End While

Using the And ensures that a row is consumed every time the condition is checked. Whereas AndAlso might read the last line of File1 and leave File2 without a consumed line.

Of course the code above wouldn't work, but I use side effects like this all the time and wouldn't consider it "bad" or "evil" code as some would lead you to believe. It's easy to read and efficient.

Sending and receiving data over a network using TcpClient

I've developed a dotnet library that might come in useful. I have fixed the problem of never getting all of the data if it exceeds the buffer, which many posts have discounted. Still some problems with the solution but works descently well https://github.com/NicholasLKSharp/DotNet-TCP-Communication

How to change btn color in Bootstrap

Remove the button color class like "btn-success" and put a custom class like "btn-custom" and write css for that class. That simply works for me.

HTML :

<button class="btn btn-block login " type="submit">Sign In</button>

CSS:

 .login  {
    background-color: #0057fc;
    color: white;   
}

How to check if IsNumeric

You could write an extension method:

public static class Extension
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

How to have an automatic timestamp in SQLite?

Just declare a default value for a field:

CREATE TABLE MyTable(
    ID INTEGER PRIMARY KEY,
    Name TEXT,
    Other STUFF,
    Timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);

However, if your INSERT command explicitly sets this field to NULL, it will be set to NULL.

How do I set the default value for an optional argument in Javascript?

If str is null, undefined or 0, this code will set it to "hai"

function(nodeBox, str) {
  str = str || "hai";
.
.
.

If you also need to pass 0, you can use:

function(nodeBox, str) {
  if (typeof str === "undefined" || str === null) { 
    str = "hai"; 
  }
.
.
.

Is the size of C "int" 2 bytes or 4 bytes?

The only guarantees are that char must be at least 8 bits wide, short and int must be at least 16 bits wide, and long must be at least 32 bits wide, and that sizeof (char) <= sizeof (short) <= sizeof (int) <= sizeof (long) (same is true for the unsigned versions of those types).

int may be anywhere from 16 to 64 bits wide depending on the platform.

Grep characters before and after match?

With gawk , you can use match function:

    x="hey there how are you"
    echo "$x" |awk --re-interval '{match($0,/(.{4})how(.{4})/,a);print a[1],a[2]}'
    ere   are

If you are ok with perl, more flexible solution : Following will print three characters before the pattern followed by actual pattern and then 5 character after the pattern.

echo hey there how are you |perl -lne 'print "$1$2$3" if /(.{3})(there)(.{5})/'
ey there how

This can also be applied to words instead of just characters.Following will print one word before the actual matching string.

echo hey there how are you |perl -lne 'print $1 if /(\w+) there/'
hey

Following will print one word after the pattern:

echo hey there how are you |perl -lne 'print $2 if /(\w+) there (\w+)/'
how

Following will print one word before the pattern , then the actual word and then one word after the pattern:

echo hey there how are you |perl -lne 'print "$1$2$3" if /(\w+)( there )(\w+)/'
hey there how

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

It took us a day to resolve this problem. The solution is forcing your webservice to use version 11.0.0 in your web.config file.

<runtime>      
  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
  </dependentAssembly>
</assemblyBinding>

Writing an input integer into a cell

You can use the Range object in VBA to set the value of a named cell, just like any other cell.

Range("C1").Value = Inputbox("Which job number would you like to add to the list?)

Where "C1" is the name of the cell you want to update.

My Excel VBA is a little bit old and crusty, so there may be a better way to do this in newer versions of Excel.

How to make the web page height to fit screen height

A quick, non-elegant but working standalone solution with inline CSS and no jQuery requirements. AFAIK it works from IE9 too.

<body style="overflow:hidden; margin:0">
    <form id="form1" runat="server">
        <div id="main" style="background-color:red">
            <div id="content">

            </div>
            <div id="footer">

            </div>
        </div>
    </form>
    <script language="javascript">
        function autoResizeDiv()
        {
            document.getElementById('main').style.height = window.innerHeight +'px';
        }
        window.onresize = autoResizeDiv;
        autoResizeDiv();
    </script>
</body>

how to change directory using Windows command line

cd /driveName driveName:\pathNamw

Is the Javascript date object always one day off?

You can convert this date to UTC date by

new Date(Date.UTC(Year, Month, Day, Hour, Minute, Second))

And it is always recommended to use UTC (universal time zone) date instead of Date with local time, as by default dates are stored in Database with UTC. So, it is good practice to use and interpret dates in UTC format throughout entire project. For example,

Date.getUTCYear(), getUTCMonth(), getUTCDay(), getUTCHours()

So, using UTC dates solves all the problem related to timezone issues.

Java null check why use == instead of .equals()

Because equal is a function derived from Object class, this function compares items of the class. if you use it with null it will return false cause cause class content is not null. In addition == compares reference to an object.

Android Studio: /dev/kvm device permission denied

Here is a simple solution

open the terminal and run the following commands

sudo groupadd -r kvm

sudo gedit /lib/udev/rules.d/60-qemu-system-common.rules

Add the following line to the opened file and save it

KERNEL=="kvm", GROUP="kvm", MODE="0660"

Finally run:

sudo usermod -a -G kvm <your_username>

Reboot your PC and Done!

How to create the pom.xml for a Java project with Eclipse

You should use the new available m2e plugin for Maven integration in Eclipse. With help of that plugin, you should create a new project and move your sources into that project. These are the steps:

  • Check if m2e (or the former m2eclipse) are installed in your Eclipse distribution. If not, install it.
  • Open the "New Project Wizard": File > New > Project...
  • Open Maven and select Maven Project and click Next.
  • Select Create a simple project (to skip the archetype selection).
  • Add the necessary information: Group Id, Artifact Id, Packaging == jar, and a Name.
  • Finish the Wizard.
  • Your new Maven project is now generated, and you are able to move your sources and test packages to the relevant location in your workspace.
  • After that, you can build your project (inside Eclipse) by selecting your project, then calling from the context menu Run as > Maven install.

How to get std::vector pointer to the raw data?

Take a pointer to the first element instead:

process_data (&something [0]);

WPF Binding StringFormat Short Date String

Try this:

<TextBlock Text="{Binding PropertyPath, StringFormat=d}" />

which is culture sensitive and requires .NET 3.5 SP1 or above.

NOTE: This is case sensitive. "d" is the short date format specifier while "D" is the long date format specifier.

There's a full list of string format on the MSDN page on Standard Date and Time Format Strings and a fuller explanation of all the options on this MSDN blog post

However, there is one gotcha with this - it always outputs the date in US format unless you set the culture to the correct value yourself.

If you do not set this property, the binding engine uses the Language property of the binding target object. In XAML this defaults to "en-US" or inherits the value from the root element (or any element) of the page, if one has been explicitly set.

Source

One way to do this is in the code behind (assuming you've set the culture of the thread to the correct value):

this.Language = XmlLanguage.GetLanguage(Thread.CurrentThread.CurrentCulture.Name);

The other way is to set the converter culture in the binding:

<TextBlock Text="{Binding PropertyPath, StringFormat=d, ConverterCulture=en-GB}" />

Though this doesn't allow you to localise the output.

Regular Expressions: Search in list

You can create an iterator in Python 3.x or a list in Python 2.x by using:

filter(r.match, list)

To convert the Python 3.x iterator to a list, simply cast it; list(filter(..)).

How to inject JPA EntityManager using spring

Is it possible to have spring to inject the JPA entityManager object into my DAO class whitout extending JpaDaoSupport? if yes, does spring manage the transaction in this case?

This is documented black on white in 12.6.3. Implementing DAOs based on plain JPA:

It is possible to write code against the plain JPA without using any Spring dependencies, using an injected EntityManagerFactory or EntityManager. Note that Spring can understand @PersistenceUnit and @PersistenceContext annotations both at field and method level if a PersistenceAnnotationBeanPostProcessor is enabled. A corresponding DAO implementation might look like this (...)

And regarding transaction management, have a look at 12.7. Transaction Management:

Spring JPA allows a configured JpaTransactionManager to expose a JPA transaction to JDBC access code that accesses the same JDBC DataSource, provided that the registered JpaDialect supports retrieval of the underlying JDBC Connection. Out of the box, Spring provides dialects for the Toplink, Hibernate and OpenJPA JPA implementations. See the next section for details on the JpaDialect mechanism.

MVC: How to Return a String as JSON

Yeah that's it without no further issues, to avoid raw string json this is it.

    public ActionResult GetJson()
    {
        var json = System.IO.File.ReadAllText(
            Server.MapPath(@"~/App_Data/content.json"));

        return new ContentResult
        {
            Content = json,
            ContentType = "application/json",
            ContentEncoding = Encoding.UTF8
        };
    } 

NOTE: please note that method return type of JsonResult is not working for me, since JsonResult and ContentResult both inherit ActionResult but there is no relationship between them.

jQuery Scroll to Div

I ran into the same. Saw an example using this: https://github.com/flesler/jquery.scrollTo

I use it as follows:

$('#arrow_back').click(function () {
    $.scrollTo('#features_1', 1000, { easing: 'easeInOutExpo', offset: 0, 'axis': 'y' }); 
});

Clean solution. Works for me!

How to easily duplicate a Windows Form in Visual Studio?

(replicated this answer from my other post in case someone is looking for this solution here)

Using VS2013 just tested this and it appears reliable and consistent. This is similar to some comments above but adds another method that's quicker.

(1st) In Windows File Explorer highlight and copy all 3 Form files (.vb or .cs, .designer, .resx)

(2nd) This can be accomplished 2 ways:

(2a-1) In File Explorer paste the 3 files into the project folder with your other forms

(2a-2) In VS Solution Explorer, turn 'Show All Files' on, Right Click on the pasted form & 'Include in Project'. It should work without other changes.

Or, I think better:

(2b-1) In VS, click into Solution Explorer and paste w/Control-C. (For some reason the right-click context menu in Solution Explorer may not show a paste option, but it works from the keyboard.) This method adds the form to the project directly without having to 'Include in Project' as above. With this method you can add as many forms at a time as you like (all 3 files for each) in a single step.

How to iterate through a list of dictionaries in Jinja template?

Just a side note for similar problem (If we don't want to loop through):

How to lookup a dictionary using a variable key within Jinja template?

Here is an example:

{% set key = target_db.Schema.upper()+"__"+target_db.TableName.upper() %}
{{ dict_containing_df.get(key).to_html() | safe }}

It might be obvious. But we don't need curly braces within curly braces. Straight python syntax works. (I am posting because I was confusing to me...)

Alternatively, you can simply do

{{dict[target_db.Schema.upper()+"__"+target_db.TableName.upper()]).to_html() | safe }}

But it will spit an error when no key is found. So better to use get in Jinja.

Take the content of a list and append it to another list

That seems fairly reasonable for what you're trying to do.

A slightly shorter version which leans on Python to do more of the heavy lifting might be:

for logs in mydir:

    for line in mylog:
        #...if the conditions are met
        list1.append(line)

    if any(True for line in list1 if "string" in line):
        list2.extend(list1)
    del list1

    ....

The (True for line in list1 if "string" in line) iterates over list and emits True whenever a match is found. any() uses short-circuit evaluation to return True as soon as the first True element is found. list2.extend() appends the contents of list1 to the end.

ExpressionChangedAfterItHasBeenCheckedError Explained

Follow the below steps:

1. Use 'ChangeDetectorRef' by importing it from @angular/core as follows:

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

2. Implement it in constructor() as follows:

constructor(   private cdRef : ChangeDetectorRef  ) {}

3. Add the following method to your function which you are calling on an event like click of button. So it look like this:

functionName() {   
    yourCode;  
    //add this line to get rid of the error  
    this.cdRef.detectChanges();     
}

Calling stored procedure from another stored procedure SQL Server

First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table

SET IDENTITY_INSERT table2 ON;

before the insert.

So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID

EXEC test2 'productName', 'productDescription'
SET @newID = SCOPE_IDENTIY()

or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID

T-SQL CASE Clause: How to specify WHEN NULL

Jason caught an error, so this works...

Can anyone confirm the other platform versions?
SQL Server:

SELECT
CASE LEN(ISNULL(last_name,'')) 
WHEN 0 THEN '' 
ELSE ' ' + last_name
END AS newlastName

MySQL:

SELECT
CASE LENGTH(IFNULL(last_name,'')) 
WHEN 0 THEN '' 
ELSE ' ' + last_name
END AS newlastName

Oracle:

SELECT
CASE LENGTH(NVL(last_name,'')) 
WHEN 0 THEN '' 
ELSE ' ' + last_name
END AS newlastName

How can I pass selected row to commandLink inside dataTable or ui:repeat?

Thanks to this site by Mkyong, the only solution that actually worked for us to pass a parameter was this

<h:commandLink action="#{user.editAction}">
    <f:param name="myId" value="#{param.id}" />
</h:commandLink>

with

public String editAction() {

  Map<String,String> params = 
            FacesContext.getExternalContext().getRequestParameterMap();
  String idString = params.get("myId");
  long id = Long.parseLong(idString);
  ...
}

Technically, that you cannot pass to the method itself directly, but to the JSF request parameter map.

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

Error 6 (net::ERR_FILE_NOT_FOUND): The files c or directory could not be found

I had the same problem: the error was File not found, while opening HTML files in chrome, but I resolved it as follows:

BEFORE:

1) I saved a html file abc.html in a folder name C#.

2) When I was opening the abc.html in Google Chrome, it was showing error as "file not found". But it was working fine on Firefox and Internet Explorer.

AFTER:

3) What I did then is, I simply changed the folder name C# to csharp without space and re opened it in Chrome. It worked.

4) The moral is: Make sure you don't give any space in a folder name as some browsers don't support it.

How do I create HTML table using jQuery dynamically?

You may use two options:

  1. createElement
  2. InnerHTML

Create Element is the fastest way (check here.):

$(document.createElement('table'));

InnerHTML is another popular approach:

$("#foo").append("<div>hello world</div>"); // Check similar for table too.

Check a real example on How to create a new table with rows using jQuery and wrap it inside div.

There may be other approaches as well. Please use this as a starting point and not as a copy-paste solution.

Edit:

Check Dynamic creation of table with DOM

Edit 2:

IMHO, you are mixing object and inner HTML. Let's try with a pure inner html approach:

function createProviderFormFields(id, labelText, tooltip, regex) {
    var tr = '<tr>' ;
         // create a new textInputBox  
           var textInputBox = '<input type="text" id="' + id + '" name="' + id + '" title="' + tooltip + '" />';  
        // create a new Label Text
            tr += '<td>' + labelText  + '</td>';
            tr += '<td>' + textInputBox + '</td>';  
    tr +='</tr>';
    return tr;
}

How to deploy a React App on Apache web server

  1. Go to your project root directory cd example /home/ubuntu/react-js
  2. Build your project first npm run build
  3. check your build directory gracefully all the files will be available in the build folder.

    asset-manifest.json

    favicon.ico

    manifest.json

    robots.txt

    static assets

    index.html

    precache-manifest.ddafca92870314adfea99542e1331500.js service-worker.js

4.copy the build folder to your apache server i.e /var/www/html

sudo cp -rf build /var/www/html
  1. go to sites-available directory

    cd /etc/apache2/sites-available/

  2. open 000-default.conf file

    sudo vi 000-default.conf and rechange the DocumentRoot path

    enter image description here

  3. Now goto apache conf.

    cd /etc/aapche2

    sudo vi apache2.conf

    add the given snippet

_x000D_
_x000D_
<Directory /var/www/html>_x000D_
_x000D_
            Options Indexes FollowSymLinks_x000D_
_x000D_
            AllowOverride All_x000D_
_x000D_
            Require all granted_x000D_
_x000D_
    </Directory>
_x000D_
_x000D_
_x000D_

  1. make a file inside /var/www/html/build

    sudo vi .htaccess

_x000D_
_x000D_
Options -MultiViews_x000D_
    _x000D_
RewriteEngine On_x000D_
    _x000D_
RewriteCond %{REQUEST_FILENAME} !-f_x000D_
_x000D_
RewriteRule ^ index.html [QSA,L]
_x000D_
_x000D_
_x000D_

9.sudo a2enmod rewrite

10.sudo systemctl restart apache2

  1. restart apache server

    sudo service apache2 restart

    thanks, enjoy your day

Converting newline formatting from Mac to Windows

  1. Install dos2unix with homebrew
  2. Run find ./ -type f -exec dos2unix {} \; to recursively convert all line-endings within current folder