text:
Q: How does the electromagnetic field behave in a complex circuit when first energized? Such as in a computer CPU booting up From what I understand in the case of a simple circuit, the electrons in the circuit wiring are steadily excited, i.e. energized, in a fairly complex way by the external energy input, as the energy flow increases to the operating parameters.
In the simplest lightbulb and battery circuit, this seems to be satisfactorily explained in the following: Path of EM wave propagation in a circuit wire
But how does this transition occur in a complex circuit?
Does it propagate like a fractal wave along the many branching and interconnecting paths of the circuit? How do the electrons know which way to move on a junction between multiple branches?

A: Electrons "know" how to move at junctions by Kirchhoff's laws and by the laws of circuit element behavior. For complex circuits studied at turn-on, transient analysis is used, and the results are well-explained by these "ordinary" laws.


text:
Q: bin stub - missing dependencies from gem (executing rake tasks within gem) I've written a gem elastic-beanstalk which is to be used inside a rails project file structure, as well as in a standalone CI environment where the rails dir and files are not available (without unzipping etc).  i.e. the Bamboo build process running eb:package will yield one primary artifact app.zip where the deploy plan at a later time and perhaps on another agent can take over and execute eb:deploy.
The goal
This is all running fine when inside a rails project structure, so my goal here is to also get this running for the standalone CI environment.
Given
an empty dir (CI environment) with just the app.zip, eb.yml, binstubs created, and the gem is available
When
I run elastic-beanstalk eb:deploy
Then
it should run the equivalent of rake eb:deploy using this gem's dependencies and lib files.
Update - Bin Stub
It appears that a bin stub may be what I'm looking for.  Exploring another SO post, I have tried (to no avail so far) bin/elastic-beanstalk:
gem_dir = File.expand_path('..',File.dirname(__FILE__))
$LOAD_PATH.unshift gem_dir# Look in gem directory for resources first.

lib = File.expand_path('lib', gem_dir)
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)

require 'elastic/beanstalk'
require 'rake'
require 'pp'

pwd=Dir.pwd
Dir.chdir("#{gem_dir}/bin") # We'll load rakefile from the gem's bin dir.
Rake.application.init
Rake.application.load_rakefile
Dir.chdir(pwd) # Revert to original pwd for any path args passed to task.

Rake.application.invoke_task(ARGV[0])

So this runs, but is still failing with the same dependency problem I began with undefined method 'safe_load_file' for Psych:Module (NoMethodError).  While I think a binstub is the way to go:
How can I resolve the dependency problem with the bin stub?

A: Ultimately, I needed a call to Bundler.setup to resolve dependencies.
After cleanup, the file below is the only thing I needed to call a rake task with a bin file inside a gem (external bin stub utilizes this file):
bin/elastic-beanstalk
#!/usr/bin/env ruby
require 'rake'
require 'bundler'

raise "Bundler is required.  Please install bundler with 'gem install bundler'" unless defined?(Bundler)

#
# Example:
#
#   elastic-beanstalk eb:show_config
#   elastic-beanstalk eb:show_config[1.1.1]
#

# init dependencies
Bundler.setup

# init rake
Rake.application.init

# load the rake tasks
gem_dir = File.expand_path('..',File.dirname(__FILE__))
load "#{gem_dir}/lib/elastic/beanstalk/tasks/eb.rake"

# invoke the given task
Rake.application.invoke_task(ARGV[0])

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular 11 (or 9+) I18n set Locale at startup I have an old angular project (v8) where i have used i18n to tag all my translations.
I have 2 xlf files one for en and one for fr - and at runtime choose which file to use.
This works fine.
However, in a new angular project (v11) this approach nolonger works.
The code doesnt error, and doenst suggest there is a problem, however the text is not tranlsated on screen.
The code in the main.ts file is as follows
let languageCode: string = localStorage.getItem("language") ? localStorage.getItem("language") : 'en-GB';

// use the require method provided by webpack
// we use the webpack raw-loader to return the content as a string
declare const require;

var translations = undefined;

switch (languageCode) {
    case AppService.Languages.english:
        break;
  default:
        translations = require(`raw-loader!./locale/messages.${languageCode}.xlf`);
  break;
}

platformBrowserDynamic().bootstrapModule(AppModule, {
  providers: [
    {provide: TRANSLATIONS, useValue: translations},
    {provide: TRANSLATIONS_FORMAT, useValue: 'xlf'},
    {provide: LOCALE_ID, useValue: languageCode }
  ]
});

I also have the following in the app.module.ts
import { registerLocaleData } from '@angular/common';
import localeFr from '@angular/common/locales/fr';
import localeFrExtra from '@angular/common/locales/extra/fr';

let urlParams: URLSearchParams = new URLSearchParams(window.location.search);
let languageCode: string = localStorage.getItem("language") ? localStorage.getItem("language") : 'en-GB';

registerLocaleData(localeFr, 'fr-FR', localeFrExtra);

