text:
Q: LocalContainerEntityManagerFactoryBean entityManagerFactory & EntityManagerHolder usage I want to implement a read-only routing for db, I have researched lots of ways to achieve this and came across the following repository.
I couldn't understand the function of the following two methods so I simplified and changed it in my repository in the following way.
transactionManager() & entityManagerFactory(EntityManagerFactoryBuilder builder)
If I keep having these methods I am getting the error , how could I overcome this error?
Thanks.
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create index contact_tag_ix_uuid on contact_tag (uuid)" via JDBC Statement
    at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:581) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:526) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applyIndexes(AbstractSchemaMigrator.java:348) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
    at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:88) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:220) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
    at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:123) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:196) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
    at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:85) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
    at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:335) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
    at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:471) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1498) ~[hibernate-core-5.6.14.Final.jar:5.6.14.Final]

package ru.project.master.slave.datasources;

import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.google.common.collect.Maps;

import ru.project.master.slave.properties.Properties;
import ru.project.master.slave.routing.RoutingDataSource;

@Configuration
@ComponentScan
@EnableJpaRepositories("ru.project.master.slave.dao")
@EnableTransactionManagement
public class DataSourcesConfiguration {

    @Autowired
    private Properties props;

    @Bean(name = "masterDataSource")
    @Primary
    public DataSource masterDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(props.getProperty("spring.datasource.master.driver-class-name"));
        dataSource.setDefaultAutoCommit(false);
        dataSource.setUsername(props.getProperty("spring.datasource.master.username"));
        dataSource.setPassword(props.getProperty("spring.datasource.master.password"));
        dataSource.setUrl(props.getProperty("spring.datasource.master.url"));
        return dataSource;
    }

    @Bean
    public RoutingDataSource routingDataSource() {
        RoutingDataSource dataSource = new RoutingDataSource();
        dataSource.setDefaultTargetDataSource(masterDataSource());
        Map<Object, Object> targets = Maps.newHashMap();
        targets.put(DataSourceType.MASTER, masterDataSource());
        targets.put(DataSourceType.SLAVE, slaveDataSource());
        dataSource.setTargetDataSources(targets);
        dataSource.afterPropertiesSet();
        return dataSource;
    }

    @Bean(name = "slaveDataSource")
    public DataSource slaveDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(props.getProperty("spring.datasource.slave.driver-class-name"));
        dataSource.setDefaultAutoCommit(false);
        dataSource.setUsername(props.getProperty("spring.datasource.slave.username"));
        dataSource.setPassword(props.getProperty("spring.datasource.slave.password"));
        dataSource.setUrl(props.getProperty("spring.datasource.slave.url"));
        return dataSource;
    }

    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(masterDataSource());
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder) {
        HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
        vendorAdapter.setGenerateDdl(Boolean.parseBoolean(props.getProperty("spring.jpa.generate-ddl")));
        Map<String, String> additionalProperties = Maps.newHashMap();
        additionalProperties.put("hibernate.dialect", props.getProperty("spring.jpa.dialect"));
        LocalContainerEntityManagerFactoryBean factory = builder.dataSource(routingDataSource())
                .packages("ru.project.master.slave.orm").persistenceUnit("routingEMF").properties(additionalProperties)
                .build();
        factory.setJpaVendorAdapter(vendorAdapter);
        factory.afterPropertiesSet();

        return factory;
    }

}

My solution:
But somehow If feels missing because I think I need to implement as have been mentioned here
https://stackoverflow.com/a/75223437/19751568
I need some configuration to provide some hibernate functionality.
Not only that the hibernate.connection.provider_disables_autocommit allows you to make better use of database connections, but it's the only way we can make this example work since, without this configuration, the connection is acquired prior to calling the determineCurrentLookupKey method TransactionRoutingDataSource.
@Configuration
@ComponentScan
@("io.api.persistence.repository")
@EnableTransactionManagement
public class DataSourcesConfiguration {

    @Value("${spring.datasource.master.url}")
    private String mstUrl;

    @Value("${spring.datasource.master.username}")
    private String mstUsername;

    @Value("${spring.datasource.master.password}")
    private String mstPassword;

    @Value("${spring.datasource.slave.url}")
    private String slaveUrl;

    @Value("${spring.datasource.slave.username}")
    private String slaveUsername;

    @Value("${spring.datasource.slave.password}")
    private String slavePassword;

    @Bean
    public DataSource dataSource() {
        RoutingDataSource masterSlaveRoutingDataSource = new RoutingDataSource();
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.MASTER, masterDataSource());
        targetDataSources.put(DataSourceType.SLAVE, slaveDataSource());
        masterSlaveRoutingDataSource.setTargetDataSources(targetDataSources);

        // Set as all transaction point to master
        masterSlaveRoutingDataSource.setDefaultTargetDataSource(masterDataSource());
        return masterSlaveRoutingDataSource;
    }

    public DataSource slaveDataSource() {
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setJdbcUrl(slaveUrl);
        hikariDataSource.setUsername(slaveUsername);
        hikariDataSource.setPassword(slavePassword);
        return hikariDataSource;
    }

    @Primary
    public DataSource masterDataSource() {
        HikariDataSource hikariDataSource = new HikariDataSource();
        hikariDataSource.setJdbcUrl(mstUrl);
        hikariDataSource.setUsername(mstUsername);
        hikariDataSource.setPassword(mstPassword);
        return hikariDataSource;
    }


text:
Q: Issue using Canvas dataURL I am trying to make work a button that would open a new window with the content of my canvas in it (a rendered image of the canvas).
Here's my JS code :
var canvas  = document.getElementById("thecanvas");
var dataUrl = canvas.toDataURL();
var context = canvas.getContext("2d");
context.fillStyle = "rgba(0, 0, 255, .5)";
context.fillRect(25, 25, 125, 125);
function clickme() {
window.open(dataUrl, "toDataURL() image", "width=200, height=500");
}

HTML code :
<input type="button" onclick="clickme()" value="OPEN"/>

<canvas id="thecanvas" height="200" width="500" style="border:1px solid black">

But when I click on the "OPEN" button, nothing happens...but I really don't see why. I have looked on alot of sites for tutorials. I even copied and pasted some codes, but still nothing happens. Am I doing something wrong? Thank you!

A: First off, the order in which you execute your statements matters. You need to call toDataURL after you draw to the canvas, or the dataURL generated with not contain that content.
I'm not sure what your script tags are like, but here's a working example that does the event in a slightly more foolproof way: http://jsfiddle.net/b7G6J/
HTML:
<input id="thebutton" type="button" value="OPEN"/>

<canvas id="thecanvas" height="200" width="500" style="border:1px solid black">

JS:
var canvas  = document.getElementById("thecanvas");
var context = canvas.getContext("2d");

// First drawing commands
context.fillStyle = "rgba(0, 0, 255, .5)";
context.fillRect(25, 25, 125, 125);
// Then toDataURL
var dataUrl = canvas.toDataURL();

var button = document.getElementById("thebutton");
button.onclick =function() {
  window.open(dataUrl, "toDataURL() image", "width=200, height=500");
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Execute grep command on Linux and capture result I am trying to execute grep command on the linux using the following java code, but I am not able to capture output. I am getting always null in the output
Process p;
        String output = null;
        try {
            String command = "grep searchString filename.txt";
            System.out.println("Running command: " + command);

            p = Runtime.getRuntime().exec(command);

            BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

            if (null != output) {

                while ((output = br.readLine()) != null)
                    System.out.println(output);
            }

            p.waitFor();
            System.out.println("exit: " + p.exitValue());
            p.destroy();
        } catch (Exception e) {
            e.printStackTrace();

    }

How to capture the output?
Is there any third party library or some better way to execute the command on linux and capture the output?

A: output has not been assigned when you do if check. Change your code like below:
    Process p;
    String output = null;
    try {
        String command = "grep searchString filename.txt";
        System.out.println("Running command: " + command);

        p = Runtime.getRuntime().exec(command);
        p.waitFor();

        BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));

            while ((output = br.readLine()) != null) {
                System.out.println(output);
                // Process your output here
            }

        System.out.println("exit: " + p.exitValue());
        p.destroy();
    } catch (Exception e) {
        e.printStackTrace();

}


text:
Q: error in Angular - firebase based chat Application I am creating a chat application by using Angular 6 and Firebase, and I am facing following errors:
Error 1 -
I am getting error in importing FirebaseListObservable from angularfire2/database
import { AngularFireDatabase, FirebaseListObservable} from 'angularfire2/database';

[ts] Module '"/Users/user/Projects/A4/chat-app/node_modules/angularfire2/database/index"' has no exported member 'FirebaseListObservable'.

Error  - 2

[ts]
  Argument of type '{ query: { limitToLast: number; orderByKey: boolean; }; }' is not assignable to parameter of type 'QueryFn'.
  Object literal may only specify known properties, and 'query' does not exist in type 'QueryFn'.

