text:
Q: Why my model not work in serviceRepository laravel? I have a service-providers here as well as http://dfg.gd/blog/decoupling-your-code-in-laravel-using-repositiories-and-services
My ServiceProvider:
class UsersRepositoryServiceProvider extends ServiceProvider
{
    public function register()
    {
        $this->app->bind('App\Repositories\Users\UsersInterface', function($app)
        {

            return new UsersRepository(new User);

        });
    }

And i get error: Call to a member function find() on a non-object
My Repository:
use \Illuminate\Database\Eloquent\Model;
//..
protected $usersModel;

public function __consturct(Model $users)
{
    $this->usersModel = $users;
}

/**
 * Get user by id
 *
 * @param mixed $userId
 * @return Model
 */
public function getUserById($userId)
{
    return $this->convertFormat($this->usersModel->find($userId));
}

A: __consturct is misspelled.
correct is __construct


text:
Q: Available Miicrosoft Cognitive regions I'm looking for a Voice Authentication API, and I find Microsoft's one.
When looking at prices, it asks you for a region. The problem is that
it only shows a region

I've been reading about Azure's regions, and it say that is where data is stored, so my question is if it would be possible to use it in a different region than allowed.
Thanks (and sorry for my spelling mistakes).

A: Quick Answer:
Normally yes, but currently the Speaker Recognition API is only offered out of the WestUS datacenter.
If it's mandatory that you have low-latency when using the service, I suggest you look into setting up and/or temporarily subscribing to a CDN service. Or, if you have a lot of time on your hands, and know waaaaay more than I do about this subject, you may be able to design a local cache to mitigate latency if you're distant from WestUS.
Less-Quick Answer:
First off, you should use the dashboard interface at https://portal.azure.com to sign up. You will first need to create a Pay-As-You-Go subscription as your payment-medium, but it will give you much more control over & visibility into your service.
Here's what the signup pane looks like inside of https://portal.azure.com:

It appears that, in it's current "PREVIEW" deployment, you are right the services is only offered from the the WestUS data center. Normally you will have the option to one of ten's of global datacenters, but it is common that PREVIEW services aren't deployed globally until they're out of PREVIEW status.
If the problem you are looking to remediate is latency-based, look into the CDN suggestion in my "Quick Answer."
If your issue is about getting different pricing based on your location, the location of the datacenter you choose will not affect this. If geographic-discounting applies to you, it is based on the country that is assigned to your Microsoft Username/Password combination at the time it was created. This value cannot be changed once a username/password combo has been created, and consequently, any payment info used along with this uname/pass will need to have a billing address in the same country.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible combine columns in MySQL in a top down format? I am trying to get the largest datetime between 2 columns on different tables, to compare it against another column in a separate table.
I eventually came across the SQL concat(), but realised that it is more for use cases like concatenating names together.
Just wondering if it would be possible for concat() to return a result as follows below, that allows me to call the newly combined column to compare against the third column.

Col 1
Col 2

no1.1
no2.1

no1.2
no2.2

Combined Columns Result (End Goal)

no1.1

no1.2

no2.1

no2.2

Instead of the normal concat() function where it just ends up being
| Combined Columns Result |
|:-:|
|no1.1 no2.1|
|no1.2 no2.2|

A: Use a union with a computed column to maintain the order of each column:
SELECT col
FROM
(
    SELECT col1 AS col, 1 AS src FROM yourTable
    UNION ALL
    SELECT col2, 2 FROM yourTable
) t
ORDER BY src, col;


text:
Q: resharper custom pattern replacement with negative equality expression I have a rule in resharper to find calls to Nullable.HasValue
T? foo;
//...

if(foo.HasValue)
{}

//And it offers to replace with a comparison directly with null:

if(foo != null)
{}

This works great, but when it encounters a negated .HasValue, the result is a little strange.
if(!foo.HasValue) {}

//is replaced with
if(!(foo != null)) {}

Then resharper wants me to simplify the statement to just if(foo == null)
//ideally it would automatically get to this without the extra step:
if(foo == null) {}

The rule is defined as:
type:     System.ValueType or derived
nullable: expression of type System.Nullable<$type$>

search pattern:
$nullable$.HasValue

replace pattern:
$nullable$ != null

('Format after replace' and 'Shorten references' are both checked)
Is there a way I can write this rule so ReSharper handles it intelligently?  I tried making a second rule for !$nullable$.HasValue, but that causes both rules to match which makes tool-tip suggestions look confusing: replace with == null and replace with != null.

A: If is not really mandatory you can give up on this rule because, according to this post:
"The compiler replaces null comparisons with a call to HasValue, so there is no real difference. Just do whichever is more readable/makes more sense to you and your colleagues."


text:
Q: How to get promises to work in IE10 with react I am trying to fetch data using promise in my react application. I installed and implemented this polyfill es6-promise but works for IE11 on window 8 but IE10 window 7 is says 'promise are undefined'. I assumed the polyfill is meant to cover all IE9+, but it is just not working for me. Has anyone come across this problem? Am I missing something in the implementation of the es6-promise polyfill with webpack??
// calling it my jsx file

    import React, { PropTypes } from 'react';
    import es6promise from 'es6-promise'; // not sure if I need this in the jsx file also??
    promise.polyfill();
    import 'isomorphic-fetch';
    class App extends React.Component {
      ...
    }
    App.propTypes = propTypes;