.....

 providers: [
    { provide: LOCALE_ID, useValue: languageCode },

Has anyone else had experience with this approach not working in newer angular versions?
NOTE: inbuild things like date formatting is coming out in the correct locale - EG date formatting 01 décembre 20.  Its purely the i18n replacement that is not being done.

A: I indeed added extra code, however i now realise that if you use ivy - (tsconfig.json -
angularCompilerOptions -     "enableIvy": false) then it plainly doesnt work with above code at runtime.
I have read the ivy documents on the changes they made for i18n and i can see that they just did not intend for translations to be changed at runtime.
I have switched off ivy and the old code now works.
I can see their reasoning, but i just cannot have a different url per language so this is my only option.


text:
Q: limit text using str_limit function in Laravel 5.5 I have been trying to limit my blog content text with str_limit that works fine until I apply limit of characters on it. kindly see what is missing in the code of my blade file:
{!! str_limit($blog->content) !!} works fine with the default limit, showing limited text on the view. But when I apply any custom limit i.e. {!! str_limit($blog->content, 20) !!} it do not show any text on the view.

A: The str_limit function has been deprecated,
but you can use Str::limit($text)Laravel doc.
In the php code use:
use \Illuminate\Support\Str;

The sample usage in blade:
{{\Illuminate\Support\Str::limit($text)}}
{{\Illuminate\Support\Str::limit($text,10)}}

A: Have sorted out this thing using {!!  substr(strip_tags($blog->content), 0, 150) !!} , works fine with what I was requiring.

A: In laravel 7, all you have to do is open your blog directory in terminal and install "composer require laravel/helpers" without quotes.. after that, close your artisan and run php artisan serve again. go back to ur file and now you can use str_limit()

A: In laravel 9 use {!! Str::words($blog->content, 1,'...')  !!}


text:
Q: Motivation for the integral notation $\int _{I \in \mathbb{I}} D(I)$ for a categorical limit? What is the motivation for the integral notation $\int _{I \in \mathbb{I}} D(I)$ for a categorical limit, which is otherwise known as $\underset  {\mathbb{I} \leftarrow} {lim} \ D$?

A: As mentioned in the comments, this notation is most commonly used for ends and coends. In fact, limits and colimits are special cases of ends and coends (the case where one takes the end /coend of a functor $F: C \times C^{op} \to D$ which depends only on one of its variables), so this notation is a special case of the end / coend notation. For more discussion of this notation, see here.


text:
Q: C++ Error 1 error C2146: syntax error: missing ';' before identifier 'records' TicTacToe.h
#pragma once
#include "Header.h"

class TicTacToe
{
    vector<char>tictac_array;
    Records records;
public:
    TicTacToe();

    ~TicTacToe();

    void push_tictac_array();

    int wincheck();

    void board(string player1, string player2);

    void start();

    void mainmenu();
};

Header.h
#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <fstream>
#include <algorithm>
#include "Records.h"
#include "TicTacToe.h"

using namespace std;

Records.h
#pragma once
#include "Header.h"

class Records
{
protected:
    vector<Records*> rec;
    string player;
    int wins;
    int games;
    int draws;
public:
    Records();
    Records(string player, int wins, int games, int draws);

    ~Records();

    void setName(string player);

    void setWins(int wins);

    void setGames(int games);

    void setDraws(int draws);

    string getName();

    int getWins();

    int getGames();

    int getDraws();

    void addRec(string player, int wins, int games, int draws);

    void sortStats();

    void outRec();

    void saveTo();

    void readFrom();
};

main.cpp
#include "Header.h"

const int NotUsed = system("color F0");

void main()
{
    setlocale(0, "rus");
    TicTacToe tictac;
    tictac.records.readFrom();
    tictac.mainmenu();
}

Before the breakdown on the files and everything worked perfectly. Only after spread all classes file, began issuing this error, what could be the problem?
Added Records.h header file

A: How many confunsion.
First of all:

*

*never use useless include in header files.

*never use namespace in header files.

In TicTacToe.h you include "Header.h" that includes "TicTacToe.h" itself: recursion.
Second:

"#pragma once" is not standard, so I recommend to use instance:

#ifndef RECORDS_H_
#define RECORDS_H_

class Records {
}

#endif

If you really want to use "#pragma once", learn to use it before: it should be the first instruction, at least before all "inclues", generally.
Third:

*

*use keyword 'private' even tough it is implicit;

*get method should be const;

*pass parameters by references, you avoid useless copy.

TicTacToe.h
#ifndef TICTACTOE_H_
#define TICTACTOE_H_

#include <vector>

#include "Records.h"

class TicTacToe {
private:
    std::vector<char> tictac_array;
    Records records;
public:
    TicTacToe();
    ~TicTacToe();
    void push_tictac_array();
    int wincheck();
    void board(const std::string& player1, const std::string& player2);
    void start();
    void mainmenu();
};

#endif

Records.h
#ifndef RECORDS_H_
#define RECORDS_H_

#include <vector>

class Records {
protected:
    std::vector<Records*> rec;
    string player;
    int wins;
    int games;
    int draws;
public:
    Record();
    Record(const std::string& player, const int& wins, const int& games,const int& draws);
    ~Record();
    void setName(const std::string& player);
    void setWins(const int& wins);
    void setGames(const int& games);
    void setDraws(const int& draws);
    string getName() const;
    int getWins() const;
    int getGames() const;
    int getDraws() const;
    void addRec(const std::string& player, const int& wins, const int& games,const int& draws);
    void sortStats();
    void outRec();
    void saveTo();
    void readFrom();
};

#endif

Main:
#include <clocale>
#include <cstdlib>

#include "TicTacToe.h"

using namespace std;

const int NotUsed = system("color F0");

void main() {
    setlocale(0, "rus");
    TicTacToe tictac;
    tictac.records.readFrom();
    tictac.mainmenu();
}

Fourth:
Records class is totally wrong: it has a std::vector of Records*, that make it recursive.
You should have instance:
Record.h
class Record {
    protected:
        string player;
        int wins;
        int games;
        int draws;
    public:
        Records();
        Records(const std::string& player, const int& wins, const int& games,const int& draws);
        ~Records();
        void setName(const std::string& player);
        void setWins(const int& wins);
        void setGames(const int& games);
        void setDraws(const int& draws);
        string getName() const;
        int getWins() const;
        int getGames() const;
        int getDraws() const;
        void addRec(const std::string& player, const int& wins, const int& games,const int& draws);
        void sortStats();
        void outRec();
        void saveTo();
        void readFrom();
    };

Records.h
class Records : public std::vector<Record*> {
}

This make more sense, for me at least.

A: You need to guard the Header.h file. Just put #pragma once at the top as you have done for Records.h


text:
Q: jQuery read all TD's table data With jquery I am reading table:
$('#lc_searchresult > table > tbody > tr').each(function() {
            var data = $(this).find("td:eq(5)").html();
            alert(data);
        });

it is working fine if TR tag has one TD inside like:

654321

but If I am having two TD's then I am geting just first one:

654321
13456

How can I get all of TD's from TR with $(this).find("td:eq(5)").html()

A: $('#lc_searchresult > table > tbody > tr').each(function() {
  $(this).children('td').each(function(){
    var data = $(this).html();
  alert(data);
  })

});

A: Why eq it? You're using .each() which means you will return an array of
's.

$('#lc_searchresult > table > tbody > tr').each(function() {
    var data = $(this).find('td').text();
    alert(data);
});

                654321
                13456

                4353535
                3453553

JSFiddle.

A: this should work,
**note thier is no need to use :eq selector here,
READ ABOUT JQUERY :eq selector

$('#lc_searchresult > table > tbody > tr').each(function() {
  var data = $(this).html();
  alert(data);
});

      654321
      13456

A: td:eq(5) : mean you get data of TD with exactly index. so you can't get all data of TR with eq().

A: well when you write
var data = $(this).find("td");

the variable data contains an array of all the td's not just the first one
if you say
data.each(function(){
    alert($(this).html())
})

you will get all the td's


text:
Q: Execute of job failed. See the history log for details I am learning SQL Server administration and setting up log shipping for the first time. SERVER1 is primary database and SERVER2 is secondary database. I was able to setup log shipping successfully from SERVER1 and database has been created on SERVER2, however, when i am trying to manually run the Job it is giving me below error:

After checking the logs in text file, i noticed that it is giving me this error:

Initially, SERVER2 was named as SERVER, i thought this might have been the problem, so i rename the server using sproc sp_addserver and sp_dropserver. However, it did not do the trick. Then i noticed that under regedit Computer\HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\120\machines, name was still SERVER so changed it from there to SERVER2 and restarted the machine. Tried running the job manually again it still gave me the same error. Turned off the firewall of SERVER1 completely, issue still persists. Also, under the shared folder on SERVER2, db backup file is not generated. I am wondering now what is this SERVER exactly here in log referring to. Any help or suggestions would be appreciated!!


text:
Q: Rspec - Mocking an object in private method In our application, we have written after_create/update/delete callbacks for some interested domain models. Inside of these models we create a new Audit model that xmlizes the necessary data of the changed model and store it in the Audit table. As an example, the after_create callback of Consultant model looks as below:

def after_create
    xml = #private xmlize() is called which returns the data of new Consultant object
    audit = Audit.new :data=>xml.to_s
    audit.save
end

Now, I would like to either mock the audit object to see if its save method is called using RSpec. Or even better, if there is a way to regex the contents of the xml through RSpec, I would be glad to learn how to do it through Ruby in Rails environment.

A: You can't naturally mock the Audit object because it's constructed within the method.
What you might want to do is create and inject (somwhere ...) an AuditFactory, and use that to create the Audit object.
Then the factory and the audit can both be mocked, with an expectation that the mock factory creates the mock audit, and that the audit's save method is called.
The expectation on the factory could also be set to expect the correct xml.


text:
Q: Why does Hibernate throw a ClassCastException when calling session.save(object)? When I do the following Hibernate call I get a ClassCastException (see Stacktrace) but I have problems to understand why. What's Hibernate trying to do here? Is it trying to cast one of my objects to a different class type? If yes, why and to what class?
session.save(fooAccount);

Stacktrace:
com.foo.web.model.exception.FailedDatabaseOperationException: java.lang.ClassCastException: com.foo.web.model.authentication.SecurePassword
    at com.foo.web.controller.db.HibernateController.savefooAccount(HibernateController.java:883)
    at com.foo.web.model.account.fooAccount.save(fooAccount.java:459)
    at com.foo.web.controller.AccountController.createfooAccount(AccountController.java:258)
    at com.foo.web.view.start.RegisterController.register(RegisterController.java:233)
    at com.foo.web.view.start.RegisterController.onClick$btn_register(RegisterController.java:196)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.zkoss.zk.ui.event.GenericEventListener.onEvent(GenericEventListener.java:81)
    at org.zkoss.zk.ui.impl.EventProcessor.process0(EventProcessor.java:192)
    at org.zkoss.zk.ui.impl.EventProcessor.process(EventProcessor.java:138)
    at org.zkoss.zk.ui.impl.EventProcessingThreadImpl.process0(EventProcessingThreadImpl.java:517)
    at org.zkoss.zk.ui.impl.EventProcessingThreadImpl.sendEvent(EventProcessingThreadImpl.java:121)
    at org.zkoss.zk.ui.event.Events.sendEvent(Events.java:319)
    at org.zkoss.zk.ui.event.Events.sendEvent(Events.java:329)
    at org.zkoss.zk.ui.AbstractComponent$ForwardListener.onEvent(AbstractComponent.java:3034)
    at org.zkoss.zk.ui.impl.EventProcessor.process0(EventProcessor.java:192)
    at org.zkoss.zk.ui.impl.EventProcessor.process(EventProcessor.java:138)
    at org.zkoss.zk.ui.impl.EventProcessingThreadImpl.process0(EventProcessingThreadImpl.java:517)
    at org.zkoss.zk.ui.impl.EventProcessingThreadImpl.run(EventProcessingThreadImpl.java:444)
Caused by: java.lang.ClassCastException: com.foo.web.model.authentication.SecurePassword
    at org.hibernate.type.ComponentType.toLoggableString(ComponentType.java:410)
    at org.hibernate.type.ComponentType.toLoggableString(ComponentType.java:414)
    at org.hibernate.pretty.Printer.toString(Printer.java:76)
    at org.hibernate.pretty.Printer.toString(Printer.java:113)
    at org.hibernate.event.def.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:120)
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1216)
    at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:383)
    at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:133)
    at com.foo.web.controller.db.HibernateController.savefooAccount(HibernateController.java:879)

Edit: Here are the mappings as well as the code that stores the object:
Mapping file (shortened version. Irrelevant stuff omitted):
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated 26.04.2011 14:49:15 by Hibernate Tools 3.3.0.GA -->
<hibernate-mapping>
    <class name="com.foo.web.model.account.fooAccount" table="fooACCOUNT">

        <id name="id" type="long" access="field">
            <column name="foo_ACCOUNT_ID" />
            <generator class="native" />
        </id>

        <many-to-one name="defaultMailAccount" lazy="false" column="DEFAULT_MAIL_ACCOUNT_ID" />

        <bag name="mailAccounts" table="MAILACCOUNTS" lazy="false" inverse="true">
            <key column="foo_ACCOUNT_ID"></key>
            <one-to-many class="com.foo.web.model.mail.account.MailAccount" />
        </bag>

        <component name="user" class="com.foo.web.model.account.fooUser">
            <component name="activationCode">
                <property name="activationCode" column="ACTIVATION_CODE"></property>
            </component>

            <component name="password" class="com.foo.web.model.authentication.MediumSecurePassword">
                <property name="hash" column="PASSWORD" />
            </component>

            <component name="resetCode">
                <property name="resetCode" column="RESET_CODE" />
            </component>
            <one-to-one name="fooAccount" class="com.foo.web.model.account.fooAccount"></one-to-one>
            <component name="username">
                <property name="username" column="USERNAME" unique="true" />
            </component>

            <property name="userStatus">
                <column name="USERSTATUS" />
                <type name="org.hibernate.type.EnumType">
                    <param name="type">12</param>
                    <param name="enumClass">com.foo.web.model.account.UserStatus</param>
                </type>
            </property>
            <property name="userType">
                <column name="USERTYPE" />
                <type name="org.hibernate.type.EnumType">
                    <param name="type">12</param>
                    <param name="enumClass">com.foo.web.model.account.UserType</param>
                </type>
            </property>
        </component>

    </class>
</hibernate-mapping>

SecurePassword.java (shortened)
/**
 * Represents a password.
 */
public class SecurePassword extends Password {

    /**
     * Default constructor
     */
    public SecurePassword() {
        super();
    }

    /**
     * Constructor method. Will throw IllegalPasswordException if password is
     * not safe.
     */
    public SecurePassword(String password) throws IllegalPasswordException {
        setPassword(password);
    }

    /**
     * Checks if the given character is a number
     *
     * @param c
     *            The character to check
     * @return Returns true if the given character is a number
     */
    public boolean isNumber(char c) {
        // ...
    }

    /**
     * Checks is a given password is valid.
     */
    public boolean passwordValid(Password password)
        throws IllegalPasswordException {
        return passwordValid(password.toString());
    }

    /**
     * Checks is a given password is valid.
     */
    public boolean passwordValid(String password)
        throws IllegalPasswordException {

        // ...
    }

    /**
     * Sets a new password.
     */
    @Override
    public void setPassword(String password) throws IllegalPasswordException {

        if (passwordValid(password)) {
            this.password = password;
        }
    }

}

Password.java (shortened)
/**
 * Represents a simple password without much restriction
 */
public class Password {
    Crypter crypter     = new Crypter();
    String  hash        = null;
    String  password    = null;

    public Password() {
        super();
    }

    public Password(String password) throws IllegalPasswordException {
        setPassword(password);
    }

    @Override
    public boolean equals(Object password) {

        if (this == password) {
            return true;
        }

        if (password instanceof Password) {
            Password p = (Password) password;
            return getHash().equals(p.getHash());
        }

        if (password instanceof String) {
            String password_str = getPassword();
            if (password_str != null) {
                return password_str.equals(password);
            }
        }

        return false;
    }

    /**
     * Returns the hashed version of this password
     *
     * @return The hashed version of this password
     */
    public String getHash() {
        if (hash == null) {
            try {
                hash = crypter.hash(getPassword());
            } catch (FailedCryptOperationException e) {
                handleException(e, false, null, null);
            }
        }
        return hash;
    }