getMessages(): FirebaseListObservable<ChatMessage[]> {

return this.db.list('messages', {
  query: {
    limitToLast: 25,
    orderByKey: true
  }
});

A: chack Angular2 fire has no exported member 'FirebaseListObservable'
You need to change your dependancy in app component as follow:
`import {AngularFireDatabase , FirebaseListObservable} from "angularfire2/database";`

to
`import { AngularFireDatabase, FirebaseListObservable } from 'angularfire2/database-deprecated';`

It will work.


text:
Q: Cannot be authenticated in Dusk using sanctum I'm trying to make login page using Laravel sanctum and React.
I can login in my browser (can see 'authenticated' message), but I cannot login in Dusk.
To be exactly, I can login once in Dusk but I'm not authenticated in next access.
I cannot understand why it happened.
How can I be authenticated with Dusk using sanctum?
Environment

*

*Laravel 7.x

*laravel/sanctum ^2.6

*React 16.13.1

Login.js
import React, { useState } from 'react';
const axios = window.axios;

export default function Login(props) {
  const [strId, setStrId] = useState('');
  const [password, setPassword] = useState('');
  const [hoge, setHoge] = useState('ini state');

  function normalUserLogin() {
    axios
      .get('/sanctum/csrf-cookie')
      .then((response) => {
        axios
          .post('/api/login', {
            strId: strId,
            password: password,
          })
          .then((response) => {
            setHoge(response.data);
            authCheck();
          })
          .catch((error) => {
            console.log(error);
          });
      })
      .catch((error) => {
        alert('Error happened.');
      });
  }

  function authCheck() {
    axios
      .get('/api/user/auth')
      .then((response) => {
        setHoge(response.data);
      })
      .catch((error) => {
        console.log(error);
        alert('error happened getting auth information');
      });
  }

  return (
    <>

          <form>

              User ID
              <input
                name="user-id"
                id="user-id"
                className="d-block"
                value={strId}
                onChange={(e) => setStrId(e.target.value)}
              />

              Password
              <input
                type="password"
                name="password"
                id="password"
                autoComplete="off"
                className="d-block"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
              />

          </form>
          <button
            type="button"
            id="normal-login"
            className="btn btn-outline-success d-block"
            onClick={normalUserLogin}
          >
            Login
          </button>

        {hoge}

    </>
  );
}

MyCustomLoginController (app/Http/Api/LoginController.php)
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Laravel\Sanctum\Sanctum;
use App\User;

class LoginController extends Controller
{
    // routing is '/api/login'
    public function login(Request $request)
    {
        $str_id = $request->input('strId');
        $password = $request->input('password');

        $credentials = compact('str_id', 'password');

        if (Auth::attempt($credentials)) {
            $hoge = Auth::check() ? 'OK' : 'NG';
            // $hoge is OK in dusk.
            return response($hoge);
        } else {
            return response('Cannot Authenticated', 401);
        }
    }
}

Auth check action
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\User;

class UserController extends Controller
{
    // routing is '/api/user/auth'
    public function auth(Request $request)
    {
        $user = Auth::user();
        if ($user) {
            $params = User::getParamsForApp($user->str_id);
            // in local environment, I can see 'Authenticated.'
            return response('AUTHENTICATED');
        } else {
            // in dusk, i can see 'Not Authenticated.'
            return response('Not Authenticated.');
        }
    }
}

Dusk
<?php

namespace Tests\Browser;

use Illuminate\Foundation\Testing\DatabaseMigrations;
use Laravel\Dusk\Browser;
use Tests\DuskTestCase;
use App\User;

class LoginTest extends DuskTestCase
{
    use DatabaseMigrations;

    public function testLogin()
    {
        $this->browse(function (Browser $browser) {

            $user = Factory(User::class)->create();

            $str_id = $user->str_id;
            $password = config('app.guest_password');

            $browser->visit('/login')
                    ->waitFor('#user-id')
                    ->type('user-id', $str_id)
                    ->type('password', $password)
                    ->press('Login')
                    ->waitFor('#message');
        });
    }
}

Setting file
.env
web (APP_URL) is container name of nginx
APP_URL=http://web

SESSION_DOMAIN=localhost
SANCTUM_STATEFUL_DOMAINS=localhost:8000

DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=****_test
DB_USERNAME=****_test
DB_PASSWORD=*********

BROADCAST_DRIVER=log
CACHE_DRIVER=file
QUEUE_CONNECTION=sync
SESSION_DRIVER=file
SESSION_LIFETIME=120

phpunit.dusk.xml
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="false"
         backupStaticAttributes="false"
         bootstrap="vendor/autoload.php"
         colors="true"
         convertErrorsToExceptions="true"
         convertNoticesToExceptions="true"
         convertWarningsToExceptions="true"
         processIsolation="false"
         stopOnFailure="false">
    <testsuites>
        <testsuite name="Browser Test Suite">
            <directory suffix="Test.php">./tests/Browser</directory>
        </testsuite>
    </testsuites>
    <php>
        <server name="SESSION_DRIVER" value="file"/>
    </php>
</phpunit>

DuskTestCase.php
<?php

namespace Tests;

use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;
use Laravel\Dusk\TestCase as BaseTestCase;

abstract class DuskTestCase extends BaseTestCase
{
    use CreatesApplication;

    public static function prepare()
    {
        // static::startChromeDriver();
    }

    protected function driver()
    {
        $options = (new ChromeOptions())->addArguments([
            '--disable-gpu',
            '--headless',
            '--window-size=1920,1080',
            '--no-sandbox',
            '--enable-file-cookies',
        ]);

        // I use Docker, container name is chrome.
        return RemoteWebDriver::create(
            'http://chrome:4444',
            DesiredCapabilities::chrome()->setCapability(
                ChromeOptions::CAPABILITY,
                $options
            )
        );
    }
}

A: Try set session driver to file
I have file phpunit.dusk.xml in the root of my app and in php section
<server name="SESSION_DRIVER" value="file"/>

Try in DuskTestCase class in method driver() set option '--enable-file-cookies'
$options = (new ChromeOptions())->addArguments([
        '--disable-gpu',
        '--headless',
        '--window-size=1920,1080',
        '--ignore-certificate-errors',
        '--no-sandbox',
        '--enable-file-cookies',
    ]);


text:
Q: Getting the logged in user in Powershell I have written this Powershell script to get Active Logged in Users.
It works perfectly in exe file (C#), when I run the same from Powershell, I am getting Arithmetic operation resulted in an overflow.
Couldn't find the issue. What's the issue?
function IsUserCurrentlyLoggedIn($UserDomain, $UserName)
{
    Add-Type -Language CSharp -TypeDefinition @'
using System;
using System.Runtime.InteropServices;

namespace Test
{
    public static class EnumerateUsers
    {
        [DllImport("wtsapi32.dll")]
        static extern IntPtr WTSOpenServer([MarshalAs(UnmanagedType.LPStr)] String pServerName);

        [DllImport("wtsapi32.dll")]
        static extern void WTSCloseServer(IntPtr hServer);

        [DllImport("wtsapi32.dll")]
        static extern Int32 WTSEnumerateSessions(
            IntPtr hServer,
            [MarshalAs(UnmanagedType.U4)] Int32 Reserved,
            [MarshalAs(UnmanagedType.U4)] Int32 Version,
            ref IntPtr ppSessionInfo,
            [MarshalAs(UnmanagedType.U4)] ref Int32 pCount);

        [DllImport("wtsapi32.dll")]
        static extern void WTSFreeMemory(IntPtr pMemory);

        [DllImport("Wtsapi32.dll")]
        static extern bool WTSQuerySessionInformation(
            System.IntPtr hServer, int sessionId, WTS_INFO_CLASS wtsInfoClass, out System.IntPtr ppBuffer, out uint pBytesReturned);

        [StructLayout(LayoutKind.Sequential)]
        private struct WTS_SESSION_INFO
        {
            public Int32 SessionID;

            [MarshalAs(UnmanagedType.LPStr)]
            public String pWinStationName;

            public WTS_CONNECTSTATE_CLASS State;
        }

        public enum WTS_INFO_CLASS
        {
            WTSInitialProgram,
            WTSApplicationName,
            WTSWorkingDirectory,
            WTSOEMId,
            WTSSessionId,
            WTSUserName,
            WTSWinStationName,
            WTSDomainName,
            WTSConnectState,
            WTSClientBuildNumber,
            WTSClientName,
            WTSClientDirectory,
            WTSClientProductId,
            WTSClientHardwareId,
            WTSClientAddress,
            WTSClientDisplay,
            WTSClientProtocolType
        }
        public enum WTS_CONNECTSTATE_CLASS
        {
            WTSActive,
            WTSConnected,
            WTSConnectQuery,
            WTSShadow,
            WTSDisconnected,
            WTSIdle,
            WTSListen,
            WTSReset,
            WTSDown,
            WTSInit
        }

        public static IntPtr OpenServer(String Name)
        {
            IntPtr server = WTSOpenServer(Name);
            return server;
        }
        public static void CloseServer(IntPtr ServerHandle)
        {
            WTSCloseServer(ServerHandle);
        }
        public static bool IsActiveSessionExists(string UserDomain, string Username)
        {
            IntPtr serverHandle = IntPtr.Zero;
            serverHandle = OpenServer(Environment.MachineName);
            IntPtr SessionInfoPtr = IntPtr.Zero;

            try
            {
                IntPtr userPtr = IntPtr.Zero;
                IntPtr domainPtr = IntPtr.Zero;
                Int32 sessionCount = 0;
                Int32 retVal = WTSEnumerateSessions(serverHandle, 0, 1, ref SessionInfoPtr, ref sessionCount);
                Int32 dataSize = Marshal.SizeOf(typeof(WTS_SESSION_INFO));
                Int32 currentSession = (int)SessionInfoPtr;
                uint bytes = 0;

                if (retVal != 0)
                {
                    for (int i = 0; i < sessionCount; i++)
                    {
                        WTS_SESSION_INFO si = (WTS_SESSION_INFO)Marshal.PtrToStructure((System.IntPtr)currentSession, typeof(WTS_SESSION_INFO));
                        currentSession += dataSize;

                        WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSUserName, out userPtr, out bytes);
                        WTSQuerySessionInformation(serverHandle, si.SessionID, WTS_INFO_CLASS.WTSDomainName, out domainPtr, out bytes);

                        var domain = Marshal.PtrToStringAnsi(domainPtr);
                        var username = Marshal.PtrToStringAnsi(userPtr);

                        if (UserDomain.Equals(domain, StringComparison.OrdinalIgnoreCase) &&
                            Username.Equals(username, StringComparison.OrdinalIgnoreCase) &&
                            si.State == WTS_CONNECTSTATE_CLASS.WTSActive)
                        {
                            WTSFreeMemory(userPtr);
                            WTSFreeMemory(domainPtr);
                            return true;
                        }
                        WTSFreeMemory(userPtr);
                        WTSFreeMemory(domainPtr);
                    }
                }
            }
            finally
            {
                WTSFreeMemory(SessionInfoPtr);
                CloseServer(serverHandle);
            }
            return false;
        }
    }
}
'@
    return [Test.EnumerateUsers]::IsActiveSessionExists($UserDomain, $UserName)
}

A: I copied your C# code to a Visual Studio 2015 project and found that disabling Prefer 32-bit or changing Platform target to x64 in the Build properties of the project produces that same exception on this line:
Int32 currentSession = (int)SessionInfoPtr;

IntPtr is 32-bits in a 32-bit process and 64-bit in a 64-bit process, but this code assumes it is 32-bits by casting to int (Int32).  On 64-bit Windows the "default" version of PowerShell at $Env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell.exe is also 64-bit, which you can confirm by the fact that [IntPtr]::Size returns 8 (bytes).  Changing the code to the following eliminates the exception both in the 64-bit C# project and PowerShell:
IntPtr currentSession = SessionInfoPtr;


text:
Q: Android Emulator Keyboard not displaying Just installed the android sdk on my macbook pro. I created a virtual device, allotted 50mb worth of memory in android 3.0. I ran the emulator, and Android_ displays on the left, but the keyboard interface does not display on the right. I have hw.keyboard.lid enabled. Not sure if that has anything to do with it.

A: This is how to make emulator to show soft keyboard:
Device settings > Language and Input > Default > Hardware (Physical Keyboard) > set to Off.

A: Press CTRL+F11 or num pad 7 to enable an onscreen keyboard within the OS.  I don't think the 3.0 emulator has an equivalent keyboard interface the way the others do.

A: I just came across this problem and solved it - the default keyboard setting in the 3.0 image is set to the Japanese IME (which I'm assuming doesn't work landscape). Simply go into the settings and change it to the Android keyboard.

A: This works for me: I enable the "Hardware Keyboard Present" in the AVD definition. When the AVD boots up, the virtual keyboard doesn't come up in the device, but the computer's keyboard works. I then go to Settings -> Language and Input -> Keyboard and input methods -> Default. Here, I switch off the Hardware (Physical Keyboard) option. Now, both the virtual keyboard as well as the computer keyboard works -- best of both worlds.
But, as user850688 said, you have to do this everytime you boot up the AVD. If you don't want to do that, switch off the Hardware Keyboard Present setting in the AVD and you will always have the virtual keyboard, but you cannot use the computer keyboard at all.

A: yes, ctrl+f11 and num-7 bring up the soft keyboard. useful, but not as convenient for testing as the old side/emulator keyboard.
In the Android 3.0 SDK using v11 or higher a side-keyboard is apparently no longer available by default, presumably to better emulate that the devices are all touch-screens. An AVD based on the default WVGA800 tablet skin and any AVD based on a custom screen size will not have a side emulator keyboard for you to use, and I couldn't find which setting might turn it on. However...
I was able to get a side-keyboard (very very handy for dev+testing) by downloading some older skins from http://teavuihuang.com/android/ and creating AVDs based on these. Somehow this enables the emulator keyboard, through some file or setting which the AVD editor doesn't make available. The window sizes and emulator keyboard placement don't exactly line up, but it beats the heck out of nothing.
Seems like Google should have documented all of these intricacies at http://developer.android.com/guide/developing/devices/emulator.html, but they haven't.

A: Just change AVD Device Features. You selected a specific Resolution eg. 240 X 360. Choose QVGA instead. Keyboard appears.

A: On the newer Android versions, you won't find it the AVD settings, you simply need to load the emulator normally and go to the Settings app, there you can choose to NOT use the hardware keyboard of your computer.

A: You can also issue a command from the keyboard.
http://developer.android.com/guide/developing/tools/emulator.html
e.g.
Android  ==   PC Keyboard
Back Key == ESC
Menu     == Page-up
++++++++++++++++++++++++++++
the link is not there any more. there are more other descriptive answers here
Android emulator doesn't take keyboard input - SDK tools rev 20

A: Yes,If you enter manual resolution in AVD it will not show keyboard just select any default resolution keyboard will start showing up

A: I don't know if this will be helpful, but in Android 4.0, even if you have the hardware keyboard emulation enabled, you can pull down the system menu at the top of the screen, and it should give you to option to turn the hardware keyboard off, enabling the virtual keyboard again. Curiously, I found that hardware keyboard emulation still works - best of both worlds!

A: you may try do this :
change default skin to with dynamic hardware controls  when you edit emulates
hopes to help you


text:
Q: SharePoint Internal Field Name I am using SPServices to update a field, however it is not updating and causing no ends of frustration.
I have been able to update other fields using this code so I can only come to the conclusion that the internal field name is incorrect.
$().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "Update",
listName: "Staff Rewards",
ID: $(this).attr("ows_ID"),
valuepairs: [["Processed%5Fx0020%5FDate", "Processed"]],
completefunc: function (xData, Status) {

}

});