    export default App;

webpack.config.js
var promise = require('es6-promise').polyfill();
switch (TARGET) {
    case 'build':
        module.exports = mergeConfig({
            plugins: [
                // Reference: http://webpack.github.io/docs/list-of-plugins.html#uglifyjsplugin
                // Minify all javascript. Loaders are switched into minimizing mode
                new webpack.optimize.UglifyJsPlugin({
                    compress: {
                        warnings: false
                    }
                }),
                new webpack.DefinePlugin({
                    'process.env': {
                        // This has effect on the react lib size
                        'NODE_ENV': JSON.stringify('production')
                    }
                }),
                new webpack.ProvidePlugin({
                    PROMISE: promise
                })
            ]
        });

        break;

A: You can try babel-polyfill.
After install it as dependency.
Import it in your app.js
import 'babel-polyfill';

A: I have an another interesting solution (it works for me in that case). I didn't want to import a polyfill into every file so I provided via WebpackProvidePlugin.
    new webpack.ProvidePlugin({

        "Promise": "babel-polyfill",
        'fetch': 'imports-loader?this=>global!exports-loader?
                  global.fetch!whatwg-fetch'
    })

So now I can use these stuff without importing into every file. And a very important note. Some resources are suggesting to use  es6-promise instead babel-polyfill, I tried to use it but it doesn't work for me. Looks like es6-promise-polyfill didn't work in case of using webpack + babel. So I switched to the babel-polyfill. Tested in the IE11 and all is fine.
Hope it helps.
Best Regard. Velidan.

A: I recommend using the native-promise-polyfill npm module, especially if you don't need the other features babel-polyfill includes:

This means you can use new built-ins like Promise or WeakMap, static methods like Array.from or Object.assign, instance methods like Array.prototype.includes, and generator functions


text:
Q: Linux: cat to named pipe in a python script I have a Java program that uses video from a framegrabber card. This program is launched through a python launcher.py.
The easiest way to read the video stream I found, is to make Java read on a named pipe, and this works perfectly. So my session is like:
$ mkfifo videopipe
$ cat /dev/video1>videopipe

and in a second terminal (since the cat command is blocking):
$ python launcher.py

I would like to automate this process. Unfortunately, the result is always the same: the Java application starts (confirmed through a print statement in the java program), but then the terminal stalls and nothing appears, exception or else.
Since this process works manually, I guess I am doing something wrong in the python program. To simplify things, I isolated the piping part:
from subprocess import call, Popen, PIPE, check_call

BASH_SWITCHTO_WINTV = ['v4l2-ctl', '-d /dev/video1', '-i 2', '--set-standard=4']
BASH_CREATE_FIFO_PIPE = ['mkfifo', 'videopipe']
BASH_PIPE_VIDEO = 'cat /dev/video1>videopipe'

def run():
    try:
        print('running bash commands...')
        call(BASH_SWITCHTO_WINTV)
        call(BASH_CREATE_FIFO_PIPE)
        Popen(['cat', '/dev/video1'], stdout=open('videopipe', 'w'))
    except:
        raise RuntimeError('An error occured while piping the video')

if __name__ == '__main__':
    run()

which when run, outputs:
running bash commands...
Failed to open  /dev/video1: No such file or directory

A little help would be very much appreciated :-)

A: If you're using shell=True, just pass a string:
BASH_PIPE_VIDEO = 'cat /dev/video1 > videopipe'

Currently, cat is passed to the shell as your script, and /dev/video>videopipe is passed to that shell as a literal argument -- not parsed as part of the script text at all, and having no effect since the script (just calling cat) doesn't look at its arguments.

Alternately, to avoid needless shell use (and thus shell-related bugs such as shellshock, and potential for injection attacks if you were accepting any argument from a non-hardcoded source):
Popen(['cat', '/dev/video1'], stdout=open('videopipe, 'w'))

On a note unrelated to your "cat to named pipe" question -- be sure you get your spaces correct.
BASH_SWITCHTO_WINTV = ['v4l2-ctl', '-d /dev/video1', ...]

...uses the name <space>/dev/video1, with a leading space, as the input device; it's the same as running v4l2-ctl "-d /dev/video1" in shell, which would cause the same problem.
Be sure that you split your arguments correctly:
BASH_SWITCHTO_WINTV = ['v4l2-ctl', '-d', '/dev/video1', ...]


text:
Q: Is there an expression to describe a situation where someone could have helped you but they didn't? I would like to know if there is an expression that describes a situation where someone, perhaps your friend, was capable of helping you but they didn't or they chose not to?
Eg: He was was free. He could have come over and consoled me. But he __________________ [didn't help despite the fact that he could].
An expression or a proverb applicable in this situation will do.

A: But he 'passed by on the other side'.
This idiom refers to the parable of the Good Samaritan, where certain chose to leave the wounded victim lying on the road, passing by on the other side.

To ignore or avoid someone who is in need of assistance. We as a people cannot continue to pass by on the other side as thousands of our fellow citizens are left on the streets in poverty.

Free Dictionary

A: "He could have come over and consoled me, but his behavior was omissive."

*

*"characterized by omissions" -  TFD

*"failing or neglecting to do" - MW

*

*Whenever there is a question about omissive or comissive behavior by an employee or an agency, an investigator's first move is to check the personnel files for ...

"He could have come over and consoled me, but he turned a blind eye to my problems."

*

*"to ignore something and pretend you do not see it" - TFD

"There's so much suffering in the world, you can't just turn a blind eye to it."
"She chose to turn a blind eye to what she suspected was going on."


text:
Q: Combining 3 datasets with a lot of columns (+100), no overlapping rows, and some unknown overlapping columns I have 3 datasets with varying rows and columns. In the end result all rows should be there, and all non-overlapping (unique) columns should be there.
a <- data.frame(a=c(0,1,2), b=c(3,4,5), c=c(6,7,8))
b <- data.frame(a=c(9,10,11), c=c(12,13,14), d=c(15,16,17))

Needs to be
c <- data.frame(a=c(0,1,2,9,10,11), b=c(3,4,5,NA,NA,NA), c=c(6,7,8,12,13,14), d=c(NA,NA,NA,15,16,17)

But imagine that instead of having abcd, you have the whole alphabet 4 times. (edit: and you don't know which ones are overlapping names (such as a and a in a and b are overlapping)).

A: The default behavior of all the dplyr join commands is to join on all columns that both datasets have in common. As you want to keep all values, even when there is nothing to join on then you will want an outer join.
Probably something like the following:
output = input_df1 %>%
  dplyr::outer_join(input_df2) %>%
  dplyr::outer_join(input_df3)

This will begin by joining the first two dataframes using all columns they have in common. Then it will join on the third dataframe using all columns in common.
This assumes that wherever dataframes have the same columns they have the same entries. Consider the following example:
df1:
 a | b | z
---+---+---
 1 | NA| 7

df2:
 a | b | Y
---+---+---
 1 | 2 | 8

df1:
 a | b | X
---+---+---
 1 | 2 | 9

This will not produce
output:
 a | b | z | y | x
---+---+---+---+---
 1 | 2 | 7 | 8 | 9

Because the first table does not have the same b value, even though it has the same a value. Instead this will produce:
output:
 a | b | z | y | x
---+---+---+---+---
 1 | 2 | NA| 8 | 9
 1 | NA| 7 | NA| NA

It you need to handle this type of case, you will have to put more effort into your joins. Perhaps start with:
colnames1 = colnames(input_df1)
colnames2 = colnames(input_df2)

common_colnames = colnames1[colnames1 %in% colnames2]

To get all common column names and decide from there how to join.


text:
Q: Why can't I declare an enum inheriting from Byte but I can from byte? If I declare an enum like this ...
public enum MyEnum : byte {
    Val1,
    Val2
}

... it's working.
If I declare an enum like this ...
public enum MyEnum : System.Byte {
    Val1,
    Val2
}

... it's not working. The compiler throw :

error CS1008: Type byte, sbyte, short, ushort, int, uint, long, or ulong expected

As byte is an alias to the actual type, System.Byte, why can't I use the second declaration ?

A: Just for information:
With new compiler Roslyn this code
enum SomeEnum : System.Int32
{
    None,
    Some
}

is valid, so, now for enum base types can be used not only aliases, but full types.
Sample on dotnetfiddle, where you can select compiler: https://dotnetfiddle.net/oXyAgV

A: There are a number of questions raised here.

Why can't I declare an enum inheriting from Byte but I can from byte?

As others have noted, that is what the specification says.
The language design committee notes do not justify this decision. The notes from June of 2000 say

The keywords for the predefined types (e.g., int) and their corresponding type names (e.g., Int32) can mostly but not entirely be used interchangeably.  We discussed whether we wanted to make any changes in this area.  We didn't.
Here is the list of places where they are not interchangeable.

*

*"int" can be used as an underlying type for enums; Int32 can't.

*Alias declarations can't use keywords.

Some musings of mine on the subject:
The first thing that comes to mind is that every time you give a user a choice, you give them an opportunity to write a bug, and every time you give them an opportunity to write a bug you have to make an error message for it. If we allowed "enum X : Byte" then we have give a sensible error message when the user has accidentally erased the "using System;". We can avoid that potential confusion and all the costs of developing and testing an error-reporting heuristic by simply not allowing the choice in the first place.
The second thing that comes to mind is that the underlying type of an enum is fundamentally about the mechanism of the enum, not its meaning. It therefore seems plausible that the underlying type clause should be limited to things that require no semantic analysis; we know that the underlying type is one of eight possible types, so let's just have the user mechanically choose from one of those eight types unambiguously.
The third thing that comes to mind is that the error analysis can be performed during syntactic analysis rather than semantic analysis. The earlier the error is caught, the better.
UPDATE: I just asked one of the people who was in the room that day whether there was anything that I missed in my musings and he said that yeah, they thought about it and decided that doing the full type analysis was work for the development, test and maintenance team, work which bought the user nothing of value. (He also noted that they had similar arguments over System.Void; should it be legal to say "public static System.Void Main(string[] args)" for example?  Again, they decided that this added no value for users but did add potential ambiguity and work for the team.)

Why is "char" not a legal underlying type?

Again, that's what the spec says. Again, the language design notes from October 1999 are no help in determining why:

The unsigned integral types may be used as the underlying types for enums.  The only integral type that cannot be used is char.

Again, we can guess. My guess would be that enums are intended to be fancy numbers. Chars are in practice integers as an implementation detail, but logically they are not numbers, they are characters.  We want to be able to do operations on enums like addition, "or-ing" and "and-ing" flags, and so on; the spec is clear that these operations are done as though they were being done on the underlying type. The char type, not logically being a number, does not define all the operators you might want. And finally, if you want a two-byte enum value then you already have short and ushort at your disposal.

A related question from an email about this question:

A careful reading of the grammar specification says that 'char' is grammatically a legal underlying type, but the paragraph of explanatory text after the grammar says that 'char' is not a legal underlying type. Is the spec inconsistent?

Yes. I'm not losing sleep over it. If it makes you feel better, imagine that the grammar line that says
enum-base : integral-type
instead reads
enum-base : integral-type (but not char)

A: Well, it's according to the specification (§14.1). The grammar specifies that the production for enum-declaration is
enum-declaration:
    attributes_opt   enum-modifiers_opt   enum   identifier   enum-base_opt   enum-body   ;_opt

where
enum-base is
:integral-type

and
integral-type:
sbyte
byte
short
ushort
int
uint
long
ulong
char

As for the why the specification is this way, it is not clear.
Note that char is listed as a terminal for integral-type but the specification explicitly states that

Note that char cannot be used as an underlying type.

By the way, I really think best practice here is to use the aliases. I only use the .NET name instead of the C# keyword for these primitive types (and string) when I want to invoke a static method. So
Int32.TryParse

instead of
int.TryParse.

Otherwise, I say, e.g., typeof(int) and not typeof(Int32).

A: Here is the answer, at least partially, from MSDN:

Every enumeration type has an
underlying type, which can be any
integral type except char. The default
underlying type of enumeration
elements is int. To declare an enum of
another integral type, such as byte,
use a colon after the identifier
followed by the type, as shown in the
following example.
Copyenum Days : byte {Sat=1, Sun, Mon,
Tue, Wed, Thu, Fri};
The approved
types for an enum are byte, sbyte,
short, ushort, int, uint, long, or
ulong.

A: The simplest answer is "that's just the way it's specified." (It's in section 14.1 of the C# 4 spec. Numbering may vary for other versions.)
The spec doesn't give any particular reason for this1, but it's arguably easier to describe the integral type alias names (which are all keywords) than to say it can be any type which resolves (via other type aliasing such as using directives) to one of a particular set.
Do you have any reason for wanting to use System.Byte instead?

1 The annotated C# 4 spec does have one annotation in this section... but it was written by me, and just points out that this is one of the few places in the spec where you really can't replace the aliases with normal type names. So not very helpful for this question :)

A: Looks like it does not accept actual type names, but language keywords only.


text:
Q: Add a tinymce editor dynamically when you already have tinymce instances on your page This is a followup to this question i already asked : Add a tinymce editor dynamically
I have a page with editors in it (tinyMCE). I add textarea dynamically (an add entry button). It works fine expect that it undo all change i have done to other TinyMCE. If i loaded a page with a tinyMCE displaying "Something 40" and i typed "Something 40 and some stuff", and then i click to add an entry, a new tinymce appear but the first one now display "Something 40".
I use the following code :
<script type="text/javascript">
//<![CDATA[
tinyMCE.init({"selector":"textarea.tinymce","theme_advanced_toolbar_location":"top","theme_advanced_toolbar_align":"left","theme_advanced_statusbar_location":"bottom","theme_advanced_buttons3_add":"tablecontrols,fullscreen","toolbar":"insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image","plugins":"paste,table,fullscreen,image,code,link","dialog_type":"modal","content_css":"/assets/application.css"});
//]]>
</script>
<script>
function loadTinyMCEEditor() {
tinyMCE.init({"selector":"textarea.tinymce","theme_advanced_toolbar_location":"top","theme_advanced_toolbar_align":"left","theme_advanced_statusbar_location":"bottom","theme_advanced_buttons3_add":"tablecontrols,fullscreen","toolbar":"insertfile undo redo | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image","plugins":"paste,table,fullscreen,image,code,link","dialog_type":"modal","content_css":"/assets/application.css"});
}
</script>

Both are the same options to add a tiny MCE, the first is for the textarea i want to display as editor at page display, the second is in a function to be called when i add a textarea dynamically.
Here is how i add tinyMCE to nex textarea :
$(document).on 'nested:fieldAdded', (event) ->
  loadTinyMCEEditor()
  #alert "azeaze"+event.field.attr("id")
  #alert "totoooot "+event.field.find('textarea').attr("id")
  tinyMCE.execCommand "mceAddControl", true, event.field.find('textarea').attr("id")

How can i add a tinyMCE without erasing the changes of other TinyMCE fields?

A: You can use :
tinymce.EditorManager.execCommand('mceAddEditor', true, "here_place_editor_class or ID");

Also you need to generate this selection ID dynamically if you want to use ID and each editor instance to be unique.


text:
Q: Convert Stream> to Stream> I have a requirement of converting Stream<List<T>> to Stream<Map<K,T>>
I have a class
class Order
{
    int id;
    DateTime date;
}

I want to convert Stream<List<Order>> to Stream<Map<DateTime, List<Order>>
I want to display orders as below
12-Dec-2020
         Order 1
         Order 2

13-Dec-2020
         Order 3
         Order 4

14-Dec-2020
         Order 5
         Order 6

Suggestions for a better DS are welcome.
How do I do this?
Please suggest.
Thanks in advance.

A: Using groupListsBy from collection: ^1.15.0
K keySelector(T t) { ... }

final Stream<List<T>> source$ = ...;
final Stream<Map<K, List<T>>> result$ = source$.map((list) => list.groupListsBy(keySelector));

A: You can do this without any package.
First, you have to create an empty Map, then map a List<Order> to a map with a key as a date from the list item (single order) then add it to That Empty map.
Check if the date is available as a key in Map. If the date exists as a key in that map then simply add a new order to that value or else simply add a new key to the Map.
Code:
Stream<List<Order>> orders = ...;

Stream<Map<DateTime, List<Order>>> ordersByDate = {};

orders.forEach((Order order){
    ordersByDate.keys.contains(order.date)
      ? ordersByDate.update(order.date, (oldValue) => oldValue + <Order>[order])
      : ordersByDate[order.date] = [order];
});

print(ordersByDate);

//At here your ordersByDate

Let me know if it works for you.

A: Fold method is what you're looking for.
Example:
void main() async {
  final today = DateTime.now();
  final tomorrow = today.add(const Duration(days: 1));
  final order1 = Order(1, today);
  final order2 = Order(2, today);
  final order3 = Order(3, tomorrow);

  final x = await Stream
    .fromIterable([order1, order2, order3])
    .fold<Map<DateTime, List<Order>>>({}, (val, element)  {
      (val[element.date] ??= []).add(element);

      // Same as:
      // if (val[element.date] == null) {
      //   val[element.date] = [];
      // }
      // val[element.date]!.add(element);

      return val;
    });

  print(x);
}

class Order
{
    int id;
    DateTime date;

    Order(this.id, this.date);

    @override
    String toString() {
      return 'Order(id: $id, date: $date)';
    }
}


text:
Q: Mongodb insert lines from growing csv file in collection I am trying to read a comma seperated CSV file and load into mongodb collection. The CSV file is continuously growing (adding new lines at end) with very high rate, lets say ~100 lines per seconds where line size is approximate 200 characters. It is ok if the operation is asynchronous but should not lock the file for any reason. My CSV file will be something like,
A001,John,male,20,Y
A002,Peter,male,22,N
A003,Mary,female,20,N,
A004,Katy,female,21,Y

And I want to insert in collection with fixed field names like,
db.test20sep.insert({
  id:"A001",
  name: "John",
  sex: "male",
  age: 20,
  present:"Y"
})

Please suggest me most efficient approach. Please note, i also have to make live dashboad based on this collection's data so there multiple quereis shall be firing on collection.
Many thanks in advance.


text:
Q: Why do Unicode emoji property escapes match numbers? I found this awesome way to detect emojis using a regex that doesn't use "huge magic ranges" by using a Unicode property escape:

console.log(/\p{Emoji}/u.test('flowers ')) // true
console.log(/\p{Emoji}/u.test('flowers')) // false

But when I shared this knowledge in this answer, @Bronzdragon noticed that \p{Emoji} also matches numbers! Why is that? Numbers are not emojis?

console.log(/\p{Emoji}/u.test('flowers 123')) // unexpectdly true

// regex-only workaround by @Bonzdragon
const regex = /(?=\p{Emoji})(?!\p{Number})/u;
console.log(
  regex.test('flowers'), // false, as expected
  regex.test('flowers 123'), // false, as expected
  regex.test('flowers 123 '), // true, as expected
  regex.test('flowers '), // true, as expected
)

// more readable workaround
const hasEmoji = str => {
  const nbEmojiOrNumber = (str.match(/\p{Emoji}/gu) || []).length;
  const nbNumber = (str.match(/\p{Number}/gu) || []).length;
  return nbEmojiOrNumber > nbNumber;
}
console.log(
  hasEmoji('flowers'), // false, as expected
  hasEmoji('flowers 123'), // false, as expected
  hasEmoji('flowers 123 '), // true, as expected
  hasEmoji('flowers '), // true, as expected
)

A: According to this post, digtis, #, *, ZWJ and some more chars contain the Emoji property set to Yes, which means digits are considered valid emoji chars:
0023          ; Emoji_Component      #  1.1  [1] (#)       number sign
002A          ; Emoji_Component      #  1.1  [1] (*)       asterisk
0030..0039    ; Emoji_Component      #  1.1 [10] (0..9)    digit zero..digit nine
200D          ; Emoji_Component      #  1.1  [1] ()        zero width joiner
20E3          ; Emoji_Component      #  3.0  [1] (⃣)       combining enclosing keycap
FE0F          ; Emoji_Component      #  3.2  [1] ()        VARIATION SELECTOR-16
1F1E6..1F1FF  ; Emoji_Component      #  6.0 [26] (..)    regional indicator symbol letter a..regional indicator symbol letter z
1F3FB..1F3FF  ; Emoji_Component      #  8.0  [5] (..)    light skin tone..dark skin tone
1F9B0..1F9B3  ; Emoji_Component      # 11.0  [4] (..)    red-haired..white-haired
E0020..E007F  ; Emoji_Component      #  3.1 [96] (..)      tag space..cancel tag

For example, 1 is a digit, but it becomes an emoji when combined with U+FE0F and U+20E3 chars: 1⃣:

console.log("1\uFE0F\u20E3 2\uFE0F\u20E3 3\uFE0F\u20E3 4\uFE0F\u20E3 5\uFE0F\u20E3 6\uFE0F\u20E3 7\uFE0F\u20E3 8\uFE0F\u20E3 9\uFE0F\u20E3 0\uFE0F\u20E3")

If you want to avoid matching digits, use Extended_Pictographic Unicode category class:

The Extended_Pictographic characters contain all the Emoji characters except for some Emoji_Components.

So, you may use either /\p{Extended_Pictographic}/gu to most emojis proper, or /\p{Extended_Pictographic}/u to test for a single emoji proper, or use /[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}]/u to match emojis proper and light skin to dark skin mode chars and red-haired to white-haired chars:

const regex_emoji = /[\p{Extended_Pictographic}\u{1F3FB}-\u{1F3FF}\u{1F9B0}-\u{1F9B3}]/u;
console.log( regex_emoji.test('flowers 123') );     // => false
console.log( regex_emoji.test('flowers ') ); // => true


text:
Q: Possible causes of duplicate requests to Signal-R hub (different ConnnectionIDs) Our web-application is exhibiting an issue whereby we're seeing duplicate requests from a single user action (all details except ConnectionId are the same) in our Signal-R hub.
Assuming the first request was received at T0 then we saw duplicate requests at (approximately)

*

*T0 + 2:00

*T0 + 2:30

*T0 + 3:30

*T0 + 8:00

Effectively, the client-side JavaScript code sets up a connection to a Signal-R hub, when the user clicks the submit button it invokes a method on the hub (kicks off procesing in the back-end).
The problem has only started recently in production - we haven't changed any relevant code (client-side nor SignalR hub). The web-app is deployed in a corporate environment (users use IE11 via Citrix). I note that (presumably due to firewalls) SignalR is using forever-frames (rather than web-sockets etc).
In our logs (from the Signnal-R hub) the user-agent appears as Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/7.0; SLCC2; .NET CLR 2.0.50727; .NET4.0C; .NET4.0E; .NET CLR 3.5.30729; .NET CLR 3.0.30729; InfoPath.3)
The client code looks along the lines of
// Setup
self.myHub = $.connection.myHub;
$.connection.hub.start().done(function () {
    console.debug("SignalR Hub Connected");
});
...
// When handling user action
self.myHub.server.someHubMethod(param1, param2);

Basically, I'm stumped as to what is going on / where I should be looking. My thoughts are that there is some caching proxy/web accelerator/spider or similar which is somehow replaying the requests.


text:
Q: Mid 2010 Mac Pro with no video card; will it run with new HDDs? I have a Mid 2010 Mac Pro that was once my main computer; however, when the graphics card failed and I couldn't find a replacement that the Mac would take I had to replace the computer.  I still have the Mac and am considering re-purposing it as a file server.  If I install new HDDs (I salvaged the old HDDs for the replacement computer), would the Mac run even without a video card?  Thanks!
CLARIFICATION: Since I would be using new HDDs, OS X would not yet be installed on those HDDs.

A: I have 2 mid 2010 MacPros and have been able to run both without a GPU. If you can load OSX with screensharing turned on onto a drive using another Mac in Target Disk mode you should be able to plug that drive in and boot it up.
I have this running as a media and file server and it works great. Also cuts back on the heat as I loaded my pro up with 6 HDDs (4 in the trays and 2 using the OWC 3.5 adaptor in the CD Drive space). Set up an SSD via a PCIe adaptor for OSx. It works perfectly.

A: This will work.  I have a 2010 MacPro running Mojave (I had a RX 560 in it).  I wanted to use the MacPro as a full time Plex server but reuse the card elsewhere.  I pulled the card and it booted fine the very first time and I was able to access Plex, VNC to the box, see file shares, etc.
The only thing I would add is that it seems to have a small timeout before booting without a card (maybe 30 or 60 seconds) as it seems like the it takes about a minute longer before the Plex services come online after a cold boot.

A: Based on the comments so far, I'm going to hazard a guess that no, it isn't possible to run the Mac with no video card - at least in my scenario.  I'd love to be proved wrong, but it is looking at this point like I will have to end up buying a video card.

A: I think you can do this as long as you have access to another Mac with firewire support. Once you put a new drive in the Mac Pro, plug in a usb keyboard and hold down the "t" key while you turn it on and it powers up. This should put the Mac Pro into target disk mode. Connect it via firewire to the secondary Mac. Press and hold the option key while you power it on. This should allow you to select the Mac Pro as your startup disk. Initiate the installation using the secondary Mac.


text:
Q: Hadoop can't find joda dependency I've tried to write a mapreduce app that takes input from a CSV file and aggregates rollover interest per account. I've passed my MRunit tests and everything seems to check out. When I try to run the jar file on my machine (I'm running Hadoop locally), the following error comes up
..........>>
14/07/16 09:09:05 INFO mapred.MapTask: Starting flush of map output
14/07/16 09:09:05 INFO mapred.LocalJobRunner: map task executor complete.
14/07/16 09:09:05 WARN mapred.LocalJobRunner: job_local1566570594_0001
java.lang.Exception: java.lang.NoClassDefFoundError: org/joda/time/ReadableInstant
    at org.apache.hadoop.mapred.LocalJobRunner$Job.runTasks(LocalJobRunner.java:462)
    at org.apache.hadoop.mapred.LocalJobRunner$Job.run(LocalJobRunner.java:522)
Caused by: java.lang.NoClassDefFoundError: org/joda/time/ReadableInstant
    at org.mrIntCalc.CalcInterestMapper.map(CalcInterestMapper.java:38)
    at org.mrIntCalc.CalcInterestMapper.map(CalcInterestMapper.java:12)
    at org.apache.hadoop.mapreduce.Mapper.run(Mapper.java:145)
    at org.apache.hadoop.mapred.MapTask.runNewMapper(MapTask.java:764)
    at org.apache.hadoop.mapred.MapTask.run(MapTask.java:340)
    at org.apache.hadoop.mapred.LocalJobRunner$Job$MapTaskRunnable.run(LocalJobRunner.java:243)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:471)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassNotFoundException: org.joda.time.ReadableInstant
    at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
    ... 11 more
14/07/16 09:09:05 INFO mapreduce.Job: Job job_local1566570594_0001 running in uber mode : false
14/07/16 09:09:05 INFO mapreduce.Job:  map 0% reduce 0%
14/07/16 09:09:05 INFO mapreduce.Job: Job job_local1566570594_0001 failed with state FAILED due to: NA
14/07/16 09:09:05 INFO mapreduce.Job: Counters: 0

I built the app using maven, so joda(v2.3) is listed as a dependency in the pom.xml. Like I said, my unit tests came out all clear. Looking up this issue, I see that some people mention there's a classpath issue at the root of this, although I don't think that's quite it. Any thoughts?

A: Copied the joda-time.jar to a hadoop common library. Probably not the best solution, but at least it works.

A: Check whether  joda-time*.jar exists in your classpath/buildpath
If it is not mentioned, add it.
Else, copy that jar into your lib directory and add it into your classpath.


text:
Q: Broken image and css on AWS Cloudfront Custom Error Page i'm having problem with setting up cloudfront custom error pages for our site.
yes, the custom error pages works. but css and images are all broken.
i follow exactly what this link tells me to do From better engineering site
for us to do an actual test, we temporarily disable the apache service in ec2 server
so the site will be redirected to the custom error page (uploaded in our s3 bucket).
the custom error page works, but not sure the css and image is broken.
anyone, have this same problem before?
thank you in advance for your help

A: A workaround to fixed the broken image and css, is by merging it to 1 html only.
instead of having 3 separate files (1 for html, 1 for css, and 1 image), what i did is combine them as 1 html. so instead of referencing css file i just use , and convert the image to base64.
the cons, is the html rows will be more longer. but it works!


text: Q: Javascript and HTML bad DOM trees This is more of a conceptual question than a coding problem. HTML5 is very robust in the sense that it will still render your page if you're missing tags or attributes (ie. missing body tags) but will it still parse a DOM tree? If so, our DOM tree is "incorrect" but our page still renders. What're the consequences of having a bad DOM tree?


text:
Q: Opencart  tag do not show site name on new controller I've created a new controller along with new template and language model to display custom registration page for new user
The problem is that the page title for new controller is not displaying site name. For example opencart default registration page title would be "Register Account - [SITE_NAME]" but my new controller displays only "Register User" without the site name
Sure that I can just place site name on language model but that doesn't feel right
I've tried to trace the problem using FirePHP on setTitle function of document class, like this:
public function setTitle($title) {
global $firephp;
$firephp->log($title, 'c:document');
$this->title = $title;
}

But I'm still unable to solve the problem.
Please help.
Thanks.

A: If you are wanting to add the site name to the store's titles site wide, there's  a simple little trick you can employ to get this done. Open system/library/document.php and find the following code
$this->title = $title;

After this line, put
global $config;
if($this->title != $config->get('config_title')) $this->title .= ' - ' . $config->get('config_title');

This will make all title's have Page Title - Site Name except for pages where the title is simply the Site name

A: From all the code I have checked I am almost sure that the site name is not added to the document title (except the homepage)...
So if You see a site name in the title at Register Account page, it is kinda strange...
The controllers have code like
$this->document->setTitle($this->language->get('heading_title'));

This mean - only the string that is present in the language file is set as the page title.
Also, from the Document class:
public function setTitle($title) {
    $this->title = $title;
}

public function getTitle() {
    return $this->title;
}

means that only what comes to the Document class is the returned back, no site name is added anywhere...
What OC version are You using? What browser are You viewing Your site through? This could also be a browser thing...


text:
Q: Replace all spaces to dash in all my "url" object from my article model I would like to replace all the spaces in my defined url objects from my Article model to "-". However, my code below doesn't seem to work.
def index(request):
    change_urls = Article.objects.all()
    for i in change_urls:
        i.url.replace(" ", "-")
        i.save()

A: .replace(..) creates a new string, it does not modify the string. You can thus work with:
def index(request):
    change_urls = list(Article.objects.all())
    for i in change_urls:
        i.url = i.url.replace(' ', '-')
    Article.objects.bulk_update(change_urls, fields=('url',))
    # …
But if you want to "slugify", please use the slugify(…) function [Django-doc].


text:
Q: Making headings that have interesting formatting readable by screen readers Say you want to stylise some heading tags to make them "01_Hosting" instead of "1. Hosting", how do you make this accessible to screen readers?
Take the snippet:

04_Hosting

speedy

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

With styling like:

I initially thought to do

04_Hosting

but afaik aria-label is meant for interactive elements only. I also tried it with my screen reader (Orca) and it ignored the label.

A: It's probably not a good idea to tell the numbers to screen reader users as the heading number will be read out as well, and the number is not likely to be hugely relevant.
If it is really important you can do

  04_
  Hosting

Otherwise, this can probably be solved simply with

04_Hosting

A:
04_Hosting

4. Hosting

.sr-only {
  height: 1px;
  width: 1px;
  position: absolute;
  overflow: hidden;
  top: -10px;
}

Seems like a possible solution inspired by https://www.w3.org/TR/2012/NOTE-WCAG20-TECHS-20120103/C7
However, this seems to be bad practice as I get the warning

A11y: h2 element should not be hidden | svelte(a11y-hidden)


text:
Q: `Error: org.json.JSONException` for json parsing using volley I am trying to fetch json data using volley from google api. I am getting Error: org.json.JSONException in logcat. How do i solve it?
my Google Api url,
private String urlJsonObj = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=21.2150756,72.8880545&radius=500&type=hospital&key=AIzaSyBldIefF25dfjjtMZq1hjUxrj4T4hK66Mg";

makeJsonObjectRequest function for to fetch the data,
private void makeJsonObjectRequest() {
showpDialog();

// Creating volley request obj
JsonArrayRequest jsonObjReq = new JsonArrayRequest(urlJsonObj,
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());
                hidepDialog();

                try {
                    JSONArray results = response.getJSONArray(1);
                    // Parsing json
                    for (int i = 0; i < results.length(); i++) {
                        try {
                            JSONObject obj = results.getJSONObject(i);
                            LocationDetailModel locationDet = new LocationDetailModel();
                            locationDet.setTitle(obj.getString("name"));
                            locationDet.setThumbnailUrl(obj.getString("vicinity"));

                            LocationDetailList.add(locationDet);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    // notifying list adapter about data changes
                    // so that it renders the list view with updated data
                    adapter.notifyDataSetChanged();
                } catch (JSONException e) {
                    Log.e("MYAPP", "unexpected JSON exception", e);
                    // Do something to recover ... or kill the app.
                }

            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.d( "VolleyError","Error: " + error.getMessage());
        VolleyLog.d(TAG, "Error: " + error.getMessage());
        hidepDialog();

    }
});

// Adding request to request queue
AppController.getInstance().addToRequestQueue(jsonObjReq);

}
I am getting bellow error in my logcat,
04-19 12:56:25.348 4485-4485/com.example.chaitanya.nearbyplace D/VolleyError: Error: org.json.JSONException: Value {"html_attributions":[],"results":[{"geometry":{"location":{"lat":21.21508679999999,"lng":72.8883554},"viewport":{"northeast":{"lat":21.2164357802915,"lng":72.8897043802915},"southwest":{"lat":21.21373781970849,"lng":72.88700641970848}}},"icon":"https:\/\/maps.gstatic.com\/mapfiles\/place_api\/icons\/doctor-71.png","id":"831a38ee464657c1b60683be963e145b566e95d1","name":"Deep Children Hospital","place_id":"ChIJE1cZjXpP4DsR1ITMcESvDeU","rating":4.2,"reference":"CmRSAAAApsEU5Kvy3RIGkxaQklHK-Jr700tF_DGu4JAEAEibQ-lVZQApAddzMtONETVQihcJ1MYooX0k5QRphjsplHb6xgALmefjoHiAc-O3N08_S5blHqRKVZogOeNCe6urVEaaEhAfVhJbsQvCY2dKrl5j8CfdGhSCsQtU2BuIGkWvMgRzVwf4oYziSQ","scope":"GOOGLE","types":["hospital","point_of_interest","establishment"],"vicinity":"302-305, Swastik Plaza, Pune- Simada Road, Yogi Chowk, Yogidarshan Society, Nana Varachha, Surat"},{"geometry":{"location":{"lat":21.2149842,"lng":72.8883906},"viewport":{"northeast":{"lat":21.2163331802915,"lng":72.88973958029149},"southwest":{"lat":21.2136352197085,"lng":72.88704161970848}}},"icon":"https:\/\/maps.gstatic.com\/mapfiles\/place_api\/icons\/doctor-71.png","id":"e62d17d2eaba8c7af64144418c845476837d0610","name":"Chirayu General Hospital","opening_hours":{"open_now":true,"weekday_text":[]},"place_id":"ChIJI_rAjHpP4DsRVfNqHtl8s24","reference":"CmRRAAAA6Sr99xxP0-2xzTjFP-ajIfr63ZtMMVCyz4xtAuV3y6CxvlsyQRUp5Lx35uc7-Ir7jafjCJPPQ0XBCy28QSqj8drtgZqhu-Pk6MAz--jG4RjdwdL1WQGzu3Pf_SEMIJMBEhBXQCMOtyY01AkUfLNSNe-rGhSjLdu_AbeYiW5cTp3xQbaYDsAO7A","scope":"GOOGLE","types":["hospital","point_of_interest","establishment"],"vicinity":"402-406 Swastik Plaza, Puna-Simada Road, Yogi Chowk Ground, Chikuwadi, Nana Varachha, Surat"},{"geometry":{"location":{"lat":21.213784,"lng":72.88569799999999},"viewport":{"northeast":{"lat":21.2151329802915,"lng":72.8870469802915},"southwest":{"lat":21.2124350197085,"lng":72.8843490197085}}},"icon":"https:\/\/maps.gstatic.com\/mapfiles\/place_api\/icons\/doctor-71.png","id":"c4290cb09a3be448718cd65ebc9a62c90799c2aa","name":"Vaghani Hospital","photos":[{"height":794,"html_attributions":["<a href=\"https:\/\/maps.google.com\/maps\/contrib\/103410682498224690153\/photos\">Vaghani Hospital<\/a>"],"photo_reference":"CoQBdwAAAFzUTtvhGHzcYJq-UdYpzxRpMKlgSkkHtu87G8u3WD6s99wwxEnwGxUEcUSCRJDsSIM8veQVPKRkUkn1rFTCB4pPotitPXtxYIMQksBTvDvuAynm9sHzxJnf65RaSFJcJ_rMUJ9ghS4PeIF0SV_C2XZ5BCBwOgkD9tgCNmOxXrxSEhAMrcGa8Khzysiffh2Vo8CkGhT-ZGU78NmQcMC5trHSS1h3nNsp_g","width":794}],"place_id":"ChIJ13n1jHBP4DsRhVsMMvBHBrU","rating":4.8,"reference":"CmRSAAAAG-tPKgTwGveJEt0PL9IDIe9XLQkBnpZFJTsY0XDArF7jUT81szl_x7F1ndeOB3TZVsYcEEMf7G93CIuPs-fodpEjM413PI7Mb1IdlO5bTWGNBebPZoAyu9dPqGjJCM6yEhAyotMjeoI9Hyvr4PEb0vKjGhRbPbYmp-uwwdVyDapzxpV4pOMfXw","scope":"GOOGLE","types":["hospital","point_of_interest","establishment"],"vicinity":"434-445, 4 th Floor, Apple Square,, Beside Swastik Plaza, Yogi Chowk, Surat., Surat"},{"geometry":{"location":{"lat":21.2150921,"lng":72.8880922},"viewport":{"northeast":{"lat":21.2164410802915,"lng":72.88944118029151},"southwest":{"lat":21.21374311970849,"lng":72.88674321970849}}},"icon":"https:\/\/maps.gstatic.com\/mapfiles\/place_api\/icons\/doctor-71.png","id":"34d3977def7c2ee31d41db96d55df1b4c07c7e72","name":"Virdiya Hospital","place_id":"ChIJ5U12jnpP4DsRylJBztn0bdE","reference":"CmRSAAAAZefzhhlgAEYxBv29zBLtp_eLrZpy-RVAFzeVtpFrNGFoYPKQ6JQddoNUvGtTz2Ow10KHYJw7pajUHe9KhDBSM5lgaDRu9bNBMX1jCgjmZqq9MO3df_EpayVsFST5Jx6NEhA8jCjggaoVYu6rZnXcFy0eGhSiq_VX6gmNptn73kB1hNRZngIuxw","scope":"GOOGLE","types":["hospital","point_of_interest","establishment"],"vicinity":"315, 3rd Floor, Swastik Plaza, Yogi Chowk, Yogi Chowk Ground, Chikuwadi, Nana Varachha, Surat"},{"geometry":{"location":{"lat":21.2150999,"lng":72.88838419999999},"viewport":{"northeast":{"lat":21.2162783302915,"lng":72.88982628029149},"southwest":{"lat":21.2135803697085,"lng":72.88712831970848}}},"icon":"https:\/\/maps.gstatic.com\/mapfiles\/place_api\/icons\/doctor-71.png","id":"9469cd58c282297693fbc0cfe0cd25a1c34926a7","name":"Viradiya Test Tube Baby","
04-19 12:56:25.349 4485-4485/com.example.chaitanya.nearbyplace D/Volley: [1] override.onErrorResponse: ItemDetailsActivity

A: Use JSONArray results = response.getJSONArray("results") instead of JSONArray results = response.getJSONArray(1)
Try this:
        @Override
        public void onResponse(JSONArray response) {
            Log.d(TAG, response.toString());
            hidepDialog();

            try {
                JSONArray results = response.getJSONArray("results");
                // Parsing json
                for (int i = 0; i < results.length(); i++) {
                    try {
                        JSONObject obj = results.getJSONObject(i);
                        LocationDetailModel locationDet = new LocationDetailModel();
                        locationDet.setTitle(obj.getString("name"));
                        locationDet.setThumbnailUrl(obj.getString("vicinity"));

                        LocationDetailList.add(locationDet);

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                // notifying list adapter about data changes
                // so that it renders the list view with updated data
                adapter.notifyDataSetChanged();
            } catch (JSONException e) {
                Log.e("MYAPP", "unexpected JSON exception", e);
                // Do something to recover ... or kill the app.
            }
        }

        ............
        ....................

A: your API response is json object not json array so try to change JsonArrayRequest to  JsonObjectRequest


text:
Q: How to draw rectangle with transparent inner region? I want to draw rectangle at center of a view like this image .For this I am using the following code
public class TransparentView extends View {

    public TransparentView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public TransparentView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TransparentView(Context context) {
        super(context);
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);
        canvas.drawColor(Color.parseColor("#60000000"));
        Paint borderPaint = new Paint();
        borderPaint.setARGB(255, 255, 128, 0);
        borderPaint.setStyle(Paint.Style.STROKE);
        borderPaint.setStrokeWidth(4);

        Paint innerPaint = new Paint();
        innerPaint.setARGB(0, 0, 0, 0);
        innerPaint.setAlpha(0);
        innerPaint.setStyle(Paint.Style.FILL);

        RectF drawRect = new RectF();

        drawRect.set(100, 100, 100,100);

        canvas.drawRect(drawRect, innerPaint);
        canvas.drawRect(drawRect, borderPaint);

    }

}

How can i make complete transparent inside the rectangle and poor transparent at the  outer region?

A: Use Path and add two Rects into it, one for the full View area and one for the "selection". Set Path fillType to EVEN_ODD. Now fill that with half-transparent color.
Path outerPath = new Path();
// add rect covering the whole view area
outerPath.addRect(0, 0, getWidth(), getHeight(), Path.Direction.CW);
// add "selection" rect;
RectF inner = new RectF(left, top, right, bottom);
outerPath.addRect(inner, Path.Direction.CW);
// set the fill rule so inner area will not be painted
outerPath.setFillType(Path.FillType.EVEN_ODD);

// set up paints
Paint outerPaint = new Paint();
outerPaint.setColor(0x60000000);

Paint borderPaint = new Paint();
borderPaint.setARGB(255, 255, 128, 0);
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setStrokeWidth(4);

// draw
canvas.drawPath(outerPath, outerPaint);
canvas.drawRect(inner, borderPaint);

Note that for better performance you should not create Paints and Paths in onPaint(). I suggest onSizeChanged() is better for that.

A: Just use
innerPaint.setStyle(Paint.Style.STROKE);

instead of
innerPaint.setStyle(Paint.Style.FILL);

A: I separated the image in 5 rectangles.
The main one is the complete transparent one, that's in the middle of the figure. The other 4 will be semi-transparent.
After that, inside onDraw(Canvas canvas) I painted over the 4 rectangles with a semi-transparent color.
Here's the code I used.
//On constructor:
float x1,x2,y1,y2;
x1 = (screenWidth - squareSize)/2;
x2 = x1 + squareSize;
y1 = (screenHeight - squareSize)/2;
y2 = y1 + squareSize;
rect = new RectF(x1, y1, x2, y2);
dark = new RectF[]{
        new RectF(0, 0, screenWidth, y1),
        new RectF(0, y1, x1, y2),
        new RectF(x2, y1, screenWidth, y2),
        new RectF(0, y2, screenWidth, screenHeight)
};

semitransparentPaint = new Paint();
semitransparentPaint.setColor(Color.BLACK);
semitransparentPaint.setAlpha((int) (256 * (1-TRANSPARENCY)));

//Inside onDraw(Canvas canvas)
for(RectF r : dark){
    canvas.drawRect(r, semitransparentPaint);
}

That may work for you.
Also, you didn't ask for the borders, but on your code snippet I saw that you called canvas.drawRect(drawRect, borderPaint); witch makes me believe you also want to draw them, so I'll paste here the code I used to draw the borders:
//Inside onDraw(Canvas canvas)
canvas.drawLines(new float[]{
    rect.left, rect.top, rect.right, rect.top,
    rect.right, rect.top, rect.right, rect.bottom,
    rect.right, rect.bottom, rect.left, rect.bottom,
    rect.left, rect.bottom, rect.left, rect.top}
    , 0, 16, squareBorderPaint);

A: You can make use of setXfermode() of Paint and pass PorterDuff.Mode.ADD and PorterDuff.Mode.ADD as parameter in order to obtain inner transparency region.
I have mentioned an example below which contains a transparent rectangle inside another rectangle, which show's how it can be implemented in Android.
    Paint outerPaint = new Paint();
    outerPaint.setColor(0x7f0600a6); // mention any background color
    outerPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.ADD));
    outerPaint.setAntiAlias(true);

    Paint innerPaint = new Paint();
    innerPaint.setColor(Color.TRANSPARENT);
    innerPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.CLEAR));
    innerPaint.setAntiAlias(true);

    canvas.drawRect(0.0F, 0.0F, width, height, outerPaint);
    canvas.drawRect(150F, 150F, innerWidth, innerHeight, innerPaint);

Please Note: You may change the values within drawRect() as per your needs.


text:
Q: ggplot2: ignoring nan values when plotting error bars I am having a seemingly simple problem that for some reason I can'f find any information on.
I am attempting to create a simple scatter plot with error bars derived from the standard deviation of my data set. However, there are a few sets of data that have only a single point - and therefore the sd function returns nan.
This becomes a problem when I attempt to use the data in ggplot2, where I get the following error:

Error: ggplot2 doesn't know how to deal with data of class uneval

Here is my code that creates the average and standard deviation data:
avg_rxn <- rxn_data %>%
  group_by(system, solvent_type, solvent_position) %>%
  summarize(distance_mean = mean(distance),
            distance_error = sd(distance),
            energy_mean = mean(energy_rxn),
            energy_error = sd(energy_rxn))

And here is my code to generate the plot:
water_distance <- avg_rxn %>%
  filter((system == "9h0m") | (system == "8h1m")) %>%
  filter(solvent_type == "water") %>%
  #filter(solvent_position == "axial") %>%
  select(energy_mean, energy_error, system, solvent_position, distance_mean, distance_error)

ylimits = aes(ymax = energy_mean + energy_error, ymin = energy_mean - energy_error)
xlimits = aes(xmax = distance_mean + distance_error, xmin = distance_mean - distance_error)

water_distance_plot <- ggplot(data = water_distance, aes(solvent_position, x = distance_mean,
                                                         y = energy_mean, shape = solvent_position,
                                                         color = system)) +
  geom_point(size = 5) +
  geom_errorbar(ylimits, xlimits, width = 0.25) +
  theme_few()

ggsave("figures/water_distance_plot.png", water_distance_plot)

I can imagine a couple of different solutions to this problem, but can't figure out how to implement them. The nan values could be replaced with 0 when computing avg_rxn, or ggplot2 could simply ignore the nan values during the arithmetic that computes the error bar limits.
Any help would be greatly appreciated!
* edit *
As requested, here is some of the data (including both points that work and points that do not). The spaces should allow it to be interpreted and then saved as a csv.

ID    system  geometry_number solvent_number  solvent_position    solvent_type energy_rxn
  0h9m_1_1  0h9m    1   1   equitorial  methanol    38.91447
  0h9m_1_2  0h9m    1   2   equitorial  methanol    42.31569
  0h9m_1_3  0h9m    1   3   equitorial  methanol    43.06978
  0h9m_1_4  0h9m    1   4   axial   methanol    42.94058
  0h9m_1_5  0h9m    1   5   axial   methanol    40.79774
  0h9m_1_6  0h9m    1   6   axial   methanol    43.06764
  0h9m_1_7  0h9m    1   7   axial   methanol    43.45027
  0h9m_1_8  0h9m    1   8   axial   methanol    42.60882
  0h9m_1_9  0h9m    1   9   axial   methanol    45.0522
  1h8m_1_1  1h8m    1   1   equitorial  methanol    41.40231
  1h8m_1_2  1h8m    1   2   equitorial  methanol    43.22337
  1h8m_1_3  1h8m    1   3   equitorial  methanol    41.43154
  1h8m_1_4  1h8m    1   4   axial   methanol    42.53526
  1h8m_1_5  1h8m    1   5   axial   methanol    43.18862
  1h8m_1_6  1h8m    1   6   axial   methanol    43.07718
  1h8m_1_7  1h8m    1   7   axial   methanol    43.00857
  1h8m_1_8  1h8m    1   8   axial   methanol    43.57557
  1h8m_1_9  1h8m    1   9   axial   water   34.68406
  1h8m_2_1  1h8m    2   1   equitorial  methanol    43.83503
  1h8m_2_2  1h8m    2   2   equitorial  methanol    45.12783
  1h8m_2_3  1h8m    2   3   equitorial  water   30.27222
  1h8m_2_4  1h8m    2   4   axial   methanol    40.47726
  1h8m_2_5  1h8m    2   5   axial   methanol    43.58034
  1h8m_2_6  1h8m    2   6   axial   methanol    44.02348
  1h8m_2_7  1h8m    2   7   axial   methanol    42.43128
  1h8m_2_8  1h8m    2   8   axial   methanol    46.02447
  1h8m_2_9  1h8m    2   9   axial   methanol    43.73061
  2h7m_1_1  2h7m    1   1   equitorial  methanol    42.28647
  2h7m_1_2  2h7m    1   2   equitorial  methanol    42.93061
  2h7m_1_3  2h7m    1   3   equitorial  methanol    42.0748
  2h7m_1_4  2h7m    1   4   axial   methanol    43.55864
  2h7m_1_5  2h7m    1   5   axial   methanol    43.33525
  2h7m_1_6  2h7m    1   6   axial   methanol    44.1656
  2h7m_1_7  2h7m    1   7   axial   methanol    42.83685
  2h7m_1_8  2h7m    1   8   axial   water   34.04387
  2h7m_1_9  2h7m    1   9   axial   water   35.07239
  2h7m_2_1  2h7m    2   1   equitorial  methanol    41.44339
  2h7m_2_2  2h7m    2   2   equitorial  methanol    43.847
  2h7m_2_3  2h7m    2   3   equitorial  methanol    41.59372
  2h7m_2_4  2h7m    2   4   axial   methanol    43.49975
  2h7m_2_5  2h7m    2   5   axial   methanol    44.02411
  2h7m_2_6  2h7m    2   6   axial   water   34.06499
  2h7m_2_7  2h7m    2   7   axial   methanol    44.79557
  2h7m_2_8  2h7m    2   8   axial   methanol    44.85728
  2h7m_2_9  2h7m    2   9   axial   water   34.51222
  2h7m_3_1  2h7m    3   1   equitorial  methanol    41.67581
  2h7m_3_2  2h7m    3   2   equitorial  methanol    42.25084
  2h7m_3_3  2h7m    3   3   equitorial  methanol    42.94723
  2h7m_3_4  2h7m    3   4   axial   methanol    43.55839
  2h7m_3_5  2h7m    3   5   axial   methanol    43.29994
  2h7m_3_6  2h7m    3   6   axial   water   34.7908
  2h7m_3_7  2h7m    3   7   axial   methanol    44.08162
  2h7m_3_8  2h7m    3   8   axial   water   35.26678
  2h7m_3_9  2h7m    3   9   axial   methanol    44.01194
  2h7m_4_1  2h7m    4   1   equitorial  methanol    42.30547
  2h7m_4_2  2h7m    4   2   equitorial  methanol    43.21565
  2h7m_4_3  2h7m    4   3   equitorial  water   33.13139
  2h7m_4_4  2h7m    4   4   axial   methanol    44.7819
  2h7m_4_5  2h7m    4   5   axial   methanol    44.36447
  2h7m_4_6  2h7m    4   6   axial   methanol    42.84187
  2h7m_4_7  2h7m    4   7   axial   methanol    43.7597
  2h7m_4_8  2h7m    4   8   axial   methanol    42.16279
  2h7m_4_9  2h7m    4   9   axial   water   33.87122
  2h7m_5_1  2h7m    5   1   equitorial  methanol    43.05943
  2h7m_5_2  2h7m    5   2   equitorial  methanol    42.42544
  2h7m_5_3  2h7m    5   3   equitorial  water   32.6147
  2h7m_5_4  2h7m    5   4   axial   methanol    43.9089
  2h7m_5_5  2h7m    5   5   axial   methanol    43.74754
  2h7m_5_6  2h7m    5   6   axial   methanol    44.32521
  2h7m_5_7  2h7m    5   7   axial   water   34.46159
  2h7m_5_8  2h7m    5   8   axial   methanol    44.44951
  2h7m_5_9  2h7m    5   9   axial   methanol    44.39225
  2h7m_6_1  2h7m    6   1   equitorial  methanol    42.45906
  2h7m_6_2  2h7m    6   2   equitorial  water   33.08564
  2h7m_6_3  2h7m    6   3   equitorial  water   32.82477
  2h7m_6_4  2h7m    6   4   axial   methanol    43.5979
  2h7m_6_5  2h7m    6   5   axial   methanol    43.62907
  2h7m_6_6  2h7m    6   6   axial   methanol    43.77689
  2h7m_6_7  2h7m    6   7   axial   methanol    43.35983
  2h7m_6_8  2h7m    6   8   axial   methanol    44.43013
  2h7m_6_9  2h7m    6   9   axial   methanol    44.49385
  3h6m_1_1  3h6m    1   1   equitorial  methanol    44.74621
  3h6m_1_2  3h6m    1   2   equitorial  methanol    44.08081
  3h6m_1_3  3h6m    1   3   equitorial  methanol    41.49557
  3h6m_1_4  3h6m    1   4   axial   methanol    42.18926
  3h6m_1_5  3h6m    1   5   axial   methanol    44.80554
  3h6m_1_6  3h6m    1   6   axial   methanol    46.12343
  3h6m_1_7  3h6m    1   7   axial   water   32.94014
  3h6m_1_8  3h6m    1   8   axial   water   35.29087
  3h6m_1_9  3h6m    1   9   axial   water   35.75008


text:
Q: Why is Entity Framework creating a discriminator column for my View Model? I've just read quite a few posts on Table per Type/TPT and the discriminator column, but, I'm not really any the wiser in my situation.
Taking an example: I have a MVC app that has a model called Foo. This has one property called Bar that is stored as a one to many elsewhere.
I am the only one using this app and I didn't want to spend a lot of time on it, so I just wanted the quickest way to add items to the list in Bar. Because of this, I made a new class called FooViewModel that is derived from Foo, and had a string property called BarTemp.
The basic idea is that I can type 111, 222 , 333,444 in to a standard text field and have the edit/create controllers clear whitespace and split to a list on the comma.
What I can't figure out is that the view model will never be written to EF, so, why is it creating the discriminator column.
It looked like when I tried to scaffold a migration, it event tried adding BarTemp to the DB.
I have since created a new type called the same, but instead of deriving, I just have Foo and BarTemp as properties in it which works as expected, but, I still don't get what happened and would like to learn more.

A: It's because EntityFramework parses the hierarchy. Just because your current code doesn't ever save a BarTemp, there's nothing explicitly stopping you from writing:
context.Bars.Add(new BarTemp());

There's nothing EntityFramework can do to detect the above. So, it plays safe and assumes that if you inherit from an entity, your subclass will also be an entity. That's a correct assumption - and you shouldn't make view models inherit from the entity. Neither should they be properties. I'm really unsure how you've setup your current code, but the classes should be completely distinct. For example, it should look something like:
class BarTemp
{
    public string BarId { get; set; }
    public string Foos { get; set; }
}

class Bar
{
    public string BarId { get; set; }
    public ICollection<Foo> Foos { get; set; }
}
class Foo
{
    public string Id { get; set; }
    public Bar Bar { get; set;
}

Your view model should know nothing about the entities, and the entities should know nothing about the view models. Your code accepting the input should do the work converting the view model to the entity. For example:
private void Update(BarTemp barTemp)
{
    var bar = context.Bars.GetById(barTemp.BarId);
    foreach (var foo in barTemp.Foos.Split(","))
    {
        var foo = context.Foos.GetById(foo);
        bar.Foos.Add(foo);
    }
    context.Save();
}

Don't take the above as an example of good code - it's extremely inefficient - but it should show you an example of where the conversions should take place, and how to keep the entities and view models separate.


text:
Q: Async Task doInBackground not performed I have a series of asyncTasks to be performed one after the other to download pdfs from the server.But sometimes when i minimize the app and then resume it (with downloads in the background) the very next asyncTask to be executed soon after the currently running asyncTask gets stuck in the preExcute ie. the doInBackground isn't being performed. Please help.

A: This is a known issue on AsyncTasks. The default executor for AsyncTasks are SERIAL_EXECUTOR. You can have 5 AsyncTasks in the queue for this executor. After that, it will stop making new Threads.
If you would do this:
public void someMethod() {
     new MyAsyncTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}

It would run your AsyncTasks on a different executor that pools your threads. It has a limit of 15. But the best thing is, it runs the threads parallel and the SERIAL_EXECUTOR puts them in a queue and executes them one by one.


text:
Q: google wmt: lost a lot of links to our site I've been having problems recently with my site and Google. There have been a number of problems (robots.txt etc.) which I fixed and resubmitted my main page & related pages via WMT. that worked fine.
But since then (2 days ago) I've lost most of the links to my site!
We have a major affiliate that had a lot of links to our site and now they don't appear in
WMT "Links to your site".
We haven't received a warning mail about "unnatural links"
the links from the other site are alive (most of them to our home page, is that a problem)
Any ideas on how to fix this or what's causing it?

A: It's one of two things:

*

*You haven't fixed your indexing/exclusion problems correctly and something is causing that problem. Check again.

*If not, remember that Google changes which links it displays and which it does not display basically according to their whim and updates. It's worth remembering the following things:

*

*Just because a link is reported in WMT does not mean it is a good link.

*Just because a link is NOT reported in WMT does not mean it is a bad link.

*Overall number of links can only be used as a trend. The appearance or disappearance of a site reporting links means very little in the grand scheme of things.

*Affiliate links are generally not a Google favourite for passing value. It's possible that your affiliate got hammered by Google.

Have your traffic and positions been affected? Then you're looking at a more major issue. If not, it's just Google being Google.


text:
Q: Boxplot in R showing the mean Does anybody know of a way of generating a boxplot in R with a line (or another symbol) in the value corresponding to the mean?
Thank you!

A: abline(h=mean(x))

for a horizontal line (use v instead of h for vertical if you orient your boxplot horizontally), or
points(mean(x))

for a point. Use the parameter pch to change the symbol. You may want to colour them to improve visibility too.
Note that these are called after you have drawn the boxplot.
If you are using the formula interface, you would have to construct the vector of means. For example, taking the first example from ?boxplot:
boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
means <- tapply(InsectSprays$count,InsectSprays$spray,mean)
points(means,col="red",pch=18)

If your data contains missing values, you might want to replace the last argument of the tapply function with function(x) mean(x,na.rm=T)

A: With ggplot2:
p<-qplot(spray,count,data=InsectSprays,geom='boxplot')
p<-p+stat_summary(fun.y=mean,shape=1,col='red',geom='point')
print(p)

A: Check chart.Boxplot from package PerformanceAnalytics. It lets you define the symbol to use for the mean of the distribution.
By default, the chart.Boxplot(data) command adds the mean as a red circle and the median as a black line.
Here is the output with sample data; MWE:
#install.packages(PerformanceAnalytics)
library(PerformanceAnalytics)
chart.Boxplot(cars$speed)

A: Based on the answers by @James and @Jyotirmoy Bhattacharya I came up with this solution:
zx <- replicate (5, rnorm(50))
zx_means <- (colMeans(zx, na.rm = TRUE))
boxplot(zx, horizontal = FALSE, outline = FALSE)
points(zx_means, pch = 22, col = "darkgrey", lwd = 7)

(See this post for more details)
If you would like to add points to horizontal box plots, please see this post.

A: I also think chart.Boxplot is the best option, it gives you the position of the mean but if you have a matrix with returns all you need is one line of code to get all the boxplots in one graph.
Here is a small ETF portfolio example.
library(zoo)
library(PerformanceAnalytics)
library(tseries)
library(xts)

VTI.prices = get.hist.quote(instrument = "VTI", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
                        compression = "m", retclass = c("zoo"))

VEU.prices = get.hist.quote(instrument = "VEU", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
                        compression = "m", retclass = c("zoo"))

VWO.prices = get.hist.quote(instrument = "VWO", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
                        compression = "m", retclass = c("zoo"))

VNQ.prices = get.hist.quote(instrument = "VNQ", start= "2007-03-01", end="2013-03-01",
                       quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
                       compression = "m", retclass = c("zoo"))

TLT.prices = get.hist.quote(instrument = "TLT", start= "2007-03-01", end="2013-03-01",
                        quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
                        compression = "m", retclass = c("zoo"))

TIP.prices = get.hist.quote(instrument = "TIP", start= "2007-03-01", end="2013-03-01",
                         quote = c("AdjClose"),provider = "yahoo",origin ="1970-01-01",
                         compression = "m", retclass = c("zoo"))

index(VTI.prices) = as.yearmon(index(VTI.prices))
index(VEU.prices) = as.yearmon(index(VEU.prices))
index(VWO.prices) = as.yearmon(index(VWO.prices))

index(VNQ.prices) = as.yearmon(index(VNQ.prices))
index(TLT.prices) = as.yearmon(index(TLT.prices))
index(TIP.prices) = as.yearmon(index(TIP.prices))

Prices.z=merge(VTI.prices, VEU.prices, VWO.prices, VNQ.prices,
           TLT.prices, TIP.prices)

colnames(Prices.z) = c("VTI", "VEU", "VWO" , "VNQ", "TLT", "TIP")

returnscc.z = diff(log(Prices.z))

start(returnscc.z)
end(returnscc.z)
colnames(returnscc.z)
head(returnscc.z)

Return Matrix
ret.mat = coredata(returnscc.z)
class(ret.mat)
colnames(ret.mat)
head(ret.mat)

Box Plot of Return Matrix
chart.Boxplot(returnscc.z, names=T, horizontal=TRUE, colorset="darkgreen", as.Tufte =F,
          mean.symbol = 20, median.symbol="|", main="Return Distributions Comparison",
          element.color = "darkgray", outlier.symbol = 20,
          xlab="Continuously Compounded Returns", sort.ascending=F)

You can try changing the mean.symbol, and remove or change the median.symbol.
Hope it helped. :)


text:
Q: Sharepoint - Changing Database Server Name Our Sharepoint Database Server will be moved to a new server, can someone please advise where we need to make the changes so that it points to the new server?
Any help will be highly appreciated as I'm new to Sharepoint 2010.
Regards

A: You need to follow this guide:
http://technet.microsoft.com/en-us/library/cc512725(v=office.14).aspx
or
1) Run this stsadm command:

stsadm -o renameserver -oldservername oldservername -newservername
  newservername

2) Rename and reboot server.
3) Enter Central Admin and look over all your Alternate Access Mappings (you'll have to change to the new server name everywhere the old server name still shows).
4) I didn't have this problem with 2010, but you might have to check and possibly reset your site collection admins. I wouldn't be surprised if you'll have to go over your host names in IIS in case you are using host headers also.
http://www.uccorner.com/67/sharepoint/rename-sharepoint-server-new-hostname/
hope it helps :)

