text:
Q: MS Access VBA using Option Explicit gives "Variable not defined" error but works on a different database I'm moving forms over from one Access database to another. When I try to compile the new database, it gives a "Variable not defined" error. This only happens when using Option Explicit. The variable is a AccessField data type that is selected by the form's SQL query. This compiles fine on the Access database that I'm moving it from, so I'm completely lost trying to figure out what's wrong?
I seem to have the exact same problem that never was solved in this old thread: https://bytes.com/topic/access/answers/896346-variable-not-defined-error-field-exists
It's more than one instance. Anything that references an AccessField that is not declared as a variable will return that error when Option Explicit is used.
For instance, the form is using the query:
Select * from BM where ClientID =143 and Month(BMDate) = 4 and year(bmdate) =2018 order by bmdate

And the VBA code inside that form would fail here with that error:
Option Explicit
Option Compare Database

Private Sub Form_Load()
    If IsNull(RecNbr) Then
        'Code fails with RecNbr on line above when I try to compile
        'RecNbr is a field selected from the query and is not declared as a variable
    End If
End Sub

A: This may or may not work, but it's too long for a comment.
This post in your linked thread seems to have an explanation:

In the form design view, the Field List and the drop-down for the Control Source for a control reflect the current table design; but VBA seems to have a stale copy of the form's recordsource schema.

Try this to re-sync VBA's cache (?) of the record source:

*

*In form design, remove the record source (save it in a text editor, if necessary)

*save and close the form

*maybe compact & repair the database (I don't know if this will change the behavior)

*reopen the form in design view

*set the record source. Note how after hitting Return, Access takes a tiny moment, and then the warning triangles for bound controls should disappear.

*See if the code compiles now.

As a note, I find find code better readable when using Me.RecNbr instead of RecNbr when refering to form controls or fields (as opposed to VBA variables).
If the above still doesn't compile, you can use Me!RecNbr.
Useful reading: Bang Notation and Dot Notation in VBA and MS-Access


text:
Q: Reflective exponential ideals in presheaf categories A well-known theorem states that a category E is a Grothendieck topos if and only if it can be embedded as a reflective subcategory of a presheaf category whose reflector preserves finite limits.
In their paper Grothendieck quasitoposes, Garner and Lack proved that a category E is a Grothendieck quasitopos (the category of sheaves for one topology that are separated for another topology) if and only if it can be embedded as a reflective subcategory of a presheaf category whose reflector has stable units (i.e. preserves all pullbacks over objects in the subcategory) and preserves monomorphisms.
Is there a characterization of when a category E can be embedded as a reflective subcategory of a presheaf category whose reflector preserves finite products?  (The reflector preserving finite products is equivalent to the reflective subcategory being an exponential ideal, i.e. $Y^X$ lies in the subcategory as soon as $Y$ does.)  Of course, any such category must be locally presentable and cartesian closed.  Can this be extended to a set of conditions which is both necessary and sufficient?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Firebase Realtime Database Edit Key and keep children I'm trying to edit the name of the classroom shown in the image below without losing the children data, how to do that in android ?

A: There is no way for doing this. There is no API that allows you to change the name of a node in a Firebase database. What can you do instead, is to create another node with the desired name, containing the same childrens and then remove the old one.


text:
Q: Confirm email address exists and is not already taken, using Parse and email Regex I am at the part of my register process where I would like to confirm if the email given by the user exists and is not already taken.
So far, I have the regex set and customized to how I want it (I am limiting the user to a student email address).
- (BOOL)validateEmail:(NSString *)emailStr {
NSString *emailRegex = @"[A-Za-z]+\\.[A-Za-z]+@[ace]+\\.[tamut]+\\.[edu]";
NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

[self checkEmailAndDisplayAlert];

return [emailTest evaluateWithObject:emailStr];

}

I throw an alert if the email is not acceptable.
 - (void)checkEmailAndDisplayAlert {

if(![self validateEmail:[_email text]]) {

     [self.email becomeFirstResponder];

    // user entered invalid email address
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Enter a valid email address." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
    [alert show];

} else {
    // user entered valid email address
    [self registerNewUser];
  }
}

If I enter an email that does not meet the regex requirements, the proper alert is not shown, and I am still allowed to pass through the registration as a new user. What am I doing wrong?
Please don't hold back on any feedback, I am new to programming and this is something I need to know, no excuses.

A: In your validateEmail method, you call checkEmailAndDisplayAlert ([self checkEmailAndDisplayAlert];), and it also calls validateEmail. I'd delete [self checkEmailAndDisplayAlert]; to avoid endless loops.
Also, try changing the regex to
NSString *emailRegex = @"^[A-Za-z]+\\.[A-Za-z]+@ace\\.tamut\\.edu$";

The function to check validity could also look like:
- (BOOL)validateEmail:(NSString *)emailStr
{
    NSError *error = nil;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"^[a-z]+\\.[a-z]+@ace\\.tamut\\.edu$" options:NSRegularExpressionCaseInsensitive error:&error];

    NSAssert(regex, @"Unable to create regular expression");

    NSRange txtRng = NSMakeRange(0, emailStr.length);
    NSRange matchRng = [regex rangeOfFirstMatchInString:emailStr options:NSMatchingReportProgress range:txtRng];

    BOOL validated = NO;

    if (matchRng.location != NSNotFound)
        validated = YES; // Match found

    return validated;
}

^ and $ are added at the beginning anf end of the regex pattern to enable whole string search.


text:
Q: How to get a MD5 hash from a string in Golang? This is how I started to get a md5 hash from a string:
import "crypto/md5"

var original = "my string comes here"
var hash = md5.New(original)

But obviously this is not how it works. Can someone provide me a working sample for this?

A: Here is a function you could use to generate an MD5 hash:
// MD5 hashes using md5 algorithm
func MD5(text string) string {
    algorithm := md5.New()
    algorithm.Write([]byte(text))
    return hex.EncodeToString(algorithm.Sum(nil))
}

I put together a group of those utility hash functions here: https://github.com/shomali11/util
You will find FNV32, FNV32a, FNV64, FNV65a, MD5, SHA1, SHA256 and SHA512

A: I found this solution to work well
package main

import (
    "crypto/md5"
    "encoding/hex"
    "fmt"
)

func main() {
    var str string = "hello world"

    hasher := md5.New()
    hasher.Write([]byte(str))
    fmt.Println(str)
    fmt.Println(hex.EncodeToString(hasher.Sum(nil)))
}

A: From crypto/md5 doc:
package main

import (
    "crypto/md5"
    "fmt"
    "io"
)

func main() {
    h := md5.New()
    io.WriteString(h, "The fog is getting thicker!")
    fmt.Printf("%x", h.Sum(nil))
}

A: just another answer
// MD5 hashes using md5 algorithm
func MD5(text string) string {
    data := []byte(text)
    return fmt.Sprintf("%x", md5.Sum(data))
}

A: I use this to MD5 hash my strings:
import (
    "crypto/md5"
    "encoding/hex"
)

func GetMD5Hash(text string) string {
    hasher := md5.New()
    hasher.Write([]byte(text))
    return hex.EncodeToString(hasher.Sum(nil))
}

A: import (
    "crypto/md5"
    "encoding/hex"
)

func GetMD5Hash(text string) string {
   hash := md5.Sum([]byte(text))
   return hex.EncodeToString(hash[:])
}

A: Reference Sum,For me,following work well:
package main

import (
    "crypto/md5"
    "fmt"
)

func main() {
    data := []byte("hello")
    fmt.Printf("%x", md5.Sum(data))
}


text:
Q: MSSQL Unexpected output of the binary field in XML I tried to get a binary(16) for my XSLT Project in a XML File to transformat it.
Here is, what I tried:
SELECT BINARY_ID FROM dbo.MyTable

SELECT CONVERT(varbinary(16), BINARY_ID) AS BINARY_ID  FROM dbo.MyTable

SELECT CAST(BINARY_ID AS varbinary(20)) AS BINARY_ID FROM dbo.MyTable

SELECT CONVERT(BINARY(16), BINARY_ID) AS BINARY_ID  FROM dbo.MyTable

SELECT CAST(BINARY_ID AS binary(20)) AS BINARY_ID FROM dbo.MyTable

What ever I tried, my BINARY_ID changed from 0x00D25E18AEFF4979A244C2EB132791C1 to ANJeGK7/SXmiRMLrEyeRwQ==
I am using a JDBC Connector for the Connection and to get the Data from the Database.
I'm starting to have no idea, what my problem cause.
Is my project possible at all or do I have to combine it with something else to achieve this?
Thanks in advance for the help.
UPDATE

Here is my XSLT Script which is powered over a Java compiler in to a JDBC Connector

<?xml version="1.0" encoding="UTF-8"?>
  <xsl:output media-type="text/xml" method="xml"></xsl:output>
  <xsl:template match="/">
    <root>
      <statement format="yyyy-MM-dd' 'hh:mm" resulttag="object_II" timezone="UTC">
        <sql>
            SELECT
                AD.GGUID,
                AD.COMPNAME AS Firmen_Name_1,
                AD.COMPNAME2 AS Firmen_Name_2,
                AD.GWBRANCH AS Branche,
                AD.COUNTRY1 AS Land,
                AD.STREET1 AS Straße,
                AD.ZIP1 AS PLZ,
                AD.TOWN1 AS Ort,
                AD.GWSTATE1 AS Bundesland,
                AD.PHONEFIELDSTR10 AS Telefon_Nr,
                AD.MAILFIELDSTR5 AS EMail
            FROM dbo.TABLE_I AS CL
            inner join dbo.TABLE_II AS AD ON AD.GGUID = CL.TABLEGUID
                Where CL.TABLENAME = 'ADDRESS'
                    AND CL.FIELDNAME = 'CHECKBOX'
                    AND AD.CHECKBOX= 1
                    AND AD.UPDATETIMESTAMP BETWEEN DATEADD(MINUTE, -60, SYSDATETIME()) AND SYSDATETIME()
            Order BY ad.GGUID DESC
        </sql>
    </statement>
    </root>
  </xsl:template>
</xsl:stylesheet>

A: Hint: the function varbintohexstring() is limited... I'd use CONVERT() here.
In the beginning a HEX-string was the default format for embedding binaries within XML. With v2005 this was changed to Base64 as it can represent a binary value with less characters.
Try this:
DECLARE @someGuid UNIQUEIDENTIFIER = NEWID();

SELECT @someGuid AS TheGuid
      ,CAST(@someGuid AS BINARY(16)) binValue_Base64
      ,CONVERT(VARCHAR(25),CAST(@someGuid AS BINARY(16)),1) binValue_HexString
FOR XML PATH('test');

The result
<test>
  <TheGuid>67D4B263-CEDC-4164-AA32-B7F8F6DCA946</TheGuid>
  <binValue_Base64>Y7LUZ9zOZEGqMrf49typRg==</binValue_Base64>
  <binValue_HexString>0x63B2D467DCCE6441AA32B7</binValue_HexString>
</test>

The idea in short:

*

*You seem to talk about a GUID, but the following holds true for any other value.

*The GUID is a very special type of value, as it is a binary but uses its very special format for representation.

