Injetar dependencias além das Activity e Fragment?

Question: É preciso algo especial para se injetar uma dependencia com Dagger em um projeto Android que não seja Activity, Fragment, Service etc????
Exemplo, se eu tiver:
ActivityMan -> FragmentListCake -> PresenterCake -> DBCakeHelper
Se eu quiser injetar alguma coisa na Activity ou no Fragment isso é facil, sempre funciona.
Mas se eu quiser fazer isso no PresenterCake ou no DBCakeHelper não funciona de forma alguma.
Error:

05-26 15:22:45.663 13451-13451/myapplication
  E/AndroidRuntime: FATAL EXCEPTION: main
      Process: myapplication, PID: 13451
      java.lang.RuntimeException: Unable to resume activity {myapplication.ui.dashboard.DashboardActivity}:
  kotlin.UninitializedPropertyAccessException: lateinit property
  compositeDisposable has not been initialized
          at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3581)
          at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3621)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2862)
          at android.app.ActivityThread.-wrap11(Unknown Source:0)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
          at android.os.Handler.dispatchMessage(Handler.java:106)
          at android.os.Looper.loop(Looper.java:164)
          at android.app.ActivityThread.main(ActivityThread.java:6494)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
       Caused by: kotlin.UninitializedPropertyAccessException: lateinit property compositeDisposable has not been initialized
          at myapplication.ui.common.BasePresenter.getCompositeDisposable(BasePresenter.kt:31)
          at myapplication.ui.dashboard.view.repository.ListRepositoryPresenter.initRepositoryPopJava(ListRepositoryPresenter.kt:25)
          at myapplication.ui.dashboard.view.repository.ListRepositoryFragment.onResume(ListRepositoryFragment.kt:73)
          at android.support.v4.app.Fragment.performResume(Fragment.java:2387)
          at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1467)
          at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1752)
          at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1821)
          at android.support.v4.app.FragmentManagerImpl.dispatchStateChange(FragmentManager.java:3251)
          at android.support.v4.app.FragmentManagerImpl.dispatchResume(FragmentManager.java:3215)
          at android.support.v4.app.FragmentController.dispatchResume(FragmentController.java:217)
          at android.support.v4.app.FragmentActivity.onResumeFragments(FragmentActivity.java:509)
          at android.support.v4.app.FragmentActivity.onPostResume(FragmentActivity.java:498)
          at android.support.v7.app.AppCompatActivity.onPostResume(AppCompatActivity.java:171)
          at android.app.Activity.performResume(Activity.java:7131)
          at android.app.ActivityThread.performResumeActivity(ActivityThread.java:3556)
          at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:3621)
          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2862)
          at android.app.ActivityThread.-wrap11(Unknown Source:0)
          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
          at android.os.Handler.dispatchMessage(Handler.java:106)
          at android.os.Looper.loop(Looper.java:164)
          at android.app.ActivityThread.main(ActivityThread.java:6494)
          at java.lang.reflect.Method.invoke(Native Method)
          at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

Estrutura de Pastas de DI App

DIAppComponent:
@Singleton
@Component(modules = arrayOf(
            AndroidSupportInjectionModule::class,
            DIAppModule::class,
            DIBuilderModule::class)
    )
interface DIAppComponent {

    @Component.Builder
    interface Builder  {
        @BindsInstance
        fun application(application: Application): Builder

        fun build(): DIAppComponent
    }

     fun inject(instance: GitApplication)

}

DIAppModule:
@Module
class DIAppModule {

        @Provides
        @Singleton
        internal fun provideGson(): Gson = GsonBuilder()
                .create()

        @Provides
        @Singleton
        internal fun provideOkHttpCliente(): OkHttpClient = OkHttpClient.Builder()
                .connectTimeout(20, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
                .build()

        @Provides
        @Singleton
        internal fun provideRxJavaCallAdapterFactory(): RxJava2CallAdapterFactory = RxJava2CallAdapterFactory.create()

        @Provides
        @Singleton
        internal fun provideFirebaseHelper(firebase: FirebaseHelper): FirebaseContract = firebase

        @Provides
        @Singleton
        internal fun provideVerifyConnectionUtil(verifyConnectionUtil: VerifyConnectionUtil): VerifyConnectionUtil = verifyConnectionUtil

        @Provides
        @Singleton
        internal fun providePreferences(preferences: Preferences): Preferences = preferences

        @Provides
        @Singleton
        internal fun provideGitHelper(gitHelper: GitHelper): GitHelper = gitHelper

        @Provides
        @Singleton
        internal fun provideApp(app: GitApplication): Application = app

}

DIBuilderModule:
@Module
abstract class DIBuilderModule {

    @PerActivity
    @ContributesAndroidInjector(modules = arrayOf(DIDashboardModule::class))
    abstract fun dashboardActivityInjector(): DashboardActivity

    @PerListRepository
    @ContributesAndroidInjector(modules = arrayOf(DIListRepositoryModule::class))
    abstract fun listRepositoryFragmentInjector(): ListRepositoryFragment

}

GitApplication:
class GitApplication : Application(), HasActivityInjector {

    @field: Inject
    internal lateinit var androidInjectorActivity : DispatchingAndroidInjector<Activity>

    val component : DIAppComponent by lazy {
              DaggerDIAppComponent
                .builder()
                .application(this)
                .build()
    }

    override fun onCreate() {
        super.onCreate()

        component.inject(this)
    }

    override fun activityInjector() = androidInjectorActivity

}

Estrutura de Pastas de DI UI Common:

DIDashboardModule :
@Module(includes = arrayOf(DIBaseActivityModule::class ))
class DIDashboardModule {

    @PerActivity
    @Provides
    fun provideAppCompact(dashboardActivity : DashboardActivity): AppCompatActivity = dashboardActivity

}

DIBaseActivityModule :
@Module
class DIBaseActivityModule {

    companion object {
        const val ARCHIVE_NAME = "app.preferences"
        const val MODE = Context.MODE_PRIVATE
    }

    @Provides
    @PerActivity
    internal fun provideFragmentManager(activity: AppCompatActivity):  FragmentManager = activity.supportFragmentManager

    @Provides
    @PerActivity
    internal fun provideRetrofit(client: OkHttpClient,
                        converterFactory: GsonConverterFactory,
                        adapterFactory: RxJava2CallAdapterFactory): Retrofit = Retrofit.Builder()
            .baseUrl(AppConstants.NetworkConstants.BASE_URL_GIT_SEARCH)
            .addConverterFactory(converterFactory)
            .addCallAdapterFactory(adapterFactory)
            .client(client)
            .build()

    @Provides
    @PerActivity
    internal fun provideSharedPreferences(context: Context): SharedPreferences = context.getSharedPreferences(ARCHIVE_NAME, MODE)

    @Provides
    @PerActivity
    internal fun provideSharedPreferencesEditor(shPreference: SharedPreferences) : SharedPreferences.Editor = shPreference.edit()

    @Provides
    @PerActivity
    internal fun context(activity: AppCompatActivity): Context = activity

    @PerActivity
    @Provides
    internal fun provideRepositoryAPI(retrofit: Retrofit): RepositoryAPI = retrofit.create(RepositoryAPI::class.java)

}

DIListRepositoryModule:
@Module
class DIListRepositoryModule {

        @PerListRepository
        @Provides
        fun provideActivity(fragment: ListRepositoryFragment): ListRepositoryMVPView = fragment

        @PerListRepository
        @Provides
        fun provideRepositoryInteractor(): ListRepositoryMVPInterator = ListRepositoryInteractor()

        @PerListRepository
        @Provides
        fun provideRepositoryPresenter(fragment : ListRepositoryMVPView): ListRepositoryMVPPresenter {
             return ListRepositoryPresenter<ListRepositoryMVPView, ListRepositoryMVPInterator>(fragment)
        }

        @PerListRepository
        @Provides
        @Named(NamedDisposableForDagger.LIST_REPOSITORY_COMPOSITE_DISPOSABLE)
        fun provideListRepositoryCompositeDisposable(): CompositeDisposable = CompositeDisposable()

}

BaseActivity:
open abstract class BaseActivity : AppCompatActivity(), MVPView, HasSupportFragmentInjector{

    @field: Inject
    internal lateinit var fragmentInjector: DispatchingAndroidInjector<Fragment>

    @field: Inject
    internal lateinit var mFragmentManager : FragmentManager