    public String getPassword() {
        return password;
    }

    /*
     * Handles the given exception
     */
    private void handleException(Exception e, boolean notifyUser,
        String customTitle, String customErrorMessage) {

        SystemController.handleException(e, notifyUser, customTitle,
            customErrorMessage);
    }

    public void setHash(String hash) {
        this.hash = hash;
    }

    @SuppressWarnings("unused")
    public void setPassword(String password) throws IllegalPasswordException {
        hash = null;
        this.password = password;
    }

    @Override
    public String toString() {

        return getPassword();
    }
}

MediumSecurePassword.java
public class MediumSecurePassword extends SecurePassword {

    public final int    MAX_LENGTH              = 64;
    public final int    MIN_LENGTH              = 6;
    StringUtil          stringUtil              = new StringUtil();

    public MediumSecurePassword() {
        super();
    }

    /**
     * Constructor method. Will throw IllegalPasswordException if password is
     * not safe. Medium Safe passwords are at least 6 characters long.
     */
    public MediumSecurePassword(String password) throws IllegalPasswordException {
        setPassword(password);
    }

    /**
     * Checks if the given character is a number
     */
    public boolean isNumber(char c) {
        // ...
    }

    /**
     * Checks is a given password is valid. Valid means that it's secure (at
     * least 8 characters, at least 1 number, at least 1 special character).
     */
    public boolean passwordValid(Password password)
        throws IllegalPasswordException {
        return passwordValid(password.toString());
    }

    /**
     * Checks is a given password is valid. Valid means that it's "medium secure" (min.
     * length of 6).
     */
    public boolean passwordValid(String password)
        throws IllegalPasswordException {

        // ...
    }

    /**
     * Sets a new password. Will throw IllegalPasswordException if password is
     * not safe. Safe passwords are at least 8 characters long, consist of
     * numbers, letters and special characters.
     */
    @Override
    public void setPassword(String password) throws IllegalPasswordException {

        if (passwordValid(password)) {
            this.password = password;
        }
    }
}

Note: If I remove these 3 lines from my mapping file everything runs smoothly:
<component name="password" class="com.foo.web.model.authentication.MediumSecurePassword">
 <property name="hash" column="PASSWORD" />
</component>

So, for me there seems to be a problem with getting the password's hash value via passwordInstance.getHash()? Not sure though.

A: What is the idea behind using a subclass of a subclass of Password in the mapping?
        <component name="password" class="com.foo.web.model.authentication.MediumSecurePassword">
            <property name="hash" column="PASSWORD" />
        </component>

What happens here is that you require a specific implementation to be serialised on the persist. In you case your object implements the parent class (SecurePassword) so it can not be cast to MediumSecurePassword.
I will advise to use the parent class in the mapping, this way you will be able to use both SecurePassword and MediumSecurePassword in your implementation:
        <component name="password" class="com.foo.web.model.authentication.Password">
            <property name="hash" column="PASSWORD" />
        </component>


text:
Q: How to make a text-box same height as the window? I want to make a text-box that has the same height as the page. For now I can only seem to make it the same height as the content I have inside the text-box. I don't know if I just haven't found the proper way to describe it with css or if it's my jQuery plugin that messes with it.
I can give it padding-top/bottom which increases the height of the text-box, but I if I give it too much padding the text gets pushed down.
The text inside the box has been given the class 'text-content' and I've applied the following css to it:
.text-content{
margin: auto;
width:40%;
font-family: 'Open Sans', sans-serif;
background-color: rgba(213,213,213,0.5);
padding-left: 10px;
padding-right: 10px;
}

Example here

A: Using CSS3, that's easily accomplished by defining a height of 100vh.
.text-content {
    margin: auto;
    width: 40%;
    font-family: 'Open Sans', sans-serif;
    background-color: rgba(213,213,213,0.5);
    padding-left: 10px;
    padding-right: 10px;
    height: 100vh;
}

JSFiddle: http://jsfiddle.net/3uczbe0s/
This does not take into account the border of the box and margin of the body, whose defaults are 1px and 8px, respectively. This means that using 100vh will actually force the page to scroll. You can easily compensate by zeroing the border of .text-content and margin of body.
The only other option is to use a script to manipulate its height, which would also be backward compatible.


text:
Q: How to go from last row to first row direstly in uitableview? iam making one application.In that iam using UITableview.In that i places one button at the last row of the tableview.How we go to first row when we click on that button.So please tell me how to solve this one.

A: Use this:
NSIndexPath *topIndexPath;
topIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[tableView scrollToRowAtIndexPath:topIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];


text:
Q: how to refer css file path I have created css file called stylesheet1.css in folder called Mystyles. See image below
I want to refer css file in my visual studio in one of my .aspx page, so i wrote something like this but its not using this stylesheet
<link href="~sitecollection/_catalogs/masterpage/MyStyles/Stylesheet1.css"  />

Please can someone tell how can i refer this? Also could be nice if there are any articles which i can read about to get idea about referring images and css files in sharepoint in different ways.

A: A correct way to reference a CSS from your master page is:
 <SharePoint:CssRegistration Name="<% $SPUrl:~sitecollection/_catalogs/masterpage/MyStyles/Stylesheet1.css %>" runat="server" After="corev15" />

Yup, surprising, but fully functionnal on my side! This is the only way to set a dynamic reference to a CSS...


text: Q: is it possible to create woocommerce website in wordpress without pro theme? is it possible to create woo-commerce website in WordPress without pro theme? I do not want customize theme and want to create website about EV Bazar.


text:
Q: Volley library and HTTPS requests I tried to look for some answers for me here, but I just fail to find anything that solves my problem.
In project I am working on we are going to change our domain. Change is bit tricky - we have to also change connection from HTTP to HTTPS. I've received .crt key (let's say, example.tech.crt - will change all of company name to "example"). After few hours of constant failures I decided to write here.
First of all, I tried using this tutorial http://ogrelab.ikratko.com/using-android-volley-with-self-signed-certificate/ - and it didn't work (I don't even mean that I had to use deprecated Apache libs because of API23). In case this is needed, this is how I created BKS file:
keytool -importcert -v -trustcacerts -file "example.tech.crt" -alias example_tech
        -keystore "example_tech.bks" -provider org.bouncycastle.jce.provider.BouncyCastleProvider
        -providerpath "bcprov-jdk16-146.jar" -storetype BKS

Then, I tried this approach Does Android Volley support SSL? - the one from best answer (with ignoring domain name check). I still tried to use BKS file - I've got some exceptions about casting errors, so I changed line:
CertificateFactory cf = CertificateFactory.getInstance("X.509");

to
CertificateFactory cf = CertificateFactory.getInstance("X.509", "BC");

as suggested somewhere - error still persisted. I tried to use .crt file instead of BKS - I still fail.
Every single time I get same error:
javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException:
SSL handshake aborted: ssl=0x650f83a0: Failure in SSL library, usually a protocol error
error:14077102:SSL routines:SSL23_GET_SERVER_HELLO:unsupported protocol
(external/openssl/ssl/s23_clnt.c:714 0x5fda0d74:0x00000000)

I tried to do pretty much same requests using Postman and they work on same address without any problem, so this is not server problem. I tried to use various domains - example.tech, www.example.tech, example.tech:80 and so on (always with https of course).
Below is example curl-like request (of course censored):
curl request: curl -X "POST"
 -D "grant_type=password&password=[passwordHere]&username=[emailHere]&"
 -H 'Authorization: Basic [tokenHere]
 "https://example.tech/oauth/token"

I fail to see what's wrong with my code and I'd be really happy to see what I am doing wrong in here. If there's any more code needed, feel free to ask for it (but 99% of it is like in second link, only with really small changes).

A: Consider this topic as example of poor comunication. After hours of trying to make this work we made to work:

*

*we are NOT using selfsigned certificates, so adding key to application is terrible idea (since they change each 3 months)

*unsupported protocol exception came from older Android APIs (<20 or <21), which are supported in this application. From I do understand (considering my poor knowledge about SSL connections) our site uses TLS, but older Android systems (pre-Lollipop I guess) have this turned off by default. Proper way of fixing this was creating custom TLSSocketFactory and using it in HurlStack used to initialize RequestQueue. After that exception disappeared.


text:
Q: scoring motifs in python dictionary I have a dictionary in python which look likes this:
raw = {'id1': ['KKKK', 'MMMMMMMMMMMMMMM'], 'id2': ['KKKKM', 'KKKKKK']}

as you see the values are list. I would like to replace the list with a number which is score. I score each character in the list based on their length. if the length is 4 to 9 they would get 1, from 10 to 15 would be 2 and 16 and longer would get 3. then I add up all scores per id and would have one score per id. here is small example:
score = {'id1': 3, 'id2': 2}

I tried this code:
score = {}
for val in raw.values():
    for i in val:
        if len(i) >=4 and len(i) <9:
            sc = 1
        elif len(i) >=10 and len(i) <15:
            sc = 2
        else:
            sc = 3
        score[raw.keys()] = sc

it did not give what I want.

A: I see two problems in your example.
The first is that there is no incrementation of the score. You should initialize a counter in the outer loop, and increment it when iterating over the items in the key.
for val in raw.values():
    score = 0
    for i in val:
        ...
        score += 1  # or 2 or 4

The second problem is that you need to access the specific key you are scoring when storing the score. As "raw.keys()" returns a list of all the keys, it doesn't make sense to use it when storing value.
Instead, your outer loop should iterate over both key and value, thus allowing you to know what key you are currently using.
for key, val in raw.items():
    ....

To summarize, here is a working example:
score = {}
for key, val in raw.items():  # iterating over both key and value (.items instead of .values)
    cur_score = 0  # initializing the current score counter
    for item in val:  # use readable names!
        item_len = len(item)  # calculated once for efficiency
        if 4 <= item_len < 9:  # the python way to check value in range
            cur_score += 1
        elif 10 <= item_len < 15:
            cur_score += 2
        else:
            cur_score += 3
        score[key] = cur_score

Have fun!

A: You tried to use the entire list of keys as an index into the dictionary.  Also, you put that assignment inside both loops.  What did you expect this to do on each iteration?
First, your outer loop has to iterate through the list of dictionary elements, not merely the values.  You would need something like:
for key, val in raw.iteritems():

Next, you need to maintain a running total of the scores for the individual strings.  You should look this up ... but the basic idea is
    total = 0
    for item in my_list:  # you have to determine what my_list should be
        sc = # score for that item
        total += sc

... and finally, after this loop ...
    score[key] = total

That should get you moving forward.

