Programs & Examples On #Type 2 dimension

@Nullable annotation usage

Different tools may interpret the meaning of @Nullable differently. For example, the Checker Framework and FindBugs handle @Nullable differently.

How to pick just one item from a generator?

Create a generator using

g = myfunct()

Everytime you would like an item, use

next(g)

(or g.next() in Python 2.5 or below).

If the generator exits, it will raise StopIteration. You can either catch this exception if necessary, or use the default argument to next():

next(g, default_value)

HTML-encoding lost when attribute read from input field

<script>
String.prototype.htmlEncode = function () {
    return String(this)
        .replace(/&/g, '&amp;')
        .replace(/"/g, '&quot;')
        .replace(/'/g, '&#39;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;');

}

var aString = '<script>alert("I hack your site")</script>';
console.log(aString.htmlEncode());
</script>

Will output: &lt;script&gt;alert(&quot;I hack your site&quot;)&lt;/script&gt;

.htmlEncode() will be accessible on all strings once defined.

How to create an empty R vector to add new items

You can create an empty vector like so

vec <- numeric(0)

And then add elements using c()

vec <- c(vec, 1:5)

However as romunov says, it's much better to pre-allocate a vector and then populate it (as this avoids reallocating a new copy of your vector every time you add elements)

Where's my JSON data in my incoming Django request?

request.raw_response is now deprecated. Use request.body instead to process non-conventional form data such as XML payloads, binary images, etc.

Django documentation on the issue.

Measuring code execution time

If you are looking for the amount of time that the associated thread has spent running code inside the application.
You can use ProcessThread.UserProcessorTime Property which you can get under System.Diagnostics namespace.

TimeSpan startTime= Process.GetCurrentProcess().Threads[i].UserProcessorTime; // i being your thread number, make it 0 for main
//Write your function here
TimeSpan duration = Process.GetCurrentProcess().Threads[i].UserProcessorTime.Subtract(startTime);

Console.WriteLine($"Time caluclated by CurrentProcess method: {duration.TotalSeconds}"); // This syntax works only with C# 6.0 and above

Note: If you are using multi threads, you can calculate the time of each thread individually and sum it up for calculating the total duration.

Partly cherry-picking a commit with Git

Assuming the changes you want are at the head of the branch you want the changes from, use git checkout

for a single file :

git checkout branch_that_has_the_changes_you_want path/to/file.rb

for multiple files just daisy chain :

git checkout branch_that_has_the_changes_you_want path/to/file.rb path/to/other_file.rb

how to query child objects in mongodb

Assuming your "states" collection is like:

{"name" : "Spain", "cities" : [ { "name" : "Madrid" }, { "name" : null } ] }
{"name" : "France" }

The query to find states with null cities would be:

db.states.find({"cities.name" : {"$eq" : null, "$exists" : true}});

It is a common mistake to query for nulls as:

db.states.find({"cities.name" : null});

because this query will return all documents lacking the key (in our example it will return Spain and France). So, unless you are sure the key is always present you must check that the key exists as in the first query.

java.lang.ClassNotFoundException: javax.servlet.jsp.jstl.core.Config

The error is telling you it cannot find the class because it is not available in your application.

If you are using Maven, make sure you have the dependency for jstl artifact:

<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
</dependency>

If you are not using it, just make sure you include the JAR in your classpath. See this answer for download links.

Ruby - ignore "exit" in code

loop {   begin     Bar.new   rescue SystemExit     p $!  #: #<SystemExit: exit>   end } 

This will print #<SystemExit: exit> in an infinite loop, without ever exiting.

How to check if a process id (PID) exists

You have two ways:

Lets start by looking for a specific application in my laptop:

[root@pinky:~]# ps fax | grep mozilla
 3358 ?        S      0:00  \_ /bin/sh /usr/lib/firefox-3.5/run-mozilla.sh /usr/lib/firefox-3.5/firefox
16198 pts/2    S+     0:00              \_ grep mozilla

All examples now will look for PID 3358.

First way: Run "ps aux" and grep for the PID in the second column. In this example I look for firefox, and then for it's PID:

[root@pinky:~]# ps aux | awk '{print $2 }' | grep 3358
3358

So your code will be:

if [ ps aux | awk '{print $2 }' | grep -q $PID 2> /dev/null ]; then
    kill $PID 
fi

Second way: Just look for something in the /proc/$PID directory. I am using "exe" in this example, but you can use anything else.

[root@pinky:~]# ls -l /proc/3358/exe 
lrwxrwxrwx. 1 elcuco elcuco 0 2010-06-15 12:33 /proc/3358/exe -> /bin/bash

So your code will be:

if [ -f /proc/$PID/exe ]; then
    kill $PID 
fi

BTW: whats wrong with kill -9 $PID || true ?


EDIT:

After thinking about it for a few months.. (about 24...) the original idea I gave here is a nice hack, but highly unportable. While it teaches a few implementation details of Linux, it will fail to work on Mac, Solaris or *BSD. It may even fail on future Linux kernels. Please - use "ps" as described in other responses.

Difference between except: and except Exception as e: in Python

There are differences with some exceptions, e.g. KeyboardInterrupt.

Reading PEP8:

A bare except: clause will catch SystemExit and KeyboardInterrupt exceptions, making it harder to interrupt a program with Control-C, and can disguise other problems. If you want to catch all exceptions that signal program errors, use except Exception: (bare except is equivalent to except BaseException:).

scikit-learn random state in splitting dataset

The random_state splits a randomly selected data but with a twist. And the twist is the order of the data will be same for a particular value of random_state.You need to understand that it's not a bool accpeted value. starting from 0 to any integer no, if you pass as random_state,it'll be a permanent order for it. Ex: the order you will get in random_state=0 remain same. After that if you execuit random_state=5 and again come back to random_state=0 you'll get the same order. And like 0 for all integer will go same. How ever random_state=None splits randomly each time.

If still having doubt watch this

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Clear android application user data

This command worked for me:

adb shell pm clear packageName

Abstraction VS Information Hiding VS Encapsulation

Encapsulation: binding data and the methods that act on it. this allows the hiding of data from all other methods in other classes. example: MyList class that can add an item, remove an item, and remove all items the methods add, remove, and removeAll act on the list(a private array) that can not be accessed directly from the outside.

Abstraction: is hiding the non relevant behavior and data. How the items are actually stored, added, or deleted is hidden (abstracted). My data may be held in simple array, ArrayList, LinkedList, and so on. Also, how the methods are implemented is hidden from the outside.

How can I add reflection to a C++ application?

You can find another library here: http://www.garret.ru/cppreflection/docs/reflect.html It supports 2 ways: getting type information from debug information and let programmer to provide this information.

I also interested in reflection for my project and found this library, i have not tried it yet, but tried other tools from this guy and i like how they work :-)

How to implement endless list with RecyclerView?

Most answer are assuming the RecyclerView uses a LinearLayoutManager, or GridLayoutManager, or even StaggeredGridLayoutManager, or assuming that the scrolling is vertical or horyzontal, but no one has posted a completly generic answer.

Using the ViewHolder's adapter is clearly not a good solution. An adapter might have more than 1 RecyclerView using it. It "adapts" their contents. It should be the RecyclerView (which is the one class which is responsible of what is currently displayed to the user, and not the adapter which is responsible only to provide content to the RecyclerView) which must notify your system that more items are needed (to load).

Here is my solution, using nothing else than the abstracted classes of the RecyclerView (RecycerView.LayoutManager and RecycerView.Adapter):

/**
 * Listener to callback when the last item of the adpater is visible to the user.
 * It should then be the time to load more items.
 **/
public abstract class LastItemListener extends RecyclerView.OnScrollListener {

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
      super.onScrolled(recyclerView, dx, dy);

      // init
      RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
      RecyclerView.Adapter adapter = recyclerView.getAdapter();

      if (layoutManager.getChildCount() > 0) {
        // Calculations..
        int indexOfLastItemViewVisible = layoutManager.getChildCount() -1;
        View lastItemViewVisible = layoutManager.getChildAt(indexOfLastItemViewVisible);
        int adapterPosition = layoutManager.getPosition(lastItemViewVisible);
        boolean isLastItemVisible = (adapterPosition == adapter.getItemCount() -1);

        // check
        if (isLastItemVisible)
          onLastItemVisible(); // callback
     }
   }

   /**
    * Here you should load more items because user is seeing the last item of the list.
    * Advice: you should add a bollean value to the class
    * so that the method {@link #onLastItemVisible()} will be triggered only once
    * and not every time the user touch the screen ;)
    **/
   public abstract void onLastItemVisible();

}


// --- Exemple of use ---

myRecyclerView.setOnScrollListener(new LastItemListener() {
    public void onLastItemVisible() {
         // start to load more items here.
    }
}

Can I have multiple primary keys in a single table?

Primary Key is very unfortunate notation, because of the connotation of "Primary" and the subconscious association in consequence with the Logical Model. I thus avoid using it. Instead I refer to the Surrogate Key of the Physical Model and the Natural Key(s) of the Logical Model.

It is important that the Logical Model for every Entity have at least one set of "business attributes" which comprise a Key for the entity. Boyce, Codd, Date et al refer to these in the Relational Model as Candidate Keys. When we then build tables for these Entities their Candidate Keys become Natural Keys in those tables. It is only through those Natural Keys that users are able to uniquely identify rows in the tables; as surrogate keys should always be hidden from users. This is because Surrogate Keys have no business meaning.

However the Physical Model for our tables will in many instances be inefficient without a Surrogate Key. Recall that non-covered columns for a non-clustered index can only be found (in general) through a Key Lookup into the clustered index (ignore tables implemented as heaps for a moment). When our available Natural Key(s) are wide this (1) widens the width of our non-clustered leaf nodes, increasing storage requirements and read accesses for seeks and scans of that non-clustered index; and (2) reduces fan-out from our clustered index increasing index height and index size, again increasing reads and storage requirements for our clustered indexes; and (3) increases cache requirements for our clustered indexes. chasing other indexes and data out of cache.

This is where a small Surrogate Key, designated to the RDBMS as "the Primary Key" proves beneficial. When set as the clustering key, so as to be used for key lookups into the clustered index from non-clustered indexes and foreign key lookups from related tables, all these disadvantages disappear. Our clustered index fan-outs increase again to reduce clustered index height and size, reduce cache load for our clustered indexes, decrease reads when accessing data through any mechanism (whether index scan, index seek, non-clustered key lookup or foreign key lookup) and decrease storage requirements for both clustered and nonclustered indexes of our tables.

Note that these benefits only occur when the surrogate key is both small and the clustering key. If a GUID is used as the clustering key the situation will often be worse than if the smallest available Natural Key had been used. If the table is organized as a heap then the 8-byte (heap) RowID will be used for key lookups, which is better than a 16-byte GUID but less performant than a 4-byte integer.

If a GUID must be used due to business constraints than the search for a better clustering key is worthwhile. If for example a small site identifier and 4-byte "site-sequence-number" is feasible then that design might give better performance than a GUID as Surrogate Key.

If the consequences of a heap (hash join perhaps) make that the preferred storage then the costs of a wider clustering key need to be balanced into the trade-off analysis.

Consider this example::

ALTER TABLE Persons
ADD CONSTRAINT pk_PersonID PRIMARY KEY (P_Id,LastName)

where the tuple "(P_Id,LastName)" requires a uniqueness constraint, and may be a lengthy Unicode LastName plus a 4-byte integer, it would be desirable to (1) declaratively enforce this constraint as "ADD CONSTRAINT pk_PersonID UNIQUE NONCLUSTERED (P_Id,LastName)" and (2) separately declare a small Surrogate Key to be the "Primary Key" of a clustered index. It is worth noting that Anita possibly only wishes to add the LastName to this constraint in order to make that a covered field, which is unnecessary in a clustered index because ALL fields are covered by it.

The ability in SQL Server to designate a Primary Key as nonclustered is an unfortunate historical circumstance, due to a conflation of the meaning "preferred natural or candidate key" (from the Logical Model) with the meaning "lookup key in storage" from the Physical Model. My understanding is that originally SYBASE SQL Server always used a 4-byte RowID, whether into a heap or a clustered index, as the "lookup key in storage" from the Physical Model.

Verifying a specific parameter with Moq

If the verification logic is non-trivial, it will be messy to write a large lambda method (as your example shows). You could put all the test statements in a separate method, but I don't like to do this because it disrupts the flow of reading the test code.

Another option is to use a callback on the Setup call to store the value that was passed into the mocked method, and then write standard Assert methods to validate it. For example:

// Arrange
MyObject saveObject;
mock.Setup(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()))
        .Callback<int, MyObject>((i, obj) => saveObject = obj)
        .Returns("xyzzy");

// Act
// ...

// Assert
// Verify Method was called once only
mock.Verify(c => c.Method(It.IsAny<int>(), It.IsAny<MyObject>()), Times.Once());
// Assert about saveObject
Assert.That(saveObject.TheProperty, Is.EqualTo(2));

ActiveXObject in Firefox or Chrome (not IE!)

ActiveX is supported by Chrome.

Chrome check parameters defined in : control panel/Internet option/Security.

Nevertheless,if it's possible to define four different area with IE, Chrome only check "Internet" area.

Java: Sending Multiple Parameters to Method

The solution depends on the answer to the question - are all the parameters going to be the same type and if so will each be treated the same?

If the parameters are not the same type or more importantly are not going to be treated the same then you should use method overloading:

public class MyClass
{
  public void doSomething(int i) 
  {
    ...
  }

  public void doSomething(int i, String s) 
  {
    ...
  }

  public void doSomething(int i, String s, boolean b) 
  {
    ...
  }
}

If however each parameter is the same type and will be treated in the same way then you can use the variable args feature in Java:

public MyClass 
{
  public void doSomething(int... integers)
  {
    for (int i : integers) 
    {
      ...
    }
  }
}

Obviously when using variable args you can access each arg by its index but I would advise against this as in most cases it hints at a problem in your design. Likewise, if you find yourself doing type checks as you iterate over the arguments then your design needs a review.

Open file dialog box in JavaScript

The simplest way:

_x000D_
_x000D_
#file-input {_x000D_
  display: none;_x000D_
}
_x000D_
<label for="file-input">_x000D_
  <div>Click this div and select a file</div>_x000D_
</label>_x000D_
<input type="file" id="file-input"/>
_x000D_
_x000D_
_x000D_

What's important, usage of display: none ensures that no place will be occupied by the hidden file input (what happens using opacity: 0).

Angular 2 - Using 'this' inside setTimeout