The field name in InfoPath 2010 is "Processed Date", however once promoted the field name has become "Processed_x0020_Date" in SharePoint using the view URL and in the Column Settings URL the field name is: Processed%5Fx0020%5FDate
I have tried all of these field names and still can't get the list to update!

A: Using the syntax with valuepairs, an array of column StaticNames and values have to be specified:
$().SPServices({
operation: "UpdateListItems",
async: false,
batchCmd: "Update",
listName: "Staff Rewards",
ID: $(this).attr("ows_ID"),
valuepairs: [["Processed_x0020_Date", "Processed"]],
   completefunc: function (xData, Status) {

   }
});

In addition, make sure that the proper List Item Id is passed for an Update operation:
$(this).attr("ows_ID")

A: OK, finally figured it out !!, had to use "Inspect Element" to check what SharePoint thinks as the Internal Name of my field and would you believe it... it seems for some reason, for longer names SharePoint just terminates them after what looks like 32 characters....my field name (Internal Name) shown in one of the comments in the final HTML (saw using "Inspect Element") was "Previous_x0020_Request_x0020_Sta"  where the Display name I have is "Previous Request Status"
this is weird, how would someone know this :-(  Oh SharePoint!!
I might be wrong in my conclusion of internal names being terminated after 32 characters, but my code now WORKS!! using that truncated name....so may be its something in SpServices if not SharePoint.... but to the best of my knowledge ....this seems like a SharePoint problem...thats what it looks like for now.


text:
Q: From command prompt store a "!" from a file name in a varible I have a set of files in a folder with names like test! - 01.avi. I want to make a new folder for each file with the same name and then move the file into that folder. I have everything but how to pull in the "!" and copy the file to the folder.
@ECHO OFF
setlocal enabledelayedexpansion
set "sourcedir=Z:\test"
set folder=null
set file=null
PUSHD %sourcedir%
FOR /f "tokens=* delims=?" %%a in ( 'dir /b /a-d "*[720p].*"'
 ) DO (
  SET file=%%a
  FOR /f "tokens=1,2,* delims=]-" %%b in ("%%a" "[*] * - * [720p].*"
   ) DO (
   FOR /f "tokens=* delims= " %%e in ("%%c"
    ) DO (
     SET folder=%%e
     FOR /l %%f in (1,1,31) do if "!folder:~-1!"==" " set folder=!folder:~0,-1!
     MD "!folder!"
     MOVE "!file!" .\"!folder!"\
     )
    )
 )
POPD
GOTO :EOF

Thanks for taking a look

A: Better to cope with file names keeping delayed expansion disabled. Treat variables assigned within a (code block) in a subroutine as follows:
@ECHO OFF
SETLOCAL EnableExtensions DisableDelayedExpansion

set "sourcedir=D:\bat\Unusual Names"
PUSHD %sourcedir%

dir /b /a-d "*!a*.*"

FOR /f "tokens=* delims=?" %%a in ( 'dir /b /a-d "*!a*.*"') DO (

  SET "file=%%~nxa"

  rem observe instructions "make a new folder for each file with the same name"
  rem suppose that without extension
  SET "folder=%%~dpna"

  call :DoDelayedExpansion
)
POPD

ENDLOCAL
goto :eof

:DoDelayedExpansion
  echo(
  echo MD "%folder%\" 2>NUL
  echo MOVE "%file%" "%folder%\"
goto :eof

Next script gives an example only using my existing test data set. Note:

*

*use set "variable=value" syntax with double quotes to escape some characters of a special meaning in batch scripting, e.g. |, &, <, > etc., and to ensure there are no (accidentally forgotten) trailing white spaces;

*both MD and MOVE commands are merely echoed for debugging purposes; remove all echo no sooner than debugged.

Output:
==>D:\bat\SF\694616.bat
01exclam!ation.txt
02exc!lam!ation.txt

MD "D:\bat\Unusual Names\01exclam!ation\"
MOVE "01exclam!ation.txt" "D:\bat\Unusual Names\01exclam!ation\"

MD "D:\bat\Unusual Names\02exc!lam!ation\"
MOVE "02exc!lam!ation.txt" "D:\bat\Unusual Names\02exc!lam!ation\"

==>

Resources (required reading):

*

*(command reference) An A-Z Index of the Windows CMD command line

*(additional particularities) Windows CMD Shell Command Line Syntax

*(%~a etc. special page) Command Line arguments (Parameters)

*(special page) EnableDelayedExpansion


text:
Q: Change connection string dynamically from C# I would like to know how can I change the connection string dynamically from C# in run time.
I have 3 connection string in the App.config, I would like to know how can I change one of the connections dynamically.
P.S
I use Ado.NET , Entity Framework.

A: Every time you want to change the connection string just you change the main connection string in App.Config file.
Reference


text:
Q: Unity Engine: 2D Rigid body is falling slowly after adding movement? I was attempting to put simple movement into a project and for some reason this has caused the object its applied to to fall extremely slow. I am using the newer input system and I haven't really been using it previously so I'm unsure if it's an error regarding that.
The movement is working as intended so far. Gravity is at default in settings.

public class Movement : MonoBehaviour
{
    public Rigidbody2D rb;

    public float moveSpeed = 4f;
    public InputAction playerControl;

    Vector2 moveDirection = Vector2.zero;

    private void OnEnable()
    {
        playerControl.Enable();
    }
    private void OnDisable()
    {
        playerControl.Disable();
    }

    // Update is called once per frame
    void Update()
    {

        moveDirection = playerControl.ReadValue<Vector2>();
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
    }
}

This is what I have applied to the player object so far. When actually moving there is no issue, but falling doesn't work as intended

A: In FixedUpdate, you set the velocity of the RigidBody, including the y component. This does not interact well with gravity.
Gravity decreases the vertical speed of the RigidBody2D to make the object fall. Meanwhile, your code erases these changes each frame, which means that it cannot accelerate downwards, leading to it falling very slowly and at a constant speed (rather than accelerating downwards as expected).
If you have complete control over your vertical movement, how would gravity work? If the player is not meant to be able to control their vertical movement, change the line to:
rb.velocity = new Vector2(moveDirection.x * moveSpeed, rb.velocity.y);
This will fix the issue but will remove your vertical control. Is this what you want?
If you want to keep vertical movement but not overwrite gravity, you have to make some kind of compromise. If you want gravity to act whenever you are not controlling your character's vertical movement, you can do something like this:
if (moveDirection.y > 0.001)
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
}
else
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, rb.velocity.y);
}