A: You need to iterate through all the key, value pairs of the dictionary and maintain a running total of the scores for each element of the dictionary values (which is a list in your case).
You can reform your code as follows to get your desired output.
raw = {'id1': ['KKKK', 'MMMMMMMMMMMMMMM'], 'id2': ['KKKKM', 'KKKKKK']}

score = {}
# iterating through all the key, value pairs of the dictionary
for key, value in raw.items():
    sc = 0
    # iterating through all the elements of the current value
    for item in value:
        if len(item) >=4 and len(item) <=9:
            sc += 1
        elif len(item) >=10 and len(item) <=15:
            sc += 2
        else:
            sc += 3
    score[key] = sc

print(score)

It outputs:
{'id1': 3, 'id2': 2}

So, the loop, for key, value in raw.items(): runs for each key, value pair of the dictionary which are 'id1': ['KKKK', 'MMMMMMMMMMMMMMM'] and 'id2': ['KKKKM', 'KKKKKK'].
Then the nested loop, for item in value: runs twice for two dictionary key's value which are ['KKKK', 'MMMMMMMMMMMMMMM'] and ['KKKKM', 'KKKKKK'].


text:
Q: Is Computationally-hard is same as NP-hard? I want to know that is there any difference between NP- hard problems and Computationally hard problems or are these two terms used for the same thing? I have tried to search the solution but cannot get some reasonable answer. Can anybody please help?

A: As of current knowledge (until that P=NP question is answered):
All NP-hard problems are computationally hard. But not all computationally hard problems are NP-hard (problems in P, with high exponents in the polynome, for example).
Note that "NP-hard" is a well defined class of problems in computer science.
"Computationally hard" on the other hand isn't, as far as I know.


text:
Q: Linear program to model given problem Here is the problem I'm trying to solve:
"A company makes three products, named product A, product B and product C. The company has 4 available workers, and the workers have different rates as they work on each of the three products. Also, because of the nature of their contracts, the workers charge a different amount depending on which product they are working on. The time it takes for worker i to make on product of time A, B or C, and the amount they charge depending on the product, are summarized in the two tables given.
Table 1: Time in minutes it takes Worker i to make one unit of product j.
Table 2: Amount paid by company for one hour of Worker i when working on product j.
(I'm not able to create the actual tables here, but it's pretty easy to get an idea of what the tables structure is from the table descriptions above)
Suppose each worker works for 40 hours each week. Due to the company's commitments to existing customers, the company must produce at least 100 units of product A, 150 units of product B and 100 units of product C. Write a linear program that will tell the company how to assign each worker in order that the demand for each widget is met, and cost to the company is minimized.
Thus, you must state what are the decision variables, and then what is the vector corresponding to the objective function, the matrix corresponding to the constraints, etc."
I've spent hours trying to formulate this as a linear program and the only approach that I could think of was to minimize the total cost by making it of the form min CX where each element of C i.e. C(i)(j) denotes the amount worker i charges to work on product j per unit time and each element of X i.e. X(i)(j) denotes the total time worker i spends working on product j. But this is obviously not the right approach as C and X are supposed to be vectors. I've tried searching for problems that might be similar to this but couldn't find any.

A: You're on the right track. You can squash the $C$ and $X$ matrices into vectors. For instance, suppose that you have two workers and three products, so that $C$ and $X$ are 2x3 matrices. Let $c=(C_{11}, C_{12}, C_{13}, C_{21}, C_{22}, C_{23})$ and let $x = (X_{11}, \dots, X_{23})$. Now you have vectors.

A: Let consider a planning time period made of 1 week. Every worker works 8 hours per day and 5 days per week, so that the amount available of time for working per week is equal to $40$ hours $= 2,400$ minutes.
Let introduce $4 \cdot 3 = 12 $ positive integer variables designated as $x_{i,j}$ where $i=1,2,3,4$ and $j=1,2,3$.
$x_{i,j}$ represents the quantity of j-th product made by i-th worker, clearly it should be a positive integer.
$a_{i,j}$ is time in minutes taken by Worker i to make one unit of product j.
$b_{i,j}$ is cost paid by company for one hour of Worker i when working on product j
We want to meet the weekly demand of the three products, spending as minimum as possible.
The objective function can be properly formulated as
$ \min \sum_{i=1}^4 \sum_{j=1}^3  (a_{i,j}/60) \cdot b_{i,j} \cdot x_{i,j}  $
subject to
$\left\{ \begin{array}{l}
\sum_{i=1}^4 x_{i,1} \geq 100 \\
\sum_{i=1}^4 x_{i,2} \geq 150 \\
\sum_{i=1}^4 x_{i,3} \geq 100 \\
\sum_{j=1}^3  a_{1,j} x_{1,j} \leq 2,400 \\
\sum_{j=1}^3  a_{2,j} x_{2,j} \leq 2,400 \\
\sum_{j=1}^3  a_{3,j} x_{3,j} \leq 2,400 \\
\sum_{j=1}^3  a_{4,j} x_{4,j} \leq 2,400 \\
x_ij \in N \forall i=1,2,3,4 \forall j=1,2,3 \\
\end{array} \right. $
$ \sum_{i=1}^4 x_{i,j} \geq c_j $ designates the constraint on weekly demand for j-th product where $c_j $ is the demand for j-th product.
$ \sum_{j=1}^3  a_{i,j} x_{i,j} $ is the working time spent by i-th worker, so $ \sum_{j=1}^3  a_{i,j} x_{i,j} \leq 2,400 $ designates the constraint on the total amount of minutes available for i-th worker in one week.


text:
Q: How do you find Sean Parent's "Shoe laces and beans" data structure instead of tree I just watched Sean Parent's CppCon 2015 talk "Better Code: Data Structures", where he suggested a "Shoe laces and beans"
data structure instead of tree.

How do you find it? Do you think this is better than tree? what would be its strength what's price?

A: The shoelace is easy to produce, as it correspond to a left recursive descent of the corresponding tree. So starting from a tree, you just have to descent it once and build the lace dynamically. After that, you doesn't need recursion anymore as the lace is simply a linked list of elements ordered as in the left recursive descent.
Better than tree ? It depends on what you want to do.

A: Better is always depending on what you measure.
Here some possibilities for quality metrics:

*

*memory usage

*random access speed

*traversal speed

*...

You can also look at worst case behavior or average case behavior.
So 'better' depends a lot on for what you will use it under which environment conditions / restrictions.
At least it has better cache-miss (and cache prefetch) characteristic while traversing it than a usual tree structure. That's because the elements are in order of traversal in the memory.


text:
Q: Link error while using QAudioDeviceInfo in QT console application I have created simple QT console application in Visual Studio 2019
Following is the code
int main(int argc, char* argv[])
{
    QCoreApplication a(argc, argv);
    std::cout << "Available Audio devices ";
    QList<QAudioDeviceInfo> audioDevices = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput);

    return a.exec();
}