You need to use Arrow function ()=> ES6 feature to preserve this context within setTimeout.

// var that = this;                             // no need of this line
this.messageSuccess = true;

setTimeout(()=>{                           //<<<---using ()=> syntax
      this.messageSuccess = false;
 }, 3000);

Is generator.next() visible in Python 3?

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.

What do we mean by Byte array?

I assume you know what a byte is. A byte array is simply an area of memory containing a group of contiguous (side by side) bytes, such that it makes sense to talk about them in order: the first byte, the second byte etc..

Just as bytes can encode different types and ranges of data (numbers from 0 to 255, numbers from -128 to 127, single characters using ASCII e.g. 'a' or '%', CPU op-codes), each byte in a byte array may be any of these things, or contribute to some multi-byte values such as numbers with larger range (e.g. 16-bit unsigned int from 0..65535), international character sets, textual strings ("hello"), or part/all of a compiled computer programs.

The crucial thing about a byte array is that it gives indexed (fast), precise, raw access to each 8-bit value being stored in that part of memory, and you can operate on those bytes to control every single bit. The bad thing is the computer just treats every entry as an independent 8-bit number - which may be what your program is dealing with, or you may prefer some powerful data-type such as a string that keeps track of its own length and grows as necessary, or a floating point number that lets you store say 3.14 without thinking about the bit-wise representation. As a data type, it is inefficient to insert or remove data near the start of a long array, as all the subsequent elements need to be shuffled to make or fill the gap created/required.

Entity Framework (EF) Code First Cascade Delete for One-to-Zero-or-One relationship

This code worked for me

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<UserDetail>()
            .HasRequired(d => d.User)
            .WithOptional(u => u.UserDetail)
            .WillCascadeOnDelete(true);
    }

The migration code was:

public override void Up()
    {
        AddForeignKey("UserDetail", "UserId", "User", "UserId", cascadeDelete: true);
    }

And it worked fine. When I first used

modelBuilder.Entity<User>()
    .HasOptional(a => a.UserDetail)
    .WithOptionalDependent()
    .WillCascadeOnDelete(true);

The migration code was:

AddForeignKey("User", "UserDetail_UserId", "UserDetail", "UserId", cascadeDelete: true); 

but it does not match any of the two overloads available (in EntityFramework 6)

react-router go back a page how do you configure history?

Go back to specific page:

  import { useHistory } from "react-router-dom";

  const history = useHistory();
  
  const routeChange = () => {
    let path = '/login';
    history.push(path);
  };

Go back to previous page:

  import { useHistory } from "react-router-dom";

  const history = useHistory();
  
  const routeChange = () => {
    history.goBack()
  };

Which version of C# am I using

Most of the answers are correct above. Just consolidating 3 which I found easy and super quick. Also #1 is not possible now in VS2019.

  1. Visual Studio: Project > Properties > Build > Advanced
    This option is disabled now, and the default language is decided by VS itself. The detailed reason is available here.

  2. Type "#error version" in the code(.cs) anywhere, mousehover it.

  3. Go to 'Developer Command Prompt for Visual Studio' and run following command. csc -langversion:?

Read more tips: here.

Get a list of all functions and procedures in an Oracle database

Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.

Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.

If you are comparing schemas on the same database then try:

select * from dba_objects 
   where schema_name = 'ASCHEMA' 
     and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects 
where schema_name = 'BSCHEMA' 
  and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )

and switch around the orders of ASCHEMA and BSCHEMA.

If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

Android and setting alpha for (image) view alpha

Maybe a helpful alternative for a plain-colored background:

Put a LinearLayout over the ImageView and use the LinearLayout as a opacity filter. In the following a small example with a black background:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#FF000000" >

<RelativeLayout
    android:id="@+id/relativeLayout2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" >

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/icon_stop_big" />

    <LinearLayout
        android:id="@+id/opacityFilter"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#CC000000"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

Vary the android:background attribute of the LinearLayout between #00000000 (fully transparent) and #FF000000 (fully opaque).

How to darken a background using CSS?

when you want to brightness or darker of background-color, you can use this css code

.brighter-span {
  filter: brightness(150%);
}

.darker-span {
  filter: brightness(50%);
}

Difference between angle bracket < > and double quotes " " while including header files in C++?

It's compiler dependent. That said, in general using " prioritizes headers in the current working directory over system headers. <> usually is used for system headers. From to the specification (Section 6.10.2):

A preprocessing directive of the form

  # include <h-char-sequence> new-line

searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

A preprocessing directive of the form

  # include "q-char-sequence" new-line

causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read

  # include <h-char-sequence> new-line

with the identical contained sequence (including > characters, if any) from the original directive.

So on most compilers, using the "" first checks your local directory, and if it doesn't find a match then moves on to check the system paths. Using <> starts the search with system headers.

setAttribute('display','none') not working

display is not an attribute - it's a CSS property. You need to access the style object for this:

document.getElementById('classRight').style.display = 'none';

Pytorch tensor to numpy array

There are 4 dimensions of the tensor you want to convert.

[:, ::-1, :, :] 

: means that the first dimension should be copied as it is and converted, same goes for the third and fourth dimension.

::-1 means that for the second axes it reverses the the axes

How do I output an ISO 8601 formatted string in JavaScript?

I typically don't want to display a UTC date since customers don't like doing the conversion in their head. To display a local ISO date, I use the function:

function toLocalIsoString(date, includeSeconds) {
    function pad(n) { return n < 10 ? '0' + n : n }
    var localIsoString = date.getFullYear() + '-'
        + pad(date.getMonth() + 1) + '-'
        + pad(date.getDate()) + 'T'
        + pad(date.getHours()) + ':'
        + pad(date.getMinutes()) + ':'
        + pad(date.getSeconds());
    if(date.getTimezoneOffset() == 0) localIsoString += 'Z';
    return localIsoString;
};

The function above omits time zone offset information (except if local time happens to be UTC), so I use the function below to show the local offset in a single location. You can also append its output to results from the above function if you wish to show the offset in each and every time:

function getOffsetFromUTC() {
    var offset = new Date().getTimezoneOffset();
    return ((offset < 0 ? '+' : '-')
        + pad(Math.abs(offset / 60), 2)
        + ':'
        + pad(Math.abs(offset % 60), 2))
};

toLocalIsoString uses pad. If needed, it works like nearly any pad function, but for the sake of completeness this is what I use:

// Pad a number to length using padChar
function pad(number, length, padChar) {
    if (typeof length === 'undefined') length = 2;
    if (typeof padChar === 'undefined') padChar = '0';
    var str = "" + number;
    while (str.length < length) {
        str = padChar + str;
    }
    return str;
}

How to assign the output of a Bash command to a variable?

In shell you assign to a variable without the dollar-sign:

TEST=`pwd`
echo $TEST

that's better (and can be nested) but is not as portable as the backtics:

TEST=$(pwd)
echo $TEST

Always remember: the dollar-sign is only used when reading a variable.

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

In spring boot 2.x you need to reference provider specific properties.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-connect-to-production-database

The default, hikari can be set with spring.datasource.hikari.maximum-pool-size.

How to Copy Text to Clip Board in Android?

Here the method to copy text to clipboard:

private void setClipboard(Context context, String text) {
  if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText(text);
  } else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", text);
    clipboard.setPrimaryClip(clip);
  }
}

This method is working on all android devices.

Favorite Visual Studio keyboard shortcuts

Expand Smart Tag (Resolve Menu): Ctrl + . (period)

Expands the tag that shows when you do things like rename an identifier.

How To limit the number of characters in JTextField?

Great question, and it's odd that the Swing toolkit doesn't include this functionality natively for JTextFields. But, here's a great answer from my Udemy.com course "Learn Java Like a Kid":

txtGuess = new JTextField();
txtGuess.addKeyListener(new KeyAdapter() {
    public void keyTyped(KeyEvent e) { 
        if (txtGuess.getText().length() >= 3 ) // limit textfield to 3 characters
            e.consume(); 
    }  
});

This limits the number of characters in a guessing game text field to 3 characters, by overriding the keyTyped event and checking to see if the textfield already has 3 characters - if so, you're "consuming" the key event (e) so that it doesn't get processed like normal.

Convert JSONObject to Map

You can use Gson() (com.google.gson) library if you find any difficulty using Jackson.

HashMap<String, Object> yourHashMap = new Gson().fromJson(yourJsonObject.toString(), HashMap.class);

What is a non-capturing group in regular expressions?

HISTORICAL MOTIVATION:

The existence of non-capturing groups can be explained with the use of parenthesis.

Consider the expressions (a|b)c and a|bc, due to priority of concatenation over |, these expressions represent two different languages ({ac, bc} and {a, bc} respectively).

However, the parenthesis are also used as a matching group (as explained by the other answers...).

When you want to have parenthesis but not capture the sub-expression you use NON-CAPTURING GROUPS. In the example, (?:a|b)c

insert/delete/update trigger in SQL server

the am giving you is the code for trigger for INSERT, UPDATE and DELETE this works fine on Microsoft SQL SERVER 2008 and onwards database i am using is Northwind

/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
                    EmpID int,
                    Activity varchar(20),
                    DoneBy varchar(50),
                    Date_Time datetime NOT NULL DEFAULT GETDATE()
                   );

select * from Emp_Audit*/

create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
    SET @activity = 'UPDATE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end

If exists (Select * from inserted) and not exists(Select * from deleted)
begin
    SET @activity = 'INSERT';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

If exists(select * from deleted) and not exists(Select * from inserted)
begin 
    SET @activity = 'DELETE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from deleted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

How can I align button in Center or right using IONIC framework?

Css is going to work in same manner i assume.

You can center the content with something like this :

.center{
     text-align:center;
}

Update

To adjust the width in proper manner, modify your DOM as below :

<div class="item-input-inset">
    <label class="item-input-wrapper"> Date
        <input type="text" placeholder="Text Area" />
    </label>
</div>
<div class="item-input-inset">
    <label class="item-input-wrapper"> Suburb
        <input type="text" placeholder="Text Area" />
    </label>
</div>

CSS

label {
    display:inline-block;
    border:1px solid red;
    width:100%;
    font-weight:bold;
}

input{
    float:right; /* shift to right for alignment*/
    width:80% /* set a width, you can use max-width to limit this as well*/
}

Demo

final update

If you don't plan to modify existing HTML (one in your question originally), below css would make me your best friend!! :)

html, body, .con {
    height:100%;
    margin:0;
    padding:0;
}
.item-input-inset {
    display:inline-block;
    width:100%;
    font-weight:bold;
}
.item-input-inset > h4 {
    float:left;
    margin-top:0;/* important alignment */
    width:15%;
}
.item-input-wrapper {
    display:block;
    float:right;
    width:85%;
}
input {
    width:100%;
}

Demo

How to pass an array into a function, and return the results with an array

Here is how I do it. This way I can actually get a function to simulate returning multiple values;

function foo($array) 
{ 
    foreach($array as $_key => $_value) 
    {
       $str .= "{$_key}=".$_value.'&';
    }
    return $str = substr($str, 0, -1);
} 

/* Set the variables to pass to function, in an Array */

    $waffles['variable1'] = "value1"; 
    $waffles['variable2'] = "value2"; 
    $waffles['variable3'] = "value3"; 

/* Call Function */

    parse_str( foo( $waffles ));

/* Function returns multiple variable/value pairs */

    echo $variable1 ."<br>";
    echo $variable2 ."<br>";
    echo $variable3 ."<br>";

Especially usefull if you want, for example all fields in a database to be returned as variables, named the same as the database table fields. See 'db_fields( )' function below.

For example, if you have a query

select login, password, email from members_table where id = $id

Function returns multiple variables:

$login, $password and $email

Here is the function:

function db_fields($field, $filter, $filter_by,  $table = 'members_table') {

 /*
    This function will return as variable names, all fields that you request, 
    and the field values assigned to the variables as variable values.  

    $filter_by = TABLE FIELD TO FILTER RESULTS BY
    $filter =  VALUE TO FILTER BY
    $table = TABLE TO RUN QUERY AGAINST

    Returns single string value or ARRAY, based on whether user requests single
    field or multiple fields.

    We return all fields as variable names. If multiple rows
    are returned, check is_array($return_field); If > 0, it contains multiple rows.
    In that case, simply run parse_str($return_value) for each Array Item. 
*/
    $field = ($field == "*") ? "*,*" : $field;
    $fields = explode(",",$field);

    $assoc_array = ( count($fields) > 0 ) ? 1 : 0;

    if (!$assoc_array) {
        $result = mysql_fetch_assoc(mysql_query("select $field from $table where $filter_by = '$filter'"));
        return ${$field} = $result[$field];
    }
    else
    {
        $query = mysql_query("select $field from $table where $filter_by = '$filter'");
        while ($row = mysql_fetch_assoc($query)) {
            foreach($row as $_key => $_value) {
                $str .= "{$_key}=".$_value.'&';
            }
            return $str = substr($str, 0, -1);
        }
    }
}

Below is a sample call to function. So, If we need to get User Data for say $user_id = 12345, from the members table with fields ID, LOGIN, PASSWORD, EMAIL:

$filter = $user_id;
$filter_by = "ID";
$table_name = "members_table"

parse_str(db_fields('LOGIN, PASSWORD, EMAIL', $filter, $filter_by, $table_name));

/* This will return the following variables: */

echo $LOGIN ."<br>";
echo $PASSWORD ."<br>";
echo $EMAIL ."<br>";

We could also call like this:

parse_str(db_fields('*', $filter, $filter_by, $table_name));

The above call would return all fields as variable names.

Configure active profile in SpringBoot via Maven

There are multiple ways to set profiles for your springboot application.

  1. You can add this in your property file:

    spring.profiles.active=dev
    
  2. Programmatic way:

    SpringApplication.setAdditionalProfiles("dev");
    
  3. Tests make it very easy to specify what profiles are active

    @ActiveProfiles("dev")
    
  4. In a Unix environment

    export spring_profiles_active=dev
    
  5. JVM System Parameter

    -Dspring.profiles.active=dev
    

Example: Running a springboot jar file with profile.

java -jar -Dspring.profiles.active=dev application.jar

Frame Buster Buster ... buster code needed

If you add an alert right after the buster code, then the alert will stall the javascript thread, and it will let the page load. This is what StackOverflow does, and it busts out of my iframes, even when I use the frame busting buster. It also worked with my simple test page. This has only been tested in Firefox 3.5 and IE7 on windows.

Code:

<script type="text/javascript">
if (top != self){
  top.location.replace(self.location.href);
  alert("for security reasons bla bla bla");
}
</script>