*Within XML, which is a text based container, any value must be represented by printable characters (well, not talking about entities here...)

*Casting a GUID to BINARY(16) will lead to a Base64 encoded value in XML.

*But you can use CONVERT() to cast a BINARY to VARCHAR, which will result in a HEX string Read the section binary styles for details)

Both string values can be re-translated to the original GUID (67D4B263-CEDC-4164-AA32-B7F8F6DCA946):
  DECLARE @base64 VARCHAR(25)='Y7LUZ9zOZEGqMrf49typRg==';

  SELECT CAST(@base64 AS xml).value('.','binary(16)') Base64_as_binary
        ,CAST(CAST(@base64 AS xml).value('.','binary(16)') AS UNIQUEIDENTIFIER) TheOriginalGuid

  DECLARE @HexString VARCHAR(25)='0x63B2D467DCCE6441AA32B7';

  SELECT CONVERT(BINARY(16),@HexString,1) Hex_as_binary
        ,CAST(CONVERT(BINARY(16),@HexString,1) AS UNIQUEIDENTIFIER) TheOriginalGuid

A: I fixed it by my own by using the master function varbintohexstr
Here is my complete MSSQL Statement.
            SELECT
                UPPER(master.sys.fn_varbintohexstr(AD.GGUID)) AS GGUID,
            FROM dbo.TABLE_I AS CL
            inner join dbo.TABLE_II AS AD ON AD.GGUID = CL.TABLEGUID
                Where CL.TABLENAME = 'ADDRESS'
                    AND CL.FIELDNAME = 'Checkbox'
                    AND AD.Checkbox = 1
                    AND AD.UPDATETIMESTAMP BETWEEN DATEADD(MINUTE, -960, SYSDATETIME()) AND SYSDATETIME()
            Order BY ad.GGUID DESC

RESAULT:
0X00D25E18AEFF4979A244C2EB132791C1


text:
Q: If the General Counter-Spell exists, why are there specific counter-curses? If a combined Finite could stop Grindelwald's extremely powerful Protego Diabolica, and various spells like the ones in the Duelling Club orchestrated by Severus Snape and Gilderoy Lockhart, why are there specific counter-curses, counter-jinxes, counter-hexes, and counter-spells? If Finite was that powerful, why would there be a need for these other spells?

A: Magical Arms Race
We know Finite Incantatum (Finite) can end many spells.  Likewise "protego" can block many spells.  But "many" is not the same as "all".  We likewise know that there's at least one spell, Avada Kadavra, that is unblockable by any means.  We also know that specific counter-jinxes/curses/spells exist.
Ergo, we can assume that there is some subset of spells that, for whatever reason, bypass finite and/or protego.  That makes them exceptionally good combat spells, since they not only ignore the "normal" general counter-spells, but more importantly can "trick" an ignorant opponent into trying to block them anyway because if you don't know "Spell X" bypasses protego/finite, you stand there and try to block it with protego/finite, get hit, and lose the duel.  On the other hand, if you know the specific counter-curse for "Spell X" not only can you stand there and block it (and therefor be able to fight back easier than if you were dodging all over the place) but you also gain some element of surprise against your attacker (who may not know the spell has a specific counter-curse or assumes you don't know it). I would argue that the more exotic spells we see in wizard duels (dumbledore v voldy in Book 5 for instance) are spells with specific counter-curses that bypass the "normal" defensive spells.  Which is why when harry watches Dumbledore v voldy he doesn't see signs that spells are ceasing (as in finite) or the bubble/shield of protego. Instead he sees both wizards conjuring up specific counters, because the normal ones simply would not work.
I should state that this is all conjecture as I don't believe the answer is said outright anywhere, but there's enough evidence for me to accept it as true until proven otherwise!


text:
Q: vue.js - unable to change the state of the message I have the following message in my login.vue
<p v-if="registered" class="greenbg white p-3 text-justify">
       {{message}}
 </p>

I have the following data property
         data(){
            return{

                email: '',
                password: '',
                role: 'issuer',
                message: this.$store.state.message,
                registered: this.$store.state.registered

            }
        }

I have used
this.$store.dispatch('ilogin',{//some data for verification})

In store index.js i have an action of sending a get request.
  actions: {

  ilogin({commit},authData){

        axios.post('/login', {
        //some data
      })
      .then((res) => {

        //do something
      })
      .catch((error) => {

        commit('noauthUser',{
          message: error.response.data.message
        })

      })
  }
}

In mutation section i have the following mutation
  mutations: {

         noauthUser(state, noauthData){

         state.message = noauthData.message,
         state.registered = true

     }

   }

i am unable to show the message though the vue developer tool says the value has been updated.

Any particular reason for this behavior

A: As the data in the store may change, you need to define message and registered as computed properties. You can also use mapGetters:
computed: mapGetters(['message', 'registered'])
Don't forget to import mapGetters from Vuex


text:
Q: LSTM prediction. How can I start a prediction? I have a problem with the prediction. The program is designed to predict stock market prices. Here EUR / USD.
I trained the model and tested it with the test data. The results look good. At this point I can't get any further.
How can I make a prediction?
I tested the program with data from yesterday.
How can I predict today's data?
What should I enter and in what format?
import math
import matplotlib.pyplot as plt
import keras
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout
from keras.layers import *
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
from keras.callbacks import EarlyStopping

daten=open("C:")
df = pd.read_csv(daten)
df

training_set = df.iloc[436065:438073, 4:5]
test_set = df.iloc[438074:438170, 4:5]

sc = MinMaxScaler(feature_range = (0, 1))
training_set_scaled = sc.fit_transform(training_set)

X_train = []
y_train = []

for i in range(70, 2000):
    X_train.append(training_set_scaled[i-70:i, 0])
    y_train.append(training_set_scaled[i, 0])

X_train, y_train = np.array(X_train), np.array(y_train)
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))

n=50
dop=0.1

model = Sequential()#1
model.add(LSTM(units = n, return_sequences = True, input_shape = (X_train.shape[1], 1)))

model.add(Dropout(dop))#2
model.add(LSTM(units = n, return_sequences = True))

model.add(Dropout(dop))#3
model.add(LSTM(units = n, return_sequences = True))

model.add(Dropout(dop))#4
model.add(LSTM(units = n, return_sequences = True))

model.add(Dropout(dop))#5
model.add(LSTM(units = n, return_sequences = True))

model.add(Dropout(dop))#6
model.add(LSTM(units = n, return_sequences = True))

model.add(Dropout(dop))#7
model.add(LSTM(units = n))

model.add(Dropout(dop))
model.add(Dense(units = 1))

model.compile(optimizer = 'adam', loss = 'mean_squared_error')

model.fit(X_train, y_train, epochs = 100, batch_size =32)

dataset_total = pd.concat((training_set, test_set), axis = 0)
inputs = dataset_total[len(dataset_total) - len(test_set) - 70:].values
inputs = inputs.reshape(-1,1)
inputs = sc.transform(inputs)

type(inputs.shape)

X_test = []

for i in range(70, 167):
    X_test.append(inputs[i-70:i, 0])

X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

print(X_test.shape)

predicted_stock_price = model.predict(X_test)

predicted_stock_price = sc.inverse_transform(predicted_stock_price)

predicted_stock_price.shape

plt.plot(df.loc[438074:438170, "Close"])

plt.grid(True)

plt.plot(predicted_stock_price)
plt.grid(True)


text:
Q: undefined method 'id' for nil:NilClass -- edit route won't work

I'm not really sure why I'm getting the error. Every other route works except for this one.
I have also attached the code for my controllers and views below
BooksController
class BooksController < ApplicationController
  get '/books' do
    if logged_in?
      @books = Book.all
      erb :'books/index'
    else
      redirect to '/login'
    end
  end

  get '/books/new' do
    if logged_in?
      erb :'books/new'
    else
      redirect to '/login'
    end
  end

  post '/books' do
    @book = Book.create(:title => params[:title], :author => params[:author])
    if @book.save
      redirect to "/books/#{@book.id}"
    else
      redirect to '/books/new'
    end
  end

  get '/books/:id' do
    if logged_in?
      @book = Book.find_by_id(params[:id])
      erb :'books/show'
    else
      flash[:message] = "Please login to access your library."
      redirect to '/login'
    end
  end

  get '/books/:id/edit' do
    if logged_in?
      @book = Book.find_by_id(params[:id])
      if @book.user_id == current_user.id
        erb :'books/edit'
      else
        redirect to '/books'
      end
    else
      redirect to '/login'
    end
  end

  patch '/books/:id' do
    if params[:title] == "" || params[:author] == ""
      redirect to "/books/#{params[:id]}/edit"
    else
      @book = Book.find_by_id(params[:id])
      @book.title = params[:title]
      @book.author = params[:author]
      @book.save
      redirect to "/book/#{@book.id}"
    end
  end

  delete '/books/:id/delete' do
    if logged_in?
      @book = Book.find_by_id(params[:id])
      @book.user_id == current_user.id
      @book.delete
      redirect to '/books'
    else
      redirect to '/login'
    end
  end

end

UsersController
class UsersController < ApplicationController
   get '/' do
    erb :'index'
  end

  get '/users/:slug' do
      @user = User.find_by_slug(params[:slug])
      erb :'users/show'
  end

  get '/signup' do
    if !logged_in?
      erb :'users/new'
    else
      redirect to '/books'
    end
  end

  get '/login' do
    if !logged_in?
      erb :'users/login'
    else
      redirect to '/books'
    end
  end

  post '/signup' do
    @user = User.new(:username => params[:username], :email => params[:email], :password => params[:password])
    if params[:username].nil? || params[:email].nil? || params[:password].nil?
      flash[:message] = "Please fill the form completely."
      redirect to '/signup'
    else
      @user.save
      session[:user_id] = @user.id
      redirect to '/books'
    end
  end

  post '/login' do
    @user = User.find_by(:username => params[:username])
    if @user && @user.authenticate(params[:password])
      session[:user_id] = @user.id
      redirect to "/users/#{@user.slug}"
    else
      flash[:message] = "Try again."
      redirect to '/login'
    end
  end

  get '/logout' do
    if logged_in?
      session.clear
      redirect to '/login'
    else
      redirect to '/'
    end
  end

end

Edit View
<h1> Edit Your Book </h1>

<form method="POST" action="/books/<%= @book.id %>">
  <input id="hidden" type="hidden" name="_method" value="PATCH">
  <input type="text" name="title" value="<%= @book.title %>">
  <input type="text" name="author" value="<%= @book.author %>">
  <input type="submit" value="Submit" id="submit">
</form>

A: This is happening because you are trying to access /books/edit instead of /books/1/edit. Check the link that you are creating for editing a book.

A: In your controller you have defined your route as patch
patch '/books/:id' do
  if params[:title] == "" || params[:author] == ""
    redirect to "/books/#{params[:id]}/edit"
  else
    @book = Book.find_by_id(params[:id])
    @book.title = params[:title]
    @book.author = params[:author]
    @book.save
    redirect to "/book/#{@book.id}"
  end
end

And your form says POST, change it..