    lateinit var mProgressDialog : ProgressDialog

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)
        super.onCreate(savedInstanceState)
        setContentView(getContentView())
    }

    override fun showLoading(@NonNull msg: String) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog(this)
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER)
            mProgressDialog.setCancelable(true)
        }
        mProgressDialog.setMessage(msg)
        mProgressDialog.show()
    }

    override fun hideLoading() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss()
        }
    }

    override fun showDialog(@NonNull title: String, @NonNull  message: String) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog(this)
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER)
            mProgressDialog.setCancelable(true)
        }

        mProgressDialog.setTitle(title)
        mProgressDialog.setMessage(message)
        mProgressDialog.show()
    }

    override fun hideDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss()
        }
    }

    override fun onError(@NonNull resId: Int) {

    }

    override fun onError(@NonNull message: String) {

    }

    override fun showMessage(@NonNull titulo: String, @NonNull mensagem: String, buttonConfirm: DialogInterface.OnClickListener, buttonNegative: DialogInterface.OnClickListener, textButtonConfirm: String, textButtonNegative: String) {

    }

    override fun showMessage(@NonNull titulo: String){

    }

    override fun showMessage(title: String, message: String){

    }

    override fun hideKeyboard() {
        val view = this.currentFocus
        if (view != null) {
            val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    @LayoutRes
    protected abstract fun getContentView():  Int

    override fun openActivityLogin() {
        val intent = Intent( this, MainActivity::class.java )
        startActivity(intent)
    }

    override fun addFragment(containerViewID: Int, fragment: Fragment,  @Nullable param : Bundle?) {
        if (param!=null){
            fragment.arguments = param
        }

        mFragmentManager!!.beginTransaction()
                .add(containerViewID, fragment)
                .commit()
    }

    override fun supportFragmentInjector() = fragmentInjector
}

BaseFragment:
open class BaseFragment : Fragment(), MVPView, HasSupportFragmentInjector  {

    @field: Inject
    internal lateinit var fragmentInjector: DispatchingAndroidInjector<Fragment>

    override fun supportFragmentInjector(): AndroidInjector<Fragment> {
        return fragmentInjector
    }

    protected lateinit var mContext: Context

    private var mProgressDialog: ProgressDialog?=null

    private lateinit var mAlertDialog: AlertDialog

    private lateinit var mActivityMom : MVPView

    override fun onAttach(activity: Activity) {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
            AndroidSupportInjection.inject(this)

        }
        super.onAttach(activity)
    }

    override fun onAttach(context: Context) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            AndroidSupportInjection.inject(this)
        }
        super.onAttach(context)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mActivityMom = activity as MVPView
        mContext = activity as Context
    }

    override fun showLoading(msg: String) {
        if (mProgressDialog == null) {
            mProgressDialog = ProgressDialog(mContext)
            mProgressDialog!!.setProgressStyle(ProgressDialog.STYLE_SPINNER)
            mProgressDialog!!.setCancelable(true)
        }
        mProgressDialog!!.setMessage(msg)
        mProgressDialog!!.show()
    }

    override fun hideLoading() {
        if (mProgressDialog != null && mProgressDialog!!.isShowing()) {
            mProgressDialog!!.dismiss()
        }
    }

    override fun showDialog(title: String, message: String) {
        mAlertDialog = AlertDialog(mContext, title, message)
        mAlertDialog.create()

    }

    override fun hideDialog() {
        mAlertDialog.dismiss()
    }

    override fun onError(resId: Int) {

    }

    override fun onError(message: String) {

    }

    override fun showMessage(   @NonNull titulo: String,
                                @NonNull mensagem: String,
                                @NonNull buttonConfirm: DialogInterface.OnClickListener,
                                @Nullable buttonNegative: DialogInterface.OnClickListener,
                                @NonNull textButtonConfirm: String,
                                @Nullable textButtonNegative: String ) {
        mAlertDialog = AlertDialog( mContext, titulo, mensagem, buttonConfirm, buttonNegative, textButtonConfirm, textButtonNegative )
        mAlertDialog.create()
    }

    override fun showMessage( @NonNull titulo: String ){

    }

    override fun showMessage( title: String, message: String ){

    }

    override fun hideKeyboard() {
        val view = activity!!.currentFocus
        if (view != null) {
            val imm = mContext.getSystemService( Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(view.windowToken, 0 )
        }
    }

    override fun openActivityLogin() {
        val intent = Intent( mContext, MainActivity::class.java )

        startActivity(intent)
    }

    override fun addFragment(containerViewID: Int, fragment: Fragment, param: Bundle?) {
        mActivityMom.addFragment(containerViewID, fragment, param) // Chamei o método da classe
    }

}

BasePresenter:
open class BasePresenter<V : MVPView, I : MVPInteractor> @Inject internal constructor(view : V) : MVPPresenter {

    private var stateConnection = false

    @DefNamedDisposableForDagger
    protected lateinit var named : String

    @DefStateLogginUser
    private var stateLoggin : Int = StateLogginUser.LOGGED_OUT

    @field: Inject
    lateinit var mContext : Context

    @field: Inject
    @field: Named (NamedDisposableForDagger.LIST_REPOSITORY_COMPOSITE_DISPOSABLE)
    lateinit var compositeDisposable: CompositeDisposable

    internal var mView :  V = view

    @field: Inject
    internal lateinit var mInteractor : I

    init {
        lazy {
            mInteractor.getConnectionInternet().subscribe { stateConnection = it } }
        lazy {
            mInteractor.getStateLogginUser().subscribe { it -> stateLoggin = it }
        }
    }

    override fun showDialog(message: String) = if (!message.isEmpty()) mView.showDialog("", message) else throw Exception("Falha")

    override fun hideDialog() = mView.hideDialog()

    override fun showMessage(message: String) = mView.showMessage(message)

    override fun showMessage(title: String, message: String) = mView.showMessage(title, message)

    override fun onError(message: String) = mView.onError(message)

    override fun isNetworkConnected() {
        mView.showLoading("Aguarde!")
        compositeDisposable.add(mInteractor.getConnectionInternet()
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe { valid ->
                mView.hideLoading()
                if (valid) {
                     mView.openActivityLogin()
                } else {
                    var title = mContext.getString(R.string.communication_opensystem_not_connection_title)
                    var message = mContext.getString(R.string.communication_opensystem_not_connection_message)
                    mView.showMessage(title, message)
                }
            })
    }

    override fun checkStateLogginUser() : Single<Int> = mInteractor.getStateLogginUser()

    override fun changeNetworkConnected() {
       // verificar conexão
    }

    override fun addDisposable(disposable: Disposable) {
        compositeDisposable.add(disposable)
    }

    override fun stop() {
        compositeDisposable.dispose()
        compositeDisposable.clear()

    }

    override fun setNamedDisposable(@DefNamedDisposableForDagger nameDispose: String) {
        named = nameDispose
    }

    override fun getView(): V = mView

}

BaseInteractor:
open class BaseInteractor @Inject internal constructor() : MVPInteractor{

    @Inject
    protected lateinit var mGitHelper : GitHelper

    @Inject
    lateinit var mPreferences: Preferences

    @Inject
    lateinit var mValidatorConnection: VerifyConnectionUtil

    override fun performLogout(): Maybe<Boolean> = Maybe.create<Boolean> { it ->
        mPreferences.let { pref ->
            try {
                TODO("Chamar metodo Firebase para deslogar e atualizar as Preferencias")
                pref!!.logout()
                it.onSuccess(true)
            }catch (e : Exception){
                it.onSuccess(false)
            }
        }
    }

    override fun getStateLogginUser(): Single<Int> = mPreferences.getStateUserLogged()

    override fun getConnectionInternet(): Maybe<Boolean> = mValidatorConnection.verifyConnectionInternet()

}

ListRepositoryFragment:
class ListRepositoryFragment: BaseFragment(), ListRepositoryMVPView {

    @field: Inject
    internal lateinit var mPresenter : ListRepositoryMVPPresenter

    private lateinit var recyclerViewListRepo : RecyclerView

    private lateinit var listRepos : ArrayList<Repo>

    private lateinit var adapterRepo : RepositoryAdapter

    private lateinit var layoutManager: LinearLayoutManager

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {

        val view  = inflater!!.inflate(R.layout.fragment_list_repository, container, false)

        recyclerViewListRepo = view.findViewById(R.id.rv_repository)

        //init()

        return view
    }

    private fun init(){
        adapterRepo = RepositoryAdapter(listRepos)
        layoutManager = LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false)
        recyclerViewListRepo.adapter = adapterRepo
    }

    override fun setListRepository(repos: List<Repo>) {
        listRepos.addAll(repos)
    }

    override fun onResume() {
        super.onResume()
        mPresenter.initRepositoryPopJava()
    }

    override fun setPresenter(presenter: ListRepositoryPresenter<ListRepositoryMVPView, ListRepositoryInteractor>) {
        this.mPresenter = presenter
    }

}

ListRepositoryPresenter:
class ListRepositoryPresenter <V : ListRepositoryMVPView, I: ListRepositoryMVPInterator> : BasePresenter<V , I>, ListRepositoryMVPPresenter{

    @Inject
    constructor(view : V) : super(view) {

        setNamedDisposable(
                NamedDisposableForDagger
                        .LIST_REPOSITORY_COMPOSITE_DISPOSABLE
        )
    }

    override fun initRepositoryPopJava() {
        getView().showLoading("Carregando Repositórios!")
        compositeDisposable!!.add(mInteractor.let {
            it!!.getAllRepositories()
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe { listRepo ->
                        getView().let { v ->
                            v.setListRepository(listRepo)
                            v.hideLoading()
                        }
                    }
        })
    }

    fun setPresenter(presenter: ListRepositoryPresenter<ListRepositoryMVPView, ListRepositoryInteractor>) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }
}

Answer: Descobrir, ou melhor, relembrei que existem duas opções:
Injeção de dependência por construtor usando o Dagger é claro.
ou
Injeção de campos(que é o que eu queria) mas para funcionar tenho que construir SubComponents e neles sobrescrever o método inject passando a classe que pode receber essas "injeções", na classe como no presenter chamo o XxXxXComponent.inject(this) e assim posso fazer a injeção.
Optei em fazer a injeção pelo construtor!!


Eigenfunctions spaces

Question: Let $\Omega$ be a bounded domain in $\mathbb{R}^N$ with boundary of class $C^2$.
It is known that there exists a sequence of eigenvalues $0<\lambda_1<\lambda_2\leq\ldots\leq\lambda_j\leq\ldots$ and a sequence of corresponding eigenfunctions $\{\varphi_j\}_{j\in\mathbb{N}^*}$ for Dirichlet problem
$$-\Delta u=\lambda u,\quad u|_{\partial\Omega}=0$$
How to show that $\varphi_j\in W^{2,p}(\Omega)$, with some $p>N$?
Answer: We know that the solution $u \in H_0^1(\Omega)$ of
$$-\Delta u = f$$
satisfies $u \in W^{2,p}(\Omega)$ for $f \in L^p(\Omega)$. Now, you can take $u = \varphi_j$ and $f = \lambda_j \, \varphi_j$.
Comment: Due to the Sobolev embedding theorem, you get $\varphi_j \in L^q(\Omega)$ for some $q > 2$. If you do not have $q > N$ already, you can iterate these arguments.
Comment: You start with $\varphi_j \in H^2$. By Sobolev embedding, you get $\varphi_j \in L^{q_1}$ with some $q_1 > 2$. From the equation, you get $\varphi_j \in W^{2,q_1}$. Now, Sobolev embedding gives $\varphi_j \in L^{q_2}$ for some $q_2 > q_1$. And so on.

Eigenfunctions spaces


Impute missing data before or after feature selection?