When compiledi am getting the following link error
>------ Build started: Project: AVSyncTesting, Configuration: Debug x64 ------
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __cdecl QAudioDeviceInfo::~QAudioDeviceInfo(void)" (__imp_??1QAudioDeviceInfo@@QEAA@XZ) referenced in function "public: void * __cdecl QAudioDeviceInfo::`scalar deleting destructor'(unsigned int)" (??_GQAudioDeviceInfo@@QEAAPEAXI@Z)
1>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: static class QList<class QAudioDeviceInfo> __cdecl QAudioDeviceInfo::availableDevices(enum QAudio::Mode)" (__imp_?availableDevices@QAudioDeviceInfo@@SA?AV?$QList@VQAudioDeviceInfo@@@@W4Mode@QAudio@@@Z) referenced in function main

A: Try to use this code to get devices:
const auto deviceInfos = QAudioDeviceInfo::availableDevices(QAudio::AudioOutput);
for (const QAudioDeviceInfo &deviceInfo : deviceInfos)
    qDebug() << "Device name: " << deviceInfo.deviceName();


text:
Q: How to tell when an Entropy Key is overloaded? I have several Entropy Keys with egd in front of them and then all load balanced by haproxy. I then have many client machines using the haproxy service IP as a network source of entropy. I have no idea how much entropy they are requesting.
The Entropy Keys can produce a limited amount of usable entropy. The specs say about 30 kilobit/sec minimum. As far as I can see, the Entropy Key doesn't have a way to query how much it is being asked for. The EGD protocol seems quite hard to sniff to find this information. Clients can request a variable amount of entropy, and they might not get back the same amount.
Has anyone found a simple way to measure how much is being requested from an Entropy Key?
It would be good to know, in order to be able to plan when additional keys are required, and to spot haywire clients.

A: The only two things that come to mind is trying to measure the response time of your entropy server (there should be a significant increase in latency if it can't keep up) or pooling /proc/sys/kernel/random/entropy_avail and monitoring how much entropy you have (I'm assuming that egd is using /dev/random and not the hardware directly).

A: It looks like the source tarball for ekeyd has a munin plugin for providing ekey statistics.
Even if you're not running munin I guess it would be possible to extrapolate the script into something usable for your infrastructure.
I think we both know the authors of the device and software though, so might be worth prodding them. :-)

A: Try:
dd if=/dev/random of=/dev/null bs=1K count=1M

When it finishes, dd will report the read bandwidth, so you will know the amount of entropy provided. You can run it in the server (disconnected from its clients) to measure entropy production, and in the clients, to measure how much are they receiving.
Killing the running dd process with SIGUSR1 signal will instruct it to report its I/O statistics, so you don't need to wait for it to finish (see man dd).
Also, clients should expose an increase in their download-bandwidth consumption, because of the entropy being read from the server (e.g.: nethogs plus netstat).


text:
Q: C# My computer calculates floats wrongly while in other computers, it works I have been following a course online for c# and I am stuck on this code.
Here is the code:
using System;

namespace ProgrammingAssignment2
{
    // IMPORTANT: Only add code in the section
    // indicated below. The code I've provided
    // makes your solution work with the
    // automated grader on Coursera

    /// <summary>
    /// Programming Assignment 2
    /// </summary>
    class Program
    {
        // x and y coordinates for points
        static float point1X;
        static float point1Y;
        static float point2X;
        static float point2Y;

        /// <summary>
        /// Programming Assignment 2
        /// </summary>
        /// <param name="args">command-line args</param>
        static void Main(string[] args)
        {
            // loop while there's more input
            string input = Console.ReadLine();
            while (input[0] != 'q')
            {
                // extract point coordinates from string
                GetInputValuesFromString(input);

                // Add your code between this comment
                // and the comment below. You can of
                // course add more space between the
                // comments as needed

                 float deltaX = point2X - point1X;
                float deltaY = point2Y - point1Y;
                float distance = (float)Math.Sqrt(Math.Pow(deltaX, 2) + Math.Pow(deltaY, 2));

                float angle = (float)Math.Atan2(deltaX, deltaY);
                angle = (angle * 180) / (float)Math.PI;

                Console.WriteLine(distance + " " + angle);

                // Don't add or modify any code below
                // this comment
                input = Console.ReadLine();
            }
        }

        /// <summary>
        /// Extracts point coordinates from the given input string
        /// </summary>
        /// <param name="input">input string</param>
        static void GetInputValuesFromString(string input)
        {
            // extract point 1 x
            int spaceIndex = input.IndexOf(' ');
            point1X = float.Parse(input.Substring(0, spaceIndex));

            // move along string and extract point 1 y
            input = input.Substring(spaceIndex + 1);
            spaceIndex = input.IndexOf(' ');
            point1Y = float.Parse(input.Substring(0, spaceIndex));

            // move along string and extract point 2 x
            input = input.Substring(spaceIndex + 1);
            spaceIndex = input.IndexOf(' ');
            point2X = float.Parse(input.Substring(0, spaceIndex));

            // point 2 y is the rest of the string
            input = input.Substring(spaceIndex + 1);
            point2Y = float.Parse(input);

            #region Unfortunately, Mono doesn't have a Split method!
            //string[] values = input.Split(' ');
            //point1X = float.Parse(values[0]);
            //point1Y = float.Parse(values[1]);
            //point2X = float.Parse(values[2]);
            //point2Y = float.Parse(values[3]);
            #endregion
        }
    }
}

When the somebody else runs the code and inputs '5 5 4 4' it is supposed to output '1.414214 -135' which is what is supposed to output but when I do it, it outputs '1,4142135 -135' I have no idea why it is like this. Please help.
but


text:
Q: java.lang.NullPointerException: Attempt to invoke virtual method '' on a null object reference I want/try to show Popup Window on first launch app but got this error

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.PopupWindow.showAtLocation(android.view.View, int, int, int)' on a null object reference

I make overlay activity to start the app with Popup on first launch.
MainActivity.java
public class MainActivity extends AppCompatActivity implements NetworkStateReceiver.NetworkStateReceiverListener {

    //PopUp
    Context popupContext;
    Activity popupActivity;
    PopupWindow popupWindow;
    RelativeLayout popupLayout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        popupWindow.showAtLocation(popupLayout, Gravity.CENTER, 0, 0);

        (***)

        //Start PopUp
        popupContext = getApplicationContext();
        popupActivity =  MainActivity.this;
        LayoutInflater inflater = (LayoutInflater) popupContext.getSystemService(LAYOUT_INFLATER_SERVICE);
        View popupView = inflater.inflate(R.layout.activity_start, null);
        popupWindow = new PopupWindow(popupView,
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);
        if (Build.VERSION.SDK_INT >= 21){
            popupWindow.setElevation(5.0f);
        }
    }
}

Error Message
05-08 09:48:18.612 7398-7398/id.nax.androidstate E/AndroidRuntime: FATAL EXCEPTION: main
    Process: id.nax.androidstate, PID: 7398
    java.lang.RuntimeException: Unable to start activity ComponentInfo{id.nax.androidstate/id.nax.androidstate.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.PopupWindow.showAtLocation(android.view.View, int, int, int)' on a null object reference
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3319)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7406)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)
     Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.PopupWindow.showAtLocation(android.view.View, int, int, int)' on a null object reference
        at id.nax.androidstate.MainActivity.onCreate(MainActivity.java:53)
        at android.app.Activity.performCreate(Activity.java:6904)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1136)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3266)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3415)
        at android.app.ActivityThread.access$1100(ActivityThread.java:229)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1821)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:7406)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

Any Suggestion to solve my code or better method to make Popup Window?

A: You're trying to call showAtLocation(...) before you actually create the PopupWindow.
    popupWindow.showAtLocation(popupLayout, Gravity.CENTER, 0, 0);

    (***)

    //Start PopUp
    popupContext = getApplicationContext();
    popupActivity =  MainActivity.this;
    LayoutInflater inflater = (LayoutInflater) popupContext.getSystemService(LAYOUT_INFLATER_SERVICE);
    View popupView = inflater.inflate(R.layout.activity_start, null);
    popupWindow = new PopupWindow(popupView,
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);
    if (Build.VERSION.SDK_INT >= 21){
        popupWindow.setElevation(5.0f);
    }

You can do it like this instead, I also refactored the code to be a little bit cleaner for you.
    // The View you're making the popup in regards to.
    View parent = findViewById(R.id....);

    View popupView = LayoutInflater.from(this).inflate(R.layout.activity_start, null);
    popupWindow = new PopupWindow(popupView,
            RelativeLayout.LayoutParams.MATCH_PARENT,
            RelativeLayout.LayoutParams.MATCH_PARENT);

    if (Build.VERSION.SDK_INT >= 21){
        popupWindow.setElevation(5.0f);
    }
    popupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);

A: You call this method on a null object you need to call it after you create the popupwindow and not before.
Put the the call after the line:
popupWindow = new PopupWindow(popupView,
                RelativeLayout.LayoutParams.MATCH_PARENT,
                RelativeLayout.LayoutParams.MATCH_PARENT);


text:
Q: Como bloquear a edição de um registro quando esta a ser editado por um outro usuario C# Em um sistema em rede(Vários utilizando o mesmo banco de dados), como faço para saber se algum usuário já esta editando o registro. Pois se no caso dois computadores editarem o mesmo registro ao mesmo tempo, ocorre um problema pois só serão salvas as alterações do ultimo usuário que editou.

A: Se estiver usando o Entity Framework, utilize o Data Annotation [ConcurrencyCheck], que o próprio contexto irá lhe auxiliar a tratar a concorrência, verifique em http://www.entityframeworktutorial.net/code-first/concurrencycheck-dataannotations-attribute-in-code-first.aspx. Verifique também o link passado no comentário do @QMechanic73, https://msdn.microsoft.com/en-us/library/aa0416cz%28v=vs.110%29.aspx


text:
Q: Obligated Bibliography for Quantum Gravity I am a graduate student who wants to begin to get into Quantum Gravity. I've looked on internet for bibliography and I've found a lot of great books, but I would like to start from the beginning (of topics related to quantum gravity, the general relativity and quantum mechanics basis I already have). I'm not looking bibliography of any particular quantum gravity theory, but something more global, like an historical overview, the current state or, if I may ask for too much, any book describing how such theory should be. Also, I'm looking for formal bibliography, not for-all-ages books.
If anyone who's adept into this topic could help me, I would appreciate it so much.

A: I think you would be very interested in the book Conversations on Quantum Gravity edited by J. Armas. The book consists of a series of interviews (37, to be precise) that Armas (who is a theoretical physicist) conducted with researchers in quantum gravity. It is definitely not a textbook or a rigorous review, but many of the interviews dive quite deep into substantive physics, and each interview includes a very thorough list of references to papers on the topics discussed. I don't think you are going to do much better than this for a bird's-eye view of "the field of quantum gravity" as a whole, especially since it's unclear as of yet what "quantum gravity" is even supposed to mean.

A: There's a text by Carlo Rovelli (worldly known for his contributions to Loop Quantum Gravity) telling a brief history of Quantum Gravity from its early stages (back in the 1930s) up to 2000. It is available at arXiv: gr-qc/0006061.
There's also the book Approaches to Quantum Gravity, edited by Daniele Oriti, which includes expositions of many of the main current approaches (including, but not restricted to, strings, loops, asymptotic safety, emergent relativity, discrete quantum gravity, and others). Might be a good start to get an overview of many different things.
R Percacci's An Introduction to Covariant Quantum Gravity and Asymptotic Safety focuses on Asymptotically Safe Quantum Gravity, but it also deals with many other interesting things, such as a historical overview, linearizations, the fact that quantized GR is not perturbatively renormalizable, and so on. Most of its calculations could be a bit more open, but it is a really nice presentation.


text:
Q: Set context on Google Actions through Dialogflow fulfillment I'm using the Dialogflow editor fulfillment to build a conversation on Google Assistant, but I'm not sure how to use the agent.setContext function.
When I ask "Turn off my device" the first step returns successfully. The problem happens when the user responds with "TV", for example. The system returns with another context, ignoring the one I set.
When the user directly asks "Turn off my TV in the kitchen" the system also works perfectly. Because of it I think that the entities are correctly defined.
Conversation 1 (success):

*

*Turn off my TV in the kitchen

*Right. Turning off.
Conversation 2 (fail):

*

*Turn off my device //Gives the same intent that Conversation 1

*OK, which device?

*TV

*"My bot" isn't responding right now. Try again soon. //It throws "'final_response' must be set". I think it's because of generic intent actions.intent.TEXT.
My code:
The code below is nested in exports.dialogflowFirebaseFulfillment = functions.https.onRequest and the intent is called by intentMap.set('smarthome.device.switch.off', setDeviceOff);

const agent = new WebhookClient({ request: request, response: response });

function setDeviceOff(agent) {
    const device = agent.parameters.device;
    const room   = agent.parameters.room;
    const context= 'device-switch'; //I tried 'smarthome.device.switch.off' too
      let resp = commandDevice(device, room, 'Off', agent, context);
      return resp;
}

function commandDevice(device, room, cmd, agent, context) {
    var conv = agent.conv();
    if(device===''){
        conv.ask("OK, which device?");
    }else if (room===''){
        conv.ask("Got it. of what room?");
    }else{
        conv.ask("Right. Turning off.");
    }
    agent.setContext({
        name:context,
        lifespan: 5, //Tried 0, 4 and 3 too
        parameters:{
            'device':device,
            'room':room
        }
    });
    agent.add(conv);
    return true;
}

So I tried another version and the same problem persists:
const app = dialogflow();
app.intent('welcome', conv =>{
   conv.ask("Welcome to auto obari. What can I do for you?");
});
app.intent('Default Fallback Intent',conv =>{
   conv.ask("I didn't understand, can you try again?");
});
app.intent('smarthome.device.switch.off', (conv,{device, room})=> {
    const context= 'device-switch';
    if(device===''){
        conv.ask("OK, which device?");
    }else if (room===''){
        conv.ask("Got it. of what room?");
    }else{
        conv.ask("Right. Turning off.");
    }
    const parameters = {'device':device, 'room': room};
    conv.contexts.set(context, 5, parameters);
});
exports.dialogflowFirebaseFulfillment = functions.https.onRequest(app); //I tried exports.factsAboutGoogle, but it threw a error too.

The contexts are the same, but the intent is different.

A: If using conv, you may also try like this:
app.intent('<INTENT>', conv => {
  conv.ask('<RESPONSE>');
  const parameters = {'param1':param1, 'param2': param2}};
  conv.contexts.set('welcome-context', 5, parameters);
});

and access it like here :
const conv.contexts.get(<context>).parameters[<param>];

A: you can try this method too it worked for me
const AppContexts = {CONTEXT_ONE: 'context-one'};
const app = dialogflow();

In current intent (for output context)
conv.contexts.set(AppContexts.CONTEXT_ONE, 1);

In next intent (for input context )
const context = conv.contexts.get(AppContexts.CONTEXT_ONE);


text:
Q: Print 95 factorial as a number and not as exponential function When the input is 25 the expected output is 15511210043330985984000000 and not 1.551121e+25. The parsing though is solved by Decimal.Parse(factorial.ToString(), System.Globalization.NumberStyles.Float).
I cannot get to calcuate for bigger numbers like 95.
using System;

namespace bigNumber
{
    class Program
    {
        static void Main(string[] args)
        {
            int number = Convert.ToInt32(Console.ReadLine());
            long factorial = 1;

            for (int i = number; i > 0; i--)
            {
                factorial = factorial * i;
            }

            Console.WriteLine(factorial);
        }
    }
}

A: You have to use BigInteger in your solution:
using System.Numerics;
using System.Linq;
...
int n = 95;

BigInteger factorial = Enumerable
  .Range(1, n)
  .Select(x => (BigInteger) x)
  .Aggregate((f, v) => f * v);

Console.WriteLine(factorial);

Answer is

10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000

note, that the factorial is far beyond long.MaxValue

A: As stated above, the BigInteger is a good candidate, as it can hold an arbitrarily large signed integer:
namespace ConsoleApplication4
{
    using System;
    using System.Numerics;

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(Factorial(0));

            Console.WriteLine(Factorial(25));

            Console.WriteLine(Factorial(95));
        }

        private static BigInteger Factorial(int number)
        {
            BigInteger factorial = 1;

            for (var i = number; i > 0; i--)
            {
                factorial *= i;
            }

            return factorial;
        }
    }
}

1
15511210043330985984000000
10329978488239059262599702099394727095397746340117372869212250571234293987594703124871765375385424468563282236864226607350415360000000000000000000000
Press any key to continue . . .

A: The BigInteger class from .Net 4.0+ supports arbitrarily large integers, int is relatively limiting in how many significant digits it represents.


text:
Q: JQuery Autocomplete - Retrieve Data from 2 Search Terms I am trying to capture a 2nd term to display results, so textbox1 has autocomplete feature and textbox2 has simple input - this is the code to autocomplete and return values on 1 term...
//connect to your database

$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends

$qstring = "SELECT description as value,id FROM test WHERE description LIKE '%".$term."%'";

$result = mysql_query($qstring);//query the database for entries containing the term

while ($row = mysql_fetch_array($result,MYSQL_ASSOC))//loop through the retrieved values
{
    $row['value']=htmlentities(stripslashes($row['value']));
    $row['id']=(int)$row['id'];
    $row_set[] = $row;//build an array
}

echo json_encode($row_set);//format the array into json data

I need something like this
$term = trim(strip_tags($_GET['term']));
$term2 = trim(strip_tags($_GET['term2']));

$qstring = "SELECT description as value, lastname, id FROM test
            WHERE description LIKE '%".$term."%'" AND lastname LIKE '%".$term2."%'";

etc...

Can anyone help?


text:
Q: CakePHP 3.x update records with jQueryUI Sortable In one of the views I have implemented a list that can be reordered by drag and drop with jQueryUI Sortable.
The output of the list in meetings.ctp looks like following:

    <?php foreach($meetings as $meeting): ?>

>
      <?php echo  $meeting['name'] . ' ' . $meeting[place]; ?>

    <?php endforeach; ?>

The list of meetings is provided based on priority:
$upcommingMeetings_query = $this->MeetingsTasks->find('all')
    ->order(['Meetings.priority' => 'ASC']);

What I need to get done is to update the priority of a Meeting record once it it has been moved. However, I can only find example for how to do this in older versions of CakePHP using JsHelper which is no longer available.
Any help or guidance is much appreciated. If there is any code that I should have shared, please ask for it.

A: First of all remove extra > from line
> and then use the stop event of sortable
$( "#selector" ).sortable({
  stop: function( event, ui ) {
    //Invoke the serialize method:
    var sorted = $(this).sortable('serialize');
    console.log(sorted);
    //output: 'sort[]=4&sort[]=1&sort[]=2&sort[]=5&sort[]=3'
    //here goes your ajax request to server
    $.ajax({
       url: 'someURL',
       cache: false,
       type: 'post',
       data: sorted,
       success: function(result) {//parse it here}
    });
  }
});

Your .ctp code should be something like this:

    <?php foreach($meetings as $meeting): ?>
        <li class="ui-state-default" id="sort-<?php echo $meeting['id']; ?>">
           <?php echo  $meeting['name'] . ' ' . $meeting['place']; ?>

    <?php endforeach; ?>

You can customize <li class="ui-state-default" id="sort-<?php echo $meeting['id']; ?>"> this part by replacing sort with anyhing you want.
On controller part you will have to parse it in foreach loop and update your db accordingly, or you may save as it is. working link


text:
Q: Find duplicates, sum corresponsive and post the sums in a new column Excel VBA I'm new here, but i hope i can get an answer to my question anyway
I tried searching for my problem but couldn't find a thread so sorry if there's already a similar thread.
I have several files that contains several lists in columns A to T. I need to find duplicates in a column and sum the corresponsive cells which are in a different column and then add the result in a new column.
I already have a code that does what i need but not exactly how i want it. The problem is this code write the results in the same row as the first (name) of the duplicates. So if my list is like this it'll write the result like shown below:
A B C
a 5 10
a 2
a 3
b 2 6
b 3
b 1
c 4 7
c 1
c 2

I want it to write the results in rows 1,2 and 3 instead of showing blanks until the "right" row. I also want to carry over the name of the type next to the results. Like so:
Name Results
a 10
b 6
c 7

`
Sub sample()