text:
Q: How do I review code changes that are the result of syncing? At my current job we develop code on a release branch and then do a code review. After all rework is done the final changes are also synced/merged to the 'main branch'. We want to be sure that all changes are synced correctly. What's a good way to review this sync work?
Note: the initial versions of files in the release branch and 'main branch' can be different. Thus it doesn't always help to compare the latest version in the release branch with the latest version in the main branch. (You then still see the 'initial differences' between both branches, although you don't see any 'sync changes' anymore).
My idea was to compare the 'delta' on the release branch with the 'delta' on the main branch. By using the GNU diff tool I can generate these two delta's, and then compare them in a file compare tool. Is this a good idea?
Note: we use ClearCase.
Just to clarify: We can't (or don't want to) rebase the release brach to the main branch, just for code review. That would again be a possible way to make mistakes. The release branch contains the code which our customers run. The main branch is used for splitting of new release branches in the future.

A: You should update your version of the main branch against the latest version of the main branch, pulling in changes that have occurred since you branched off for your feature branch.  Once this is done you can then compare your differences alone.
Example using git:
First git rebase (or git merge but I prefer git rebasein case of code conflicts) the feature branch against the main branch.  You will need to resolve any code conflicts.
Then you can do a git diff directly to the main branch.
n.b. Do a git fetch first to make sure you are doing your rebase/merge and diff against the latest version of the main branch.
I don't know the syntax for ClearCase but the process will likely be similar.


text:
Q: Feedback about ActiveMQ. How about it? Is it worth? we are evaluating ActiveMQ and I whould like to know what you think about it. Any feedback is welcome.
EDIT:
actually, I need to know things like: how does it scale? What about stability? Is it stable enough for production environments? Memory consumption, etc.

A: Its been used in thousands of production environments, some examples are Sabre Holdings (travelocity,lastminute.com,etc),FAA,CERN,JPL, etc - so its proven to be robust and perform:

*

*Sabre -32k transactions per second -
that's reliable performance

*A large retailer (can't name them) -
10k+ stores, all connected with
real-time updates over ActiveMQ - that's scalability

A: Here's my opinion & experience, for what its worth.
We have been using ActiveMQ in production for almost 2 years.  We did have a couple of issues with ActiveMQ 5.1 that we had work arounds for, but since ActiveMQ 5.3 (we are using SNAPSHOT from July) we have not had any issues and have been happy.  Our system pushes an average of 60 msgs/sec through the system with peak volumes > 700 msgs/sec.  We run a single active/passive broker pair with persistence journaling via NFS mount to a dedicated NAS device.
--Steven

A: We have had customers move from ActiveMQ to FioranoMQ - they had the following problems that they reported -  found Active MQ configuring very cumbersome/difficult to the point of giving up;  and stability could not be achieved; support and documentation are a big issue as he said he can't get a working answer from them how to solve the problem which means even if they paid for support it might not help. Data loss prevention configs for non-persistant/persistant and stability are big concerns and ofcourse limitations on speed. Failure under peak conditions - eg. when message-rate
 spikes.


text:
Q: Singleton как область видимости Spring бинов по умолчанию. Причина связан ли тот факт, что singleton - Spring bean scope by default с тем обстоятельством, что обычно бины stateless?
Прошу разъяснений о возможной взаимосвязи состояния бина (statefull, stateless) с его областью видимости.


text:
Q: problems JSSOR Slider I have a big problem with jssor Slider I made a gallery with more photos when access from iphone 4 safari crashing only iphone 4. On iphone 5 I don't have this problem.
function ScaleSlider() {
    var parentWidth = jssor_slider2.$Elmt.parentNode.clientWidth;
    if (parentWidth)
        jssor_slider2.$ScaleWidth(Math.min(parentWidth, 960));
    else
        window.setTimeout(ScaleSlider, 30);
}

ScaleSlider(); // Here is the problem when the page loading...

$(window).bind("load", ScaleSlider);
$(window).bind("resize", ScaleSlider);
$(window).bind("orientationchange", ScaleSlider);

A: There are 3 ways to reduce the impact, please kindly have a try.
1. Set $AutoPlay option to false and then make it auto play by api call (jssor_slider2.$Play();) after the first scale.
function ScaleSlider() {
    var parentWidth = jssor_slider2.$Elmt.parentNode.clientWidth;
    if (parentWidth)
        jssor_slider2.$ScaleWidth(Math.min(parentWidth, 960));
    else
        window.setTimeout(ScaleSlider, 30);
}

ScaleSlider(); // Here is the problem when the page loading...
jssor_slider2.$Play();

$(window).bind("load", ScaleSlider);
$(window).bind("resize", ScaleSlider);
$(window).bind("orientationchange", ScaleSlider);

2. Set $HWA option to false to disable hardware acceleration.
3. Define image in lazy loading format to reduce loading at the beginning.


text:
Q: How to display events text in codeigniter calendar? I am using Codeigniter 3.0 Calendar Library, I am not getting event text in my CI calendar, Instead of displaying event text it shows link on the number.
Sample Codeigniter Code:
class Welcome extends CI_Controller {

    function index()
    {
        $this->display($year = null, $month = null);
    }
     public function display($year = null, $month = null)
    {
            $config = array(
            'show_next_prev' => TRUE,
            'show_other_days' => TRUE,
            'next_prev_url' => site_url('welcome/display')
            );
            $events = array(
                1 =>'test1',
                2 =>'test2'
            );
            $this->load->library('calendar', $config);
            echo $data['calendar'] = $this->calendar->generate($year, $month, $events);

    }
}

Sample Calendar image (output of above code) :

In the above calender you can see 1st and 2nd days are linked and not displaying events text like test1 and test2 in the calendar, how can i rectify this?

A: You can modify any piece of calendar template, change content and just provide data. For example you can provide title attribute inside a element, to use it as simple tooltip on hover, or adjust html to provide more sophisticated ui interaction. Take a look:
$prefs['template'] = array(
        'cal_cell_content'       => '{content}',
        'cal_cell_content_today' => '
{content}
'
    );
    $this->load->library('calendar', $prefs);
    $data = array(
        3  => 'My event',
        7  => 'Conference',
        13 => 'Lecture',
        26 => 'City walk'
    );

    echo $this->calendar->generate(2015, 6, $data);


text:
Q: OWIN SelfHost Web Api - Request Cancellation - How is it done? Thread aborts? Could someone point me to a resource that would help explain how web api (specifically using Owin Self Host) handles request cancellation?
Here's the sequence of events i'm observing:

*

*someone makes a GET from chrome

*Api controller (through some layers) fires off an async SQL query

*someone hits the X button in chrome (i don't know exactly what happens on socket for this)

What happens next in Web Api??
There was some code running in a controller, does the thread running it get aborted? If it was an async controller awaiting another Task, does that task still have an awaiter in case it returns with an exception?
For context: I do have an async controller awaiting a Task (this is the only call site) which looks to be throwing an unobserved exception in some edge cases. I haven't been able to isolate or re-produce yet :)
I did find something called HttpResponse.ClientDisconnectedToken, but don't know well that is supported in Owin Selfhost + is it even the good thing to use for all user cancels.

A: I've dealt with this by handing the System.OperationCanceledException in a custom middleware I've registered before WebApi.
public class ExceptionHanldingMiddleware : OwinMiddleware
{
    public override async Task Invoke(IOwinContext context)
    {
        try
        {
            await Next.Invoke(context);
        }
        catch (OperationCanceledException) when (context.Request.CallCancelled.IsCancellationRequested)
        {
            //swallow user-agent cancelling request.
            _log.Trace($"client disconnected on request for: {context.Request.Path}.");
        }
        catch (Exception ex)
        {
            _log.Error(ex);
            context.Response.StatusCode = (int) HttpStatusCode.InternalServerError;
            context.Response.ReasonPhrase = "Internal Server Error";
        }
    }
}

A: As you stated that your async controller is awaiting for a Task, which sometimes got some exception, I suggest you ContinueWith extension method for a task, which can be run only then your task is faulted, like this:
task.ContinueWith(
       t =>
       logger.Error(t.Exception.Message, t.Exception);
       , TaskContinuationOptions.OnlyOnFaulted);

This is a default mechanism to handle the exceptions, and this will work in OWIN application.
Second, as for the cancellation: task can be started with a CancellationToken structure, which can be used for a cancelling the task during the execution. You can read more in the MSDN article.
HttpResponse.ClientDisconnectedToken is used for a situation when the client has been disconnected and the request should not be proceed in execution.
You can use this token, or create your own with CancellationTokenSource, like this:
var source = new CancellationTokenSource();
var token = source.Token;

var task = Task.Factory.StartNew(() =>
{

    // Were we already canceled?
    ct.ThrowIfCancellationRequested();

    var moreToDo = true;
    while (moreToDo)
    {
        // Poll on this property if you have to do
        // other cleanup before throwing.
        if (ct.IsCancellationRequested)
        {
            // Clean up here, then...
            ct.ThrowIfCancellationRequested();
        }

    }
}, token);


text:
Q: Need to merge multiple data frames by multiple common columns I have 5 common data frames that differ by year:
2010
POLY STRA  Spp  breeders2010 nonbreeders2010
1      1   mall     20             5
1      1   cite     6              0
1      3   mall     10             0
2      1   gadw     6              2

2011
POLY STRA  Spp  breeders2011 nonbreeders2011
1      1   mall     24             2
1      1   cite     8              2
1      3   mall     14             4
2      1   gadw     8              4

2012
POLY STRA  Spp  breeders2012 nonbreeders2012
1      1   mall     20             5
1      1   cite     6              0
1      3   mall     10             0
2      1   gadw     6              2

I need to merge these 5 data frames by POLY, STRA and Spp such that the final result looks like:
POLY STRA  Spp  breeders2010 nonbreeders2010 breeders2011 nonbreeders2011 breeders2012 nonbreeders2012 breeders2013 nonbreeders2013 breeders2014 nonbreeders2014
1      1   mall     20            5               24            2             20             5 .....
1      1   cite     6             0               8             2             6              0 ......
1      3   mall     10            0               14            4             10             0 .....
2      1   gadw     6             2               8             4             6              2 .....

I have tried merge and cbind and I cannot get columns to line up properly.

A: I think merge should be just fine.
For several data frames you can use Reduce:
Reduce(merge, list(df1, df2, df3, df4, df5))

If there are any missing rows in any of the data frames all = TRUE may help:
Reduce(function(x, y) merge(x, y, all = TRUE), list(df1, df2, df3, df4, df5))


text:
Q: PlayN - Bad rendering performance on iOS We have a game that runs pretty smoothly on Android but the game is unplayably slow on iOS especially on iPhone 4. We have found some candidates what may be delaying the game rendering but still the overall performance is quite bad.
The following insights can be written down:

*

*We are quite sure that something in PlayN rendering loop may be the main reason of bad perfomance. Effect of disabling physics simulation and game update computations is marginal, while it is 70% of computing time on Android).

*There is no significant dependency on screen resolution (retina/non-retina) so insufficient fill rate could be eliminated.

*Avoiding CanvasLayers and SurfaceLayers usage has only minor effect - most of the game are just moving ImageLayers.

*Vector text labels rendering (from Triple Play) is slightly slower but marginal.

*Composite operation is even slower but still not the main cause.

The question/s:
Do you know any other PlayN operation that may be slow on iOS platform and should (and could) be avoided? Is there any way how to get symbols to XCode profiler to get better knowledge of the main holdups in the game? Is there any other tool we can use for PlayN internals profiling?
Thanks for any experience with iOS performance problems.

A: Have to say that GWT JBox2d (in PLAYN v1.4,v1.5 last releases) are EXTREMELY SLOW on Android.
Just add >50 bodies and it starts hangs and drop down framerate.
Really thinking about Nape or native libs ... Google -_-


text:
Q: sending request with token not work in MVC? I use web model-view-controller ( i use it at two project) and I'm trying to send this request to UpdatePasswordFirstTime but I have a problem with the authentication and it directs me to log in. I tried to go to data with the same token from Postman it still just directs me to login page.
Note: I use Identity Server in response function UpdatePasswordFirstTime
public async Task<ActionResult> UpdatePasswordFirstTime1(UserPasswordChangeResourcesFirstTime resources)

     var valtoken = claim.GetAccessToken().Result;
                _httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", claim.GetAccessToken().Result);

                var response = await _httpClient.PostAsJsonAsync(JsonAppSettings.GetIdentityServerUrl() + "Users/UpdatePasswordFirstTime", new { Id =resources.Id, Password =resources.Password, ConfirmPassword =resources.ConfirmPassword});

                if (response.IsSuccessStatusCode)
                {
                    return new SignOutResult(new[] { CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme });
                }

                return new SignOutResult(new[] { CookieAuthenticationDefaults.AuthenticationScheme, OpenIdConnectDefaults.AuthenticationScheme });

            }