Pass multiple parameters to rest API - Spring

Yes its possible to pass JSON object in URL

queryString = "{\"left\":\"" + params.get("left") + "}";
 httpRestTemplate.exchange(
                    Endpoint + "/A/B?query={queryString}",
                    HttpMethod.GET, entity, z.class, queryString);

How to debug in Django, the good way?

As mentioned in other posts here - setting breakpoints in your code and walking thru the code to see if it behaves as you expected is a great way to learn something like Django until you have a good sense of how it all behaves - and what your code is doing.

To do this I would recommend using WingIde. Just like other mentioned IDEs nice and easy to use, nice layout and also easy to set breakpoints evaluate / modify the stack etc. Perfect for visualizing what your code is doing as you step through it. I'm a big fan of it.

Also I use PyCharm - it has excellent static code analysis and can help sometimes spot problems before you realize they are there.

As mentioned already django-debug-toolbar is essential - https://github.com/django-debug-toolbar/django-debug-toolbar

And while not explicitly a debug or analysis tool - one of my favorites is SQL Printing Middleware available from Django Snippets at https://djangosnippets.org/snippets/290/

This will display the SQL queries that your view has generated. This will give you a good sense of what the ORM is doing and if your queries are efficient or you need to rework your code (or add caching).

I find it invaluable for keeping an eye on query performance while developing and debugging my application.

Just one other tip - I modified it slightly for my own use to only show the summary and not the SQL statement.... So I always use it while developing and testing. I also added that if the len(connection.queries) is greater than a pre-defined threshold it displays an extra warning.

Then if I spot something bad (from a performance or number of queries perspective) is happening I turn back on the full display of the SQL statements to see exactly what is going on. Very handy when you are working on a large Django project with multiple developers.

HTML text input allow only numeric input

You can attach to the key down event and then filter keys according to what you need, for example:

<input id="FIELD_ID" name="FIELD_ID" onkeypress="return validateNUM(event,this);"  type="text">

And the actual JavaScript handler would be:

function validateNUM(e,field)
{
    var key = getKeyEvent(e)
    if (specialKey(key)) return true;
    if ((key >= 48 && key <= 57) || (key == 46)){
        if (key != 46)
            return true;
        else{
            if (field.value.search(/\./) == -1 && field.value.length > 0)
                return true;
            else
                return false;
        }
    }

function getKeyEvent(e){
    var keynum
    var keychar
    var numcheck
    if(window.event) // IE
        keynum = e.keyCode
    else if(e.which) // Netscape/Firefox/Opera
        keynum = e.which
    return keynum;
}

Sending emails with Javascript

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

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

How to get MAC address of your machine using a C program?

I have just write one and test it on gentoo in virtualbox.

// get_mac.c
#include <stdio.h>    //printf
#include <string.h>   //strncpy
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if.h>   //ifreq
#include <unistd.h>   //close

int main()
{
    int fd;
    struct ifreq ifr;
    char *iface = "enp0s3";
    unsigned char *mac = NULL;

    memset(&ifr, 0, sizeof(ifr));

    fd = socket(AF_INET, SOCK_DGRAM, 0);

    ifr.ifr_addr.sa_family = AF_INET;
    strncpy(ifr.ifr_name , iface , IFNAMSIZ-1);

    if (0 == ioctl(fd, SIOCGIFHWADDR, &ifr)) {
        mac = (unsigned char *)ifr.ifr_hwaddr.sa_data;

        //display mac address
        printf("Mac : %.2X:%.2X:%.2X:%.2X:%.2X:%.2X\n" , mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
    }

    close(fd);

    return 0;
}

Codeigniter's `where` and `or_where`

You can use : Query grouping allows you to create groups of WHERE clauses by enclosing them in parentheses. This will allow you to create queries with complex WHERE clauses. Nested groups are supported. Example:

$this->db->select('*')->from('my_table')
        ->group_start()
                ->where('a', 'a')
                ->or_group_start()
                        ->where('b', 'b')
                        ->where('c', 'c')
                ->group_end()
        ->group_end()
        ->where('d', 'd')
->get();

https://www.codeigniter.com/userguide3/database/query_builder.html#query-grouping

Difference between web server, web container and application server

Web Server: It provides HTTP Request and HTTP response. It handles request from client only through HTTP protocol. It contains Web Container. Web Application mostly deployed on web Server. EX: Servlet JSP

Web Container: it maintains the life cycle for Servlet Object. Calls the service method for that servlet object. pass the HttpServletRequest and HttpServletResponse Object

Application Server: It holds big Enterprise application having big business logic. It is Heavy Weight or it holds Heavy weight Applications. Ex: EJB

NHibernate.MappingException: No persister for: XYZ

Make sure you have called the CreateCriteria(typeof(DomainObjectType)) method on Session for the domain object which you intent to fetch from DB.

How to add new line in Markdown presentation?

I was using Markwon for markdown parsing in Android. The following worked great:

"My first line  \nMy second line  \nMy third line  \nMy last line"

...two spaces followed by \n at the end of each line.

Call function with setInterval in jQuery?

setInterval(function() {
    updatechat();
}, 2000);

function updatechat() {
    alert('hello world');
}

How to do multiline shell script in Ansible

Ansible uses YAML syntax in its playbooks. YAML has a number of block operators:

  • The > is a folding block operator. That is, it joins multiple lines together by spaces. The following syntax:

    key: >
      This text
      has multiple
      lines
    

    Would assign the value This text has multiple lines\n to key.

  • The | character is a literal block operator. This is probably what you want for multi-line shell scripts. The following syntax:

    key: |
      This text
      has multiple
      lines
    

    Would assign the value This text\nhas multiple\nlines\n to key.

You can use this for multiline shell scripts like this:

- name: iterate user groups
  shell: |
    groupmod -o -g {{ item['guid'] }} {{ item['username'] }} 
    do_some_stuff_here
    and_some_other_stuff
  with_items: "{{ users }}"

There is one caveat: Ansible does some janky manipulation of arguments to the shell command, so while the above will generally work as expected, the following won't:

- shell: |
    cat <<EOF
    This is a test.
    EOF

Ansible will actually render that text with leading spaces, which means the shell will never find the string EOF at the beginning of a line. You can avoid Ansible's unhelpful heuristics by using the cmd parameter like this:

- shell:
    cmd: |
      cat <<EOF
      This is a test.
      EOF

delete a column with awk or sed

Try this :

awk '$3="";1' file.txt > new_file && mv new_file file.txt

or

awk '{$3="";print}' file.txt > new_file && mv new_file file.txt

Using Google maps API v3 how do I get LatLng with a given address?

If you need to do this on the backend you can use the following URL structure:

https://maps.googleapis.com/maps/api/geocode/json?address=[STREET_ADDRESS]&key=[YOUR_API_KEY]

Sample PHP code using curl:

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, 'https://maps.googleapis.com/maps/api/geocode/json?address=' . rawurlencode($address) . '&key=' . $api_key);

curl_setopt ($curl, CURLOPT_RETURNTRANSFER, 1);

$json = curl_exec($curl);

curl_close ($curl);

$obj = json_decode($json);

See additional documentation for more details and expected json response.

The docs provide sample output and will assist you in getting your own API key in order to be able to make requests to the Google Maps Geocoding API.

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

You can find the codes in the DB2 Information Center. Here's a definition of the -302 from the z/OS Information Center:

THE VALUE OF INPUT VARIABLE OR PARAMETER NUMBER position-number IS INVALID OR TOO LARGE FOR THE TARGET COLUMN OR THE TARGET VALUE

On Linux/Unix/Windows DB2, you'll look under SQL Messages to find your error message. If the code is positive, you'll look for SQLxxxxW, if it's negative, you'll look for SQLxxxxN, where xxxx is the code you're looking up.

how to use a like with a join in sql?

Using INSTR:

SELECT *
  FROM TABLE a
  JOIN TABLE b ON INSTR(b.column, a.column) > 0

Using LIKE:

SELECT *
  FROM TABLE a
  JOIN TABLE b ON b.column LIKE '%'+ a.column +'%'

Using LIKE, with CONCAT:

SELECT *
  FROM TABLE a
  JOIN TABLE b ON b.column LIKE CONCAT('%', a.column ,'%')

Mind that in all options, you'll probably want to drive the column values to uppercase BEFORE comparing to ensure you are getting matches without concern for case sensitivity:

SELECT *
  FROM (SELECT UPPER(a.column) 'ua'
         TABLE a) a
  JOIN (SELECT UPPER(b.column) 'ub'
         TABLE b) b ON INSTR(b.ub, a.ua) > 0

The most efficient will depend ultimately on the EXPLAIN plan output.

JOIN clauses are identical to writing WHERE clauses. The JOIN syntax is also referred to as ANSI JOINs because they were standardized. Non-ANSI JOINs look like:

SELECT *
  FROM TABLE a,
       TABLE b
 WHERE INSTR(b.column, a.column) > 0

I'm not going to bother with a Non-ANSI LEFT JOIN example. The benefit of the ANSI JOIN syntax is that it separates what is joining tables together from what is actually happening in the WHERE clause.

remove attribute display:none; so the item will be visible

The removeAttr() function only removes HTML attributes. The display is not a HTML attribute, it's a CSS property. You'd like to use css() function instead to manage CSS properties.

But jQuery offers a show() function which does exactly what you want in a concise call:

$("span").show();

SQL Server 2008 Windows Auth Login Error: The login is from an untrusted domain

I had wrong entry in hosts file under C:\Windows\System32\drivers\etc

[Microsoft][SQL Server Native Client 11.0][SQL Server]Login failed. The login is from an untrusted domain and cannot be used with Windows authentication.

Make sure to have entry like below

127.0.0.1   localhost
127.0.0.1   localhost   servername

How to JSON decode array elements in JavaScript?

If you get this text in an alert:

function(){return JSON.encode(this);}

when you try alert(myArray[i]), then there are a few possibilities:

  • myArray[i] is a function (most likely)
  • myArray[i] is the literal string "function(){return JSON.encode(this);}"
  • myArray[i] has a .toString() method that returns that function or that string. This is the least likely of the three.

The simplest way to tell would be to check typeof(myArray[i]).

include antiforgerytoken in ajax post ASP.NET MVC

In Account controller:

    // POST: /Account/SendVerificationCodeSMS
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public JsonResult SendVerificationCodeSMS(string PhoneNumber)
    {
        return Json(PhoneNumber);
    }

In View:

$.ajax(
{
    url: "/Account/SendVerificationCodeSMS",
    method: "POST",
    contentType: 'application/x-www-form-urlencoded; charset=utf-8',
    dataType: "json",
    data: {
        PhoneNumber: $('[name="PhoneNumber"]').val(),
        __RequestVerificationToken: $('[name="__RequestVerificationToken"]').val()
    },
    success: function (data, textStatus, jqXHR) {
        if (textStatus == "success") {
            alert(data);
            // Do something on page
        }
        else {
            // Do something on page
        }
    },
    error: function (jqXHR, textStatus, errorThrown) {
        console.log(textStatus);
        console.log(jqXHR.status);
        console.log(jqXHR.statusText);
        console.log(jqXHR.responseText);
    }
});

It is important to set contentType to 'application/x-www-form-urlencoded; charset=utf-8' or just omit contentTypefrom the object ...

Email address validation in C# MVC 4 application: with or without using Regex

Don't.

Use a regex for a quick sanity check, something like .@.., but almost all langauges / frameworks have better methods for checking an e-mail address. Use that.

It is possible to validate an e-mail address with a regex, but it is a long regex. Very long.
And in the end you will be none the wiser. You'll only know that the format is valid, but you still don't know if it's an active e-mail address. The only way to find out, is by sending a confirmation e-mail.

The most sophisticated way for creating comma-separated Strings from a Collection/Array/List?

I think it's not a good idea contruct the sql concatenating the where clause values like you are doing :

SELECT.... FROM.... WHERE ID IN( value1, value2,....valueN)

Where valueX comes from a list of Strings.

First, if you are comparing Strings they must be quoted, an this it isn't trivial if the Strings could have a quote inside.

Second, if the values comes from the user,or other system, then a SQL injection attack is possible.

It's a lot more verbose but what you should do is create a String like this:

SELECT.... FROM.... WHERE ID IN( ?, ?,....?)

and then bind the variables with Statement.setString(nParameter,parameterValue).

Remove title in Toolbar in appcompat-v7

Nobody mentioned:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
    }

Converting an array to a function arguments list

@bryc - yes, you could do it like this:

Element.prototype.setAttribute.apply(document.body,["foo","bar"])

But that seems like a lot of work and obfuscation compared to:

document.body.setAttribute("foo","bar")

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

javascript code to check special characters

You can test a string using this regular expression:

function isValid(str){
 return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

sudo apt-get install libv4l-dev

Editing for RH based systems :

On a Fedora 16 to install pygame 1.9.1 (in a virtualenv):

sudo yum install libv4l-devel
sudo ln -s /usr/include/libv4l1-videodev.h   /usr/include/linux/videodev.h 

Setting selected values for ng-options bound select elements

If using AngularJS 1.2 you can use 'track by' to tell Angular how to compare objects.

<select 
    ng-model="Choice.SelectedOption"                 
    ng-options="choice.Name for choice in Choice.Options track by choice.ID">
</select>

Updated fiddle http://jsfiddle.net/gFCzV/34/

How to execute UNION without sorting? (SQL)

Consider these tables (Standard SQL code, runs on SQL Server 2008):

WITH A 
     AS 
     (
      SELECT * 
        FROM (
              VALUES (1), 
                     (2), 
                     (3), 
                     (4), 
                     (5), 
                     (6) 
             ) AS T (col)
     ),
     B 
     AS 
     (
      SELECT * 
        FROM (
              VALUES (9), 
                     (8), 
                     (7), 
                     (6), 
                     (5), 
                     (4) 
             ) AS T (col)
     ), ...

The desired effect is this to sort table A by col ascending, sort table B by col descending then unioning the two, removing duplicates, retaining order before the union and leaving table A results on the "top" with table B on the "bottom" e.g. (pesudo code)

(
 SELECT *
   FROM A
  ORDER 
     BY col
)
UNION
(
 SELECT *
   FROM B
  ORDER 
     BY col DESC
);

Of course, this won't work in SQL because there can only be one ORDER BY clause and it can only be applied to the top level table expression (or whatever the output of a SELECT query is known as; I call it the "resultset").

The first thing to address is the intersection between the two tables, in this case the values 4, 5 and 6. How the intersection should be sorted needs to be specified in SQL code, therefore it is desirable that the designer specifies this too! (i.e. the person asking the question, in this case).

The implication in this case would seem to be that the intersection ("duplicates") should be sorted within the results for table A. Therefore, the sorted resultset should look like this:

      VALUES (1), -- A including intersection, ascending
             (2), -- A including intersection, ascending
             (3), -- A including intersection, ascending
             (4), -- A including intersection, ascending
             (5), -- A including intersection, ascending
             (6), -- A including intersection, ascending
             (9), -- B only, descending 
             (8), -- B only, descending  
             (7), -- B only, descending 

Note in SQL "top" and "bottom" has no inferent meaning and a table (other than a resultset) has no inherent ordering. Also (to cut a long story short) consider that UNION removes duplicate rows by implication and must be applied before ORDER BY. The conclusion has to be that each table's sort order must be explicitly defined by exposing a sort order column(s) before being unioned. For this we can use the ROW_NUMBER() windowed function e.g.

     ...
     A_ranked
     AS
     (
      SELECT col, 
             ROW_NUMBER() OVER (ORDER BY col) AS sort_order_1
        FROM A                      -- include the intersection
     ),
     B_ranked
     AS
     (
      SELECT *, 
             ROW_NUMBER() OVER (ORDER BY col DESC) AS sort_order_1
        FROM B
       WHERE NOT EXISTS (           -- exclude the intersection
                         SELECT * 
                           FROM A
                          WHERE A.col = B.col 
                        )
     )
SELECT *, 1 AS sort_order_0 
  FROM A_ranked
UNION
SELECT *, 2 AS sort_order_0 
  FROM B_ranked
ORDER BY sort_order_0, sort_order_1;

Close Form Button Event

Apply the below code where you want to make code to exit application.

System.Windows.Forms.Application.Exit( )

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

I can think of different method to achieve the same

IList<SelectableEnumItem> result= array;

or (i had some situation that this one didn't work well)

var result = (List<SelectableEnumItem>) array;

or use linq extension

var result = array.CastTo<List<SelectableEnumItem>>();

or

var result= array.Select(x=> x).ToArray<SelectableEnumItem>();

or more explictly

var result= array.Select(x=> new SelectableEnumItem{FirstName= x.Name, Selected = bool.Parse(x.selected) });

please pay attention in above solution I used dynamic Object

I can think of some more solutions that are combinations of above solutions. but I think it covers almost all available methods out there.

Myself I use the first one

Difference between sh and bash

sh: http://man.cx/sh
bash: http://man.cx/bash

TL;DR: bash is a superset of sh with a more elegant syntax and more functionality. It is safe to use a bash shebang line in almost all cases as it's quite ubiquitous on modern platforms.

NB: in some environments, sh is bash. Check sh --version.

Bash: infinite sleep (infinite blocking)

sleep infinity looks most elegant, but sometimes it doesn't work for some reason. In that case, you can try other blocking commands such as cat, read, tail -f /dev/null, grep a etc.

How to use ? : if statements with Razor and inline code blocks

The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.

How can I delete all Git branches which have been merged?

kuboon's answer missed deleting branches which have the word master in the branch name. The following improves on his answer:

git branch -r --merged | grep -v "origin/master$" | sed 's/\s*origin\///' | xargs -n 1 git push --delete origin

Of course, it does not delete the "master" branch itself :)

How do I get a list of installed CPAN modules?

I like to use the CPAN 'r' command for this. You can get into the CPAN shell with the old style:

sudo perl -MCPAN -e shell

or, on most newer systems, there is a 'cpan' command, so this command will get you to the shell:

sudo cpan

(You typically have to use 'sudo' to run it as root, or use 'su -' to become root before you run it, unless you have cpan set up to let you run it as a normal user, but install as root. If you don't have root on this machine, you can still use the CPAN shell to find out this information, but you won't be able to install modules, and you may have to go through a bit of setup the first time you run it.)

Then, once you're in the cpan shell, you can use the 'r' command to report all installed modules and their versions. So, at the "cpan>" prompt, type 'r'. This will list all installed modules and their versions. Use '?' to get some more help.

How do I write a method to calculate total cost for all items in an array?

The total of 7 numbers in an array can be created as:

import java.util.*;
class Sum
{
   public static void main(String arg[])
   {
     int a[]=new int[7];
     int total=0;
     Scanner n=new Scanner(System.in);
     System.out.println("Enter the no. for total");

     for(int i=0;i<=6;i++) 
     {
       a[i]=n.nextInt();
       total=total+a[i];
      }
       System.out.println("The total is :"+total);
    }
}

Jenkins, specifying JAVA_HOME

I was facing the same issue and for me downgrading the JAVA_HOME from jdk12 was not the plausible option like said in the answer. So I did a trial and error experiment and I got the Jenkins running without even downgrading the version of JAVA_HOME.

Steps:

  • open configuration $ sudo vi /etc/init.d/jenkins
  • Comment following line:
 #JAVA=`type -p java`
  • Introduced the line mentioned below. (Note: Insert the specific path of JDK in your machine.)
 JAVA=`type -p /usr/lib/jdk8/bin/java`
  • Reload systemd manager configuration: $ sudo systemctl daemon-reload
  • Start Jenkins service: $ sudo systemctl start jenkins
    ? jenkins.service - LSB: Start Jenkins at boot time
       Loaded: loaded (/etc/init.d/jenkins; generated)
       Active: active (exited) since Sun 2020-05-31 21:05:30 CEST; 9min ago
         Docs: man:systemd-sysv-generator(8)
      Process: 9055 ExecStart=/etc/init.d/jenkins start (code=exited, status=0/SUCCESS)
    

django order_by query set, ascending and descending

for ascending order:

Reserved.objects.filter(client=client_id).order_by('check_in')

for descending order:

1.  Reserved.objects.filter(client=client_id).order_by('-check_in')

or

2.  Reserved.objects.filter(client=client_id).order_by('check_in')[::-1]

How to set Spinner default value to null?

In my case, although size '2' is displayed in the spinner, nothing happens till some selection is done!

I have an xml file (data_sizes.xml) which lists all the spinner values.

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="chunks">
        <item>2</item>
        <item>4</item>
        <item>8</item>
        <item>16</item>
        <item>32</item>
    </string-array>
</resources>    

In main.xml file: Spinner element

<Spinner android:id="@+id/spinnerSize"  
android:layout_marginLeft="50px"
android:layout_width="fill_parent"                  
android:drawSelectorOnTop="true"
android:layout_marginTop="5dip"
android:prompt="@string/SelectSize"
android:layout_marginRight="30px"
android:layout_height="35px" /> 

Then in my java code, I added:

In my activity: Declaration

Spinner spinnerSize;
ArrayAdapter adapter;

In a public void function - initControls(): Definition

spinnerSize = (Spinner)findViewById(R.id.spinnerSize);
adapter = ArrayAdapter.createFromResource(this, R.array.chunks, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSize.setAdapter(adapter);
spinnerSize.setOnItemSelectedListener(new MyOnItemSelectedListener());

My spinner listener:

/* Spinner Listener */

class MyOnItemSelectedListener implements OnItemSelectedListener {

    public void onItemSelected(AdapterView<?> parent,
        View view, int pos, long id) {
        chunkSize = new Integer(parent.getItemAtPosition(pos).toString()).intValue();
    }
    public void onNothingSelected(AdapterView<?> parent) {
      // Dummy
    }
}

Request exceeded the limit of 10 internal redirects due to probable configuration error

i solved this by http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/ just uncomment or add this:

RewriteBase /
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

to your .htaccess file

How can I show line numbers in Eclipse?

Window ? Preferences ? General ? Editors ? Text Editors ? Show line numbers.


Edit: I wrote this long ago but as @ArtOfWarfar and @voidstate mentioned you can now simply:

Right click the gutter and select "Show Line Numbers":

How can I see normal print output created during pytest run?


Try pytest -s -v test_login.py for more info in console.

-v it's a short --verbose

-s means 'disable all capturing'



ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

In my case, I'm not able to access mysql and after 3 days research, I have got a solution. This is perfect solution because I have searched /var/run/mysqld/mysqld.sock and I did not find the folder. You can run on putty the commands listed below.

sudo mkdir /var/run/mysqld/
sudo chown -R mysql:mysql /var/log/mysql
sudo mysqld --basedir=/usr --datadir=/var/lib/mysql --user=mysql --socket=/var/run/mysqld/mysqld.sock
sudo /etc/init.d/mysql restart

You will save your valuable time.

Enable CORS in fetch api

Browser have cross domain security at client side which verify that server allowed to fetch data from your domain. If Access-Control-Allow-Origin not available in response header, browser disallow to use response in your JavaScript code and throw exception at network level. You need to configure cors at your server side.

You can fetch request using mode: 'cors'. In this situation browser will not throw execption for cross domain, but browser will not give response in your javascript function.

So in both condition you need to configure cors in your server or you need to use custom proxy server.

Checking if object is empty, works with ng-show but not from controller?

you can check length of items

ng-show="items.length"

Cannot execute script: Insufficient memory to continue the execution of the program

Sometimes, due to the heavy size of the script and data, we encounter this type of error. Server needs sufficient memory to execute and give the result. We can simply increase the memory size, per query.

You just need to go to the sql server properties > Memory tab (left side)> Now set the maximum memory limit you want to add.

Also, there is an option at the top, "Results to text", which consume less memory as compare to option "Results to grid", we can also go for Result to Text for less memory execution.

Tool for comparing 2 binary files in Windows

I prefer to use objcopy to convert to hex, then use diff.

Apache HttpClient Android (Gradle)

The accepted answer does not seem quite right to me. There is no point dragging a different version of HttpMime when one can depend on the same version of it.

compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5'
compile (group: 'org.apache.httpcomponents' , name: 'httpmime' , version: '4.3.5') {
    exclude module: 'org.apache.httpcomponents:httpclient'
}

Defining private module functions in python

This question was not fully answered, since module privacy is not purely conventional, and since using import may or may not recognize module privacy, depending on how it is used.

If you define private names in a module, those names will be imported into any script that uses the syntax, 'import module_name'. Thus, assuming you had correctly defined in your example the module private, _num, in a.py, like so..

#a.py
_num=1

..you would be able to access it in b.py with the module name symbol:

#b.py
import a
...
foo = a._num # 1

To import only non-privates from a.py, you must use the from syntax:

#b.py
from a import *
...
foo = _num # throws NameError: name '_num' is not defined

For the sake of clarity, however, it is better to be explicit when importing names from modules, rather than importing them all with a '*':

#b.py
from a import name1 
from a import name2
...

'uint32_t' identifier not found error

I have the same error and it fixed it including in the file the following

#include <stdint.h>

at the beginning of your file.

ojdbc14.jar vs. ojdbc6.jar

The "14" and "6" in those driver names refer to the JVM they were written for. If you're still using JDK 1.4 I'd say you have a serious problem and need to upgrade. JDK 1.4 is long past its useful support life. It didn't even have generics! JDK 6 u21 is the current production standard from Oracle/Sun. I'd recommend switching to it if you haven't already.

Twig: in_array or similar possible within if statement?

You just have to change the second line of your second code-block from

{% if myVar is in_array(array_keys(someOtherArray)) %}

to

{% if myVar in someOtherArray|keys %}

in is the containment-operator and keys a filter that returns an arrays keys.

How to destroy a DOM element with jQuery?

Not sure if it's just me, but using .remove() doesn't seem to work if you are selecting by an id.

Ex: $("#my-element").remove();

I had to use the element's class instead, or nothing happened.

Ex: $(".my-element").remove();

What are the default access modifiers in C#?

The default access for everything in C# is "the most restricted access you could declare for that member".

So for example:

namespace MyCompany
{
    class Outer
    {
        void Foo() {}
        class Inner {}
    }
}

is equivalent to

namespace MyCompany
{
    internal class Outer
    {
        private void Foo() {}
        private class Inner {}
    }
}

The one sort of exception to this is making one part of a property (usually the setter) more restricted than the declared accessibility of the property itself:

public string Name
{
    get { ... }
    private set { ... } // This isn't the default, have to do it explicitly
}

This is what the C# 3.0 specification has to say (section 3.5.1):

Depending on the context in which a member declaration takes place, only certain types of declared accessibility are permitted. Furthermore, when a member declaration does not include any access modifiers, the context in which the declaration takes place determines the default declared accessibility.

  • Namespaces implicitly have public declared accessibility. No access modifiers are allowed on namespace declarations.
  • Types declared in compilation units or namespaces can have public or internal declared accessibility and default to internal declared accessibility.
  • Class members can have any of the five kinds of declared accessibility and default to private declared accessibility. (Note that a type declared as a member of a class can have any of the five kinds of declared accessibility, whereas a type declared as a member of a namespace can have only public or internal declared accessibility.)
  • Struct members can have public, internal, or private declared accessibility and default to private declared accessibility because structs are implicitly sealed. Struct members introduced in a struct (that is, not inherited by that struct) cannot have protected or protected internal declared accessibility. (Note that a type declared as a member of a struct can have public, internal, or private declared accessibility, whereas a type declared as a member of a namespace can have only public or internal declared accessibility.)
  • Interface members implicitly have public declared accessibility. No access modifiers are allowed on interface member declarations.
  • Enumeration members implicitly have public declared accessibility. No access modifiers are allowed on enumeration member declarations.

(Note that nested types would come under the "class members" or "struct members" parts - and therefore default to private visibility.)

Group by multiple field names in java 8

You can use List as a classifier for many fields, but you need wrap null values into Optional:

Function<String, List> classifier = (item) -> List.of(
    item.getFieldA(),
    item.getFieldB(),
    Optional.ofNullable(item.getFieldC())
);

Map<List, List<Item>> grouped = items.stream()
    .collect(Collectors.groupingBy(classifier));

How to create Drawable from resource

The getDrawable (int id) method is deprecated as of API 22.

Instead you should use the getDrawable (int id, Resources.Theme theme) for API 21+

Code would look something like this.

Drawable myDrawable;
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    myDrawable = context.getResources().getDrawable(id, context.getTheme());
} else {
    myDrawable = context.getResources().getDrawable(id);
}

How to display a pdf in a modal window?

You can have a look at this library: https://github.com/mozilla/pdf.js it renders PDF document in a Web/HTML page

Also you can use Flash to embed the document into any HTML page like that:

<object data="your_file.pdf#view=Fit" type="application/pdf" width="100%" height="850">
    <p>
        It appears your Web browser is not configured to display PDF files. No worries, just <a href="your_file.pdf">click here to download the PDF file.</a>
    </p>
</object>

How do you convert a C++ string to an int?

Let me add my vote for boost::lexical_cast

#include <boost/lexical_cast.hpp>

int val = boost::lexical_cast<int>(strval) ;

It throws bad_lexical_cast on error.

creating list of objects in Javascript

dynamically build list of objects

var listOfObjects = [];
var a = ["car", "bike", "scooter"];
a.forEach(function(entry) {
    var singleObj = {};
    singleObj['type'] = 'vehicle';
    singleObj['value'] = entry;
    listOfObjects.push(singleObj);
});

here's a working example http://jsfiddle.net/b9f6Q/2/ see console for output

Reading local text file into a JavaScript array

Using Node.js

sync mode:

var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")

async mode:

var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
    var textByLine = text.split("\n")
});

UPDATE

As of at least Node 6, readFileSync returns a Buffer, so it must first be converted to a string in order for split to work:

var text = fs.readFileSync("./mytext.txt").toString('utf-8');

Or

var text = fs.readFileSync("./mytext.txt", "utf-8");

Remove HTML tags from string including &nbsp in C#

Sanitizing an Html document involves a lot of tricky things. This package maybe of help: https://github.com/mganss/HtmlSanitizer

Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe

Even when you asked finally for the opposite, to reform 0s and 1s into Trues and Falses, however, I post an answer about how to transform falses and trues into ones and zeros (1s and 0s), for a whole dataframe, in a single line.

Example given

df <- structure(list(p1_1 = c(TRUE, FALSE, FALSE, NA, TRUE, FALSE, 
                NA), p1_2 = c(FALSE, TRUE, FALSE, NA, FALSE, NA, 
                TRUE), p1_3 = c(TRUE, 
                TRUE, FALSE, NA, NA, FALSE, TRUE), p1_4 = c(FALSE, NA, 
                FALSE,  FALSE, TRUE, FALSE, NA), p1_5 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_6 = c(TRUE, NA, 
                FALSE, TRUE, FALSE, NA, TRUE), p1_7 = c(TRUE, NA, 
                FALSE, TRUE, NA, FALSE, TRUE), p1_8 = c(FALSE, 
                FALSE, NA, FALSE, TRUE, FALSE, NA), p1_9 = c(TRUE, 
                FALSE,  NA, FALSE, FALSE, NA, TRUE), p1_10 = c(TRUE, 
                FALSE, NA, FALSE, FALSE, NA, TRUE), p1_11 = c(FALSE, 
                FALSE, NA, FALSE, NA, FALSE, TRUE)), .Names = 
                c("p1_1", "p1_2", "p1_3", "p1_4", "p1_5", "p1_6", 
                "p1_7", "p1_8", "p1_9", "p1_10", "p1_11"), row.names = 
                 c(NA, -7L), class = "data.frame")

   p1_1  p1_2  p1_3  p1_4  p1_5  p1_6  p1_7  p1_8  p1_9 p1_10 p1_11
1  TRUE FALSE  TRUE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE FALSE
2 FALSE  TRUE  TRUE    NA    NA    NA    NA FALSE FALSE FALSE FALSE
3 FALSE FALSE FALSE FALSE FALSE FALSE FALSE    NA    NA    NA    NA
4    NA    NA    NA FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE FALSE
5  TRUE FALSE    NA  TRUE FALSE FALSE    NA  TRUE FALSE FALSE    NA
6 FALSE    NA FALSE FALSE    NA    NA FALSE FALSE    NA    NA FALSE
7    NA  TRUE  TRUE    NA  TRUE  TRUE  TRUE    NA  TRUE  TRUE  TRUE

Then by running that: df * 1 all Falses and Trues are trasnformed into 1s and 0s. At least, this was happen in the R version that I have (R version 3.4.4 (2018-03-15) ).

> df*1
  p1_1 p1_2 p1_3 p1_4 p1_5 p1_6 p1_7 p1_8 p1_9 p1_10 p1_11
1    1    0    1    0    1    1    1    0    1     1     0
2    0    1    1   NA   NA   NA   NA    0    0     0     0
3    0    0    0    0    0    0    0   NA   NA    NA    NA
4   NA   NA   NA    0    1    1    1    0    0     0     0
5    1    0   NA    1    0    0   NA    1    0     0    NA
6    0   NA    0    0   NA   NA    0    0   NA    NA     0
7   NA    1    1   NA    1    1    1   NA    1     1     1

I do not know if it a total "safe" command, under all different conditions / dfs.

Can you nest html forms?

I ran into a similar problem, and I know that is not an answer to the question, but it can be of help to someone with this kind of problem:
if there is need to put the elements of two or more forms in a given sequence, the HTML5 <input> form attribute can be the solution.

From http://www.w3schools.com/tags/att_input_form.asp:

  1. The form attribute is new in HTML5.
  2. Specifies which <form> element an <input> element belongs to. The value of this attribute must be the id attribute of a <form> element in the same document.

Scenario:

  • input_Form1_n1
  • input_Form2_n1
  • input_Form1_n2
  • input_Form2_n2

Implementation:

<form id="Form1" action="Action1.php" method="post"></form>
<form id="Form2" action="Action2.php" method="post"></form>

<input type="text" name="input_Form1_n1" form="Form1" />
<input type="text" name="input_Form2_n1" form="Form2" />
<input type="text" name="input_Form1_n2" form="Form1" />
<input type="text" name="input_Form2_n2" form="Form2" />

<input type="submit" name="button1" value="buttonVal1" form="Form1" />
<input type="submit" name="button2" value="buttonVal2" form="Form2" />

Here you'll find browser's compatibility.

How to add border around linear layout except at the bottom?

Create an XML file named border.xml in the drawable folder and put the following code in it.

 <?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
  <item> 
    <shape android:shape="rectangle">
      <solid android:color="#FF0000" /> 
    </shape>
  </item>   
    <item android:left="5dp" android:right="5dp"  android:top="5dp" >  
     <shape android:shape="rectangle"> 
      <solid android:color="#000000" />
    </shape>
   </item>    
 </layer-list> 

Then add a background to your linear layout like this:

         android:background="@drawable/border"

EDIT :

This XML was tested with a galaxy s running GingerBread 2.3.3 and ran perfectly as shown in image below:

enter image description here

ALSO

tested with galaxy s 3 running JellyBean 4.1.2 and ran perfectly as shown in image below :

enter image description here

Finally its works perfectly with all APIs

EDIT 2 :

It can also be done using a stroke to keep the background as transparent while still keeping a border except at the bottom with the following code.

<?xml version="1.0" encoding="utf-8"?>
 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
   <item android:left="0dp" android:right="0dp"  android:top="0dp"  
        android:bottom="-10dp"> 
    <shape android:shape="rectangle">
     <stroke android:width="10dp" android:color="#B22222" />
    </shape>
   </item>  
 </layer-list> 

hope this help .

Get operating system info

You can look for this information in $_SERVER['HTTP_USER_AGENT'], but its format is free-form, not guaranteed to be sent, and could easily be altered by the user, whether for privacy or other reasons.

If you've not set the browsecap directive, this will return a warning. To make sure it's set, you can retrieve the value using ini_get and see if it's set.

if(ini_get("browscap")) {
    $browser = get_browser(null, true);
    $browser = get_browser($_SERVER['HTTP_USER_AGENT']);  
} 

As kba explained in his answer, your browser sends a lot of information to the server while loading a webpage. Most websites use these User-agent information to determine the visitor's operating system, browser and various information.

What does $_ mean in PowerShell?

This is the variable for the current value in the pipe line, which is called $PSItem in Powershell 3 and newer.

1,2,3 | %{ write-host $_ } 

or

1,2,3 | %{ write-host $PSItem } 

For example in the above code the %{} block is called for every value in the array. The $_ or $PSItem variable will contain the current value.

The differences between initialize, define, declare a variable

Declaration says "this thing exists somewhere":

int foo();       // function
extern int bar;  // variable
struct T
{
   static int baz;  // static member variable
};

Definition says "this thing exists here; make memory for it":

int foo() {}     // function
int bar;         // variable
int T::baz;      // static member variable

Initialisation is optional at the point of definition for objects, and says "here is the initial value for this thing":

int bar = 0;     // variable
int T::baz = 42; // static member variable

Sometimes it's possible at the point of declaration instead:

struct T
{
   static int baz = 42;
};

…but that's getting into more complex features.

Why doesn't margin:auto center an image?

Because your image is an inline-block element. You could change it to a block-level element like this:

<img src="queuedError.jpg" style="margin:auto; width:200px;display:block" />

and it will be centered.

How to make HTML input tag only accept numerical values?

HTML 5

You can use HTML5 input type number to restrict only number entries:

<input type="number" name="someid" />

This will work only in HTML5 complaint browser. Make sure your html document's doctype is:

<!DOCTYPE html>

See also https://github.com/jonstipe/number-polyfill for transparent support in older browsers.

JavaScript

Update: There is a new and very simple solution for this:

It allows you to use any kind of input filter on a text <input>, including various numeric filters. This will correctly handle Copy+Paste, Drag+Drop, keyboard shortcuts, context menu operations, non-typeable keys, and all keyboard layouts.

See this answer or try it yourself on JSFiddle.

For general purpose, you can have JS validation as below:

function isNumberKey(evt){
    var charCode = (evt.which) ? evt.which : evt.keyCode
    if (charCode > 31 && (charCode < 48 || charCode > 57))
        return false;
    return true;
}

<input name="someid" type="number" onkeypress="return isNumberKey(event)"/>

If you want to allow decimals replace the "if condition" with this:

if (charCode > 31 && (charCode != 46 &&(charCode < 48 || charCode > 57)))

Source: HTML text input allow only numeric input

JSFiddle demo: http://jsfiddle.net/viralpatel/nSjy7/

Adding a background image to a <div> element

<div class="foo">Foo Bar</div>

and in your CSS file:

.foo {
    background-image: url("images/foo.png");
}

Convert list to array in Java

For ArrayList the following works:

ArrayList<Foo> list = new ArrayList<Foo>();

//... add values

Foo[] resultArray = new Foo[list.size()];
resultArray = list.toArray(resultArray);

Facebook Graph API : get larger pictures in one request

Change the array of fields id,name,picture to id,name,picture.type(large)

https://graph.facebook.com/v2.8/me?fields=id,name,picture.type(large)&access_token=<the_token>

Result:

{
   "id": "130716224073524",
   "name": "Julian Mann",
   "picture": {
      "data": {
         "is_silhouette": false,
         "url": "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/15032818_133926070419206_3681208703790460208_n.jpg?oh=a288898d87420cdc7ed8db5602bbb520&oe=58CB5D16"
      }
   }
}

How to set breakpoints in inline Javascript in Google Chrome?

Refresh the page containing the script whilst the developer tools are open on the scripts tab. This will add a (program) entry in the file list which shows the html of the page including the script. From here you can add breakpoints.

Most concise way to convert a Set<T> to a List<T>

List<String> l = new ArrayList<String>(listOfTopicAuthors);

Launching a website via windows commandline

IE has a setting, located in Tools / Internet options / Advanced / Browsing, called Reuse windows for launching shortcuts, which is checked by default. For IE versions that support tabbed browsing, this option is relevant only when tab browsing is turned off (in fact, IE9 Beta explicitly mentions this). However, since IE6 does not have tabbed browsing, this option does affect opening URLs through the shell (as in your example).

Build project into a JAR automatically in Eclipse

You want a .jardesc file. They do not kick off automatically, but it's within 2 clicks.

  1. Right click on your project
  2. Choose Export > Java > JAR file
  3. Choose included files and name output JAR, then click Next
  4. Check "Save the description of this JAR in the workspace" and choose a name for the new .jardesc file

Now, all you have to do is right click on your .jardesc file and choose Create JAR and it will export it in the same spot.

How to set the environmental variable LD_LIBRARY_PATH in linux

The file .bash_profile is only executed by login shells. You may need to put it in ~/.bashrc, or simply logout and login again.

python max function using 'key' and lambda expression

max function is used to get the maximum out of an iterable.

The iterators may be lists, tuples, dict objects, etc. Or even custom objects as in the example you provided.

max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value

With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.

So, the key=func basically allows us to pass an optional argument key to the function on whose basis is the given iterator/arguments are sorted & the maximum is returned.

lambda is a python keyword that acts as a pseudo function. So, when you pass player object to it, it will return player.totalScore. Thus, the iterable passed over to function max will sort according to the key totalScore of the player objects given to it & will return the player who has maximum totalScore.

If no key argument is provided, the maximum is returned according to default Python orderings.

Examples -

max(1, 3, 5, 7)
>>>7
max([1, 3, 5, 7])
>>>7

people = [('Barack', 'Obama'), ('Oprah', 'Winfrey'), ('Mahatma', 'Gandhi')]
max(people, key=lambda x: x[1])
>>>('Oprah', 'Winfrey')

.jar error - could not find or load main class

Had this problem couldn't find the answer so i went looking on other threads, I found that i was making my app with 1.8 but for some reason my jre was out dated even though i remember updating it. I downloaded the lastes jre 8 and the jar file runs perfectly. Hope this helps.

How to add new activity to existing project in Android Studio?

To add an Activity using Android Studio.

This step is same as adding Fragment, Service, Widget, and etc. Screenshot provided.

[UPDATE] Android Studio 3.5. Note that I have removed the steps for the older version. I assume almost all is using version 3.x.

enter image description here

  1. Right click either java package/java folder/module, I recommend to select a java package then right click it so that the destination of the Activity will be saved there
  2. Select/Click New
  3. Select Activity
  4. Choose an Activity that you want to create, probably the basic one.

To add a Service, or a BroadcastReceiver, just do the same step.

Is there an equivalent for var_dump (PHP) in Javascript?

Based on previous functions found in this post. Added recursive mode and indentation.

function dump(v, s) {
  s = s || 1;
  var t = '';
  switch (typeof v) {
    case "object":
      t += "\n";
      for (var i in v) {
        t += Array(s).join(" ")+i+": ";
        t += dump(v[i], s+3);
      }
      break;
    default: //number, string, boolean, null, undefined 
      t += v+" ("+typeof v+")\n";
      break;
  }
  return t;
}

Example

var a = {
  b: 1,
  c: {
    d:1,
    e:2,
    d:3,
    c: {
      d:1,
      e:2,
      d:3
    }
  }
};

var d = dump(a);
console.log(d);
document.getElementById("#dump").innerHTML = "<pre>" + d + "</pre>";

Result

b: 1 (number)
c: 
   d: 3 (number)
   e: 2 (number)
   c: 
      d: 3 (number)
      e: 2 (number)

How to serialize an Object into a list of URL query parameters?

A functional approach.

_x000D_
_x000D_
var kvToParam = R.mapObjIndexed((val, key) => {_x000D_
  return '&' + key + '=' + encodeURIComponent(val);_x000D_
});_x000D_
_x000D_
var objToParams = R.compose(_x000D_
  R.replace(/^&/, '?'),_x000D_
  R.join(''),_x000D_
  R.values,_x000D_
  kvToParam_x000D_
);_x000D_
_x000D_
var o = {_x000D_
  username: 'sloughfeg9',_x000D_
  password: 'traveller'_x000D_
};_x000D_
_x000D_
console.log(objToParams(o));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.22.1/ramda.min.js"></script>
_x000D_
_x000D_
_x000D_

how to get javaScript event source element?

You should change the generated HTML to not use inline javascript, and use addEventListener instead.

If you can not in any way change the HTML, you could get the onclick attributes, the functions and arguments used, and "convert" it to unobtrusive javascript instead by removing the onclick handlers, and using event listeners.

We'd start by getting the values from the attributes

_x000D_
_x000D_
$('button').each(function(i, el) {_x000D_
    var funcs = [];_x000D_
_x000D_
 $(el).attr('onclick').split(';').map(function(item) {_x000D_
     var fn     = item.split('(').shift(),_x000D_
         params = item.match(/\(([^)]+)\)/), _x000D_
            args;_x000D_
            _x000D_
        if (params && params.length) {_x000D_
         args = params[1].split(',');_x000D_
            if (args && args.length) {_x000D_
                args = args.map(function(par) {_x000D_
              return par.trim().replace(/('")/g,"");_x000D_
             });_x000D_
            }_x000D_
        }_x000D_
        funcs.push([fn, args||[]]);_x000D_
    });_x000D_
  _x000D_
    $(el).data('args', funcs); // store in jQuery's $.data_x000D_
  _x000D_
    console.log( $(el).data('args') );_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<button onclick="doSomething('param')" id="id_button1">action1</button>_x000D_
<button onclick="doAnotherSomething('param1', 'param2')" id="id_button1">action2</button>._x000D_
<button onclick="doDifferentThing()" id="id_button3">action3</button>
_x000D_
_x000D_
_x000D_

That gives us an array of all and any global methods called by the onclick attribute, and the arguments passed, so we can replicate it.

Then we'd just remove all the inline javascript handlers

$('button').removeAttr('onclick')

and attach our own handlers

$('button').on('click', function() {...}

Inside those handlers we'd get the stored original function calls and their arguments, and call them.
As we know any function called by inline javascript are global, we can call them with window[functionName].apply(this-value, argumentsArray), so

$('button').on('click', function() {
    var element = this;
    $.each(($(this).data('args') || []), function(_,fn) {
        if (fn[0] in window) window[fn[0]].apply(element, fn[1]);
    });
});

And inside that click handler we can add anything we want before or after the original functions are called.

A working example

_x000D_
_x000D_
$('button').each(function(i, el) {_x000D_
    var funcs = [];_x000D_
_x000D_
 $(el).attr('onclick').split(';').map(function(item) {_x000D_
     var fn     = item.split('(').shift(),_x000D_
         params = item.match(/\(([^)]+)\)/), _x000D_
            args;_x000D_
            _x000D_
        if (params && params.length) {_x000D_
         args = params[1].split(',');_x000D_
            if (args && args.length) {_x000D_
                args = args.map(function(par) {_x000D_
              return par.trim().replace(/('")/g,"");_x000D_
             });_x000D_
            }_x000D_
        }_x000D_
        funcs.push([fn, args||[]]);_x000D_
    });_x000D_
    $(el).data('args', funcs);_x000D_
}).removeAttr('onclick').on('click', function() {_x000D_
 console.log('click handler for : ' + this.id);_x000D_
  _x000D_
 var element = this;_x000D_
 $.each(($(this).data('args') || []), function(_,fn) {_x000D_
     if (fn[0] in window) window[fn[0]].apply(element, fn[1]);_x000D_
    });_x000D_
  _x000D_
    console.log('after function call --------');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<button onclick="doSomething('param');" id="id_button1">action1</button>_x000D_
<button onclick="doAnotherSomething('param1', 'param2')" id="id_button2">action2</button>._x000D_
<button onclick="doDifferentThing()" id="id_button3">action3</button>_x000D_
_x000D_
<script>_x000D_
 function doSomething(arg) { console.log('doSomething', arg) }_x000D_
    function doAnotherSomething(arg1, arg2) { console.log('doAnotherSomething', arg1, arg2) }_x000D_
    function doDifferentThing() { console.log('doDifferentThing','no arguments') }_x000D_
</script>
_x000D_
_x000D_
_x000D_

How to compare dates in datetime fields in Postgresql?

Use the range type. If the user enter a date:

select *
from table
where
    update_date
    <@
    tsrange('2013-05-03', '2013-05-03'::date + 1, '[)');

If the user enters timestamps then you don't need the ::date + 1 part

http://www.postgresql.org/docs/9.2/static/rangetypes.html

http://www.postgresql.org/docs/9.2/static/functions-range.html

Character reading from file in Python

There are a few points to consider.

A \u2018 character may appear only as a fragment of representation of a unicode string in Python, e.g. if you write:

>>> text = u'‘'
>>> print repr(text)
u'\u2018'

Now if you simply want to print the unicode string prettily, just use unicode's encode method:

>>> text = u'I don\u2018t like this'
>>> print text.encode('utf-8')
I don‘t like this

To make sure that every line from any file would be read as unicode, you'd better use the codecs.open function instead of just open, which allows you to specify file's encoding:

>>> import codecs
>>> f1 = codecs.open(file1, "r", "utf-8")
>>> text = f1.read()
>>> print type(text)
<type 'unicode'>
>>> print text.encode('utf-8')
I don‘t like this

How do you check that a number is NaN in JavaScript?

You should use the global isNaN(value) function call, because:

  • It is supported cross-browser
  • See isNaN for documentation

Examples:

 isNaN('geoff'); // true
 isNaN('3'); // false

I hope this will help you.

MySQL WHERE: how to write "!=" or "not equals"?

DELETE FROM konta WHERE taken <> '';

What is the reason and how to avoid the [FIN, ACK] , [RST] and [RST, ACK]

Here is a rough explanation of the concepts.

[ACK] is the acknowledgement that the previously sent data packet was received.

[FIN] is sent by a host when it wants to terminate the connection; the TCP protocol requires both endpoints to send the termination request (i.e. FIN).

So, suppose

  • host A sends a data packet to host B
  • and then host B wants to close the connection.
  • Host B (depending on timing) can respond with [FIN,ACK] indicating that it received the sent packet and wants to close the session.
  • Host A should then respond with a [FIN,ACK] indicating that it received the termination request (the ACK part) and that it too will close the connection (the FIN part).

However, if host A wants to close the session after sending the packet, it would only send a [FIN] packet (nothing to acknowledge) but host B would respond with [FIN,ACK] (acknowledges the request and responds with FIN).

Finally, some TCP stacks perform half-duplex termination, meaning that they can send [RST] instead of the usual [FIN,ACK]. This happens when the host actively closes the session without processing all the data that was sent to it. Linux is one operating system which does just this.

You can find a more detailed and comprehensive explanation here.

How can I specify a branch/tag when adding a Git submodule?

Note: Git 1.8.2 added the possibility to track branches. See some of the answers below.


It's a little confusing to get used to this, but submodules are not on a branch. They are, like you say, just a pointer to a particular commit of the submodule's repository.

This means, when someone else checks out your repository, or pulls your code, and does git submodule update, the submodule is checked out to that particular commit.

This is great for a submodule that does not change often, because then everyone on the project can have the submodule at the same commit.

If you want to move the submodule to a particular tag:

cd submodule_directory
git checkout v1.0
cd ..
git add submodule_directory
git commit -m "moved submodule to v1.0"
git push

Then, another developer who wants to have submodule_directory changed to that tag, does this

git pull
git submodule update --init

git pull changes which commit their submodule directory points to. git submodule update actually merges in the new code.

Javascript-Setting background image of a DIV via a function and function parameter

If you are looking for a direct approach and using a local File in that case. Try

<div
style={{ background-image: 'url(' + Image + ')', background-size: 'auto' }}
/>

This is the case of JS with inline styling where Image is a local file that you must have imported with a path.

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

... or if you really want to use NOT IN you can use

SELECT * FROM match WHERE id NOT IN ( SELECT id FROM email WHERE id IS NOT NULL)

Using if(isset($_POST['submit'])) to not display echo when script is open is not working

You must give a name to your submit button

<input type="submit" value"Submit" name="login">

Then you can call the button with $_POST['login']

How to position a div in the middle of the screen when the page is bigger than the screen

Well, below is the working example for this.

This will handle the center position if you resize the webpage or load in anysize.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
.loader {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  margin-top: -50px;_x000D_
  margin-left: -50px;_x000D_
  border: 10px solid #dcdcdc;_x000D_
  border-radius: 50%;_x000D_
  border-top: 10px solid #3498db;_x000D_
  width: 30px;_x000D_
  height: 30px;_x000D_
  -webkit-animation: spin 2s linear infinite;_x000D_
  animation: spin 1s linear infinite;  _x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin {_x000D_
  0% { -webkit-transform: rotate(0deg); }_x000D_
  100% { -webkit-transform: rotate(360deg); }_x000D_
}_x000D_
_x000D_
@keyframes spin {_x000D_
  0% { transform: rotate(0deg); }_x000D_
  100% { transform: rotate(360deg); }_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
_x000D_
<div class="loader" style="display:block"></div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

In above sample loading div will always be in center.

Hoping this will help you :)

How to prevent IFRAME from redirecting top-level window

Try using the onbeforeunload property, which will let the user choose whether he wants to navigate away from the page.

Example: https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload

In HTML5 you can use sandbox property. Please see Pankrat's answer below. http://www.html5rocks.com/en/tutorials/security/sandboxed-iframes/

Git reset single file in feature branch to be the same as in master

If you want to revert the file to its state in master:

git checkout origin/master [filename]

What is the difference between Scrum and Agile Development?

Scrum is just one of the many iterative and incremental agile software development methods. You can find here a very detailed description of the process.

In the SCRUM methodology, a Sprint is the basic unit of development. Each Sprint starts with a planning meeting, where the tasks for the sprint are identified and an estimated commitment for the sprint goal is made. A Sprint ends with a review or retrospective meeting where the progress is reviewed and lessons for the next sprint are identified. During each Sprint, the team creates finished portions of a Product.

In the Agile methods each iteration involves a team working through a full software development cycle, including planning, requirements analysis, design, coding, unit testing, and acceptance testing when a working product is demonstrated to stakeholders.

So if in a SCRUM Sprint you perform all the software development phases (from requirement analysis to acceptance testing), and in my opinion you should, you can say SCRUM Sprints correspond to AGILE Iterations.

How to insert multiple rows from a single query using eloquent/fluent

using Eloquent

$data = array(
    array('user_id'=>'Coder 1', 'subject_id'=> 4096),
    array('user_id'=>'Coder 2', 'subject_id'=> 2048),
    //...
);

Model::insert($data);

Removing All Items From A ComboBox?

You can use the ControlFormat method:

ComboBox1.ControlFormat.RemoveAllItems

jQuery.each - Getting li elements inside an ul

Given an answer as high voted and views. I did find the answer with mixed of here and other links.

I have a scenario where all patient-related menu is disabled if a patient is not selected. (Refer link - how to disable a li tag using JavaScript)

//css
.disabled{
    pointer-events:none;
    opacity:0.4;
}
// jqvery
$("li a").addClass('disabled');
// remove .disabled when you are done

So rather than write long code, I found an interesting solution via CSS.

_x000D_
_x000D_
$(document).ready(function () {_x000D_
 var PatientId ; _x000D_
 //var PatientId =1;  //remove to test enable i.e. patient selected_x000D_
 if (typeof PatientId == "undefined" || PatientId == "" || PatientId == 0 || PatientId == null) {_x000D_
  console.log(PatientId);_x000D_
  $("#dvHeaderSubMenu a").each(function () {   _x000D_
   $(this).addClass('disabled');_x000D_
  });  _x000D_
  return;_x000D_
 }_x000D_
})
_x000D_
.disabled{_x000D_
    pointer-events:none;_x000D_
    opacity:0.4;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dvHeaderSubMenu">_x000D_
     <ul class="m-nav m-nav--inline pull-right nav-sub">_x000D_
      <li class="m-nav__item">_x000D_
       <a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
        <i class="m-nav__link-icon fa fa-tachometer"></i>_x000D_
        Overview_x000D_
       </a>_x000D_
      </li>_x000D_
_x000D_
      <li class="m-nav__item active">_x000D_
       <a href="#" onclick="console.log('PatientMenu Clicked')" >_x000D_
        <i class="m-nav__link-icon fa fa-user"></i>_x000D_
        Personal_x000D_
       </a>_x000D_
      </li>_x000D_
            <li class="m-nav__item m-dropdown m-dropdown--inline m-dropdown--arrow" data-dropdown-toggle="hover">_x000D_
       <a href="#" class="m-dropdown__toggle dropdown-toggle" onclick="console.log('PatientMenu Clicked')">_x000D_
        <i class="m-nav__link-icon flaticon-medical-8"></i>_x000D_
        Insurance Claim_x000D_
       </a>_x000D_
       <div class="m-dropdown__wrapper">_x000D_
        <span class="m-dropdown__arrow m-dropdown__arrow--left"></span>_x000D_
        _x000D_
           <ul class="m-nav">_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')" >_x000D_
              <i class="m-nav__link-icon flaticon-toothbrush-1"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Primary_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
              <i class="m-nav__link-icon flaticon-interface"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Secondary_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
            <li class="m-nav__item">_x000D_
             <a href="#" class="m-nav__link" onclick="console.log('PatientMenu Clicked')">_x000D_
              <i class="m-nav__link-icon flaticon-healthy"></i>_x000D_
              <span class="m-nav__link-text">_x000D_
               Medical_x000D_
              </span>_x000D_
             </a>_x000D_
            </li>_x000D_
           </ul>_x000D_
          _x000D_
       _x000D_
      </li>_x000D_
     </ul>            _x000D_
</div>
_x000D_
_x000D_
_x000D_

Android : Check whether the phone is dual SIM

I am able to read both the IMEI's from OnePlus 2 Phone

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                TelephonyManager manager = (TelephonyManager) getActivity().getSystemService(Context.TELEPHONY_SERVICE);
                Log.i(TAG, "Single or Dual Sim " + manager.getPhoneCount());
                Log.i(TAG, "Default device ID " + manager.getDeviceId());
                Log.i(TAG, "Single 1 " + manager.getDeviceId(0));
                Log.i(TAG, "Single 2 " + manager.getDeviceId(1));
            }

How to perform case-insensitive sorting in JavaScript?

You can also use the Elvis operator:

arr = ['Bob', 'charley', 'fudge', 'Fudge', 'biscuit'];
arr.sort(function(s1, s2){
    var l=s1.toLowerCase(), m=s2.toLowerCase();
    return l===m?0:l>m?1:-1;
});
console.log(arr);

Gives:

biscuit,Bob,charley,fudge,Fudge

The localeCompare method is probably fine though...

Note: The Elvis operator is a short form 'ternary operator' for if then else, usually with assignment.
If you look at the ?: sideways, it looks like Elvis...
i.e. instead of:

if (y) {
  x = 1;
} else {
  x = 2;
}

you can use:

x = y?1:2;

i.e. when y is true, then return 1 (for assignment to x), otherwise return 2 (for assignment to x).

Convert from MySQL datetime to another format with PHP

An easier way would be to format the date directly in the MySQL query, instead of PHP. See the MySQL manual entry for DATE_FORMAT.

If you'd rather do it in PHP, then you need the date function, but you'll have to convert your database value into a timestamp first.

header location not working in my php code

The function ob_start() will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer. So browser will not receive any output and the header will work.Also we should make sure that header() is used on the top of the code.

JQuery window scrolling event?

Check if the user has scrolled past the header ad, then display the footer ad.

if($(your header ad).position().top < 0) { $(your footer ad).show() }

Am I correct at what you are looking for?

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

I had a similar problem and although I made sure that referenced entities were saved first it keeps failing with the same exception. After hours of investigation it turns out that the problem was because the "version" column of the referenced entity was NULL. In my particular setup i was inserting it first in an HSQLDB(that was a unit test) a row like that:

INSERT INTO project VALUES (1,1,'2013-08-28 13:05:38','2013-08-28 13:05:38','aProject','aa',NULL,'bb','dd','ee','ff','gg','ii',NULL,'LEGACY','0','CREATED',NULL,NULL,1,'0',NULL,NULL,NULL,NULL,'0','0', NULL);

The problem of the above is the version column used by hibernate was set to null, so even if the object was correctly saved, Hibernate considered it as unsaved. When making sure the version had a NON-NULL(1 in this case) value the exception disappeared and everything worked fine.

I am putting it here in case someone else had the same problem, since this took me a long time to figure this out and the solution is completely different than the above.

Unable to locate tools.jar

No, according to your directory structure, you have installed a JRE, not a JDK. There's a difference.

C:\Program Files\Java\jre6\lib
                      ^^^^

It should be something like:

C:\Program Files\Java\jdk1.6.0_24

node.js TypeError: path must be absolute or specify root to res.sendFile [failed to parse JSON]

I used the code below and tried to show the sitemap.xml file

router.get('/sitemap.xml', function (req, res) {
    res.sendFile('sitemap.xml', { root: '.' });
});

Property 'value' does not exist on type 'EventTarget'

You need to explicitly tell TypeScript the type of the HTMLElement which is your target.

The way to do it is using a generic type to cast it to a proper type:

this.countUpdate.emit((<HTMLTextAreaElement>e.target).value./*...*/)

or (as you like)

this.countUpdate.emit((e.target as HTMLTextAreaElement).value./*...*/)

or (again, matter of preference)

const target = e.target as HTMLTextAreaElement;

this.countUpdate.emit(target.value./*...*/)

This will let TypeScript know that the element is a textarea and it will know of the value property.

The same could be done with any kind of HTML element, whenever you give TypeScript a bit more information about their types it pays you back with proper hints and of course less errors.

To make it easier for the future you might want to directly define an event with the type of its target:

// create a new type HTMLElementEvent that has a target of type you pass
// type T must be a HTMLElement (e.g. HTMLTextAreaElement extends HTMLElement)
type HTMLElementEvent<T extends HTMLElement> = Event & {
  target: T; 
  // probably you might want to add the currentTarget as well
  // currentTarget: T;
}

// use it instead of Event
let e: HTMLElementEvent<HTMLTextAreaElement>;

console.log(e.target.value);

// or in the context of the given example
emitWordCount(e: HTMLElementEvent<HTMLTextAreaElement>) {
  this.countUpdate.emit(e.target.value);
}

How to get the absolute path to the public_html folder?

Let's asume that show_images.php is in folder images and the site root is public_html, so:

echo dirname(__DIR__); // prints '/home/public_html/'
echo dirname(__FILE__); // prints '/home/public_html/images'

How to kill a thread instantly in C#?

thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.

Add space between HTML elements only using CSS

You can take advantage of the fact that span is an inline element

span{
     word-spacing:10px;
}

However, this solution will break if you have more than one word of text in your span

setOnItemClickListener on custom ListView

If in the listener you get the root layout of the item (say itemLayout), and you gave some id's to the textviews, you can then get them with something like itemLayout.findViewById(R.id.textView1).

Resize UIImage by keeping Aspect ratio and width

Zeeshan Tufail and Womble answers in Swift 5 with small improvements. Here we have extension with 2 functions to scale image to maxLength of any dimension and jpeg compression.

extension UIImage {
    func aspectFittedToMaxLengthData(maxLength: CGFloat, compressionQuality: CGFloat) -> Data {
        let scale = maxLength / max(self.size.height, self.size.width)
        let format = UIGraphicsImageRendererFormat()
        format.scale = scale
        let renderer = UIGraphicsImageRenderer(size: self.size, format: format)
        return renderer.jpegData(withCompressionQuality: compressionQuality) { context in
            self.draw(in: CGRect(origin: .zero, size: self.size))
        }
    }
    func aspectFittedToMaxLengthImage(maxLength: CGFloat, compressionQuality: CGFloat) -> UIImage? {
        let newImageData = aspectFittedToMaxLengthData(maxLength: maxLength, compressionQuality: compressionQuality)
        return UIImage(data: newImageData)
    }
}

Groovy / grails how to determine a data type?

Simple groovy way to check object type:

somObject in Date

Can be applied also to interfaces.

How to render a PDF file in Android

Since API Level 21 (Lollipop) Android provides a PdfRenderer class:

// create a new renderer
 PdfRenderer renderer = new PdfRenderer(getSeekableFileDescriptor());

 // let us just render all pages
 final int pageCount = renderer.getPageCount();
 for (int i = 0; i < pageCount; i++) {
     Page page = renderer.openPage(i);

     // say we render for showing on the screen
     page.render(mBitmap, null, null, Page.RENDER_MODE_FOR_DISPLAY);

     // do stuff with the bitmap

     // close the page
     page.close();
 }

 // close the renderer
 renderer.close();

For more information see the sample app.

For older APIs I recommend Android PdfViewer library, it is very fast and easy to use, licensed under Apache License 2.0:

pdfView.fromAsset(String)
  .pages(0, 2, 1, 3, 3, 3) // all pages are displayed by default
  .enableSwipe(true)
  .swipeHorizontal(false)
  .enableDoubletap(true)
  .defaultPage(0)
  .onDraw(onDrawListener)
  .onLoad(onLoadCompleteListener)
  .onPageChange(onPageChangeListener)
  .onPageScroll(onPageScrollListener)
  .onError(onErrorListener)
  .enableAnnotationRendering(false)
  .password(null)
  .scrollHandle(null)
  .load();

Read String line by line

There is also Scanner. You can use it just like the BufferedReader:

Scanner scanner = new Scanner(myString);
while (scanner.hasNextLine()) {
  String line = scanner.nextLine();
  // process the line
}
scanner.close();

I think that this is a bit cleaner approach that both of the suggested ones.

Make browser window blink in task Bar

"Make browser window blink in task Bar"

via Javascript 

is not possible!!

How to connect to a MS Access file (mdb) using C#?

The simplest way to connect is through an OdbcConnection using code like this

using System.Data.Odbc;

using(OdbcConnection myConnection = new OdbcConnection())
{
    myConnection.ConnectionString = myConnectionString;
    myConnection.Open();

    //execute queries, etc

}

where myConnectionString is something like this

myConnectionString = @"Driver={Microsoft Access Driver (*.mdb)};" + 
"Dbq=C:\mydatabase.mdb;Uid=Admin;Pwd=;

See ConnectionStrings

In alternative you could create a DSN and then use that DSN in your connection string

  • Open the Control Panel - Administrative Tools - ODBC Data Source Manager
  • Go to the System DSN Page and ADD a new DSN
  • Choose the Microsoft Access Driver (*.mdb) and press END
  • Set the Name of the DSN (choose MyDSN for this example)
  • Select the Database to be used
  • Try the Compact or Recover commands to see if the connection works

now your connectionString could be written in this way

myConnectionString = "DSN=myDSN;"

How do I fix 'Invalid character value for cast specification' on a date column in flat file?

I was ultimately able to resolve the solution by setting the column type in the flat file connection to be of type "database date [DT_DBDATE]"

Apparently the differences between these date formats are as follow:

DT_DATE A date structure that consists of year, month, day, and hour.

DT_DBDATE A date structure that consists of year, month, and day.

DT_DBTIMESTAMP A timestamp structure that consists of year, month, hour, minute, second, and fraction

By changing the column type to DT_DBDATE the issue was resolved - I attached a Data Viewer and the CYCLE_DATE value was now simply "12/20/2010" without a time component, which apparently resolved the issue.

Can I apply a CSS style to an element name?

if in case you are not using name in input but other element, then you can target other element with there attribute.

_x000D_
_x000D_
    [title~=flower] {_x000D_
      border: 5px solid yellow;_x000D_
    }
_x000D_
    <img src="klematis.jpg" title="klematis flower" width="150" height="113">_x000D_
    <img src="img_flwr.gif" title="flower" width="224" height="162">_x000D_
    <img src="img_flwr.gif" title="flowers" width="224" height="162">
_x000D_
_x000D_
_x000D_

hope its help. Thank you

Can the :not() pseudo-class have multiple arguments?

I was having some trouble with this, and the "X:not():not()" method wasn't working for me.

I ended up resorting to this strategy:

INPUT {
    /* styles */
}
INPUT[type="radio"], INPUT[type="checkbox"] {
    /* styles that reset previous styles */
}

It's not nearly as fun, but it worked for me when :not() was being pugnacious. It's not ideal, but it's solid.

How to draw a checkmark / tick using CSS?

Try this // html example

<span>&#10003;</span>

// css example

span {
  content: "\2713";
}

simple HTTP server in Java using only Java SE API

Since Java SE 6, there's a builtin HTTP server in Sun Oracle JRE. The com.sun.net.httpserver package summary outlines the involved classes and contains examples.

Here's a kickoff example copypasted from their docs (to all people trying to edit it nonetheless, because it's an ugly piece of code, please don't, this is a copy paste, not mine, moreover you should never edit quotations unless they have changed in the original source). You can just copy'n'paste'n'run it on Java 6+.

package com.stackoverflow.q3732109;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class Test {

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/test", new MyHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
    }

    static class MyHandler implements HttpHandler {
        @Override
        public void handle(HttpExchange t) throws IOException {
            String response = "This is the response";
            t.sendResponseHeaders(200, response.length());
            OutputStream os = t.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }

}

Noted should be that the response.length() part in their example is bad, it should have been response.getBytes().length. Even then, the getBytes() method must explicitly specify the charset which you then specify in the response header. Alas, albeit misguiding to starters, it's after all just a basic kickoff example.

Execute it and go to http://localhost:8000/test and you'll see the following response:

This is the response


As to using com.sun.* classes, do note that this is, in contrary to what some developers think, absolutely not forbidden by the well known FAQ Why Developers Should Not Write Programs That Call 'sun' Packages. That FAQ concerns the sun.* package (such as sun.misc.BASE64Encoder) for internal usage by the Oracle JRE (which would thus kill your application when you run it on a different JRE), not the com.sun.* package. Sun/Oracle also just develop software on top of the Java SE API themselves like as every other company such as Apache and so on. Using com.sun.* classes is only discouraged (but not forbidden) when it concerns an implementation of a certain Java API, such as GlassFish (Java EE impl), Mojarra (JSF impl), Jersey (JAX-RS impl), etc.

Python Requests throwing SSLError

I have found an specific approach for solving a similar issue. The idea is pointing the cacert file stored at the system and used by another ssl based applications.

In Debian (I'm not sure if same in other distributions) the certificate files (.pem) are stored at /etc/ssl/certs/ So, this is the code that work for me:

import requests
verify='/etc/ssl/certs/cacert.org.pem'
response = requests.get('https://lists.cacert.org', verify=verify)

For guessing what pem file choose, I have browse to the url and check which Certificate Authority (CA) has generated the certificate.

EDIT: if you cannot edit the code (because you are running a third app) you can try to add the pem certificate directly into /usr/local/lib/python2.7/dist-packages/requests/cacert.pem (e.g. copying it to the end of the file).

Selecting Values from Oracle Table Variable / Array?

You might need a GLOBAL TEMPORARY TABLE.

In Oracle these are created once and then when invoked the data is private to your session.

Oracle Documentation Link

Try something like this...

CREATE GLOBAL TEMPORARY TABLE temp_number
   ( number_column   NUMBER( 10, 0 )
   )
   ON COMMIT DELETE ROWS;

BEGIN 
   INSERT INTO temp_number
      ( number_column )
      ( select distinct sgbstdn_pidm 
          from sgbstdn 
         where sgbstdn_majr_code_1 = 'HS04' 
           and sgbstdn_program_1 = 'HSCOMPH' 
      ); 

    FOR pidms_rec IN ( SELECT number_column FROM temp_number )
    LOOP 
        -- Do something here
        NULL; 
    END LOOP; 
END; 
/

Perl: Use s/ (replace) and return new string

If you have Perl 5.14 or greater, you can use the /r option with the substitution operator to perform non-destructive substitution:

print "bla: ", $myvar =~ s/a/b/r, "\n";

In earlier versions you can achieve the same using a do() block with a temporary lexical variable, e.g.:

print "bla: ", do { (my $tmp = $myvar) =~ s/a/b/; $tmp }, "\n";

redirect while passing arguments

I found that none of the answers here applied to my specific use case, so I thought I would share my solution.

I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:

/app/4903294/my-great-car?email=coolguy%40gmail.com to

/public/4903294/my-great-car?email=coolguy%40gmail.com

Here's the solution that worked for me.

return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))

Hope this helps someone!

Is there a unique Android device ID?

Settings.Secure#ANDROID_ID returns the Android ID as an unique for each user 64-bit hex string.

import android.provider.Settings.Secure;

private String android_id = Secure.getString(getContext().getContentResolver(),
                                                        Secure.ANDROID_ID);

Also read Best practices for unique identifiers: https://developer.android.com/training/articles/user-data-ids

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

I had installed Python 32 bit version and psycopg2 64 bit version to get this problem. I installed psycopg2 32 bit version and then it worked.

Subscript out of range error in this Excel VBA script

Set sh1 = Worksheets(filenum(lngPosition)).Activate

You are getting Subscript out of range error error becuase it cannot find that Worksheet.

Also please... please... please do not use .Select/.Activate/Selection/ActiveCell You might want to see How to Avoid using Select in Excel VBA Macros.

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

You can use the following code. Here I am uploading the image to firebase storage and then I am storing the image download url to firebase database.

//getting the storage reference
            StorageReference sRef = storageReference.child(Constants.STORAGE_PATH_UPLOADS + System.currentTimeMillis() + "." + getFileExtension(filePath));

            //adding the file to reference 
            sRef.putFile(filePath)
                    .addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
                            //dismissing the progress dialog
                            progressDialog.dismiss();

                            //displaying success toast 
                            Toast.makeText(getApplicationContext(), "File Uploaded ", Toast.LENGTH_LONG).show();

                            //creating the upload object to store uploaded image details 
                            Upload upload = new Upload(editTextName.getText().toString().trim(), taskSnapshot.getDownloadUrl().toString());

                            //adding an upload to firebase database 
                            String uploadId = mDatabase.push().getKey();
                            mDatabase.child(uploadId).setValue(upload);
                        }
                    })
                    .addOnFailureListener(new OnFailureListener() {
                        @Override
                        public void onFailure(@NonNull Exception exception) {
                            progressDialog.dismiss();
                            Toast.makeText(getApplicationContext(), exception.getMessage(), Toast.LENGTH_LONG).show();
                        }
                    })
                    .addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
                        @Override
                        public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
                            //displaying the upload progress 
                            double progress = (100.0 * taskSnapshot.getBytesTransferred()) / taskSnapshot.getTotalByteCount();
                            progressDialog.setMessage("Uploaded " + ((int) progress) + "%...");
                        }
                    });

Now to fetch all the images stored in firebase database you can use

//adding an event listener to fetch values
        mDatabase.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot snapshot) {
                //dismissing the progress dialog 
                progressDialog.dismiss();

                //iterating through all the values in database
                for (DataSnapshot postSnapshot : snapshot.getChildren()) {
                    Upload upload = postSnapshot.getValue(Upload.class);
                    uploads.add(upload);
                }
                //creating adapter
                adapter = new MyAdapter(getApplicationContext(), uploads);

                //adding adapter to recyclerview
                recyclerView.setAdapter(adapter);
            }

            @Override
            public void onCancelled(DatabaseError databaseError) {
                progressDialog.dismiss();
            }
        });

Fore more details you can see my post Firebase Storage Example.

Why would one mark local variables and method parameters as "final" in Java?

Yes do it.

It's about readability. It's easier to reason about the possible states of the program when you know that variables are assigned once and only once.

A decent alternative is to turn on the IDE warning when a parameter is assigned, or when a variable (other than a loop variable) is assigned more than once.

how to add button click event in android studio

You need to do nothing but, just type new View.OnClickListener() in your btnClick.setOnClickListener(). I mean you have to type btnClick.setOnClickListener(new View.onClickListener the bracket will remain open, just hit enter then a method will be created like this,

btnClick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

        }
    });

It's just mean that you are creating a new view of OnClickListener and passing a view as it's a parameter. Now you can do whatever u were supposed to do, in that onClick(View v) method.

jQuery UI Dialog with ASP.NET button postback

I just added the following line after you created the dialog:

$(".ui-dialog").prependTo("form");

sqldeveloper error message: Network adapter could not establish the connection error

https://forums.oracle.com/forums/thread.jspa?threadID=2150962

Re: SQL DevErr:The Network Adapter could not establish the connection VenCode20 Posted: Dec 7, 2011 3:23 AM in response to: MehulDoshi Reply

This worked for me:

Open the "New/Select Database Connection" dialogue and try changing the connection type setting from "Basic" to "TNS" and then selecting the network alias (for me: "ORCL").

How to calculate an age based on a birthday?

Stackoverflow uses such function to determine the age of a user.

Calculate age in C#

The given answer is

DateTime now = DateTime.Today;
int age = now.Year - bday.Year;
if (now < bday.AddYears(age)) age--;

So your helper method would look like

public static string Age(this HtmlHelper helper, DateTime birthday)
{
    DateTime now = DateTime.Today;
    int age = now.Year - birthday.Year;
    if (now < birthday.AddYears(age)) age--;

    return age.ToString();
}

Today, I use a different version of this function to include a date of reference. This allow me to get the age of someone at a future date or in the past. This is used for our reservation system, where the age in the future is needed.

public static int GetAge(DateTime reference, DateTime birthday)
{
    int age = reference.Year - birthday.Year;
    if (reference < birthday.AddYears(age)) age--;

    return age;
}

What does value & 0xff do in Java?

From http://www.coderanch.com/t/236675/java-programmer-SCJP/certification/xff

The hex literal 0xFF is an equal int(255). Java represents int as 32 bits. It look like this in binary:

00000000 00000000 00000000 11111111

When you do a bit wise AND with this value(255) on any number, it is going to mask(make ZEROs) all but the lowest 8 bits of the number (will be as-is).

... 01100100 00000101 & ...00000000 11111111 = 00000000 00000101

& is something like % but not really.

And why 0xff? this in ((power of 2) - 1). All ((power of 2) - 1) (e.g 7, 255...) will behave something like % operator.

Then
In binary, 0 is, all zeros, and 255 looks like this:

00000000 00000000 00000000 11111111

And -1 looks like this

11111111 11111111 11111111 11111111

When you do a bitwise AND of 0xFF and any value from 0 to 255, the result is the exact same as the value. And if any value higher than 255 still the result will be within 0-255.

However, if you do:

-1 & 0xFF

you get

00000000 00000000 00000000 11111111, which does NOT equal the original value of -1 (11111111 is 255 in decimal).


Few more bit manipulation: (Not related to the question)

X >> 1 = X/2
X << 1 = 2X

Check any particular bit is set(1) or not (0) then

 int thirdBitTobeChecked =   1 << 2   (...0000100)
 int onWhichThisHasTobeTested = 5     (.......101)

 int isBitSet = onWhichThisHasTobeTested  & thirdBitTobeChecked;
 if(isBitSet > 0) {
  //Third Bit is set to 1 
 } 

Set(1) a particular bit

 int thirdBitTobeSet =   1 << 2    (...0000100)
 int onWhichThisHasTobeSet = 2     (.......010)
 onWhichThisHasTobeSet |= thirdBitTobeSet;

ReSet(0) a particular bit

int thirdBitTobeReSet =   ~(1 << 2)  ; //(...1111011)
int onWhichThisHasTobeReSet = 6      ;//(.....000110)
onWhichThisHasTobeReSet &= thirdBitTobeReSet;

XOR

Just note that if you perform XOR operation twice, will results the same value.

byte toBeEncrypted = 0010 0110
byte salt          = 0100 1011

byte encryptedVal  =  toBeEncrypted ^ salt == 0110 1101
byte decryptedVal  =  encryptedVal  ^ salt == 0010 0110 == toBeEncrypted :)

One more logic with XOR is

if     A (XOR) B == C (salt)
then   C (XOR) B == A
       C (XOR) A == B

The above is useful to swap two variables without temp like below

a = a ^ b; b = a ^ b; a = a ^ b;

OR

a ^= b ^= a ^= b;

How do I concatenate strings and variables in PowerShell?

I seem to struggle with this (and many other unintuitive things) every time I use PowerShell after time away from it, so I now opt for:

[string]::Concat("There are ", $count, " items in the list")

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

Here is the pure HTML and CSS solution.

  1. We create a container box for navbar with position: fixed; height:100%;

  2. Then we create an inner box with height: 100%; overflow-y: scroll;

  3. Next, we put out content inside that box.

Here is the code:

_x000D_
_x000D_
.nav-box{_x000D_
        position: fixed;_x000D_
        border: 1px solid #0a2b1d;_x000D_
        height:100%;_x000D_
   }_x000D_
   .inner-box{_x000D_
        width: 200px;_x000D_
        height: 100%;_x000D_
        overflow-y: scroll;_x000D_
        border: 1px solid #0A246A;_x000D_
    }_x000D_
    .tabs{_x000D_
        border: 3px solid chartreuse;_x000D_
        color:darkred;_x000D_
    }_x000D_
    .content-box p{_x000D_
      height:50px;_x000D_
      text-align:center;_x000D_
    }
_x000D_
<div class="nav-box">_x000D_
  <div class="inner-box">_x000D_
    <div class="tabs"><p>Navbar content Start</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content</p></div>_x000D_
    <div class="tabs"><p>Navbar content End</p></div>_x000D_
    </div>_x000D_
</div>_x000D_
<div class="content-box">_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
  <p>Lorem Ipsum</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link to jsFiddle:

File path for project files?

You would do something like this to get the path "Data\ich_will.mp3" inside your application environments folder.

string fileName = "ich_will.mp3";
string path = Path.Combine(Environment.CurrentDirectory, @"Data\", fileName);

In my case it would return the following:

C:\MyProjects\Music\MusicApp\bin\Debug\Data\ich_will.mp3

I use Path.Combine and Environment.CurrentDirectory in my example. These are very useful and allows you to build a path based on the current location of your application. Path.Combine combines two or more strings to create a location, and Environment.CurrentDirectory provides you with the working directory of your application.

The working directory is not necessarily the same path as where your executable is located, but in most cases it should be, unless specified otherwise.

How to check if a Java 8 Stream is empty?

Following Stuart's idea, this could be done with a Spliterator like this:

static <T> Stream<T> defaultIfEmpty(Stream<T> stream, Stream<T> defaultStream) {
    final Spliterator<T> spliterator = stream.spliterator();
    final AtomicReference<T> reference = new AtomicReference<>();
    if (spliterator.tryAdvance(reference::set)) {
        return Stream.concat(Stream.of(reference.get()), StreamSupport.stream(spliterator, stream.isParallel()));
    } else {
        return defaultStream;
    }
}

I think this works with parallel Streams as the stream.spliterator() operation will terminate the stream, and then rebuild it as required

In my use-case I needed a default Stream rather than a default value. that's quite easy to change if this is not what you need

Reverse a string in Python

def reverse(input):
    return reduce(lambda x,y : y+x, input)

Check which element has been clicked with jQuery

Another option can be to utilize the tagName property of the e.target. It doesn't apply exactly here, but let's say I have a class of something that's applied to either a DIV or an A tag, and I want to see if that class was clicked, and determine whether it was the DIV or the A that was clicked. I can do something like:

$('.example-class').click(function(e){
  if ((e.target.tagName.toLowerCase()) == 'a') {
    console.log('You clicked an A element.');
  } else { // DIV, we assume in this example
    console.log('You clicked a DIV element.');
  }
});

Parsing jQuery AJAX response

you must parse JSON string to become object

var dataObject = jQuery.parseJSON(data);

so you can call it like:

success: function (data) {
    var dataObject = jQuery.parseJSON(data);
    if (dataObject.success == 1) {
       var insertedGoalId = dataObject.inserted.goal_id;
       ...
       ...
    }
}

How do I 'foreach' through a two-dimensional array?

Here's a simple extension method that returns each row as an IEnumerable<T>. This has the advantage of not using any extra memory:

public static class Array2dExt
{
    public static IEnumerable<IEnumerable<T>> Rows<T>(this T[,] array)
    {
        for (int r = array.GetLowerBound(0); r <= array.GetUpperBound(0); ++r)
            yield return row(array, r);
    }

    static IEnumerable<T> row<T>(T[,] array, int r)
    {
        for (int c = array.GetLowerBound(1); c <= array.GetUpperBound(1); ++c)
            yield return array[r, c];
    }
}

Sample usage:

static void Main()
{
    string[,] siblings = { { "Mike", "Amy" }, { "Mary", "Albert" }, {"Fred", "Harry"} };

    foreach (var row in siblings.Rows())
        Console.WriteLine("{" + string.Join(", ", row) + "}");
}

What is the "__v" field in Mongoose

Well, I can't see Tony's solution...so I have to handle it myself...


If you don't need version_key, you can just:

var UserSchema = new mongoose.Schema({
    nickname: String,
    reg_time: {type: Date, default: Date.now}
}, {
    versionKey: false // You should be aware of the outcome after set to false
});

Setting the versionKey to false means the document is no longer versioned.

This is problematic if the document contains an array of subdocuments. One of the subdocuments could be deleted, reducing the size of the array. Later on, another operation could access the subdocument in the array at it's original position.

Since the array is now smaller, it may accidentally access the wrong subdocument in the array.

The versionKey solves this by associating the document with the a versionKey, used by mongoose internally to make sure it accesses the right collection version.

More information can be found at: http://aaronheckmann.blogspot.com/2012/06/mongoose-v3-part-1-versioning.html

iOS UIImagePickerController result image orientation after upload

I achieve this by writing below a few lines of code

extension UIImage {

    public func correctlyOrientedImage() -> UIImage {
        guard imageOrientation != .up else { return self }

        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        draw(in: CGRect(origin: .zero, size: size))
        let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()

        return normalizedImage
    }
}

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

I've created config/initializers/secret_key.rb file and I wrote only following line of code:

Rails.application.config.secret_key_base = ENV["SECRET_KEY_BASE"]

But I think that solution posted by @Erik Trautman is more elegant ;)

Edit: Oh, and finally I found this advice on Heroku: https://devcenter.heroku.com/changelog-items/426 :)

Enjoy!

How do I reference a cell range from one worksheet to another using excel formulas?

Simple ---

I have created a Sheet 2 with 4 cells and Sheet 1 with a single Cell with a Formula:

=SUM(Sheet2!B3:E3)

Note, trying as you stated, it does not make sense to assign a Single Cell a value from a range. Send it to a Formula that uses a range to do something with it.