You can also add the vertical movement to your vertical speed. This will mean that the player does not have complete control over their vertical speed like their horizontal speed, but rather being able to apply a force against it.
rb.velocity = new Vector2(moveDirection.x * moveSpeed, rb.y + moveDirection.y * verticalMoveSpeed);


text:
Q: Is it possible to create anti-muons in a particle accelerator? I love particle and nuclear physics and I'm starting to search some things about it even. So, my doubt is: is it possible to create antimuons (positive charged muons) in a particle accelerator, but without colliding two beams? I mean, only colliding a beam against objects or with the help of machines like Cherenkov detectors or Muon filters.

A: Yes.  In fact, the first process you generally learn about in quantum field theory is the annhilation of an electron/positron pair to produce a muon/antimuon pair.

A:
is it possible to create antimuons (positive charged muons) in a particle accelerator, but without colliding two beams? I mean, only colliding a beam against objects

Yes, these are the fixed target experiments, various beams interacting with nuclei in the targets.
In this bubble chamber picture the target is the protons in the nucleus of the hydrogen atoms:

This picture comes from an experiment at CERN in which a beam of 8.2 GeV/c K- particles is fired into the 2 metre hydrogen-filled bubble chamber.
The main interaction produces 4 charged particles and a neutral particle that decays a little way downstream into two charged charged particles (with a characteristc `vee' shape).
This event is rich in the number of different particles that can be identified from a `reading' of the tracks: electron, positron, pi+, pi-, K0, , K-, mu +, mu-; for details.
In addition, one can infer the existence of various neutrinos in the decay of the pi+ (muon neutrino) and the mu+ (electron neutrino and antimuon neutrino).

The muons, + and - come from decays.

or with the help of machines like Cherenkov detectors or Muon filters.

There is some confusion here, detectors detect particles, they do not produce them. In the picture above the detector is the camera taking the picture, plus the volume of hydrogen where the particles leave a track. The production happens at the vertices. In particular the muon producing  vertices is where the green tracks begin, the decay of the Kaon and pion.
The site may interest you.


text:
Q: Export extension list for Visual Studio Code on WSL I am on Windows 10 with WSL2 (Windows Subsystem für Linux) activated (Alpine and Ubuntu as distro), I use Remote-WSL inside VScode. On my "normal" VScode I can do code --list-extensions to get all my extensions.
How can I do it on a WSL-Remote Terminal (zsh, bash)?

A: VS Code communicates to WSL2 via a server component installed on the Linux machine, which apparently as of now doesn't support the --list-extensions flag.
The following output difference between the same command, code --list-extensions typed in Windows and WSL shows it
On WSL
code 1.49.0

Usage: code [options][paths...]

To read from stdin, append '-' (e.g. 'ps aux | grep code | code -')

Options
  -d --diff <file> <file>           Compare two files with each other.
  -a --add <folder>                 Add folder(s) to the last active window.
  -g --goto <file:line[:character]> Open a file at the path on the specified line and
character position.
  -n --new-window                   Force to open a new window.
  -r --reuse-window                 Force to open a file or folder in an already
opened window.
  --folder-uri <uri>                Opens a window with given folder uri(s)
  --file-uri <uri>                  Opens a window with given file uri(s)
  -w --wait                         Wait for the files to be closed before returning.
  --locale <locale>                 The locale to use (e.g. en-US or zh-TW).
  -h --help                         Print usage.

Extensions Management
  --enable-proposed-api <extension-id> Enables proposed API features for extensions.
Can receive one or more extension
                                       IDs to enable individually.

Troubleshooting
  -v --version                       Print version.
  --verbose                          Print verbose output (implies --wait).
  --log <level>                      Log level to use. Default is 'info'. Allowed
values are 'critical', 'error',
                                     'warn', 'info', 'debug', 'trace', 'off'.
  -s --status                        Print process usage and diagnostics information.
  --prof-startup                     Run CPU profiler during startup
  --disable-extensions               Disable all installed extensions.
  --disable-extension <extension-id> Disable an extension.
  --sync <on> <off>                  Turn sync on or off
  --inspect-extensions <port>        Allow debugging and profiling of extensions.
Check the developer tools for the
                                     connection URI.
  --inspect-brk-extensions <port>    Allow debugging and profiling of extensions with
the extension host being paused
                                     after start. Check the developer tools for the
connection URI.
  --disable-gpu                      Disable GPU hardware acceleration.
  --max-memory                       Max memory size for a window (in Mbytes).

On Windows
Visual Studio Code 1.49.0

Usage: code.exe [options][paths...]

To read output from another program, append '-' (e.g. 'echo Hello World | code.exe -')

Options
  -d --diff <file> <file>           Compare two files with each other.
  -a --add <folder>                 Add folder(s) to the last active window.
  -g --goto <file:line[:character]> Open a file at the path on the specified
                                    line and character position.
  -n --new-window                   Force to open a new window.
  -r --reuse-window                 Force to open a file or folder in an
                                    already opened window.
  --folder-uri <uri>                Opens a window with given folder uri(s)
  --file-uri <uri>                  Opens a window with given file uri(s)
  -w --wait                         Wait for the files to be closed before
                                    returning.
  --locale <locale>                 The locale to use (e.g. en-US or zh-TW).
  --user-data-dir <dir>             Specifies the directory that user data is
                                    kept in. Can be used to open multiple
                                    distinct instances of Code.
  -h --help                         Print usage.

Extensions Management
  --extensions-dir <dir>
      Set the root path for extensions.
  --list-extensions
      List the installed extensions.
  --show-versions
      Show versions of installed extensions, when using --list-extension.
  --category
      Filters installed extensions by provided category, when using --list-extension.
  --install-extension <extension-id[@version] | path-to-vsix>
      Installs or updates the extension. Use `--force` argument to avoid prompts. The identifier of an extension is always `${publisher}.${name}`. To install a specific version provide `@${version}`. For example: 'vscode.csharp@1.2.3'.
  --uninstall-extension <extension-id>
      Uninstalls an extension.
  --enable-proposed-api <extension-id>
      Enables proposed API features for extensions. Can receive one or more extension IDs to enable individually.

Troubleshooting
  -v --version                       Print version.
  --verbose                          Print verbose output (implies --wait).
  --log <level>                      Log level to use. Default is 'info'.
                                     Allowed values are 'critical', 'error',
                                     'warn', 'info', 'debug', 'trace', 'off'.
  -s --status                        Print process usage and diagnostics
                                     information.
  --prof-startup                     Run CPU profiler during startup
  --disable-extensions               Disable all installed extensions.
  --disable-extension <extension-id> Disable an extension.
  --sync <on> <off>                  Turn sync on or off
  --inspect-extensions <port>        Allow debugging and profiling of
                                     extensions. Check the developer tools for
                                     the connection URI.
  --inspect-brk-extensions <port>    Allow debugging and profiling of
                                     extensions with the extension host being
                                     paused after start. Check the developer
                                     tools for the connection URI.
  --disable-gpu                      Disable GPU hardware acceleration.
  --max-memory                       Max memory size for a window (in Mbytes).
  --telemetry                        Shows all telemetry events which VS code
                                     collects.

Note the Extension Management section of the output

A: As pointed out by @dopewind, vscode in WSL doesn't support --list-extensions flag.
You can get the list by inspecting the vscode UI html:
Open vscode in WSL, go to Help>Toggle Developer Tools.
Select Extensions, and filter them by Installed.
Select the Extensions div in Developer Tools, then go to Console to print the list with:
$0.innerText

A: Did you ever tried extensions.json?
When I switch between WSL and Windows to manage extension between platform, I use extensions.json approach.
More details, Click Here
You should be creating extensions.json within the .vscode folder.
I am not sure if my solution helped the question, but it provides different perspective of managing extensions easily across the team.


text:
Q: How to upload file using axios to database? I don't know how to send/upload file to database using axios while not using vue and react.
<script>
                        var submit1 = document.getElementById("submit");
                        submit1.addEventListener("click", function(e){
                            e.preventDefault();
                            var email1 = document.getElementById("email").value;
                            var f2 = document.getElementById("file").value;
                            var url = "apply2.php";
                            var data = {usEmail:email1,usF2:f2};
                            axios.post(url,data)

                            .then(function(res){
                                alert(res.data)

                            })
                            .catch(function(error){
                                alert("erre");
                            })
                        });
                    </script>

And this is apply2.php where

$_POST = json_decode(file_get_contents('php://input'),true);

$e = mysqli_real_escape_string($conn, $_POST['usEmail']);

$filet1 = rand(1000, 10000) . "-" . $_FILES["usF2"]["name"];
    $tname1 = $_FILES["usF2"]["tmp_name"];
    $uploads_dir1 = '../files';
    move_uploaded_file($tname1, $uploads_dir1 . '/' . $filet1);

$sql = "INSERT into applyey(email,file)
    VALUES('$e','$filet1')";

I don't know why it won't work with file but works with email.

A: You need to add data to formdata object and content-type as multipart
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("usF2", imagefile.files[0]);
var email1 = document.getElementById("email").value;
formData.append("usEmail", email1);
var url = "apply2.php";
axios.post('url', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})


text:
Q: Can't get data from a composable using destructuring in Vue 3 I'm trying to get books data from firebase in the Vue component (Book.vue). It works fine when I write a the function inside the component.
But it doesn't work when I try to convert it into a composable.
Althought the console isn't showing any error, but still the page isn't displaying any data.

This code works (when showBooks is used as a function)

Book.vue
<template>

     favorite

{{ book.title }}

       done
       edit
       delete

</template>

This doesn't work. (when showBooks is used inside a composable)

getBooks.js (composable)
import { ref } from "@vue/reactivity";
import { collection, getDocs } from "firebase/firestore";
import { db } from "../firebase/config";

async function showBooks() {
    const books = ref([]);
    const colRef = collection(db, "books");

    const docs = await getDocs(colRef);
    docs.forEach((doc) => {
        const book = { ...doc.data(), id: doc.id };
        books.value.push(book);
    });

    return { books }
}