Dim lastRow As Integer, num As Integer, i As Integer
lastRow = Range("C65000").End(xlUp).Row

For i = 14 To lastRow
num = WorksheetFunction.Match(Cells(i, 3), Range("C1:C" & lastRow), 0)
If i = num Then
Cells(i, 25) = WorksheetFunction.SumIf(Range("C1:C" & lastRow), Cells(i, 3), Range("J1:J" & lastRow))
Cells(i, 25).Interior.Color = vbGreen
Else
Cells(i, 3).Interior.Color = vbYellow
End If
Next i

End Sub

`
I've tried tweeking the code abit but i just don't get how to make it so i get what i need.. :/
Thanks for any help
Another problem i have with the code, if there's a blank row (which happens alot) the code only works for the rows until the blank then quit and tells me there's a problem.

A: Try this, works for me.
Application.ScreenUpdating = False
Range("c:c").Clear
For i = 1 To Sheet1.UsedRange.Rows.Count
    alreadythere = False
    For k = 1 To i
        If Cells(k, 1) = Cells(i, 1) Then
            alreadythere = True
            Exit For
        End If
    Next k
    If alreadythere = False Then
        Cells(i, 3) = Cells(i, 2)
      Else
        Cells(k, 3) = Cells(k, 3) + Cells(i, 2)
    End If
Next i
Application.ScreenUpdating = True


text:
Q: node.js File upload configurations No Matter how much I've searched and changed and toyed over the last 24 hours, I simply can not find the right combination of settings that allows Node.js to upload multiple files.
My setup is quite simple - I have a form interface that posts multipart content (files) to an endpoint.. lets call it: /theendpoint
and this end point is supposed to parse the multiple files. However, during the parsing, there are various events that need to be called once the file is uploaded.
I'm currently using the express.bodyParser({ uploadDir:'/tmp', keepextensions:true, defer:true}); in the app configuration.
Using the following method, I am trying to parse the file, but the problem is

Only 2 files will begin uploading, and will not complete (ie. the progress bar hangs near the end without fully completing).
The other files to be uploaded by the form (item 3+) do not even begin to upload to the server.

It seems to be some sort of asynchronus holdup, however I can't properly interpret the problem. Some of the code used at the upload endpoint are as follows:
// This applies to /theendpoint route. Using Express.
exports.theendpoint = function(req,res){
   console.log(req.files);
   fs.readfile(uploadPath, function(err,data){

      if(err) throw err;
      fs.writeFile(newFilePath, data, function(err){
         // Series of checks and definitions
         // Database connection
         // Conditional executions

         fs.unlink(req.files.file.path, function(err){
            if(err) throw err;
            console.log('Deleted');
         });
      });
   });
};

Obviously I've left out some of the code here. If anyone can help - is this structure workable?
You should know that items in the commented section.. ie DB connection etc. are asynchronus tasks.

A: after
fs.unlink(req.files.file.path, function(err){
   if(err) throw err;
   console.log('Deleted');
});

add
res.redirect("back");

and it works!


text:
Q: grok filter fails for ISO8601 timestamps since 5.2 since I've upgraded our ELK-stack from 5.0.2 to 5.2 our grok filters fail and I've no idea why. Maybe I've overlooked something in the changelogs?
Filter
filter {
  if [type] == "nginx_access" {
    grok {
      match => { "message" => "%{IPORHOST:remote_addr} - %{USERNAME:remote_user} \[%{TIMESTAMP_ISO8601:timestamp}\] \"%{WORD:method} %{URIPATHPARAM:request} HTTP/%{NUMBER:httpversion}\" %{INT:status} %{INT:body_bytes_sent} %{QS:http_referer} %{QS:http_user_agent} \"%{DATA:host_uri}\" \"%{DATA:proxy}\" \"%{DATA:upstream_addr}\" \"%{WORD:cache_status}\" \[%{NUMBER:request_time}\] \[(?:%{NUMBER:proxy_response_time}|-)\]" }
      add_field => [ "received_at", "%{@timestamp}" ]
    }
    mutate {
      convert => {
        "proxy_response_time" => "float"
        "request_time" => "float"
        "body_bytes_sent" => "integer"
      }
    }
  }
}

Error
Invalid format: \"2017-02-05T15:55:38+01:00\" is malformed at \"-02-05T15:55:38+01:00\"

Full Error
[2017-02-05T15:55:49,500][WARN ][logstash.outputs.elasticsearch] Failed action. {:status=>400, :action=>["index", {:_id=>nil, :_index=>"filebeat-2017.02.05", :_type=>"nginx_access", :_routing=>nil}, 2017-02-05T14:55:38.000Z proxy2 4.3.2.1 - - [2017-02-05T15:55:38+01:00] "HEAD / HTTP/1.1" 200 0 "-" "Zabbix" "example.com" "host1:10040" "1.2.3.4:10040" "MISS" [0.095] [0.095]], :response=>{"index"=>{"_index"=>"filebeat-2017.02.05", "_type"=>"nginx_access", "_id"=>"AVoOxh7p5p68dsalXDFX", "status"=>400, "error"=>{"type"=>"mapper_parsing_exception", "reason"=>"failed to parse [timestamp]", "caused_by"=>{"type"=>"illegal_argument_exception", "reason"=>"Invalid format: \"2017-02-05T15:55:38+01:00\" is malformed at \"-02-05T15:55:38+01:00\""}}}}}

The whole thing works perfectly on http://grokconstructor.appspot.com and the TIMESTAMP_ISO8601 still seems the right choice (https://github.com/logstash-plugins/logstash-patterns-core/blob/master/patterns/grok-patterns)
Techstack

*

*Ubuntu 16.04

*Elasticsearch 5.2.0

*Logstash 5.2.0

*Filebeat 5.2.0

*Kibana 5.2.0

Any idas?
Cheers,
Finn
UPDATE
So this version works for some reason
filter {
  if [type] == "nginx_access" {
    grok {
      match => { "message" => "%{IPORHOST:remote_addr} - %{USERNAME:remote_user} \[%{TIMESTAMP_ISO8601:timestamp}\] \"%{WORD:method} %{URIPATHPARAM:request} HTTP/%{NUMBER:httpversion}\" %{INT:status} %{INT:body_bytes_sent} %{QS:http_referer} %{QS:http_user_agent} \"%{DATA:host_uri}\" \"%{DATA:proxy}\" \"%{DATA:upstream_addr}\" \"%{WORD:cache_status}\" \[%{NUMBER:request_time}\] \[(?:%{NUMBER:proxy_response_time}|-)\]" }
      add_field => [ "received_at", "%{@timestamp}" ]
    }
    date {
        match => [ "timestamp" , "yyyy-MM-dd'T'HH:mm:ssZ" ]
        target => "timestamp"
    }
    mutate {
      convert => {
        "proxy_response_time" => "float"
        "request_time" => "float"
        "body_bytes_sent" => "integer"
      }
    }
  }
}

If someone can shed some light why I have to redefine a valid ISO8601 date I would be happy to know.

A: Make sure you specify the format of timestamp you are expecting in your documents, where the mapping could look like:
PUT index
{
  "mappings": {
    "your_index_type": {
      "properties": {
        "date": {
          "type":   "date",
          "format": "yyyy-MM-ddTHH:mm:ss+01:SS" <-- make sure to give the correct one
        }
      }
    }
  }
}

If you do not specify it correctly, Elasticsearch will expect  the timestamp value in format of ISO. OR you could do a date match for your timestamp field, which could look something like this within your filter:
date {
    match => [ "timestamp" , "yyyy-MM-ddTHH:mm:ss+01:SS" ] <--match the timestamp (I'm not sure what +01:ss stands for, make sure it matches)
    target => "timestamp"
    locale => "en"
    timezone => "UTC"
}

Or you could add a new field and match that to the timestamp if you wish, and then you could remove it if you aren't really using it, since you have the timestamp on the new field. Hope it helps.


text:
Q: SQL Query throws error "failed to convert parameter value from a Guid to String' I'm trying to get the UserName and put it in TempData but I get an error when the code reaches the ExecuteReader() method.
Here's my query code:
var InvoiceId = TempData["newinvoice"];
TempData["invoiceid"] = InvoiceId;
var UserID = TempData["UserID"];

string connection = "Data Source=.;Initial Catalog=project;Integrated Security=true;";

using (SqlConnection sqlconn = new SqlConnection(connection))
{
    using (SqlCommand sqlcomm = new SqlCommand("SELECT UserName FROM AspNetUsers WHERE Id = @id"))
    {
        sqlcomm.Parameters.Add("@id", SqlDbType.VarChar).Value = UserID;

        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            sqlcomm.Connection = sqlconn;
            sqlconn.Open();

            sda.SelectCommand = sqlcomm;

            SqlDataReader sdr = sqlcomm.ExecuteReader();

            while (sdr.Read())
            {
                TempData["UserId"] = sdr["UserName"];
            }
        }
    }
}

The User Id from TempData["UserID"] is an nvarchar(450) not an integer. I have no clue why that exception is happening - any help?
Note: here's an example from one of my user ids:
'aa776084-053e-452c-8b0d-b445cdbf457d'

A: It looks like your id is a uniqueidentifier and if so I would recommend changing your database and code to use GUIDs.
However to fix your problem, you should be able to pass in the UserId and call toString() (as the value is most likely an object) e.g:
sqlcomm.Parameters.Add("@id", SqlDbType.NVarChar, UserID.ToString());

If you're only going to return one results, maybe use ExecuteScalar()
    using (SqlConnection sqlconn = new SqlConnection(connection))
    {
        using (SqlCommand sqlcomm = new SqlCommand("SELECT TOP 1 UserName from AspNetUsers where Id=@id", sqlconn)
        {
            sqlcomm.Parameters.Add("@id", SqlDbType.NVarChar, UserID.ToString());
            object result = sqlcomm.ExecuteScalar();
            if (result != null)
            {
                TempData["UserId"] = result.ToString(); // It looks like you're mixing UserId & UserName .
            }
        }
    }


text:
Q: IISExpress error in Visual Studio 2015 After updating to Visual Studio 2015, IISExpress stopped working properly.
Each time I start up a new instance of VS I'll get an error that it cannot write to the Applicationhost file because the site already exists.
<site name="MySite" id="1">
  <application path="/">
     <virtualDirectory path="/" physicalPath="%SystemDrive%\inetpub\MySite" />
  </application>
  <bindings>
     <binding protocol="http" bindingInformation="*:6231:" />
     <binding protocol="https" bindingInformation="*:6231:" />
  </bindings>
</site>

If I remove the site, see above, from the applicationhost.config file (in the .vs folder) and go back to visual studio and tell it to create a new Virtual Directory everything starts working again. But as soon as I restart my instance of Visual Studio I need to do the same all over again.
It's pretty annoying having to do this process each time I need to start Visual Studio
All suggestions appreciated.

A: Find the applicationhost.config file, it may be somewhere like C:\Users\yourName\Documents\IISExpress\config\applicationHost.config.
Check the IISExpress folder to make sure it's not read only. If it is read only, make it not read only, and apply those changes to all subfolders.
Also check to make sure this folder is not encrypted, and make sure the Documents folder is not encrypted also.
Try running Visual Studio as Administrator and see if that makes a difference.
There are additional things you can try on this Stack Overflow post


text:
Q: how many disks can saturate a 6GSAS controller ? :LSI 9260-8i This is my build:

*

*LSI 9260-8i: MAX read throughput of 2,875 MB/s, write performance of 1,800 MB/s

*24x SAS 10K RPM drives

*2x 100GB Dell SSDR (SATA) drives for ZIL and L2ARC

All plugged to same controller.

*

*With ZFS as the file system, can the LSI9260-8i sustain the peak loads?

*Do I need dedicated RAID controller for SSD's?

*Can use any SATA RAID like SAS6i?

A: The LSI 9260-8i has 8 x 6Gb/s SAS ports and that's the amount of throughput you'll get.
However, depending on your workload/application, disks rarely run at 100% throughput. It's more likely you'll reach the max number of IOPS of your disks (unless you're doing bulk reads, streaming, etc).
It also depends on how your SAS backplane "exports" these disks. For instance, some backplanes will have as many mini-SAS or standard SAS ports as there are disks. Others will use an expander like the SuperMicro 846E1 (24 disks for a mini-SAS x4 port).
SuperMicro has a chassis that (TQ edition) that exports all disks individually, in that case you'd need 3 x 8-port HBAs to connect all 24-disks. It makes cable management a bit trickier but has better performance.
My suggestion is that you first determine what workload your application will be throwing at this server before considering it doesn't fit your needs. If it's a NAS/SAN appliance, pay attentio

A: You're going through a SAS expander based on this setup. You typically don't want your SSDs to go through an expander. You'd be better off connecting each of your SSDs directly to a motherboard SATA port or a dedicated controller. You can probably get away with having the L2ARC SSD on the LSI controller, but definitely not the ZIL device.


text:
Q: How to get audit history data using web api in 2016 on premise CRM I need to get the audit history details for specific record wise using web api only not though custom code.
I tried to get the audit history by using the below code. But it is not returning the required information as I need the old and value column wise.
https://xxxxx/api/data/v8.2/audits?$filter=_objectid_value%20eq%20AFF6BF88-8A78-CDAE-8829-5B702E2F89D9
Then I tried the "RetrieveRecordChangeHistory" function. It is working in the custom c# code but not working in the web api.

https://xxxx/api/data/v8.2/RetrieveRecordChangeHistory(Target=@Target)?@Target={%22contactid%22:%22AFF6BF88-8A78-CDAE-8829-5B702E2F89D9%22,%22@odata.type%22:%22Microsoft.Dynamics.CRM.contact%22}.

The above url giving the below error.

{   "error":{
      "code":"","message":"Resource not found for the segment 'RetrieveRecordChangeHistory'.","innererror":{
        "message":"Resource not found for the segment 'RetrieveRecordChangeHistory'.","type":"Microsoft.OData.Core.UriParser.ODataUnrecognizedPathException","stacktrace":"
  at
  Microsoft.OData.Core.UriParser.Parsers.ODataPathParser.CreateFirstSegment(String
  segmentText)\r\n   at
  Microsoft.OData.Core.UriParser.Parsers.ODataPathParser.ParsePath(ICollection1
  segments)\r\n   at
  Microsoft.OData.Core.UriParser.Parsers.ODataPathFactory.BindPath(ICollection1
  segments, ODataUriParserConfiguration configuration)\r\n   at
  Microsoft.OData.Core.UriParser.ODataUriParser.Initialize()\r\n   at
  System.Web.OData.Routing.DefaultODataPathHandler.Parse(IEdmModel
  model, String serviceRoot, String odataPath, ODataUriResolverSetttings
  resolverSettings, Boolean enableUriTemplateParsing)\r\n   at
  System.Web.OData.Routing.DefaultODataPathHandler.Parse(IEdmModel
  model, String serviceRoot, String odataPath)\r\n   at
  Microsoft.Crm.Extensibility.OData.CrmODataPathHandler.Parse(IEdmModel
  model, String serviceRoot, String odataPath)"
      }   } }

A: The RetrieveRecordChangeHistory function was not available from web api in CRM 2016 (v8.2) and it was added in web api function list later, which is v9
v8.2 functions list
v9 functions list


text:
Q: Which is best practice of getting state from redux to component? Example 1:
Component1:
<Fragment>
    Hello world
   <component2 {...this.props} />
</Fragment>

export default connect(mapStateToProps)(component1)

(or)
Example 2
Component1:
<Fragment>
    Hello world
   <component2  />
</Fragment>

Component2:
    <Fragment>
        Hello world
    </Fragment>

export default connect(mapStateToProps)(component2)

In my scenario i want to use state for the component 1 and component 2..So i need to connect to redux in both component1 and 2, So what would you suggest?And which one is best approach
Thanks

A: If the Second component is a child of the First component you should mapStateToProps in the First component and then pass it via props to the second component. Just like you did on the first example!

A: It really depends. In general you try to connect "high" in the component hierarchy and pass down props in order to keep as many dumb components as possible. But beware, if you connect really high, then every time the store changes, a lot of component will be rendered for nothing (unless they are pure). Don't optimize before you have a problem, but keep that in mind.
My rule of thumb is one connected component per "topic" in the store. If a component connects to get two things and passes one thing to a child and the other thing to another child, then I'd consider moving the connect down to each component. But no hard rules here, only guidance.


text:
Q: Android Studio verificar caracteres de un TextView estoy empezando con Android studio y tengo un problema quiero verificar que al introducir el nombre y apellidos haya caracteres sino avisar de que no ha puesto nada.
El código es el siguiente:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class EAC1 extends AppCompatActivity {
    TextView texto;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_eac1);
    }

// Métodes dels botons!
    public void ResetTextNom (View vista){ //Hem creat aquest métode que el que fa es que al donar a la X esborri la info.
        TextView TexToResultado = (TextView) findViewById(R.id.TextNom); //fem la variable TextoResultado es canvia per textNom
        TexToResultado.setText(""); // cambia el text actual a un " "
    }
// Ahora vamos hacer el TEXTVIEW.

    public void TextAcceptat (View vista){
        texto = (TextView) findViewById(R.id.TextNom); // Primer verifiquem el text i l'agafem
        if(texto ==null){ // Verifiquem que no estigui buït
            Toast toast1 = Toast.makeText(getApplicationContext(),"Heu d'escriure quelcom!",Toast.LENGTH_LONG);
            toast1.show();
        }else{
            Toast toast2 = Toast.makeText(getApplicationContext(),"bien!",Toast.LENGTH_SHORT);
            toast2.show();
        }
    }}

El problema lo tengo en la parte final en el if texto=null...
adjunto layout..
 <EditText
        android:id="@+id/TextNom"
        android:text="@string/name"
        android:layout_width="295dp"
        android:layout_height="49dp"
        android:layout_marginBottom="321dp"
        android:ems="10"
        android:inputType="textAutoComplete|textPersonName"
        android:textColor="@color/colorNegre"
        android:textColorLink="@color/colorAccent"
        app:layout_constraintBottom_toBottomOf="parent"
        tools:ignore="MissingConstraints,RtlHardcoded"
        android:layout_marginRight="8dp"
        app:layout_constraintRight_toRightOf="parent"
        android:layout_marginLeft="8dp"
        app:layout_co

Puede ser que me falte algo en el layout? En los botones hay que crear el android:onclick.. pero no sé si en los textos también..
gracias!

A: Bien hagamos unas cuantas aclaraciones.

*

*En el layout tienes un EditText no un TextView.

*Estas enlazando el EditText que declaraste en el layout con un TextView. Tienes que enlazar el EditText del layout con un EditText no con un TextView.

*Estas creando dos variables del EditText, una en el metodo ResetTextNom() y otra en el metodo TextAcceptat(). Por lo que en ambos metodos estas trabajando con dos variables diferentes y los cambios que agas en una no afectaran a la otra. Si modificas el valor de la variable TexToResultado, el valor de la variable texto seguira siendo el mismo ya que son dos variables diferentes.

Solo tienes que declarar una variable del EditText en el métodoonCreate() de la clase y luego obtienes o modificas el valor de esa variable desde los métodos ResetTextNom() y TextAcceptat().
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class EAC1 extends AppCompatActivity {

    // Declaras el EditText
    EditText texto;

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

        // Inicializas el EditText
        texto = (EditText) findViewById(R.id.TextNom);
    }

// Métodes dels botons!
    public void ResetTextNom (View vista){ //Hem creat aquest métode que el que fa es que al donar a la X esborri la info.
        //fem la variable TextoResultado es canvia per textNom
        // Modificas el valor del EditText
        texto.setText(""); // cambia el text actual a un " "
    }
// Ahora vamos hacer el TEXTVIEW.

    public void TextAcceptat (View vista){

        // Con getText() obtienes el texto del EditText.
        // Con toString() convierte el texto a String.
        // Con isEmpit() confirma si el EditText esta vacio. Si esta vacio retorna true.
        if(editText.getText().toString().isEmpty()) {
            Toast toast1 = Toast.makeText(getApplicationContext(),"Heu d'escriure quelcom!",Toast.LENGTH_LONG);
            toast1.show();
        }else{
            Toast toast2 = Toast.makeText(getApplicationContext(),"bien!",Toast.LENGTH_SHORT);
            toast2.show();
        }
    }
}


text:
Q: Related post by custom field I use wordpress acf custom post type to create my custop post type.
this code (in my custop post type page php) to display the related post of a taxonomy type, now i want to display by Custom Field instead of taxonomy. Thank you for helping me solve my problem
<?php

global $post;

$current_post_type = get_post_type( $post );

$args = array(
    'posts_per_page' => 3,
    'order' => 'DESC',
    'orderby' => 'ID',
    'post_type' => $current_post_type,
    'post__not_in' => array( $post->ID )
);

$rel_query = new WP_Query( $args );

if( $rel_query->have_posts() ) :
?>

Related

<?php
    // The Loop
    while ( $rel_query->have_posts() ) :
        $rel_query->the_post();
?>

        <a href="<?php the_permalink() ?>" title="<?php the_title() ?>" rel="bookmark">

<?php the_title() ?>

<?php the_time('F j, Y'); ?>

<?php the_excerpt(); ?>

<?php
    endwhile;
?>

<?php
endif;

// Reset the query
wp_reset_query();

?>

A: WP_Query Object accept arguments to query custom field values (more info here: https://www.advancedcustomfields.com/resources/query-posts-custom-fields/). So you need the name of your custom field in this example 'location' and then the value you want 'Melbourne' (you will get the value using get_field('location')).
So your args should look like this:
$args = array(
    'posts_per_page' => 3,
    'order' => 'DESC',
    'orderby' => 'ID',
    'meta_key'      => 'location',
    'meta_value'    => 'Melbourne'
    'post_type' => $current_post_type,
    'post__not_in' => array( $post->ID )
);

Hope this helps


text:
Q: Datatable not being filled? After creating a new datatable, the dataset does not fill the datatable with the 50 columns it should, I get an empty datatable.
List<DataTable> test = new List<DataTable>();
foreach (string currentconstring in constrings)
{
    started = false;
    DataTable dt = new DataTable();
    DataSet _dataSet = new DataSet();
    test.Add(dt);
    Thread connectthread = new Thread(() =>
    {
        started = true;
        DataTable localdt = dt;
        try
        {
             // access the database
            MySqlConnection mySqlconnection = new MySqlConnection(currentconstring); //Connects to the MySQL database with the current connection string
            mySqlconnection.Open();
            MySqlCommand SqlCommand = new MySqlCommand(_sqlQuery, mySqlconnection); //Sends the specified query to the server
            MySqlDataAdapter SqlDataAdapter = new MySqlDataAdapter(SqlCommand);

            SqlDataAdapter.Fill(_dataSet);  //Fill Dataset
            localdt = _dataSet.Tables[0];

            mySqlconnection.Close();

        }
        catch (Exception)
        {
        }
    });

A: You have created a thread and passed it a delegate (function), but you have not started the thread.
Try to put connectthread.Start(); after declaring the thread.
You might need to wait for the thread to finish so might have to use Thread.Join().
You might want to use async/await as that would be better than creating threads on your own, also you are sharing a data structure which is being written to without using locks. Please do check the regular problems when using multi threading.


text:
Q: Use for loop to get distinct value each column of a data frame with count of the distinct value Below is the example if a table :-
Table
A      B    Income
satya India 10000
Amlan Usa   20000
Satya India 10000
Amlan Usa   20000
Sid   India 30000

Results required
Query 1
A <- sqldf( " Select distinct A,sum(Income) from Table ")

A     Total
Satya 20000
Amlan 40000
Sid   30000

Query 2
B <- sqldf( " Select distinct B,Sum(Income) from Table ")

B     Total
India 50000
Usa   40000

I want use a loop so that I can write one query and get unique value of each filed with sum of income, instead of writing separate query for each field .I want this in R.

A: You can do something like this:
First of all, you need to loop through the colnames in the for loop and inside sqldf statement, you need to pass that colname using `sprintf' Otherwise, it won't work.
col_names <- colnames(df)
col_names <- col_names[-length(col_names)]