// the response function
another mvc

     [Authorize]
          [HttpPost]
          [ValidateAntiForgeryToken]

public async Task<ActionResult> UpdatePasswordFirstTime([FromBody] UserPasswordChangeResourcesFirstTime resources)
{
            {

                try
                {
                    //do something
                }

                catch (Exception ex)
                {
                    //do something
                    throw;
                }
            }


text:
Q: File does NOT exist but ls shows "No such file or directory" error File system ext4 //
which ls -> /bin/ls //
Bash -> 3.2.57(2)-release //
whoami -> admin

If I run ls then I firstly get a list of files with error

"No such file or directory"

and then the healthy files of the directory.
The folder that contains these bad files has an unusual size:

Concerning the files with error, I cannot:

*

*delete the file

*copy the file

*move the file

*delete the directory since it is not empty (rm -r [DirectoryName])

*Bad files are not shown/listed on either Mac OS nor MS-Windows
I can:

*

*Move the content of the directory (mv) including bad files

*Get tab to complete the name of the bad file
Any hint? Either to delete them or to recover them.

A: As per comment - the solution was to unmount and fsck the filesystem (using e2fsck or fsck.ext4).
It would seem that the filesystem got corrupted - possibly due to a sudden outage while writing to the disk - and the filesystem would have detected the problem and locked itself until repaired to prevent further damage to itself.


text:
Q: Compute shader can't get result image I am using the compute shader to get a column of colors to match the conditions and I want to get the results for further processing. I want to get the output data in image1D imgOutput, but get_img can't get anything, did I do something wrong?
the texture in the first block has been generated before.
Shader spriteRowProgram, spriteColumnProgram;
unsigned int resultTexture = 0;
const std::string path = found::utils::Environment::GetRunPath();
const std::string sprite_row_path = path + "shaders/glfw_sprite_row.comp";
spriteRowProgram = Shader(sprite_row_path);
std::vector<GLfloat> get_img(qMax(TEX_WIDTH, TEX_HEIGHT) * 4);
glGenTextures(1, &resultTexture);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_1D, resultTexture);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_1D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage1D(GL_TEXTURE_1D, 0, GL_RGBA32F, qMax(TEX_WIDTH, TEX_HEIGHT), 0, GL_RGBA, GL_FLOAT, get_img.data());

glActiveTexture(GL_TEXTURE0 + 1);
glBindTexture(GL_TEXTURE_2D, texture);

spriteRowProgram.use();
glUniform1i(1, 1);
glBindImageTexture(1, texture, 0, GL_FALSE, 0, GL_READ_ONLY, GL_RGBA32F);
glUniform1i(0, 0);
glBindImageTexture(0, resultTexture, 0, GL_FALSE, 0, GL_WRITE_ONLY, GL_RGBA32F);
glClear(GL_COLOR_BUFFER_BIT);

spriteRowProgram.setInt("input_width", TEX_WIDTH);
spriteRowProgram.setInt("input_height", TEX_HEIGHT);
glDispatchCompute(TEX_WIDTH, 1, 1);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);

#version 430 core
layout (local_size_x = 1, local_size_y = 1) in;
layout(rgba32f, location = 0, binding = 0) uniform writeonly image1D imgOutput;

// texture samplers
layout(rgba32f, location = 1, binding = 1) uniform readonly image2D inputImage;
uniform int input_width;
uniform int input_height;

void main()
{
    vec4 baseColor = imageLoad(inputImage, ivec2(0, 0));
    bool alpha = baseColor.w == 1;
    bool success = true;
    for (int i = 0; i <= input_height; ++i)
    {
        vec4 current = imageLoad(inputImage, ivec2(gl_GlobalInvocationID.x, i));
        if (alpha) {
            if (current.w > 0.99) continue;
            else {
                success = false;
                break;
            }
        } else {
            vec4 difference = baseColor - current;
            success = abs(difference.x) < 0.01 && abs(difference.y) < 0.01 && abs(difference.z) < 0.01;
            if (success) continue;
            else {
                break;
            }
        }
    }
    if (success) baseColor = ivec4(0.1, 0.1, 0.1, 0.1);
    else baseColor = ivec4(1.0, 1.0, 1.0, 1.0);
    imageStore(imgOutput, int(gl_GlobalInvocationID.x), baseColor);
}

A: One issue might be that if you want to access images after the compute shader, the argument for glMemoryBarrier should be GL_SHADER_IMAGE_ACCESS_BARRIER_BIT and not GL_SHADER_STORAGE_BARRIER_BIT.
So
spriteRowProgram.setInt("input_width", TEX_WIDTH);
spriteRowProgram.setInt("input_height", TEX_HEIGHT);
glDispatchCompute(TEX_WIDTH, 1, 1);
glMemoryBarrier(GL_SHADER_STORAGE_BARRIER_BIT);

should really be
spriteRowProgram.setInt("input_width", TEX_WIDTH);
spriteRowProgram.setInt("input_height", TEX_HEIGHT);
glDispatchCompute(TEX_WIDTH, 1, 1);
glMemoryBarrier(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT);


text:
Q: booting stops at "[OK] Reached Target Graphical Interface" after uninstalling NVidia drivers I've installed drivers from nVidia Graphics Drivers repo in OpenSuse 13.1. The drivers didn't work well so I've uninstalled them. After this X-Windows would not start at all, with the last message:
[OK] Reached Target Graphical Interface

What happened?

A: It's the same problem as with ATI drivers, as discussed on OpenSuse forum 2 years ago:
ATI Driver installs have destroyed SUSE/GNOME graphics setup
Uninstalling RPMs doesn't revert changes made during installation and leaves system with:

*

*symlink /var/lib/X11/X pointing to nonexistent /usr/bin/X.x11-video-nvidiaG03 (it should be reverted to point to /usr/bin/Xorg)

*changed DISPLAYMANAGER_XSERVER value in /etc/sysconfig/displaymanager (it should be changed back to Xorg)
(The link above has more details. But it took me a couple of hours of reading logs, rebooting and googling to find it. Maybe this Q&A will save someone's time).


text:
Q: Java 8 Applying stream filter based on a condition In Java 8, is there a way to apply the filter on a stream based on a condition,
example
I have this stream
if (isAccessDisplayEnabled) {
     src = (List < Source > ) sourceMeta.getAllSources.parallelStream()
         .filter(k - > isAccessDisplayEnabled((Source) k))
         .filter(k - > containsAll((Source) k, substrings, searchString))
         .collect(Collectors.toList());
 } else {
     src = (List < Source > ) sourceMeta.getAllSources.parallelStream()
         .filter(k - > containsAll((Source) k, substrings, searchString))
         .collect(Collectors.toList());
 }

I am adding the filter
.filter(k - > isAccessDisplayEnabled((Source) k)))

on the stream based on the if-else condition. Is there a way to avoid that if-else, since if there are more filters coming up,then it will be hard to maintain.
Please let me know

A: One way to do it is
Stream<Source> stream = sourceMeta.getAllSources.parallelStream().map(x -> (Source)x);
if(isAccessDisplayEnabled) stream = stream.filter(s -> isAccessDisplayEnabled(s));
src = stream.filter(s - > containsAll(s, substrings, searchString))
            .collect(Collectors.toList());

another
 src = sourceMeta.getAllSources.parallelStream().map(x -> (Source)x)
     .filter(isAccessDisplayEnabled? s - > isAccessDisplayEnabled(s): s -> true)
     .filter(s - > containsAll(s, substrings, searchString))
     .collect(Collectors.toList());

In either case, note how performing one type cast at the beginning simplifies the entire stream pipline.
Both solutions avoid re-evaluating isAccessDisplayEnabled for every stream element, however, the second relies on the JVM's capability of inlining s -> true when this code turns out to be performance critical.

A: Your condition has the same name as your method. I'm going to assume you meant for those to be different, so let's say it was this:
if (someCondition) {
    src = (List < Source > ) sourceMeta.getAllSources.parallelStream()
        .filter(k - > isAccessDisplayEnabled((Source) k))
        .filter(k - > containsAll((Source) k, substrings, searchString))
        .collect(Collectors.toList());
} else {
    src = (List < Source > ) sourceMeta.getAllSources.parallelStream()
        .filter(k - > containsAll((Source) k, substrings, searchString))
        .collect(Collectors.toList());
}

If you want to remove the if/else, you can instead perform the check in the first filter:
src = (List < Source > ) sourceMeta.getAllSources.parallelStream()
    .filter(k - > !someCondition || isAccessDisplayEnabled((Source) k))
    .filter(k - > containsAll((Source) k, substrings, searchString))
    .collect(Collectors.toList());

In the else case, you take everything and remove the isAccessDisplayEnabled() method call, so the condition is effectively "if someCondition is false or isAccessDisplayEnabled(k)". If someCondition comes out false, then the isAccessDisplayEnabled() check is skipped.


text:
Q: MSBuild not updating NuGet references when building with PackageVersion Property I've got two .NetStandard NuGet Packages that I'm building in the same solution (A and B)
A has a project reference to B.
By default, when I build in VS it will create me a NuGet package for both projects.
The package A.1.0.0.nupkg will contain this dependency, which was automatically added by msbuild:
<dependency id="B" version="1.0.0" exclude="Build,Analyzers" />

That works fine, and its automatic which is great.
If I change the Package Version of B, to 2.0.0 and build, the line in A.nuspec will be automatically updated to:
<dependency id="B" version="2.0.0" exclude="Build,Analyzers" />

This is fantastic, and it works like magic.
Problem is, this does not work if I build using the PackageVersion property:
msbuild /p:PackageVersion="3.0.0"

I would expect that msbuild would create two nupkgs:

*

*A.3.0.0.nupkg

*B.3.0.0.nupkg
And it does. However, A.nuspec still has this dependency:
<dependency id="B" version="2.0.0" exclude="Build,Analyzers" />

I would expect it to be version="3.0.0"
Are there any workarounds for this? Is there a different way I should be configuring my packages?

A: At the moment (NuGet 4.5.0), the version is locked during the restore operation and not during the package build.
This will be changed in NuGet 4.6.0 (included in VS 15.6).
To work around this, use msbuild /restore /p:PackageVersion=3.0.0 instead.
See this GitHub issue for more details.


text:
Q: Spring RestTemplate Interceptor not execute request When I configure RestTemplate use HttpClient then my interceptor only execute for first time, in second time it'll hang up when execute, in this block below. There is no exception, I don't know why!
If I remove httpClient then no problem.
(My interceptor intention is catch 401 unauthorized status to refresh access token)
if (url.contains("/auth") || url.contains("/custcare-common")) {
    return execution.execute(request, body);
}

Full code below:
public class RestTemplateHeaderInterceptor implements ClientHttpRequestInterceptor {

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
    String url = request.getURI().getPath();
    if (url.contains("/auth") || url.contains("/custcare-common")) {
        return execution.execute(request, body);
    }

    HttpSession session = SessionBean.getSession();
    if (session != null) {
        // check header does not has token then add to header
        if (request.getHeaders().isEmpty() || !request.getHeaders().containsKey(HttpHeaders.AUTHORIZATION)) {
            // add jwt token to header
            Object accessToken = session.getAttribute(AppConstants.Token.ACCESS_TOKEN);
            if (accessToken != null) {
                request.getHeaders().add(HttpHeaders.AUTHORIZATION, SecurityConstants.TOKEN_PREFIX + accessToken);
            }
        }

        // refresh token when expire
        ClientHttpResponse response = execution.execute(request, body);
        if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            Object refreshToken = session.getAttribute(AppConstants.Token.REFRESH_TOKEN);
            if (refreshToken != null) {
                TokenData newTokenData = getNewToken(refreshToken.toString());
                if (newTokenData != null) {
                    session.setAttribute(AppConstants.Token.ACCESS_TOKEN, newTokenData.getAccessToken());
                    session.setAttribute(AppConstants.Token.REFRESH_TOKEN, newTokenData.getRefreshToken());

                    request.getHeaders().set(HttpHeaders.AUTHORIZATION, SecurityConstants.TOKEN_PREFIX + newTokenData.getAccessToken());

                    return execution.execute(request, body);
                }
            }
        }
    }

    return execution.execute(request, body);
}

private TokenData getNewToken(String refreshToken) {
    TokenData tokenData = null;

    RefreshTokenRequest request = new RefreshTokenRequest();
    request.setRefreshToken(refreshToken);

    MessagesResponse<TokenData> response = RestUtil.post(RestUtil.getCcApiUrl("cc-api.authen.refresh-token"), request, new ParameterizedTypeReference<MessagesResponse<TokenData>>() {});

    if (response != null) {
        tokenData = response.getData();
    }

    return tokenData;
}

}
My RestTemplate config:
@Configuration
public class RestTemplateConfig {

    @Bean
    public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {
        PoolingHttpClientConnectionManager result = new PoolingHttpClientConnectionManager();
        result.setMaxTotal(20);
        return result;
    }

    @Bean
    public RequestConfig requestConfig() {
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000).setConnectTimeout(60000)
                .setSocketTimeout(60000).build();

        return requestConfig;
    }

    @Bean
    public CloseableHttpClient httpClient() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
        TrustStrategy trustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
                return true;
            }
        };
        SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, trustStrategy).build();
        SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
        CloseableHttpClient result = HttpClientBuilder.create()
                .setConnectionManager(poolingHttpClientConnectionManager())
                .setDefaultRequestConfig(requestConfig())
                .setSSLSocketFactory(csf)
                .build();

        return result;
    }

    @Bean
    @Primary
    public RestTemplate restTemplate() throws KeyManagementException, NoSuchAlgorithmException, KeyStoreException {
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient());

        RestTemplate restTemplate = new RestTemplate(requestFactory);

        restTemplate.setErrorHandler(new RestResponseErrorHandler());

        List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors();
        if (interceptors.isEmpty()) {
            interceptors = new ArrayList<>();
        }
        interceptors.add(new RestTemplateHeaderInterceptor());
        restTemplate.setInterceptors(interceptors);

        return restTemplate;
    }
}

Finally, I done deal with this issue by setting DefaultMaxPerRoute, but I still confuse about this. :D
@Bean
public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager() {
    PoolingHttpClientConnectionManager result = new PoolingHttpClientConnectionManager();
    result.setMaxTotal(100);
    result.setDefaultMaxPerRoute(100);
    return result;
}

A: This is an old question, but as people still come here via their search engine of choice and there was confusion about why the change "worked", this might save someone some time:
The issue stems from the original http response not being consumed in your custom Interceptor class, if a 401 is the response code.
Upping the ConnectionPool capacity only hides the problem (and may "fix" the issue for the application run), but does not actually release the connection back to the pool and fix the problem.
In your interceptor class, the 401 response is never consumed, just used for the StatusCode check. This response blocks one connection of the Pool. The 401 response needs to be manually consumed as its never handed down.
If a response has a 401 status, you execute a new request, and the original 401 response just blocks a connection forever. That's why there are no more connections available after a certain number of 401 requests (5 is default afaik). As no more connections are available in the ConnectionPool after those 5 401 requests, the thread just hangs around and the execute call never finishes since it's waiting for a free connection to use.
The required change? One line of code to save us the headache and the workaround, close the response after the 401 check (or any time a response is not returned/consumed):
public class RestTemplateHeaderInterceptor implements ClientHttpRequestInterceptor {

@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution)
        throws IOException {
        // ... omitted ...

        // refresh token when expire
        // THIS RESPONSE IS NEVER HANDLED
        ClientHttpResponse response = execution.execute(request, body);
        if (response.getStatusCode() == HttpStatus.UNAUTHORIZED) {
            // Close response only needed for the status code and refresh
            response.close();
            // Continue on with your code.
            Object refreshToken = session.getAttribute(AppConstants.Token.REFRESH_TOKEN);
            if (refreshToken != null) {
                // ... omitted ...
                    return execution.execute(request, body);
                }
            }
        }
    }

    return execution.execute(request, body);
}

There also is a convenience way for HttpEntities: org.apache.http.util.EntityUtils#consume when working with HttpEntites.
Note that a rerequest in an interceptor as done in this code for a 401 will not be passed through other interceptors added to the interceptorlist for the httpclient.

A: Can you try this
instead of below block of code i.e.
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient());
RestTemplate restTemplate = new RestTemplate(requestFactory);

try
RestTemplate restTemplate = new RestTemplate();
restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(clientHttpRequestFactory()));

see if this works for you.


text:
Q: Convert P-256 DH java string to java PublicKey I'm trying to send web push notifications to my browser and am able to subscribe successfully. I get a subscription object with "an elliptic curve Diffie–Hellman public key on P-256 curve".
I want to convert this string to a public key in Java but keep getting a invalid key format exception.
Here's the code that I'm trying:
  String publicK = "BBoN_OkTfE_0uObues82qHr96z8x3nepYoUwCBoftFDS_Vgx2MUHN1vAFxc1eDiyDrvmZ2bQ4sJq3F8Qz71RWI0=";
  byte[] publicBytes = publicK.getBytes();
  X509EncodedKeySpec keySpec = new X509EncodedKeySpec(publicBytes);
  KeyFactory keyFactory = KeyFactory.getInstance("DiffieHellman");
  PublicKey pubKey = keyFactory.generatePublic(keySpec);

Could someone help me with this please? Encryption noob here :/

A: For my code, I used java 1.7 and BouncyCastle library. If you use maven, just add to your pom.xml:
<dependency>
    <groupId>org.bouncycastle</groupId>
    <artifactId>bcprov-jdk16</artifactId>
    <version>1.46</version>
</dependency>

Or download the jars in BouncyCastle site. This is a cryptography API for java, with lots of useful stuff (including classes to handle elliptic curves keys).
The code for reading the public key and converting to an object is:
import java.security.KeyFactory;
import java.security.Security;
import java.security.interfaces.ECPublicKey;
import java.security.spec.ECPoint;
import java.security.spec.ECPublicKeySpec;

import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.ECPointUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.jce.spec.ECNamedCurveSpec;
import org.bouncycastle.util.encoders.Base64;

// you need to add the BouncyCastle provider to use its functionalities
Security.addProvider(new BouncyCastleProvider());

String publicK = "BBoN_OkTfE_0uObues82qHr96z8x3nepYoUwCBoftFDS_Vgx2MUHN1vAFxc1eDiyDrvmZ2bQ4sJq3F8Qz71RWI0=";
// publicK is encoded in base64, so you need to decode it first
byte[] publicBytes = Base64.decode(publicK.getBytes());

// spec for P-256 curve
ECNamedCurveParameterSpec spec = ECNamedCurveTable.getParameterSpec("prime256v1");
// create a KeyFactory with ECDSA (Elliptic Curve Diffie-Hellman) algorithm and use BouncyCastle as the provider
KeyFactory kf = KeyFactory.getInstance("ECDSA", BouncyCastleProvider.PROVIDER_NAME);

// code below just creates the public key from the bytes contained in publicK
// using the curve parameters (spec variable)
ECNamedCurveSpec params = new ECNamedCurveSpec("prime256v1", spec.getCurve(), spec.getG(), spec.getN());
ECPoint point = ECPointUtil.decodePoint(params.getCurve(), publicBytes);
ECPublicKeySpec pubKeySpec = new ECPublicKeySpec(point, params);
ECPublicKey pk = (ECPublicKey) kf.generatePublic(pubKeySpec);

System.out.println(pk.toString());

Output:
EC Public Key
            X: 1a0d00e9137c4034b8e6ee7acf36a87afdeb3f31de77a9628530081a1fb450d2
            Y: 15831d8c507375bc01717357838b20ebbe66766d0e2c26adc5f10cfbd51588d

Notes:

*

*I'm not aware of all the math behind elliptic curve keys, just the basic idea. I know that a curve has parameters like G and n (which are obtained via getG() and getN() methods) and that there are some "standard pre-defined" curves (like P-256) that you can get using ECNamedCurveTable.getParameterSpec().

*You can take a look at all the math details if you want. There is also a list of different standard curves and which ones are considered secure.

*ECPublicKey extends PublicKey, so you can use it just like a PublicKey


text:
Q: Using $pull with Deployd method I have a Deployd API which exposes a json structure like this:
[
  {id: "1"
   username: "john",
   password: " ..... ",
   email: "example@gmail.com",
   coins: 60,
   badges: [ ],
   courses:[
       { id: "123456",
         title: "Animals",
         grades_per_module: [ [30], [28, 26], [25, 24]]
         .....
       },
       { id: "112233",
         title: "Food",
         grades_per_module: [ [20, 25, 27], [22]]
         .....
       }
    ]
  },

  {id: "2"
   username: "mark",
   password: " ..... ",
   email: "ex@gmail.com",
   coins: 40,
   badges: [ ],
   courses:[
       { id: "123456",
         title: "Animals",
         grades_per_module: [ [27], [21, 30], [30, 30]]
         .....
       }
    ]
  }
]

Then I need to remove the intere course with id="112233" of the user "john"  using an angular code.
So I use this code, but it doesn't work:
this.http.put('http://localhost:2403/users/1',
              { "courses": { $pull: { "id": 112233 } }
             }).subscribe( ..... )

Deployd API returns me a positive message, but the course is not really removed from the user object.
Can anyone help me?


text:
Q: Cant send response with "POST" method on js node server Im trying to create a small login page.
My idea is to send the login data to the server who will check the username and the password and then send a response to the client saying that his login was found.
Here is the server:

const server = http.createServer(function(request, response) {
    let data;
    if (request.method == 'POST') {
      console.log('POST');
      const chunks = [];
      request.on("data", (chunk) => {
        chunks.push(chunk);
      });
      request.on("end", () => {
        console.log("all parts/chunks have arrived");
        data = JSON.parse(chunks.toString())
        console.log(data);
      });
      response.setHeader("Content-Type", "text/html")
      response.write("Hello")
      response.end()
    }
})

const port = 3300
const host = '//////////'
server.listen(port, host)
console.log(`Listening at http://${host}:${port}`)

And here the client:
const Http = new XMLHttpRequest();
const url='http://///////:3300';
Http.open("POST", url, "This is a test");
Http.send(JSON.stringify({username : Id.value, password : Pw.value}));

I have tried writing the respone but it causes errors.
What can I do to reply to the client?
(Vanilla Js Node/Javascript)

A: I dont know if im right but your url is http://///////3300 with 9 slashes
but in the server your host is ////////// with 10 slashes
maybe this is the problem


text:
Q: Print received data from client in NodeJS server I have a simple html file containing that piece of javascript:
<script type="text/javascript">
            $.ajax({
            url: 'http://192.168.X.X:8080',
            data: '{"data": "1"}',
            dataType: "jsonp",
            cache: false,
            timeout: 5000,
            success: function(data) {
                    var ret = jQuery.parseJSON(data);
                },
                error: function (xhr, status, error) {
                    console.log('Error: ' + error.message);
                    document.getElementById("error").innerHTML = 'Error: ' + error.message;
                }
            });
    </script>

I simply want my NodeJS server to print data received (there: the number 1°).
Here is my NodeJS code:
var http = require('http');
var s = http.createServer();
s.on('request', function(request, response) {
    response.writeHead(200);
    console.log('a: '+request.method);
    console.log('b: '+request.headers);
    console.log('c: '+request.url);
});
s.listen(8080);

Server is receiving requests just find but how to retrieve the value of the data sent?
I just want server to receive a number from client and print it. How to do that?
Many thanks1

A: If you just want to see jsonp works using the http module, you could use something like that (I wouldn't advise using this in any of your code, it's just for the demonstration):
var http = require('http');
var querystring = require('querystring');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  var query = querystring.parse(req.url.split('?')[1]);
  console.log(query);
  res.end(query.callback + '({"Name": "Foo", "Id": 1234, "Rank": 7})');
}).listen(8080);

Note: when using jquery jsonp data should better be an object, not a string (see https://learn.jquery.com/ajax/working-with-jsonp/)
You should, however, ask yourself:

*

*Why jsonp?

*Is there a module that does all that for you & parse JSON, help you with errors/authentication/etc? I usually use https://www.npmjs.com/package/hapi (It supports jsonp if you really need it), there other modules like express.

A: I think this does what your looking for.
#!/usr/bin/node

var http = require('http');
var s = http.createServer();
s.on('request', function(request, response) {
    response.writeHead(200);
    console.log('a: '+request.method);
    console.log('b: '+request.headers);
    console.log('c: '+request.url);

    var url = decodeURIComponent(request.url);
    var startPos = url.indexOf('{');
    var endPos = url.indexOf('}');
    var jsonString = url.substring(startPos, endPos+1);
    json = JSON.parse(jsonString);
    console.log(json['data'])
});
s.listen(8080);


text:
Q: SQL Server T-SQL search special characters In SQL Server, how to search special characters like square brackets?
I have tried using code below to search .
select *
from dbo.Content
where title like '%\[TESTING(TEST)(\[]%' escape '\'.

I need to manually put backslash in front of all square bracket in order to get the result. Does anyone know what query/function can use to query all kind of data especially special characters.

A: To search for [ just write [[]
Any special character can be escaped this way. So % will be [%]
Or maybe this suits more your question
REPLACE(REPLACE(REPLACE(@myString, '[', '[[]'), '_', '[_]'), '%', '[%]')

How to escape a string for use with the LIKE operator in SQL Server?

A: Instead of checking for Special character  we can check for alphanumeric and then have NOT (!) to get the row where title has special characters. (WHERE title  LIKE '%[^a-z0-9 .]%' )


text:
Q: How do I find this root? How can the third root of $\sqrt{x} - 2x + x^a$ be expressed in terms of a when $a>1.5$? (Obviously there is always one at 1 and 0)

A: Beside the trivial $x=0$ and $x=1$, the third solution of the equation
$$\sqrt{x} - 2x + x^a=0$$ is close to $\frac 14$ as soon as $a >3$.
So, we can have approximations using Taylor series. For example
$$0=4^{-a}+\left(4^{1-a} a-1\right) \left(x-\frac{1}{4}\right)-2^{-2 a} \left(-8 a^2+8
   a+4^{a}\right)
   \left(x-\frac{1}{4}\right)^2+O\left(\left(x-\frac{1}{4}\right)^3\right)$$ which is a quadratic in $\left(x-\frac{1}{4}\right)$.
Using only the first term (this would be equivalent to the first iterate of Newton method
$$x_1=\frac{1}{4}+\frac{1}{4^a-4 a}$$ is quite decent. For $a=3$, it would give $x=\frac 7{26}=0.269231$ while the "exact" solution is $0.269143$.
But we can continue with series reversion and have
$$x_2=\frac 14+\frac{1}{4^a-4 a}+\frac{8 (a-1) a-4^a}{\left(4^a-4 a\right)^3}+\cdots$$
For $a=3$, this gives $x=\frac{2365}{8788}=0.269117$
Another one which is not bad
$$x_3=\frac 14+\frac{4^a-4 a}{8 a \left(a-4^a+1\right)+4^a+4^{2a}}$$
For the case where $a$ is close to $1.5^+$, the third solution is close to $1$ but, using the same method, it can be approximated as
$$x=1-\frac{4(2a-3)}{4 (a-1) a-1}-\frac{8 (2 a-3)^3 \left(4 a^2-6 a-1\right)}{3 (4 (a-1) a-1)^3}-$$
$$\frac{4 (2 a-3)^3(320 a^6-1728 a^5+3440 a^4-2784 a^3+452 a^2+300 a+27 )}{9 (4 (a-1) a-1)^5}$$
For example, for $a=2$, the above formula gives $x=\frac{6639}{16807}=0.395014$ while the exact solution is $x=\frac{3-\sqrt{5}}{2} =0.381966$.


text:
Q: Loop over Array in array I've got this data: http://api.tvmaze.com/shows?page=0
What i am trying to achieve is looping over the data and echo each id. This is the code i used:
<?php

$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);

$response = json_decode($json, TRUE);

foreach( $response as $serie){

  foreach( $serie as $info => $value){
    echo $info->$value["id"];
  }

}

I don't really know what i am doing wrong.. Do you guys have any idea?
Greetz,

A: Try below code for getting id and url. You have to use array because you are passing TRUE in json_decode().
<?php

$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);

$response = json_decode($json, TRUE);

foreach( $response as $serie)
{
    echo $serie['id']."->".$serie['url']."
";
}
?>

A: Keep it simple to fetch ids you wanted,
$url = ('http://api.tvmaze.com/shows?page=0');
$json = file_get_contents($url);
$response = json_decode($json, TRUE);
echo "
";

foreach ($response as  $value) {
    echo $value['id']."
"; // you will get ids in here only
}


text:
Q: A command that I ran that works wrongly in sed this command does not work in sed, version 4.2.1.
    sed 's/[[:upper:]]/[[:lower:]]/' <file.

although it does detect the upper case pattern, it does not do the conversion to lower case, rather it converts the captured patterns to [[:lower:]]. any workaround?

A: Use tr instead:
tr '[:upper:]' '[:lower:]' file

A: With sed, you need to capture the upper-case pattern in a group and then substitute with the lowercase version
sed -r 's/([[:upper:]])/\L\1/g' <file


text:
Q: I need a little explaination on this bitwise puzzle I have been stuck on this bitwise puzzle for a few hours. I was searching for a good solution to this problem on google to see how others were solving it and i came across this solution. I am trying to figure out how it works. The only thing i don't understand about this is the rounding process and the lost bits? what bits are lost?
I would really appreciate someone explaining this solution to me.
Thanks in advance guys, Yosemite :)
/*
 * ezThreeFourths - multiplies by 3/4 rounding toward 0,
 *   Should exactly duplicate effect of C expression (x*3/4),
 *   including overflow behavior.
 *   Examples: ezThreeFourths(11) = 8
 *             ezThreeFourths(-9) = -6
 *             ezThreeFourths(1073741824) = -268435456 (overflow)
 *   Legal ops: ! ~ & ^ | + << >>
 *   Max ops: 12
 *   Rating: 3
 */

int ezThreeFourths(int x) {
/*
 *sets y to make up for the lost bits while rounding. Multiplies
 *by three by adding x 3 times. Records the sign since
 * what is added will be different depending on whether the sign
 *is positive or negative and adds this to to the number. Then
 *divedes by 8 by shifting.
 */
  int y = 3;
  x =x+x+x;
  int z = x>>31;
  z = y & z;
  x = z + x;
  x = x>>2;
  return x;
}

this is the link where i got it from: link the individual didn't mark his name in the file so i don't know his name

A: All the work here is just being done to match the fact that iso C defines division to round towards zero. The much easier version of multiplying by 3/4 is to just multiply by three and shift by 2:
return (x+x+x) >> 2;

Unfortunately this has the wrong behaviour for negative values (it floors the value instead of rounding towards zero).
To fix it we need to add 3* to negative terms before shifting by 2 to emulate rounding via truncation. We do it as follows:
int z = x >> 31; // Arithmetic right shift extracts sign mask (0xffffffff or 0x0)
int y = 3 & z; // 3 for negative values, 0 for nonnegative
return (x + x + x + y) >> 2; // Multiply and divide with rounding

To be even more correct we should take into account that we don't really know the size of an integer is 32 by changing the code like so:
int three_fourths(int x) {
    return (x + x + x + (3 & (x >> (8 * sizeof(x) - 1)))) >> 2;
}

You can see this final implementation in action here.
* This is an idiom for turning a flooring divide into a ceiling divide. If you have x / N rounding down you can change the expression to (x + N - 1) / N to round up instead. For N==4 the transformation would be x / 4->(x + 3) / 4

Undefined Behavior
What we have finally still has some assumptions. While of course x + x + x can overflow and yield undefined behavior, thats no different than x * 3 (ignore the question writer suggesting this has the same behavior for overflow, it will on some implementations but that's not guaranteed).
The big piece of implementation defined behavior is the arithmetic right shift. Here's what the C standard has to say on the issue (ISO/IEC 9899:TC3 §6.5.7 ¶5):

The result of E1 >> E2 is E1 right-shifted E2 bit positions. If E1 has an unsigned type
or if E1 has a signed type and a nonnegative value, the value of the result is the integral
part of the quotient of E1 / 2E2. If E1 has a signed type and a negative value, the
resulting value is implementation-defined.

So the mask extraction will only work if right shifting any negative value by one less than the width of an int yields a value with ones in all of the bit positions. This holds in the common implementation for two's complement systems (and likely any system you will ever work on) but it's not technically guaranteed by the standard.


text:
Q: Why won't @Secured annotations work after a grails spring-security manual login? I've been attempting to log in a user automatically after a successful signup using grails with the spring-security-core plugin. While the forced login works, and all the authorities etc. are loaded, the @Secured annotations in other controllers won't recognise the granted authorities and consequently the browser gets stuck in a redirect loop between the secured and login pages.
My login action:
def forceLogin = {
  PSysuser sysuser = flash.sysuser;
  String username = flash.username ?: params.username;
  String password = flash.password ?: params.password;
  UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(
      sysuser?.username ?: username,
      sysuser?.password ?: password
  );
  request.session;
  token.details = new WebAuthenticationDetails(request);
  Authentication authenticatedUser = authenticationManager.authenticate(token);
  SecurityContextHolder.context.authentication = authenticatedUser;
  springSecurityService.reauthenticate(username, password); //doesn't appear to work, but doesn't hurt either.
  redirect action:auth;
}

Does anyone know how I can get the annotations to work properly?

A: If you are using the spring-security-plugin, take a look at some of the helper classes. More specifically, check out the reauthenticate method of the SpringSecurityService. Here is an example from Burt's amazing documentation:
class UserController {
   def springSecurityService

   def update = {
      def userInstance = User.get(params.id)

      params.salt = person.salt
      if (userInstance.password != params.password) {
         params.password = springSecurityService.encodePassword(params.password, salt)
         def salt = … // e.g. randomly generated using some utility method
         params.salt = salt
      }
      userInstance.properties = params
      if (!userInstance.save(flush: true)) {
         render view: 'edit', model: [userInstance: userInstance]
         return
      }

      if (springSecurityService.loggedIn &&
             springSecurityService.principal.username == userInstance.username) {
         springSecurityService.reauthenticate userInstance.username
      }

      flash.message = "The user was updated"
      redirect action: show, id: userInstance.id
   }
}

A: So, turns out that it wasn't the @Secured annotations at all, but the session-based authentication code left over from before spring-security was implemented.
After adding the correct object to the session scope, the problem went away.
ARGH!


text:
Q: Is there a way to achieve one to one messaging in react native with firebase real time database? I am trying to achieve one-to-one messaging in react native using the firebase real time database. I am very new to react native/firebase and I am not too sure how I can send a message to a specific user uid. I have seen a few links online which uses firebase firestore for group chats but I would like to perform this using the real time database and only one-to-one messaging. So far I have managed to send a message in my app but I am displaying all messages from all users from the database too when logged in as the current user. I am using react-native-gifted-chat for the UI.
// This is file MessagesScreen.js

class MessagesScreen extends Component {
  state = {
    messages: []
  }

  get user() {
    return {
      _id: FireMessage.uid,
    }
  }

  componentDidMount() {
    FireMessage.get(message => this.setState(previous => ({
      messages: GiftedChat.append(previous.messages, message)
    })));
  }

  componentWillUnmount() {
    FireMessage.off();
  }

  render() {
    const chat = <GiftedChat messages={this.state.messages} onSend={FireMessage.send} user={this.user} />;

    if (Platform.OS === "android") {
      return (
        <KeyboardAvoidingView style={{ flex: 1}} behavior="padding" keyboardVerticalOffset={10} enabled>
          {chat}
        </KeyboardAvoidingView>
      );
    }

    return <SafeAreaView style={{ flex: 1}}>{chat}</SafeAreaView>;
  }
}

export default MessagesScreen;

// This is file FireMessage.js

class FireMessage {

  constructor() {
    this.init()
    this.checkAuth()
  }

  init = () => {
    if (!firebase.apps.length && firebaseConfig.apps.length === 0) {
      firebase.initializeApp({
        apiKey: "xxxxxxxxxxx",
        authDomain: "xxxxxxxxxxx",
        databaseURL: "xxxxxxxxxx",
        projectId: "xxxxxxxx",
        storageBucket: "xxxxxxxxxx",
        messagingSenderId: "xxxxxxxx",
        appId: "xxxxxxxxxxx",
        measurementId: "xxxxxxxxx"
      });
    }
  };

  checkAuth = () => {
    firebase.auth().onAuthStateChanged(user => {
      if (!user) {
        firebase.auth().signInAnonymously();
      }
    });
  };

  send = messages => {
    messages.forEach(item => {
      const message = {
        text: item.text,
        timestamp: firebase.database.ServerValue.TIMESTAMP,
        user: item.user
      };

      this.db.push(message)
    });
  };

  parse = message => {
    const { user, text, timestamp } = message.val();
    const { key: _id } = message;
    const createdAt = new Date(timestamp);

    return {
      _id,
      createdAt,
      text,
      user
    };
  };

  get = callback => {
    this.db.on("child_added", snapshot =>
      callback(this.parse(snapshot)));
  };

  off() {
    this.db.off();
  }

  get db() {
    return firebase.database().ref("messages");
  }

  get uid() {
    return (firebase.auth().currentUser || {}).uid;
  }
}

export default new FireMessage();

Realtime Database structure:


text:
Q: Finding Favorites I haven't shared In Photos.app, I have the special Favorites smart album and an iCloud Shared Album called Shared Favorites. I display Shared Favorites as our AppleTV screen saver. The issue is that when I favorite a photo, I have no easy way to reliably add it to the Shared Favorites album.
I was hoping to create a smart album containing photos that are a favorite and are not in Shared Favorites. But iCloud Shared Albums are not listed as albums.
When I tried dragging all of the Favorites into the Shared Favorites album, I wound up getting hundreds of duplicates.
Any ideas for a workflow that lets me just add new favorites to a shared album?


text:
Q: How do I connect to a new Amazon Lightsail instance from my Mac? I've created a new NodeJS instance on Amazon Lightsail, and wish to connect to it from my Mac's command line. Not sure how to include the required SSH key in the connection command when it says Permission denied (publickey).

A: To be able to connect to your amazon lightsail instance you need to download the key first.

*

*Go to Accounts > SSH Keys (
https://lightsail.aws.amazon.com/ls/webapp/account/keys ) >
Download
(Make sure that you download the key for the same region where your instance is installed.)

*Save it in a folder in your local machine. For Example- "Desktop > keys"

*Open the terminal and navigate to the directory where the key is stored(cd desktop/keys )

*Enter this command in terminal: chmod 600 keyfilename.pem (replace keyfile name with your actual key name e.g chmod 600 LightsailDefaultKey-eu-west-2.pem )
It is required that your private key files are NOT accessible by others.
This is why we have to change the file permissions

*Run this command ssh -i keyfilename.pem username@ip
replace keyfilename.pem with your actual file name, username with your username(e.g bitnami or user) and replace IP with actual IP

You can find your IP and username on your instance page (https://lightsail.aws.amazon.com/ls/webapp/home/instances > Select Instance> Manage)

A: *

*Go to the "SSH Keys" tab under your Lightsail Account page

*Select the Default option under your region and download the key pair file

*

*Will be a .pem file, ex. LightsailDefaultPrivateKey-us-west-2.pem

*Open up your terminal and navigate to the directory where the above file is stored

*Run chmod 600 [fileName] at the command line to restrict file permission so only you can read it

*Run ssh -i [fileName] [username]@[Public IP] to establish the connection to Lightsail

*

*Username and IP are available under the "Connect" tab on the Lightsail web dashboard for your resource

A: I spent hours figuring out how to add an additional key to login to my Wordpress/Bitnami Lightsail Instance.
I though that by adding new key pairs in [https://lightsail.aws.amazon.com/ls/webapp/account/keys][1], I could get direct access to my instances, but that was not the case. I always got "Permission denied (publickey)" when trying to connect via SSH/SFTP.
How to solve it?
You should add your public keys directly to your Lightsail instance:

*

*Connect first to your instance via your Lightsail console. The link should looks like this: https://lightsail.aws.amazon.com/ls/remote/yourzone/instances/instancename/terminal?protocol=ssh

*nano ~/.ssh/authorized_keys
It should looks something like:
ssh-rsa AFGGS#%NzaC1yc2EFDSGgpCvpVhFyRSpfsdfjhgasdDSduD$

This means that only one key par is allowed to connect via SSH/SFTP to your Lightsail instance (voilà!).
You should add to that file the new public key bellow:
(YOUR PREVIOUS KEY)ssh-rsa AFGGS#%NzaC1yc2EFDSGgpCvpVhFyRSpfsdfjhgasdDSduD$
(ADD NEW PUBLIC KEY) ssh-rsa ASJKAKKFS#%ASDFbsdjfhJHGJvpVhFyRSpfsdfjhgasdDSduD$

*Restart your server and login from your local terminal:
ssh bitnami@yourpublicip -i /Users/youruser/.ssh/yourkeyfile
With this, I could also login via SFTP in Filezilla (Mac), adding the private key in the Site Manager.

A: To use your existing ~/.ssh/id_rsa.pub

*

*Login to the server using the browser client

*Do nano ~/.ssh/authorized_keys

*Get your local public key with xclip -sel clip < ~/.ssh/id_rsa.pub

*Append the ~/.ssh/authorized_keys with the copied key

*Restart the instance

*Login locally using ssh ubuntu@[instance_public_ip]


text:
Q: Peek into gSuite drive users files I have a problem, where a former employee has filled up his gDrive way to much, as to have reason. The user is disabled, but we have to keep it deactivated for legal purposes, because we suspect ilegal content.
My question is if there is a way to peek into those files. Maybe list them only, without opening them. I tried googleing around but was not able to find ans answer to that.

A: This types of questions are outside of the scope for Stack Overflow and (likely) no one here is qualified to tell you how to proceed.
If you suspect illegal content is being stored on said user, do not reactivate it or try to peek into the files without being explicitly instructed to do so by someone that has the knowledge to tell you if, when and how to do it in the eyes of the law.
Contact your legal department and ask for legal advice on this matter.
This answer does not constitute legal advice or a legal opinion on any matter discussed.

If you still want to do it...
You can:
- Use Google Vault for Legal Hold
or

*

*Reactivate the user with a different temporary password and browse the files.


text:
Q: Precautions to take with stratified random sampling in machine learning I am looking to train a machine learning model to solve a regression problem. The targets, y, are not normally distributed. It is perhaps best described as somewhat bimodal. For context, I have 13,000 points in total.
I am looking to have an 80%/20% train/test split, and on the training set, I intend to do 5-fold cross-validation. My concern is that, depending on the seed used to split the data, there can be somewhat significant run-to-run variability because the distribution is sampled randomly and the subsamples do not have a similar distribution as the parent dataset or between other subsamples.
For this reason, I am considering doing stratified sampling with the train/test split as well as during the 5-fold cross-validation. My plan is to set up five strata of the type (-$\infty$,1], (1,2], (3,4], (4,+$\infty$] and have the subsamples contain a similar distribution as the parent dataset.
However, I see very few people in my field do stratified sampling for regression problems and am concerned about unforeseen circumstances. What concerns are there that one should consider when it comes to stratified sampling in machine learning? Of course, I can also run the ML regression several times and average the results, regardless of whether I do stratified sampling or purely random sampling.

A: In general, variation is a good thing in cross-validation or train/test split, so there's little reason to reduce variability by stratified sampling. I can think of some situations where stratified sampling may make sense though. For example, if your outcome is binary where the proportion of 1 (or 0) is very low. Then effectively you have a very small sample size, and you may want to ensure there are enough 1 (or 0) in each of the folds. Other than that, if your sample size is around 13000 and it is unlikely that your splits would lead to perfect (or near perfect) classification in one of the folds then I don't think you should do stratified sampling.

A: My thoughts are first, to perform a discriminate analysis to assign the y's to one of two populations. This may be based on a simple rule (perhaps size based) or something more complex depending on available information. The goal is to remove (or, at least, mitigate) the bimodal nature of the data.
Second, as the assignment is not likely perfect in Step 1, use a robust regression like Least-Absolute-Deviations which is median, not mean-centered (the latter being sensitive to outliers, which in the current context, are possibly misclassified points). The robust regression analysis is applied separately to each identified subpopulation (two in the current case).
Also, optionally consider a power transformation also to induce normality and homogeneity of variance (like Box-Cox) especially if considering non-robust regression analysis in each population. Caution, this may create interpretations issues with the data results.
As such, your concerns over "seed used to split the data, there can be somewhat significant run-to-run variability because the distribution is sampled randomly and the subsamples do not have a similar distribution as the parent dataset or between other subsamples" may be reduced.


text:
Q: Postfix spam (hack) My mailq is getting filled with reports about email been sent (to for example freshsamuel2009@yahoo.com) by non existing local user (for example jeanne_cox@localdomains.tld)
mailq example:
8F979561A3     1440 Thu Aug 25 13:54:32  jeanne_cox@localdomains.tld
(delivery temporarily suspended: connect to 127.0.0.1[127.0.0.1]:10024: Connection refused)
                                         freshsamuel2009@yahoo.com

How can I stop it?
my main.cf is:
# See /usr/share/postfix/main.cf.dist for a commented, more complete version

# Debian specific:  Specifying a file name will cause the first
# line of that file to be used as the name.  The Debian default
# is /etc/mailname.
#myorigin = /etc/mailname

smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

readme_directory = /usr/share/doc/postfix

# TLS parameters
smtpd_tls_cert_file = /etc/postfix/smtpd.cert
smtpd_tls_key_file = /etc/postfix/smtpd.key
smtpd_use_tls = yes
smtpd_tls_session_cache_database = btree:${data_directory}/smtpd_scache
smtp_tls_session_cache_database = btree:${data_directory}/smtp_scache

# See /usr/share/doc/postfix/TLS_README.gz in the postfix-doc package for
# information on enabling SSL in the smtp client.

myhostname = faster2.jbmd.com
alias_maps = hash:/etc/aliases, hash:/var/lib/mailman/data/aliases
alias_database = hash:/etc/aliases, hash:/var/lib/mailman/data/aliases
myorigin = /etc/mailname
mydestination =  localhost, localhost.localdomain
relayhost =
mynetworks = 127.0.0.0/8 [::1]/128
mailbox_command = procmail -a "$EXTENSION"
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
html_directory = /usr/share/doc/postfix/html
virtual_alias_domains =
virtual_alias_maps = hash:/var/lib/mailman/data/virtual-mailman, proxy:mysql:/etc/postfix/mysql-virtual_forwardings.cf, proxy:mysql:/etc/postfix/mysql-virtual_email2email.cf
virtual_mailbox_domains = proxy:mysql:/etc/postfix/mysql-virtual_domains.cf
virtual_mailbox_maps = proxy:mysql:/etc/postfix/mysql-virtual_mailboxes.cf
virtual_mailbox_base = /var/vmail
virtual_uid_maps = static:5000
virtual_gid_maps = static:5000
inet_protocols = all
smtpd_sasl_auth_enable = yes
broken_sasl_auth_clients = yes
smtpd_sasl_authenticated_header = yes
smtpd_recipient_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unauth_destination, check_recipient_access mysql:/etc/postfix/mysql-virtual_recipient.cf
smtpd_tls_security_level = may
transport_maps = hash:/var/lib/mailman/data/transport-mailman, proxy:mysql:/etc/postfix/mysql-virtual_transports.cf
relay_domains = mysql:/etc/postfix/mysql-virtual_relaydomains.cf
relay_recipient_maps = mysql:/etc/postfix/mysql-virtual_relayrecipientmaps.cf
proxy_read_maps = $local_recipient_maps $mydestination $virtual_alias_maps $virtual_alias_domains $virtual_mailbox_maps $virtual_mailbox_domains $relay_recipient_maps $relay_domains $canonical_maps $sender_canonical_maps $recipient_canonical_maps $relocated_maps $transport_maps $mynetworks
smtpd_sender_restrictions = reject_non_fqdn_sender, reject_unlisted_sender,  reject_unknown_sender_domain,check_sender_access regexp:/etc/postfix/tag_as_originating.re, permit_mynetworks, permit_sasl_authenticated, check_sender_access mysql:/etc/postfix/mysql-virtual_sender.cf, check_sender_access regexp:/etc/postfix/tag_as_foreign.re
smtpd_client_restrictions = permit_mynetworks, permit_sasl_authenticated, reject_unknown_client_hostname, check_client_access mysql:/etc/postfix/mysql-virtual_client.cf reject_rbl_client cbl.abuseat.org,  reject_rbl_client b.barracudacentral.org
smtpd_client_message_rate_limit = 100
maildrop_destination_concurrency_limit = 1
maildrop_destination_recipient_limit = 1
virtual_transport = dovecot
header_checks = regexp:/etc/postfix/header_checks
mime_header_checks = regexp:/etc/postfix/mime_header_checks
nested_header_checks = regexp:/etc/postfix/nested_header_checks
body_checks = regexp:/etc/postfix/body_checks
owner_request_special = no
smtp_tls_security_level = may
smtpd_tls_mandatory_protocols = !SSLv2, !SSLv3
smtpd_tls_protocols = !SSLv2,!SSLv3
smtp_tls_protocols = !SSLv2,!SSLv3
dovecot_destination_recipient_limit = 1
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
content_filter = amavis:[127.0.0.1]:10024
receive_override_options = no_address_mappings
message_size_limit = 0
default_process_limit = 150
local_recipient_maps = proxy:unix:passwd.byname $alias_maps

A: In the best of the scenarios, one or more of your users is compromised e.g. bad actors guessed/phished the password.
Since you allow sending email from authenticated users, they are most probably faking the From field to avoid detection.
Editing the full body of a couple of relevant messages will give you a hint of which user(s) you have compromised.
As a starting point I would advise restricting the From field to known users, have a look at this thread. Postfix: prevent users from changing the real e-mail address
As the middle scenario, you can have an exploit of some page/cgi in a web server if the postfix server is running Apache.
As the worst scenario, you can have a compromised box.
Have a look at postfix and Apache access logs (if you have Apache), it will give you a more reasonable idea of what it is happening.
EDIT: After @P.Masher posted an example of the deferred message:
The relevant line to pay attention is:
X-PHP-Originating-Script: 5015:alias.php(1944) : eval()'d code

What it says it that you have a script name alias.php, possibly planted in a less secure directory accessible to your web server (Apache?), that is the culprit for sending the emails.
The script will have to be deleted, and the directory and any other possible way in (old wordpress, SQL injection, old webmail interface) the spammers have used to plant this script will have to be closed.
A temporary solution may be stopping the web server altogether.
I would also collect web server logs of the access to alias.php and would send them to the local CERT. (if you have one that you usually work with )
As for more security considerations, the fact they are executing code through an eval() means they basically have access to any file the user that is running the vhost/Apache has access. i.e. it is the same as having a remote shell account in the server.
If the server is old/has no updates, they might as well have leveraged privileges to root level in the worst scenario; in the best scenario, they only have access equivalent to the web server non-privileged user, but may have already tried to leverage passwords from HTML/PHP files, and might as well have collected the hashed passwords of your postfix users.
I would advise to:
1) Reinstall the server if it is too old or has no security updates;
2) Change DB/root passwords;
3) Advise the postfix users to change their passwords just in case.


text:
Q: I am getting an error saying 'The trial period for this product has expired.' on my SharePoint Foundation 2010 server I have SharePoint Foundation 2010 installed a server few months back. We were using it for quite some months and it was behaving nicely. But, one fine day when one user tried to access a site on this server, which he was referencing daily, he got an error saying 'The trial period for this product has expired.'.
Being an administrator user I am still able to log in to Central administration. But, none of the sites in site collection are accessible.
I was under impression that SharePoint Foundation 2010 is a free product.
Can anybody help me in this regard ?

A: It is a bug with the health analyzer.  See http://social.technet.microsoft.com/Forums/en-US/sharepoint2010setup/thread/644ab342-4eaa-468c-95c1-f345a4f65f26 for a quick solution on how to disable that health analyzer rule and thus fix your issue.

A: My ShaerePoint 2010 list would generate "The trial period for this product has expired" each time I tried to edit a particular item.  List Ribbon / List Settings / Form Settings will give a choice of SharePoint Form or InfoPath.  Found InfoPath set (must not be installed correctly); switched to SharePoint Standard.  Upon refresh I see a single radio button with a caption to the right "Customize the current form using Microsoft InfoPath"  Since then I have been able to edit the list item; no more "expired" message.

A: Here is the solution that worked for me.
1.  Open IIS Management Console
2.  Go to the Application Pool Page
3.  look which users has been used for SharePoint
4.  add this users to the local administration group
5.  iisreset


text:
Q: Is there a more efficient method than this to calculate the volume of an advanced 3D object? In a project I'm planning to calculate the volume of an advanced 3D object by creating an array of 1x1 unit squares which make up a grid, passing that grid through the object and, every 1 unit of distance, running collision detection on each square with the object, so essentially we're really creating a cubed grid and running a simplified implementation of 1x1x1 cube collision detection throughout the object. Sum of volume of all collided cubes = volume of advanced 3D object.
Like so (the grid here is less subdivided for the sake of demonstration):

I can then control a balance between computational cost and accuracy by further subdividing the grid.
This seems like it would work but I wanted to make sure I wasn't making a mess of a task that could be much cleaner / simpler before I started. Is there a better way of calculating the volume of an advanced 3D object?