A: There is another way to use an Alias for the server Instance. so in the new server use alias which will reflect with old server instance.


text:
Q: how can i put commas in thousands? `$.ajax({
                url : "/selectList.do",
                data:{memberNo:memberNo},
                success : function(list){
                    console.log(list);
                    for(let i=0;i<list.length;i++){
                             list[i].NUMBER;
                    }
                  }
            });`

I got numbers from ajax and I want to put a commas in this number in thousands.
How can I do it?

A: Try use regex

const thousands = (o) => o.toString().replace(/\B(?<!\.\d*)(?=(\d{3})+(?!\d))/g, ',');

console.log(thousands(123456789));
console.log(thousands(123456789.123));

Or use Number.prototype.toLocaleString()

const num = 123456.789;

console.log(num.toLocaleString());

Or use Intl.NumberFormat

const number = 123456.789;
const nf = new Intl.NumberFormat('en-US');

console.log(nf.format(number));

Or use Array.prototype

const insert = (arr, index, newItem) => [
  ...arr.slice(0, index),
  newItem,
  ...arr.slice(index)
];

const thousands = (o) => {
  let tmpArr = o.toString().split('.');
  let splitArr = tmpArr[0].split('');
  const reversed = splitArr.reverse();
  for (let i = 1; i <= reversed.length; i++) {
    if (i % 3 == 0)
      splitArr = insert(splitArr, i, ',');
  }
  tmpArr[0] = tmpArr.length > 1 ? '.' : '';
  return splitArr.reverse().concat(tmpArr).join('');
};