Question: Will the results of the feature selection be biased if I perform the feature selection before imputing missing data?
I have a large data set of 20000 samples and 130 variables. The data sets consists of binary, numeric, and ordinal variables. The outcome variable is binary.
I want to do two things:
1) Feature selection to determine the most important variables
2) Build a predictive model with SVM, Random Forest, and Logistic Regression.
The complete case data set contains 70% of the original data (i.e if I keep only samples with no missing variable values, then I'm left with 70% of the samples)
I am using MICE in R to impute the missing data.
Following some guidelines I found in this paper, I plan to impute 30 datasets. (I estimate the Fraction of Missing Information using the percentage of incomplete cases, which is 30%. This is where the 30 comes from)
This is computationally intensive and will take too long. If I take only the top 10 predictors and impute this smaller data set, I will be able to impute my 30 data sets as desired in a reasonable amount of time.
I cannot assume the data are Missing Completely at Random (MCAR). Most variables are Missing at Random (MAR) where the missing values can be modeled from existing data.
Will the results of the feature selection be biased because of missing-ness in the data?
Answer: You should consider a couple of factors before you make your decision.

Having a lot of covariates in the imputation model strengthens the MAR assumption for each covariate.
Will you be using the imputations at a later time for a different analysis? If so, you might want to keep everything.
It takes a while to run MICE, but once you have done it (correctly), you never need to touch it again. Also, it doesn't take any effort to run it...you can just let it run overnight! It takes a while to check (for convergence and validity), but it's not like you need to sit around for hours watching it.

I recently did imputation with about 90 covariates. It took a while to set up, but I'm glad I did. I imputed covariates I didn't intend to put in my analysis model, and I ended up actually using them in a related analysis later.
So, I would recommend variable selection after imputation. If you had 1000 covariates, I would say do variable selection before, but 130 is relatively not that large.
As for the bias issue, I'm not sure how to answer this. Hopefully somebody else can answer it better. If you truly have MAR data, then I think you will be ok. However, if it is MNAR, then the missing data is systematically different. If this is the case, variable selection before may yield different results than after imputation.
Comment: I'll go ahead and impute the data first. I guess there's not much value speeding up one step that I'm only going to do one time. Thank you.
Comment: Great. As well, you might want to have a look at [chapter 6.4](http://www.amazon.com/Flexible-Imputation-Missing-Interdisciplinary-Statistics/dp/1439868247) which gives some advice and references for model selection.


Amazon EC2 Socket connection not being accepted

Question: I am trying to run a java application on my EC2 instance. The application accepts socket connections on port 54321. If I try and connect to it, it times out. My Security Group is set as:
<code>TCP Port (Service)  Source  Action
21  0.0.0.0/0   Delete
22 (SSH)    0.0.0.0/0   Delete
80 (HTTP)   0.0.0.0/0   Delete
20393   0.0.0.0/0   Delete
54321   0.0.0.0/0   Delete
</code>
Is there anything else I need to do?
<code># iptables -nvL
Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain FORWARD (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
# iptables -nvL -t nat
Chain PREROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain INPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain OUTPUT (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination

Chain POSTROUTING (policy ACCEPT 0 packets, 0 bytes)
 pkts bytes target     prot opt in     out     source               destination
#
</code>
Comment: @Joseph are you sure the app is listening to the outside? do a `netstat -tlpn |grep 54321` and see if you see `0.0.0.0:54321` in the output
Comment: Is there a firewall running in the instance itself? (Paste the output of `iptables -nvL` and `iptables -nvL -t nat` if you're not sure.)
Comment: @mgorven Added to the question.
Comment: What version of linux is your EC2 instance?  Do you have SELinux installed/enabled?  Not sure if you need to run IPTables since the EC2 firewall can protect you.
Answer: I've just had this exact same problem. I was running a RHEL instance, and it's been bugging me for a while.
Anyway, the solution, thanks to @mgorven (in the OP comments) for pointing me in the right direction, is to turn off the Linux firewall, thus:
<code>[root@myserver ~]$ service iptables stop
</code>
This will shut the firewall down, but you also need to  ensure that it does not turn itself back on with the next reboot:
<code>[root@myserver ~]$ chkconfig iptables off
</code>
This solved my problems - hopefully it will solve your issue.
HTH


Como deixa um alinhamento Span para direita

Question: Vamos la, quero deixar o alinhamento do span a direita, mas não estou conseguindo
meu codigo abaixo:

Campeonato Brasileiro Série D

Rodada 8 - 15:00 TEMPO REAL

                 Caucaia1

                 Fluminense-PI 1

Acompanhe em tempo real

Quero deixa aonde esta o placar do lado direito e o logo do clube e no nome para a esquerda.
Answer: A tag center está deprecada. Terias que adicionar a seguinte propriedade css:

Comment: A pergunta é sobre bootstrap, talvez a solução seja `Texto` ou a solução seja obtida manipulando o sistema de grade, mas em todo o caso o código da pergunta não deixa claro qual o caminho seguir. Referências https://getbootstrap.com/docs/4.0/utilities/float/ e https://getbootstrap.com/docs/4.0/layout/grid/
Answer: Pelo visto está usando bootstrap...
Eu faria algo assim:

Campeonato Brasileiro Série D

Rodada 8 - 15:00 TEMPO
                        REAL

                    Caucaia1

                    Fluminense-PI 1

                    Acompanhe em tempo real

E como o amigo disse ali, a tag  está em defasada, evite de usar ou terá problemas em breve.
Espero ter ajudado
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Toolbar não é exibida no editor

Question: Em quaiquer projeto que crio:
A Toolbar é exibida no emulador mas não aparece no editor.
Também aparecem esses erros:

Segue os códigos:
Styles:
<resources>

</resources>

xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Gradle:
apply plugin: 'com.android.application'

android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.example.l.componentes_layout_basicos"
    minSdkVersion 22
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-alpha3'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

}

Answer: Colega você não implementou a Toolbar, segue como deve fazer:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

E no arquivo .java correspondente a essa tela XML, ponha o seguinte:
public class Feedback extends AppCompatActivity {

    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tela_feedback);
    //Instanciando, pondo título e adicionando o batão voltar (opcional)
//Lembrando que a partir disso você poderá adicionar mais funcionalidades
        toolbar = findViewById(R.id.toolbar);
        toolbar.setTitle(getResources().getString(R.string.sugestao));
        toolbar.setNavigationIcon(R.drawable.ic_arrow_back);

//Aplicando coor a toolbar
toolbar.setBackgroundColor(getResources().getColor(R.color.unicolor_amareloDark));
            setSupportActionBar(toolbar);
        }

@Override //Método para ativar o botão voltar da toolbar
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
}

    }

No seu Style deve mudar o parent para NoActionBar, como abaixo, assim a ActionBar será oculta:

</resources>

Se houver algo mais para ajustar, comente abaixo
Comment: Sim, mas mesmo não implementando, a toolbar aparece no emulador
Comment: O que está aparecendo é a ActionBar, vou add a correção na resposta para ocultar a ActionBar que está entrando em desuso.

Toolbar não é exibida no editor


Change published date to 12 hour time

Question: Right now my nodes say published by "author name 19:02". How can I change it to display 12 hour time 7:02?
Answer: It uses the default date format of the site, which is medium. You can configure that at admin/settings/date-time and choose a format which uses am/pm.
You can also implement hook_preprocess_node() in your theme or module and then override the 'submitted' variable set by template_preprocess_node(). That allows you to use a different date format just there.
Answer: In Drupal there are specific theming functions to customize this:
This is the default (for nodes):
function theme_node_submitted($node) {
  return t('Submitted by !username on @datetime',
    array(
      '!username' => theme('username', $node),
      '@datetime' => format_date($node->created),
    ));
}

This is the default for comments:
function theme_comment_submitted($comment) {
  return t('Submitted by !username on @datetime.',
    array(
      '!username' => theme('username', $comment),
      '@datetime' => format_date($comment->timestamp)
    ));
}

To override them, add these functions in your template.tpl.php of your theme, and change the name to MYTHEME_node_submitted. And now you can customize it:
Drupal 6 uses by default the format 'D, m/d/Y - H:i' , to understand the meaning of these letters, see full PHP doc here
To display in 12 hour format, replace H by h like this:
format_date($node->created, 'custom', 'D, m/d/Y - h:i');

API reference about format_date()

Change published date to 12 hour time


Is it correct to use taxonomy_term_is_page() in this code?

Question: I am trying to get some content to show up when some conditions are verified: if I am on a certain page, the content will be shown; differently, the content is blank.
Everything looks correct; I just don't know if I am not using the correct function or something else is wrong.
<?php if (!taxonomy_term_is_page('18')): ?>

blah 1 News

<?php elseif (!taxonomy_term_is_page('28')): ?>

blah 2 News

<?php elseif (!taxonomy_term_is_page('29')): ?>

blah 3 News

<?php elseif (!taxonomy_term_is_page('30')): ?>

blah 4 News

<?php elseif (!taxonomy_term_is_page('81')): ?>

blah 5 News

<?php endif; ?>

This displays the results; however, when I am on one of the other terms the output doesn't change: it stays the same as the output for the taxonomy term with ID equal to 18.
My description for what I was trying to achieve has been changed; I am not trying to get anything shown based on any conditions. To put it in better words, I am trying to have the content shown; if I am on taxonomy/term/18, the content would show the else nothing would shown if I am on taxonomy/term/28 content shows and so on. It's simular to is_front_page function and you have content shown if you are on the front page, except these are taxonomy terms.
Comment: Why is there a "!" in the condition? Right now, you are saying if this is not the page for taxonomy term 18, display blah 1 news. You probably want to remove that...
Comment: when i remove it nothing displays what do you suggest i put instead?
Comment: Don't use taxonomy_term_is_page() in the first place :) See kiamlaluno's updated answer.
Answer: Basing on the documentation of taxonomy_term_is_page(),  the function just checks if the current page is the page of the passed-in term. Looking at the code, the function verifies the path of the current page is "taxonomy/term/%term-id", and "%term-id" is the term ID of the taxonomy term passed as argument.
function taxonomy_term_is_page($term) {
  $page_term = menu_get_object('taxonomy_term', 2);
  return (!empty($page_term) ? $page_term->tid == $term->tid : FALSE);
}

You are passing to the function the wrong parameters; you should pass it a taxonomy term object.
The code you reported is calling the function as taxonomy_term_is_page('28').
If you know the term ID for the taxonomy term, then you can use the following code:
<?php
  $page_term = menu_get_object('taxonomy_term', 2);
?>
<?php if (!empty($page_term)): ?>
  <?php if ($page_term->tid != 18): ?>

blah 1 News

  <?php elseif ($page_term->tid != 28): ?>

blah 2 News

  <?php elseif ($page_term->tid != 29)): ?>