export { showBooks }

Books.vue
<template>

     favorite

{{ book.title }}

       done
       edit
       delete

</template>

A: You've got a couple things going wrong here, but you're close.

*

*In the Book.vue that's working you define books like so const books = ref([]);. That's great continue to do that instead of defining it like this const { books } = showBooks();. This latter way you're not using ref so your template won't be reactive with books and you're not awaiting the result.

*Then update your mounted hook to await the promise and assign the value to your books ref. onMounted(async () => { let data = await showBooks(); books.value = data.books; });


text:
Q: Where does "Uniform" in "Uniform central limit theorem" come from? We may all know about the CLT. Today I have seen two articles where the use a new term (to me), that is "Uniform central limit theorem".

*

*A uniform central limit theorem and efficiency for deconvolution estimators

*Empirical Processes in M-Estimation
My question is that where the word "uniform" come from? Does it come from "uniform Donsker class"?

A: Uniform Central Limit theorems relate to functional extensions of the classic central limit theorem (extending from application to single valued random variables to random functions). They are about the convergence of random functions. For instance think about a the Wiener process as a limit of a random walk. With a random walk we do not deal with the convergence of a single random value, but with the convergence of an entire function (the entire walk).
Uniform relates to uniform convergence.
See also

*

*The Glivenko Cantelli theorem, which is about a uniform law of large numbers (more specifically the case of convergence of the empirical distribution to the true distribution function). The theorem proves that this convergence is not just pointwise, but also uniform.

*Donsker's theorem, which states that a scaled random walk converges uniformly in distribution to a normal distribution.

*There is a whole book written about this topic.
Dudley, Richard M. Uniform central limit theorems. Vol. 142. Cambridge university press, 2014.


text:
Q: How to obtain standardized regression coefficients for bootstrapped models or models with robust SE in R In R, when we fit a regression model, standardized coefficients are unfortunately not readily available. Luckily, there is a package lm.beta that extracts them. For example:
fit.model1.lm <- lm(Sepal.Length ~ Sepal.Width + Petal.Width, iris)
lm.beta(fit.model1.lm)

However, if we use bootstrapping (e.g. from the package simpleboot):
fit.model1.boot <- lm.boot(fit.model1.lm)

Or if we use robust standard errors (e.g. from the sandwich package):
coeftest(fit.model1.lm, vcov = vcovHC(fit.model1.lm))

It's impossible to obtain standardized coefficients via lm.beta since they only work on objects of class lm.
How to obtain them in that case then?

A: To get standardized coefficients we also may scale our variables before estimation:
library("lm.beta")
fit.model1.lm <- lm(Sepal.Length ~ Sepal.Width + Petal.Width, iris)
lm.beta(fit.model1.lm)
# Call:
#   lm(formula = Sepal.Length ~ Sepal.Width + Petal.Width, data = iris)
#
# Standardized Coefficients::
# (Intercept) Sepal.Width Petal.Width
#   0.0000000   0.2100575   0.8948486
(fit.model1.lm.st <- lm(Sepal.Length ~ Sepal.Width + Petal.Width,
                        cbind(lapply(iris[-5], scale), iris[5])))
# Call:
#   lm(formula = Sepal.Length ~ Sepal.Width + Petal.Width, data = cbind(lapply(iris[-5],
#                                                                              scale), iris[5]))
#
# Coefficients:
# (Intercept)  Sepal.Width  Petal.Width
#  -1.422e-15    2.101e-01    8.948e-01

So using the scaled lm fit (here fit.model1.lm.st) in lm.boot will give you the desired standardized bootstrap coefficients.
library("simpleboot")
set.seed(42)  # for sake of reproducibility
(fit.model1.boot <- lm.boot(fit.model1.lm.st, R=200))
# BOOTSTRAP OF LINEAR MODEL  (method = rows)
#
# Original Model Fit
# ------------------
# Call:
# lm(formula = Sepal.Length ~ Sepal.Width + Petal.Width, data = cbind(lapply(iris[-5],
#                                                                              scale), iris[5]))
#
# Coefficients:
# (Intercept)  Sepal.Width  Petal.Width
#  -1.422e-15    2.101e-01    8.948e-01

library(lmtest)
library(sandwich)
coeftest(fit.model1.lm.st, vcov=vcovHC(fit.model1.lm.st))
# t test of coefficients:
#
#                Estimate  Std. Error t value  Pr(>|t|)
# (Intercept) -1.4222e-15  4.4920e-02  0.0000         1
# Sepal.Width  2.1006e-01  4.7055e-02  4.4641 1.591e-05 ***
# Petal.Width  8.9485e-01  5.2321e-02 17.1031 < 2.2e-16 ***
# ---
# Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


text:
Q: WCF security negotiation exception We are using below mentioned security configuration for our services
Configuration:
<security mode="Message">
    <transport clientCredentialType="Windows" proxyCredentialType="None" realm="" />
    <message clientCredentialType="Windows" negotiateServiceCredential="true" algorithmSuite="Default" establishSecurityContext="true" />
</security>

In our local network while accessing services we getting below exception from some of the clients:
System.ServiceModel.Security.SecurityNegotiationException: The caller was not authenticated by the service. ---> System.
ServiceModel.FaultException: The request for security token could not be satisfied because authentication failed.
   at System.ServiceModel.Security.SecurityUtils.ThrowIfNegotiationFault(Message message, EndpointAddress target)
   at System.ServiceModel.Security.SspiNegotiationTokenProvider.GetNextOutgoingMessageBody(Message incomingMessage, Sspi
NegotiationTokenProviderState sspiState)

I have collected the WCF traces, but it is not helpful. I am guessing that windows kerberos is not able to authenticate windows identity. I have verified that client machine/logged in user details are available in ADS and both server and clients are in same domain.
Please let me know if you have any solutions for this problem.
Many thanks in advance for your help.

A: It might be time skew. Try to see if the affected clients clock is different.
Otherwise. If you can attach Visual Studio debugger to the client code, and disable "just my code", you can break on the internal exceptions in WCF. By default WCF hides all internal exceptions.


text:
Q: Adding noindex header to php redirect file I have a simple php redirect script (link.php) that I use to keep track of our affiliate links. (Example: http://www.example.net/link.php?id=1 will bring you to http://www.product1url.com)
I've noticed that Google is indexing http://www.example.net/link.php?id=1. I have link.php set to noindex in Robots.txt but that's not stopping the indexing. So I want to add a "noindex", "nofollow" header to each URL itself.
Here's the script I have:
<?php

    $path = array(

    '1' => 'http://www.producturl1.com',
    '2' => 'http://www.producturl2.com',
    );

    if (array_key_exists($_GET['id'], $path))
     header('Location: ' . $path[$_GET['id']]);

 ?>

How do I modify this to include: "X-Robots-Tag: noindex, nofollow"? Is this possible?

A: You can output as many headers as you want as long as they are in the code before any potential output is generated. Generally the redirect should be last, though.
Simply add your header("X-Robots-Tag: noindex, nofollow", true); before the $path = array( line.
Also, I know this wasn't in the question, but you will want to update your sitemap.xml file for the index.php URI set to today's date. This will often lead to faster deindexing. (see: https://www.reddit.com/r/bigseo/comments/5nbh3n/google_ignoring_my_noindex_tags/ the post from johnmu, who is (was?) a Google employee.)


text:
Q: Checkmarks not working in a tableview In my iOS app, I have a tableView and when you click on the cell, a checkmark shows up. When you click on the cell again though, the checkmark doesn't do away. I have checked my code over and over again. These are the two methods that have to do with UITableViewAccessoryCheckmark:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

PFUser *user = [self.allUsers objectAtIndex:indexPath.row];
cell.textLabel.text = user.username;

if ([self isFriend:user]) {
    cell.accessoryType = UITableViewCellAccessoryNone;
}
else {
    cell.accessoryType = UITableViewCellAccessoryNone;
}

return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[self.tableView deselectRowAtIndexPath:indexPath animated:NO];

UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];

PFRelation *friendsRelation = [self.currentUser relationforKey:@"friendsRelation"];
PFUser *user = [self.allUsers objectAtIndex:indexPath.row];

if ([self isFriend:user]) {
    cell.accessoryType = UITableViewCellAccessoryNone;

    for(PFUser *friend in self.friends) {
        if ([friend.objectId isEqualToString:user.objectId]) {
            [self.friends removeObject:friend];
            break;
        }
    }

    [friendsRelation removeObject:user];
}
else {
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    [self.friends addObject:user];
    [friendsRelation addObject:user];
}

[self.currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
    if (error) {
        NSLog(@"Error: %@ %@", error, [error userInfo]);
    }
}];
}

Can someone please post the correct code? Thank you!

A: Try setting the accessory view property on UITableViewCell to nil.
cell.accessoryView = nil;