console.log(thousands(123456));
console.log(thousands(123456.789));


text:
Q: java.lang.NoSuchMethodError: javax.persistence.Table.indexes()[Ljavax/persistence/Index; inspite of hibernate-jpa-2.1.jar in classpath I know this question already has answers but I am unable to resolve my issue.
I have hibernate-commons-annotations-5.0.1.Final.jar, hibernate-core-4.3.5.Final.jar, hibernate-jpa-2.1-api-1.0.0.final.jar in the classpath.
Following is my HibernateUtil code:
public class HibernateUtil {

private static SessionFactory sessionAnnotationFactory;

private static SessionFactory buildSessionAnnotationFactory() {
    try {
        // Create the SessionFactory from hibernate-annotation.cfg.xml
        Configuration configuration = new Configuration();
        configuration.configure("hibernate-annotation.cfg.xml");
        System.out.println("Hibernate Annotation Configuration loaded");
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
        System.out.println("Hibernate Annotation serviceRegistry created");
        SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
        return sessionFactory;
    } catch (Throwable ex) {
        // Make sure you log the exception, as it might be swallowed
        System.err.println("Initial SessionFactory creation failed." + ex);
        throw new ExceptionInInitializerError(ex);
    }
}

public static SessionFactory getSessionAnnotationFactory() {
    if (sessionAnnotationFactory == null) sessionAnnotationFactory = buildSessionAnnotationFactory();
    return sessionAnnotationFactory;
}

}
Still I am getting the following error:

Initial SessionFactory creation failed.java.lang.NoSuchMethodError:
  javax.persistence.Table.indexes()[Ljavax/persistence/Index;
Caused By: java.lang.NoSuchMethodError:
  javax.persistence.Table.indexes()[Ljavax/persistence/Index;   at
  org.hibernate.cfg.annotations.EntityBinder.processComplementaryTableDefinitions(EntityBinder.java:936)
    at
  org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:824)
    at
  org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:3788)
    at
  org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3742)
    at
  org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410)
    at
  org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
    at
  net.deldot.util.HibernateUtil.buildSessionAnnotationFactory(Unknown
  Source)   at
  net.deldot.util.HibernateUtil.getSessionAnnotationFactory(Unknown
  Source)

I am using IntelliJ if that helps. Its not a maven project. I am not using jboss. There are no glassfish jars.I have read other answers that say this error occurs because of conflicting hibernate-jpa-2.1-api-1.0.0.final.jar and hibernate-jpa-2.0-api-1.0.0.final.jar. But I don't see hibernate-jpa-2.0 jar anywhere in my project. I don't know which jar is conflicting with hibernate-jpa-2.1 jar .How do I check that?

A: You are using hibernate-commons-annotations-5.0.1.Final.jar from Hibernate 5 with  hibernate-core-4.3.5.Final.jar from Hibernate 4. It is incorrect.
@Table annotation with Table#indexes() method should be in the hibernate-jpa-2.1-api-1.0.0.Final.jar
https://stackoverflow.com/a/35569978/3405171
You can try to check where the old @Table annotation comes from using this approach
https://stackoverflow.com/a/37409315/3405171
And, please, use Maven or Gradle.

A: Okay, not the best solution but a workaround. Since I was unable to enable weblogic's support for JPA2.1, I replaced Hibernate-core-4.3.5.Final.jar with Hibernate-core-4.2.21.Final.jar (JPA2.1 support was introduced in Hibernate 4.3.0). Not getting that error anymore.


text:
Q: Pushing two viewcontroller one after another does not localize backBarButtonItem I am pushing two viewcontrollers one after another like below on a button press:
//Pushing first view controller
    MyViewControllerOne *myViewControllerOne = [[MyViewControllerOne alloc] init];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"keyBack",nil) style:UIBarButtonItemStyleBordered target:nil action:nil];
    [self.navigationController pushViewController:myViewControllerOne animated:NO];