for (i in col_names) {
  A <- sqldf(sprintf( "Select distinct %s, sum(Income) as Total from df group by %s", i, i))
  print(A)
}

The output looks like this:
      A Total
1 Amlan 40000
2 Satya 20000
3   Sid 30000
      B Total
1 India 50000
2    US 40000

Hereafter, you can append the results to a list or create a data frame as you wish.
EDIT: To save df to different Excel files
In order to save the df to a new excel file every time, you'll need to use a package called xlsx.
Your code will look like this:
for (i in col_names) {
  A <- sqldf(sprintf( "Select distinct %s, sum(Income) as Total from df group by %s", i, i))
  write.xlsx(A, file = paste0(i, '.xlsx'))
}

Note: It will save the df in an excel file with the name of the column. (look for i in the write.xlsx function.

A: You may try this
df <- data.frame(A = c('satya', 'Amlan', 'Satya', 'Amlan', 'Sid'),
             B = c('India', 'Usa', 'India', 'Usa', 'India'),
             Income = c(10000, 20000, 10000, 20000, 30000))

# Converting to upper case since R is case sensitive
df$A <- toupper(df$A)
df$B <- toupper(df$B)

Cols_Group <- names(df)[!names(df) %in% 'Income']

library(data.table)
setDT(df)

# Creating different objects for each column
for(i in Cols_Group) {
  assign(i, df[, .(Total = sum(Income)), i])
}

A

       A Total
1: SATYA 20000
2: AMLAN 40000
3:   SID 30000

B

       B Total
1: INDIA 50000
2:   USA 40000

If you need it in single object you may use the below code
Result <- data.table()

for(i in Cols_Group) {
  Result <- rbindlist(list(Result, df[, .(Total = sum(Income)), i]), use.names = FALSE)
}

Result

       A Total
1: SATYA 20000
2: AMLAN 40000
3:   SID 30000
4: INDIA 50000
5:   USA 40000