text:
Q: mvc entity framework : login using a database I have created a database in Microsoft sql server express. I need to be able to login on Mvc 2 app, using my database ( not the one existing on AcountController meaning MembershipService )
I just need to replace MemeberAhipService with my database. How can I do that ( i'm using entity framework code first ) . I don't need to create a model in visual studio. I have the usermodel, userContext: Db . I think i need repository also. Can anyone show me an example, of tell me the steps ?

A: You can create your own MembershipService.
Example:
New MembershipService.cs (or whatever you want)

public class MembershipService
{
    public bool IsUserValid(string username, string password)
    {
         var db = new DatabaseContext();
         var user = db.GetUser(username, password);
         // Or however you want to get your data, via Context or Repository
         return (user != null);
    }
}

New FormsClass.cs

public class FormService
{
     public void SignIn(string username, List&ltstring> roles)
     {

            FormsAuthenticationTicket authTicket = new
                            FormsAuthenticationTicket(1,            // Version
                            username,                               // Username
                            DateTime.Now,                           // Creation
                            DateTime.Now.AddMinutes(30),            // Expiration
                            false,                                  // Persistent
                            string.Join(",", roles.ToArray()));     // Roles

            string encTicket = FormsAuthentication.Encrypt(authTicket);
            HttpContext.Current.Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

            GenericIdentity id = new GenericIdentity(username);
            HttpContext.Current.User = new GenericPrincipal(id, roles.ToArray());
     }
}

In Global.asax:

        protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
        {
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
            if (authCookie != null)
            {
                string encTicket = authCookie.Value;
                if (!String.IsNullOrEmpty(encTicket))
                {
                    FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(encTicket);
                    FormsIdentity id = (FormsIdentity)Context.User.Identity;
                    var roles = ticket.UserData.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

                    GenericPrincipal prin = new GenericPrincipal(id, roles);
                    HttpContext.Current.User = prin;

                }
            }

        }


text:
Q: How to change border colour of text box with rounded corners extender attached. How do you change the border colour of a text box (on focus and on blur) with an extender attached to it?
I tried some JavaScript which worked on the text box by itself, but not with rounded corners extender attached.
I don't have the JS on me right now, but if you wat the code, let me know and I'll add it.

A: I think the easiest way to do this is use jQuery to select the  element for the rounded corners then manipulate its background color.

*

*Include the jQuery script in your page

*In your onblur() and onfocus() event handlers, change the background color using the following syntax. You can use Firebug or Chrome Developer Tools to obtain the  element ID (see attached screenshot). [e.g. ctl00_SampleContent_Panel1]
$("#ctl00_SampleContent_Panel1").css('background-color', 'blue');

A: Your Question is not clear but use the below code in your stylesheet
to change the border color of textbox onfocus
input[type=text]:focus {border:#00F solid 2px}


text:
Q: WordPress get_terms not outputting URL I've got the following PHP code that I'm using to output a list of all custom taxonomy values, then group them into alphabetical order by first letter. This is working fine, except that the URL isn't being outputted. Anyone able to help?
<?php
$list = '';
$tags = get_terms( 'film-categories' );
$groups = array();
if( $tags && is_array( $tags ) ) {
    foreach( $tags as $tag ) {
        $first_letter = strtoupper( $tag->name[0] );
        $groups[ $first_letter ][] = $tag;
    }
    if( !empty( $groups ) ) {
        foreach( $groups as $letter => $tags ) {
            $list .= '

' . apply_filters( 'the_title', $letter ) . '
';
            $list .= '
';
            foreach( $tags as $tag ) {
                $url = esc_attr( get_tag_link( $tag->term_id ) );
                $name = apply_filters( 'the_title', $tag->name );
                $list .= '
' . $name . '
';
            }
            $list .= '

';
        }
    }
} else $list .= '
Sorry, but no tags were found
';

echo $list;

?>

A: I'm afraid you've confused.
According to your second line - you're fetching terms of custom tax and not tags.
$tags = get_terms( 'film-categories' );
Therefore , any function related to tags won't work correctly.
In order to get the url of the term use the get_term_link() function.
Just replace the current line with:
$url = esc_attr( get_term_link( $tag ) );

Should work.


text:
Q: Why is $c_p/c_v$ term introduced in adiabatic process? In an adiabatic process we know there is no change in enthalpy or basically enthalpy change is zero. which means any external work done the internal energy does equal opposite work so as to keep $dH=0$. which means in adiabatic process the pressure and temperature have to change. but while deriving the equation for adiabatic process why do we say that $cp=cv+R$ when this can only be true for isobaric process where pressure is constant and also we introduce the term $cp/cv$ being a constant value called adiabatic constant, my question is why do we even use cp value here while clearly in  the adiabatic process pressure is not constant.
Where am I going wrong? Am I wrong here because $cp=cv+R$ is true for all processes but I thought it is only true for isobaric process.

A: Let me try to clarify a few key points.

*

*$c_p=c_v+R$ is an equality between two state functions (the specific heat depends on the process connected to the heat transfer, but the final quantity is a function f the state). The two specific heats actually correspond to different processes (isobaric and isochoric). It is wrong to think that the equation is valid for a specific process. A more accurate description of the physics underlying the relation is that a change of entropy at constant pressure can be written as the change at constant volume plus an additional term taking care of the variation of the remaining thermodynamic variables. Notice, that, written this way, it is valid only for ideal gases.

*Enthalpy is a state function depending on entropy and pressure (for a closed system). Therefore the variation of enthalpy is zero for an adiabatic and isobaric process. The reason for the appearance of enthalpy in connection with this formula is that
$$
dH=TdS+Vdp
$$
and
$$
dU=TdS-pdV
$$
Therefore, at constant pressure, the enthalpy change is equal to $TdS=Q_{p,rev}$, while at constant volume $TdS=Q_{v,rev}$, where $Q_{p,rev}$ and $Q_{v,rev}$ are the heat exchanged in a reversible transformation at constant pressure and constant volume respectively.

A: "In an adiabatic process we know there is no change in enthalpy or basically enthalpy change is zero."
This is untrue. Adiabatic compression of a real or ideal gas will increase its enthalpy and temperature. (For an ideal gas, enthalpy is a function of temperature.)
People often think enthalpy is the stored thermal energy and only heat flow can increase thermal energy. Neither are exactly right, although the former is close to true and true for ideal. It's the second one. (Finally, theres often also the idea that $pv$ only changes from work, never heat, also untrue.)

"which means any external work done the internal energy does equal opposite work so as to keep =0".
This is untrue for a different reason. Work can be done on the substance or by it, only.
One thing that is true: at constant pressure the enthalpy change equals the energy exchanged with the environment by heat.


text:
Q: JSP website pre-database configuration I'm working on a website in JSP (in GWT really, but on the server side, it's really just JSP), and I need to configure my database.
I know HOW to code in the database connection etc, but i'm wondering how/where the database config should be saved.
To clarify my doubt, let me give an example; in PHP, a website usualy has a config.php, where the user configures the database, user, etc (or an install.php generates it).
However, since JSP is bytecode, I can't code this info into my site and have the user modify it, nor can I modify it analogously to an install.php.
How should I handle this? what's the best/most common practice ? I've found NO examples of this. Mainly, where should the config file be stored?

A: There are several possibilities to do this, what I've seen done include:

*

*Having database credentials in a special file, usually db.properties or some simple XML file that contain the required information (driver, url, username, password, any ORM parameters if needed). The properties file would be placed under WEB-INF or WEB-INF/classes; the downside of this approach is that the user would have to modify the file inside the WAR before deploying it to the application server.

*Acquire the database connection via JNDI and expect it to be provided by the application server. This seems to be the most common way of doing this; on the upside, your WAR doesn't have to be changed, however, the downside is that configuring a JNDI data source is different for every application server and may be confusing if your system administrators are not experienced with Java technology.


text:
Q: primefaces validation message not showing (composite component, primefaces and validation method ) This is peticionario, a composite component that asks you for your pin. It's not mandatory but if you fill in something it must be numeric and the app will look in the db so no other person has the same number:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:cc="http://java.sun.com/jsf/composite"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:dabit="http://java.sun.com/jsf/composite/components">

<cc:interface>
    <cc:attribute name="peticionarioB" />
</cc:interface>

<cc:implementation>

<h:form id="peticionario_form">
<p:panel id="unooo">
    <h:panelGrid columns="2" id="ohruiseñor">
    <f:facet name="header">
            <h:outputText value="Datos personales"/>
        </f:facet>

        <h:outputText value="Número de documento"/>
    <h:panelGroup>
        <h:inputText
        id="numDoc"
    validator="#{radicadoOficioBean.validarPeticionario}"
    value="#{peticionarioBean.peticionario.numDocumento}">
        <f:validateLongRange/>
    </h:inputText>
    <h:message for="peticionario_form:numDoc" style="color:red"/>
    </h:panelGroup>
    </h:panelGrid>
</p:panel>
</h:form>

This is _crear.xhtml, a page that uses peticionario component in a p:dialog
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:dabit="http://java.sun.com/jsf/composite/components">

<h:body>

<h:form id="form">
<p:panel header="Radicación de oficio" >
<p:dialog
header="Creación de peticionario"
id="peticionario_dialog"
widgetVar="peticionario_dlg">
    <dabit:peticionario peticionarioB="#{radicadoOficioBean.peticionarioBean}"/>
        <p:ajax
    event="close"
    update="form:peticionarioExistentePG"/>
</p:dialog>
</h:body>
</html>

And this is RadicadoOficioBean's validate method
public void validarPeticionario (FacesContext context, UIComponent component, Object value) {
if (value == null) {
    return;
}

Long l = new Long(value.toString());

if (DAOBase.findByUniqueLongProperty(Peticionario.class, "numDocumento", l) != null) {
    FacesMessage fm = new FacesMessage("ya existe un usuario con el numero de documento ingresado");
context.addMessage(component.getClientId(), fm);
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
System.out.println(component.getClientId());
throw new ValidatorException(fm);
}
}

The validation actually occurs :) but the message i cannot get :(

A: <h:inputText id="numDoc" ... />
<h:message for="peticionario_form:numDoc" ... />

This doesn't match. You should be using
<h:inputText id="numDoc" ... />
<h:message for="numDoc" ... />

Another possible cause, not visible in the code posted so far, is that you're sending an ajax request but not re-rendering the message component at all. You should make sure that you're re-rendering (updating) the message component or at least one of its parents on ajax request.

Unrelated to the concrete problem, the way how you prepare the validation message is clumsy. It's unnecessary to manually add the message to the context. That job is already done when the ValidatorException is caught by JSF.
FacesMessage fm = new FacesMessage("ya existe un usuario con el numero de documento ingresado");
context.addMessage(component.getClientId(), fm);
fm.setSeverity(FacesMessage.SEVERITY_ERROR);
System.out.println(component.getClientId());
throw new ValidatorException(fm);

Just the following oneliner was been sufficient:
throw new ValidatorException(new FacesMessage(
    FacesMessage.SEVERITY_ERROR, "ya existe un usuario con el numero de documento ingresado", null);


text:
Q: Is it possible to decompose the model evidence? Assume I want to apply Bayes theorem with some state variable $x$ (scalar or vector, doesn't matter) and an observation vector $\mathbf{y}=[y_1,...,y_N]^T$::
$$p(x|\mathbf{y})=\frac{p(x)p(\mathbf{y}|x)}{p(\mathbf{y})}$$
Further assume that my likelihood is composite, i.e.:
$$p(\mathbf{y}|x)=\prod_{i=1}^N p(y_i|x)$$
where the $y_i$ are independent observations. Would it be possible to also decompose the model evidence $p(\mathbf{y})$ into its components as:
$$p(x|\mathbf{y})=\frac{p(x)p(\mathbf{y}|x)}{p(y_1)p(y_2)...p(y_N)}$$
If not, why?

A: We can obtain some intuition from an example.
Let $p(y_i|x) = \textsf{N}(y_i|x,1)$, $p(x) = \textsf{N}(x|0,s^2)$, and let $N = 2$. Then
\begin{equation}
p(y) = \textsf{N}(y|0_2,\Sigma)
\end{equation}
where $y = (y_1,y_2)$, $0_2 = (0,0)$, and
\begin{equation}
\Sigma = \begin{pmatrix}
s^2 + 1 & s^2 \\
s^2 & s^2 + 1
\end{pmatrix} .
\end{equation}
The point is that variation in $x$ induces dependence among the $y_i$.
In this example, we can eliminate the variation in $x$ by letting $s$ go to zero, thereby eliminating the dependence among the $y_i$:
\begin{equation}
\lim_{s\to 0}\ \Sigma = \begin{pmatrix}
1 & 0 \\ 0 & 1
\end{pmatrix} .
\end{equation}
In the limit, $p(y) = p(y_1)\,p(y_2)$. The limiting case amounts to putting a point-mass prior on $x$.

A: You can, yes. In the more general case, if we also expand the numerator in the same way, we'd get the following:
$$p(x|\mathbf{y}) = p(x) \frac{p(y_1|x)}{p(y_1)} \frac{p(y_2|x, y_1)}{p(y_2|y_1)} \ldots \frac{p(y_N|x, y_1, \ldots, y_{N-1})}{p(y_N | y_1, \ldots, y_{N-1})},$$
where the conditioning on previous $y$ in the numerator and the denominator vanishes when the observations are independent, which is the case you're looking at.
This decomposes the likelihood/marginal ratio into a ratio for each observation, conditional on previous ones. Sticking with the general case, if we then collapse these terms one by one...
$$\begin{align*}
p(x|\mathbf{y})
&= p(x|y_1) \frac{p(y_2|x, y_1)}{p(y_2|y_1)} \ldots \frac{p(y_N|x, y_1, \ldots, y_{N-1})}{p(y_N | y_1, \ldots, y_{N-1})}\\
&= p(x|y_1, y_2) \frac{p(y_3|x, y_1, y_2)}{p(y_3|y_1, y_2)} \ldots \frac{p(y_N|x, y_1, \ldots, y_{N-1})}{p(y_N | y_1, \ldots, y_{N-1})}\ldots\\
&= p(x|y_1, y_2, \ldots, y_N),
\end{align*}$$
we can see that this is equivalent to finding the posterior conditional on $y_1$, then using this as the prior for observing $y_2$, and so on. Hence, we can decompose the model evidence as if we'd only taken one observation before each model update.


text:
Q: How do we create object literals from arrays of object in javascript? How do we create object literals from arrays of object in javascript ? , so that I can access name using a value or a number like for example I have literal object which is
#literal sample object
SAMPLE_LITERALS {
  '1': 'Sample1',
  '2': 'Sample2',
  '3': 'Sample3',
  '4': 'Sample4'
}

then I can access a value for example  SAMPLE_LITERALS[4] and the result would be Sample4.
I wanted to implement like that on my array of object sample below. Help would be appricated. Thank you.
I wanted to access the name .
#Code Query
 const team = await TeamsModel.findAll({
    where: {
      deletedAt: { [Op.eq]: null },
    },
  });

#result
[
        {
            "id": 1,
            "name": "Admin",
            "createdAt": "2019-12-10T07:01:16.000Z",
            "updatedAt": "2019-12-10T07:01:16.000Z",
            "deletedAt": null,
            "createdById": null,
            "updatedById": null,
            "createdBy": null,
            "updatedBy": null
        },
        {
            "id": 2,
            "name": "Customer Support",
            "createdAt": "2019-12-10T07:01:16.000Z",
            "updatedAt": "2019-12-10T07:01:16.000Z",
            "deletedAt": null,
            "createdById": null,
            "updatedById": null,
            "createdBy": null,
            "updatedBy": null
        },
]

A: Assuming you want to index on id, this is a pretty simple way to do that:
const teamsAsObject = {};
teams.forEach(team => {
  teamsAsObject[team.id] = team;
});


text:
Q: How to create an formdata that contains a running index in its field name? I need to create an formdata that contains a running index in its name as well as its value. My previous approach (see beyond) fails due to a syntax error. But appart from that im not sure if it is gernally possible.
  for (var i = 0; i < files.length; i++) {
    formData.append('story_media'[i]'isTitlePicture', files[i].isTitlePicture)
    formData.append('story_files'[i]'files', files[i].file)
  }

The target is to achieve a formdata strucutre like this, as that is what my backend understands.

Im happy for any clarification.

A:   for (var i = 0; i < files.length; i++) {
    formData.append(`story_media[${i}]isTitlePicture`, files[i].isTitlePicture)
    formData.append(`story_files[${i}]files`, files[i].file)
  }


text:
Q: Fuse dead after restart I rebuilt my docker with Fuse (Red Hat Fuse (7.0.0.fuse-000191-redhat-1)
) on Centos 7, and everything is broken now.  I didn't change anything.
Could a yum update cause this?
 Exception caught while executing command
org.osgi.service.resolver.ResolutionException: Unable to resolve root:
missing requirement [root] osgi.identity; osgi.identity=jline;
type=karaf.feature; version="[3.6.2,3.6.2]"; filter:="(&(osgi.identity=jline)
(type=karaf.feature)(version>=3.6.2)(version<=3.6.2))" [caused by: Unable to
resolve jline/3.6.2: missing requirement [jline/3.6.2] osgi.identity;
osgi.identity=org.jline.terminal-jansi; type=osgi.fragment; version="
[3.6.2,3.6.2]"; resolution:=mandatory [caused by: Fragment was not selected
for attachment: org.jline.terminal-jansi/3.6.2]]