//Pushing Second view controller
    MyViewControllerTwo *myViewControllerTwo = [[MyViewControllerTwo alloc] init];
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:NSLocalizedString(@"keyBack",nil) style:UIBarButtonItemStyleBordered target:nil action:nil];
    [self.navigationController pushViewController:myViewControllerTwo animated:YES];

Now when I press the button , MyViewControllerTwo is shown, but with a back button title as "Back" and not the localized title that I have set for "keyBack" in Localizable.strings file, whereas when I push just only one viewcontroller in other parts of the code, it works fine and back button is shown in localized language.
How can I show the localized version of the backbarbutton?

A: Pushing more than one ViewController in to the navigation stack at once is bad practice.
I advise you find another way to accomplish what you want to do.


text:
Q: SQL that matches all or nothing I have the following table in PostgreSQL database:
CREATE TABLE maclist (
    username character varying,
    mac macaddr NOT NULL,
    CONSTRAINT maclist_user_mac_key UNIQUE (username, mac)
);

I need a way to check if the MAC address is assigned to the user or the user has no assigned MAC addresses at all. Basically I need a query that returns row if all conditions are true or no condition is true ie NOT a XOR b.
EDIT:
Example:
username | mac
john     | 11:22:33:44:55:66
john     | 11:22:33:44:55:67
doe      | 11:22:33:44:55:68

If I query:
username = john, mac = 11:22:33:44:55:66                     -> true, 1 whatever...
username = john, mac != 11:22:33:44:55:66                    -> 0, null or nothing...
username = jane, mac = no matter what except john's or doe's -> true, 1 whatever...
username = jane, mac = john's or doe's                       ->  0, null or nothing...

I need true under two conditions:

*

*There is a row for that (user, mac) combination. There are no rows

*for that user AND there are no rows for that mac

So far I got this:
SELECT yes
FROM
  (SELECT 1 AS yes) AS dummy
LEFT JOIN maclist ON (username = 'user'
                      OR mac = '11:22:33:44:55:66')
WHERE ((username = 'user'
        AND mac = '11:22:33:44:55:66')
       OR (username IS NULL
           AND mac IS NULL);

It works, but it seems to me like a hack and I also have no idea about the performance of this query as the database grows.
My question is if there are any better ways to do this.

A: EDIT: I've revised the logic slightly, I think it matches what you want
The following code will return 1 under two conditions...

*

*There is a row for that user and that mac

*There are 0 rows for that user and there are 0 rows for that mac
Under all other conditions, the query returns 0.

*

*There are rows for that user but none of them are for that mac

*There are rows for that mac  but none of them are for that user

SELECT
  CASE WHEN COUNT(*) = 0                                THEN 1
       WHEN SUM(CASE WHEN mac = '11:22:33:44:55:66'
                      AND user = 'user' THEN 1
                                        ELSE 0 END) = 1 THEN 1
                                                        ELSE 0
  END
FROM
  maclist
WHERE
     username = 'user'
  OR mac      = '11:22:33:44:55:66'

A: You can write the query simply as:
prepare query_mac(text, macaddr) as
select exists (select 1 from maclist where username = $1 and mac = $2)
       or (not exists (select 1 from maclist where username = $1)
           and not exists (select 1 from maclist where mac = $2)
          );

PostgreSQL will evaluate each of the three queries separately, and use the unique index on (username,mac) for the first two. If you need to, you can add an index on (mac) for the third.

A: Practically all databases won't use an index when an OR is involved, so avoid those in the joins.
Edited:
It seems you are really making two separate queries:

*

*who is the mac assigned to (if any)

*what mac is assigned to the user (if any)

so a union won't be as easy as a collection of subselects. Use separate queries to split up the info into their own simple query, and combine them into one:
select
    (select username from maclist
     where mac = '11.22:33:44:55:66') as mac_assigned_to,
    (select mac from maclist
     where username = 'user') as user_assigned_to

Both columns may have nulls if there is nothing currently assigned, otherwise they'll show what's assigned for each concern.


text:
Q: Problems adding object to database in Entity Framework I have the following code trying to add an object to the database:
public static void saveAudit(List<AUDIT> audit)
{
 Entities dao = new Entities();

 foreach (CMUAUDIT a in audit)
 {
    dao.CMUAUDITs.AddObject(a);
 }

 dao.SaveChanges();
}

However I get the error message:

"...does not contain a definition for 'AddObject' and no extension
  method 'AddObject' accepting a first argument of type 'System.Data.Entity.DbSet' could be found (are you missing a using directive or an assembly reference?)"

I've done some searching, and there is mention of the primary key having something to do with it. Any suggestions?
I'm using a DB2 database if that makes any difference?

A: ...System.Data.Entity.DbSet...: Apparently your class Entities is derived from DbContext and not ObjectContext. CMUAUDITs will be a DbSet<T> (and not an ObjectSet<T>) in this case. The correct method to add an entity to a DbSet<T> is:
dao.CMUAUDITs.Add(a);

AddObject is only available for an ObjectSet<T>.


text:
Q: Generate consecutive substring from the string using recursion I am having a string let say ABCD I want to create all the subsets in such a way that they are consecutive like this:
`A` ,`AB`, `ABC`, `ABCD`, `B`, `BC`, `BCD`, `C`, `CD`, `D`

AC, AD, BD etc should not be generated as they are not next to each other.
I tried to write the logic but now I am getting:

See the highlighted ones. Is it possible to generate consecutive subset using recursion?
Reason for using recursion is to understand how the recursion works so I am attempting all the questions using recursion only (without loops)
Code:
#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:

void print_str(string s){
    for(int i=0; i<s.length();i++)
    {
        cout<<s[i];
    }
    cout<<endl;
}
void recur(string st, string ans, int prev, int n, int ind){

    print_str(ans);
    for(int i=prev; i<n;i++){
        recur(st, ans+st[i], i+1, n, ind+1);
    }

    }

};

int main()
{
    Solution sol;
    string st = "ABCD";
    sol.recur(st, "", 0, st.length(),0);
}

A: With recursion, you might do:
void print_seq(std::string_view s)
{
    if (s.size() > 1) print_seq(s.substr(0, s.size() - 1));
    std::cout << s << std::endl;
}

void print_all(std::string_view s)
{
    print_seq(s);
    if (s.size() > 1) print_all(s.substr(1));
}

int main()
{
    print_all("ABCD");
}

Demo

A: From your rules, it can be said that once you started to append something to ans, you mustn't skip characters.
#include <iostream>
#include <string>

using namespace std;

class Solution {
public:

    void print_str(const string& s){
        cout<<s<<endl;
    }
    void recur(const string& st, string ans, int i, int n){
        if (i >= n){
            if (ans!="") print_str(ans); // print non-empty answer
        }else if(ans==""){ // when current answer is empty
            recur(st, ans+st[i], i+1, n); // start appending characters to the answer
            recur(st, ans, i+1, n); // or keep the answer empty
        }else{
            print_str(ans); // print non-empty answer
            recur(st, ans+st[i], i+1, n); // append a character (no choice to skip a character)
        }
    }

};

int main()
{
    Solution sol;
    string st = "ABCD";
    sol.recur(st, "", 0, st.length());
}

Output:
A
AB
ABC
ABCD
B
BC
BCD
C
CD
D


text:
Q: Saving sqlite database in cached directory instead of documents Until now my database was saved in the documents directory of application. Now Apple refuse to do it anymore and I need to change the directory.
Does anyone know how to save a database in cached directory, or even direct me to a tutorial/example.

A: The caches directory will be the last entry returned from NSSearchPathForDirectoriesInDomains:
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *dbPath = [cachesPath stringByAppendingPathComponent:@"mydatabase.db"];


text:
Q: Insert Line under different lines in excel Thinking this may be a basic one but I am afraid I don't know how to do it!
If I have a long list of different suppliers but want to add a row under each group (Sometimes they will be listed more than once. Is there a basic formula for this rather than doing each one by one.
Example
SUPPLIER1
SUPPLIER1
SUPPLIER1
SUPPLIER2
SUPPLIER2
SUPPLIER3
SUPPLIER4
SUPPLIER4

to look like
SUPPLIER1
SUPPLIER1
SUPPLIER1

SUPPLIER2
SUPPLIER2

SUPPLIER3

SUPPLIER4
SUPPLIER4

Many thanks in advance for your help.
Mark

A: Pretty quickly done in VBA:
Sub split_Series()
Dim lastRow&, i&
lastRow = Cells(Rows.Count, 1).End(xlUp).Row

For i = lastRow To 1 Step -1
If i > 1 Then
    If Cells(i, 1).Value <> Cells(i - 1, 1).Value Then
        Cells(i, 1).EntireRow.Insert
    End If
End If
Next i

End Sub

This is assuming your Column A has the most data, and is the one with the suppliers.  If not, just change the Y value (cells(x,y)) to 2 (for "B"), 3 (for "C"), etc.

A: One quick way, without using VBA, is inserting subtotals in a list of data in a worksheet.

*

*Select the range.

*go to Data tab → click Subtotal.

more info here


text:
Q: Visible refinement of class methods consider the following small ocaml class hierarchy:
class x = object method i = 0 end ;;
class y = object method x = new x end ;;
class x2 = object method i = 0 method j = 1 end ;;
class z = object method x = new x2 inherit y end;; (* type error *)

What I want to achieve is to refine the field x of class z w.r.t. class y and have that refinement visible at the type of z, i.e.
class z = object method x = (new x2 :> x) inherit y end;;
(new z)#x#j;; (* type error *)

is not what I want to achieve.
I am pretty confident that there is a way to convinve the type checker of the compatibility of the refinement, but how?

A: It looks like it is difficult to do this directly: if you try to relax the type of method x in y using a type parameter,
class ['a] y = object
  constraint 'a = #x
  method x = new x
end

you can see that the type-checker forces 'a to be exactly x and not any subtype #x of x:
class ['a] y = object
  constraint 'a = x
  method x = new x
end

which will thus preclude any attempt to redefine method x with another type. However, it is possible to define classes that expects an object of type #x as argument, and to derive the original class y and class z from them:
class x = object method i = 0 end ;;

class ['a] y_gen (x:'a) = object
  constraint 'a = #x
  method x = x end
;;

class y = object inherit [x] y_gen (new x) end

class x2 = object method i = 0 method j = 1 end ;;

class ['a] z_gen (x:'a) = object
  constraint 'a = #x2
  inherit ['a] y_gen x
  method! x = x
end;;

class z = object inherit [x2] z_gen (new x2) end

Furthermore, z is indeed a subtype of y, i.e. the following is correctly type-checked:
let my_z = new z
let my_y = (my_z :> y)


text:
Q: Replace failed RAID 1 Drive on Intel Platform Good afternoon, I have a Intel Server running Windows 2008 R2 Standard. It has a RMS25PB080 Raid controller card in with. It has two logical drives, a RAID 1 and a RAID 5. The one harddrive on the RAID 1 is failing but I have no idea how to replace it. Must it be exactly the same drive? Can it be same size but different RPM (Currently it has SEAGATE SAS 6Gb/s ST3300657SS at 15000rpm)?
I have read here: Replacing a failed drive - RAID 1 and here: One drive failed in my RAID 1+0 array, am I safe to replace it without losing data? as well as here SSDs or 15k sas for server OS / application drive? but it is flying over my head. Any help would be greatly appreciated as out supplier says that they can't get the ST3300657SS Drive anymore.
Thank you!
UPDATE 1.
Supplier came back to me with the following HDD http://www.seagate.com/em/en/internal-hard-drives/enterprise-hard-drives/hdd/enterprise-performance-15k-hdd/?sku=ST300MP0005
Would this drive work?

A: Ok so the new hard drive arrived today and I am very very relieved to see that it worked. Although it is a 2.5" and the bay is a 3.5". Set the drive to offline in RAID Console, swapped it out with the new hdd and it is now rebuilding the array.
Here was the HDD that I got: http://www.seagate.com/em/en/internal-hard-drives/enterprise-hard-drives/hdd/enterprise-performance-15k-hdd/?sku=ST300MP0005
Hope this helps someone else in the future