Programs & Examples On #Unmodifiable

UnmodifiableMap (Java Collections) vs ImmutableMap (Google)

ImmutableMap does not accept null values whereas Collections.unmodifiableMap() does. In addition it will never change after construction, while UnmodifiableMap may. From the JavaDoc:

An immutable, hash-based Map with reliable user-specified iteration order. Does not permit null keys or values.

Unlike Collections.unmodifiableMap(java.util.Map), which is a view of a separate map which can still change, an instance of ImmutableMap contains its own data and will never change. ImmutableMap is convenient for public static final maps ("constant maps") and also lets you easily make a "defensive copy" of a map provided to your class by a caller.

Java Immutable Collections

Pure4J supports what you are after, in two ways.

First, it provides an @ImmutableValue annotation, so that you can annotate a class to say that it is immutable. There is a maven plugin to allow you to check that your code actually is immutable (use of final etc.).

Second, it provides the persistent collections from Clojure, (with added generics) and ensures that elements added to the collections are immutable. Performance of these is apparently pretty good. Collections are all immutable, but implement java collections interfaces (and generics) for inspection. Mutation returns new collections.

Disclaimer: I'm the developer of this

Java - How to convert type collection into ArrayList?

More information needed for a definitive answer, but this code

myNodeList = (ArrayList<MyNode>)this.getVertices();

will only work if this.getVertices() returns a (subtype of) List<MyNode>. If it is a different collection (like your Exception seems to indicate), you want to use

new ArrayList<MyNode>(this.getVertices())

This will work as long as a Collection type is returned by getVertices.

Primary key or Unique index?

There are no disadvantages of primary keys.

To add just some information to @MrWiggles and @Peter Parker answers, when table doesn't have primary key for example you won't be able to edit data in some applications (they will end up saying sth like cannot edit / delete data without primary key). Postgresql allows multiple NULL values to be in UNIQUE column, PRIMARY KEY doesn't allow NULLs. Also some ORM that generate code may have some problems with tables without primary keys.

UPDATE:

As far as I know it is not possible to replicate tables without primary keys in MSSQL, at least without problems (details).

What is a regular expression which will match a valid domain name without a subdomain?

Not enough rep yet to comment. In response to paka's solution, I found I needed to adjust three items:

  • The dash and underscore were moved due to the dash being interpreted as a range (as in "0-9")
  • Added a full stop for domain names with many subdomains
  • Extended the potential length for the TLDs to 13

Before:

^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][a-zA-Z0-9-_]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,6}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$

After:

^(([a-zA-Z]{1})|([a-zA-Z]{1}[a-zA-Z]{1})|([a-zA-Z]{1}[0-9]{1})|([0-9]{1}[a-zA-Z]{1})|([a-zA-Z0-9][-_\.a-zA-Z0-9]{1,61}[a-zA-Z0-9]))\.([a-zA-Z]{2,13}|[a-zA-Z0-9-]{2,30}\.[a-zA-Z]{2,3})$

What's the most elegant way to cap a number to a segment?

A simple way would be to use

Math.max(min, Math.min(number, max));

and you can obviously define a function that wraps this:

function clamp(number, min, max) {
  return Math.max(min, Math.min(number, max));
}

Originally this answer also added the function above to the global Math object, but that's a relic from a bygone era so it has been removed (thanks @Aurelio for the suggestion)

SQL Server: how to create a stored procedure

In T-SQL stored procedures for input parameters explicit 'in' keyword is not required and for output parameters an explicit 'Output' keyword is required. The query in question can be written as:

CREATE PROCEDURE dept_count 
    (
    -- Add input and output parameters for the stored procedure here
    @dept_name varchar(20), --Input parameter 
    @d_count int OUTPUT     -- Output parameter declared with the help of OUTPUT/OUT keyword
    ) 
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

     -- Statements for procedure here
    SELECT @d_count = count(*)
    from instructor
      where instructor.dept_name=@dept_name

END
GO

and to execute above procedure we can write as:

Declare @dept_name varchar(20), -- Declaring the variable to collect the dept_name
        @d_count int            -- Declaring the variable to collect the d_count 
SET @dept_name = 'Test'

Execute  dept_count @dept_name,@d_count output
SELECT   @d_count               -- "Select" Statement is used to show the output 

Command to get latest Git commit hash from a branch

Note that when using "git log -n 1 [branch_name]" option. -n returns only one line of log but order in which this is returned is not guaranteed. Following is extract from git-log man page

.....
.....
Commit Limiting

Besides specifying a range of commits that should be listed using the special notations explained in the     description, additional commit limiting may be applied.

Using more options generally further limits the output (e.g. --since=<date1> limits to commits newer than <date1>, and using it with --grep=<pattern> further limits to commits whose log message has a line that matches <pattern>), unless otherwise noted.

Note that these are applied before commit ordering and formatting options, such as --reverse.

-<number>
-n <number>
.....
.....

How to display HTML tags as plain text

Use htmlentities() to convert characters that would otherwise be displayed as HTML.

Reading my own Jar's Manifest

  public static Manifest getManifest( Class<?> cl ) {
    InputStream inputStream = null;
    try {
      URLClassLoader classLoader = (URLClassLoader)cl.getClassLoader();
      String classFilePath = cl.getName().replace('.','/')+".class";
      URL classUrl = classLoader.getResource(classFilePath);
      if ( classUrl==null ) return null;
      String classUri = classUrl.toString();
      if ( !classUri.startsWith("jar:") ) return null;
      int separatorIndex = classUri.lastIndexOf('!');
      if ( separatorIndex<=0 ) return null;
      String manifestUri = classUri.substring(0,separatorIndex+2)+"META-INF/MANIFEST.MF";
      URL url = new URL(manifestUri);
      inputStream = url.openStream();
      return new Manifest( inputStream );
    } catch ( Throwable e ) {
      // handle errors
      ...
      return null;
    } finally {
      if ( inputStream!=null ) {
        try {
          inputStream.close();
        } catch ( Throwable e ) {
          // ignore
        }
      }
    }
  }

Assign command output to variable in batch file

This is work for me

@FOR /f "delims=" %i in ('reg query hklm\SOFTWARE\Macromedia\FlashPlayer\CurrentVersion') DO set var=%i
echo %var%

LaTeX: remove blank page after a \part or \chapter

I believe that in the book class all \part and \chapter are set to start on a recto page.

from book.cls:

\newcommand\part{%
  \if@openright
    \cleardoublepage
  \else
    \clearpage
  \fi
  \thispagestyle{plain}%
  \if@twocolumn
    \onecolumn
    \@tempswatrue
  \else
    \@tempswafalse
  \fi
  \null\vfil
  \secdef\@part\@spart}

you should be able to renew that command, and something similar for the \chapter.

How do you declare an interface in C++?

A little addition to what's written up there:

First, make sure your destructor is also pure virtual

Second, you may want to inherit virtually (rather than normally) when you do implement, just for good measures.

laravel 5.3 new Auth::routes()

If you are searching these same routes for laravel 7 version you'll find it here Vendor/laravel/ui/src/AuthRouteMethods.php

How do I list loaded plugins in Vim?

If you use vim-plug (Plug), " A minimalist Vim plugin manager.":

:PlugStatus

That will not only list your plugins but check their status.

How to generate .json file with PHP?

Use PHP's json methods to create the json then write it to a file with fwrite.

Unknown column in 'field list' error on MySQL Update query

Just sharing my experience on this. I was having this same issue. My query was like:

select table1.column2 from table1

However, table1 did not have column2 column.

Convert alphabet letters to number in Python

If you are looking the opposite like 1 = A , 2 = B etc, you can use the following code. Please note that I have gone only up to 2 levels as I had to convert divisions in a class to A, B, C etc.

loopvariable = 0 
    numberofdivisions = 53
    while (loopvariable <numberofdivisions):
        if(loopvariable<26):
            print(chr(65+loopvariable))
        loopvariable +=1
        if(loopvariable > 26 and loopvariable <53):
            print(chr(65)+chr(65+(loopvariable-27)))

How to use find command to find all files with extensions from list?

find /path/to -regex ".*\.\(jpg\|gif\|png\|jpeg\)" > log

C++ int float casting

Because (a.y - b.y) is probably less then (a.x - b.x) and in your code the casting is done after the divide operation so the result is an integer so 0.

You should cast to float before the / operation

Favicon dimensions?

favicon.ico is 16x16

<link rel="shortcut icon" href="favicon.ico"/>

And I use these ones to be beautiful in mobile and tablet:

<link rel="apple-touch-icon-precomposed" sizes="144x144" href="img/ico144.png">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/ico114.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/ico72.png">
<link rel="apple-touch-icon-precomposed" href="img/ico57.png">

It's important to use the name "favicon.ico" in the root because many browsers will try to find there first.

Apply CSS rules if browser is IE

I prefer using a separate file for ie rules, as described earlier.

<!--[if IE]><link rel="stylesheet" type="text/css" href="ie-style.css"/><![endif]-->

And inside it you can set up rules for different versions of ie using this:

.abc {...} /* ALL MSIE */
*html *.abc {...} /* MSIE 6 */
*:first-child+html .abc {...} /* MSIE 7 */

how to remove empty strings from list, then remove duplicate values from a list

To simplify Amiram Korach's solution:

dtList.RemoveAll(s => string.IsNullOrWhiteSpace(s))

No need to use Distinct() or ToList()

CodeIgniter activerecord, retrieve last insert id?

$this->db->insert_id()  

//please try this

how to use getSharedPreferences in android

After reading around alot, only this worked: In class to set Shared preferences:

 SharedPreferences userDetails = getApplicationContext().getSharedPreferences("test", MODE_PRIVATE);
                    SharedPreferences.Editor edit = userDetails.edit();
                    edit.clear();
                    edit.putString("test1", "1");
                    edit.putString("test2", "2");
                    edit.commit();

In AlarmReciever:

SharedPreferences userDetails = context.getSharedPreferences("test", Context.MODE_PRIVATE);
    String test1 = userDetails.getString("test1", "");
    String test2 = userDetails.getString("test2", "");

Connecting to SQL Server Express - What is my server name?

by default -

you can also log in to sql express using server name as:

./SQLEXPRESS

or log in to sql server simply as

.

How to convert a currency string to a double with jQuery or Javascript?

This worked for me and covers most edge cases :)

function toFloat(num) {
  const cleanStr = String(num).replace(/[^0-9.,]/g, '');
  let dotPos = cleanStr.indexOf('.');
  let commaPos = cleanStr.indexOf(',');

  if (dotPos < 0) dotPos = 0;

  if (commaPos < 0) commaPos = 0;

  const dotSplit = cleanStr.split('.');
  const commaSplit = cleanStr.split(',');

  const isDecimalDot = dotPos
    && (
      (commaPos && dotPos > commaPos)
      || (!commaPos && dotSplit[dotSplit.length - 1].length === 2)
    );

  const isDecimalComma = commaPos
    && (
      (dotPos && dotPos < commaPos)
      || (!dotPos && commaSplit[commaSplit.length - 1].length === 2)
    );

  let integerPart = cleanStr;
  let decimalPart = '0';
  if (isDecimalComma) {
    integerPart = commaSplit[0];
    decimalPart = commaSplit[1];
  }
  if (isDecimalDot) {
    integerPart = dotSplit[0];
    decimalPart = dotSplit[1];
  }

  return parseFloat(
    `${integerPart.replace(/[^0-9]/g, '')}.${decimalPart.replace(/[^0-9]/g, '')}`,
  );
}

toFloat('USD 1,500.00'); // 1500
toFloat('USD 1,500'); // 1500
toFloat('USD 500.00'); // 500
toFloat('USD 500'); // 500

toFloat('EUR 1.500,00'); // 1500
toFloat('EUR 1.500'); // 1500
toFloat('EUR 500,00'); // 500
toFloat('EUR 500'); // 500

How to debug Ruby scripts

Debugging by raising exceptions is far easier than squinting through print log statements, and for most bugs, its generally much faster than opening up an irb debugger like pry or byebug. Those tools should not always be your first step.


Debugging Ruby/Rails Quickly:

1. Fast Method: Raise an Exception then and .inspect its result

The fastest way to debug Ruby (especially Rails) code is to raise an exception along the execution path of your code while calling .inspect on the method or object (e.g. foo):

raise foo.inspect

In the above code, raise triggers an Exception that halts execution of your code, and returns an error message that conveniently contains .inspect information about the object/method (i.e. foo) on the line that you're trying to debug.

This technique is useful for quickly examining an object or method (e.g. is it nil?) and for immediately confirming whether a line of code is even getting executed at all within a given context.

2. Fallback: Use a ruby IRB debugger like byebug or pry

Only after you have information about the state of your codes execution flow should you consider moving to a ruby gem irb debugger like pry or byebug where you can delve more deeply into the state of objects within your execution path.


General Beginner Advice

When you are trying to debug a problem, good advice is to always: Read The !@#$ing Error Message (RTFM)

That means reading error messages carefully and completely before acting so that you understand what it's trying to tell you. When you debug, ask the following mental questions, in this order, when reading an error message:

  1. What class does the error reference? (i.e. do I have the correct object class or is my object nil?)
  2. What method does the error reference? (i.e. is their a type in the method; can I call this method on this type/class of object?)
  3. Finally, using what I can infer from my last two questions, what lines of code should I investigate? (remember: the last line of code in the stack trace is not necessarily where the problem lies.)

In the stack trace pay particular attention to lines of code that come from your project (e.g. lines starting with app/... if you are using Rails). 99% of the time the problem is with your own code.


To illustrate why interpreting in this order is important...

E.g. a Ruby error message that confuses many beginners:

You execute code that at some point executes as such:

@foo = Foo.new

...

@foo.bar

and you get an error that states:

undefined method "bar" for Nil:nilClass

Beginners see this error and think the problem is that the method bar is undefined. It's not. In this error the real part that matters is:

for Nil:nilClass

for Nil:nilClass means that @foo is Nil! @foo is not a Foo instance variable! You have an object that is Nil. When you see this error, it's simply ruby trying to tell you that the method bar doesn't exist for objects of the class Nil. (well duh! since we are trying to use a method for an object of the class Foo not Nil).

Unfortunately, due to how this error is written (undefined method "bar" for Nil:nilClass) its easy to get tricked into thinking this error has to do with bar being undefined. When not read carefully this error causes beginners to mistakenly go digging into the details of the bar method on Foo, entirely missing the part of the error that hints that the object is of the wrong class (in this case: nil). It's a mistake that's easily avoided by reading error messages in their entirety.

Summary:

Always carefully read the entire error message before beginning any debugging. That means: Always check the class type of an object in an error message first, then its methods, before you begin sleuthing into any stacktrace or line of code where you think the error may be occurring. Those 5 seconds can save you 5 hours of frustration.

tl;dr: Don't squint at print logs: raise exceptions or use an irb debugger instead. Avoid rabbit holes by reading errors carefully before debugging.

Instantiating a generic type

You cannot do new T() due to type erasure. The default constructor can only be

public Navigation() {     this("", "", null); } 

​ You can create other constructors to provide default values for trigger and description. You need an concrete object of T.

IntelliJ how to zoom in / out

Update: This answer is old. Intellij has since added actions to adjust font size. Check out Wilker's answer for assigning the new actions to keymaps.

Try Ctrl+Mouse Wheel which can be enabled under File > Settings... > Editor > General : Change font size (Zoom) with Ctrl+Mouse Wheel

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

You can use the datedif function to find out difference in days.

=DATEDIF(A1,TODAY(),"d")

Quote from excel.datedif.com

The mysterious datedif function in Microsoft Excel

The Datedif function is used to calculate interval between two dates in days, months or years.

This function is available in all versions of Excel but is not documented. It is not even listed in the "Insert Function" dialog box. Hence it must be typed manually in the formula box. Syntax

DATEDIF( start_date, end_date, interval_unit )

start_date from date end_date to date (must be after start_date) interval_unit Unit to be used for output interval Values for interval_unit

interval_unit Description

D Number of days

M Number of complete months

Y Number of complete years

YD Number of days excluding years

MD Number of days excluding months and years

YM Number of months excluding years

Errors

Error Description

#NUM! The end_date is later than (greater than) the start_date or interval_unit has an invalid value. #VALUE! end_date or start_date is invalid.

How to use ESLint with Jest

In your .eslintignore file add the following value:

**/__tests__/

This should ignore all instances of the __tests__ directory and their children.

How do I run all Python unit tests in a directory?

This is an old question, but what worked for me now (in 2019) is:

python -m unittest *_test.py

All my test files are in the same folder as the source files and they end with _test.

How to generate a unique hash code for string input in android...?

String input = "some input string";
int hashCode = input.hashCode();
System.out.println("input hash code = " + hashCode);

What is Python buffer type for?

An example usage:

>>> s = 'Hello world'
>>> t = buffer(s, 6, 5)
>>> t
<read-only buffer for 0x10064a4b0, size 5, offset 6 at 0x100634ab0>
>>> print t
world

The buffer in this case is a sub-string, starting at position 6 with length 5, and it doesn't take extra storage space - it references a slice of the string.

This isn't very useful for short strings like this, but it can be necessary when using large amounts of data. This example uses a mutable bytearray:

>>> s = bytearray(1000000)   # a million zeroed bytes
>>> t = buffer(s, 1)         # slice cuts off the first byte
>>> s[1] = 5                 # set the second element in s
>>> t[0]                     # which is now also the first element in t!
'\x05'

This can be very helpful if you want to have more than one view on the data and don't want to (or can't) hold multiple copies in memory.

Note that buffer has been replaced by the better named memoryview in Python 3, though you can use either in Python 2.7.

Note also that you can't implement a buffer interface for your own objects without delving into the C API, i.e. you can't do it in pure Python.

Is object empty?

Underscore and lodash each have a convenient isEmpty() function, if you don't mind adding an extra library.

_.isEmpty({});

Eclipse executable launcher error: Unable to locate companion shared library

I encountered this error with the Eclipse 4.10 installer. We had failed to complete the install correctly due to platform security settings and attempted to uninstall but had to do it by hand since no uninstaller was introduced during the failed install. We suspected this corrupted the end result - even after re-installing.

The solution was to use the JVM to launch Eclipse and bypass the launcher executable entirely. The following command successfully launches Eclipse 4.10 (some parameters will change based on the version of Eclipse):

%JDK190%\bin\javaw.exe -jar C:\<fully_qualified_path_to_eclipse>\Eclipse410\plugins\org.eclipse.equinox.launcher_1.5.200.v20180922-1751.jar -clean -showsplash

After using this command/shortcut to launch Eclipse we had no further errors with Eclipse itself but we weren't able to use the EXE launcher in the future. Even after a year of using this version, the launcher continues to display this same error.

To be clear, you'll have to modify your javaw.exe command to match your system specifications on MS Windows.

How to get the entire document HTML as a string?

PROBABLY ONLY IE:

>     webBrowser1.DocumentText

for FF up from 1.0:

//serialize current DOM-Tree incl. changes/edits to ss-variable
var ns = new XMLSerializer();
var ss= ns.serializeToString(document);
alert(ss.substr(0,300));

may work in FF. (Shows up the VERY FIRST 300 characters from the VERY beginning of source-text, mostly doctype-defs.)

BUT be aware, that the normal "Save As"-Dialog of FF MIGHT NOT save the current state of the page, rather the originallly loaded X/h/tml-source-text !! (a POST-up of ss to some temp-file and redirect to that might deliver a saveable source-text WITH the changes/edits prior made to it.)

Although FF surprises by good recovery on "back" and a NICE inclusion of states/values on "Save (as) ..." for input-like FIELDS, textarea etc. , not on elements in contenteditable/ designMode...

If NOT a xhtml- resp. xml-file (mime-type, NOT just filename-extension!), one may use document.open/write/close to SET the appr. content to the source-layer, that will be saved on user's save-dialog from the File/Save menue of FF. see: http://www.w3.org/MarkUp/2004/xhtml-faq#docwrite resp.

https://developer.mozilla.org/en-US/docs/Web/API/document.write

Neutral to questions of X(ht)ML, try a "view-source:http://..." as the value of the src-attrib of an (script-made!?) iframe, - to access an iframes-document in FF:

<iframe-elementnode>.contentDocument, see google "mdn contentDocument" for appr. members, like 'textContent' for instance. 'Got that years ago and no like to crawl for it. If still of urgent need, mention this, that I got to dive in ...

Webview load html from assets directory

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        WebView wb = new WebView(this);
        wb.loadUrl("file:///android_asset/index.html");
        setContentView(wb);
    }


keep your .html in `asset` folder

Creating a random string with A-Z and 0-9 in Java

Here you can use my method for generating Random String

protected String getSaltString() {
        String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        StringBuilder salt = new StringBuilder();
        Random rnd = new Random();
        while (salt.length() < 18) { // length of the random string.
            int index = (int) (rnd.nextFloat() * SALTCHARS.length());
            salt.append(SALTCHARS.charAt(index));
        }
        String saltStr = salt.toString();
        return saltStr;

    }

The above method from my bag using to generate a salt string for login purpose.

How to list only files and not directories of a directory Bash?

ls -p | grep -v /

ls -p lets you show / after the folder name, which acts as a tag for you to remove.

How can I make grep print the lines below and above each matching line?

Use -A and -B switches (mean lines-after and lines-before):

grep -A 1 -B 1 FAILED file.txt

How to stop a thread created by implementing runnable interface?

If you use ThreadPoolExecutor, and you use submit() method, it will give you a Future back. You can call cancel() on the returned Future to stop your Runnable task.

How can I make a horizontal ListView in Android?

Gallery is the best solution, i have tried it. I was working on one mail app, in which mails in the inbox where displayed as listview, i wanted an horizontal view, i just converted listview to gallery and everything worked fine as i needed without any errors. For the scroll effect i enabled gesture listener for the gallery. I hope this answer may help u.

How can I know when an EditText loses focus?

Kotlin way

editText.setOnFocusChangeListener { _, hasFocus ->
    if (!hasFocus) {  }
}

Why do I get "warning longer object length is not a multiple of shorter object length"?

When you perform a boolean comparison between two vectors in R, the "expectation" is that both vectors are of the same length, so that R can compare each corresponding element in turn.

R has a much loved (or hated) feature called recycling, whereby in many circumstances if you try to do something where R would normally expect objects to be of the same length, it will automatically extend, or recycle, the shorter object to force both objects to be of the same length.

If the longer object is a multiple of the shorter, this amounts to simply repeating the shorter object several times. Oftentimes R programmers will take advantage of this to do things more compactly and with less typing.

But if they are not multiples, R will worry that you may have made a mistake, and perhaps didn't mean to perform that comparison, hence the warning.

Explore yourself with the following code:

> x <- 1:3
> y <- c(1,2,4)
> x == y
[1]  TRUE  TRUE FALSE
> y1 <- c(y,y)
> x == y1
[1]  TRUE  TRUE FALSE  TRUE  TRUE FALSE
> y2 <- c(y,2)
> x == y2
[1]  TRUE  TRUE FALSE FALSE
Warning message:
In x == y2 :
  longer object length is not a multiple of shorter object length

Counting duplicates in Excel

If you perhaps also want to eliminate all of the duplicates and keep only a single one of each

Change the formula =COUNTIF(A:A,A2) to =COUNIF($A$2:A2,A2) and drag the formula down. Then autofilter for anything greater than 1 and you can delete them.

Is it possible for UIStackView to scroll?

Up to date for 2020.

100% storyboard OR 100% code.


Here's the simplest possible explanation:

  1. Have a blank full-screen scene

  2. Add a scroll view. Control-drag from the scroll view to the base view, add left-right-top-bottom, all zero.

  3. Add a stack view in the scroll view. Control-drag from the stack view to the scroll view, add left-right-top-bottom, all zero.

  4. Put two or three labels inside the stack view.

For clarity, make the background color of the label red. Set the label height to 100.

  1. Now set the width of each UILabel:

    Surprisingly, control-drag from the UILabel to the scroll view, not to the stack view, and select equal widths.

To repeat:

Don't control drag from the UILabel to the UILabel's parent - go to the grandparent. (In other words, go all the way to the scroll view, do not go to the stack view.)

It's that simple. That's the secret.

Secret tip - Apple bug:

It will not work with only one item! Add a few labels to make the demo work.

You're done.

Tip: You must add a height to every new item. Every item in any scrolling stack view must have either an intrinsic size (such as a label) or add an explicit height constraint.


The alternative approach:

In the above: surprisingly, set the widths of the UILabels to the width of the scroll view (not the stack view).

Alternately...

Drag from the stack view to the scroll view, and add a "width equal" constraint. This seems strange because you already pinned left-right, but that is how you do it. No matter how strange it seems that's the secret.

So you have two options:

  1. Surprisingly, set the width of each item in the stack view to the width of the scrollview grandparent (not the stackview parent).

or

  1. Surprisingly, set a "width equal" of the stackview to the scrollview - even though you do have the left and right edges of the stackview pinned to the scrollview anyway.

To be clear, do ONE of those methods, do NOT do both.

Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

public class MainActivity extends Activity
        implements View.OnClickListener {
    private Button btnForward, btnBackword, btnPause, btnPlay;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initControl();
    }

    private void initControl() {
        btnForward = (Button) findViewById(R.id.btnForward);
        btnBackword = (Button) findViewById(R.id.btnBackword);
        btnPause = (Button) findViewById(R.id.btnPause);
        btnPlay = (Button) findViewById(R.id.btnPlay);
        btnForward.setOnClickListener(this);
        btnBackword.setOnClickListener(this);
        btnPause.setOnClickListener(this);
        btnPlay.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnForward:
                break;
            case R.id.btnBackword:
                break;
            case R.id.btnPause:
                break;
            case R.id.btnPlay:
                break;
        }
    }
}

Get name of currently executing test in JUnit 4

I'd suggest you decouple the test method name from your test data set. I would model a DataLoaderFactory class which loads/caches the sets of test data from your resources, and then in your test case cam call some interface method which returns a set of test data for the test case. Having the test data tied to the test method name assumes the test data can only be used once, where in most case i'd suggest that the same test data in uses in multiple tests to verify various aspects of your business logic.

How to search in a List of Java object

Using Java 8

With Java 8 you can simply convert your list to a stream allowing you to write:

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

List<Sample> list = new ArrayList<Sample>();
List<Sample> result = list.stream()
    .filter(a -> Objects.equals(a.value3, "three"))
    .collect(Collectors.toList());

Note that

  • a -> Objects.equals(a.value3, "three") is a lambda expression
  • result is a List with a Sample type
  • It's very fast, no cast at every iteration
  • If your filter logic gets heavier, you can do list.parallelStream() instead of list.stream() (read this)


Apache Commons

If you can't use Java 8, you can use Apache Commons library and write:

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

Collection result = CollectionUtils.select(list, new Predicate() {
     public boolean evaluate(Object a) {
         return Objects.equals(((Sample) a).value3, "three");
     }
 });

// If you need the results as a typed array:
Sample[] resultTyped = (Sample[]) result.toArray(new Sample[result.size()]);

Note that:

  • There is a cast from Object to Sample at each iteration
  • If you need your results to be typed as Sample[], you need extra code (as shown in my sample)



Bonus: A nice blog article talking about how to find element in list.

Direct download from Google Drive using Google Drive API

Update December 8th, 2015 According to Google Support using the

googledrive.com/host/ID

method will be turned off on Aug 31st, 2016.


I just ran into this issue.

The trick is to treat your Google Drive folder like a web host.

Update April 1st, 2015

Google Drive has changed and there's a simple way to direct link to your drive. I left my previous answers below for reference but to here's an updated answer.

  1. Create a Public folder in Google Drive.

  2. Share this drive publicly.

    enter image description here

  3. Get your Folder UUID from the address bar when you're in that folder

    enter image description here
  4. Put that UUID in this URL

    https://googledrive.com/host/<folder UUID>/
  5. Add the file name to where your file is located.

    https://googledrive.com/host/<folder UUID>/<file name>

Which is intended functionality by Google
new Google Drive Link.

All you have to do is simple get the host URL for a publicly shared drive folder. To do this, you can upload a plain HTML file and preview it in Google Drive to find your host URL.

Here are the steps:

  1. Create a folder in Google Drive.

  2. Share this drive publicly.

    enter image description here

  3. Upload a simple HTML file. Add any additional files (subfolders ok)

    enter image description here

  4. Open and "preview" the HTML file in Google Drive

    enter image description here

  5. Get the URL address for this folder

    enter image description here

  6. Create a direct link URL from your URL folder base

    enter image description here

  7. This URL should allow direct downloads of your large files.

[edit]

I forgot to add. If you use subfolders to organize your files, you simple use the folder name as you would expect in a URL hierarchy.

https://googledrive.com/host/<your public folders id string>/images/my-image.png


What I was looking to do

I created a custom Debian image with Virtual Box for Vagrant. I wanted to share this ".box" file with colleagues so they could put the direct link into their Vagrantfile.

In the end, I needed a direct link to the actual file.

Google Drive problem

If you set the file permissions to be publicly available and create/generate a direct access link by using something like the gdocs2direct tool or just crafting the link yourself:

https://docs.google.com/uc?export=download&id=<your file id>

You will get a cookie based verification code and prompt "Google could not scan this file" prompt, which won't work for things such as wget or Vagrantfile configs.

The code that it generates is a simple code that appends GET query variable ...&confirm=### to the string, but it's per user specific, so it's not like you can copy/paste that query variable for others.

But if you use the above "Web page hosting" method, you can get around that prompt.

I hope that helps!

CSS selectors ul li a {...} vs ul > li > a {...}

1) for example HTML code:

<ul>
    <li>
        <a href="#">firstlink</a>
        <span><a href="#">second link&lt;/a>
    </li>
</ul>

and css rules:

1) ul li a {color:red;} 
2) ul > li > a {color:blue;}

">" - symbol mean that that will be searching only child selector (parentTag > childTag)

so first css rule will apply to all links (first and second) and second rule will apply anly to first link

2) As for efficiency - I think second will be more fast - as in case with JavaScript selectors. This rule read from right to left, this mean that when rule will parse by browser, it get all links on page: - in first case it will find all parent elements for each link on page and filter all links where exist parent tags "ul" and "li" - in second case it will check only parent node of link if it is "li" tag then -> check if parent tag of "li" is "ul"

some thing like this. Hope I describe all properly for you

How to make div appear in front of another?

In order an element to appear in front of another you have to give higher z-index to the front element, and lower z-index to the back element, also you should indicate position: absolute/fixed...

Example:

<div style="z-index:100; position: fixed;">Hello</div>
<div style="z-index: -1;">World</div>

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

You create handler in background thread this way

private void createHandler() {
        Thread thread = new Thread() {
          public void run() {
               Looper.prepare();

               final Handler handler = new Handler();
               handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                       // Do Work
                        handler.removeCallbacks(this);
                        Looper.myLooper().quit();
                   }
                }, 2000);

                Looper.loop();
            }
        };
        thread.start();
    }

Best way to show a loading/progress indicator?

Use ProgressDialog

ProgressDialog.show(Context context, CharSequence title, CharSequence message);

enter image description here

However this is considered as an anti pattern today (2013): http://www.youtube.com/watch?v=pEGWcMTxs3I

Jquery UI Datepicker not displaying

Please make sure that you are using the same version of jquery-ui 'js' and 'css' files. Sometimes that could be a problem.

Pycharm does not show plot

Comment from DanT fixed this for me, matplotlib with pycharm on linux with the GTKagg backend. Upon importing matplotlib I would get the following error:

>>> import matplotlib as mpl

Backend GTKAgg is interactive backend. Turning interactive mode on.
Failed to enable GUI event loop integration for 'gtk'

When plotting something like so:

from matplotlib import pyplot as plt
plt.figure()
plt.plot(1,2)
plt.show()

A figure screen would pop up but no charts appear. using:

plt.show(block=True)

displays the graphic correctly.

W3WP.EXE using 100% CPU - where to start?

If your CPU is spiking to 100% and staying there, it's quite likely that you either have a deadlock scenario or an infinite loop. A profiler seems like a good choice for finding an infinite loop. Deadlocks are much more difficult to track down, however.

The program can't start because MSVCR110.dll is missing from your computer

This error appears when you wish to run a software which require the Microsoft Visual C++ Redistributable 2012. Download it fromMicrosoft website as x86 or x64 edition. Depending on the software you wish to install you need to install either the 32 bit or the 64 bit version. Visit the following link: http://www.microsoft.com/en-us/download/details.aspx?id=30679#

How to set URL query params in Vue with Vue-Router

To set/remove multiple query params at once I've ended up with the methods below as part of my global mixins (this points to vue component):

    setQuery(query){
        let obj = Object.assign({}, this.$route.query);

        Object.keys(query).forEach(key => {
            let value = query[key];
            if(value){
                obj[key] = value
            } else {
                delete obj[key]
            }
        })
        this.$router.replace({
            ...this.$router.currentRoute,
            query: obj
        })
    },

    removeQuery(queryNameArray){
        let obj = {}
        queryNameArray.forEach(key => {
            obj[key] = null
        })
        this.setQuery(obj)
    },

Calling a Fragment method from a parent Activity

not get the question exactly as it is too simple :

ExampleFragment fragment = (ExampleFragment) getFragmentManager().findFragmentById(R.id.example_fragment);
fragment.<specific_function_name>(); 

Update: For those who are using Kotlin

var fragment = supportFragmentManager.findFragmentById(R.id.frameLayoutCW) as WebViewFragment
fragment.callAboutUsActivity()

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

The above solution works perfectly. I prefer to choose Web API option while selecting the project template as shown in the picture below

Note: The solution works with Visual Studio 2013 or higher. The original question was asked in 2012 and it is 2016, therefore adding a solution Visual Studio 2013 or higher.

Project template showing web API option

get everything between <tag> and </tag> with php

you can use /<code>([\s\S]*)<\/code>/msU this catch NEWLINES too!

Making an array of integers in iOS

If the order of your integers is not required, and if there are only unique values

you can also use NSIndexSet or NSMutableIndexSet You will be able to easily add and remove integers, or check if your array contains an integer with

- (void)addIndex:(NSUInteger)index
- (void)removeIndex:(NSUInteger)index
- (BOOL)containsIndexes:(NSIndexSet *)indexSet

Check the documentation for more info.

Android WebView not loading an HTTPS URL

To handle SSL urls the method onReceivedSslError() from the WebViewClient class, This is an example:

 webview.setWebViewClient(new WebViewClient() {
              ...
              ...
              ...

            @Override
            public void onReceivedSslError(WebView view, final SslErrorHandler handler, SslError error) {
                String message = "SSL Certificate error.";
                switch (error.getPrimaryError()) {
                    case SslError.SSL_UNTRUSTED:
                        message = "The certificate authority is not trusted.";
                        break;
                    case SslError.SSL_EXPIRED:
                        message = "The certificate has expired.";
                        break;
                    case SslError.SSL_IDMISMATCH:
                        message = "The certificate Hostname mismatch.";
                        break;
                    case SslError.SSL_NOTYETVALID:
                        message = "The certificate is not yet valid.";
                        break;
                }
                message += "\"SSL Certificate Error\" Do you want to continue anyway?.. YES";

                handler.proceed();
            }

        });

You can check my complete example here: https://github.com/Jorgesys/Android-WebView-Logging

enter image description here

How to convert string to integer in PowerShell

Use:

$filelist = @("11", "1", "2")
$filelist | sort @{expression={[int]$_}} | % {$newName = [string]([int]$_ + 1)}
New-Item $newName -ItemType Directory

How do I make case-insensitive queries on Mongodb?

An easy way would be to use $toLower as below.

db.users.aggregate([
    {
        $project: {
            name: { $toLower: "$name" }
        }
    },
    {
        $match: {
            name: the_name_to_search
        }
    }
])

How to check if a string is numeric?

You can use Character.isDigit(char ch) method or you can also use regular expression.

Below is the snippet:

public class CheckDigit {

private static Scanner input;

public static void main(String[] args) {

    System.out.print("Enter a String:");
    input = new Scanner(System.in);
    String str = input.nextLine();

    if (CheckString(str)) {
        System.out.println(str + " is numeric");
    } else {
        System.out.println(str +" is not numeric");
    }
}

public static boolean CheckString(String str) {
    for (char c : str.toCharArray()) {
        if (!Character.isDigit(c))
            return false;
    }
    return true;
}

}

Access files in /var/mobile/Containers/Data/Application without jailbreaking iPhone

If this is your app, if you connect the device to your computer, you can use the "Devices" option on Xcode's "Window" menu and then download the app's data container to your computer. Just select your app from the list of installed apps, and click on the "gear" icon and choose "Download Container".

enter image description here

Once you've downloaded it, right click on the file in the Finder and choose "Show Package Contents".

Storing sex (gender) in database

There is already an ISO standard for this; no need to invent your own scheme:

http://en.wikipedia.org/wiki/ISO_5218

Per the standard, the column should be called "Sex" and the 'closest' data type would be tinyint with a CHECK constraint or lookup table as appropriate.

How can you encode a string to Base64 in JavaScript?

While a bit more work, if you want a high performance native solution there are some HTML5 functions you can use.

If you can get your data into a Blob, then you can use the FileReader.readAsDataURL() function to get a data:// URL and chop off the front of it to get at the base64 data.

You may have to do further processing however to urldecode the data, as I'm not sure whether + characters are escaped or not for the data:// URL, but this should be pretty trivial.

Differences between action and actionListener

TL;DR:

The ActionListeners (there can be multiple) execute in the order they were registered BEFORE the action

Long Answer:

A business action typically invokes an EJB service and if necessary also sets the final result and/or navigates to a different view if that is not what you are doing an actionListener is more appropriate i.e. for when the user interacts with the components, such as h:commandButton or h:link they can be handled by passing the name of the managed bean method in actionListener attribute of a UI Component or to implement an ActionListener interface and pass the implementation class name to actionListener attribute of a UI Component.

Getting Integer value from a String using javascript/jquery

just do this , you need to remove char other than "numeric" and "." form your string will do work for you

yourString = yourString.replace ( /[^\d.]/g, '' );

your final code will be

  str1 = "test123.00".replace ( /[^\d.]/g, '' );
  str2 = "yes50.00".replace ( /[^\d.]/g, '' );
  total = parseInt(str1, 10) + parseInt(str2, 10);
  alert(total);

Demo

batch script - run command on each file in directory

I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.

set codedirectory=C:\Users\code
for /r  %codedirectory% %%i in (*.c) do 
( some GCC commands )

Ajax call Into MVC Controller- Url Issue

Simple way to access the Url Try this Code

 $.ajax({
     type: "POST",
      url: '/Controller/Search', 
     data: "{queryString:'" + searchVal + "'}",
     contentType: "application/json; charset=utf-8",
     dataType: "html",
     success: function (data) {
     alert("here" + data.d.toString());
    });

Using ExcelDataReader to read Excel data starting from a particular cell

I found this useful to read from a specific column and row:

FileStream stream = File.Open(@"C:\Users\Desktop\ExcelDataReader.xlsx", FileMode.Open, FileAccess.Read);
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
DataSet result = excelReader.AsDataSet();
excelReader.IsFirstRowAsColumnNames = true;         
DataTable dt = result.Tables[0];
string text = dt.Rows[1][0].ToString();

Uninstall all installed gems, in OSX?

Use either

$ gem list --no-version | xargs gem uninstall -ax

or

$ sudo gem list --no-version | xargs sudo gem uninstall -ax

Depending on what you want, you may need to execute both, because "gem list" and "sudo gem list" provide independent lists.

Do not mix a normal "gem list" with a sudo-ed "gem uninstall" nor the other way around otherwise you may end up uninstalling sudo-installed gems (former) or getting a lot of errors (latter).

Why is the Android emulator so slow? How can we speed up the Android emulator?

Remove unwanted activation of some of the plugins at start-up by going to windows-->preference-->General-->Startup and shutdown. Also make sure you don't use those plugins in any of your views

Eclipse is not a word processor. Better to disable the spell check. Disabling spell check will reduce the eclipse burden by going to Windows-->Preference-->General-->Editors --> Text Editors-->Spelling

When eclipse builds the project, it will delete all output folders and rebuild classes built by other compilers. We can disable such features, as deleting the output folders and rebuilding will take sometime. Goto Windows-->Preference-->Java-->Compiler-->Building

Disabling label decorations which is of less use for you, will also help you to gain some performance . Goto Windows-->Preference-->General-->Appearance-->Label Decorations

Close unwanted projects and use working set option to move from one group of project to another smoothly.

You could also disable Eclipse automatic building, if it is not needed for you. Goto Project-->Build Automatically (uncheck it)

Do not keep lot of tabs opened in the editor. Better to have around 20 tabs . Regularly close the unused tabs. To open resource we can always use ctrl+shift+R and ctrl+shift+T (java resource) instead of opening lot of tabs

Disable unwanted plugins. Full J2EE eclipse version has an option to disable/uninstall plugins. Goto Help-->Software Updates-->Manage Configuration. Right click on any installed plugin to get disable option. If this option is not available then enable Classic Update by going to Windows-->Preference-->Capabilty and check classic update. Now the manage configuration option should be available in help menu

Make Iframe to fit 100% of container's remaining height

I think you have a conceptual problem here. To say "I tried set height:100% on iframe, the result is quite close but the iframe tried to fill the whole page", well, when has "100%" not been equal to "whole"?

You have asked the iframe to fill the entire height of its container (which is the body) but unfortunately it has a block level sibling in the <div> above which you've asked to be 30px big. So the parent container total is now being asked to size to 100% + 30px > 100%! Hence scrollbars.

What I think you mean is that you would like the iframe to consume what's left like frames and table cells can, i.e. height="*". IIRC this doesn't exist.

Unfortunately to the best of my knowledge there is no way to effectively mix/calculate/subtract absolute and relative units either, so I think you're reduced to two options:

  1. Absolutely position your div, which will take it out of the container so the iframe alone will consume it's containers height. This leaves you with all manner of other problems though, but perhaps for what you're doing opacity or alignment would be ok.

  2. Alternatively you need to specify a % height for the div and reduce the height of the iframe by that much. If the absolute height is really that important you'll need to apply that to a child element of the div instead.

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

'Property does not exist on type 'never'

if you're receiving the error in parameter, so keep any or any[] type of input like below

getOptionLabel={(option: any) => option!.name}
 <Autocomplete
    options={tests}
    getOptionLabel={(option: any) => option!.name}
    ....
  />

ORA-00907: missing right parenthesis

I would recommend separating out all of the foreign-key constraints from your CREATE TABLE statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.

You can add an FK constraint to a table using SQL like the following:

ALTER TABLE orders ADD CONSTRAINT orders_FK
  FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);

In particular, your formats and library tables both have foreign-key constraints on one another. The two CREATE TABLE statements to create these two tables can never run successfully, as each will only work when the other table has already been created.

Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.

Is it possible to use jQuery .on and hover?

The jQuery plugin hoverIntent http://cherne.net/brian/resources/jquery.hoverIntent.html goes much further than the naive approaches listed here. While they certainly work, they might not necessarily behave how users expect.

The strongest reason to use hoverIntent is the timeout feature. It allows you to do things like prevent a menu from closing because a user drags their mouse slightly too far to the right or left before they click the item they want. It also provides capabilities for not activating hover events in a barrage and waits for focused hovering.

Usage example:

var config = {    
 sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)    
 interval: 200, // number = milliseconds for onMouseOver polling interval    
 over: makeTall, // function = onMouseOver callback (REQUIRED)    
 timeout: 500, // number = milliseconds delay before onMouseOut    
 out: makeShort // function = onMouseOut callback (REQUIRED)
};
$("#demo3 li").hoverIntent( config )

Further explaination of this can be found on https://stackoverflow.com/a/1089381/37055

How to install wkhtmltopdf on a linux based (shared hosting) web server

Chances are that without full access to this server (due to being a hosted account) you are going to have problems. I would go so far as to say that I think it is a fruitless endeavor--they have to lock servers down in hosted environments for good reason.

Call your hosting company and make the request to them to install it, but don't expect a good response--they typically won't install very custom items for single users unless there is a really good reason (bug fixes for example).

Lastly, depending on how familiar you are with server administration and what you are paying for server hosting now consider something like http://www.slicehost.com. $20 a month will get you a low grade web server (256 ram) and you can install anything you want. However, if you are running multiple sites or have heavy load the cost will go up as you need larger servers.

GL!

Regex date format validation on Java

Construct a SimpleDateFormat with the mask, and then call: SimpleDateFormat.parse(String s, ParsePosition p)

How do I use an INSERT statement's OUTPUT clause to get the identity value?

You can either have the newly inserted ID being output to the SSMS console like this:

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

You can use this also from e.g. C#, when you need to get the ID back to your calling app - just execute the SQL query with .ExecuteScalar() (instead of .ExecuteNonQuery()) to read the resulting ID back.

Or if you need to capture the newly inserted ID inside T-SQL (e.g. for later further processing), you need to create a table variable:

DECLARE @OutputTbl TABLE (ID INT)

INSERT INTO MyTable(Name, Address, PhoneNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)
VALUES ('Yatrix', '1234 Address Stuff', '1112223333')

This way, you can put multiple values into @OutputTbl and do further processing on those. You could also use a "regular" temporary table (#temp) or even a "real" persistent table as your "output target" here.

Could not insert new outlet connection: Could not find any information for the class named

I had the same problem. I realised than in X-Code Manual item was selected when I tried to create an outlet by control-drag

enter image description here

After I set it to automatic it worked

enter image description here

Switch role after connecting to database

If someone still needs it (like I do).

The specified role_name must be a role that the current session user is a member of. https://www.postgresql.org/docs/10/sql-set-role.html

We need to make the current session user a member of the role:

create role myrole;
set role myrole;
grant myrole to myuser;
set role myrole;

produces:

Role ROLE created.


Error starting at line : 4 in command -
set role myrole
Error report -
ERROR: permission denied to set role "myrole"

Grant succeeded.


Role SET succeeded.

How to find elements by class

How to find elements by class

I'm having trouble parsing html elements with "class" attribute using Beautifulsoup.

You can easily find by one class, but if you want to find by the intersection of two classes, it's a little more difficult,

From the documentation (emphasis added):

If you want to search for tags that match two or more CSS classes, you should use a CSS selector:

css_soup.select("p.strikeout.body")
# [<p class="body strikeout"></p>]

To be clear, this selects only the p tags that are both strikeout and body class.

To find for the intersection of any in a set of classes (not the intersection, but the union), you can give a list to the class_ keyword argument (as of 4.1.2):

soup = BeautifulSoup(sdata)
class_list = ["stylelistrow"] # can add any other classes to this list.
# will find any divs with any names in class_list:
mydivs = soup.find_all('div', class_=class_list) 

Also note that findAll has been renamed from the camelCase to the more Pythonic find_all.

SQL - How to select a row having a column with max value

Technically, this is the same answer as @Sujee. It also depends on your version of Oracle as to whether it works. (I think this syntax was introduced in Oracle 12??)

SELECT *
FROM   table
ORDER BY value DESC, date_column ASC
FETCH  first 1 rows only;

As I say, if you look under the bonnet, I think this code is unpacked internally by the Oracle Optimizer to read like @Sujee's. However, I'm a sucker for pretty coding, and nesting select statements without a good reason does not qualify as beautiful!! :-P

Variable interpolation in the shell

Use curly braces around the variable name:

`tail -1 ${filepath}_newstap.sh`

How to open an existing project in Eclipse?

Just do like below, it helped me after doing like this.

To load existing Eclipse projects in the IDE, you need to import them into the Eclipse workspace.

  1. Click File > Import > General
  2. Click Existing Projects into Workspace.
  3. You can edit the project directly in its original location or choose to create a copy of the project in the workspace.
  4. Select the directory that contains the projects you want to import.
  5. Click Finish. This imports the projects into the current workspace and loads them in the IDE.

Look at this below link for reference. https://www.microfocus.com/documentation/enterprise-developer/ed30/Eclipse/GUID-773A19C7-98B2-442D-9D36-240E20E3F2CE.html

How to loop through an associative array and get the key?

While arguably being less clear this method is faster by roughly a factor of roughly 3.5 (At least on the box I used to test)

$foo = array(
    1 => "Value1",
    2 => "Value2",
    10 => "Value10"
);
while($bar = each($foo)){
    echo $bar[0] . " => " . $bar[1];
}

I would imagine that this is due to the fact the foreach copies the entire array before iterating over it.

PHP upload image

The code overlooks calling the function move_uploaded_file() which would check whether the indicated file is valid for uploading.

You may wish to review a simple example at:

http://www.w3schools.com/php/php_file_upload.asp

Hibernate: get entity by id

In getUserById you shouldn't create a new object (user1) which isn't used. Just assign it to the already (but null) initialized user. Otherwise Hibernate.initialize(user); is actually Hibernate.initialize(null);

Here's the new getUserById (I haven't tested this ;)):

public User getUserById(Long user_id) {
    Session session = null;
    Object user = null;
    try {
        session = HibernateUtil.getSessionFactory().openSession();
        user = (User)session.load(User.class, user_id);
        Hibernate.initialize(user);
    } catch (Exception e) {
       e.printStackTrace();
    } finally {
        if (session != null && session.isOpen()) {
            session.close();
        }
    }
    return user;
}

How to check for the type of a template parameter?

You can specialize your templates based on what's passed into their parameters like this:

template <> void foo<animal> {

}

Note that this creates an entirely new function based on the type that's passed as T. This is usually preferable as it reduces clutter and is essentially the reason we have templates in the first place.

Common elements in two lists

Why reinvent the wheel? Use Commons Collections:

CollectionUtils.intersection(java.util.Collection a, java.util.Collection b)

Netbeans - Error: Could not find or load main class

I had the same problem, I had the package and class named the same. I renamed the class, then clean and build. Then I set the main class in the "run" under the properties of the project. I works now.

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

How to get the selected item of a combo box to a string variable in c#

Try this:

string selected = this.ComboBox.GetItemText(this.ComboBox.SelectedItem);
MessageBox.Show(selected);

zsh compinit: insecure directories

This fixed it for me:

$ sudo chmod -R 755 /usr/local/share/zsh/site-functions

Credit: a post on zsh mailing list


EDIT: As pointed out by @biocyberman in the comments. You may need to update the owner of site-functions as well:

$ sudo chown -R root:root /usr/local/share/zsh/site-functions

On my machine (OSX 10.9), I do not need to do this but YMMV.

EDIT2: On OSX 10.11, only this worked:

$ sudo chmod -R 755 /usr/local/share/zsh
$ sudo chown -R root:staff /usr/local/share/zsh

Also user:staff is the correct default permission on OSX.

How to use a Java8 lambda to sort a stream in reverse order?

Use

Comparator<File> comparator = Comparator.comparing(File::lastModified); 
Collections.sort(list, comparator.reversed());

Then

.forEach(item -> item.delete());

Difference between \b and \B in regex

\B is not \b e.g. negative \b

pass-key here is no word boundary beside - so it matches \B in your first example there are word boundary beside cat so it matches \b

similar rules apply for others too. \W is negative of \w \UPPER CASE is negative of \LOWER CASE

call a function in success of datatable ajax call

You can use dataSrc :

Here is a typical example of datatables.net

var table = $('#example').DataTable( {
    "ajax": {
            "type" : "GET",
            "url" : "ajax.php",
            "dataSrc": function ( json ) {
                //Make your callback here.
                alert("Done!");
                return json.data;
            }       
            },
    "columns": [
            { "data": "name" },
            { "data": "position" },
            { "data": "office" },
            { "data": "extn" },
            { "data": "start_date" },
            { "data": "salary" }

        ]
    } );

Get records of current month

Try this query:

SELECT *
FROM table 
WHERE MONTH(FROM_UNIXTIME(columnName))= MONTH(CURDATE())

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

Linux delete file with size 0

you would want to use find:

 find . -size 0 -delete

Disable ONLY_FULL_GROUP_BY

One important thing to note, if you have ANSI on sql_mode:

Equivalent to REAL_AS_FLOAT, PIPES_AS_CONCAT, ANSI_QUOTES, IGNORE_SPACE, and (as of MySQL 5.7.5) ONLY_FULL_GROUP_BY.

See https://dev.mysql.com/doc/refman/5.7/en/sql-mode.html#sqlmode_ansi

How do I properly set the Datetimeindex for a Pandas datetime object in a dataframe?

You are not creating datetime index properly,

format = '%Y-%m-%d %H:%M:%S'
df['Datetime'] = pd.to_datetime(df['date'] + ' ' + df['time'], format=format)
df = df.set_index(pd.DatetimeIndex(df['Datetime']))

What is the Swift equivalent to Objective-C's "@synchronized"?

In the "Understanding Crashes and Crash Logs" session 414 of the 2018 WWDC they show the following way using DispatchQueues with sync.

In swift 4 should be something like the following:

class ImageCache {
    private let queue = DispatchQueue(label: "sync queue")
    private var storage: [String: UIImage] = [:]
    public subscript(key: String) -> UIImage? {
        get {
          return queue.sync {
            return storage[key]
          }
        }
        set {
          queue.sync {
            storage[key] = newValue
          }
        }
    }
}

Anyway you can also make reads faster using concurrent queues with barriers. Sync and async reads are performed concurrently and writing a new value waits for previous operations to finish.

class ImageCache {
    private let queue = DispatchQueue(label: "with barriers", attributes: .concurrent)
    private var storage: [String: UIImage] = [:]

    func get(_ key: String) -> UIImage? {
        return queue.sync { [weak self] in
            guard let self = self else { return nil }
            return self.storage[key]
        }
    }

    func set(_ image: UIImage, for key: String) {
        queue.async(flags: .barrier) { [weak self] in
            guard let self = self else { return }
            self.storage[key] = image
        }
    }
}

How to integrate SAP Crystal Reports in Visual Studio 2017

Please wait Support Pack 21 in September 2017

UPDATE: More info

https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads

VS 2017 - Tested opening existing app and it works, CR for VS is not integrated into the app so no new CR projects available- should be fully integrated in SP 21

About release

Link: https://answers.sap.com/questions/168439/crystal-report-for-vs-2017.html

Moderator Don Williams said:

Not supported yet, I tried to get it into SP 20 but due to time constraints DEV can't get it into VS until SP 21, due out in September time...

Listing files in a directory matching a pattern in Java

See File#listFiles(FilenameFilter).

File dir = new File(".");
File [] files = dir.listFiles(new FilenameFilter() {
    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(".xml");
    }
});

for (File xmlfile : files) {
    System.out.println(xmlfile);
}

AutoComplete TextBox Control

    You can add a parameter in the query like @emailadd to be added in the aspx.cs file where the Stored Procedure is called with cmd.Parameter.AddWithValue.
    The trick is that the @emailadd parameter doesn't exist in the table design of the select query, but being added and inserted in the table.

    USE [DRDOULATINSTITUTE]
    GO
    /****** Object:  StoredProcedure [dbo].[ReikiInsertRow]    Script Date: 5/18/2016 11:12:33 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER procedure [dbo].[ReikiInsertRow]
    @Reiki varchar(100),
    @emailadd varchar(50)
    as
    insert into dbo.ReikiPowerDisplay
    select Reiki,ReikiDescription, @emailadd from ReikiPower
    where Reiki=@Reiki;

Posted By: Aneel Goplani. CIS. 2002. USA

How to display JavaScript variables in a HTML page without document.write

Similar to above, but I used (this was in CSHTML):

JavaScript:

var value = "Hello World!"<br>
$('.output').html(value);

CSHTML:

<div class="output"></div>

Google Chrome redirecting localhost to https

Open Chrome Developer Tools -> go to Network -> select Disable Cache -> reload

Virtual network interface in Mac OS X

i have resorted to running PFSense, a BSD based router/firewall to achieve this goal….

why? because OS X Server gets so FREAKY without a Static IP…

so after wrestling with it for DAYS to make NAT and DHCP and firewall and …

I'm trying this is parallels…

will let ya know how it goes...

iPhone SDK:How do you play video inside a view? Rather than fullscreen

Swift version:

import AVFoundation

func playVideo(url: URL) {

    let player = AVPlayer(url: url)

    let layer: AVPlayerLayer = AVPlayerLayer(player: player)
    layer.backgroundColor = UIColor.white.cgColor
    layer.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
    layer.videoGravity = .resizeAspectFill
    self.view.layer.addSublayer(layer)

    player.play()
}

What is an idiomatic way of representing enums in Go?

For a use case like this, it may be useful to use a string constant so it can be marshaled into a JSON string. In the following example, []Base{A,C,G,T} would get marshaled to ["adenine","cytosine","guanine","thymine"].

type Base string

const (
    A Base = "adenine"
    C      = "cytosine"
    G      = "guanine"
    T      = "thymine"
)

When using iota, the values get marshaled into integers. In the following example, []Base{A,C,G,T} would get marshaled to [0,1,2,3].

type Base int

const (
    A Base = iota
    C
    G
    T
)

Here's an example comparing both approaches:

https://play.golang.org/p/VvkcWvv-Tvj

How to get image height and width using java?

Simple way:

BufferedImage readImage = null;

try {
    readImage = ImageIO.read(new File(your path);
    int h = readImage.getHeight();
    int w = readImage.getWidth();
} catch (Exception e) {
    readImage = null;
}

Activate a virtualenv with a Python script

The simplest solution to run your script under virtualenv's interpreter is to replace the default shebang line with path to your virtualenv's interpreter like so at the beginning of the script:

#!/path/to/project/venv/bin/python

Make the script executable:

chmod u+x script.py

Run the script:

./script.py

Voila!

best practice font size for mobile

Based on my comment to the accepted answer, there are a lot potential pitfalls that you may encounter by declaring font-sizes smaller than 12px. By declaring styles that lead to computed font-sizes of less than 12px, like so:

html {
  font-size: 8px;
}
p {
  font-size: 1.4rem;
}
// Computed p size: 11px.

You'll run into issues with browsers, like Chrome with a Chinese language pack that automatically renders any font sizes computed under 12px as 12px. So, the following is true:

h6 {
    font-size: 12px;
}
p {
   font-size: 8px;
}
// Both render at 12px in Chrome with a Chinese language pack.   
// How unpleasant of a surprise.

I would also argue that for accessibility reasons, you generally shouldn't use sizes under 12px. You might be able to make a case for captions and the like, but again--prepare to be surprised under some browser setups, and prepared to make your grandma squint when she's trying to read your content.

I would instead, opt for something like this:

h1 {
    font-size: 2.5rem;
}

h2 {
    font-size: 2.25rem;
}

h3 {
    font-size: 2rem;
}

h4 {
    font-size: 1.75rem;
}

h5 {
    font-size: 1.5rem;
}

h6 {
    font-size: 1.25rem;
}

p {
    font-size: 1rem;
}

@media (max-width: 480px) {
    html {
        font-size: 12px;
    }
}

@media (min-width: 480px) {
    html {
        font-size: 13px;
    }
}

@media (min-width: 768px) {
    html {
        font-size: 14px;
    }
}

@media (min-width: 992px) {
    html {
        font-size: 15px;
    }
}

@media (min-width: 1200px) {
    html {
        font-size: 16px;
    }
}

You'll find that tons of sites that have to focus on accessibility use rather large font sizes, even for p elements.

As a side note, setting margin-bottom equal to the font-size usually also tends to be attractive, i.e.:

h1 {
    font-size: 2.5rem;
    margin-bottom: 2.5rem;
}

Good luck.

Count the frequency that a value occurs in a dataframe column

I believe this should work fine for any DataFrame columns list.

def column_list(x):
    column_list_df = []
    for col_name in x.columns:
        y = col_name, len(x[col_name].unique())
        column_list_df.append(y)
return pd.DataFrame(column_list_df)

column_list_df.rename(columns={0: "Feature", 1: "Value_count"})

The function "column_list" checks the columns names and then checks the uniqueness of each column values.

How to display a list inline using Twitter's Bootstrap

According to Bootstrap documentation of 2.3.2 and 3, the class should be defined like this:

Bootstrap 2.3.2

<ul class="inline">
  <li>...</li>
</ul>

Bootstrap 3

<ul class="list-inline">
  <li>...</li>
</ul>

List comprehension on a nested list?

Since i am little late here but i wanted to share how actually list comprehension works especially nested list comprehension :

New_list= [[float(y) for x in l]

is actually same as :

New_list=[]
for x in l:
    New_list.append(x)

And now nested list comprehension :

[[float(y) for y in x] for x in l]

is same as ;

new_list=[]
for x in l:
    sub_list=[]
    for y in x:
        sub_list.append(float(y))

    new_list.append(sub_list)

print(new_list)

output:

[[40.0, 20.0, 10.0, 30.0], [20.0, 20.0, 20.0, 20.0, 20.0, 30.0, 20.0], [30.0, 20.0, 30.0, 50.0, 10.0, 30.0, 20.0, 20.0, 20.0], [100.0, 100.0], [100.0, 100.0, 100.0, 100.0, 100.0], [100.0, 100.0, 100.0, 100.0]]

phpmyadmin - count(): Parameter must be an array or an object that implements Countable

Work for me.. Ubuntu 18.04

sudo nano /usr/share/phpmyadmin/libraries/sql.lib.php

Find for count($analyzed_sql_results['select_expr'] code on file. You can get this at line ~613.

|| (count($analyzed_sql_results['select_expr'] == 1)

Just replace with code :

|| ((count($analyzed_sql_results['select_expr']) == 1)

Save the file and reload PhpMyAdmin.

Done!!!

How can I enable MySQL's slow query log without restarting MySQL?

Find log enabled or not?

SHOW VARIABLES LIKE '%log%';

Set the logs:-

SET GLOBAL general_log = 'ON'; 

SET GLOBAL slow_query_log = 'ON'; 

Display milliseconds in Excel

First represent the epoch of the millisecond time as a date (usually 1/1/1970), then add your millisecond time divided by the number of milliseconds in a day (86400000):

=DATE(1970,1,1)+(A1/86400000)

If your cell is properly formatted, you should see a human-readable date/time.

Can I add and remove elements of enumeration at runtime in Java

You could try to assign properties to the ENUM you're trying to create and statically contruct it by using a loaded properties file. Big hack, but it works :)

Instantiate and Present a viewController in Swift

I know it's an old thread, but I think the current solution (using hardcoded string identifier for given view controller) is very prone to errors.

I've created a build time script (which you can access here), which will create a compiler safe way for accessing and instantiating view controllers from all storyboard within the given project.

For example, view controller named vc1 in Main.storyboard will be instantiated like so:

let vc: UIViewController = R.storyboard.Main.vc1^  // where the '^' character initialize the controller

What is the syntax meaning of RAISERROR()

16 is severity and 1 is state, more specifically following example might give you more detail on syntax and usage:

BEGIN TRY
    -- RAISERROR with severity 11-19 will cause execution to 
    -- jump to the CATCH block.
    RAISERROR ('Error raised in TRY block.', -- Message text.
               16, -- Severity.
               1 -- State.
               );
END TRY
BEGIN CATCH
    DECLARE @ErrorMessage NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState INT;

    SELECT 
        @ErrorMessage = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState = ERROR_STATE();

    -- Use RAISERROR inside the CATCH block to return error
    -- information about the original error that caused
    -- execution to jump to the CATCH block.
    RAISERROR (@ErrorMessage, -- Message text.
               @ErrorSeverity, -- Severity.
               @ErrorState -- State.
               );
END CATCH;

You can follow and try out more examples from http://msdn.microsoft.com/en-us/library/ms178592.aspx

getting integer values from textfield

You need to use Integer.parseInt(String)

private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
        if(evt.getSource()==jTextField2){
            int jml = Integer.parseInt(jTextField3.getText());
            jTextField1.setText(numberToWord(jml));

        }
    }

How to pass form input value to php function

you must have read about function call . here i give you example of it.

<?php
 funtion pr($n)
{
echo $n;
 }
?>
<form action="<?php $f=$_POST['input'];pr($f);?>" method="POST">
<input name=input type=text></input>
</form>

angularjs: allows only numbers to be typed into a text box

This answer serves as a simplification and optimisation over Leopoldo's answer.

Trigger a function from your input on every keydown like this:

<input type="text" ng-keydown="onlyNumbers($event);"/>

You can describe the function in this manner in your controller

$scope.onlyNumbers = function(event){    
    // 'up': 38,'right':39,'down':40,'left':37,
    // 'escape':27,'backspace':8,'tab':9,'enter':13,'del':46,
    // '0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57
    var keys = { 38:true,39:true,40:true,37:true,27:true,8:true,9:true,13:true,
                 46:true,48:true,49:true, 50:true,51:true,52:true,53:true,
                 54:true,55:true,56:true,57:true };

    // if the pressed key is not listed, do not perform any action
    if(!keys[event.keyCode]) { event.preventDefault(); }
}

In case you're using Angular 2+, you can call this same function in this manner:

<input type="text" (keydown)="onlyNumbers($event);"/>

Your Angular 2+ function should look something like this:

onlyNumbers(event) { // the logic here }

Bypass invalid SSL certificate errors when calling web services in .Net

ServicePointManager.ServerCertificateValidationCallback +=
            (mender, certificate, chain, sslPolicyErrors) => true;

will bypass invaild ssl . Write it to your web service constructor.

SELECT INTO USING UNION QUERY

select *
into new_table
from table_A
UNION
Select * 
From table_B

This only works if Table_A and Table_B have the same schemas

Get current value selected in dropdown using jQuery

The options discussed above won't work because they are not part of the CSS specification (it is jQuery extension). Having spent 2-3 days digging around for information, I found that the only way to select the Text of the selected option from the drop down is:

{ $("select", id:"Some_ID").find("option[selected='selected']")}

Refer to additional notes below: Because :selected is a jQuery extension and not part of the CSS specification, queries using :selected cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :selected to select elements, first select the elements using a pure CSS selector, then use .filter(":selected"). (copied from: http://api.jquery.com/selected-selector/)

AppFabric installation failed because installer MSI returned with error code : 1603

I had a similar problem

9/21/2012 11:28:01 AM EXEPATH=powershell.exe PARAMS=-command "$str = [System.Environment]::GetEnvironmentVariable(\"PSModulePath\", [System.EnvironmentVariableTarget]::Machine); $str = $str+\";c:\Program Files\AppFabric 1.1 for Windows Server\PowershellModules\"; c:\Windows\system32\setx.exe /M PSModulePath \"$str\"" LOGFILE=C:\Users\XXXXXXX\AppData\Local\Temp\AppServerSetup1_1_CustomActions(2012-09-21 11-27-26).log Error: ERROR: Invalid syntax. Default option is not allowed more than '2' time(s). Error: Type "SETX /?" for usage.

My issue was the PSModulePath having an improper " in it

it was:

C:\Windows\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules"

removing the extraneous " corrected the issue

To change this go to Control Panel -> System -> Advanced System Settings -> On the Advanced Tab Select Enviroment Variables -> Under System Variables there is a Variable named PSModulePath, select it -> Click Edit -> Remove trailing "

System Properties

Change the size of a JTextField inside a JBorderLayout

With a BorderLayout you need to use setPreferredSize instead of setSize

Convert time fields to strings in Excel

copy the column paste it into notepad copy it again paste special as Text

How to get enum value by string or int

Could be much simpler if you use TryParse or Parse and ToObject methods.

public static class EnumHelper
{
    public static  T GetEnumValue<T>(string str) where T : struct, IConvertible
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }
        T val;
        return Enum.TryParse<T>(str, true, out val) ? val : default(T);
    }

    public static T GetEnumValue<T>(int intValue) where T : struct, IConvertible
    {
        Type enumType = typeof(T);
        if (!enumType.IsEnum)
        {
            throw new Exception("T must be an Enumeration type.");
        }

        return (T)Enum.ToObject(enumType, intValue);
    }
}

As noted by @chrfin in comments, you can make it an extension method very easily just by adding this before the parameter type which can be handy.

c# replace \" characters

In .NET Framework 4 and MVC this is the only representation that worked:

Replace(@"""","")

Using a backslash in whatever combination did not work...

JavaScript code for getting the selected value from a combo box

There is an unnecessary hashtag; change the code to this:

var e = document.getElementById("ticket_category_clone").value;

How to run a command as a specific user in an init script?

Instead of sudo, try

su - username command

In my experience, sudo is not always available on RHEL systems, but su is, because su is part of the coreutils package whereas sudo is in the sudo package.

How to truncate text in Angular2?

Truncate Pipe with optional params:

  • limit - string max length
  • completeWords - Flag to truncate at the nearest complete word, instead of character
  • ellipsis - appended trailing suffix

-

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'truncate'
})
export class TruncatePipe implements PipeTransform {
  transform(value: string, limit = 25, completeWords = false, ellipsis = '...') {
    if (completeWords) {
      limit = value.substr(0, limit).lastIndexOf(' ');
    }
    return value.length > limit ? value.substr(0, limit) + ellipsis : value;
  }
}

Don't forget to add a module entry.

@NgModule({
  declarations: [
    TruncatePipe
  ]
})
export class AppModule {}

Usage

Example String:

public longStr = 'A really long string that needs to be truncated';

Markup:

  <h1>{{longStr | truncate }}</h1> 
  <!-- Outputs: A really long string that... -->

  <h1>{{longStr | truncate : 12 }}</h1> 
  <!-- Outputs: A really lon... -->

  <h1>{{longStr | truncate : 12 : true }}</h1> 
  <!-- Outputs: A really... -->

  <h1>{{longStr | truncate : 12 : false : '***' }}</h1> 
  <!-- Outputs: A really lon*** -->

How do you get the list of targets in a makefile?

This is an attempt to improve on Brent Bradburn's great approach as follows:

  • uses a more robust command to extract the target names, which hopefully prevents any false positives (and also does away with the unnecessary sh -c)
  • does not invariably target the makefile in the current directory; respects makefiles explicitly specified with -f <file>
  • excludes hidden targets - by convention, these are targets whose name starts neither with a letter nor a digit
  • makes do with a single phony target
  • prefixes the command with @ to prevent it from being echoed before execution

Curiously, GNU make has no feature for listing just the names of targets defined in a makefile. While the -p option produces output that includes all targets, it buries them in a lot of other information and also executes the default target (which could be suppressed with -f/dev/null).

Place the following rule in a makefile for GNU make to implement a target named list that simply lists all target names in alphabetical order - i.e.: invoke as make list:

.PHONY: list
list:
    @$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | sort | egrep -v -e '^[^[:alnum:]]' -e '^$@$$'

Important: On pasting this, make sure that the last line is indented by exactly 1 actual tab char. (spaces do not work).

Note that sorting the resulting list of targets is the best option, since not sorting doesn't produce a helpful ordering in that the order in which the targets appear in the makefile is not preserved.
Also, the sub-targets of a rule comprising multiple targets are invariably output separately and will therefore, due to sorting, usually not appear next to one another; e.g., a rule starting with a z: will not have targets a and z listed next to each other in the output, if there are additional targets.

Explanation of the rule:

  • .PHONY: list

    • declares target list a phony target, i.e., one not referring to a file, which should therefore have its recipe invoked unconditionally
  • $(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null

    • Invokes make again in order to print and parse the database derived from the makefile:
      • -p prints the database
      • -Rr suppresses inclusion of built-in rules and variables
      • -q only tests the up-to-date-status of a target (without remaking anything), but that by itself doesn't prevent execution of recipe commands in all cases; hence:
      • -f $(lastword $(MAKEFILE_LIST)) ensures that the same makefile is targeted as in the original invocation, regardless of whether it was targeted implicitly or explicitly with -f ....
        Caveat: This will break if your makefile contains include directives; to address this, define variable THIS_FILE := $(lastword $(MAKEFILE_LIST)) before any include directives and use -f $(THIS_FILE) instead.
      • : is a deliberately invalid target that is meant to ensure that no commands are executed; 2>/dev/null suppresses the resulting error message. Note: This relies on -p printing the database nonetheless, which is the case as of GNU make 3.82. Sadly, GNU make offers no direct option to just print the database, without also executing the default (or given) task; if you don't need to target a specific Makefile, you may use make -p -f/dev/null, as recommended in the man page.
  • -v RS=

    • This is an awk idiom that breaks the input into blocks of contiguous non-empty lines.
  • /^# File/,/^# Finished Make data base/

    • Matches the range of lines in the output that contains all targets (true as of GNU make 3.82) - by limiting parsing to this range, there is no need to deal with false positives from other output sections.
  • if ($$1 !~ "^[#.]")

    • Selectively ignores blocks:
      • # ... ignores non-targets, whose blocks start with # Not a target:
      • . ... ignores special targets
    • All other blocks should each start with a line containing only the name of an explicitly defined target followed by :
  • egrep -v -e '^[^[:alnum:]]' -e '^$@$$' removes unwanted targets from the output:

    • '^[^[:alnum:]]' ... excludes hidden targets, which - by convention - are targets that start neither with a letter nor a digit.
    • '^$@$$' ... excludes the list target itself

Running make list then prints all targets, each on its own line; you can pipe to xargs to create a space-separated list instead.

Loop through an array of strings in Bash?

I loop through an array of my projects for a git pull update:

#!/bin/sh
projects="
web
ios
android
"
for project in $projects do
    cd  $HOME/develop/$project && git pull
end

Efficient way to determine number of digits in an integer

convert to string and then use built-in functions

unsigned int i;
cout<< to_string(i).length()<<endl;

bypass invalid SSL certificate in .net core

ServicePointManager.ServerCertificateValidationCallback isn't supported in .Net Core.

Current situation is that it will be a a new ServerCertificateCustomValidationCallback method for the upcoming 4.1.* System.Net.Http contract (HttpClient). .NET Core team are finalizing the 4.1 contract now. You can read about this in here on github

You can try out the pre-release version of System.Net.Http 4.1 by using the sources directly here in CoreFx or on the MYGET feed: https://dotnet.myget.org/gallery/dotnet-core

Current WinHttpHandler.ServerCertificateCustomValidationCallback definition on Github

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

Did you accidentally create the repository using the root user?

It just happens that I created the git repository as the root user.

I deleted the git repository and created it again without sudo and it works.

Generate Java classes from .XSD files...?

Well best option is %java_home%\bin\xjc -p [your namespace] [xsd_file].xsd.

I also have a question if we have an option to do reverse engineering here. if yes can we generate xsd from pojo class?

Using SSH keys inside docker container

A concise overview of the challenges of SSH inside Docker containers is detailed here. For connecting to trusted remotes from within a container without leaking secrets there are a few ways:

Beyond these there's also the possibility of using a key-store running in a separate docker container accessible at runtime when using Compose. The drawback here is additional complexity due to the machinery required to create and manage a keystore such as Vault by HashiCorp.

For SSH key use in a stand-alone Docker container see the methods linked above and consider the drawbacks of each depending on your specific needs. If, however, you're running inside Compose and want to share a key to an app at runtime (reflecting practicalities of the OP) try this:

  • Create a docker-compose.env file and add it to your .gitignore file.
  • Update your docker-compose.yml and add env_file for service requiring the key.
  • Access public key from environment at application runtime, e.g. process.node.DEPLOYER_RSA_PUBKEY in the case of a Node.js application.

The above approach is ideal for development and testing and, while it could satisfy production requirements, in production you're better off using one of the other methods identified above.

Additional resources:

Get battery level and state in Android

Based on official android docs, you can use this method in a Helper or Util class to get current battery percentage:

Java version:

public static int getBatteryPercentage(Context context) {

    if (Build.VERSION.SDK_INT >= 21) {

         BatteryManager bm = (BatteryManager) context.getSystemService(BATTERY_SERVICE);
         return bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);

    } else {

         IntentFilter iFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
         Intent batteryStatus = context.registerReceiver(null, iFilter);

         int level = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) : -1;
         int scale = batteryStatus != null ? batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1) : -1;

         double batteryPct = level / (double) scale;

         return (int) (batteryPct * 100);
   }
}

Kotlin version:

fun getBatteryPercentage(context: Context): Int {
    return if (Build.VERSION.SDK_INT >= 21) {
        val bm = context.getSystemService(BATTERY_SERVICE) as BatteryManager
        bm.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY)
    
    } else {
        val iFilter = IntentFilter(Intent.ACTION_BATTERY_CHANGED)
        val batteryStatus: Intent = context.registerReceiver(null, iFilter)
        val level = batteryStatus?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1)
        val scale = batteryStatus?.getIntExtra(BatteryManager.EXTRA_SCALE, -1)
        val batteryPct = level / scale.toDouble()
        (batteryPct * 100).toInt()
    }
}

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

Lots of answers here, but here comes a working example with code that you can copy and paste and test immediately:

For me the error 12514 was solved after specifying the correct SERVICE_NAME. You find that on the server in the file tnsnames.ora which comes with 3 predefined service names (one of them is "XE").

  1. I installed the Oracle Express database OracleXE112 which already comes with some preinstalled demo tables.
  2. When you start the installer you are asked for a password. I entered "xxx" as password. (not used in production)
  3. My server runs on the machine 192.168.1.158
  4. On the server you must explicitely allow access for the process TNSLSNR.exe in the Windows Firewall. This process listens on port 1521.
  5. OPTION A: For C# (.NET2 or .NET4) you can download ODAC11, from which you have to add Oracle.DataAccess.dll to your project. Additionally this DLL depends on: OraOps11w.dll, oci.dll, oraociei11.dll (130MB!), msvcr80.dll. These DLLs must be in the same directory as the EXE or you must specify the DLL path in: HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\ODP.NET\4.112.4.0\DllPath. On 64 bit machines write additionally to HKLM\SOFTWARE\Wow6432Node\Oracle\...
  6. OPTION B: If you have downloaded ODAC12 you need Oracle.DataAccess.dll, OraOps12w.dll, oci.dll, oraociei12.dll (160MB!), oraons.dll, msvcr100.dll. The Registry path is HKEY_LOCAL_MACHINE\SOFTWARE\Oracle\ODP.NET\4.121.2.0\DllPath
  7. OPTION C: If you don't want huge DLL's of more than 100 MB you should download ODP.NET_Managed12.x.x.x.xxxxx.zip in which you find Oracle.ManagedDataAccess.dll which is only 4 MB and is a pure managed DLL which works in 32 bit and 64 bit processes as well and depends on no other DLL and does not require any registry entries.
  8. The following C# code works for me without any configuration on the server side (just the default installation):
using Oracle.DataAccess.Client;
or
using Oracle.ManagedDataAccess.Client;

....

string oradb = "Data Source=(DESCRIPTION="
    + "(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=192.168.1.158)(PORT=1521)))"
    + "(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=XE)));"
    + "User Id=SYSTEM;Password=xxx;";

using (OracleConnection conn = new OracleConnection(oradb)) 
{
    conn.Open();
    using (OracleCommand cmd = new OracleCommand())
    {
        cmd.Connection  = conn;
        cmd.CommandText = "select TABLESPACE_NAME from DBA_DATA_FILES";

        using (OracleDataReader dr = cmd.ExecuteReader())
        {
            while (dr.Read())
            {
                listBox.Items.Add(dr["TABLESPACE_NAME"]);
            }
        }
    }
}

If the SERVICE_NAME=XE is wrong you get error 12514. The SERVICE_NAME is optional. You can also leave it away.

How to pass url arguments (query string) to a HTTP request on Angular?

In latest Angular 7/8, you can use the simplest approach:-

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

getDetails(searchParams) {
    const httpOptions = {
        headers: { 'Content-Type': 'application/json' },
        params: { ...searchParams}
    };
    return this.http.get(this.Url, httpOptions);
}

Can multiple different HTML elements have the same ID if they're different elements?

I think you can't do it because Id is unique you have to use it for one element . You can use class for the purpose

CSS align one item right with flexbox

For a terse, pure flexbox option, group the left-aligned items and the right-aligned items:

<div class="wrap">
  <div>
    <span>One</span>
    <span>Two</span>
  </div>
  <div>Three</div>
</div>

and use space-between:

.wrap {
  display: flex;
  background: #ccc;
  justify-content: space-between;
}

This way you can group multiple items to the right(or just one).

https://jsfiddle.net/c9mkewwv/3/

Flutter- wrapping text

You can use Flexible, in this case the person.name could be a long name (Labels and BlankSpace are custom classes that return widgets) :

new Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: <Widget>[
   new Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        new Flexible(
            child: Labels.getTitle_2(person.name,
            color: StyleColors.COLOR_BLACK)),
        BlankSpace.column(3),
        Labels.getTitle_1(person.likes())
      ]),
    BlankSpace.row(3),
    Labels.getTitle_2(person.shortDescription),
  ],
)

JavaScript Uncaught ReferenceError: jQuery is not defined; Uncaught ReferenceError: $ is not defined

You have an error in you script tag construction, this:

<script language="JavaScript" type="text/javascript" script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

Should look like this:

<script language="JavaScript" type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.0/jquery-ui.min.js"></script>

You have a 'script' word lost in the middle of your script tag. Also you should remove the http:// to let the browser decide whether to use HTTP or HTTPS.

UPDATE

But your main error is that you are including jQuery UI (ONLY) you must include jQuery first! jQuery UI and jQuery are used together, not in separate. jQuery UI depends on jQuery. You should put this line before jQuery UI:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

Linear regression with matplotlib / numpy

This code:

from scipy.stats import linregress

linregress(x,y) #x and y are arrays or lists.

gives out a list with the following:

slope : float
slope of the regression line
intercept : float
intercept of the regression line
r-value : float
correlation coefficient
p-value : float
two-sided p-value for a hypothesis test whose null hypothesis is that the slope is zero
stderr : float
Standard error of the estimate

Source

Less than or equal to

There is no => for if.
Use if %energy% GEQ %m2enc%

See if /? for some other details.

Mysql - delete from multiple tables with one query

The documentation for DELETE tells you the multi-table syntax.

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    tbl_name[.*] [, tbl_name[.*]] ...
    FROM table_references
    [WHERE where_condition]

Or:

DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
    FROM tbl_name[.*] [, tbl_name[.*]] ...
    USING table_references
    [WHERE where_condition]

Keystore type: which one to use?

Here is a post which introduces different types of keystore in Java and the differences among different types of keystore. http://www.pixelstech.net/article/1408345768-Different-types-of-keystore-in-Java----Overview

Below are the descriptions of different keystores from the post:

JKS, Java Key Store. You can find this file at sun.security.provider.JavaKeyStore. This keystore is Java specific, it usually has an extension of jks. This type of keystore can contain private keys and certificates, but it cannot be used to store secret keys. Since it's a Java specific keystore, so it cannot be used in other programming languages.

JCEKS, JCE key store. You can find this file at com.sun.crypto.provider.JceKeyStore. This keystore has an extension of jceks. The entries which can be put in the JCEKS keystore are private keys, secret keys and certificates.

PKCS12, this is a standard keystore type which can be used in Java and other languages. You can find this keystore implementation at sun.security.pkcs12.PKCS12KeyStore. It usually has an extension of p12 or pfx. You can store private keys, secret keys and certificates on this type.

PKCS11, this is a hardware keystore type. It servers an interface for the Java library to connect with hardware keystore devices such as Luna, nCipher. You can find this implementation at sun.security.pkcs11.P11KeyStore. When you load the keystore, you no need to create a specific provider with specific configuration. This keystore can store private keys, secret keys and cetrificates. When loading the keystore, the entries will be retrieved from the keystore and then converted into software entries.

Bootstrap with jQuery Validation Plugin

Here is what I use when adding validation to form:

// Adding validation to form.
        $(form).validate({
            rules: {
                title: {
                    required: true,
                    minlength: 3,
                },
                server: {
                    ipAddress: true,
                    required: true
                }   
            },
            highlight: function(element) {
                $(element).closest('.form-group').removeClass('has-success').addClass('has-error');
            },
            success: function(element) {
                $(element).closest('.form-group').removeClass('has-error').addClass('has-success');
            },
            errorClass: 'help-block'
        });

This worked for me for Bootstrap 3 styling when using the jquery validation library.

javascript: calculate x% of a number

var result = (35.8 / 100) * 10000;

(Thank you jball for this change of order of operations. I didn't consider it).

AngularJS: Basic example to use authentication in Single Page Application

I think that every JSON response should contain a property (e.g. {authenticated: false}) and the client has to test it everytime: if false, then the Angular controller/service will "redirect" to the login page.

And what happen if the user catch de JSON and change the bool to True?

I think you should never rely on client side to do these kind of stuff. If the user is not authenticated, the server should just redirect to a login/error page.

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

#temp is materalized and CTE is not.

CTE is just syntax so in theory it is just a subquery. It is executed. #temp is materialized. So an expensive CTE in a join that is execute many times may be better in a #temp. On the other side if it is an easy evaluation that is not executed but a few times then not worth the overhead of #temp.

The are some people on SO that don't like table variable but I like them as the are materialized and faster to create than #temp. There are times when the query optimizer does better with a #temp compared to a table variable.

The ability to create a PK on a #temp or table variable gives the query optimizer more information than a CTE (as you cannot declare a PK on a CTE).

How to save a new sheet in an existing excel file, using Pandas?

For creating a new file

x1 = np.random.randn(100, 2)
df1 = pd.DataFrame(x1)
with pd.ExcelWriter('sample.xlsx') as writer:  
    df1.to_excel(writer, sheet_name='x1')

For appending to the file, use the argument mode='a' in pd.ExcelWriter.

x2 = np.random.randn(100, 2)
df2 = pd.DataFrame(x2)
with pd.ExcelWriter('sample.xlsx', engine='openpyxl', mode='a') as writer:  
    df2.to_excel(writer, sheet_name='x2')

Default is mode ='w'. See documentation.

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

"sed" command in bash

sed is the Stream EDitor. It can do a whole pile of really cool things, but the most common is text replacement.

The s,%,$,g part of the command line is the sed command to execute. The s stands for substitute, the , characters are delimiters (other characters can be used; /, : and @ are popular). The % is the pattern to match (here a literal percent sign) and the $ is the second pattern to match (here a literal dollar sign). The g at the end means to globally replace on each line (otherwise it would only update the first match).

Regex in JavaScript for validating decimal numbers

Please see my project of the cross-browser filter of value of the text input element on your web page using JavaScript language: Input Key Filter . You can filter the value as an integer number, a float number, or write a custom filter, such as a phone number filter. See an example of custom filter of input of an float number with decimal pointer and limitation to 2 digit after decimal pointer:

_x000D_
_x000D_
<!doctype html>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" >_x000D_
<head>_x000D_
    <title>Input Key Filter Test</title>_x000D_
 <meta name="author" content="Andrej Hristoliubov [email protected]">_x000D_
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>_x000D_
 _x000D_
 <!-- For compatibility of IE browser with audio element in the beep() function._x000D_
 https://www.modern.ie/en-us/performance/how-to-use-x-ua-compatible -->_x000D_
 <meta http-equiv="X-UA-Compatible" content="IE=9"/>_x000D_
 _x000D_
 <link rel="stylesheet" href="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.css" type="text/css">  _x000D_
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/Common.js"></script>_x000D_
 <script type="text/javascript" src="https://rawgit.com/anhr/InputKeyFilter/master/InputKeyFilter.js"></script>_x000D_
 _x000D_
</head>_x000D_
<body>_x000D_
 <h1>Float field</h1>_x000D_
<input id="Float" _x000D_
 onchange="javascript: onChangeFloat(this)"_x000D_
 onblur="inputKeyFilter.isNaN(parseFloat(this.value), this);"_x000D_
/>_x000D_
<script>_x000D_
 function CreateFloatFilterCustom(elementID, onChange, onblur){_x000D_
  try{_x000D_
   inputKeyFilter.Create(elementID_x000D_
    , onChange_x000D_
    , function(elementInput, value){//customFilter_x000D_
     if(value.match(/^(-?\d*)((\.(\d{0,2})?)?)$/i) == null){_x000D_
      inputKeyFilter.TextAdd(isRussian() ?_x000D_
        "?????????? ??????: -[0...9].[0...9] ??? -[0...9]e-[0...9]. ????????: -12.34 1234"_x000D_
        : "Acceptable formats: -[0...9].[0...9] or -[0...9]e-[0...9]. Examples: -12.34 1234"_x000D_
       , elementInput);_x000D_
      return false;_x000D_
     }_x000D_
     return true;_x000D_
    }_x000D_
    , onblur_x000D_
   )_x000D_
  } catch(e) {_x000D_
   consoleError("Create float filter failed. " + e);_x000D_
  }_x000D_
 }_x000D_
 _x000D_
 CreateFloatFilterCustom("Float");_x000D_
 _x000D_
 function onChangeFloat(input){_x000D_
  inputKeyFilter.RemoveMyTooltip();_x000D_
  var elementNewFloat = document.getElementById("NewFloat");_x000D_
  var float = parseFloat(input.value);_x000D_
  if(inputKeyFilter.isNaN(float, input)){_x000D_
   elementNewFloat.innerHTML = "";_x000D_
   return;_x000D_
  }_x000D_
  elementNewFloat.innerHTML = float;_x000D_
 }_x000D_
</script>_x000D_
 New float: <span id="NewFloat"></span>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Also see my page example of the input key filter

ASP.NET - How to write some html in the page? With Response.Write?

If you want something lighter than a Label or other ASP.NET-specific server control you can just use a standard HTML DIV or SPAN and with runat="server", e.g.:

Markup:

<span runat="server" id="FooSpan"></span>

Code:

FooSpan.Text = "Foo";

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

You can use below code for your solution:-

public void Linq94() 
{ 
    int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 }; 
    int[] numbersB = { 1, 3, 5, 7, 8 }; 

    var allNumbers = numbersA.Concat(numbersB); 

    Console.WriteLine("All numbers from both arrays:"); 
    foreach (var n in allNumbers) 
    { 
        Console.WriteLine(n); 
    } 
}

String strip() for JavaScript?

A better polyfill from the MDN that supports removal of BOM and NBSP:

if (!String.prototype.trim) {
  String.prototype.trim = function () {
    return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  };
}

Bear in mind that modifying built-in prototypes comes with a performance hit (due to the JS engine bailing on a number of runtime optimizations), and in performance critical situations you may need to consider the alternative of defining myTrimFunction(string) instead. That being said, if you are targeting an older environment without native .trim() support, you are likely to have more important performance issues to deal with.

PHP - Copy image to my server direct from URL

From Copy images from url to server, delete all images after

function getimg($url) {         
    $headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';              
    $headers[] = 'Connection: Keep-Alive';         
    $headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';         
    $user_agent = 'php';         
    $process = curl_init($url);         
    curl_setopt($process, CURLOPT_HTTPHEADER, $headers);         
    curl_setopt($process, CURLOPT_HEADER, 0);         
    curl_setopt($process, CURLOPT_USERAGENT, $user_agent); //check here         
    curl_setopt($process, CURLOPT_TIMEOUT, 30);         
    curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);         
    curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);         
    $return = curl_exec($process);         
    curl_close($process);         
    return $return;     
} 

$imgurl = 'http://www.foodtest.ru/images/big_img/sausage_3.jpg'; 
$imagename= basename($imgurl);
if(file_exists('./tmp/'.$imagename)){continue;} 
$image = getimg($imgurl); 
file_put_contents('tmp/'.$imagename,$image);       

How to gettext() of an element in Selenium Webdriver

You need to store it in a String variable first before displaying it like so:

String Txt = TxtBoxContent.getText();
System.out.println(Txt);

How to keep the local file or the remote file during merge using Git and the command line?

This approach seems more straightforward, avoiding the need to individually select each file:

# keep remote files
git merge --strategy-option theirs
# keep local files
git merge --strategy-option ours

or

# keep remote files
git pull -Xtheirs
# keep local files
git pull -Xours

Copied directly from: Resolve Git merge conflicts in favor of their changes during a pull

Moq, SetupGet, Mocking a property

But while mocking read-only properties means properties with getter method only you should declare it as virtual otherwise System.NotSupportedException will be thrown because it is only supported in VB as moq internally override and create proxy when we mock anything.

Mac SQLite editor

I've published instructions for how to run the Firefox SQLite Manager outside of Firefox, since FF hase become so bloated in the last few releases. It's really easy and I've even compiled a DMG for the sqlite gui if anyone wants it.

MVC 3 file upload and model binding

Your form doesn't contain any input tag other than the file so in your controller action you cannot expect to get anything else than the uploaded file (that's all that's being sent to the server). One way to achieve this would be to include a hidden tag containing the id of the model which will allow you to retrieve it from your datastore inside the controller action you are posting to (use this if the user is not supposed to modify the model but simply attach a file):

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.HiddenFor(x => x.Id)
    <input type="file" name="file" id="file" />
    <input type="submit" value="submit" />
}

and then in your controller action:

[HttpPost]
public ActionResult Uploadfile(int id, HttpPostedFileBase file)
{
    Containers containers = Repository.GetContainers(id);
    ...
}

On the other hand if you wanted to allow the user to modify this model then you will need to include the proper input fields for each field of your model that you want to be sent to the server:

@using (Html.BeginForm("Uploadfile", "Containers", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.TextBoxFor(x => x.Prop1)
    @Html.TextBoxFor(x => x.Prop2)
    @Html.TextBoxFor(x => x.Prop3)
    <input type="file" name="file" id="file" />
    <input type="submit" value="submit" />
}

and then you will have the default model binder reconstruct this model from the request:

[HttpPost]
public ActionResult Uploadfile(Container containers, HttpPostedFileBase file)
{
    ...
}

Angular2 QuickStart npm start is not working correctly

First you need update npm, lite-server and typescript:

sudo npm update -g && sudo npm install -g concurrently lite-server typescript

Delete node_modules folder from your Angular project directory (if exist). Next run:

npm install

After that resolve ENOSPC errors:

echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

Finally:

npm start

This is my package.json file:

_x000D_
_x000D_
{_x000D_
  "name": "reservationsystem",_x000D_
  "version": "0.0.1",_x000D_
  "scripts": {_x000D_
    "tsc": "tsc",_x000D_
    "tsc:w": "tsc -w",_x000D_
    "lite": "lite-server",_x000D_
    "start": "concurrent \"npm run tsc:w\" \"npm run lite\" "_x000D_
  },_x000D_
  "dependencies": {_x000D_
    "a2-in-memory-web-api": "~0.1.0",_x000D_
    "angular2": "2.0.0-beta.3",_x000D_
    "es6-promise": "^3.0.2",_x000D_
    "es6-shim": "^0.33.3",_x000D_
    "reflect-metadata": "0.1.2",_x000D_
    "rxjs": "5.0.0-beta.0",_x000D_
    "systemjs": "0.19.17",_x000D_
    "zone.js": "0.5.11"_x000D_
  },_x000D_
  "devDependencies": {_x000D_
    "concurrently": "^1.0.0",_x000D_
    "lite-server": "^2.0.1",_x000D_
    "typescript": "^1.7.5"_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

What is the size of a pointer?

On 32-bit machine sizeof pointer is 32 bits ( 4 bytes), while on 64 bit machine it's 8 byte. Regardless of what data type they are pointing to, they have fixed size.

URL rewriting with PHP

You can essentially do this 2 ways:

The .htaccess route with mod_rewrite

Add a file called .htaccess in your root folder, and add something like this:

RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1

This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:

The PHP route

Put the following in your .htaccess instead: (note the leading slash)

FallbackResource /index.php

This will tell it to run your index.php for all files it cannot normally find in your site. In there you can then for example:

$path = ltrim($_SERVER['REQUEST_URI'], '/');    // Trim leading slash(es)
$elements = explode('/', $path);                // Split path on slashes
if(empty($elements[0])) {                       // No path elements means home
    ShowHomepage();
} else switch(array_shift($elements))             // Pop off first item and switch
{
    case 'Some-text-goes-here':
        ShowPicture($elements); // passes rest of parameters to internal function
        break;
    case 'more':
        ...
    default:
        header('HTTP/1.1 404 Not Found');
        Show404Error();
}

This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess will do fine though.

How to quickly and conveniently disable all console.log statements in my code?

I have used winston logger earlier.

Nowadays I am using below simpler code from experience:

  1. Set the environment variable from cmd/ command line (on Windows):

    cmd
    setx LOG_LEVEL info
    

Or, you could have a variable in your code if you like, but above is better.

  1. Restart cmd/ command line, or, IDE/ editor like Netbeans

  2. Have below like code:

    console.debug = console.log;   // define debug function
    console.silly = console.log;   // define silly function
    
    switch (process.env.LOG_LEVEL) {
        case 'debug':
        case 'silly':
            // print everything
            break;
    
        case 'dir':
        case 'log':
            console.debug = function () {};
            console.silly = function () {};
            break;
    
        case 'info':
            console.debug = function () {};
            console.silly = function () {};
            console.dir = function () {};
            console.log = function () {};
            break;
    
        case 'trace':   // similar to error, both may print stack trace/ frames
        case 'warn':    // since warn() function is an alias for error()
        case 'error':
            console.debug = function () {};
            console.silly = function () {};
            console.dir = function () {};
            console.log = function () {};
            console.info = function () {};
            break;
    }
    
  3. Now use all console.* as below:

    console.error(' this is a error message '); // will print
    console.warn(' this is a warn message '); // will print
    console.trace(' this is a trace message '); // will print
    console.info(' this is a info message '); // will print, LOG_LEVEL is set to this
    
    console.log(' this is a log message '); // will NOT print
    console.dir(' this is a dir message '); // will NOT print
    console.silly(' this is a silly message '); // will NOT print
    console.debug(' this is a debug message '); // will NOT print
    

Now, based on your LOG_LEVEL settings made in the point 1 (like, setx LOG_LEVEL log and restart command line), some of the above will print, others won't print

Hope that helped.

Build Android Studio app via command line

Try this (OS X only):

brew install homebrew/versions/gradle110
gradle build

You can use gradle tasks to see all tasks available for the current project. No Android Studio is needed here.

Using RegEX To Prefix And Append In Notepad++

Assuming alphanumeric words, you can use:

Search  = ^([A-Za-z0-9]+)$
Replace = able:"\1"

Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):

Search = ^(.+)$

^ points to the start of the line.
$ points to the end of the line.

\1 will be the source match within the parentheses.

git diff between two different files

Specify the paths explicitly:

git diff HEAD:full/path/to/foo full/path/to/bar

Check out the --find-renames option in the git-diff docs.

Credit: twaggs.

Finding square root without using sqrt function?

Here is a very simple but unsafe approach to find the square-root of a number. Unsafe because it only works by natural numbers, where you know that the base respectively the exponent are natural numbers. I had to use it for a task where i was neither allowed to use the #include<cmath> -library, nor i was allowed to use pointers.

potency = base ^ exponent

// FUNCTION: square-root
int sqrt(int x)
{
    int quotient = 0;
    int i = 0;

    bool resultfound = false;
    while (resultfound == false) {
        if (i*i == x) {
          quotient = i;
          resultfound = true;
        }
        i++;
    }
    return quotient;
}

Bootstrap 4 align navbar items to the right

It's little change in boostrap 4. To align navbar to right side, you've to make only two changes. they are:

  1. in navbar-nav class add w-100 as navbar-nav w-100 to make width as 100
  2. in nav-item dropdown class add ml-auto as nav-item dropdown ml-auto to make margin left as auto.

If you didn't understand, please refer the image that i've attached to this.

CodePen Link

enter image description here

Full source code

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarNavDropdown">
    <ul class="navbar-nav w-100">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricing</a>
      </li>
      <li class="nav-item dropdown ml-auto">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown link
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
    </ul>  
  </div>
</nav>

How to call a method after a delay in Android

More Safety - With Kotlin

Most of the answers use Handler but I give a different solution to delay in activity, fragment, view model with Android Lifecycle ext. This way will auto cancel when the lifecycle begins destroyed.

In Activity or Fragment:

lifecycleScope.launch { 
  delay(DELAY_MS)
  doSomething()
}

In ViewModel:

viewModelScope.lanch {
  delay(DELAY_MS)
  doSomething()
}

In suspend function: (Kotlin Coroutine)

suspend fun doSomethingAfter(){
    delay(DELAY_MS)
    doSomething()
}

If you get an error with the lifecycleScope not found - import to gradle file:

implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.2.0"

Spring Boot - Error creating bean with name 'dataSource' defined in class path resource

In my case I just ignored the following in application.properties file:

# Hibernate

#spring.jpa.hibernate.ddl-auto=update

It works for me....

Remove all subviews?

For ios6 using autolayout I had to add a little bit of code to remove the constraints too.

NSMutableArray * constraints_to_remove = [ @[] mutableCopy] ;
for( NSLayoutConstraint * constraint in tagview.constraints) {
    if( [tagview.subviews containsObject:constraint.firstItem] ||
       [tagview.subviews containsObject:constraint.secondItem] ) {
        [constraints_to_remove addObject:constraint];
    }
}
[tagview removeConstraints:constraints_to_remove];

[ [tagview subviews] makeObjectsPerformSelector:@selector(removeFromSuperview)];

I'm sure theres a neater way to do this, but it worked for me. In my case I could not use a direct [tagview removeConstraints:tagview.constraints] as there were constraints set in XCode that were getting cleared.

Very simple log4j2 XML configuration file using Console and File appender

log4j2 has a very flexible configuration system (which IMHO is more a distraction than a help), you can even use JSON. See https://logging.apache.org/log4j/2.x/manual/configuration.html for a reference.

Personally, I just recently started using log4j2, but I'm tending toward the "strict XML" configuration (that is, using attributes instead of element names), which can be schema-validated.

Here is my simple example using autoconfiguration and strict mode, using a "Property" for setting the filename:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorinterval="30" status="info" strict="true">
    <Properties>
        <Property name="filename">log/CelsiusConverter.log</Property>
    </Properties>
    <Appenders>
        <Appender type="Console" name="Console">
            <Layout type="PatternLayout" pattern="%d %p [%t] %m%n" />
        </Appender>
        <Appender type="Console" name="FLOW">
            <Layout type="PatternLayout" pattern="%C{1}.%M %m %ex%n" />
        </Appender>
        <Appender type="File" name="File" fileName="${filename}">
            <Layout type="PatternLayout" pattern="%d %p %C{1.} [%t] %m%n" />
        </Appender>
    </Appenders>
    <Loggers>
        <Root level="debug">
            <AppenderRef ref="File" />
            <AppenderRef ref="Console" />
            <!-- Use FLOW to trace down exact method sending the msg -->
            <!-- <AppenderRef ref="FLOW" /> -->
        </Root>
    </Loggers>
</Configuration>

C++ printing boolean, what is displayed?

0 will get printed.

As in C++ true refers to 1 and false refers to 0.

In case, you want to print false instead of 0,then you have to sets the boolalpha format flag for the str stream.

When the boolalpha format flag is set, bool values are inserted/extracted by their textual representation: either true or false, instead of integral values.

#include <iostream>
int main()
{
  std::cout << std::boolalpha << false << std::endl;
}

output:

false

IDEONE

How to pass complex object to ASP.NET WebApi GET from jQuery ajax call?

If you append json data to query string, and parse it later in web api side. you can parse complex object. It's useful rather than post json object style. This is my solution.

//javascript file 
var data = { UserID: "10", UserName: "Long", AppInstanceID: "100", ProcessGUID: "BF1CC2EB-D9BD-45FD-BF87-939DD8FF9071" };
var request = JSON.stringify(data);
request = encodeURIComponent(request);

doAjaxGet("/ProductWebApi/api/Workflow/StartProcess?data=", request, function (result) {
    window.console.log(result);
});

//webapi file:
[HttpGet]
public ResponseResult StartProcess()
{
    dynamic queryJson = ParseHttpGetJson(Request.RequestUri.Query);
        int appInstanceID = int.Parse(queryJson.AppInstanceID.Value);
    Guid processGUID = Guid.Parse(queryJson.ProcessGUID.Value);
    int userID = int.Parse(queryJson.UserID.Value);
    string userName = queryJson.UserName.Value;
}

//utility function:
public static dynamic ParseHttpGetJson(string query)
{
    if (!string.IsNullOrEmpty(query))
    {
        try
        {
            var json = query.Substring(7, query.Length - 7); //seperate ?data= characters
            json = System.Web.HttpUtility.UrlDecode(json);
            dynamic queryJson = JsonConvert.DeserializeObject<dynamic>(json);

            return queryJson;
        }
        catch (System.Exception e)
        {
            throw new ApplicationException("can't deserialize object as wrong string content!", e);
        }
    }
    else
    {
        return null;
    }
}

SSLHandshakeException: No subject alternative names present

Unlike some browsers, Java follows the HTTPS specification strictly when it comes to the server identity verification (RFC 2818, Section 3.1) and IP addresses.

When using a host name, it's possible to fall back to the Common Name in the Subject DN of the server certificate, instead of using the Subject Alternative Name.

When using an IP address, there must be a Subject Alternative Name entry (of type IP address, not DNS name) in the certificate.

You'll find more details about the specification and how to generate such a certificate in this answer.

How to create global variables accessible in all views using Express / Node.JS?

you can also use "global"

Example:

declare like this :

  app.use(function(req,res,next){
      global.site_url = req.headers.host;   // hostname = 'localhost:8080'
      next();
   });

Use like this: in any views or ejs file <% console.log(site_url); %>

in js files console.log(site_url);