I've noticed that there's now an extra shell that wasn't there before.
admin@root()> features:list | grep shell
shell                                    ? 4.2.3                       ?          ? Uninstalled ? standard-4.2.3                              ? Karaf Shell
shell-compat                             ? 4.2.3                       ?          ? Uninstalled ? standard-4.2.3                              ? Karaf Shell Compatibility
shell                                    ? 4.2.0.fuse-000237-redhat-1  ? x        ? Started     ? standard-4.2.0.fuse-000237-redhat-1         ? Karaf Shell
shell-compat                             ? 4.2.0.fuse-000237-redhat-1  ?          ? Uninstalled ? standard-4.2.0.fuse-000237-redhat-1         ? Karaf Shell Compatibility

I know if I upgrade to the latest, I'm going to have to upgrade all my services and fix all the new problems.  Supposed to go live tomorrow.  Why did I have to touch it.


text:
Q: Scheme - checking structural equivalences of lists (how to use AND) I am trying to write a program that will check the structural equivalence of some list input, whether it includes just atoms or nested sub lists.
I am having trouble with using AND, I don't even know if its possible and I cant seem to understand documentation I am looking at.
My code:
 (define (structEqual a b)
   (cond
     (((null? car a) AND (null? car b)) (structEqual (cdr a) (cdr b)))
     (((null? car a) OR (null? car b)) #f)
     (((pair? car a) AND (pair? car b))
      (if (= (length car a) (length car b))
          (structEqual (cdr a) (cdr b))
          #f))
     (((pair? car a) OR (pair? car b)) #f)
     (else (structEqual (cdr a) (cdr b)))))

The idea is (i think): (when I say both, i mean the current cdr of a or b)

*

*Check if both a and b are null, then they are structurally equal

*Check if only either a or b is null, then they are not structually equal

*Check if both of them are pairs

*If they are both pairs, then see if the length of the pair is equal, if not they are not structurally equal.

*If they are not both pairs, then if one of them is a pair and the other isnt then they are not structurally equivalent.

*If neither of them are pairs, then they both must be atoms, so they are structurally equivalent.
So as you can see I am trying to recursively do this by checking the equivalence of the car of a or b, and then either returning #f if they fail or moving on to the cdr of each if they are equivalent at each step.
Any help?

A: There is no infix operators in Scheme (or any LISP) only prefix. Every time the operator comes first. (or x (and y z q) (and y w e)) where each letter can be a complex expression. Everything that is not #f is a true value. Thus (if 4 'a 'b) evaluates to a because 4 is a true value. car needs its parentheses.
When evaluating another predicate in cond you should make use of the fact that everything up to that has been false. eg.
(define (structure-equal? a b)
  (cond
    ((null? a) (null? b))                                ; if a is null the result is if b is null
    ((not (pair? a)) (not (pair? b)))                    ; if a is not pair the result is if b is not also
    ((pair? b) (and (structure-equal? (car a) (car b))   ; if b is pair (both a and b is pair then) both
                    (structure-equal? (cdr a) (cdr b)))) ; car and cdr needs to be structurally equal
    (else #f)))                                          ; one pair the other not makes it #f

(structure-equal '(a (b (c d e) f) g . h) '(h (g (f e d) c) b . a)) ; ==> #t


text:
Q: Kibana closes HTTP connection after 120 seconds So, I have this problem with Kibana that I don't know how to solve. I'll start by describing the environment:

*

*12 Elasticsearch (version 2.1.2) nodes. Those are various AWS machines with Linux/CentOS installed, using r3/r4/i3 instance types, spread over three AZs. Each machine does have:

*

*800 GiB storage (EBS and SSD)

*30 GiB RAM

*Kibana (version 4.3.3)

*elasticsearch.requestTimeout and elasticsearch.shardTimeout are set to 1500000, i.e. 1500s, i.e. 25 minutes.

*We create 26 indices per day, keep them for 12 days, most of them have 12 shards and 1 replica.

*An AWS ELB that distributes requests (non-sticky) to all 12 nodes.

*

*The idle timeout for the ELB is at 900s, i.e. 15 minutes.

Now, when running more complicated queries Kibana, when accessed over the ELB, shows a "gateway timeout" error message after between two and three minutes. The Network console in Chrome reveals that two requests are being fired, the first to determine the indices for the requested timespan, the second for the result data. The first request takes from 20 to 50 seconds and succeeds, the second request is always finished with a 504 (gateway timeout) after exactly two minutes.
When running the query generated by Kibana directly against one of the Elasticsearch nodes, the query takes about 7 minutes and completes successfully.
When running the query without the ELB directly against one of the Kibana instances (using curl) it also fails after pretty much exactly two minutes. Using Wireshark, I can see that Kibana simply closes the HTTP connection after 120 seconds.
Where does that timeout come from? How do I get rid of it?

A: Turns out, one of the sockets used also had a timeout. This pull request contains links to commits of which parts can be used to fix Kibana 4.3.3.


text: Q: Error con ng build --prod en angular 5 Hola tengo un problema con angular 5, tengo una semana buscando respuestas a esto y me vi obligado a formular una pregunta aquí, mi problema es que cuando hago ng build --prod osea compilar el proyecto para producción me sale el error que aparece en la image pero cuando hago ng build o ng build --watch no me ningún y todo esta perfectamente tienen alguna idea de como resolver esto por favor necesito su ayuda


text:
Q: Implement Panel Color Inspector Control in Gutenberg I am trying to implement Panel Color in the Inspector Control for a custom block but can't seem to figure it out. Below is the JSX code that attempts it. It renders the block, but when it's in focus, it encounters a Minified React error #130.
const { registerBlockType, InspectorControls, PanelColor } = wp.blocks;

registerBlockType( 'test/test', {
    title: 'Test',
    icon: 'universal-access-alt',
    category: 'layout',

    edit( { attributes, className, setAttributes } ) {
        const { backgroundColor } = attributes;
        const onChangeBackgroundColor = newBackgroundColor => {
            setAttributes( { backgroundColor: newBackgroundColor } );
        };

        return (

            { !! focus && (
              <InspectorControls>
                <PanelColor
                  title={ 'Background Color' }
                  value={ backgroundColor }
                  onChange={ onChangeBackgroundColor }
                />
              </InspectorControls>
            ) }

        );
    },
    save( { attributes, className } ) {
        const { backgroundColor } = attributes;
        return (

        );
    },
} );

A: Many wp.blocks.* controls have been moved to wp.editor.* (see release notes).
Specifically wp.blocks.InspectorControls is now wp.editor.InspectorControls - you'll need to change the first line of your code.
Note: registerBlockType is still imported from wp.blocks.* iirc.
As a side note, I've also found that the focus && trick no longer required as GB automatically displays the InspectorControls when the block is focused.

A: I'm going to give you a walk through to the point, because I struggled too :)
First import the InspectorControls
const { InspectorControls } = wp.editor;

then import components such as ColorPalette
const { ColorPalette } = wp.components;

In order to save the state you have to define an attribute:
attributes: {
    // To storage background colour of the div
    background_color: {
        type: 'string',
        default: 'red', // Default value for newly added block
    },
    // To storage the complete style of the div that will be 'merged' with the selected colors
    block_style: {
        selector: 'div', // From tag a
        source: 'attribute', // binds an attribute of the tag
        attribute: 'style', // binds style of a: the dynamic colors
    }
},

Then at the edit function... Define the onChangeColorHandler and a variable to hold the changed value in the JSX, because of course you can't from the css.
In the return part return an array of two elements [] the Inspector and the rendered div in the editor
edit: function( props ) {

    var background_color = props.attributes.background_color // To bind button background color

    // Style object for the button
    // I created a style in JSX syntax to keep it here for
    // the dynamic changes
    var block_style = props.attributes.block_style // To bind the style of the button
    block_style = {
        backgroundColor: background_color,
        color: '#000',
        padding: '14px 25px',
        fontSize: '16px',
    }

    //
    // onChange event functions
    //
    function onChangeBgColor ( content ) {
        props.setAttributes({background_color: content})
    }

    // Creates a

.
    return [
        <InspectorControls>
            background color
            <ColorPalette // Element Tag for Gutenberg standard colour selector
                onChange={onChangeBgColor} // onChange event callback
            />
        </InspectorControls>
        ,

— Hello from the backend.

    ];
},

** FINALLY: ** the save method, just create variable for the style and give the rendered div the JSX style of that value.
save: function( props ) {

    var block_style = {
        backgroundColor: props.attributes.background_color
    }
    return (

— Hello from the frontend.

    );
},

here is a complete gist of the file

A: PanelColor has been deprecated, use PanelColorSettings instead:
const {
    PanelColorSettings,
    …
} = wp.editor;

…

edit: (props) => {
    …
    return (
        …
        <InspectorControls>
            <PanelColorSettings
            title={ 'Background Color' }
            colorSettings={[{
              value: backgroundColor,
              onChange: onChangeBackgroundColor,
              label: __('Background Color')
            }]}
          />
      </InspectorControls>
      …


text:
Q: How can I find the analytical solution for this optimization problem? How to find the analytical solution for this optimization problem?
$$
\begin{align}
& \underset{x,y,z}{\text{maximize}} & (1+\frac{x}{1+z})(1+\frac{y}{1+z})\\
& \text{such that} & 0\leq x\leq x^+\\
&& 0\leq y\leq y^+\\
&& 0\leq z\leq z^+\\
&& x,y,z\in\mathbb{R}\\
\end{align}
$$
where $x^+$,$x^+$ and $z^+$ are positive numbers.

A: $$(1+\frac{x}{1+z})(1+\frac{y}{1+z})\le (1 + x) (1 +y) \le (1 + x^+)(1 + y^+)$$
The function achieves the maximum at $(x^+, y^+, 0)$


text:
Q: Finding the temperature of a gas using the $P$-$V$ diagram I need to know a way to relate the P-V curve of an ideal gas to its temperature.I found a similar question on stackexchange but couldn't understand how the relationship between a point and the adiabatic curve drawn there gives us an idea about the temperature of the gas .
If you can explain it using the below graph it will be much easier.
I need to compare the temperatures at A,B,C.


text:
Q: Python program that replaces each word in a sentence with a synonym Basically what I want to do is create a program that takes in a sentence/paragraph as user input, looks up a synonym for each word, and replaces the word with the synonym. The program I've created so far to do this runs perfectly, but there are some kinks/human errors/logic errors. Here's what I've got right now:
response=input("Enter what you want to thesaurize")
orig=response #puts user input into a string
num=orig.count(" ")+1 #finds number of words in the sentence
orig=orig.split(" ") #turns the sentence into a list of its words
new=[] #creates a new list to put the new words in, in case I'd want to go back to the original sentence for any reason
for i in range (num):
        if orig[i] not in badWords: #makes sure that the word is not a no-synonym word like "the" or "be"
            new.insert(i, myFuncs.replace(orig[i])) #the replace function (which I put in a separate module for neatness purposes) looks up the word on thesaurus.com and replaces it with a synonym
        else:
            new.insert(i, orig[i]) #If the word is an excluded word, it simply leaves it alone and keeps it in the new sentence

final="" #creates an empty string to put the new words in
for j in range(0,num):
    final=final+new[j]+" "  #turns the list of new words into a string that can be printed
print(final)

Again, this runs perfectly, but there are some issues. Basically, I've reduced it to 4 basic problems that occur:
1) The word doesn't have a synonym but still wasn't in the excluded words list;
2) The wrong meaning of a word is entered in, or a meaning is returned that doesn't make sense in the context of the user's input;
3) The wrong tense of a verb is returned and
4) When a noun is entered, the verb of that word is returned, or vice versa (i.e. "I will grill the chicken" turns into "I will firepit the chicken" or something to that effect).
Basically, I can fix all of these problems manually by having the user go through each word that doesn't make sense, and then using nested if-else and other control structures to guide them through picking the right word, but I think this would be tedious for the user and would ruin the whole point, especially if they enter in something with a lot of words.
So basically I'm asking, which of these problems can I automate? That is to say, is there any way I can write code to get the computer to recognize any of these problems? Fixing them is the easy part, but actually getting the program to recognize the logic errors instead of making the user deal with it is the hard part.

A: You should look into NLP (Natural language processing), especially POS tagging (Part-of-speech tagging). POS tagging will tag each word of a text corpus according to the word-category like verb, noun etc. and the grammatical form of the word. A great Python library to look into would be NLTK, the Natural Language Toolkit.
Here is a small example from the project's website.
>>> import nltk
>>> sentence = """At eight o'clock on Thursday morning
... Arthur didn't feel very good."""
>>> tokens = nltk.word_tokenize(sentence)
>>> tokens
['At', 'eight', "o'clock", 'on', 'Thursday', 'morning',
'Arthur', 'did', "n't", 'feel', 'very', 'good', '.']
>>> tagged = nltk.pos_tag(tokens)
>>> tagged[0:6]
[('At', 'IN'), ('eight', 'CD'), ("o'clock", 'JJ'), ('on', 'IN'),
('Thursday', 'NNP'), ('morning', 'NN')]

After tagging your sentence extract only word-categories you want to lookup synonyms for, normalize the words to present tense, do the synonym lookup and transform the result back to the correct tense and replace the desired word.
Resolving the tense of a word can also be achieved through NLP mechanisms as well as transforming words from normal form to a specific tense.


text:
Q: Azure Data Factory - Lookup Activity I'm calling a procedure using a lookup activity in Azure Data Factory.
NOTE: The reason to use Lookup here is, I wanted to store the OUTPUT parameter value from procedure into a variable in ADF for future use.
Below works,
DECLARE @ADFOutputMsg [VARCHAR](500);
EXEC Test.spAsRunTVA @ReportDate = '2022-06-01', @OutputMsg = @ADFOutputMsg OUTPUT;
SELECT @ADFOutputMsg As OutputMsg;

But when I want to pass dynamic parameters, it doesn't like,
DECLARE @ADFOutputMsg [VARCHAR](500);
EXEC @{pipeline().parameters.SchemaName}.spAsRunTVA @ReportDate = @{substring(pipeline().parameters.FileName,8,10)}, @OutputMsg = ADFOutputMsg OUTPUT;
SELECT @ADFOutputMsg As OutputMsg;

I also tried to keep the date As-Is and just updated SchemaName to be dynamic but I still get the error.

A: Please Provide single quote ' ' at your dynamic content
'@{substring(pipeline().parameters.FileName,8,10)}'
I tried to reproduce similar kind of approach in my environment and I got below results:
Use the below dynamic content in the query with lookup activity.  and also Added dynamic content with single quotes ' '
select * from for_date where date1='@{string(pipeline().parameters.Date)}'

Added Date Parameter

Got this Output: