Programs & Examples On #Window handles

Winforms issue - Error creating window handle

This problem is almost always related to the GDI Object count, User Object count or Handle count and usually not because of an out-of-memory condition on your machine.

When I am tracking one of these bugs, I open ProcessExplorer and watch these columns: Handles, Threads, GDI Objects, USER Objects, Private Bytes, Virtual Size and Working Set.

(In my experience, the problem is usually an object leak due to an event handler holding the object and preventing it from being disposed.)

Showing percentages above bars on Excel column graph

In Excel for Mac 2016 at least,if you place the labels in any spot on the graph and are looking to move them anywhere else (in this case above the bars), select:

Chart Design->Add Chart Element->Data Labels -> More Data Label Options

then you can grab each individual label and pull it where you would like it.

Merge two Excel tables Based on matching data in Columns

Teylyn's answer worked great for me, but I had to modify it a bit to get proper results. I want to provide an extended explanation for whoever would need it.

My setup was as follows:

  • Sheet1: full data of 2014
  • Sheet2: updated rows for 2015 in A1:D50, sorted by first column
  • Sheet3: merged rows
  • My data does not have a header row

I put the following formula in cell A1 of Sheet3:

=iferror(vlookup(Sheet1!A$1;Sheet2!$A$1:$D$50;column(A1);false);Sheet1!A1)

Read this as follows: Take the value of the first column in Sheet1 (old data). Look up in Sheet2 (updated rows). If present, output the value from the indicated column in Sheet2. On error, output the value for the current column of Sheet1.

Notes:

  • In my version of the formula, ";" is used as parameter separator instead of ",". That is because I am located in Europe and we use the "," as decimal separator. Change ";" back to "," if you live in a country where "." is the decimal separator.

  • A$1: means always take column 1 when copying the formula to a cell in a different column. $A$1 means: always take the exact cell A1, even when copying the formula to a different row or column.

After pasting the formula in A1, I extended the range to columns B, C, etc., until the full width of my table was reached. Because of the $-signs used, this gives the following formula's in cells B1, C1, etc.:

=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(B1);FALSE);'Sheet1'!B1)
=IFERROR(VLOOKUP('Sheet1'!$A1;'Sheet2'!$A$1:$D$50;COLUMN(C1);FALSE);'Sheet1'!C1)

and so forth. Note that the lookup is still done in the first column. This is because VLOOKUP needs the lookup data to be sorted on the column where the lookup is done. The output column is however the column where the formula is pasted.

Next, select a rectangle in Sheet 3 starting at A1 and having the size of the data in Sheet1 (same number of rows and columns). Press Ctrl-D to copy the formulas of the first row to all selected cells.

Cells A2, A3, etc. will get these formulas:

=IFERROR(VLOOKUP('Sheet1'!$A2;'Sheet2'!$A$1:$D$50;COLUMN(A2);FALSE);'Sheet1'!A2)
=IFERROR(VLOOKUP('Sheet1'!$A3;'Sheet2'!$A$1:$D$50;COLUMN(A3);FALSE);'Sheet1'!A3)

Because of the use of $-signs, the lookup area is constant, but input data is used from the current row.

matplotlib has no attribute 'pyplot'

Did you import it? Importing matplotlib is not enough.

>>> import matplotlib
>>> matplotlib.pyplot
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'pyplot'

but

>>> import matplotlib.pyplot
>>> matplotlib.pyplot

works.

pyplot is a submodule of matplotlib and not immediately imported when you import matplotlib.

The most common form of importing pyplot is

import matplotlib.pyplot as plt

Thus, your statements won't be too long, e.g.

plt.plot([1,2,3,4,5])

instead of

matplotlib.pyplot.plot([1,2,3,4,5])

And: pyplot is not a function, it's a module! So don't call it, use the functions defined inside this module instead. See my example above

Does VBScript have a substring() function?

Yes, Mid.

Dim sub_str
sub_str = Mid(source_str, 10, 5)

The first parameter is the source string, the second is the start index, and the third is the length.

@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid results in "invalid procedure call or argument Mid".

Android MediaPlayer Stop and Play

I may have not got your answer correct, but you can try this:

public void MusicController(View view) throws IOException{
    switch (view.getId()){
        case R.id.play: mplayer.start();break;
        case R.id.pause: mplayer.pause(); break;
        case R.id.stop:
            if(mplayer.isPlaying()) {
                mplayer.stop();
                mplayer.prepare(); 
            }
            break;

    }// where mplayer is defined in  onCreate method}

as there is just one thread handling all, so stop() makes it die so we have to again prepare it If your intent is to start it again when your press start button(it throws IO Exception) Or for better understanding of MediaPlayer you can refer to Android Media Player

Access restriction on class due to restriction on required library rt.jar?

http://www.digizol.com/2008/09/eclipse-access-restriction-on-library.html worked best for me.

On Windows: Windows -> Preferences -> Java -> Compiler -> Errors/Warnings -> Deprecated and restricted API -> Forbidden reference (access rules): -> change to warning

On Mac OS X/Linux: Eclipse -> Preferences -> Java -> Compiler -> Errors/Warnings -> Deprecated and restricted API -> Forbidden reference (access rules): -> change to warning

Why is the Java main method static?

What is the meaning of public static void main(String args[])?

  1. public is an access specifier meaning anyone can access/invoke it such as JVM(Java Virtual Machine.
  2. static allows main() to be called before an object of the class has been created. This is neccesary because main() is called by the JVM before any objects are made. Since it is static it can be directly invoked via the class.

    class demo {    
        private int length;
        private static int breadth;
        void output(){
            length=5;
            System.out.println(length);
        }
    
        static void staticOutput(){
            breadth=10; 
            System.out.println(breadth);
        }
    
        public static  void main(String args[]){
            demo d1=new demo();
            d1.output(); // Note here output() function is not static so here
            // we need to create object
            staticOutput(); // Note here staticOutput() function is  static so here
            // we needn't to create object Similar is the case with main
            /* Although:
            demo.staticOutput();  Works fine
            d1.staticOutput();  Works fine */
        }
    }
    

    Similarly, we use static sometime for user defined methods so that we need not to make objects.

  3. void indicates that the main() method being declared does not return a value.

  4. String[] args specifies the only parameter in the main() method.

    args - a parameter which contains an array of objects of class type String.

How to use System.Net.HttpClient to post a complex type?

You should use the SendAsync method instead, this is a generic method, that serializes the input to the service

Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268/api/test");
client.SendAsync(new HttpRequestMessage<Widget>(widget))
    .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );

If you don't want to create the concrete class, you can make it with the FormUrlEncodedContent class

var client = new HttpClient();

// This is the postdata
var postData = new List<KeyValuePair<string, string>>();
postData.Add(new KeyValuePair<string, string>("Name", "test"));
postData.Add(new KeyValuePair<string, string>("Price ", "100"));

HttpContent content = new FormUrlEncodedContent(postData); 

client.PostAsync("http://localhost:44268/api/test", content).ContinueWith(
    (postTask) =>
    {
        postTask.Result.EnsureSuccessStatusCode();
    });

Note: you need to make your id to a nullable int (int?)

How to delete and update a record in Hive

Delete has been recently added in Hive version 0.14 Deletes can only be performed on tables that support ACID Below is the link from Apache .

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML#LanguageManualDML-Delete

VBA - If a cell in column A is not blank the column B equals

Another way (Using Formulas in VBA). I guess this is the shortest VBA code as well?

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        .Range("B1:B" & lRow).Formula = "=If(A1<>"""",""My Text"","""")"
        .Range("B1:B" & lRow).Value = .Range("B1:B" & lRow).Value
    End With
End Sub

How do I hide javascript code in a webpage?

My solution is inspired from the last comment. This is the code of invisible.html

<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script type="text/javascript" src="invisible_debut.js" ></script>
<body>
</body>

The clear code of invisible_debut.js is:

$(document).ready(function () {
var ga = document.createElement("script"); //ga is to remember Google Analytics ;-)
ga.type = 'text/javascript';
ga.src = 'invisible.js';
ga.id = 'invisible';
document.body.appendChild(ga);
$('#invisible').remove();});

Notice that at the end I'm removing the created script. invisible.js is:

$(document).ready(function(){
    alert('try to find in the source the js script which did this alert!');
    document.write('It disappeared, my dear!');});

invisible.js doesn't appear in the console, because it has been removed and never in the source code because created by javascript.

Concerning invisible_debut.js, I obfuscated it, which means that it is very complicated to find the url of invisible.js. Not perfect, but enought hard for a normal hacker.

prevent iphone default keyboard when focusing an <input>

You can add a callback function to your DatePicker to tell it to blur the input field before showing the DatePicker.

$('.selector').datepicker({
   beforeShow: function(){$('input').blur();}
});

Note: The iOS keyboard will appear for a fraction of a second and then hide.

How can I issue a single command from the command line through sql plus?

For UNIX (AIX):

export ORACLE_HOME=/oracleClient/app/oracle/product/version
export DBUSER=fooUser
export DBPASSWD=fooPW
export DBNAME=fooSchema 

echo "select * from someTable;" | $ORACLE_HOME/bin/sqlplus $DBUSER/$DBPASSWD@$DBNAME

Makefile If-Then Else and Loops

Here's an example if:

ifeq ($(strip $(OS)),Linux)
        PYTHON = /usr/bin/python
        FIND = /usr/bin/find
endif

Note that this comes with a word of warning that different versions of Make have slightly different syntax, none of which seems to be documented very well.

How to add property to a class dynamically?

I asked a similary question on this Stack Overflow post to create a class factory which created simple types. The outcome was this answer which had a working version of the class factory. Here is a snippet of the answer:

def Struct(*args, **kwargs):
    def init(self, *iargs, **ikwargs):
        for k,v in kwargs.items():
            setattr(self, k, v)
        for i in range(len(iargs)):
            setattr(self, args[i], iargs[i])
        for k,v in ikwargs.items():
            setattr(self, k, v)

    name = kwargs.pop("name", "MyStruct")
    kwargs.update(dict((k, None) for k in args))
    return type(name, (object,), {'__init__': init, '__slots__': kwargs.keys()})

>>> Person = Struct('fname', 'age')
>>> person1 = Person('Kevin', 25)
>>> person2 = Person(age=42, fname='Terry')
>>> person1.age += 10
>>> person2.age -= 10
>>> person1.fname, person1.age, person2.fname, person2.age
('Kevin', 35, 'Terry', 32)
>>>

You could use some variation of this to create default values which is your goal (there is also an answer in that question which deals with this).

XPath - Difference between node() and text()

Select the text of all items under produce:

//produce/item/text()

Select all the manager nodes in all departments:

//department/*

How do you create a UIImage View Programmatically - Swift

In Swift 4.2 and Xcode 10.1

//Create image view simply like this.
let imgView = UIImageView()
imgView.frame = CGRect(x: 200, y: 200, width: 200, height: 200)
imgView.image = UIImage(named: "yourimagename")//Assign image to ImageView
imgView.imgViewCorners()
view.addSubview(imgView)//Add image to our view

//Add image view properties like this(This is one of the way to add properties).  
extension UIImageView {
    //If you want only round corners
    func imgViewCorners() {
        layer.cornerRadius = 10
        layer.borderWidth = 1.0
        layer.masksToBounds = true
    }
}

Pros/cons of using redux-saga with ES6 generators vs redux-thunk with ES2017 async/await

One quick note. Generators are cancellable, async/await — not. So for an example from the question, it does not really make sense of what to pick. But for more complicated flows sometimes there is no better solution than using generators.

So, another idea could be is to use generators with redux-thunk, but for me, it seems like trying to invent a bicycle with square wheels.

And of course, generators are easier to test.

ClientScript.RegisterClientScriptBlock?

Hai sridhar, I found an answer for your prob

ClientScript.RegisterClientScriptBlock(GetType(), "sas", "<script> alert('Inserted successfully');</script>", true);

change false to true

or try this

ScriptManager.RegisterClientScriptBlock(ursavebuttonID, typeof(LinkButton or button), "sas", "<script> alert('Inserted successfully');</script>", true);

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

You will want to use a CONVERT() statement.

Try the following;

SELECT CONVERT(VARCHAR(10), SA.[RequestStartDate], 103) as 'Service Start Date', CONVERT(VARCHAR(10), SA.[RequestEndDate], 103) as 'Service End Date', FROM (......) SA WHERE.....

See MSDN Cast and Convert for more information.

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

An alternative solution is to introduce a method to the file instance that would do the explicit conversion.

import types

def _write_str(self, ascii_str):
    self.write(ascii_str.encode('ascii'))

source_file = open("myfile.bin", "wb")
source_file.write_str = types.MethodType(_write_str, source_file)

And then you can use it as source_file.write_str("Hello World").

Error: "Could Not Find Installable ISAM"

I have just encountered a very similar problem.

Like you, my connection string appeared correct--and indeed, exactly the same connection string was working in other scenarios.

The problem turned out to be a lack of resources. 19 times out of 20, I would see the "Could not find installable ISAM," but once or twice (without any code changes at all), it would yield "Out of memory" instead.

Rebooting the machine "solved" the problem (for now...?). This happened using Jet version 4.0.9505.0 on Windows XP.

Printing an array in C++?

Just iterate over the elements. Like this:

for (int i = numElements - 1; i >= 0; i--) 
    cout << array[i];

Note: As Maxim Egorushkin pointed out, this could overflow. See his comment below for a better solution.

jQuery Selector: Id Ends With?

Since this is ASP.NET, you can simply use the ASP <%= %> tag to print the generated ClientID of txtTitle:

$('<%= txtTitle.ClientID %>')

This will result in...

$('ctl00$ContentBody$txtTitle')

... when the page is rendered.

Note: In Visual Studio, Intellisense will yell at you for putting ASP tags in JavaScript. You can ignore this as the result is valid JavaScript.

Configuring ObjectMapper in Spring

SOLUTION 1

First working solution (tested) useful especially when using @EnableWebMvc:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this won't add a 2nd MappingJackson2HttpMessageConverter 
        // as the SOLUTION 2 is doing but also might seem complicated
        converters.stream().filter(c -> c instanceof MappingJackson2HttpMessageConverter).forEach(c -> {
            // check default included objectMapper._registeredModuleTypes,
            // e.g. Jdk8Module, JavaTimeModule when creating the ObjectMapper
            // without Jackson2ObjectMapperBuilder
            ((MappingJackson2HttpMessageConverter) c).setObjectMapper(this.objectMapper);
        });
    }

SOLUTION 2

Of course the common approach below works too (also working with @EnableWebMvc):

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
    @Autowired
    private ObjectMapper objectMapper;// created elsewhere
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // this will add a 2nd MappingJackson2HttpMessageConverter 
        // (additional to the default one) but will work and you 
        // won't lose the default converters as you'll do when overwriting
        // configureMessageConverters(List<HttpMessageConverter<?>> converters)
        // 
        // you still have to check default included
        // objectMapper._registeredModuleTypes, e.g.
        // Jdk8Module, JavaTimeModule when creating the ObjectMapper
        // without Jackson2ObjectMapperBuilder
        converters.add(new MappingJackson2HttpMessageConverter(this.objectMapper));
    }

Why @EnableWebMvc usage is a problem?

@EnableWebMvc is using DelegatingWebMvcConfiguration which extends WebMvcConfigurationSupport which does this:

if (jackson2Present) {
    Jackson2ObjectMapperBuilder builder = Jackson2ObjectMapperBuilder.json();
    if (this.applicationContext != null) {
        builder.applicationContext(this.applicationContext);
    }
    messageConverters.add(new MappingJackson2HttpMessageConverter(builder.build()));
}

which means that there's no way of injecting your own ObjectMapper with the purpose of preparing it to be used for creating the default MappingJackson2HttpMessageConverter when using @EnableWebMvc.

Twitter Bootstrap carousel different height images cause bouncing arrows

Include this JavaScript in your footer (after loading jQuery):

$('.item').css('min-height',$('.item').height());

Get Absolute Position of element within the window in wpf

Hm. You have to specify window you clicked in Mouse.GetPosition(IInputElement relativeTo) Following code works well for me

protected override void OnMouseDown(MouseButtonEventArgs e)
    {
        base.OnMouseDown(e);
        Point p = e.GetPosition(this);
    }

I suspect that you need to refer to the window not from it own class but from other point of the application. In this case Application.Current.MainWindow will help you.

How to get an enum value from a string value in Java?

You should also be careful with your case. Let me explain: doing Blah.valueOf("A") works, but Blah.valueOf("a") will not work. Then again Blah.valueOf("a".toUpperCase(Locale.ENGLISH)) would work.

edit
Changed toUpperCase to toUpperCase(Locale.ENGLISH) based on tc. comment and the java docs

edit2 On android you should use Locale.US, as sulai points out.

Find text in string with C#

Simply add this code:

if (string.Contains("search_text")) { MessageBox.Show("Message."); }

How to convert a List<String> into a comma separated string without iterating List explicitly

Join / concat & Split functions on ArrayList:

To Join /concat all elements of arraylist with comma (",") to String.

List<String> ids = new ArrayList<String>();
ids.add("1");
ids.add("2");
ids.add("3");
ids.add("4");
String allIds = TextUtils.join(",", ids);
Log.i("Result", allIds);

To split all elements of String to arraylist with comma (",").

String allIds = "1,2,3,4";
String[] allIdsArray = TextUtils.split(allIds, ",");
ArrayList<String> idsList = new ArrayList<String>(Arrays.asList(allIdsArray));
for(String element : idsList){
    Log.i("Result", element);
}

Done

What is the difference between class and instance methods?

Instances methods operate on instances of classes (ie, "objects"). Class methods are associated with classes (most languages use the keyword static for these guys).

Commands out of sync; you can't run this command now

You can't have two simultaneous queries because mysqli uses unbuffered queries by default (for prepared statements; it's the opposite for vanilla mysql_query). You can either fetch the first one into an array and loop through that, or tell mysqli to buffer the queries (using $stmt->store_result()).

See here for details.

Java: how to import a jar file from command line

you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".

Android:java.lang.OutOfMemoryError: Failed to allocate a 23970828 byte allocation with 2097152 free bytes and 2MB until OOM

I don't really recommend editing manifest like this

android:hardwareAccelerated="false" , android:largeHeap="true"

These options cause not smooth animation effect on your app. Moreover 'liveData' or changing your local DB(Sqlite, Room) activate slowly. It is bad for user experience.

So I recommend RESIZE bitmap

Below is the sample code

fun resizeBitmap(source: Bitmap): Bitmap {
      val maxResolution = 1000    //edit 'maxResolution' to fit your need
      val width = source.width
      val height = source.height
      var newWidth = width
      var newHeight = height
      val rate: Float

            if (width > height) {
                if (maxResolution < width) {
                    rate = maxResolution / width.toFloat()
                    newHeight = (height * rate).toInt()
                    newWidth = maxResolution
                }
            } else {
                if (maxResolution < height) {
                    rate = maxResolution / height.toFloat()
                    newWidth = (width * rate).toInt()
                    newHeight = maxResolution
                }
            }
            return Bitmap.createScaledBitmap(source, newWidth, newHeight, true)
 }

Swift Alamofire: How to get the HTTP response status code

For Swift 2.0 users with Alamofire > 2.0

Alamofire.request(.GET, url)
  .responseString { _, response, result in
    if response?.statusCode == 200{
      //Do something with result
    }
}

Check whether a string matches a regex in JS

You can try this, it works for me.

 <input type="text"  onchange="CheckValidAmount(this.value)" name="amount" required>

 <script type="text/javascript">
    function CheckValidAmount(amount) {          
       var a = /^(?:\d{1,3}(?:,\d{3})*|\d+)(?:\.\d+)?$/;
       if(amount.match(a)){
           alert("matches");
       }else{
        alert("does not match"); 
       }
    }
</script>

Function that creates a timestamp in c#

You can also use

Stopwatch.GetTimestamp().ToString();

Why should Java 8's Optional not be used in arguments

This seems a bit silly to me, but the only reason I can think of is that object arguments in method parameters already are optional in a way - they can be null. Therefore forcing someone to take an existing object and wrap it in an optional is sort of pointless.

That being said, chaining methods together that take/return optionals is a reasonable thing to do, e.g. Maybe monad.

How to fix java.lang.UnsupportedClassVersionError: Unsupported major.minor version

In Eclipse, I just went to menu command Window -> Preferences -> Java -> Compiler and then set "Compiler compliance level" to 1.6.

iOS 7 - Failing to instantiate default view controller

Product "Clean" was the solution for me.

How do I iterate over the words of a string?

The following is a much better way to do this. It can take any character, and doesn't split lines unless you want. No special libraries needed (well, besides std, but who really considers that an extra library), no pointers, no references, and it's static. Just simple plain C++.

#pragma once
#include <vector>
#include <sstream>
using namespace std;
class Helpers
{
    public:
        static vector<string> split(string s, char delim)
        {
            stringstream temp (stringstream::in | stringstream::out);
            vector<string> elems(0);
            if (s.size() == 0 || delim == 0)
                return elems;
            for(char c : s)
            {
                if(c == delim)
                {
                    elems.push_back(temp.str());
                    temp = stringstream(stringstream::in | stringstream::out);
                }
                else
                    temp << c;
            }
            if (temp.str().size() > 0)
                elems.push_back(temp.str());
                return elems;
            }

        //Splits string s with a list of delimiters in delims (it's just a list, like if we wanted to
        //split at the following letters, a, b, c we would make delims="abc".
        static vector<string> split(string s, string delims)
        {
            stringstream temp (stringstream::in | stringstream::out);
            vector<string> elems(0);
            bool found;
            if(s.size() == 0 || delims.size() == 0)
                return elems;
            for(char c : s)
            {
                found = false;
                for(char d : delims)
                {
                    if (c == d)
                    {
                        elems.push_back(temp.str());
                        temp = stringstream(stringstream::in | stringstream::out);
                        found = true;
                        break;
                    }
                }
                if(!found)
                    temp << c;
            }
            if(temp.str().size() > 0)
                elems.push_back(temp.str());
            return elems;
        }
};

pip: no module named _internal

This command works for me.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py python get-pip.py --force-reinstall --user

Delete rows containing specific strings in R

You could use dplyr::filter() and negate a grepl() match:

library(dplyr)

df %>% 
  filter(!grepl('REVERSE', Name))

Or with dplyr::filter() and negating a stringr::str_detect() match:

library(stringr)

df %>% 
  filter(!str_detect(Name, 'REVERSE'))

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Find files in created between a date range

If you use GNU find, since version 4.3.3 you can do:

find -newerct "1 Aug 2013" ! -newerct "1 Sep 2013" -ls

It will accept any date string accepted by GNU date -d.

You can change the c in -newerct to any of a, B, c, or m for looking at atime/birth/ctime/mtime.

Another example - list files modified between 17:30 and 22:00 on Nov 6 2017:

find -newermt "2017-11-06 17:30:00" ! -newermt "2017-11-06 22:00:00" -ls

Full details from man find:

   -newerXY reference
          Compares the timestamp of the current file with reference.  The reference argument is normally the name of a file (and one of its timestamps  is  used
          for  the  comparison)  but  it may also be a string describing an absolute time.  X and Y are placeholders for other letters, and these letters select
          which time belonging to how reference is used for the comparison.

          a   The access time of the file reference
          B   The birth time of the file reference
          c   The inode status change time of reference
          m   The modification time of the file reference
          t   reference is interpreted directly as a time

          Some combinations are invalid; for example, it is invalid for X to be t.  Some combinations are not implemented on all systems; for example B  is  not
          supported on all systems.  If an invalid or unsupported combination of XY is specified, a fatal error results.  Time specifications are interpreted as
          for the argument to the -d option of GNU date.  If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal
          error  message  results.   If  you  specify a test which refers to the birth time of files being examined, this test will fail for any files where the
          birth time is unknown.

Why do python lists have pop() but not push()

FYI, it's not terribly difficult to make a list that has a push method:

>>> class StackList(list):
...     def push(self, item):
...             self.append(item)
... 
>>> x = StackList([1,2,3])
>>> x
[1, 2, 3]
>>> x.push(4)
>>> x
[1, 2, 3, 4]

A stack is a somewhat abstract datatype. The idea of "pushing" and "popping" are largely independent of how the stack is actually implemented. For example, you could theoretically implement a stack like this (although I don't know why you would):

l = [1,2,3]
l.insert(0, 1)
l.pop(0)

...and I haven't gotten into using linked lists to implement a stack.

Java ArrayList of Arrays?

As already answered, you can create an ArrayList of String Arrays as @Péter Török written;

    //Declaration of an ArrayList of String Arrays
    ArrayList<String[]> listOfArrayList = new ArrayList<String[]>();

When assigning different String Arrays to this ArrayList, each String Array's length will be different.

In the following example, 4 different Array of String added, their lengths are varying.

String Array #1: len: 3
String Array #2: len: 1
String Array #3: len: 4
String Array #4: len: 2

The Demonstration code is as below;

import java.util.ArrayList;

public class TestMultiArray {

    public static void main(String[] args) {
        //Declaration of an ArrayList of String Arrays
        ArrayList<String[]> listOfArrayList = new ArrayList<String[]>();

        //Assignment of 4 different String Arrays with different lengths
        listOfArrayList.add( new String[]{"line1: test String 1","line1: test String 2","line1: test String 3"}  );
        listOfArrayList.add( new String[]{"line2: test String 1"}  );
        listOfArrayList.add( new String[]{"line3: test String 1","line3: test String 2","line3: test String 3", "line3: test String 4"}  );
        listOfArrayList.add( new String[]{"line4: test String 1","line4: test String 2"}  );

        // Printing out the ArrayList Contents of String Arrays
        // '$' is used to indicate the String elements of String Arrays
        for( int i = 0; i < listOfArrayList.size(); i++ ) {
            for( int j = 0; j < listOfArrayList.get(i).length; j++ )
                System.out.printf(" $ " + listOfArrayList.get(i)[j]);

            System.out.println();
        }

    }
}

And the output is as follows;

 $ line1: test String 1 $ line1: test String 2 $ line1: test String 3
 $ line2: test String 1
 $ line3: test String 1 $ line3: test String 2 $ line3: test String 3 $ line3: test String 4
 $ line4: test String 1 $ line4: test String 2

Also notify that you can initialize a new Array of Sting as below;

new String[]{ str1, str2, str3,... }; // Assuming str's are String objects

So this is same with;

String[] newStringArray = { str1, str2, str3 }; // Assuming str's are String objects

I've written this demonstration just to show that no theArrayList object, all the elements are references to different instantiations of String Arrays, thus the length of each String Arrays are not have to be the same, neither it is important.

One last note: It will be best practice to use the ArrayList within a List interface, instead of which that you've used in your question.

It will be better to use the List interface as below;

    //Declaration of an ArrayList of String Arrays
    List<String[]> listOfArrayList = new ArrayList<String[]>();

Update records using LINQ

I assume person_id is the primary key of Person table, so here's how you update a single record:

Person result = (from p in Context.Persons
              where p.person_id == 5
              select p).SingleOrDefault();

result.is_default = false;

Context.SaveChanges();

and here's how you update multiple records:

List<Person> results = (from p in Context.Persons
                        where .... // add where condition here
                        select p).ToList();

foreach (Person p in results)
{
    p.is_default = false;
}

Context.SaveChanges();

How can I use jQuery to make an input readonly?

Maybe use atribute disabled:

<input disabled="disabled" id="fieldName" name="fieldName" type="text" class="text_box" />

Or just use label tag: ;)

<label>

Python method for reading keypress?

from msvcrt import getch

pos = [0, 0]

def fright():
    global pos
    pos[0] += 1

def fleft():
    global pos 
    pos[0] -= 1

def fup():
    global pos
    pos[1] += 1

def fdown():
    global pos
    pos[1] -= 1

while True:
    print'Distance from zero: ', pos
    key = ord(getch())
    if key == 27: #ESC
        break
    elif key == 13: #Enter
        print('selected')
    elif key == 32: #Space
        print('jump')
    elif key == 224: #Special keys (arrows, f keys, ins, del, etc.)
        key = ord(getch())
        if key == 80: #Down arrow
            print('down')
            fdown
        elif key == 72: #Up arrow
            print('up')
            fup()
        elif key == 75: #Left arrow
            print('left')
            fleft()
        elif key == 77: #Right arrow
            print('right')
            fright()

How to make a pure css based dropdown menu?

_x000D_
_x000D_
html, body {_x000D_
    font-family: Arial, Helvetica, sans-serif;_x000D_
}_x000D_
_x000D_
/* define a fixed width for the entire menu */_x000D_
.navigation {_x000D_
  width: 150px;_x000D_
}_x000D_
_x000D_
/* reset our lists to remove bullet points and padding */_x000D_
.mainmenu, .submenu {_x000D_
  list-style: none;_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
/* make ALL links (main and submenu) have padding and background color */_x000D_
.mainmenu a {_x000D_
  display: block;_x000D_
  background-color: #CCC;_x000D_
  text-decoration: none;_x000D_
  padding: 10px;_x000D_
  color: #000;_x000D_
}_x000D_
_x000D_
/* add hover behaviour */_x000D_
.mainmenu a:hover {_x000D_
    background-color: #C5C5C5;_x000D_
}_x000D_
_x000D_
_x000D_
/* when hovering over a .mainmenu item,_x000D_
  display the submenu inside it._x000D_
  we're changing the submenu's max-height from 0 to 200px;_x000D_
*/_x000D_
_x000D_
.mainmenu li:hover .submenu {_x000D_
  display: block;_x000D_
  max-height: 200px;_x000D_
}_x000D_
_x000D_
/*_x000D_
  we now overwrite the background-color for .submenu links only._x000D_
  CSS reads down the page, so code at the bottom will overwrite the code at the top._x000D_
*/_x000D_
_x000D_
.submenu a {_x000D_
  background-color: #999;_x000D_
}_x000D_
_x000D_
/* hover behaviour for links inside .submenu */_x000D_
.submenu a:hover {_x000D_
  background-color: #666;_x000D_
}_x000D_
_x000D_
/* this is the initial state of all submenus._x000D_
  we set it to max-height: 0, and hide the overflowed content._x000D_
*/_x000D_
.submenu {_x000D_
  overflow: hidden;_x000D_
  max-height: 0;_x000D_
  -webkit-transition: all 0.5s ease-out;_x000D_
}
_x000D_
<html>_x000D_
<body>_x000D_
<head>_x000D_
<link rel="stylesheet" type="css/text" href="nav.css">_x000D_
</head>_x000D_
</body>_x000D_
<nav class="navigation">_x000D_
  <ul class="mainmenu">_x000D_
    <li><a href="">Home</a></li>_x000D_
    <li><a href="">About</a></li>_x000D_
    <li><a href="">Products</a>_x000D_
      <ul class="submenu">_x000D_
        <li><a href="">Tops</a></li>_x000D_
        <li><a href="">Bottoms</a></li>_x000D_
        <li><a href="">Footwear</a></li>_x000D_
      </ul>_x000D_
    </li>_x000D_
    <li><a href="">Contact us</a></li>_x000D_
  </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

What is the size of ActionBar in pixels?

public int getActionBarHeight() {
    int actionBarHeight = 0;
    TypedValue tv = new TypedValue();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv,
                true))
            actionBarHeight = TypedValue.complexToDimensionPixelSize(
                    tv.data, getResources().getDisplayMetrics());
    } else {
        actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
                getResources().getDisplayMetrics());
    }
    return actionBarHeight;
}

WARNING: sanitizing unsafe style value url

Check this handy pipe for Angular2: Usage:

  1. in the SafePipe code, substitute DomSanitizationService with DomSanitizer

  2. provide the SafePipe if your NgModule

  3. <div [style.background-image]="'url(' + your_property + ')' | safe: 'style'"></div>

Can I force a page break in HTML printing?

@Chris Doggett makes perfect sense. Although, I found one funny trick on lvsys.com, and it actually works on firefox and chrome. Just put this comment anywhere you want the page-break to be inserted. You can also replace the <p> tag with any block element.

<p><!-- pagebreak --></p>

jQuery attr('onclick')

As @Richard pointed out above, the onClick needs to have a capital 'C'.

$('#stop').click(function() {
     $('next').attr('onClick','stopMoving()');
}

Where is the IIS Express configuration / metabase file found?

To come full circle and include all versions of Visual Studio, @Myster originally stated that;

Pre Visual Studio 2015 the paths to applicationhost.config were:

%userprofile%\documents\iisexpress\config\applicationhost.config
%userprofile%\my documents\iisexpress\config\applicationhost.config

Visual Studio 2015/2017 path can be found at: (credit: @Talon)

$(solutionDir)\.vs\config\applicationhost.config

Visual Studio 2019 path can be found at: (credit: @Talon)

$(solutionDir)\.vs\config\$(ProjectName)\applicationhost.config

But the part that might get some people is that the project settings in the .sln file can repopulate the applicationhost.config for Visual Studio 2015+. (credit: @Lex Li)

So, if you make a change in the applicationhost.config you also have to make sure your changes match here:

$(solutionDir)\ProjectName.sln

The two important settings should look like:

Project("{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}") = "ProjectName", "ProjectPath\", "{XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}"

and

VWDPort = "Port#"

What is important here is that the two settings in the .sln must match the name and bindingInformation respectively in the applicationhost.config file if you plan on making changes. There may be more places that link these two files and I will update as I find more links either by comments or more experience.

Is it possible to read from a InputStream with a timeout?

Inspired in this answer I came up with a bit more object-oriented solution.

This is only valid if you're intending to read characters

You can override BufferedReader and implement something like this:

public class SafeBufferedReader extends BufferedReader{

    private long millisTimeout;

    ( . . . )

    @Override
    public int read(char[] cbuf, int off, int len) throws IOException {
        try {
            waitReady();
        } catch(IllegalThreadStateException e) {
            return 0;
        }
        return super.read(cbuf, off, len);
    }

    protected void waitReady() throws IllegalThreadStateException, IOException {
        if(ready()) return;
        long timeout = System.currentTimeMillis() + millisTimeout;
        while(System.currentTimeMillis() < timeout) {
            if(ready()) return;
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                break; // Should restore flag
            }
        }
        if(ready()) return; // Just in case.
        throw new IllegalThreadStateException("Read timed out");
    }
}

Here's an almost complete example.

I'm returning 0 on some methods, you should change it to -2 to meet your needs, but I think that 0 is more suitable with BufferedReader contract. Nothing wrong happened, it just read 0 chars. readLine method is a horrible performance killer. You should create a entirely new BufferedReader if you actually want to use readLine. Right now, it is not thread safe. If someone invokes an operation while readLines is waiting for a line, it will produce unexpected results

I don't like returning -2 where I am. I'd throw an exception because some people may just be checking if int < 0 to consider EOS. Anyway, those methods claim that "can't block", you should check if that statement is actually true and just don't override'em.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.nio.CharBuffer;
import java.util.concurrent.TimeUnit;
import java.util.stream.Stream;

/**
 * 
 * readLine
 * 
 * @author Dario
 *
 */
public class SafeBufferedReader extends BufferedReader{

    private long millisTimeout;

    private long millisInterval = 100;

    private int lookAheadLine;

    public SafeBufferedReader(Reader in, int sz, long millisTimeout) {
        super(in, sz);
        this.millisTimeout = millisTimeout;
    }

    public SafeBufferedReader(Reader in, long millisTimeout) {
        super(in);
        this.millisTimeout = millisTimeout;
    }



    /**
     * This is probably going to kill readLine performance. You should study BufferedReader and completly override the method.
     * 
     * It should mark the position, then perform its normal operation in a nonblocking way, and if it reaches the timeout then reset position and throw IllegalThreadStateException
     * 
     */
    @Override
    public String readLine() throws IOException {
        try {
            waitReadyLine();
        } catch(IllegalThreadStateException e) {
            //return null; //Null usually means EOS here, so we can't.
            throw e;
        }
        return super.readLine();
    }

    @Override
    public int read() throws IOException {
        try {
            waitReady();
        } catch(IllegalThreadStateException e) {
            return -2; // I'd throw a runtime here, as some people may just be checking if int < 0 to consider EOS
        }
        return super.read();
    }

    @Override
    public int read(char[] cbuf) throws IOException {
        try {
            waitReady();
        } catch(IllegalThreadStateException e) {
            return -2;  // I'd throw a runtime here, as some people may just be checking if int < 0 to consider EOS
        }
        return super.read(cbuf);
    }

    @Override
    public int read(char[] cbuf, int off, int len) throws IOException {
        try {
            waitReady();
        } catch(IllegalThreadStateException e) {
            return 0;
        }
        return super.read(cbuf, off, len);
    }

    @Override
    public int read(CharBuffer target) throws IOException {
        try {
            waitReady();
        } catch(IllegalThreadStateException e) {
            return 0;
        }
        return super.read(target);
    }

    @Override
    public void mark(int readAheadLimit) throws IOException {
        super.mark(readAheadLimit);
    }

    @Override
    public Stream<String> lines() {
        return super.lines();
    }

    @Override
    public void reset() throws IOException {
        super.reset();
    }

    @Override
    public long skip(long n) throws IOException {
        return super.skip(n);
    }

    public long getMillisTimeout() {
        return millisTimeout;
    }

    public void setMillisTimeout(long millisTimeout) {
        this.millisTimeout = millisTimeout;
    }

    public void setTimeout(long timeout, TimeUnit unit) {
        this.millisTimeout = TimeUnit.MILLISECONDS.convert(timeout, unit);
    }

    public long getMillisInterval() {
        return millisInterval;
    }

    public void setMillisInterval(long millisInterval) {
        this.millisInterval = millisInterval;
    }

    public void setInterval(long time, TimeUnit unit) {
        this.millisInterval = TimeUnit.MILLISECONDS.convert(time, unit);
    }

    /**
     * This is actually forcing us to read the buffer twice in order to determine a line is actually ready.
     * 
     * @throws IllegalThreadStateException
     * @throws IOException
     */
    protected void waitReadyLine() throws IllegalThreadStateException, IOException {
        long timeout = System.currentTimeMillis() + millisTimeout;
        waitReady();

        super.mark(lookAheadLine);
        try {
            while(System.currentTimeMillis() < timeout) {
                while(ready()) {
                    int charInt = super.read();
                    if(charInt==-1) return; // EOS reached
                    char character = (char) charInt;
                    if(character == '\n' || character == '\r' ) return;
                }
                try {
                    Thread.sleep(millisInterval);
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt(); // Restore flag
                    break;
                }
            }
        } finally {
            super.reset();
        }
        throw new IllegalThreadStateException("readLine timed out");

    }

    protected void waitReady() throws IllegalThreadStateException, IOException {
        if(ready()) return;
        long timeout = System.currentTimeMillis() + millisTimeout;
        while(System.currentTimeMillis() < timeout) {
            if(ready()) return;
            try {
                Thread.sleep(millisInterval);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt(); // Restore flag
                break;
            }
        }
        if(ready()) return; // Just in case.
        throw new IllegalThreadStateException("read timed out");
    }

}

Call int() function on every list element?

In Python 2.x another approach is to use map:

numbers = map(int, numbers)

Note: in Python 3.x map returns a map object which you can convert to a list if you want:

numbers = list(map(int, numbers))

Facebook API - How do I get a Facebook user's profile image through the Facebook API (without requiring the user to "Allow" the application)

UPDATE:

Starting end August 2012, the API has been updated to allow you to retrieve user's profile pictures in varying sizes. Add the optional width and height fields as URL parameters:

https://graph.facebook.com/USER_ID/picture?width=WIDTH&height=HEIGHT

where WIDTH and HEIGHT are your requested dimension values.

This will return a profile picture with a minimum size of WIDTH x HEIGHT while trying to preserve the aspect ratio. For example,

https://graph.facebook.com/redbull/picture?width=140&height=110

returns

    {
      "data": {
        "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-ash4/c0.19.180.142/s148x148/2624_134501175351_4831452_a.jpg",
        "width": 148,
        "height": 117,
        "is_silhouette": false
      }
   }

END UPDATE

To get a user's profile picture, call

https://graph.facebook.com/USER_ID/picture

where USER_ID can be the user id number or the user name.

To get a user profile picture of a specific size, call

https://graph.facebook.com/USER_ID/picture?type=SIZE

where SIZE should be replaced with one of the words

square
small
normal
large

depending on the size you want.

This call will return a URL to a single image with its size based on your chosen type parameter.

For example:

https://graph.facebook.com/USER_ID/picture?type=small

returns a URL to a small version of the image.

The API only specifies the maximum size for profile images, not the actual size.

Square:

maximum width and height of 50 pixels.

Small

maximum width of 50 pixels and a maximum height of 150 pixels.

Normal

maximum width of 100 pixels and a maximum height of 300 pixels.

Large

maximum width of 200 pixels and a maximum height of 600 pixels.

If you call the default USER_ID/picture you get the square type.

CLARIFICATION

If you call (as per above example)

https://graph.facebook.com/redbull/picture?width=140&height=110

it will return a JSON response if you're using one of the Facebook SDKs request methods. Otherwise it will return the image itself. To always retrieve the JSON, add:

&redirect=false

like so:

https://graph.facebook.com/redbull/picture?width=140&height=110&redirect=false

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

Why can't Python import Image from PIL?

All the answers were great however what did it for me was a combination of uninstalling Pillow

pip uninstall Pillow

Then installing whatever packages you need e.g.

sudo apt-get -y install python-imaging
sudo apt-get -y install zlib1g-dev
sudo apt-get -y install libjpeg-dev

And then using easy_install to reinstall Pillow

easy_install Pillow

Hope this helps others

Calling jQuery method from onClick attribute in HTML

Don't do this!

Stay away from putting the events inline with the elements! If you don't, you're missing the point of JQuery (or one of the biggest ones at least).

The reason why it's easy to define click() handlers one way and not the other is that the other way is simply not desirable. Since you're just learning JQuery, stick to the convention. Now is not the time in your learning curve for JQuery to decide that everyone else is doing it wrong and you have a better way!

Remove decimal values using SQL query

If it's a decimal data type and you know it will never contain decimal places you can consider setting the scale property to 0. For example to decimal(18, 0). This will save you from replacing the ".00" characters and the query will be faster. In such case, don't forget to to check if the "prevent saving option" is disabled (SSMS menu "Tools>Options>Designers>Table and database designer>prevent saving changes that require table re-creation").

Othewise, you of course remove it using SQL query:

select replace(cast([height] as varchar), '.00', '') from table

libxml/tree.h no such file or directory

Form the link of @Matt Ball,

I found following helpful to me.

You need to add libxml2.dylib to your project (don't put it in the Frameworks section). On the Mac, you'll find it at /usr/lib/libxml2.dylib and for the iPhone, you'll want the /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.0.sdk/usr/lib/libxml2.dylib version.

Since libxml2 is a .dylib (not a nice friendly .framework) we still have one more thing to do. Go to the Project build settings (Project->Edit Project Settings->Build) and find the "Search Paths". In "Header Search Paths" add the following path on the Mac:

 /usr/include/libxml2 

How to get a list of all files in Cloud Storage in a Firebase app?

As of May 2019, version 6.1.0 of the Firebase SDK for Cloud Storage now supports listing all objects from a bucket. You simply need to call listAll() in a Reference:

    // Since you mentioned your images are in a folder,
    // we'll create a Reference to that folder:
    var storageRef = firebase.storage().ref("your_folder");


    // Now we get the references of these images
    storageRef.listAll().then(function(result) {
      result.items.forEach(function(imageRef) {
        // And finally display them
        displayImage(imageRef);
      });
    }).catch(function(error) {
      // Handle any errors
    });

    function displayImage(imageRef) {
      imageRef.getDownloadURL().then(function(url) {
        // TODO: Display the image on the UI
      }).catch(function(error) {
        // Handle any errors
      });
    }

Please note that in order to use this function, you must opt-in to version 2 of Security Rules, which can be done by making rules_version = '2'; the first line of your security rules:

    rules_version = '2';
    service firebase.storage {
      match /b/{bucket}/o {
        match /{allPaths=**} {

I'd recommend checking the docs for further reference.

Also, according to setup, on Step 5, this script is not allowed for Node.js since require("firebase/app"); won't return firebase.storage() as a function. This is only achieved using import * as firebase from 'firebase/app';.

Private class declaration

private modifier will make your class inaccessible from outside, so there wouldn't be any advantage of this and I think that is why it is illegal and only public, abstract & final are permitted.

Note : Even you can not make it protected.

How do I delete unpushed git commits?

I wonder why the best answer that I've found is only in the comments! (by Daenyth with 86 up votes)

git reset --hard origin

This command will sync the local repository with the remote repository getting rid of every change you have made on your local. You can also do the following to fetch the exact branch that you have in the origin.

git reset --hard origin/<branch>

I can't install pyaudio on Windows? How to solve "error: Microsoft Visual C++ 14.0 is required."?

The answer by Agalin is already great and I just want to explain it in a step by step format for a novice like myself:

  • find your Python version by python --version mine is 3.7.3 for example
  • the easiest way to check either you have 64 or 32 Python just open it in the terminal:

  • find the appropriate .whl file from here, for example mine is PyAudio-0.2.11-cp37-cp37m-win_amd64.whl, and download it.
  • go to the folder where it is downloaded for example cd C:\Users\foobar\Downloads
  • install the .whl file with pip for example in my case:
pip install PyAudio-0.2.11-cp37-cp37m-win_amd64.whl

Getting the source HTML of the current page from chrome extension

Inject a script into the page you want to get the source from and message it back to the popup....

manifest.json

{
  "name": "Get pages source",
  "version": "1.0",
  "manifest_version": 2,
  "description": "Get pages source from a popup",
  "browser_action": {
    "default_icon": "icon.png",
    "default_popup": "popup.html"
  },
  "permissions": ["tabs", "<all_urls>"]
}

popup.html

<!DOCTYPE html>
<html style=''>
<head>
<script src='popup.js'></script>
</head>
<body style="width:400px;">
<div id='message'>Injecting Script....</div>
</body>
</html>

popup.js

chrome.runtime.onMessage.addListener(function(request, sender) {
  if (request.action == "getSource") {
    message.innerText = request.source;
  }
});

function onWindowLoad() {

  var message = document.querySelector('#message');

  chrome.tabs.executeScript(null, {
    file: "getPagesSource.js"
  }, function() {
    // If you try and inject into an extensions page or the webstore/NTP you'll get an error
    if (chrome.runtime.lastError) {
      message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
    }
  });

}

window.onload = onWindowLoad;

getPagesSource.js

// @author Rob W <http://stackoverflow.com/users/938089/rob-w>
// Demo: var serialized_html = DOMtoString(document);

function DOMtoString(document_root) {
    var html = '',
        node = document_root.firstChild;
    while (node) {
        switch (node.nodeType) {
        case Node.ELEMENT_NODE:
            html += node.outerHTML;
            break;
        case Node.TEXT_NODE:
            html += node.nodeValue;
            break;
        case Node.CDATA_SECTION_NODE:
            html += '<![CDATA[' + node.nodeValue + ']]>';
            break;
        case Node.COMMENT_NODE:
            html += '<!--' + node.nodeValue + '-->';
            break;
        case Node.DOCUMENT_TYPE_NODE:
            // (X)HTML documents are identified by public identifiers
            html += "<!DOCTYPE " + node.name + (node.publicId ? ' PUBLIC "' + node.publicId + '"' : '') + (!node.publicId && node.systemId ? ' SYSTEM' : '') + (node.systemId ? ' "' + node.systemId + '"' : '') + '>\n';
            break;
        }
        node = node.nextSibling;
    }
    return html;
}

chrome.runtime.sendMessage({
    action: "getSource",
    source: DOMtoString(document)
});

how to mysqldump remote db from local machine

mysqldump from remote server use SSL

1- Security with SSL

192.168.0.101 - remote server

192.168.0.102 - local server

Remore server

CREATE USER 'backup_remote_2'@'192.168.0.102' IDENTIFIED WITH caching_sha2_password BY '3333333' REQUIRE SSL;

GRANT ALL PRIVILEGES ON *.* TO 'backup_remote_2'@'192.168.0.102';

FLUSH PRIVILEGES;

-

Local server

sudo /usr/local/mysql/bin/mysqldump \
 --databases test_1 \
 --host=192.168.0.101 \
 --user=backup_remote_2 \
 --password=3333333 \
 --master-data \
 --set-gtid-purged \
 --events \
 --triggers \
 --routines \
 --verbose \
 --ssl-mode=REQUIRED \
 --result-file=/home/db_1.sql

====================================

2 - Security with SSL (REQUIRE X509)

192.168.0.101 - remote server

192.168.0.102 - local server

Remore server

CREATE USER 'backup_remote'@'192.168.0.102' IDENTIFIED WITH caching_sha2_password BY '1111111' REQUIRE X509;

GRANT ALL PRIVILEGES ON *.* TO 'backup_remote'@'192.168.0.102';

FLUSH PRIVILEGES;

-

Local server

sudo /usr/local/mysql/bin/mysqldump \
 --databases test_1 \
 --host=192.168.0.101 \
 --user=backup_remote \
 --password=1111111 \
 --events \
 --triggers \
 --routines \
 --verbose \
 --ssl-mode=VERIFY_CA \
 --ssl-ca=/usr/local/mysql/data/ssl/ca.pem \
 --ssl-cert=/usr/local/mysql/data/ssl/client-cert.pem \
 --ssl-key=/usr/local/mysql/data/ssl/client-key.pem \
 --result-file=/home/db_name.sql

[Note]

On local server

/usr/local/mysql/data/ssl/

-rw------- 1 mysql mysql 1.7K Apr 16 22:28 ca-key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 ca.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28 client-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28 client-key.pem

Copy this files from remote server for (REQUIRE X509) or if SSL without (REQUIRE X509) do not copy


On remote server

/usr/local/mysql/data/

-rw------- 1 mysql mysql 1.7K Apr 16 22:28  ca-key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  ca.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  client-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  client-key.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  private_key.pem
-rw-r--r-- 1 mysql mysql  451 Apr 16 22:28  public_key.pem
-rw-r--r-- 1 mysql mysql 1.1K Apr 16 22:28  server-cert.pem
-rw------- 1 mysql mysql 1.7K Apr 16 22:28  server-key.pem

my.cnf

[mysqld]
# SSL
ssl_ca=/usr/local/mysql/data/ca.pem
ssl_cert=/usr/local/mysql/data/server-cert.pem
ssl_key=/usr/local/mysql/data/server-key.pem

Increase Password Security

https://dev.mysql.com/doc/refman/8.0/en/password-security-user.html

How to empty a list in C#?

To give an alternative answer (Who needs 5 equal answers?):

list.Add(5); 
// list contains at least one element now
list = new List<int>();
// list in "list" is empty now

Keep in mind that all other references to the old list have not been cleared (depending on the situation, this might be what you want). Also, in terms of performance, it is usually a bit slower.

Bootstrap 4 align navbar items to the right

Just copied this from one of the getbootstrap pages for the released version 4 which worked much better than the above

<div class="d-none d-xl-block col-xl-2 bd-toc float-md-right">
    <ul class="section-nav">
         <li class="toc-entry toc-h2"><a href="#overview">Overview</a></li>
         <li class="toc-entry toc-h2"><a href="#classes">Classes</a></li>
         <li class="toc-entry toc-h2"><a href="#mixins">Mixins</a></li>
         <li class="toc-entry toc-h2"><a href="#responsive">Responsive</a></li>
    </ul>
</div> 

Excel - Button to go to a certain sheet

In Excel 2007, goto Insert/Shape and pick a shape. Colour it and enter whatever text you want. Then right click on the shape and insert a hyperlink

enter image description here

enter image description here

A few tips with shapes..

If you want to easily position the shape with cells, hold down Alt when you move the shape and it will lock to the cell. If you don't want the shape to move or resize with rows/columns, right click the shape, select size and properties and choose the setting which works best.

jsPDF multi page PDF with HTML renderer

You can use html2canvas plugin and jsPDF both. Process order: html to png & png to pdf

Example code:

jQuery('#part1').html2canvas({
    onrendered: function( canvas ) {
        var img1 = canvas.toDataURL('image/png');
    }
});
jQuery('#part2').html2canvas({
    onrendered: function( canvas ) {
        var img2 = canvas.toDataURL('image/png');
    }
});
jQuery('#part3').html2canvas({
    onrendered: function( canvas ) {
        var img3 = canvas.toDataURL('image/png');
    }
});
var doc = new jsPDF('p', 'mm');
doc.addImage( img1, 'PNG', 0, 0, 210, 297); // A4 sizes
doc.addImage( img2, 'PNG', 0, 90, 210, 297); // img1 and img2 on first page

doc.addPage();
doc.addImage( img3, 'PNG', 0, 0, 210, 297); // img3 on second page
doc.save("file.pdf");

Vertical dividers on horizontal UL menu

A simpler solution would be to just add #navigation ul li~li { border-left: 1px solid #857D7A; }

Convert seconds into days, hours, minutes and seconds

a=int(input("Enter your number by seconds "))
d=a//(24*3600)   #Days
h=a//(60*60)%24  #hours
m=a//60%60       #minutes
s=a%60           #seconds
print("Days ",d,"hours ",h,"minutes ",m,"seconds ",s)

Sending emails with Javascript

You don't need any javascript, you just need your href to be coded like this:

<a href="mailto:[email protected]">email me here!</a>

Basic Authentication Using JavaScript

After Spending quite a bit of time looking into this, i came up with the solution for this; In this solution i am not using the Basic authentication but instead went with the oAuth authentication protocol. But to use Basic authentication you should be able to specify this in the "setHeaderRequest" with minimal changes to the rest of the code example. I hope this will be able to help someone else in the future:

var token_ // variable will store the token
var userName = "clientID"; // app clientID
var passWord = "secretKey"; // app clientSecret
var caspioTokenUrl = "https://xxx123.caspio.com/oauth/token"; // Your application token endpoint  
var request = new XMLHttpRequest(); 

function getToken(url, clientID, clientSecret) {
    var key;           
    request.open("POST", url, true); 
    request.setRequestHeader("Content-type", "application/json");
    request.send("grant_type=client_credentials&client_id="+clientID+"&"+"client_secret="+clientSecret); // specify the credentials to receive the token on request
    request.onreadystatechange = function () {
        if (request.readyState == request.DONE) {
            var response = request.responseText;
            var obj = JSON.parse(response); 
            key = obj.access_token; //store the value of the accesstoken
            token_ = key; // store token in your global variable "token_" or you could simply return the value of the access token from the function
        }
    }
}
// Get the token
getToken(caspioTokenUrl, userName, passWord);

If you are using the Caspio REST API on some request it may be imperative that you to encode the paramaters for certain request to your endpoint; see the Caspio documentation on this issue;

NOTE: encodedParams is NOT used in this example but was used in my solution.

Now that you have the token stored from the token endpoint you should be able to successfully authenticate for subsequent request from the caspio resource endpoint for your application

function CallWebAPI() {
    var request_ = new XMLHttpRequest();        
    var encodedParams = encodeURIComponent(params);
    request_.open("GET", "https://xxx123.caspio.com/rest/v1/tables/", true);
    request_.setRequestHeader("Authorization", "Bearer "+ token_);
    request_.send();
    request_.onreadystatechange = function () {
        if (request_.readyState == 4 && request_.status == 200) {
            var response = request_.responseText;
            var obj = JSON.parse(response); 
            // handle data as needed... 

        }
    }
} 

This solution does only considers how to successfully make the authenticated request using the Caspio API in pure javascript. There are still many flaws i am sure...

Correct MIME Type for favicon.ico?

When you're serving an .ico file to be used as a favicon, it doesn't matter. All major browsers recognize both mime types correctly. So you could put:

<!-- IE -->
<link rel="shortcut icon" type="image/x-icon" href="favicon.ico" />
<!-- other browsers -->
<link rel="icon" type="image/x-icon" href="favicon.ico" />

or the same with image/vnd.microsoft.icon, and it will work with all browsers.

Note: There is no IANA specification for the MIME-type image/x-icon, so it does appear that it is a little more unofficial than image/vnd.microsoft.icon.

The only case in which there is a difference is if you were trying to use an .ico file in an <img> tag (which is pretty unusual). Based on previous testing, some browsers would only display .ico files as images when they were served with the MIME-type image/x-icon. More recent tests show: Chromium, Firefox and Edge are fine with both content types, IE11 is not. If you can, just avoid using ico files as images, use png.

iframe to Only Show a Certain Part of the Page

Assuming you are using an iframe to import content available to the public but not owned by you into your website, you can always use the page anchor to direct you iframe to load where you want it to.

First you create an iframe with the width and height needed to display the data.

<iframe src="http://www.mygreatsite.com/page2.html" width="200px" height="100px"></iframe>

Second install addon such as Show Anchors 2 for Firefox and use it to display all the page anchors on the page you would like display in your iframe. Find the anchor point you want your frame to use and copy the anchor location by right clicking on it.

(You can download and install the plugin here => https://addons.mozilla.org/en-us/firefox/addon/show-anchors-2/)

Third use the copied web address with anchor point as your iframe source. When the frame loads, it will show the page starting at the anchor point you specified.

<iframe src="http://www.mygreatsite.com/page2.html#anchorname_1" width="200px" height="100px"></iframe>

That is the condensed instruction list. Hope it helps!

JavaScript: Check if mouse button down?

Regarding Pax' solution: it doesn't work if user clicks more than one button intentionally or accidentally. Don't ask me how I know :-(.

The correct code should be like that:

var mouseDown = 0;
document.body.onmousedown = function() { 
  ++mouseDown;
}
document.body.onmouseup = function() {
  --mouseDown;
}

With the test like this:

if(mouseDown){
  // crikey! isn't she a beauty?
}

If you want to know what button is pressed, be prepared to make mouseDown an array of counters and count them separately for separate buttons:

// let's pretend that a mouse doesn't have more than 9 buttons
var mouseDown = [0, 0, 0, 0, 0, 0, 0, 0, 0],
    mouseDownCount = 0;
document.body.onmousedown = function(evt) { 
  ++mouseDown[evt.button];
  ++mouseDownCount;
}
document.body.onmouseup = function(evt) {
  --mouseDown[evt.button];
  --mouseDownCount;
}

Now you can check what buttons were pressed exactly:

if(mouseDownCount){
  // alright, let's lift the little bugger up!
  for(var i = 0; i < mouseDown.length; ++i){
    if(mouseDown[i]){
      // we found it right there!
    }
  }
}

Now be warned that the code above would work only for standard-compliant browsers that pass you a button number starting from 0 and up. IE uses a bit mask of currently pressed buttons:

  • 0 for "nothing is pressed"
  • 1 for left
  • 2 for right
  • 4 for middle
  • and any combination of above, e.g., 5 for left + middle

So adjust your code accordingly! I leave it as an exercise.

And remember: IE uses a global event object called … "event".

Incidentally IE has a feature useful in your case: when other browsers send "button" only for mouse button events (onclick, onmousedown, and onmouseup), IE sends it with onmousemove too. So you can start listening for onmousemove when you need to know the button state, and check for evt.button as soon as you got it — now you know what mouse buttons were pressed:

// for IE only!
document.body.onmousemove = function(){
  if(event.button){
    // aha! we caught a feisty little sheila!
  }
};

Of course you get nothing if she plays dead and not moving.

Relevant links:

Update #1: I don't know why I carried over the document.body-style of code. It will be better to attach event handlers directly to the document.

Get month name from date in Oracle

to_char(mydate, 'MONTH') will do the job.

Get the name of an object's type

Use class.name. This also works with function.name.

class TestA {}
console.log(TestA.name); // "TestA"

function TestB() {}
console.log(TestB.name); // "TestB"

Getting Data from Android Play Store

There's an unofficial open-source API for the Android Market you may try to use to get the information you need. Hope this helps.

In-place type conversion of a NumPy array

a = np.subtract(a, 0., dtype=np.float32)

get size of json object

you dont need to change your JSON format.

replace:

console.log(data.phones.length);

with:

console.log( Object.keys( data.phones ).length ) ;

How to hide a column (GridView) but still access its value?

If you do have a TemplateField inside the columns of your GridView and you have, say, a control named blah bound to it. Then place the outlook_id as a HiddenField there like this:

<asp:TemplateField HeaderText="OutlookID">
    <ItemTemplate>
        <asp:Label ID="blah" runat="server">Existing Control</asp:Label>
        <asp:HiddenField ID="HiddenOutlookID" runat="server" Value='<%#Eval("Outlook_ID") %>'/>
    </ItemTemplate>
</asp:TemplateField>

Now, grab the row in the event you want the outlook_id and then access the control.
For RowDataBound access it like:

string outlookid = ((HiddenField)e.Row.FindControl("HiddenOutlookID")).Value;

Do get back, if you have trouble accessing the clicked row. And don't forget to mention the event at which you would like to access that.

Comparing two java.util.Dates to see if they are in the same day

private boolean isSameDay(Date date1, Date date2) {
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        Calendar calendar2 = Calendar.getInstance();
        calendar2.setTime(date2);
        boolean sameYear = calendar1.get(Calendar.YEAR) == calendar2.get(Calendar.YEAR);
        boolean sameMonth = calendar1.get(Calendar.MONTH) == calendar2.get(Calendar.MONTH);
        boolean sameDay = calendar1.get(Calendar.DAY_OF_MONTH) == calendar2.get(Calendar.DAY_OF_MONTH);
        return (sameDay && sameMonth && sameYear);
    }

Switch android x86 screen resolution

Verified the following on Virtualbox-5.0.24, Android_x86-4.4-r5. You get a screen similar to an 8" table. You can play around with the xxx in DPI=xxx, to change the resolution. xxx=100 makes it really small to match a real table exactly, but it may be too small when working with android in Virtualbox.

VBoxManage setextradata <VmName> "CustomVideoMode1" "440x680x16"

With the following appended to android kernel cmd:

UVESA_MODE=440x680 DPI=120

Automatically scroll down chat div

_x000D_
_x000D_
const messages = document.getElementById('messages');_x000D_
_x000D_
function appendMessage() {_x000D_
 const message = document.getElementsByClassName('message')[0];_x000D_
  const newMessage = message.cloneNode(true);_x000D_
  messages.appendChild(newMessage);_x000D_
}_x000D_
_x000D_
function getMessages() {_x000D_
 // Prior to getting your messages._x000D_
  shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;_x000D_
  /*_x000D_
   * Get your messages, we'll just simulate it by appending a new one syncronously._x000D_
   */_x000D_
  appendMessage();_x000D_
  // After getting your messages._x000D_
  if (!shouldScroll) {_x000D_
    scrollToBottom();_x000D_
  }_x000D_
}_x000D_
_x000D_
function scrollToBottom() {_x000D_
  messages.scrollTop = messages.scrollHeight;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
_x000D_
setInterval(getMessages, 100);
_x000D_
#messages {_x000D_
  height: 200px;_x000D_
  overflow-y: auto;_x000D_
}
_x000D_
<div id="messages">_x000D_
  <div class="message">_x000D_
    Hello world_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to return JSon object

You only have one row to serialize. Try something like this :

List<results> resultRows = new List<results>

resultRows.Add(new results{id = 1, value="ABC", info="ABC"});
resultRows.Add(new results{id = 2, value="XYZ", info="XYZ"});

string json = JavaScriptSerializer.Serialize(new { results = resultRows});
  • Edit to match OP's original json output

** Edit 2 : sorry, but I missed that he was using JSON.NET. Using the JavaScriptSerializer the above code produces this result :

{"results":[{"id":1,"value":"ABC","info":"ABC"},{"id":2,"value":"XYZ","info":"XYZ"}]}

Test credit card numbers for use with PayPal sandbox

In case anyone else comes across this in a search for an answer...

The test numbers listed in various places no longer work in the Sandbox. PayPal have the same checks in place now so that a card cannot be linked to more than one account.

Go here and get a number generated. Use any expiry date and CVV

https://ppmts.custhelp.com/app/answers/detail/a_id/750/

It's worked every time for me so far...

"configuration file /etc/nginx/nginx.conf test failed": How do I know why this happened?

sudo nginx -t should test all files and return errors and warnings locations

Should Jquery code go in header or footer?

Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.

What does it mean if a Python object is "subscriptable" or not?

Off the top of my head, the following are the only built-ins that are subscriptable:

string:  "foobar"[3] == "b"
tuple:   (1,2,3,4)[3] == 4
list:    [1,2,3,4][3] == 4
dict:    {"a":1, "b":2, "c":3}["c"] == 3

But mipadi's answer is correct - any class that implements __getitem__ is subscriptable

Difference between decimal, float and double in .NET?

I won't reiterate tons of good (and some bad) information already answered in other answers and comments, but I will answer your followup question with a tip:

When would someone use one of these?

Use decimal for counted values

Use float/double for measured values

Some examples:

  • money (do we count money or measure money?)

  • distance (do we count distance or measure distance? *)

  • scores (do we count scores or measure scores?)

We always count money and should never measure it. We usually measure distance. We often count scores.

* In some cases, what I would call nominal distance, we may indeed want to 'count' distance. For example, maybe we are dealing with country signs that show distances to cities, and we know that those distances never have more than one decimal digit (xxx.x km).

Where does error CS0433 "Type 'X' already exists in both A.dll and B.dll " come from?

Close the Solution and re-open it, then check the projects references for doubling up:

enter image description here

This can happen if you were using NuGet and changed the DLLs reference location. To fix it you have to manually edit the proj file removing the entries, eg:

  <Import Project="..\packages\CefSharp.WinForms.53.0.0\build\CefSharp.WinForms.targets" Condition="Exists('..\packages\CefSharp.WinForms.53.0.0\build\CefSharp.WinForms.targets')" />

Watch out as these "<Import" references can appear at different spots in the proj file.

Named tuple and default values for optional keyword arguments

Wrap it in a function.

NodeT = namedtuple('Node', 'val left right')

def Node(val, left=None, right=None):
  return NodeT(val, left, right)

jQuery or CSS selector to select all IDs that start with some string

$('div[id ^= "player_"]');

This worked for me..select all Div starts with "players_" keyword and display it.

How to show code but hide output in RMarkdown?

To hide warnings, you can also do {r, warning=FALSE}

How to install SignTool.exe for Windows 10

April 28th 2020

I found it here:

C:\Program Files (x86)\Windows Kits\10\App Certification Kit

How to fix corrupted git repository?

If you have a remote configured and you have / don't care about losing some unpushed code, you can do :

git fetch && git reset --hard

header('HTTP/1.0 404 Not Found'); not doing anything

No, it probably is actually working. It's just not readily visible. Instead of just using the header call, try doing that, then including 404.php, and then calling die.

You can test the fact that the HTTP/1.0 404 Not Found works by creating a PHP file named, say, test.php with this content:

<?php

header("HTTP/1.0 404 Not Found");
echo "PHP continues.\n";
die();
echo "Not after a die, however.\n";

Then viewing the result with curl -D /dev/stdout reveals:

HTTP/1.0 404 Not Found
Date: Mon, 04 Apr 2011 03:39:06 GMT
Server: Apache
X-Powered-By: PHP/5.3.2
Content-Length: 14
Connection: close
Content-Type: text/html

PHP continues.

PHP Warning: Unknown: failed to open stream

I had the same error and my problem was the file permissions were incorrect.

chmod 755 index.php

worked for me.

MySQL default datetime through phpmyadmin

You're getting that error because the default value current_time is not valid for the type DATETIME. That's what it says, and that's whats going on.

The only field you can use current_time on is a timestamp.

Edit and replay XHR chrome/firefox etc?

Updating/completing zszep answer:

After copying the request as cUrl (bash), simply import it in the Postman App:

enter image description here

Could not open ServletContext resource

Put the things like /src/main/resources/foo/bar.properties and then reference them as classpath:/foo/bar.properties.

Select objects based on value of variable in object using jq

Adapted from this post on Processing JSON with jq, you can use the select(bool) like this:

$ jq '.[] | select(.location=="Stockholm")' json
{
  "location": "Stockholm",
  "name": "Walt"
}
{
  "location": "Stockholm",
  "name": "Donald"
}

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

Here Web Supportive Application is an example of website.

Here Web Supportive Application is an example of website. Website and Web Application both can be dynamic/static its depends upon requirements, here is an example to understand working of website's and web application.

Play multiple CSS animations at the same time

you can try something like this

set the parent to rotate and the image to scale so that the rotate and scale time can be different

_x000D_
_x000D_
div {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  width: 120px;_x000D_
  height: 120px;_x000D_
  margin: -60px 0 0 -60px;_x000D_
  -webkit-animation: spin 2s linear infinite;_x000D_
}_x000D_
.image {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  width: 120px;_x000D_
  height: 120px;_x000D_
  margin: -60px 0 0 -60px;_x000D_
  -webkit-animation: scale 4s linear infinite;_x000D_
}_x000D_
@-webkit-keyframes spin {_x000D_
  100% {_x000D_
    transform: rotate(180deg);_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes scale {_x000D_
  100% {_x000D_
    transform: scale(2);_x000D_
  }_x000D_
}
_x000D_
<div>_x000D_
  <img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to export table as CSV with headings on Postgresql?

From psql command line:

\COPY my_table TO 'filename' CSV HEADER

no semi-colon at the end.

LINQ Joining in C# with multiple conditions

If you need not equal object condition use cross join sequences:

var query = from obj1 in set1
from obj2 in set2
where obj1.key1 == obj2.key2 && obj1.key3.contains(obj2.key5) [...conditions...]

Disable/Enable button in Excel/VBA

... I don't know if you're using an activex button or not, but when I insert an activex button into sheet1 in Excel called CommandButton1, the following code works fine:

Sub test()

   Sheets(1).CommandButton1.Enabled = False

End Sub

Hope this helps...

How can I remove the top and right axis in matplotlib?

Alternatively, this

def simpleaxis(ax):
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

seems to achieve the same effect on an axis without losing rotated label support.

(Matplotlib 1.0.1; solution inspired by this).

How to download all files (but not HTML) from a website using wget?

You may try:

wget --user-agent=Mozilla --content-disposition --mirror --convert-links -E -K -p http://example.com/

Also you can add:

-A pdf,ps,djvu,tex,doc,docx,xls,xlsx,gz,ppt,mp4,avi,zip,rar

to accept the specific extensions, or to reject only specific extensions:

-R html,htm,asp,php

or to exclude the specific areas:

-X "search*,forum*"

If the files are ignored for robots (e.g. search engines), you've to add also: -e robots=off

jQuery click event on radio button doesn't get fired

put ur js code under the form html or use $(document).ready(function(){}) and try this.

$('#inline_content input[type="radio"]').click(function(){
                if($(this).val() == "walk_in"){
                    alert('ok');
                }
});

How to print time in format: 2009-08-10 18:17:54.811

Use strftime().

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

int main()
{
    time_t timer;
    char buffer[26];
    struct tm* tm_info;

    timer = time(NULL);
    tm_info = localtime(&timer);

    strftime(buffer, 26, "%Y-%m-%d %H:%M:%S", tm_info);
    puts(buffer);

    return 0;
}

For milliseconds part, have a look at this question. How to measure time in milliseconds using ANSI C?

Bash if statement with multiple conditions throws an error

You can use either [[ or (( keyword. When you use [[ keyword, you have to use string operators such as -eq, -lt. I think, (( is most preferred for arithmetic, because you can directly use operators such as ==, < and >.

Using [[ operator

a=$1
b=$2
if [[ a -eq 1 || b -eq 2 ]] || [[ a -eq 3 && b -eq 4 ]]
then
     echo "Error"
else
     echo "No Error"
fi

Using (( operator

a=$1
b=$2
if (( a == 1 || b == 2 )) || (( a == 3 && b == 4 ))
then
     echo "Error"
else
     echo "No Error"
fi

Do not use -a or -o operators Since it is not Portable.

How do operator.itemgetter() and sort() work?

a = []
a.append(["Nick", 30, "Doctor"])
a.append(["John",  8, "Student"])
a.append(["Paul",  8,"Car Dealer"])
a.append(["Mark", 66, "Retired"])
print a

[['Nick', 30, 'Doctor'], ['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Mark', 66, 'Retired']]

def _cmp(a,b):     

    if a[1]<b[1]:
        return -1
    elif a[1]>b[1]:
        return 1
    else:
        return 0

sorted(a,cmp=_cmp)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]

def _key(list_ele):

    return list_ele[1]

sorted(a,key=_key)

[['John', 8, 'Student'], ['Paul', 8, 'Car Dealer'], ['Nick', 30, 'Doctor'], ['Mark', 66, 'Retired']]
>>> 

How can I determine if a date is between two dates in Java?

If you don't know the order of the min/max values

Date a, b;   // assume these are set to something
Date d;      // the date in question

return a.compareTo(d) * d.compareTo(b) > 0;

If you want the range to be inclusive

return a.compareTo(d) * d.compareTo(b) >= 0;

iPhone UITextField - Change placeholder text color

In Swift:

if let placeholder = yourTextField.placeholder {
    yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder, 
        attributes: [NSForegroundColorAttributeName: UIColor.blackColor()])
}

In Swift 4.0:

if let placeholder = yourTextField.placeholder {
    yourTextField.attributedPlaceholder = NSAttributedString(string:placeholder, 
        attributes: [NSAttributedStringKey.foregroundColor: UIColor.black])
}

how does Array.prototype.slice.call() work?

First, you should read how function invocation works in JavaScript. I suspect that alone is enough to answer your question. But here's a summary of what is happening:

Array.prototype.slice extracts the slice method from Array's prototype. But calling it directly won't work, as it's a method (not a function) and therefore requires a context (a calling object, this), otherwise it would throw Uncaught TypeError: Array.prototype.slice called on null or undefined.

The call() method allows you to specify a method's context, basically making these two calls equivalent:

someObject.slice(1, 2);
slice.call(someObject, 1, 2);

Except the former requires the slice method to exist in someObject's prototype chain (as it does for Array), whereas the latter allows the context (someObject) to be manually passed to the method.

Also, the latter is short for:

var slice = Array.prototype.slice;
slice.call(someObject, 1, 2);

Which is the same as:

Array.prototype.slice.call(someObject, 1, 2);

How to get the client IP address in PHP

Try this one:

 $_SERVER['REMOTE_ADDR'];

Browse and display files in a git repo without cloning

The command you want is git ls-remote which allows you to get some information about remote repositories, but you cant show history or list directories or anything of that level: essentially it only lets you see the remote objects at a very high-level (you can see the current HEADs and tags for example).

The only real way to do what you want (if I understand correctly) would be to use ssh to run a remote command and return the results, for example:

ssh me@otherhost "cd repo && git log -n 10"

What you want would be lovely functionality if they could add it, but from what I read it's not very easy since getting history etc needs a lot of information to be local to git, and at that point you may as well have done a git fetch.

Open Source Alternatives to Reflector?

Another replacement would be dotPeek. JetBrains announced it as a free tool. It will probably have more features when used with their Resharper but even when used alone it works very well.

User experience is more like MSVS than a standalone disassembler. I like code reading more than in Reflector. Ctrl+T navigation suits me better too. Just synchronizing the tree with the code pane could be better.

All in all, it is still in development but very well usable already.

How to add font-awesome to Angular 2 + CLI project

I wasted several hours trying to get the latest version of FontAwesome 5.2.0 working with AngularCLI 6.0.3 and Material Design. I followed the npm installation instructions off of the FontAwesome website

Their latest docs instruct you do install using the following:

npm install @fortawesome/fontawesome-free

After wasting several hours I finally uninstalled it and installed font awesome using the following command (this installs FontAwesome v4.7.0):

npm install font-awesome --save

Now it's working fine using:

$fa-font-path: "~font-awesome/fonts" !default;
@import "~font-awesome/scss/font-awesome.scss";
<mat-icon fontSet="fontawesome" fontIcon="fa-android"></mat-icon>

How to check if a Ruby object is a Boolean

An object that is a boolean will either have a class of TrueClass or FalseClass so the following one-liner should do the trick

mybool = true
mybool.class == TrueClass || mybool.class == FalseClass
=> true

The following would also give you true/false boolean type check result

mybool = true    
[TrueClass, FalseClass].include?(mybool.class)
=> true

How to insert an element after another element in JavaScript without using a library?

a robust implementation of insertAfter.

// source: https://github.com/jserz/domPlus/blob/master/src/insertAfter()/insertAfter.js
Node.prototype.insertAfter = Node.prototype.insertAfter || function (newNode, referenceNode) {
  function isNode(node) {
    return node instanceof Node;
  }

  if(arguments.length < 2){
    throw(new TypeError("Failed to execute 'insertAfter' on 'Node': 2 arguments required, but only "+ arguments.length +" present."));
  }

  if(isNode(newNode)){
    if(referenceNode === null || referenceNode === undefined){
      return this.insertBefore(newNode, referenceNode);
    }

    if(isNode(referenceNode)){
      return this.insertBefore(newNode, referenceNode.nextSibling);
    }

    throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 2 is not of type 'Node'."));
  }

  throw(new TypeError("Failed to execute 'insertAfter' on 'Node': parameter 1 is not of type 'Node'."));
};

Convert 24 Hour time to 12 Hour plus AM/PM indication Oracle SQL

For the 24-hour time, you need to use HH24 instead of HH.

For the 12-hour time, the AM/PM indicator is written as A.M. (if you want periods in the result) or AM (if you don't). For example:

SELECT invoice_date,
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH24:MI:SS') "Date 24Hr",
       TO_CHAR(invoice_date, 'DD-MM-YYYY HH:MI:SS AM') "Date 12Hr"
  FROM invoices
;

For more information on the format models you can use with TO_CHAR on a date, see http://docs.oracle.com/cd/E16655_01/server.121/e17750/ch4datetime.htm#NLSPG004.

Echo tab characters in bash script

Using echo to print values of variables is a common Bash pitfall. Reference link:

http://mywiki.wooledge.org/BashPitfalls#echo_.24foo

How to insert &nbsp; in XSLT

Try to use

<xsl:text>&#160;</xsl:text>

But it depends on XSLT processor you are using: the XSLT spec does not require XSLT processors to convert it into "&nbsp;".

How can I express that two values are not equal to eachother?

"Not equals" can be expressed with the "not" operator ! and the standard .equals.

if (a.equals(b)) // a equals b
if (!a.equals(b)) // a not equal to b

How can I use the HTML5 canvas element in IE?

The page is using excanvas - a JS library that simulates the canvas element using IE's VML renderer.

Note that in Internet Explorer 9, the canvas tag is supported natively! See MSDN docs for details...

storing user input in array

You're not actually going out after the values. You would need to gather them like this:

var title   = document.getElementById("title").value;
var name    = document.getElementById("name").value;
var tickets = document.getElementById("tickets").value;

You could put all of these in one array:

var myArray = [ title, name, tickets ];

Or many arrays:

var titleArr   = [ title ];
var nameArr    = [ name ];
var ticketsArr = [ tickets ];

Or, if the arrays already exist, you can use their .push() method to push new values onto it:

var titleArr = [];

function addTitle ( title ) {
  titleArr.push( title );
  console.log( "Titles: " + titleArr.join(", ") );
}

Your save button doesn't work because you refer to this.form, however you don't have a form on the page. In order for this to work you would need to have <form> tags wrapping your fields:

I've made several corrections, and placed the changes on jsbin: http://jsbin.com/ufanep/2/edit

The new form follows:

<form>
  <h1>Please enter data</h1>
  <input id="title" type="text" />
  <input id="name" type="text" />
  <input id="tickets" type="text" />
  <input type="button" value="Save" onclick="insert()" />
  <input type="button" value="Show data" onclick="show()" />
</form>
<div id="display"></div>

There is still some room for improvement, such as removing the onclick attributes (those bindings should be done via JavaScript, but that's beyond the scope of this question).

I've also made some changes to your JavaScript. I start by creating three empty arrays:

var titles  = [];
var names   = [];
var tickets = [];

Now that we have these, we'll need references to our input fields.

var titleInput  = document.getElementById("title");
var nameInput   = document.getElementById("name");
var ticketInput = document.getElementById("tickets");

I'm also getting a reference to our message display box.

var messageBox  = document.getElementById("display");

The insert() function uses the references to each input field to get their value. It then uses the push() method on the respective arrays to put the current value into the array.

Once it's done, it cals the clearAndShow() function which is responsible for clearing these fields (making them ready for the next round of input), and showing the combined results of the three arrays.

function insert ( ) {
 titles.push( titleInput.value );
 names.push( nameInput.value );
 tickets.push( ticketInput.value );

 clearAndShow();
}

This function, as previously stated, starts by setting the .value property of each input to an empty string. It then clears out the .innerHTML of our message box. Lastly, it calls the join() method on all of our arrays to convert their values into a comma-separated list of values. This resulting string is then passed into the message box.

function clearAndShow () {
  titleInput.value = "";
  nameInput.value = "";
  ticketInput.value = "";

  messageBox.innerHTML = "";

  messageBox.innerHTML += "Titles: " + titles.join(", ") + "<br/>";
  messageBox.innerHTML += "Names: " + names.join(", ") + "<br/>";
  messageBox.innerHTML += "Tickets: " + tickets.join(", ");
}

The final result can be used online at http://jsbin.com/ufanep/2/edit

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

Between matplotlib+pylab and NumPy I don't think there's much actual difference between Matlab and python other than cultural inertia as suggested by @Adam Bellaire.

Java JDBC - How to connect to Oracle using Service Name instead of SID

So there are two easy ways to make this work. The solution posted by Bert F works fine if you don't need to supply any other special Oracle-specific connection properties. The format for that is:

jdbc:oracle:thin:@//HOSTNAME:PORT/SERVICENAME

However, if you need to supply other Oracle-specific connection properties then you need to use the long TNSNAMES style. I had to do this recently to enable Oracle shared connections (where the server does its own connection pooling). The TNS format is:

jdbc:oracle:thin:@(description=(address=(host=HOSTNAME)(protocol=tcp)(port=PORT))(connect_data=(service_name=SERVICENAME)(server=SHARED)))

If you're familiar with the Oracle TNSNAMES file format, then this should look familiar to you. If not then just Google it for the details.

How to read barcodes with the camera on Android?

2016 update

With the latest release of Google Play Services, v7.8, you have access to the new Mobile Vision API. That's probably the most convenient way to implement barcode scanning now, and it also works offline.

From the Android Barcode API:

The Barcode API detects barcodes in real-time, on device, in any orientation. It can also detect multiple barcodes at once.

It reads the following barcode formats:

  • 1D barcodes: EAN-13, EAN-8, UPC-A, UPC-E, Code-39, Code-93, Code-128, ITF, Codabar
  • 2D barcodes: QR Code, Data Matrix, PDF-417, AZTEC

It automatically parses QR Codes, Data Matrix, PDF-417, and Aztec values, for the following supported formats:

  • URL
  • Contact information (VCARD, etc.)
  • Calendar event
  • Email
  • Phone
  • SMS
  • ISBN
  • WiFi
  • Geo-location (latitude and longitude)
  • AAMVA driver license/ID

Tried to Load Angular More Than Once

For anyone that has this issue in the future, for me it was caused by an arrow function instead of a function literal in a run block:

// bad
module('a').run(() => ...)

// good
module('a').run(function() {...})

H.264 file size for 1 hr of HD video

It would be a couple of gigs per hour.

MPEG-4 (of which H.264 is a sub-part) define high quality as around 4Mbps. which would be 1.8GB per hour.

This can vary depending on the type of video and the type of compression used.

add a string prefix to each value in a string column using Pandas

If you load you table file with dtype=str
or convert column type to string df['a'] = df['a'].astype(str)
then you can use such approach:

df['a']= 'col' + df['a'].str[:]

This approach allows prepend, append, and subset string of df.
Works on Pandas v0.23.4, v0.24.1. Don't know about earlier versions.

select the TOP N rows from a table

you can also check this link

SELECT * FROM master_question WHERE 1 ORDER BY question_id ASC LIMIT 20

for more detail click here

Integrity constraint violation: 1452 Cannot add or update a child row:

I just exported the table deleted and then imported it again and it worked for me. This was because i deleted the parent table(users) and then recreated it and child table(likes) has the foreign key to parent table(users).

How to calculate probability in a normal distribution given mean & standard deviation?

Here is more info. First you are dealing with a frozen distribution (frozen in this case means its parameters are set to specific values). To create a frozen distribution:

import scipy.stats
scipy.stats.norm(loc=100, scale=12)
#where loc is the mean and scale is the std dev
#if you wish to pull out a random number from your distribution
scipy.stats.norm.rvs(loc=100, scale=12)

#To find the probability that the variable has a value LESS than or equal
#let's say 113, you'd use CDF cumulative Density Function
scipy.stats.norm.cdf(113,100,12)
Output: 0.86066975255037792
#or 86.07% probability

#To find the probability that the variable has a value GREATER than or
#equal to let's say 125, you'd use SF Survival Function 
scipy.stats.norm.sf(125,100,12)
Output: 0.018610425189886332
#or 1.86%

#To find the variate for which the probability is given, let's say the 
#value which needed to provide a 98% probability, you'd use the 
#PPF Percent Point Function
scipy.stats.norm.ppf(.98,100,12)
Output: 124.64498692758187

Convert PEM traditional private key to PKCS8 private key

Try using following command. I haven't tried it but I think it should work.

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

Cannot start MongoDB as a service

Following works with MongoDB 3.6.0

Make sure you have these folders:

  • C:\mongodb\data
  • C:\mongodb\data\db

Then all you need are these commands:

  • mongod --directoryperdb -dbpath C:\mongodb\data\db --logpath C:\mongodb\log\mongo.log --logappend --service --install
  • net start MongoDB
  • mongo

How can I use JQuery to post JSON data?

Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.

var DoPost = function(url, body) {
    try {
        body = JSON.stringify(body);
    } catch (error) {
        return reject(error);
    }
    return new Promise((resolve, reject) => {
        $.ajax({
                type: 'POST',
                url: url,
                data: body,
                contentType: "application/json",
                dataType: 'json'
            })
            .done(function(data) {
                return resolve(data);
            })
            .fail(function(error) {
                console.error(error);
                return reject(error);
            })
            .always(function() {
                // called after done or fail
            });
    });
}

How do I get a file's last modified time in Perl?

You need the stat call, and the file name:

my $last_mod_time = (stat ($file))[9];

Perl also has a different version:

my $last_mod_time = -M $file;

but that value is relative to when the program started. This is useful for things like sorting, but you probably want the first version.

Implementation difference between Aggregation and Composition in Java

I would use a nice UML example.

Take a university that has 1 to 20 different departments and each department has 1 to 5 professors. There is a composition link between a University and its' departments. There is an aggregation link between a department and its' professors.

Composition is just a STRONG aggregation, if the university is destroyed then the departments should also be destroyed. But we shouldn't kill the professors even if their respective departments disappear.

In java :

public class University {

     private List<Department> departments;

     public void destroy(){
         //it's composition, when I destroy a university I also destroy the departments. they cant live outside my university instance
         if(departments!=null)
             for(Department d : departments) d.destroy();
         departments.clean();
         departments = null;
     }
}

public class Department {

     private List<Professor> professors;
     private University university;

     Department(University univ){
         this.university = univ;
         //check here univ not null throw whatever depending on your needs
     }

     public void destroy(){
         //It's aggregation here, we just tell the professor they are fired but they can still keep living
         for(Professor p:professors)
             p.fire(this);
         professors.clean();
         professors = null;
     }
}

public class Professor {

     private String name;
     private List<Department> attachedDepartments;

     public void destroy(){

     }

     public void fire(Department d){
         attachedDepartments.remove(d);
     }
}

Something around this.

EDIT: an example as requested

public class Test
{
    public static void main(String[] args)
    {
        University university = new University();
        //the department only exists in the university
        Department dep = university.createDepartment();
        // the professor exists outside the university
        Professor prof = new Professor("Raoul");
        System.out.println(university.toString());
        System.out.println(prof.toString());

        dep.assign(prof);
        System.out.println(university.toString());
        System.out.println(prof.toString());
        dep.destroy();

        System.out.println(university.toString());
        System.out.println(prof.toString());

    }


}

University class

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class University {

    private List<Department> departments = new ArrayList<>();

    public Department createDepartment() {
        final Department dep = new Department(this, "Math");
        departments.add(dep);
        return dep;
    }

    public void destroy() {
        System.out.println("Destroying university");
        //it's composition, when I destroy a university I also destroy the departments. they cant live outside my university instance
        if (departments != null)
            departments.forEach(Department::destroy);
        departments = null;
    }

    @Override
    public String toString() {
        return "University{\n" +
                "departments=\n" + departments.stream().map(Department::toString).collect(Collectors.joining("\n")) +
                "\n}";
    }
}

Department class

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class Department {

    private final String name;
    private List<Professor> professors = new ArrayList<>();
    private final University university;

    public Department(University univ, String name) {
        this.university = univ;
        this.name = name;
        //check here univ not null throw whatever depending on your needs
    }

    public void assign(Professor p) {
        //maybe use a Set here
        System.out.println("Department hiring " + p.getName());
        professors.add(p);
        p.join(this);
    }

    public void fire(Professor p) {
        //maybe use a Set here
        System.out.println("Department firing " + p.getName());
        professors.remove(p);
        p.quit(this);
    }

    public void destroy() {
        //It's aggregation here, we just tell the professor they are fired but they can still keep living
        System.out.println("Destroying department");
        professors.forEach(professor -> professor.quit(this));
        professors = null;
    }

    @Override
    public String toString() {
        return professors == null
                ? "Department " + name + " doesn't exists anymore"
                : "Department " + name + "{\n" +
                "professors=" + professors.stream().map(Professor::toString).collect(Collectors.joining("\n")) +
                "\n}";
    }
}

Professor class

import java.util.ArrayList;
import java.util.List;

public class Professor {

    private final String name;
    private final List<Department> attachedDepartments = new ArrayList<>();

    public Professor(String name) {
        this.name = name;
    }

    public void destroy() {

    }

    public void join(Department d) {
        attachedDepartments.add(d);
    }

    public void quit(Department d) {
        attachedDepartments.remove(d);
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "Professor " + name + " working for " + attachedDepartments.size() + " department(s)\n";
    }
}

The implementation is debatable as it depends on how you need to handle creation, hiring deletion etc. Unrelevant for the OP

Finding the Eclipse Version Number

1 - Open Eclipse IDE. 2 - Press: Alt + H 3 - Use keyboard arrows to go dwn the list 4 - Select About Eclipse IDE tab.

Any way to make plot points in scatterplot more transparent in R?

If you are using the hex codes, you can add two more digits at the end of the code to represent the alpha channel:

E.g. half-transparency red:

plot(1:100, main="Example of Plot With Transparency")
lines(1:100 + sin(1:100*2*pi/(20)), col='#FF000088', lwd=4)
mtext("use `col='#FF000088'` for the lines() function")

example plot of color with transparency

How to solve java.lang.NullPointerException error?

This error occures when you try to refer to a null object instance. I can`t tell you what causes this error by your given information, but you can debug it easily in your IDE. I strongly recommend you that use exception handling to avoid unexpected program behavior.

how to remove css property using javascript?

element.style.height = null;

output:

<div style="height:100px;"> 
// results: 
<div style="">

Is there any kind of hash code function in JavaScript?

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol

you can use Es6 symbol to create unique key and access object. Every symbol value returned from Symbol() is unique. A symbol value may be used as an identifier for object properties; this is the data type's only purpose.

var obj = {};

obj[Symbol('a')] = 'a';
obj[Symbol.for('b')] = 'b';
obj['c'] = 'c';
obj.d = 'd';

How can I create Min stl priority_queue?

You can do it in multiple ways:
1. Using greater as comparison function :

 #include <bits/stdc++.h>

using namespace std;

int main()
{
    priority_queue<int,vector<int>,greater<int> >pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<< " ";
    }
    return 0;
}

2. Inserting values by changing their sign (using minus (-) for positive number and using plus (+) for negative number :

int main()
{
    priority_queue<int>pq2;
    pq2.push(-1); //for +1
    pq2.push(-2); //for +2
    pq2.push(-3); //for +3
    pq2.push(4);  //for -4

    while(!pq2.empty())
    {
        int r = pq2.top();
        pq2.pop();
        cout<<-r<<" ";
    }

    return 0;
}

3. Using custom structure or class :

struct compare
{
    bool operator()(const int & a, const int & b)
    {
        return a>b;
    }
};

int main()
{

    priority_queue<int,vector<int>,compare> pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<<" ";
    }

    return 0;
}

4. Using custom structure or class you can use priority_queue in any order. Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.

    struct people
    {
        int age,salary;

    };
    struct compare{
    bool operator()(const people & a, const people & b)
        {
            if(a.salary==b.salary)
            {
                return a.age>b.age;
            }
            else
            {
                return a.salary>b.salary;
            }

    }
    };
    int main()
    {

        priority_queue<people,vector<people>,compare> pq;
        people person1,person2,person3;
        person1.salary=100;
        person1.age = 50;
        person2.salary=80;
        person2.age = 40;
        person3.salary = 100;
        person3.age=40;


        pq.push(person1);
        pq.push(person2);
        pq.push(person3);

        while(!pq.empty())
        {
            people r = pq.top();
            pq.pop();
            cout<<r.salary<<" "<<r.age<<endl;
    }
  1. Same result can be obtained by operator overloading :

    struct people
    {
    int age,salary;
    
    bool operator< (const people & p)const
    {
        if(salary==p.salary)
        {
            return age>p.age;
        }
        else
        {
            return salary>p.salary;
        }
    }};
    

    In main function :

    priority_queue<people> pq;
    people person1,person2,person3;
    person1.salary=100;
    person1.age = 50;
    person2.salary=80;
    person2.age = 40;
    person3.salary = 100;
    person3.age=40;
    
    
    pq.push(person1);
    pq.push(person2);
    pq.push(person3);
    
    while(!pq.empty())
    {
        people r = pq.top();
        pq.pop();
        cout<<r.salary<<" "<<r.age<<endl;
    }
    

relative path in BAT script

Use this in your batch file:

%~dp0\bin\Iris.exe

%~dp0 resolves to the full path of the folder in which the batch script resides.

Using lodash to compare jagged arrays (items existence without order)

PURE JS (works also when arrays and subarrays has more than 2 elements with arbitrary order). If strings contains , use as join('-') parametr character (can be utf) which is not used in strings

array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join()

_x000D_
_x000D_
var array1 = [['a', 'b'], ['b', 'c']];_x000D_
var array2 = [['b', 'c'], ['b', 'a']];_x000D_
_x000D_
var r = array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join();_x000D_
_x000D_
console.log(r);
_x000D_
_x000D_
_x000D_

alternative to "!is.null()" in R

I have also seen:

if(length(obj)) {
  # do this if object has length
  # NULL has no length
}

I don't think it's great though. Because some vectors can be of length 0. character(0), logical(0), integer(0) and that might be treated as a NULL instead of an error.

JSON Parse File Path

This solution uses an Asynchronous call. It will likely work better than a synchronous solution.

var request = new XMLHttpRequest();
request.open("GET", "../../data/file.json", false);
request.send(null);
request.onreadystatechange = function() {
  if ( request.readyState === 4 && request.status === 200 ) {
    var my_JSON_object = JSON.parse(request.responseText);
    console.log(my_JSON_object);
  }
}

How to convert a boolean array to an int array

The 1*y method works in Numpy too:

>>> import numpy as np
>>> x = np.array([4, 3, 2, 1])
>>> y = 2 >= x
>>> y
array([False, False,  True,  True], dtype=bool)
>>> 1*y                      # Method 1
array([0, 0, 1, 1])
>>> y.astype(int)            # Method 2
array([0, 0, 1, 1]) 

If you are asking for a way to convert Python lists from Boolean to int, you can use map to do it:

>>> testList = [False, False,  True,  True]
>>> map(lambda x: 1 if x else 0, testList)
[0, 0, 1, 1]
>>> map(int, testList)
[0, 0, 1, 1]

Or using list comprehensions:

>>> testList
[False, False, True, True]
>>> [int(elem) for elem in testList]
[0, 0, 1, 1]

Synchronous XMLHttpRequest warning and <script>

if you just need to load script dont do as bellow

$(document.body).html('<script type="text/javascript" src="/json.js" async="async"><\/script>');

Try this

var scriptEl = document.createElement('SCRIPT');
    scriptEl.src = "/module/script/form?_t="+(new Date()).getTime();
    //$('#holder').append(scriptEl) // <--- create warning
    document.body.appendChild(scriptEl);

Android SeekBar setOnSeekBarChangeListener

I hope this will help you:

final TextView t1=new TextView(this); 
t1.setText("Hello Android");        
final SeekBar sk=(SeekBar) findViewById(R.id.seekBar1);     
sk.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {       

    @Override       
    public void onStopTrackingTouch(SeekBar seekBar) {      
        // TODO Auto-generated method stub      
    }       

    @Override       
    public void onStartTrackingTouch(SeekBar seekBar) {     
        // TODO Auto-generated method stub      
    }       

    @Override       
    public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {     
        // TODO Auto-generated method stub      

        t1.setTextSize(progress);
        Toast.makeText(getApplicationContext(), String.valueOf(progress),Toast.LENGTH_LONG).show();

    }       
});             

Can't import Numpy in Python

Your sys.path is kind of unusual, as each entry is prefixed with /usr/intel. I guess numpy is installed in the usual non-prefixed place, e.g. it. /usr/share/pyshared/numpy on my Ubuntu system.

Try find / -iname '*numpy*'

Division in Python 2.7. and 3.3

"/" is integer division in python 2 so it is going to round to a whole number. If you would like a decimal returned, just change the type of one of the inputs to float:

float(20)/15 #1.33333333

How to find the last day of the month from date?

You could create a date for the first of the next month, and then use strtotime("-1 day", $firstOfNextMonth)

How to compare timestamp dates with date-only parameter in MySQL?

Use a conversion function of MYSQL :

SELECT * FROM table WHERE DATE(timestamp) = '2012-05-05' 

This should work

Setting default permissions for newly created files and sub-directories under a directory in Linux?

in your shell script (or .bashrc) you may use somthing like:

umask 022

umask is a command that determines the settings of a mask that controls how file permissions are set for newly created files.

Today's Date in Perl in MM/DD/YYYY format

You can do it fast, only using one POSIX function. If you have bunch of tasks with dates, see the module DateTime.

use POSIX qw(strftime);

my $date = strftime "%m/%d/%Y", localtime;
print $date;

What is the simplest and most robust way to get the user's current location on Android?

EDIT: Updated with the latest Location Service API from Google Play Services library (July 2014)

I would recommend you to use the new Location Service API, available from the Google Play Services library, which provides a more powerful, high-level framework that automates tasks such as location provider choice and power management. According to the official documentation: "... Location API make it easy for you to build location-aware applications, without needing to focus on the details of the underlying location technology. They also let you minimize power consumption by using all of the capabilities of the device hardware."

For further information visit: Making Your App Location-Aware

To see a full example using the latest Location Service API visit: Android LocationClient class is deprecated but used in documentation

How do I get into a Docker container's shell?

For docker-compose up (Docker4Drupal)

docker-compose exec php bash

I use Docker for Drupal on a Linux laptop. After running the container I use 'docker-compose exec php bash' to connect with the container so I can run drush commandos. It works fine for me.

Store mysql query output into a shell variable

myvariable=$(mysql -u user -p'password' -s -N <<QUERY_INPUT
    use databaseName;
    SELECT fieldName FROM tablename WHERE filedName='fieldValue';
QUERY_INPUT
)
echo "myvariable=$myvariable"

HTML5 Pre-resize images before uploading

The accepted answer works great, but the resize logic ignores the case in which the image is larger than the maximum in only one of the axes (for example, height > maxHeight but width <= maxWidth).

I think the following code takes care of all cases in a more straight-forward and functional way (ignore the typescript type annotations if using plain javascript):

private scaleDownSize(width: number, height: number, maxWidth: number, maxHeight: number): {width: number, height: number} {
    if (width <= maxWidth && height <= maxHeight)
      return { width, height };
    else if (width / maxWidth > height / maxHeight)
      return { width: maxWidth, height: height * maxWidth / width};
    else
      return { width: width * maxHeight / height, height: maxHeight };
  }

How to start new activity on button click

Start another activity from this activity and u can pass parameters via Bundle Object also.

Intent intent = new Intent(getBaseContext(), YourActivity.class);
intent.putExtra("USER_NAME", "[email protected]");
startActivity(intent);

Retrive data in another activity (YourActivity)

String s = getIntent().getStringExtra("USER_NAME");

Onclick on bootstrap button

Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:

$('#myButton').on('click', function(event) {
  event.preventDefault(); // To prevent following the link (optional)
  ...
});

You can also use inline javascript in the onclick attribute:

<a ... onclick="myFunc();">..</a>

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

I've found that using the Moment.js library with some of the concepts described here (comparing Jan to June) works very well.

This simple function will return whether the timezone that the user is in observes Daylight Saving Time:

function HasDST() {
    return moment([2017, 1, 1]).isDST() != moment([2017, 6, 1]).isDST();
}

A simple way to check that this works (on Windows) is to change your timezone to a non DST zone, for example Arizona will return false, whereas EST or PST will return true.

enter image description here

bash shell nested for loop

#!/bin/bash
# loop*figures.bash

for i in 1 2 3 4 5  # First loop.
do
    for j in $(seq 1 $i)
    do
        echo  -n "*" 
    done
    echo 
done
echo
# outputs
# *
# **
# ***
# ****
# *****

for i in 5 4 3 2 1 # First loop.
do
    for j in $(seq -$i -1)
    do
        echo  -n "*" 
    done
    echo 
done

# outputs
# *****
# ****
# ***
# **
# *

for i in 1 2 3 4 5  # First loop.
do
    for k in $(seq -5 -$i)
    do
        echo -n ' '
    done
    for j in $(seq 1 $i)
    do
        echo  -n "* " 
    done
    echo 
done
echo

# outputs
#     * 
#    * * 
#   * * * 
#  * * * * 
# * * * * * 

for i in 1 2 3 4 5  # First loop.
do
    for j in $(seq -5 -$i)
    do
        echo  -n "* " 
    done
    echo 
    for k in $(seq 1 $i)
    do
        echo -n ' '
    done
done
echo

# outputs
# * * * * * 
#  * * * * 
#   * * * 
#    * * 
#     *


exit 0

spring data jpa @query and pageable

With @Query , we can use pagination as well where you need to pass object of Pageable class at end of JPA method

For example:

Pageable pageableRequest = new PageRequest(page, size, Sort.Direction.DESC, rollNo);

Where, page = index of page (index start from zero)
size = No. of records
Sort.Direction = Sorting as per rollNo
rollNo = Field in User class

UserRepository repo
repo.findByFirstname("John", pageableRequest);

public interface UserRepository extends JpaRepository<User, Long> {

  @Query(value = "SELECT * FROM USER WHERE FIRSTNAME = :firstname)
  Page<User> findByLastname(@Param("firstname") String firstname, Pageable pageable);
}

CSS background-image - What is the correct usage?

1) putting quotes is a good habit

2) it can be relative path for example:

background-image: url('images/slides/background.jpg');

will look for images folder in the folder from which css is loaded. So if images are in another folder or out of the CSS folder tree you should use absolute path or relative to the root path (starting with /)

3) you should use complete declaration for background-image to make it behave consistently across standards compliant browsers like:

background:blue url('/images/clouds.jpg') no-repeat scroll left center;

Return values from the row above to the current row

You can also use =OFFSET([@column];-1;0) if you are in a named table.

SQL: IF clause within WHERE clause

To clarify some of the logical equivalence solutions.

An if statement

if (a) then b

is logically equivalent to

(!a || b)

It's the first line on the Logical equivalences involving conditional statements section of the Logical equivalence wikipedia article.

To include the else, all you would do is add another conditional

if(a) then b; 
if(!a) then c;

which is logically equivalent to (!a || b) && (a || c)

So using the OP as an example:

IF IsNumeric(@OrderNumber) = 1
    OrderNumber = @OrderNumber
ELSE
    OrderNumber LIKE '%' + @OrderNumber + '%'

the logical equivalent would be:

(IsNumeric(@OrderNumber) <> 1 OR OrderNumber = @OrderNumber)
AND (IsNumeric(@OrderNumber) = 1 OR OrderNumber LIKE '%' + @OrderNumber + '%' )

jquery mobile background image

Try this. This should work:

<div data-role="page" id="page" style="background-image: url('#URL'); background-attachment: fixed; background-repeat: no-repeat; background-size: 100% 100%;"
    data-theme="a">

JavaScript calculate the day of the year (1 - 366)

I think this is more straightforward:

var date365 = 0;

var currentDate = new Date();
var currentYear = currentDate.getFullYear();
var currentMonth = currentDate.getMonth(); 
var currentDay = currentDate.getDate(); 

var monthLength = [31,28,31,30,31,30,31,31,30,31,30,31];

var leapYear = new Date(currentYear, 1, 29); 
if (leapYear.getDate() == 29) { // If it's a leap year, changes 28 to 29
    monthLength[1] = 29;
}

for ( i=0; i < currentMonth; i++ ) { 
    date365 = date365 + monthLength[i];
}
date365 = date365 + currentDay; // Done!

Class has no member named

The reason that the error is occuring is because all the files are not being recognized as being in the same project directory. The easiest way to fix this is to simply create a new project.

File -> Project -> Console application -> Next -> select C or C++ -> Name the project and select the folder to create the project in -> then click finish.

Then to create the class and header files by clicking New -> Class. Give the class a name and uncheck "Use relative path." Make sure you are creating the class and header file in the same project folder.

After these steps, the left side of the IDE will display the Sources and Headers folders, with main.cpp, theclassname.cpp, and theclassname.h all conviently arranged.

How to install Java 8 on Mac

I'm having the same problem to solve, because I need to install JDK8 to run Android SDK Manager (because it seems that don't work well with JDK9). However, I tell you how I solve all problems on a Mac (Sierra).

First, you need brew with cask and jenv.

  1. You can find an useful guide here,Homebrew Cask Installation Guide. Remember to tap 'caskroom/versions' running in the terminal: brew tap caskroom/versions
  2. After that, install jenv with: brew install jenv
  3. Install whatever version you want with cask brew cask install java8 (or java7 or java if you want to install the latest version, jdk9)
  4. The last step is to configure which version to run (and let jenv to manage your JAVA_HOME) jenv versions to list all versions installed on your machine and then activate the one you want with jenv global [JDK_NAME_OF_LIST]

You could find other useful informations here on this Github Gist brew-java-and-jenv.md, on this blog Install multiple JDK on a Mac and on Jenv Website

How can I override the OnBeforeUnload dialog and replace it with my own?

I faced the same problem, I was ok to get its own dialog box with my message, but the problem I faced was : 1) It was giving message on all navigations I want it only for close click. 2) with my own confirmation message if user selects cancel it still shows the browser's default dialog box.

Following is the solutions code I found, which I wrote on my Master page.

function closeMe(evt) {
    if (typeof evt == 'undefined') {
        evt = window.event; }
    if (evt && evt.clientX >= (window.event.screenX - 150) &&
        evt.clientY >= -150 && evt.clientY <= 0) {
        return "Do you want to log out of your current session?";
    }
}
window.onbeforeunload = closeMe;

jQuery Ajax requests are getting cancelled without being sent

I had the same problem, but in my case it turned out to be a cookie issue. The guys working on the back-end had changed the path of the JSESSIONID cookie that's set when we log in to our app, and I had an old cookie by that name on my computer, but with the old path. So when I tried logging in the browser (Chrome) sent two cookies called JSESSIONID, with different values, to the server - which understandably confused it - so it cancelled the request. Deleting the cookies from my computer fixed it.

warning: assignment makes integer from pointer without a cast

What Jeremiah said, plus the compiler issues the warning because the production:

*src ="anotherstring";

says: take the address of "anotherstring" -- "anotherstring" IS a char pointer -- and store that pointer indirect through src (*src = ... ) into the first char of the string "abcdef..." The warning might be baffling because there is nowhere in your code any mention of any integer: the warning seems nonsensical. But, out of sight behind the curtain, is the rule that "int" and "char" are synonymous in terms of storage: both occupy the same number of bits. The compiler doesn't differentiate when it issues the warning that you are storing into an integer. Which, BTW, is perfectly OK and legal but probably not exactly what you want in this code.

-- pete

Pushing to Git returning Error Code 403 fatal: HTTP request failed

To definitely be able to login using https protocol, you should first set your authentication credential to the git Remote URI:

git remote set-url origin https://[email protected]/user/repo.git

Then you'll be asked for a password when trying to git push.

In fact, this is on the http authentication format. You could set a password too:

https://youruser:[email protected]/user/repo.git

You should be aware that if you do this, your github password will be stored in plaintext in your .git directory, which is obviously undesirable.

Centos/Linux setting logrotate to maximum file size for all logs

It specifies the size of the log file to trigger rotation. For example size 50M will trigger a log rotation once the file is 50MB or greater in size. You can use the suffix M for megabytes, k for kilobytes, and G for gigabytes. If no suffix is used, it will take it to mean bytes. You can check the example at the end. There are three directives available size, maxsize, and minsize. According to manpage:

minsize size
              Log  files  are  rotated when they grow bigger than size bytes,
              but not before the additionally specified time interval (daily,
              weekly,  monthly, or yearly).  The related size option is simi-
              lar except that it is mutually exclusive with the time interval
              options,  and  it causes log files to be rotated without regard
              for the last rotation time.  When minsize  is  used,  both  the
              size and timestamp of a log file are considered.

size size
              Log files are rotated only if they grow bigger then size bytes.
              If size is followed by k, the size is assumed to  be  in  kilo-
              bytes.  If the M is used, the size is in megabytes, and if G is
              used, the size is in gigabytes. So size 100,  size  100k,  size
              100M and size 100G are all valid.
maxsize size
              Log files are rotated when they grow bigger than size bytes even before
              the additionally specified time interval (daily, weekly, monthly, 
              or yearly).  The related size option is  similar  except  that  it 
              is mutually exclusive with the time interval options, and it causes
              log files to be rotated without regard for the last rotation time.  
              When maxsize is used, both the size and timestamp of a log file are                  
              considered.

Here is an example:

"/var/log/httpd/access.log" /var/log/httpd/error.log {
           rotate 5
           mail [email protected]
           size 100k
           sharedscripts
           postrotate
               /usr/bin/killall -HUP httpd
           endscript
       }

Here is an explanation for both files /var/log/httpd/access.log and /var/log/httpd/error.log. They are rotated whenever it grows over 100k in size, and the old logs files are mailed (uncompressed) to [email protected] after going through 5 rotations, rather than being removed. The sharedscripts means that the postrotate script will only be run once (after the old logs have been compressed), not once for each log which is rotated. Note that the double quotes around the first filename at the beginning of this section allows logrotate to rotate logs with spaces in the name. Normal shell quoting rules apply, with ,, and \ characters supported.

how to pass command line arguments to main method dynamically

We can pass string value to main method as argument without using commandline argument concept in java through Netbean

 package MainClass;
 import java.util.Scanner;
 public class CmdLineArgDemo {

static{
 Scanner readData = new Scanner(System.in);   
 System.out.println("Enter any string :");
 String str = readData.nextLine();
 String [] str1 = str.split(" ");
 // System.out.println(str1.length);
 CmdLineArgDemo.main(str1);
}  

   public static void main(String [] args){
      for(int i = 0 ; i<args.length;i++) {
        System.out.print(args[i]+" ");
      }
    }
  }

Output

Enter any string : 
Coders invent Digital World 
Coders invent Digital World

How to create streams from string in Node.Js?

in coffee-script:

class StringStream extends Readable
  constructor: (@str) ->
    super()

  _read: (size) ->
    @push @str
    @push null

use it:

new StringStream('text here').pipe(stream1).pipe(stream2)

How to request Administrator access inside a batch file

Ben Gripka's solution causes infinite loops. His batch works like this (pseudo code):

IF "no admin privileges?"
    "write a VBS that calls this batch with admin privileges"
ELSE
    "execute actual commands that require admin privileges"

As you can see, this causes an infinite loop, if the VBS fails requesting admin privileges.

However, the infinite loop can occur, although admin priviliges have been requested successfully.

The check in Ben Gripka's batch file is just error-prone. I played around with the batch and observed that admin privileges are available although the check failed. Interestingly, the check worked as expected, if I started the batch file from windows explorer, but it didn't when I started it from my IDE.

So I suggest to use two separate batch files. The first generates the VBS that calls the second batch file:

@echo off

echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
set params = %*:"=""
echo UAC.ShellExecute "cmd.exe", "/c ""%~dp0\my_commands.bat"" %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

"%temp%\getadmin.vbs"
del "%temp%\getadmin.vbs"

The second, named "my_commands.bat" and located in the same directory as the first contains your actual commands:

pushd "%CD%"
CD /D "%~dp0"
REM Your commands which require admin privileges here

This causes no infinite loops and also removes the error-prone admin privilege check.

How does tuple comparison work in Python?

The Python documentation does explain it.

Tuples and lists are compared lexicographically using comparison of corresponding elements. This means that to compare equal, each element must compare equal and the two sequences must be of the same type and have the same length.

How to get absolute path to file in /resources folder of your project

You can use ClassLoader.getResource method to get the correct resource.

URL res = getClass().getClassLoader().getResource("abc.txt");
File file = Paths.get(res.toURI()).toFile();
String absolutePath = file.getAbsolutePath();

OR

Although this may not work all the time, a simpler solution -

You can create a File object and use getAbsolutePath method:

File file = new File("resources/abc.txt");
String absolutePath = file.getAbsolutePath();

cast a List to a Collection

First Collection is class Interface and you can not instantiate. Collection API

List Ver APi is also an interface class.

It may be so

List list = Collections.synchronizedList(new ArrayList(...)); 

ver enter link description here

Collection collection= Collections.synchronizedList(new ArrayList(...)); 

Response.Redirect to new window

If you can re-structure your code so that you do not need to postback, then you can use this code in the PreRender event of the button:

protected void MyButton_OnPreRender(object sender, EventArgs e)
{
    string URL = "~/MyPage.aspx";
    URL = Page.ResolveClientUrl(URL);
    MyButton.OnClientClick = "window.open('" + URL + "'); return false;";
}

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

In this two queries, you are using JOIN to query all employees that have at least one department associated.

But, the difference is: in the first query you are returning only the Employes for the Hibernate. In the second query, you are returning the Employes and all Departments associated.

So, if you use the second query, you will not need to do a new query to hit the database again to see the Departments of each Employee.

You can use the second query when you are sure that you will need the Department of each Employee. If you not need the Department, use the first query.

I recomend read this link if you need to apply some WHERE condition (what you probably will need): How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

Update

If you don't use fetch and the Departments continue to be returned, is because your mapping between Employee and Department (a @OneToMany) are setted with FetchType.EAGER. In this case, any HQL (with fetch or not) query with FROM Employee will bring all Departments. Remember that all mapping *ToOne (@ManyToOne and @OneToOne) are EAGER by default.

How to enable Auto Logon User Authentication for Google Chrome

Chrome did change their menus since this question was asked. This solution was tested with Chrome 47.0.2526.73 to 72.0.3626.109.

If you are using Chrome right now, you can check your version with : chrome://version

  1. Goto: chrome://settings

  1. Scroll down to the bottom of the page and click on "Advanced" to show more settings.

OLDER VERSIONS:

Scroll down to the bottom of the page and click on "Show advanced settings..." to show more settings.

  1. In the "System" section, click on "Open proxy settings".

OLDER VERSIONS:

In the "Network" section, click on "Change proxy settings...".

  1. Click on the "Security" tab, then select "Local intranet" icon and click on "Sites" button.

  1. Click on "Advanced" button.

  1. Insert your intranet local address and click on the "Add" button.

  1. Close all windows.

That's it.

How do I run a file on localhost?

You can do it by running with following command.

php -S localhost:8888

How to compare numbers in bash?

If you have floats you can write a function and then use that e.g.

#!/bin/bash

function float_gt() {
    perl -e "{if($1>$2){print 1} else {print 0}}"
}

x=3.14
y=5.20
if [ $(float_gt $x $y) == 1 ] ; then
    echo "do stuff with x"
else
    echo "do stuff with y"
fi