blah 3 News

  <?php elseif ($page_term->tid != 30): ?>

blah 4 News

  <?php elseif ($page_term->tid != 81): ?>

blah 5 News

  <?php endif; ?>
<?php endif; ?>

Comment: @Jeremy: Also, it is cleaner and the "Drupal way" to place logic like that in a preprocess function, save it in $variables['title'] for example, and in your template, just print $title.
Comment: yes i saw that but i need the function to work from a view theme not from in the functions page thats why i did a if else statement.
Comment: @Jeremy Love See my updated answer.
Comment: its the same code?
Comment: @Jeremy Love `taxonomy_term_is_page()` is the function you are calling, but as you see the parameters you are passing are not correct; you should pass just a taxonomy term object to the function, not a string and an integer.
Comment: i updated the code
Comment: updated, im sorry if im being confusing im still learning the functions to this, and i appreciate you guys help
Comment: @Jeremy Love: No, you don't touch "2", that means it loads the third argument from the path as the term. You only touch the numbers below, like 18 and so on. The code *is* correct, try it :)


Importing .txt file with metadata before and after table into R

Question: I am trying to import a .txt file into R, but am having some difficulty. My file has metadata in the file, before and after the actual data table. How do I tell the read.table() function to account for this? I've experimented with the skip parameter, but am not successful. If anyone could point me in the direction of a good resource, that would be great! I'm not getting there from the documentation alone.
Here is a Google Drive link to my .txt file: https://drive.google.com/file/d/1VG3fBso0s15NGeHnN32CK68bylxrB06t/view?usp=sharing
Comment: Show what you have done.
Answer: data <- read.table('hackr.txt',header = T, sep =';', skip=22, stringsAsFactors = FALSE)
# Optional: cn   <- colnames(data)

tmp <- as.data.frame(stringr::str_split_fixed(data[,1], "\t",n=Inf))[2:nrow(data),]

I can also clean up (remove) some junk columns for you:
for (f in names(tmp)) {
  if (length(unique(tmp[[f]])) == 1) {
    cat(f, "is constant. I am deleting it.\n"); tmp[[f]] <- NULL
}}

head(tmp)
    V1           V2         V3           V4       V5       V6         V7          V8          V9         V10      V11
    2018-05-28   20:38:34   00:00:29.9   32.1     32.1     -.-        -.-         -.-         -.-
    2018-05-28   20:38:34   00:00:29.8   32.7     32.4     -.-        -.-         -.-         -.-
    2018-05-28   20:38:34   00:00:29.7   31.9     32.2     -.-        -.-         -.-         -.-
    2018-05-28   20:38:34   00:00:29.6   34.9     33.1     -.-        -.-         -.-         -.-
    2018-05-28   20:38:34   00:00:29.5   70.6     63.6     -.-        -.-         -.-         -.-
    2018-05-28   20:38:34   00:00:29.4   70.4     65.7     -.-        -.-         -.-         -.-

If you want to keep the original headers just run the optional (commented) line as well and parse them with the same type of logic. They have a different delimiter than the rest of your table.


How to display game on the screen?

Question: I'm trying to make an kivy app with starting menu, but I can't display my Pong Game on the second screen. How should I refer to the game to make it visible? I tried and searched but can't find anything. I'm 100% sure that PongGame work corectly, I just can't display it. It would be great if someone could show me how to do it corectly.
Main.py:
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager, Screen, WipeTransition
from kivy.properties import ObjectProperty
from kivy.uix.widget import Widget
from kivy.properties import NumericProperty, ReferenceListProperty,\
    ObjectProperty
from kivy.vector import Vector
from kivy.clock import Clock
from kivy.uix.popup import Popup
from kivy.uix.label import Label

class PongPaddle(Widget):
    score = NumericProperty(0)

    def bounce_ball(self, ball):
        if self.collide_widget(ball):
            vx, vy = ball.velocity
            offset = (ball.center_y - self.center_y) / (self.height / 2)
            bounced = Vector(-1 * vx, vy)
            vel = bounced * 1.1
            ball.velocity = vel.x, vel.y + offset

class PongBall(Widget):
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    def move(self):
        self.pos = Vector(*self.velocity) + self.pos

class PongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)

    def serve_ball(self, vel=(4, 0)):
        self.ball.center = self.center
        self.ball.velocity = vel

    def update(self, dt):
        self.ball.move()

        #bounce of paddles
        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)

        #bounce ball off bottom or top
        if (self.ball.y < self.y) or (self.ball.top > self.top):
            self.ball.velocity_y *= -1

        #went of to a side to score point?
        if self.ball.x < self.x:
            self.player2.score += 1
            self.serve_ball(vel=(4, 0))

        if self.ball.x > self.width:
            self.player1.score += 1
            self.serve_ball(vel=(-4, 0))
            if self.player1.score == 10:
                popup = Popup(title='Test popup', content=Label(text='Hello world'), auto_dismiss=False)
                return popup
    def on_touch_move(self, touch):
        if touch.x < self.width / 3:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3:
            self.player2.center_y = touch.y

class ScreenThree(Screen):
    pass

class ScreenTwo(Screen):
    pass

class ScreenOne(Screen):
    pass

class Manager(ScreenManager):

    screen_one = ObjectProperty(None)
    screen_two = ObjectProperty(None)
    screen_three = ObjectProperty(None)

class ScreensApp(App):

    def build(self):
        m = Manager(transition=WipeTransition())
        return m

if __name__ == '__main__':
    ScreensApp().run()

screen.kv:
<PongBall>:
    size: 50, 50
    canvas:
        Ellipse:
            pos: self.pos
            size: self.size

<PongPaddle>:
    size: 25, 200
    canvas:
        Rectangle:
            pos:self.pos
            size:self.size

<PongGame>:
    ball: pong_ball
    player1: player_left
    player2: player_right

    canvas:
        Rectangle:
            pos: self.center_x-5, 0
            size: 10, self.height

    Label:
        font_size: 70
        center_x: root.width / 4
        top: root.top - 50
        text: str(root.player1.score)

    Label:
        font_size: 70
        center_x: root.width * 3 / 4
        top: root.top - 50
        text: str(root.player2.score)

    PongBall:
        id: pong_ball
        center: self.parent.center

    PongPaddle:
        id: player_left
        x: root.x
        center_y: root.center_y

    PongPaddle:
        id: player_right
        x: root.width-self.width
        center_y: root.center_y

<ScreenOne>:
    Button:
        text: "Screen 1 >> Screen 2"
        on_press: root.manager.current = 'screen2'
<ScreenTwo>:
        def build(self):
            game = PongGame()
            game.serve_ball()
            Clock.schedule_interval(game.update, 1.0 / 60.0)
            return game

<ScreenThree>:
    Button:
        text: "Screen 3 >> Screen 1"
        on_press: root.manager.current = 'screen1'

<Manager>:
    id: screen_manager

    screen_one: screen_one
    screen_two: screen_two
    screen_three: screen_three

    ScreenOne:
        id: screen_one
        name: 'screen1'
        manager: screen_manager

    ScreenTwo:
        id: screen_two
        name: 'screen2'
        manager: screen_manager

    ScreenThree:
        id: screen_three
        name: 'screen3'
        manager: screen_manager

Answer: Well! there were a lot of errors in your program and I had to make ton's of improvement. (I understand it as you are beginner)
First of all, please read complete kivy language documentation, as I can clearly see that you directly started with coding without grasping the basics.
You may make couple of good games but in the long run you will face such problems which can't be solved without clear concepts.
And unfortunately you won't be able to discover the true power of kivy. :)
You might also wanna do revision of your python concepts.
Some improvements aren't worth mentioning but were important, you will get an idea when you read the code.
Improvement 1:
An application can be built if you return a widget on build(), or if you set self.root.(But you cannot make the application again n again)
 as you did here:
<ScreenTwo>:
    def build(self):
        game = PongGame()
        game.serve_ball()
        Clock.schedule_interval(game.update, 1.0 / 60.0)
        return game

Improvement 2:
As you click on button play ping pong which is of screen game. your game starts with serve of ball.
on_release: root.current = 'game';game.serve_ball()

(for knowledge)
If you still get black screen you might want to check the name of kivy file, for that you could either go to kivy documentation or this link
 class PongPaddle(Widget):
    score = NumericProperty(0)

    def bounce_ball(self, ball):
        if self.collide_widget(ball):
            vx, vy = ball.velocity
            offset = (ball.center_y - self.center_y) / (self.height / 2)
            bounced = Vector(-1 * vx, vy)
            vel = bounced * 1.1
            ball.velocity = vel.x, vel.y + offset

class PongBall(Widget):
    velocity_x = NumericProperty(0)
    velocity_y = NumericProperty(0)
    velocity = ReferenceListProperty(velocity_x, velocity_y)

    def move(self):
        self.pos = Vector(*self.velocity) + self.pos

class PongGame(Widget):
    ball = ObjectProperty(None)
    player1 = ObjectProperty(None)
    player2 = ObjectProperty(None)

    def __init__(self, *args, **kwargs):
        super(PongGame, self).__init__(*args, **kwargs)
        Clock.schedule_interval(self.update, 1.0 / 60.0)

    def serve_ball(self, vel=(4, 0)):
        self.ball.center = self.center
        self.ball.velocity = vel

    def update(self, dt):
        self.ball.move()

        #bounce of paddles
        self.player1.bounce_ball(self.ball)
        self.player2.bounce_ball(self.ball)

    #bounce ball off bottom or top
        if (self.ball.y < self.y) or (self.ball.top > self.top):
        self.ball.velocity_y *= -1

    #went of to a side to score point?
        if self.ball.x < self.x:
            self.player2.score += 1
            self.serve_ball(vel=(4, 0))
        if self.ball.x > self.width:
            self.player1.score += 1
            self.serve_ball(vel=(-4, 0))

    def on_touch_move(self, touch):
        if touch.x < self.width / 3:
            self.player1.center_y = touch.y
        if touch.x > self.width - self.width / 3:
            self.player2.center_y = touch.y

class Manager(ScreenManager):
    pass

class ScreensApp(App):
    def build(self):
        self.load_kv('t6.kv')
        return Manager(transition=WipeTransition())

if __name__ == '__main__':
    ScreensApp().run()

Here is the kv file.
<PongBall>:
    size: 50, 50
    canvas:
        Ellipse:
            pos: self.pos
            size: self.size

<PongPaddle>:
    size: 25, 200
    canvas:
        Rectangle:
            pos:self.pos
            size:self.size

<PongGame>:
    ball: pong_ball
    player1: player_left
    player2: player_right

    canvas:
        Rectangle:
            pos: self.center_x-5, 0
            size: 10, self.height

    Label:
        font_size: 70
        center_x: root.width / 4
        top: root.top - 50
        text: str(root.player1.score)

    Label:
        font_size: 70
        center_x: root.width * 3 / 4
        top: root.top - 50
        text: str(root.player2.score)

    PongBall:
        id: pong_ball
        center: self.parent.center

    PongPaddle:
        id: player_left
        x: root.x
        center_y: root.center_y

    PongPaddle:
        id: player_right
        x: root.width-self.width
        center_y: root.center_y

<Manager>:
    id: screen_manager

    Screen:
        name: 'home'
        Button:
            text: 'Play Ping Pong'
            halign: 'center'
            valign: 'middle'
            font_size: 100
            text_size: self.size
            on_release: root.current = 'game';game.serve_ball()

    Screen:
        name: 'game'
        PongGame:
            id: game

Comment: Thanks a lot! I think I'm more than beginner and your advices are very helpful. Now everything works fine and it's easy to understand why. Once again thank you very much! :)

How to display game on the screen?


LINQ-to-SQL: Searching against a CSV

Question: I'm using LINQtoSQL and I want to return a list of matching records for a CSV contains a list of IDs to match. The following code is my starting point, having turned a CSV string in a string array, then into a generic list (which I thought LINQ would like) - but it doesn't:
Error
Error 22 Operator '==' cannot be applied to operands of type 'int' and 'System.Collections.Generic.List<int>' C:\Documents and Settings\....\Search.cs 41 42 C:\...\

Code
    DataContext db = new DataContext();

    List<int> geographyList = new List<int>( Convert.ToInt32(geography.Split(',')) );

        var geographyMatches = from cg in db.ContactGeographies
                               where cg.GeographyId == geographyList
                               select new { cg.ContactId };

Where do I go from here?
Answer: var geographyMatches = from cg in db.ContactGeographies
                               where geographyList.Contains(cg.GeographyId)
                               select new { cg.ContactId };

Comment: This does the trick - this syntax seems odd to me, but I look at LINQ strange SQL eyes which it blinding me to these type of approaches
Answer: Like the error says, in where cg.GeographyId == geographyList you're trying to compare int to a List<int>. They're totally different types. I think you want to do geographyList.Contains(cg.GeographyId) or some other operation like that.

LINQ-to-SQL: Searching against a CSV


Why is LD_LIBRARY_PATH undefined when I run my Node.js script using mocha on macOS?

Question: Nice to meet you, i am here to ask a question, i am trying to make unit test using oracledb, but i getting an error because it can't found oracle client, testing i found when i run my test file using mocha one of my oracle variable is undefined and this is probably the reason why my code fail, when i run same file using node command this variable have it real value, someone know what it happening and how to fix it?

node v10.21.0
mocha 8.0.1
os macOS Catalina 10.15.5
oracle 22.214.171.124.0

File:
console.log('OCI_LIB_DIR', process.env.OCI_LIB_DIR);
console.log('OCI_INC_DIR', process.env.OCI_INC_DIR);
console.log('LD_LIBRARY_PATH', process.env.LD_LIBRARY_PATH);

$ mocha file.js

result:
OCI_LIB_DIR /Users/lmorales/Documents/instantclient_12_2/
OCI_INC_DIR /Users/lmorales/Documents/instantclient_12_2/sdk/include
LD_LIBRARY_PATH /Users/lmorales/Documents/instantclient_12_2

$ node file.js

result:
CI_LIB_DIR /Users/lmorales/Documents/instantclient_12_2/
OCI_INC_DIR /Users/lmorales/Documents/instantclient_12_2/sdk/include
LD_LIBRARY_PATH undefined

screenshot with evidence
Answer: Apple macOS's SIP stops variables like LD_LIBRARY_PATH being passed down to subshells (This was noted in node-oracledb issue #231).   The node-oracledb install doc has never recommended LD_LIBRARY_PATH on macOS, and stopped recommending DYLD_LIBRARY_PATH many versions ago.
Also I notice you are setting OCI* variables that haven't been needed for several years.
Please read the installation documentation https://oracle.github.io/node-oracledb/INSTALL.html#instosx for current ways to install node-oracledb.
You can use the new initOracleClient() call, create a sym link in your node_modules/oracledb/build/Release directory, or put the Instant Client in /usr/local/lib - see the doc.
Comment: yes, because i am using oracle 12, so we need use too old configuration
Comment: The Oracle Client version has nothing to do with it. You can still use Oracle client 12 with the latest version of node-oracledb. (But if your database versions are 11.2 or later, then you could / should update your Oracle Client version)


Is it possible to use a PHP variable from the main php page in an php included file?

Question: I have a "main" php webpage called "main.php" and I have an included file called "comments.php".
In main.php I'm using the following to get the url of the page, but I'm trying to use the $shareURL variable in the included file (comments.php) and it isn't working.
Code In Main.php
<?php $shareURL = "http://".$_SERVER[\'SERVER_NAME\'] . $_SERVER[\'REQUEST_URI\']; ?>

Above is the variable.
Below is the include.
<?php include "$domainName/assets/includes/fbCommentBox.php"; ?>

Code in the Include File (comment.php)
<?php echo "

"; ?>

If I use the above in my included file, I get the pages URL for the include file, not the main.php page.
Is there a method to use a php variable within the main.php page that will pass its value into the included (comments.php) file?
SCOPE OF THE PROJECT
The main.php code is being placed 'inside' of another php variable that is being used to create a webpage. I need the \ in <?php $shareURL = "http://".$_SERVER[\'SERVER_NAME\'] . $_SERVER[\'REQUEST_URI\']; ?>.
Example
<?php
$content = '
<?php $shareURL = "http://".$_SERVER[\'SERVER_NAME\'] . $_SERVER[\'REQUEST_URI\']; ?>
';
?>

Comment: please show _how_ you try to use the variable. It should be no problem actually. Included files are treated as if it was one file.
Comment: @Mr.B, try to show more about your code. Maybe your problem is not clearly explained.
Comment: If your question is about the variable, see what PHP manual says:
When a file is included, the code it contains inherits the variable scope of the line on which the include occurs. Any variables available at that line in the calling file will be available within the called file, from that point forward. However, all functions and classes defined in the included file have the global scope.
Comment: ok, I think I understand what are you trying to do. You are trying to declare the $shareURL into another PHP file by passing it as a string. And you are expecting that this $shareURL should be automatic declarated after inserted. right?
Comment: @Mr.B and why don't you directly declare the $shareURL ?
Comment: I've updated the question to include the code i'm using
Comment: Mr.B, I reproduced your code (with some modifications) here and it should work. try to use ['SERVER_NAME'] instead of [\'SERVER_NAME\'] (do the same for REQUEST_URI)
Comment: I can't reproduce your problem either. No matter if I declare the `$shareURL` in the main.php file or in some include.php file within a couple of other dirs, the result remains the same.
Comment: @MarcelKohls, thank you for your help, but I'm using the `\` because that line of code is inside of another variable being used to write that code to a file the writes a final webpage.
Comment: `$_SERVER['SERVER_NAME']` returns the domain. `$_SERVER['REQUEST_URI']` returns the path where the script was called by the user. So if the user visits _https://example.com/test/_, the result will be _https://example.com/test/_ no matter if those variables are declared in some index.php file inside _/test/_ or some include.php file inside _/test/some/other/folder/_
Comment: @MarcelKohls yes, I'm trying to pass the url as a string and use that string in the included file.
Comment: @MarcelKohls I need it to be a variable because it will change for each different webpage the comment include is on.

The comment code will be on every page and I need the comment code to be tied the to URL of the page. There will be thousands of pages.
Comment: ok, I think I understand. Try to use anonymous functions on that variable, it should return what you expect: $shareURL = function(){ return "http:...".$_SERVER['SERVER_NAME']."...."; }
Comment: @Mr.B instead of anonymous function, try to use the anonymous class and the magic method __toSring: $shareURL = new class{
        public function __toString() {
            return "http://".$_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];
        }
    }
Comment: @MarcelKohls1st, thanks for working on this with me. I greatly appreciate it. 2nd, I've decided to simplify the question and post it here with full code and output. It might be clearer. Can you please take a look?
https://stackoverflow.com/questions/48858279/how-use-a-php-variable-declared-in-the-parent-file-into-the-included-file
Answer: A better [than globals], though possibly more involved, approach would be to have all the code in the included file wrapped in functions or in a class, and then passing the variable into those functions when you call them from the main file.
EDIT: Removed my suggestion of using global, per the comment below. global only applies if you are sharing a variable between scopes, i.e. between one function and another or between a function body and the global space.
Comment: You don't need `global` to use variables from an included file. `global` is tangential to the asked question (at least if it's read exactly).


How to make new predictions via a trained Gaussian Process?

Question: I've been interested in GP for the past few weeks, and so far, I get how to determine the posterior mean and covariance. But, maybe it's just me, I do not see how, given a new input x, find its image y via the GP model.
For instance, let's say I have an unknown function (blue) and a few observations (red dots) allowed me to compute a mean function (black), an uncertainty domain (green) and some candidates functions (light green)
How can I get the value provided by a candidate function, or more simply, the mean function at a new input, say $x = -0.5$? (I do see the value for $x$ on the figure, but how can we compute it is my question)
EDIT
On the presented figure, the black, green curves and green shaded area were obtained using informations from the book of Rasmussen. The problem is that the posterior mean or candidates functions are under the form of an $n$-dimensional vector. Now, if I want the value of, say, $x = -0.5,$ does it mean that I have to manually browse through zip(meanFunction, xSpace) until I have xSpace${} = -0.5$ and get the according model value? Or is there another way to extract this knowledge?
Comment: Can you be more specific about what you've tried so far? Do you have the kernel covariance matrices for the 'training' observations and the new input? Are you looking at theory or trying to write some code?
Comment: Adding to the answer given by Kevin Yang, a more general Equation for mean prediction is 2.38 if you have not assumed you mean function as zero. (Earlier I was confused a lot not knowing this, so trying to make it clear for the OP and others :)
Comment: I know this was posted for a while ago. But finally I see someone having the same basic intuitive question as me. Why is no one talking about this??? So, have you gained more understanding since the post? Could you please explain to me? Best regards!
Answer: The closed form expressions for the posterior mean and variance can be found in Equations 2.25 and 2.26 on page 17 of Gaussian Processes for Machine Learning. If you need help with those, feel free to add comments here.


WordPress custom query by meta_key

Question: I'm trying to figure out how to achieve a specific query to modify my search results for posts with WordPress. I'm trying to search via a custom field called "Common Authors".
There can be multiple Common authors, which is causing my query to sometimes fail. Here is what I've got for now:
<?php
...
$query->set('meta_key', 'common_authors');
$query->set('meta_value', serialize( array(strval($_GET['common_author'])))); // I get a single ID from the url as a string
$query->set('meta_compare', 'IN');

This is what I see when I var_dump the query:
'meta_key' => string 'common_authors'
'meta_value' => string 'a:1:{i:0;s:5:"17145";}'

This works fine if there is only one common_author.
However, there can be multiple common_authors for a post. Here is a meta_value example from the database:
a:4:{i:0;s:5:"14409";i:1;s:5:"17145";i:2;s:5:"14407";i:3;s:5:"14406";}

Could somebody help me out, to figure out how to adapt my query, so that it would return this one as well?
Answer: Try This One Work Prefect!
 $args = array(
        'post_type' => 'post',
        'meta_query' => array(
            array(
                'key' => 'common_authors',
                'value' => array ( 'author1', 'author2', 'author3' ),
                'compare' => 'IN'
            )
        )
    );
$query = new WP_QUERY($args);

if You Need To Use It In pre_get_posts
$meta_query = array(
                array(
                    'key' => 'common_authors',
                    'value' => array ( 'author1', 'author2', 'author3' ),
                    'compare' => 'IN'
                )
            );

$query->set('meta_query', $meta_query);

Comment: Hi Code Updated
Comment: That doesn't seem to work.. I'm overriding the default search via the pre_get_posts filter, I'm guessing that may have something to do with it.

WordPress custom query by meta_key


Write mix node (tag + text )replacing only specific node

Question: I have a loop between child nodes
I can have word a fo:block than another word like:
<mynode>
Hi ok
<fo:block>
hi ok fo block
< /fo:block>
maybe another text node here...
</mynode>

I have to replace <fo:block> with
 but i have to leave text in the same position (before and maybe after fo:block if it exists)
I try this code but  (suppose to loop child (*) nodes):
<xsl:for-each select="/mynode">
  <xsl:if test="text()"><xsl:value-of select="text()"/></xsl:if>
  <xsl:for-each select="child::*">

    <xsl:choose>
      <xsl:when test="normalize-space(local-name())
                      = normalize-space('block')">
        <xsl:call-template name="fo-block">
          <xsl:with-param .../>
        </xsl:call-template>
      </xsl:when>
    <xsl:otherwise>
      <xsl:if test="text()"><xsl:value-of select="text()"/></xsl:if>
    </xsl:otherwise>
  </xsl:choose>
</xsl:for-each>
</xsl:for-each>

if test= text() so node contains text then display text, otherwise i get the name of node and test if is a block: if so, i call a specific template otherwise a test if contains text.
Seems to work for now..So, could be the right choice/code for my scope?
thanks!
roby
Answer: The problems that appear at first glance include:

Your inner for-each loop loops over child::*, which will match every element child; it will not match any other children (text nodes, comments, processing instructions).  I think you meant child::node().
Your test for block elements ("normalize-space(local-name()) = normalize-space('block')") is namespace-oblivious, so it is unnecessarily fragile.  The calls to normalize-space() are pointless, since local-name() never returns any string containing whitespace, and the literal string 'block' doesn't contain any whitespace.
A shorter, more reliable test would be test="self::fo:block".
You say
Seems to work for now..

If your tests show this code working, your tests are not doing you as much good as they should.

The portion of your processing that you describe seems to amount to:  change fo:block elements to div; leave everything else the same.  The simplest way to approach such a transform is to write an identity transform and then add more specific rules to capture things that need to change.  For example:
<xsl:template match="fo:block">

    <xsl:apply-templates select="@*|node()"/>

</xsl:template>

<xsl:template match="@*|node()">
 <xsl:copy>
   <xsl:apply-templates select="@*|node()"/>
 </xsl:copy>
</xsl:template>

Comment: What is the purpose of the two templates matching `comment()` and `processing-instruction()`? These nodes are already handled by the identity transform template. AFAICT, the only effect of these templates is to produce an error message of "Error: Ambiguous rule match for ...".
Comment: I suspect that when I made my version of the identity transform years ago, I factored them out because I often want to treat them separately.  They aren't handled by the general rule I gave originally, because they don't match the match pattern `@*|*` (unless I'm missing something here).  But I can make your observation true, and remove them, if you like
Answer: M .,
your schema and response was very useful
I add complexity to my fo:block translation: consider attributes replaced by html if im in a table  (in a fo:cell parent) i use div, otherwise(anywhere) p.. So, i make these changes, hope you are agree:
<xsl:template match="fo:block">

<xsl:choose>
<xsl:when test="parent::fo:table-cell">

    <xsl:apply-templates select="node()"/>

 </xsl:when>
 <xsl:otherwise>
    <xsl:if test="@space-before">
        <xsl:call-template name="count-br">
            <xsl:with-param name="howmuch"><xsl:value-of select="substring-before(normalize-space(@space-before),'cm')"/></xsl:with-param>
        </xsl:call-template>
    </xsl:if>

    <xsl:if test="@font-size">
        <xsl:attribute name="font-size"><xsl:value-of select="@font-size"/></xsl:attribute>
    </xsl:if>
    <xsl:if test="@text-align">
        <xsl:attribute name="text-align"><xsl:value-of select="@text-align"/></xsl:attribute>
    </xsl:if>
    <xsl:if test="@font-family">
        <xsl:attribute name="font-family"><xsl:value-of select="@font-family"/></xsl:attribute>
    </xsl:if>
    <xsl:apply-templates select="node()"/>

 </xsl:otherwise>
 </xsl:choose>
 </xsl:template>


Android SQlite to json

Question: I have some data stored inside SQlite at my android application and I want to export it into json file and send it to a server via post HTTP.
You can actually see my code in this link - Old question containing my code
After searching the web, I'm only finding samples of doing it the other way around (from json to sqlite). I'll be happy to receive some help/push to the right direction.
Edit -
I get a small exeption while trying to initilise Gson - String json = gson.toJson(Record);
. Can you take a look please -
public ArrayList<Record> getAllRecordsArray() {
        ArrayList<Record> localList = new ArrayList<Record>();

        String selectQuery = "SELECT * FROM " + TABLE_RECORD;

        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);

        //Loops through all rows and adds them to the local list
        if(cursor.moveToFirst())
        {
            do {
                //Get record information
                Record record = new Record();
                record.setpLat(cursor.getDouble(0));
                record.setpLong(cursor.getDouble(1));
                record.setpAcc(cursor.getFloat(2));
                record.setpTime(cursor.getLong(2));
                //Add record  to list
                localList.add(record);
            } while (cursor.moveToNext());
        }

        return localList;
    }

    Gson gson = new Gson();
    String json = gson.toJson(Record);

Comment: Check this out http://stackoverflow.com/questions/25722585/convert-sqlite-to-json
Comment: Thanks. when handling myPath=DB_PATH, How can I know my database path ?
Comment: The path where you created your database. By default its something like this `/data/data/com.me.myapp/databases/mydb.db` Or you can use `String dbname = "mydb.db";
Path dbpath = ctx.getDatabasePath(dbname);`
Answer: Using the GSON library is by far the easiest way of handling it.
1) Initilize an ArrayList
2) Retrieve all the data from your database and store it in the ArrayList
3) Use gson.toJson(NameOfArrayList);
4) DONE. You now have a string containing all the data from your database.
Comment: Thanks you. Sounds indeed easy, but I have no experience with that. Can you provide an example please ? How can I insert the data from the SQlite into the ArrayList ?
Comment: I quickly put together this pastebin, with code snippets taken from one of my own projects:
http://pastebin.com/2WYDvyha

With that, you can get an ArrayList with all the data, then you can simply create a gson variable and use that:
Gson gson = new Gson();
String jsonString = gson.toJson(arrayList);
Comment: Thank you. I get a little exception, I added it to the main post. can you take a look please ?
Comment: There is absolutely no way for me to identify your problem if you don't post the actual exception message.
Answer: Have you considered using a library such as Gson? It allows you to easily convert a POJO (Plain old java object) to JSON.
You can simply get your object form your db and then do the following.
MyObject obj = new MyObject();
Gson gson = new Gson();
String json = gson.toJson(obj);

Its very useful, here is a link to the user guide:
https://sites.google.com/site/gson/gson-user-guide
Good Luck!
Comment: Thank you, but it looks a bit too complicated for me.
Answer: The below procedure could help ,
public JSONArray QueryAsJSON(String Query)
            throws org.json.simple.parser.ParseException {
        String out = "[";

        try {
            Cursor c = null;

            c = database.rawQuery(Query, null);
            c.moveToFirst();
            String VergCol = "";

            for (int j = 0; j < c.getCount(); j++) {
                out += VergCol + "{";
                String vergRow = "";

                for (int i = 0; i < c.getColumnCount(); i++) {
                    out += vergRow + "\"" + c.getColumnName(i) + "\"" + ":"
                            + "\"" + c.getString(i) + "\"";
                    vergRow = ",";
                }

                out += "}";
                VergCol = ",";
                c.moveToNext();
            }
        }
        catch (Exception e1) {
            e1.printStackTrace();
        }

        out += "]";

        JSONParser parser = new JSONParser();
        org.json.simple.JSONArray jsonArray = (org.json.simple.JSONArray) parser
                .parse(out);
        return jsonArray;

}

Comment: please don't ever do this.

Android SQlite to json


Modules with rank and localization

Question: This question is from my assignment of localization of modules and I need help with it.

Let A be a non-zero commutative ring. $S_0$ be the multiplicatively closed subset of non-zero  divisors in A and $Q(A)= S_{0}^{-1}A $ be the total quotient ring of A. An A-module V is called a module with rank over A if $S_{0}^{-1} V$ is  a free Q(A) module; we also say that V has rank over A and put $Rank_A V= Rank_{Q(A)} S_{0}^{-1} V$.

(a) Every free A-module V is an A-module with rank and in this case its rank  is the   rank of the free A-module V.
I have done this.
(b)  If A is an integral domain, then Q(A) is the quotient field of A and hence every A-module has a rank and $Rank_A V= \dim_{Q(A)} S_{0}^{-1}V$.
How to construct basis of A-module in this case?
(c) If V is an A-module with rank , then $S_{0}^{-1} V$ has a Q(A)- basis of the type $x_i /1$ $i\in I$ and $x_i , i\in I$ is a maximal linearly independent (over A) family in V.
V is an A-module with rank means that $S_{0}^{-1} V$ is a free Q(A) module means there exists a basis. I have been given $x_i's$ are maximal Linearly independent set for V , it must also generate V as if it doesn't an element say v then { $v, x_i $} is a L I set , hence {$x_i's$} is not maximal LI set.  So, this part is easy to complete and I have done it.
(d) Every finite torsion free A-module with rank is isomorphic to a A-submodule of a finite free A-module.
Well, any submodule of a free A-module will also be free and if in the basis of V there exists an element $a \in A$ which is not torsional free then I have av=0 , which will force v =0 which is a contradiction. Any submodule of V and V itself are torsion free but how should I prove that an isomorphism exists?
Thanks!
Answer: There are quite a few misunderstandings in what you say, so let's go through them.
b) You do not need to construct a basis of an $A$-module here.  All you need is that every vector space (e.g. module over the field $Q(A)$) has a basis.
c) No, the $x_i$ do not necessarily generate $V$.  A set can be maximal linearly independent, without generating the module.  For example regard $\mathbb{Z}$ as a module over itself.  Then $\{2\}$ is a maximal linearly independent set.  Thus $\{2,3\}$ is not linearly independent: $2\times 3-3\times 2=0$.  However $3$ is not in the span of $2$.
In fact you do not need to show the $x_i$ generate $V$ here.  You are not "given" the $x_i$ are maximal linearly independent.  You need to deduce it:
Any $v\in S_0^{-1}V$ has the form: $$v=s^{-1}\left(\sum_i a_i x_i) \right),$$ with $s\in S_0$ and $a_i\in A$.  Thus $$vs-\left(\sum_i a_i x_i) \right)=0,$$ so $\{x_i|i\in I,v\}$ is not linearly independent over $A$.
d) No a submodule of a free module is not necessarily free.  Consider $\mathbb{Q}\times \mathbb{Q}$ as a module over itself. Then neither factor of $\mathbb{Q}$ is free.
The point here is that because $V$ is torsion free, it embeds in $S_0^{-1}V$, which has a basis $\frac {x_i}1$ over $Q(A)$.  As $V$ is finitely generated, all its generators are contained in the span of the $\frac {x_i}s$, for some fixed $s\in S$.  It remains only to show that the $\frac {x_i}s$ are linearly independent over $A$, which follows from the fact that they are linearly independent over $Q(A)$.
Thus we can conclude that over $A$, the  $\frac {x_i}s$ span a free $A$-module, which contains $V$.
Comment: In (b) $Q(A)$ is a field.  A module over a field is a vector space (definition of vector space).  Every vector space has a basis.  Therefore it is free (definition of free).
Comment: You misread.  I did not claim the $\{x_i\}$ are not linearly independent over $A$.  I said that $\{x_i\}\cup \{v\}$ are not linearly independent over $A$.
Comment: This is precisely the meaning of maximal linearly independent set: It is linearly independent, and if you throw in any extra element $v$, then it stops being linearly independent.
Comment: By definition of $module$ $with$ $rank$ $S_0^{-1}V$ has a $Q(A)$ basis of the form $\frac{x_i}{y_i}$, where $y_i\in S_0$.  Then each $y_i$ is a unit in $Q(A)$, and multiplying the elements of a basis by units, results in a basis.  In particular we may multiply each  $\frac{x_i}{y_i}$ by $y_i$ to get $\frac{x_i}{1}$.
Comment: I am aware of the fact that every vector space has a basis but how will it help in (b)?
Comment: I am aware of the definition of Linear independence but how does $ vs -(\sum_i a_i x_i) =0$ implies that {$x_i$} is not Linear independent over A? Also , can you help with proving how {$x_i$} is a maximal  LI set over V?
Comment: I understand how I was wrong in (c). Can you please help in proving how $S_0^{-1}V$ has Q(A) basis of the type $frac{x_i} {1}$?
Comment: Thank you very much for this answer!

Modules with rank and localization


Value Object optimization using array functions of PHP

Question: I have these two methods inside a Value Object:
public final function unlockableLetters()
{
    return [
        [],
        ['A', 'B'],
        ['C']
    ][$this->level];
}

public final function unlockedLetters()
{
    return [
        [],
        ['A', 'B'],
        ['A', 'B', 'C'],
    ][$this->level];
}

The first one returns unlockable elements of each level.

At level 0, returns [].
At level 1 returns A and B.
At level 2 returns C.

The second one returns unlocked elements.

At level 0, returns [].
At level 1 returns A and B.      // NULL + A + B
At level 2 returns A, B and C.   // A + B + C

There is a way to use array functions of php that create an merge of array returned by unlockLetters() from index 0 to current $this->level?
EDIT
I want to leave letters only inside unlockableLetters() method. So, unlockedLetters() can "build" its own return value from first method. If something change in the former, change will occur in the latter.
Comment: I agree with @deceze, its not clear what you want to merge... are you saying you wantto generate the return of `unlockedLetters()` from `unlockLetters()` using array functions instead of hard coding it? Also i think better method names are in order here because that also makes it confusing... i would use `getUnlockableLetters` and `getUnlockedLetters()` or something along those lines depending on how these are used.
Comment: You've spent a lot of time setting up your question, but your actual question is a bit terse and hard to understand. I for one am very unclear on what it is that you're asking.
Comment: I've edited unlockedLetters() to unlockableLetters(). Is more clear. Thank you
Answer: It's not completely clear what you want. As I said in my comment:

agree with @deceze, it's not clear what you want to merge... are you saying you want to generate the return of unlockedLetters() from unlockLetters() using array functions instead of hard coding it? Also I think better method names are in order here because that also makes it confusing... I would use getUnlockableLetters and getUnlockedLetters() or something along those lines depending on how these are used.

However, what I think you mean might look something like this:
// add a property so we can reference it - you might want to adjust
// the visibility to private or public depending on its nature
protected $unlockableLetters = [
    [],
    ['A', 'B'],
    ['C']
];

public final function unlockLetters()
{
    // just return the reference to the letters for the level
    return $this->unlockableLetters[$this->level];
}

public final function unlockedLetters()
{
    // slice off the array of latters from the lowest level
    // to the current one - note the +1 since array_slice
    // wants a length and our offsets are 0-based and thus length-1
    $data = array_slice($this->unlockableLetters, 0, $this->level+1);

    // use array reduce to build a single array that has
    // all the letters for levels 0 --> $this->level
    return array_reduce($data, function ($merged, $datum) {
       return array_merge($merged, $datum);
    }, []);
}

Answer: As long as I understand your question, you are looking for this
public final function unlockableLetters() {
    $unlockables = [
        [],
        ['A', 'B'],
        ['C']
    ];
    return array_reduce(array_slice($unlockables, 0, $this->level + 1), function($carry, $item){
        return array_merge($carry, $item);
    }, []);
}

Answer: I agree with other developers here.
Question is not clear.
But here is my guess:
public final function unlockLetters()
{
    $arr =  [
        [],
        ['A', 'B'],
        ['C']
        ];
    return $arr[$this->level];
}

public final function unlockedLetters()
{
    $arr = [
        [],
        ['A', 'B'],
        ['A', 'B', 'C']
    ];
    return $arr[$this->level];
}

Comment: Ok, sorry. I've updated the question. The point is I do not want to change both method if something change. I want to leave $arr only inside unlockableLetters().


Rolling fixed window scheme for GARCH forecasting

Question: I'm working on my bachelors thesis which mainly revolves around this paper: https://www.mdpi.com/2225-1146/4/1/3/htm
Shortly after describing the dataset in 3.1 the authors mention that they use a rolling fixed window scheme to estimate the parameters and to predict the conditional variance for the next 20 days. The time windows and forecast horizons are listed in a table in the appendix.
I get what they did and I understand the reasoning behind it, but I can't find any literature about it. Why did they decide to chose 20 days? Why not 10 or 50? Is there any rule I should follow if I want to incorporate this method myself, considering I use a different dataset and timescale?
As of now, I estimated the parameters for my in-sample and then forecasted the variance for the out-sample using this parameter. Would that be wrong?
Comment: What do you think about my answer? If it is helpful, consider accepting it by clicking on the tick mark to the left. Otherwise, you may ask for further clarification. This is [how Cross Validated works](https://stats.stackexchange.com/tour).
Answer: Forecast horizon should normally depend on the application. If the model is considered in a context where agents are looking 20 days ahead and making decisions based on a 20-day outlook, 20-day ahead forecasts is what is needed. If the model is analyzed without a particular application in mind, one could look at multiple forecast horizons and analyze all of them. Of course, that would be more work.
What is sensible in your case also depends on the application. There is likely nothing wrong with using a 20-day horizon, but this horizon may or may not be relevant and interesting.
Comment: Thanks for pointing out that I can accept the answer by clicking on the tick, I didn't know that. Regarding your answer, do you know any literature that explains rolling fixed windows mathematically? I've looked through my textbooks on time series but haven't found anything unfortunately.
Comment: @crevez, which aspects of rolling windows are you interested in? The construction of rolling windows is pretty simple. The use is based on the general idea of cross validation combined with the fact that time series observations are not independent.
Comment: I was thinking about using a rolling window in my bachelors thesis, which is why I wanted to know a mathematical description of it so that I can mention it briefly in my thesis. But I just decided against that, since I don't think it will add any value to the analysis I actually focus on. Still, thanks a lot for your help.
Comment: @crevez, you are welcome!


Cors erro - Visual Studio .Net Web API React

Question: Tenho um projeto onde o back é em .net e o front em react.
Consigo fazer todas as operações do CRUD com postman, entretanto, no react recebo erro de cors.
Já entendo a causa do problema, mas não consigo encontrar a solução. Consultei diversos sites (lista ao final) seguindo a risca as orientações, mas sem sucesso.
Para me certificar que não há problema com o front, subi uma api com php, "resolvi o cors" e tudo funcionou bem. Tentei usar proxy no react e extensões no navegador onde "resolvem o cors", mas problema persiste com o .net.
Alguém poderia ajudar? Removi todo código que não funcionou em meus testes.
setup.js
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.EntityFrameworkCore;
using FAP.Models;

namespace FAP
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<FapContext>(options => options.UseMySql(Configuration.GetConnectionString("DefaultConnection")));
            services.AddControllers();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

Controller
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using FAP.Models;

namespace FAP.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class SolucaoPadroesController : ControllerBase
    {
        private readonly FapContext _context;

        public SolucaoPadroesController(FapContext context)
        {
            _context = context;
        }

        // GET: api/SolucaoPadroes
        [HttpGet]
        public async Task<ActionResult<IEnumerable<SolucaoPadrao>>> GetSolucaoPadrao()
        {
            return await _context.SolucaoPadrao.ToListAsync();
        }

        // GET: api/SolucaoPadroes/5
        [HttpGet("{id}")]
        public async Task<ActionResult<SolucaoPadrao>> GetSolucaoPadrao(int id)
        {
            var solucaoPadrao = await _context.SolucaoPadrao.FindAsync(id);

            if (solucaoPadrao == null)
            {
                return NotFound();
            }

            return solucaoPadrao;
        }

        // PUT: api/SolucaoPadroes/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPut("{id}")]
        public async Task<IActionResult> PutSolucaoPadrao(int id, SolucaoPadrao solucaoPadrao)
        {
            if (id != solucaoPadrao.Id)
            {
                return BadRequest();
            }

            _context.Entry(solucaoPadrao).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!SolucaoPadraoExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/SolucaoPadroes
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see https://aka.ms/RazorPagesCRUD.
        [HttpPost]
        public async Task<ActionResult<SolucaoPadrao>> PostSolucaoPadrao(SolucaoPadrao solucaoPadrao)
        {
            _context.SolucaoPadrao.Add(solucaoPadrao);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetSolucaoPadrao", new { id = solucaoPadrao.Id }, solucaoPadrao);
        }

        // DELETE: api/SolucaoPadroes/5
        [HttpDelete("{id}")]
        public async Task<ActionResult<SolucaoPadrao>> DeleteSolucaoPadrao(int id)
        {
            var solucaoPadrao = await _context.SolucaoPadrao.FindAsync(id);
            if (solucaoPadrao == null)
            {
                return NotFound();
            }

            _context.SolucaoPadrao.Remove(solucaoPadrao);
            await _context.SaveChangesAsync();

            return solucaoPadrao;
        }

        private bool SolucaoPadraoExists(int id)
        {
            return _context.SolucaoPadrao.Any(e => e.Id == id);
        }
    }
}

Consumindo um WEB API no Visual Studio
https://stackoverflow.com/questions/6290053/setting-access-control-allow-origin-in-asp-net-mvc-simplest-possible-method
https://developer.mozilla.org/pt-BR/docs/Web/HTTP/Controle_Acesso_CORS
https://www.hexacta.com/2014/09/15/How-to-enable-CORS-on-your-Web-API
https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#cors-with-named-policy-and-middleware
https://www.html5rocks.com/en/tutorials/cors/
Comment: Supostamente basta configurar conforme [neste link](https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#cors-with-named-policy-and-middleware). Tente novamente e certifique-se que o endereço é exatamente igual ao do front, inclusive com o http ou HTTPS.
Answer: Entendendo CORS
Isso aconteceu porque CORS é uma implementação de segurança do browser. É o browser quem bloqueia a requisição.
O server, nesse caso, tem apenas o papel de notificar, quando perguntado, se uma origem é permitida ou não.
Isso quer dizer que por mais que ele diga que não reconhece a origem, uma requisição server-to-server não é bloqueada. Inclusive a requisição que faz a consulta de CORS é uma requisição adicional que usa o método OPTIONS (monitore isso com o devtools).
Solução
Este é um startup.cs que habilita CORS.
Pontos de atenção:

services.AddCors
builder.WithOrigins
app.UseCors

    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(MyAllowSpecificOrigins,
                builder =>
                {
                    builder.WithOrigins("http://example.com",
                                        "http://www.contoso.com");
                });
            });

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            app.UseCors(MyAllowSpecificOrigins);

            app.UseHttpsRedirection();
            app.UseMvc();
        }
    }

Link da Documentação
https://docs.microsoft.com/pt-br/aspnet/core/security/cors?view=aspnetcore-3.1
Comment: Eu já havia tentado, mas sem sucesso.
Comment: Consegui, mas mexi em muita coisa. Agora vou remover o excesso e ver o que realmente fez funcionar. Achando, informo aqui.


Calling different class' constructor in a constructor?

Question: Inside separate .h files:
    class Appt{
        public:
        Appt(string location, string individual, DaTime whenwhere);

        private:
        string individual;
        string location;
        DaTime whenwhere;  // I thought this would initialize it
        DaTime a;
    }

    class DaTime{
        public:
        DaTime(Day day, Time start, Time end); // Day is enum, Time is class

        private:
        int duration;
        Day day;
        Time start;
        Time end;

    }

Inside separate .cc files:
    // class Appt constructor
    Appt::Appt(string location, string individual, DaTime whenwhere)
    {
            a_SetLocation(location);
            a_SetIndividual(individual);
            DaTime a(whenwhere); // THE LINE IN QUESTION
    }

    // class DaTime constructor
    DaTime::DaTime(Day day, Time start, Time end)
    {

            dt_SetDay(day);
            dt_SetStart(start);
            dt_SetEnd(end);
    }

inside main():
    /* Creating random variables for use in our classes */
    string loc1 = "B";
    string p1 = "A";

    /* Creating instances of our classes */
    Time t1(8, 5), t2(8, 30);
    DaTime dt1('m', t1, t2);
    Appt A1(loc1, p1, dt1);

My question is if there is a clean way for me to call DaTimes constructor inside of Appt? I know this way wouldn't work because my instance of DaTime, a would die after the constructor was finished.
EDIT: The error I am getting is:
    In constructor 'Appt::Appt(std::string, std::string, DaTime)':
    appt.cc: error: no matching function for call to 'DaTime::DaTime()'
     Appt::Appt(string location, string individual, DaTime when where)
    In file included from appt.h:15:0,
             from appt.cc:15:
    class.h:note: DaTime::DaTime(Day, Time, Time)
      DaTime(Day day, Time start, Time end);
      ^
    note:   candidate expects 3 arguments, 0 provided
    note: DaTime::DaTime(const DaTime&)

Answer: Make a a data member of Appt and initialize it in the constructor initialization list:
Appt::Appt(string location, string individual, DaTime whenwhere) : a (whenwhere)
{
  ....
}

Also, it isn't clear whether you want to pass all of your parameters by value. Consider passing const references instead.
Note: The error you are getting seems to indicate that you do have a DaTime data member in your class, and that you are not initializing it in the constructor initialization list. This means that a default initialization must be performed, and since DaTime does not have a default constructor, you get the error. Remember: once you are in the body of a constructor, all your data members have been initialized. If you don't initialize them explicitly, they get default constructed.
DaTime whenwhere;  // I thought this would initialize it

This is not an initialization. It just a member declaration. whenwhere will get initialized when a DaTime constructor is called. In C++11, you can also initialize at the point of declaration:
DaTime whenwhere{arg1, arg2, aer3};

Comment: But then I would have to return `a`?
Comment: Yes, I do have a DaTime data member, so that makes sense. I thought I had initialized it. I hate to post a ton of code, but I'll add an edit to show that portion of the class.
Comment: @AllenS You don't need to post a ton of code, just a simplified example that reproduces the problem. But it should be easy to spot if a data member has been initialized or not. Your compiler error is pretty clear: the default constructor is required at some point, which means you are not initializing an object in the way it should be.
Comment: @AllenS So now you have two `DaTime` data members now, `a` and `whenwhere`. You have to initialize *both* of them correctly.
Comment: If I am initializing `a` to `whenwhere`, where am I supposed to initialize `whenwhere` to?
Comment: @AllenS That is up to you to decide. It depends on what you want your program to do. But note that you have two things called `whenwhere`, so your question is not clear.
Answer: In class  Appt include following code:
DaTime a;

and In Constructor of Appt
Appt::Appt(string location, string individual, DaTime whenwhere)
    {
            a_SetLocation(location);
            a_SetIndividual(individual);
            a = whenwhere; //call copy constructor of `DaTime`
    }

About error:
You do not have a default constructor for your DaTime Class.
So, What you can do is pass the  values for DaTime ti your constructor of Appt and create an object of DaTime as a= new DaTime(a,b,c).
Or Do pass the object by reference.
Hope this will help you.
Comment: Thanks for the help. It doesn't solve my error, though it makes sense compared to my attempt at a solution. I made an edit to include my error since perhaps my error is elsewhere.
Comment: @AllenS My solution fixes that error. I will add a note explaining why.