text:
Q: .NET Core program.cs and Startup.cs not hit I have a big problem with an application. When I use IIS Express, everything works fine, but if I start the app with IIS (both with or without Visual Studio), the Program.cs and Startup.cs are ignored so the app is not working.
This happen both with .NET Core 2.2 and .NET Core 3.1 and also with Razor Pages or MVC projects.
The strange thing is that IIS was working until yesterday and I haven't done any changes, only a computer restart between two days. This both in my notebook and desktop PC.
I don't understand why but this is driving me crazy. Do you have any suggestions for solve the issue?
Program.cs
public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args)
            .Build()
            .Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

Startup.cs
    public const string GenericCookieScheme = "XXX";
    public const string AuthSecret = "XXX";

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

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddRazorPages(options =>
        {
            options.Conventions.AuthorizePage("/Pages");
            options.Conventions.AllowAnonymousToFolder("/Pages/Login");
        });

        services.AddSession();

        services.AddControllersWithViews().AddRazorRuntimeCompilation();

        services.AddSingleton(Configuration.GetSection("AppSettings").Get<AppSettings>());
        #region SERVER
        services.AddEntityFrameworkSqlServer()
            .AddDbContext<DbConfigContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("ConfigContainer")));

        services.AddEntityFrameworkSqlServer()
            .AddDbContext<DbDataContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DataContainer")));

        services.AddScoped<ITenantProvider, TenantProvider>();
        services.AddScoped<IUserProvider, UserProvider>();
        services.AddTransient<IDbContextFactory, DbContextFactory>();
        DbDataContext.Init();
        #endregion

        #region AUTHENTICATION
        services.AddAuthentication(o =>
        {
            o.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            o.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            o.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        }).AddCookie(options =>
        {
            options.AccessDeniedPath = new PathString("/Login");
            options.LoginPath = new PathString("/Login");
        });
        #endregion

        services.Configure<IISOptions>(options =>
        {
            options.AutomaticAuthentication = false;
        });
        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Error");
            // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
            app.UseHsts();
        }

        app.UseHttpsRedirection();

        var defaultCulture = new CultureInfo("it-IT");
        var localizationOptions = new RequestLocalizationOptions
        {
            DefaultRequestCulture = new RequestCulture(defaultCulture),
            SupportedCultures = new List<CultureInfo> { defaultCulture },
            SupportedUICultures = new List<CultureInfo> { defaultCulture }
        };
        app.UseRequestLocalization(localizationOptions);

        app.UseHttpsRedirection();
        app.UseSession();
        app.UseAuthentication();

        app.UseStaticFiles();
        app.UseRequestLocalization("it-IT");

        app.UseRouting();

        app.UseRouter(r =>
        {
            r.MapGet(".well-known/acme-challenge/{id}", async (request, response, routeData) =>
            {
                var id = routeData.Values["id"] as string;
                var file = Path.Combine(env.WebRootPath, ".well-known", "acme-challenge", id);
                await response.SendFileAsync(file);
            });
        });

        app.UseAuthorization();

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

        using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
        {
            var t = serviceScope.ServiceProvider.GetService<IHttpContextAccessor>();
            #region CONFIG CONTAINER
            if (!serviceScope.ServiceProvider.GetService<DbConfigContext>().AllMigrationsApplied())
            {
                serviceScope.ServiceProvider.GetService<DbConfigContext>().Database.Migrate();
            }
            serviceScope.ServiceProvider.GetService<DbConfigContext>().EnsureSeeded(env.WebRootPath);
            #endregion
            #region DATA CONTAINER

            var dbContextFactory = serviceScope.ServiceProvider.GetService<IDbContextFactory>();
            //var allTenants = serviceScope.ServiceProvider.GetService<SigfridAppConfigContext>().Tenants.First();
            var context = dbContextFactory.CreateDbContext(Configuration);
            if (!context.AllMigrationsApplied())
            {
                context.Database.Migrate();
            }
            //serviceScope.ServiceProvider.GetService<DbDataContext>().EnsureSeeded(Guid.Parse("A2DDFB53-3221-41E7-AD27-F3CD70EC5BAF"));
            #endregion
        }
    }

A: Your checklist:

*

*If IIS can handle requests for ASP.NET Core?

*If IIS know that it needs to handle requests for ASP.NET Core?

For the first item
Please check if your IIS has the hosting bundle for ASP.NET Core installed.
Check it here:

If not, download and install it here:
https://dotnet.microsoft.com/download/dotnet-core/thank-you/runtime-aspnetcore-3.1.3-windows-hosting-bundle-installer
The second item
Please check if there is a file named web.config located in your site's root folder:

And its content shall be similar like this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\Aiursoft.Account.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

Check the part: <aspNetCore> under <system.webServer>.

A: Ok I found the problem. Duplicated routes. I have a route called "/dashboard" with a controller in controller folder and the same in api folder. I don't know why there is no error of "duplicated route" but now it's fine. I'm sorry for having wasted your time with a stupid problem :)


text:
Q: Lottie Files on Safari I have a Lottie file that is showing when the page is reloaded with the Lottie in the viewport and will play on the scroll but once it leaves the viewport layers of the file or the entire file are lost. This only happened on SAFARI and is not a problem for chrome.
here is a viewing link:
http://app-mba.rgubdr27a6-rz83y7k0p3d7.p.runcloud.link
All suggestions are appreciated!
Cheers,
Collin

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to save stream of image data to the root of the local app data folder in windows phone? I am trying to save the stream of image data to a file. I was able to save it to Pictures library though.
But I want to save it to a  file in the root of my application/ project.
I was trying the below but it doesn't work.
         using (MediaLibrary mediaLibrary = new MediaLibrary())
         mediaLibrary.SavePicture(@"\DefaultScreen.jpg", stream);

A: In this case you should use LocalStorage.
Here is a simple solution to do this:
using (IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication())
{
  if (!isoStore.FileExists(fileName)
  {
    var sr = Application.GetResourceStream(new Uri(fileName, UriKind.Relative));

    using (var br = new BinaryReader(sr.Stream))
    {
      byte[] data = br.ReadBytes((int)sr.Stream.Length);
      string strBaseDir = string.Empty;
      const string DelimStr = "/";
      char[] delimiter = DelimStr.ToCharArray();
      string[] dirsPath = fileName.Split(delimiter);

      // Recreate the directory structure
      for (int i = 0; i < dirsPath.Length - 1; i++)
      {
          strBaseDir = Path.Combine(strBaseDir, dirsPath[i]);
          isoStore.CreateDirectory(strBaseDir);
      }

      using (BinaryWriter bw = new BinaryWriter(isoStore.CreateFile(fileName)))
      {
          bw.Write(data);
      }
    }
  }
}

Here you can find all info about data in Windows Phone:
http://msdn.microsoft.com/en-us/library/windowsphone/develop/ff402541(v=vs.105).aspx


text:
Q: Covariance of a bivariate Gaussian given identity matrix I have a homework problem about finding an optimal decision boundary. I know the formula (not really the process) for calculating one, so that may be another question entirely, but I do know I need the mean, covariance, and priors. The question is shown below
Suppose points in R^2 are being obtained from two classes, C1 and C2, both of which
are well described by bivariate Gaussians with means at (0,0) and (1,3) and covariances
I and 2I respectively. I is the (2x2) identity matrix. If the priors of C1 and C2 are
0.4 and 0.6 respectively, what is the ideal (i.e. Bayes Optimal) decision boundary
(derive the equation for this boundary)?

I'm puzzled when it says "covariances I and 2I... I is the (2x2) identity matrix."
Is there a way to calculate a numerical value for covariance based on this information? If so, how? I've never heard it phrased this way.

A: Conditioned on being from class C1, the observation $(X,Y)$ is a pair of independent $N(0,1)$ random variables, while conditioned on being from class C2, the observation $(X,Y)$  consists of independent $N(1,2)$ and
$N(3,2)$ random variables.  How do we know this? The random variables are
given to be (conditionally)
independent because their covariance matrix is $I$ or $2I$ and so we know
that $\text{cov}(X,Y) = I_{1,2} = 0$ in one case, and $2I_{1,2} = 0$
in the other case. As has been discussed repeatedly on this stackexchange,
uncorrelated jointly normal random variables are independent random variables.
So, you can write down the conditional
joint pdfs $f_1(x,y)$ and $f_2(x,y)$ under the two hypotheses
as bivariate normal densities of independent random variables.
The Bayesian decision boundary is
the set of all points $(x,y)$ for which
$$0.4f_1(x,y) = 0.6f_2(x,y).$$


text:
Q: Count returned by a Query when Particular column is null and not-null in MySql i want to select a count returned by a query when a particular column is null and another query to select a count when that column is not null into single query how can i achieve it..?
i had tried some of the example that are avail in SOF but no use..
for example i want to
select students count of class table where the address null and notnull

A: In MySQL this can do it
SELECT
    SUM(IF(address IS NULL,1,0))       as  `Student_With_No_Address`,
    SUM(IF(address IS NOT NULL,1,0)) as    `Student_With_Address`
FROM students

SQL Fiddle Demo
Output :
Student_With_No_Address |   Student_With_Address
---------------------------------------------
        4               |           6

A: Try this
SELECT
COUNT(CASE when address is null then 1 end) AS StudentsWithNoAddress,
COUNT(CASE when address is not null then 1 end) AS StudentsWithAddress
FROM Class

A: You have to write two SELECT statements and combine them using UNION
SELECT 'No Address' AS AddressStatus, COUNT(*) AS NoOfStudents
FROM Class WHERE Address IS NULL
UNION
SELECT 'With Address' AS AddressStatus, COUNT(*) AS NoOfStudents
FROM Class WHERE Address IS NOT NULL

A: select
 SUM( CASE when studentId is not NULL THEN 1 else 0 END ) as result1 ,
 SUM( CASE when studentId is NULL THEN 1 else 0 END) as result2
from class


text:
Q: Calling javascript and getting yes no values inside server code I am calling a javascript function to return yes,no values from the user in a button click event inside an update panel. I want to call certain server side functions depending on user action (yes/no). My javascript code is given below
function Confirm() {
        var confirm_value = document.createElement("INPUT");
        confirm_value.type = "hidden";
        confirm_value.name = "confirm_value";
        if (confirm("Do you want to save data?")) {
            confirm_value.value = "Yes";
        } else {
            confirm_value.value = "No";
        }
        document.forms[0].appendChild(confirm_value);
    }

I am calling this in my server side button click which is shown below.
 if ((Convert.ToInt32(_dsLeaveDetails.Tables[0].Rows[0][0]) == 1)
            {

                ShowAlert("Leave is already marked for this date");
                return;

            }
            else if ((Convert.ToInt32(_dsAttendanceDetails.Tables[0].Rows[0][0]) >= 1))
            {

                ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "Confirm();", true);
                string confirmValue = Request.Form["confirm_value"];
                if (confirmValue == "Yes")
                {
                      ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('You clicked YES!');", true);
                }
                else
                {
                  ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "alert('You clicked YES!');", true);
                }

                return;
            }

The issue is, pop up is showing only after the code is fully executed and because of that user action (yes/no) cannot be processed further.
Also I cannot call javascript function on clientclick event because immediately I dont require a pop up. Only after checking the dataset dsAttendanceDetails, I need the pop up. Kindly help.

A: You seems to assume that the line ScriptManager.RegisterStartupScript(this, this.GetType(), "alert", "Confirm();", true); would execute the java-script function immediately - but that's simply not possible. This call would execute the JS function when response reaches to the client i.e. when subsequent server code would have been already executed.
The java-script function would be executed at the client side and you will need a form submit (sync or asynchronous does not matter) to retrieve the user's choice at the server side. So you need to two requests - first would register the script that would confirm user choice and subsequent request to send the user's choice to the server.


text:
Q: AMDeviceSecureInstallApplication when using Node.js webdriver.io on AWS Device Farm I have successfully ran the tests on Android devices. But still struggling with iOS.
Locally it all runs fine, but on AWS it just wont launch the app.
I can see the being installed, but wont launch
I have added all the relevant code on this gist https://gist.github.com/cescoferraro/2196382c88f6c0c50bd8f2f16cf4fb61
const awsopts = {
    path: '/wd/hub',
    port: 4723,
    capabilities: {
        automationName: "XCUITest",
        platformName: process.env.DEVICEFARM_DEVICE_PLATFORM_NAME,
        udid: "auto",
        app: process.env.DEVICEFARM_APP_PATH,
    },
};

Definitions
version: 0.1

# Phases are collection of commands that get executed on Device Farm.
phases:
  # The install phase includes commands that install dependencies that your tests use.
  # Default dependencies for testing frameworks supported on Device Farm are already installed.
  install:
    commands:
      # This test execution environment uses Appium version 1.7.2 by default, however we enable you to change it using the Appium version manager (avm)
      # An example "avm" command below changes the version to 1.14.2
      # For your convenience, we have preinstalled the following versions: 1.9.1, 1.10.1, 1.11.1, 1.12.1, 1.13.0, 1.14.1, 1.14.2, 1.15.1, 1.16.0, and 1.17.1
      # For iOS devices on OS version 13.4 and above, please use Appium version 1.17.1 for the best possible experience
      # Additionally, for iOS devices on OS version 13.0 through 13.3, please use Appium version 1.16.0 or higher
      # To use one of these Appium versions, change the version number in the "avm" command below to your desired version:
      - export APPIUM_VERSION=1.14.2
      - avm $APPIUM_VERSION
      - ln -s /usr/local/avm/versions/$APPIUM_VERSION/node_modules/.bin/appium  /usr/local/avm/versions/$APPIUM_VERSION/node_modules/appium/bin/appium.js

      # Device farm provides 4 different pre-built versions of WebDriverAgent, and each is suggested for different versions of Appium:
      # DEVICEFARM_WDA_DERIVED_DATA_PATH_V4: this version is suggested for Appium 1.17.1. V4 is built from the following source code: https://github.com/appium/WebDriverAgent/releases/tag/v2.14.1
      # DEVICEFARM_WDA_DERIVED_DATA_PATH_V3: this version is suggested for Appium 1.16.0. V3 is built from the following source code: https://github.com/appium/WebDriverAgent/releases/tag/v2.3.2
      # DEVICEFARM_WDA_DERIVED_DATA_PATH_V2: this version is suggested for Appium 1.15.1. V2 is built from the following source code: https://github.com/appium/WebDriverAgent/tree/v1.3.5
      # DEVICEFARM_WDA_DERIVED_DATA_PATH_V1: this version is suggested for Appium 1.9.1 through 1.14.2. V1 is built from the following source code: https://github.com/appium/WebDriverAgent/tree/2dbbf917ec2e4707bae9260f701d43c82b55e1b9
      # We will automatically configure your WebDriverAgent version based on your Appium version using the following code.

      # For users of Appium versions 1.15.0 and higher, your Appium version requires that your UDID of the device not contain any "-" characters
      # So, we will create a new environment variable of your UDID specifically for Appium based on your Appium version
      - >-
        if [ $(echo $APPIUM_VERSION | cut -d "." -f2) -ge 17 ];
        then
          DEVICEFARM_DEVICE_UDID_FOR_APPIUM=$(echo $DEVICEFARM_DEVICE_UDID | tr -d "-");
          DEVICEFARM_WDA_DERIVED_DATA_PATH=$DEVICEFARM_WDA_DERIVED_DATA_PATH_V4;
        elif [ $(echo $APPIUM_VERSION | cut -d "." -f2) -ge 16 ];
        then
          DEVICEFARM_DEVICE_UDID_FOR_APPIUM=$(echo $DEVICEFARM_DEVICE_UDID | tr -d "-");
          DEVICEFARM_WDA_DERIVED_DATA_PATH=$DEVICEFARM_WDA_DERIVED_DATA_PATH_V3;
        elif [ $(echo $APPIUM_VERSION | cut -d "." -f2) -ge 15 ];
        then
          DEVICEFARM_DEVICE_UDID_FOR_APPIUM=$(echo $DEVICEFARM_DEVICE_UDID | tr -d "-");
          DEVICEFARM_WDA_DERIVED_DATA_PATH=$DEVICEFARM_WDA_DERIVED_DATA_PATH_V2;
        else
          DEVICEFARM_DEVICE_UDID_FOR_APPIUM=$DEVICEFARM_DEVICE_UDID;
          DEVICEFARM_WDA_DERIVED_DATA_PATH=$DEVICEFARM_WDA_DERIVED_DATA_PATH_V1;
        fi

      # By default the node version installed is 10.9.0
      # you can switch to an alternate node version using below command.
      - nvm install 14.9.0

      # Unpackage and install the node modules that you uploaded in the test phase.
      - echo "Navigate to test package directory"
      - cd $DEVICEFARM_TEST_PACKAGE_PATH
      - npm install *.tgz

  # The pre-test phase includes commands that setup your test environment.
  pre_test:
    commands:
      # We recommend starting appium server process in the background using the command below.
      # Appium server log will go to $DEVICEFARM_LOG_DIR directory.
      # The environment variables below will be auto-populated during run time.
      - echo "Start appium server"
      - >-
        appium --log-timestamp
        --default-capabilities "{\"usePrebuiltWDA\": true, \"derivedDataPath\":\"$DEVICEFARM_WDA_DERIVED_DATA_PATH\",
        \"deviceName\": \"$DEVICEFARM_DEVICE_NAME\", \"platformName\":\"$DEVICEFARM_DEVICE_PLATFORM_NAME\", \"app\":\"$DEVICEFARM_APP_PATH\",
        \"automationName\":\"XCUITest\", \"udid\":\"$DEVICEFARM_DEVICE_UDID_FOR_APPIUM\", \"platformVersion\":\"$DEVICEFARM_DEVICE_OS_VERSION\"}"
        >> $DEVICEFARM_LOG_DIR/appiumlog.txt 2>&1 &

      - >-
        start_appium_timeout=0;
        while [ true ];
        do
            if [ $start_appium_timeout -gt 60 ];
            then
                echo "appium server never started in 60 seconds. Exiting";
                exit 1;
            fi;
            grep -i "Appium REST http interface listener started on 0.0.0.0:4723" $DEVICEFARM_LOG_DIR/appiumlog.txt >> /dev/null 2>&1;
            if [ $? -eq 0 ];
            then
                echo "Appium REST http interface listener started on 0.0.0.0:4723";
                break;
            else
                echo "Waiting for appium server to start. Sleeping for 1 second";
                sleep 1;
                start_appium_timeout=$((start_appium_timeout+1));
            fi;
        done;

  # The test phase includes commands that start your test suite execution.
  test:
    commands:
      # Your test package is downloaded in $DEVICEFARM_TEST_PACKAGE_PATH
      # However, we must navigate to its subdirectory "node_modules/*", as this directory has your test code and dependency node modules
      - echo "Navigate to test code directory"
      - cd $DEVICEFARM_TEST_PACKAGE_PATH/node_modules/*

      - echo "Start Appium Node test"
      # Enter the command below to start the tests . The comamnd should be similar to what you use to run the tests locally.
      # For e.g. assuming you run your tests locally using command "node YOUR_TEST_FILENAME.js.", enter the same command below:
      - npm run ios

  # The post test phase includes commands that are run after your tests are executed.
  post_test:
    commands:

# The artifacts phase lets you specify the location where your tests logs, device logs will be stored.
# And also let you specify the location of your test logs and artifacts which you want to be collected by Device Farm.
# These logs and artifacts will be available through ListArtifacts API in Device Farm.
artifacts:
  # By default, Device Farm will collect your artifacts from following directories
  - $DEVICEFARM_LOG_DIR

A: Can you please share run url of the iOS runs?
Also can you give a try with empty capabilities i.e.
const awsopts = {
                 path: '/wd/hub',
                 port: 4723,
                 capabilities: {
                  },
                 };

as the device farm platform already sets the same as default-capabilities in pre_test phase.


text:
Q: PHP AJAX POST request returns error I am using PHP to process an AJAX POST request from a form, and need it to send a JSON object back. My php code.
<?php

function main(){
$a = $_POST['args'];
$myFile = "jsonargs.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
fwrite($fh, $a);
fwrite($fh, "\n");
fwrite($fh, "-o ./json\n");
fwrite($fh, "-j\n");
fclose($fh);
$output = shell_exec('command 2>&1; ./syn-bin/synoptic-jar.sh -c jsonargs.txt ' . $_FILES["file"]["tmp_name"]);
$json = file_get_contents('./json.json');
header('Content-Type: application/json');
echo json_encode($json);

}

main();

?>

However, when I make the ajax call with jquery's ajax form plugin, my error function is called. If I submit it as a normal form instead of making an ajax call, it works correctly.  How do I properly return a JSON object?
My AJAX request:
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
    target:        '#output1',   // target element(s) to be updated with server response
    beforeSubmit:  showRequest,  // pre-submit callback
    success:       showResponse,  // post-submit callback
    error: showResponse
};

// bind form using 'ajaxForm'
$('#myForm').ajaxForm(options);
});

// pre-submit callback
function showRequest(formData, jqForm, options) {

alert('About to submit: \n\n' + queryString);

return true;
}

// post-submit callback
function showResponse(responseText, statusText, xhr, $form)  {

alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
    '\n\nThe output div should have already been updated with the responseText.');
    console.log(responseText);
}

A: After research, my problem was that I can't upload a file with AJAX. I had to use a hidden iframe to fix the problem.


text:
Q: Multi-level data vs multi-level models I am confused about the applicability of linear multi-levels models (also called hierarchical linear models or mixed-effect models) on data with multiple levels. At first, I thought they are made for each other but after trying to use a multi-level model on my own data I got very confused.
By multi-level data I mean that the data is about different levels in an hierarchy. For example, in the popularity data used by Joop Hox there is data about the pupil (popularity, sex) and the teacher (experience and popularity). In my case I want to asses the relation between the student-level and teacher-level predictors on the popularity of the student.
What I do know now about multi-level modeling is that they assess the effects of predictors on the lowest level possibly grouped by higher levels of the hierarchy (at least that is what I assume). For example, you can use multi-level models to check if schools have a different intercept or if the effect of sex is different for schools.
The problem I am trying to solve is how to use data higher up in the hierarchy to predict values lower in the hierarchy. In my real-case example I want to predict the house-prices using data about the districts they are in. Since the number of districts is much lower than the number of houses I want to incorporate this information in the estimation of the variance of the coefficients.
Below is a parallel example with pupil-teacher data used by Joop Hox. In this example, I want to asses the effect of sex on the pupil level and the effect of teacher experience on the teacher level. The model should take into account that there are much less observations (100) of teacher experience than of student sex (2000). Note that there is only one teacher per school; for clarity I rename school to teacher.
Following Joop Hox's notation that would be the following in math:
$$\text{popularity}_{ij} = \beta_{0j} + \beta_{1j} \text{gender}_{ij} + e_{ij}$$
$$\beta_{0j} = \gamma_{00} + \gamma_{01} \text{experience}_{j} + u_{0j}$$
Ordinary linear model
library(foreign)
library(lme4)
library(arm)
library(tidyverse)
library(broom)
df <- read.dta("http://www.ats.ucla.edu/stat/stata/examples/mlm_ma_hox/popular.dta") %>%
  rename(teacher = school)
fit_lm <- lm(popular ~ sex + texp, df)
display(fit_lm)

This would underestimate the standard error of the effect of the teacher experience since it assumes there are 2000 observations of teacher experience instead of only 100 (number of teachers).
Stacked linear models
fit_lm_1 <- lm(popular ~ sex + factor(teacher) + 0, df)
teacher_effect <- tidy(fit_lm_1)[3:101,] %>%
  mutate(teacher = as.numeric(substr(term, 15,18))) %>%
  dplyr::select(teacher, estimate) %>%
  bind_rows(data.frame(teacher = 1, estimate = 0))
df_teacher <- df %>%
  group_by(teacher) %>%
  summarise(texp = first(texp)) %>%
  left_join(teacher_effect)
fit_lm_2 <- lm(estimate ~ texp, df_teacher)
display(fit_lm_2)

Takes into account that there is less data about teachers than about pupils. However, does not allow for dependencies between teacher-experience and gender (e.g. think of a private boys/girls school).
Multi-level model with teacher-experience per school
fit_lmer1 <- lmer(popular ~ sex + (texp + 0 | teacher), df)
display(fit_lmer1)
ranef(fit_lmer1)

This would give a separate slope for teacher experience for each teacher. Since there is only a single teacher per teacher (duh!) this is a strange thing to do.
Multi-level model with fixed teacher-experience and intercept per school
fit_lmer2 <- lmer(popular ~ sex + texp + (1 | teacher), df)
display(fit_lmer2)
fixef(fit_lmer2)

This results in a single estimate for teacher experience. According to this blog post lmer understands that texp and teacher are related and that there are only 100 observations of teacher experience.
Fine, you would say? Not totally, I do not want to model the teacher intercept but only the teacher experience, because what could the teacher experience possibly add to an intercept per teacher. Furthermore, I doubt that lmer really understands that texp and school belong together.
In short
I have data on two separate levels and I want to draw valid conclusions about there relationships with a dependent variable. Can I use multi-level modeling for this? How to do this in R with lme4 (or possibly nlme)

A: First of all, that there are only 100 different teachers for 2000 students will not lead to an underestimation of teacher experience on the popularity of the student (measured on the student level). There are not 100 observations of teacher experience but 2000! To explain this with an analogy: if we want to study the effect of gender on an outcome variable, say test score on an exam, we might have 2000 test scores from 2000 students, but only 2 different genders. This will not lead to underestimated standard errors for the effect of gender, because there are 2000 observations of the relation between gender and test score, even though there are only two different genders.
So I'd say that your ordinary regression model is fine from that perspective:
fit_lm <- lm(popular ~ sex + texp, df)

However, students are nested within schools and it might be the case that there are some differences among schools that might be captured by modeling schools as a random intercept:
fit_lmer <- lmer(popular ~ sex + (1 | school), df)

This model does not take teacher experience into account, and you say that you don't understand what teacher experience could add to a school-based intercept. To understand this, we might think about what might influence the outcome variable (popularity, whatever that is?) on a school level. Obviously teacher experience might do so, but also perhaps the environment in the school, the social class of the students, the personality of the teacher, the skill of the teacher (might be different from teacher experience) etc. All of those variables might be bundled together as a school-level random intercept.
Then why should we add teacher experience? We have information about teacher experience, so it might be used in addition to the random intercept of school, and it might provide a better fit. What if some very experienced teachers work in a very bad school (which might be associated with lower popularity)? Or a very inexperienced teacher works in a very good school? By using both teacher experience and school itself as a random variable, we take the rest of the random variance associated with teacher/school into account, while also taking teacher experience into account. This might provide a better fit for the data, and consequently more accurate estimates:
fit_lmer2 <- lmer(popular ~ sex + texp + (1 | school), df)

However, it is also possible that the influence of teacher experience on popularity varies across schools. In some schools, the environment might be so supportive, the education of the teachers so high etc, that the influence of the individual teacher's experience is lower. Conversely, some schools might be so dysfunctional that the individual teacher's experience might have a much higher influence. I don't work in the education system, but from my experience within the health care system, this is not a too far-fetched idea. Some clinics work very well, and all patients get more or less the same care regardless of clinician's experience, while other clinics are more dysfunctional and the level of care depends to a high degree on the individual clinician's expertise.
So this idea might be modeled as a random slope in addition to the random intercept of school:
fit_lmer3 <- lmer(popular ~ sex + texp + (1 + texp | school), df)

I would try model 2 and 3, and then compare them:
anova(fit_lmer2, fit_lmer3)

In summary: yes, you can use multilevel modeling to compare data on separate levels. There is no problem with using district-level data (perhaps income, education and other things) along with using the districts themselves as random variables when predicting house prices.

A: In the end I decided that the stacked linear model was the best option for my application. With more than a two-level hierarchy this could be difficult, but for me it is suitable.
In the first run the linear model distinguishes between the pupil and teacher effect. The pupil effect is directly explained by the pupil predictors (sex and intercept) and the teacher effect is a dummy coding of the teacher.
fit_lm_11 <- lm(popular ~ sex + factor(teacher) + 0, df)

Then I summarise the data on the teacher level, including the intercepts (coefficients for the dummy variables:
teacher_effect <- tidy(fit_lm_11)[3:101,] %>%
  mutate(teacher = as.numeric(substr(term, 16,19))) %>%
  dplyr::select(teacher, estimate) %>%
  bind_rows(data.frame(teacher = 1, estimate = 0))
df_teacher <- df %>%
  group_by(teacher) %>%
  summarise(texp = first(texp)) %>%
  left_join(teacher_effect)

And finally learn the influence of the teacher experience on his or hers intercept.
fit_lm_12 <- lm(estimate ~ texp, df_teacher)

This explains 43% of the variation between teachers:
> display(fit_lm_12)
lm(formula = estimate ~ texp, data = df_teacher)
            coef.est coef.se
(Intercept) -3.57     0.17
texp         0.09     0.01
---
n = 100, k = 2
residual sd = 0.71, R-Squared = 0.43

And the standard error of the teacher experience estimate is much more realistic (0.01086) than the one of the ordinary linear model (0.003299). About three times higher.


text:
Q: Large ECommerce Workload with Ruby on Rails? I'm tasked with building a large eCommerce site for a retailer. We are using packaged software for it. The package is difficult to tailor, and inflexible, but it scales on a solidly tested java application.
In the background though, I've been considering trying to use this as a reference workload to build a custom Ruby on Rails eCommerce application - just for interest sake and to learn the framework. But before I start too far down the path, I guess I'm looking for a high level is determination if it's even possible to reach this type of workload with ROR.
The app would have to capture about 2000 orders per hour, but each order is big, so would be processing about 140,000 line items per hour. Concurrent customers are relatively straightforward, at about 5,000 active in an hour. But browse to shop is high, with a conversion of about 45% of customers coming to the site to shop so majority of processing is order capture rather than search & browse of most sites.
So my question is, what is "large workload" when it comes to ROR? Is this a feasible NFR to meet with a ROR application? What considerations should I make?

A: Actually, as a web framework, RoR does not impose any restrictions on the work load limit.
The work load limit depends on:

*

*How many machines to serve the request

*Complexity of your business logic, which determines work load limit of single machine

*Any bottleneck in bandwidth, or database disk I/O?


text:
Q: Probability of getting at least two 6 with 12 dice I have 12 dice. I want to know how likely it is to get two 6's. MY attempt is to call $A$ such an event. Note
$$ P(A) = 1 - P(\text{no six}) = 1 - \left(\frac 5 {12} \right)^{12}$$
IS this correct? The problem confuses because I dont really understand whether they mean to throw the dice one by one or all at  the same time.

A: You have not accounted for the probability of getting exactly one six.
Letting $X$ denote the number of sixes we observed,
$$P(X\geq 2)=1-P(X=0)-P(X=1)$$
The probability that an individual die is not a six is $\frac{5}{6}$ so
$$P(X=0)=\left(\frac{5}{6}\right)^{12}$$
Can you go from here to solve for $P(X=1)$ noting that exactly one success can occur in $12$ places?


text:
Q: Powershell command is not recognized in gitlab.ci.yml I am trying to execute a PowerShell script from gitlab.ci.yml file, but the PowerShell command is not recognized. The PowerShell which I am trying to trigger just has a single line to print some message.

Running with gitlab-runner 11.5.0 (3afdaba6)
  on docker-auto-scale fa6cab46
Using Docker executor with image ruby:2.5 ...
Pulling docker image ruby:2.5 ...
Using docker image sha356:7834f561ba80e65515163209a3f952fcd1d11f9ce4420ba63d952e5b52b77e1 for ruby:2.5 ...
Running on runner-fa6cab46-project-9772339-concurrent-0 via runner-srm-1545289526-a4a36a59...
Cloning repository...
Cloning into 'builds/leo.danny/jenkinsintegration'...
Checking out 4b9beba2 as master...
Skipping Git submodules setup
$ powershell "./JenkinsPowershell.ps1"
/bin/bash: line 70: powershell: command not found
ERROR: Job failed: exit code 1


text:
Q: Getting error DecimalFields must define a 'max_digits' attribute I'm having a problem with these DecimalField types.
I have the next model:
class Mediciones(models.Model):
    id = models.AutoField(primary_key=True)
    nombre = models.CharField(max_length=30, verbose_name='Nombre dispositivo')
    dispositivo = models.ForeignKey(Dispositivos, on_delete=models.CASCADE)
    temperatura = models.DecimalField(max_digits=5, decimal_places=2)
    humedad = models.DecimalField(max_digits=5, decimal_places=2)
    ruido = models.DecimalField(max_digits=7, decimal_places=2)
    c02 = models.DecimalField(max_digits=7, decimal_places=2)
    alerta = models.BooleanField(null=False)
    fecha = models.DateTimeField(verbose_name="Fecha", blank = False)

As you can see, I have four DecimalField, and all of them have defined both "max_digits" and "decimal_places", and max_digits is greater than decimal_places. Despite of that, I'm getting errors "DecimalFields must define a 'max_digits' attribute." when I try to make a migration. Do you know why?
Thanks in advance!

A: In the end I have managed to solve. The problem was not with the syntax, it seemed to be with the Python cache. I realized that when changing some fields it kept coming out (although I deleted the ones that gave error), so I assumed that I was not checking the file. I deleted the "pychache" and "migrations" folders, did a new migration and it worked.

A: Try reordering the parameters, so it will look like:
temperatura = models.DecimalField(decimal_places=2, max_digits=5)
humedad = models.DecimalField(decimal_places=2, max_digits=5)
ruido = models.DecimalField(decimal_places=2, max_digits=7)
c02 = models.DecimalField(decimal_places=2, max_digits=7)

It is the only thing that I think that can be wrong, I had this problem once, and I did this to solve it.


text:
Q: Angular2 print text passed in ngModel instead of it's value In Angular2, If we need name of passed model instead of value how we can achieve this ?
For example
@Input() field: any;

<one-line [title]="'Last Name'" [(field)]="doc.lastName"></one-line>

My requirement is to have "doc.lastName" (anything which passed in field) not the value of doc.lastName
We can easily do in Angular1
scope:{
   field: '='
   fieldName: '@field'
}

A: If you want to provide a string value to an input, simply remove the [(...]):
<one-line [title]="'Last Name'" field="doc.lastName"></one-line>

In the OneLineComponent, the value of the field property will be 'doc.lastName' in this case.
You can also notice that [title]="'Last Name'" is similar to title="Last Name".


text:
Q: Refused to execute JavaScript URL because it violates the following Content Security Policy directive: Before posting I read the posts relating to the title and I'm sure there's a solution to my problem but I'm such a n00b with Extensions, JavaScript, and JQuery I can't tell...
The code that's causing the Refused is:
innerframe = $("<iframe/>").css({
    top: WIDGET_TITLE_HEIGHT + "px",
    left: "0px",
    width: "100%",
    height: "1000px",
    border: "none",
    align: "center",
    display: "block"})
.appendTo(innerdiv)
.load(function() {
    onStart()
})
.attr({
    frameBorder: 0,
    //scrolling:0,
    src: 'javascript:(function(){document.open();document.domain="' + document.domain + '";document.write(\' <!DOCTYPE html>' + '\');document.close();})();'
})[0];

The line src: 'javascript....' is the offender but I don't know what the solution is.
The posts I've read make it clear the code is violating Chrome's CSP and I've seen mention of message passing, sandboxing, etc.
I'm hoping someone can provide a solution and help me understand what's going on.
Thanks in advance!

A: Your script probably violates the Same origin policy, which says that scripts may only be executed on pages that come from the same domain. To be specific, they have to have the same protocol and host.
Your line document.write(\' <!DOCTYPE html>' + '\'); is probably the culprit.


text:
Q: Keep persistent variables in memory between runs of Python script Is there any way of keeping a result variable in memory so I don't have to recalculate it each time I run the beginning of my script?
I am doing a long (5-10 sec) series of the exact operations on a data set (which I am reading from disk) every time I run my script.
This wouldn't be too much of a problem since I'm pretty good at using the interactive editor to debug my code in between runs; however sometimes the interactive capabilities just don't cut it.
I know I could write my results to a file on disk, but I'd like to avoid doing so if at all possible. This should be a solution which generates a variable the first time I run the script, and keeps it in memory until the shell itself is closed or until I explicitly tell it to fizzle out. Something like this:
# Check if variable already created this session
in_mem = var_in_memory() # Returns pointer to var, or False if not in memory yet
if not in_mem:
    # Read data set from disk
    with open('mydata', 'r') as in_handle:
        mytext = in_handle.read()
    # Extract relevant results from data set
    mydata = parse_data(mytext)
    result = initial_operations(mydata)
    in_mem = store_persistent(result)

I've an inkling that the shelve module might be what I'm looking for here, but looks like in order to open a shelve variable I would have to specify a file name for the persistent object, and so I'm not sure if it's quite what I'm looking for.
Any tips on getting shelve to do what I want it to do? Any alternative ideas?

A: To keep data in memory, the process must keep running.  Memory belongs to the process running the script, NOT to the shell.  The shell cannot hold memory for you.
So if you want to change your code and keep your process running, you'll have to reload the modules when they're changed.  If any of the data in memory is an instance of a class that changes, you'll have to find a way to convert it to an instance of the new class.  It's a bit of a mess.  Not many languages were ever any good at this kind of hot patching (Common Lisp comes to mind), and there are a lot of chances for things to go wrong.

A: If you only want to persist one object (or object graph) for future sessions, the shelve module probably is overkill.  Just pickle the object you care about. Do the work and save the pickle if you have no pickle-file, or load the pickle-file if you have one.
import os
import cPickle as pickle

pickle_filepath = "/path/to/picklefile.pickle"

if not os.path.exists(pickle_filepath):
    # Read data set from disk
    with open('mydata', 'r') as in_handle:
        mytext = in_handle.read()
    # Extract relevant results from data set
    mydata = parse_data(mytext)
    result = initial_operations(mydata)
    with open(pickle_filepath, 'w') as pickle_handle:
        pickle.dump(result, pickle_handle)
else:
    with open(pickle_filepath) as pickle_handle:
        result = pickle.load(pickle_handle)

A: You can achieve something like this using the reload global function to re-execute your main script's code.  You will need to write a wrapper script that imports your main script, asks it for the variable it wants to cache, caches a copy of that within the wrapper script's module scope, and then when you want (when you hit ENTER on stdin or whatever), it calls reload(yourscriptmodule) but this time passes it the cached object such that yourscript can bypass the expensive computation.  Here's a quick example.
wrapper.py
import sys
import mainscript

part1Cache = None
if __name__ == "__main__":
    while True:
        if not part1Cache:
            part1Cache = mainscript.part1()
        mainscript.part2(part1Cache)
        print "Press enter to re-run the script, CTRL-C to exit"
        sys.stdin.readline()
        reload(mainscript)

mainscript.py
def part1():
    print "part1 expensive computation running"
    return "This was expensive to compute"

def part2(value):
    print "part2 running with %s" % value

While wrapper.py is running, you can edit mainscript.py, add new code to the part2 function and be able to run your new code against the pre-computed part1Cache.

A: Python's shelve is a persistence solution for pickled (serialized) objects and is file-based.  The advantage is that it stores Python objects directly, meaning the API is pretty simple.
If you really want to avoid the disk, the technology you are looking for is a "in-memory database."  Several alternatives exist, see this SO question: in-memory database in Python.

A: Weirdly, none of the earlier answers here mention simple text files. The OP says they don't like the idea, but as this is becoming a canonical for duplicates which might not have that constraint, this alternative deserves a mention. If all you need is for some text to survive between invocations of your script, save it in a regular text file.
def main():
    # Before start, read data from previous run
    try:
        with open('mydata.txt', encoding='utf-8') as statefile:
            data = statefile.read().rstrip('\n')
    except FileNotFound:
        data = "some default, or maybe nothing"

    updated_data = your_real_main(data)

    # When done, save new data for next run
    with open('mydata.txt', 'w', encoding='utf-8') as statefile:
        statefile.write(updated_data + '\n')

This easily extends to more complex data structures, though then you'll probably need to use a standard structured format like JSON or YAML (for serializing data with tree-like structures into text) or CSV (for a matrix of columns and rows containing text and/or numbers).
Ultimately, shelve and pickle are just glorified generalized versions of the same idea; but if your needs are modest, the benefits of a simple textual format which you can inspect and update in a regular text editor, and read and manipulate with ubiquitous standard tools, and easily copy and share between different Python versions and even other programming languages as well as version control systems etc, are quite compelling.
As an aside, character encoding issues are a complication which you need to plan for; but in this day and age, just use UTF-8 for all your text files.
Another caveat is that beginners are often confused about where to save the file. A common convention is to save it in the invoking user's home directory, though that obviously means multiple users cannot share this data. Another is to save it in a shared location, but this then requires an administrator to separately grant write access to this location (except I guess on Windows; but that then comes with its own tectonic plate of other problems).
The main drawback is that text is brittle if you need multiple processes to update the file in rapid succession, and slow to handle if you have lots of data and need to update parts of it frequently. For these use cases, maybe look at a database (probably start with SQLite which is robust and nimble, and included in the Python standard library; scale up to Postgres or etc if you have entrerprise-grade needs).
And, of course, if you need to store native Python structures, shelve and pickle are still there.

A: This is a os dependent solution...
$mkfifo inpipe

#/usr/bin/python3
#firstprocess.py
complicated_calculation()
while True:
 with open('inpipe') as f:
  try:
   print( exec (f.read()))
  except Exception as e: print(e)

$./first_process.py &
$cat second_process.py > inpipe

This will allow you to change and redefine variables in the first process without copying or recalculating anything. It should be the most efficient solution compared to multiprocessing, memcached, pickle, shelve modules or databases.
This is really nice if you want to edit and redefine second_process.py iteratively in your editor or IDE until you have it right without having to wait for the first process (e.g. initializing a large dict, etc.) to execute each time you make a change.

A: You can do this but you must use a Python shell. In other words, the shell that you use to start Python scripts must be a Python process. Then, any global variables or classes will live until you close the shell.
Look at the cmd module which makes it easy to write a shell program. You can even arrange so that any commmands that are not implemented in your shell get passed to the system shell for execution (without closing your shell). Then you would have to implement some kind of command, prun for instance, that runs a Python script by using the runpy module.
http://docs.python.org/library/runpy.html
You would need to use the init_globals parameter to pass your special data to the program's namespace, ideally a dict or a single class instance.

A: You could run a persistent script on the server through the os which loads/calcs, and even periodically reloads/recalcs the sql data into memory structures of some sort and then acess the in-memory data from your other script through a socket.


text:
Q: Aligning equations with text with alignat I'm trying to add this expression to my work:

I understand that the best way to achieve this is using the alignat environment within the amsmath package, so I tried the following:
\begin{alignat*}{3}
m && \text{módulo} && m>0\\
a && \text{multiplicador} && 0<a<m\\
c && \text{constante aditiva} && 0\leq c<m\\
x_0 && \text{valor inicial} && 0\leq x_0 <m
\end{alignat*}

But the spacing I'm getting is really weird, I have read the amsmath documentation but I can't figure out what's the problem.
This was I'm getting:

My version is in spanish and I'm using polyglossia, but I don't think that's relevant.
Anyway I'm using xelatex, and the book class.
I also wanted to know if there is a way to write the whole equation in the same environment with the middle text, or do I need to make another math environment for the centered equation at the end.

A: The important things to remember are that

*

*alignat doesn't add space between the columns;

*the columns are as many rl pairs as specified by the argument.

So, if you want left alignment for the symbols, the descriptions, and the conditions, you should place them after a &, with another & to separate the pairs:

\begin{alignat*}{3}
& m   \quad && \text{módulo}            \quad && m>0\\
& a   \quad && \text{multiplicador}     \quad && 0<a<m\\
& c   \quad && \text{constante aditiva} \quad && 0\leq c<m\\
& x_0 \quad && \text{valor inicial}     \quad && 0\leq x_0 <m
\end{alignat*}

By adding \quad we separate the columns. It wouldn't be necessary to specify them on all rows, but doing so spares to guess what is the widest entry.
However, this will center the whole alignment. You can get a non centered alignment using tabular (and the array package):

\begin{tabular}{@{}>{$}l<{$}l>{$}l<{$}@{}}
m   & módulo            & m>0\\
a   & multiplicador     & 0<a<m\\
c   & constante aditiva & 0\leq c<m\\
x_0 & valor inicial     & 0\leq x_0 <m
\end{tabular}


text:
Q: My Selenium WebDriver tests hang on Opera browser I'm using Opera driver from this
and the last version of Opera browser(37.0.2178.54)
My test case hangs each time during loading page just after authorization.
I.e. browser became not responding and page is not loaded completely.
The same test case works good on both Chrome and Firefox.
Can anyone help me with this issue?

A: Your problem is too simple.
You just need to give path of your browser and operadriver like this:
from selenium import webdriver
from selenium.webdriver.opera.options import Options

s = Options()
s.binary_location = r'C:\Users\Admin\AppData\Local\Programs\Opera\launcher.exe'
driver = webdriver.Opera( executable_path=r'F:\ffmpeg\bin\operadriver.exe')
driver.get("http://google.com/")

A: With Opera open, do:
chrome_options = ChromeOptions()
chrome_options.add_argument("user-data-dir=" + OPERA_PROFILE)
Browser = webdriver.Chrome(executable_path=driver, chrome_options=chrome_options)


text:
Q: searchString, searchField and searchOper returned as empty from jqGrid in ASP.NET application I am creating a asp.net mvc application and loaded the data into jqgrid and have paging and sorting working completely. I am trying to implement searching and have implemented code to display the
search window; but when I click the Find button, I am unable to retrieve the searchString, searchField and searchOper since they are returned as empty. I am sure that I need to implement postdata code in the javascript but having trouble implementing one. Can anyone point me in the right direction?
Also, any idea about how to implement searching in the controller action??
This is what I have currently in the javascript:
 <script type="text/javascript">
    $(function () {
          $("#list").jqGrid({
              url: '/Home/GetData/',
                    datatype: 'json',
                    mtype: 'GET',
                    colNames: ['ID', 'NAME'],
                    colModel: [
      { name: 'ID', index: 'ID', width: 250, align: 'center', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
      { name: 'NAME', index: 'NAME', width: 250, align: 'center',  searchoptions: { sopt: ['eq', 'ne', 'cn']} }],
                    pager: jQuery('#pager'),
                    rowNum: 10,
                    rowList: [5, 10, 20, 30, 40, 50],
                    sortname: 'ID',
                    sortorder: "desc",
                    viewrecords: true,
                    height: '100%'
                    });

                $("#list").jqGrid('navGrid', '#pager', { edit: true, add: true, del: true, search: true},
                                                        {},
                                                        {},
                                                        {},
                                                        {closeOnEscape: true, multipleSearch: true, closeAfterSearch: true},
                                                        {});

            });
</script>

Any help is greatly appreciated!

A: You use multipleSearch: true searching option. It allows to create more powerful queries, but it uses another format of parameters. Instead of three parameters searchString, searchField and searchOper will be used one filters parameter which represent in form of JSON string the full information about the filter. See the documentation for more information.
In the answer for example you will find the code which demonstrate how one can parse the filters parameter and create the corresponding filtering of the data in case of usage Entity Framework for access to the database.


text:
Q: Horizontal Scrolling of items in BottomNavigationBar In my app, I want to create a BottomNavigationBar having almost 10-15 items. Items should scroll in the horizontal orientation.
For example;

like this, items should be scrolled horizontally.
<FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="110dp"
        android:backgroundTint="@color/colorLight"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="4dp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/linearLayout3">

        <com.google.android.material.bottomnavigation.BottomNavigationView
            android:id="@+id/navigationView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="bottom"
            app:itemIconTint="@drawable/selector"
            android:visibility="visible"
            app:labelVisibilityMode="unlabeled"
            app:itemBackground="@color/colorPrimary"
            app:itemTextColor="@color/whiteTextColor"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:menu="@menu/navigation"/>

    </FrameLayout>

A: try one with this ,
https://github.com/huang3eng/CustomLayoutManager
it may helps you

A: If you want to make bottom left right scrolling bar with icons and text just copy past code and change icons according to your drawable.

<HorizontalScrollView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fillViewport="false">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="horizontal"
    android:layout_gravity="left">

    // Your components/control here like text view, icons
  // You can copy my blow code for each block like crop, filter, effect

</LinearLayout>
</HorizontalScrollView>
</androidx.cardview.widget.CardView>

For Single Block as you can see in image here is code like crop, filter etc
<!--          Crop Icon-->
          <androidx.cardview.widget.CardView
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              app:cardBackgroundColor="#1B1B1B"
              android:layout_marginLeft="6dp"
              android:layout_marginRight="22dp"
              android:id="@+id/cropIcon">

              <LinearLayout
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:orientation="vertical"
                  android:gravity="center">

                  <ImageView
                      android:layout_marginTop="3dp"
                      android:layout_width="25dp"
                      android:layout_height="25dp"
                      android:src="@drawable/cropicon"/>
                  <TextView
                      android:layout_width="match_parent"
                      android:layout_height="wrap_content"
                      android:text="Crop"
                      android:textColor="#464646"
                      android:textSize="9sp"
                      android:textStyle="bold"
                      android:textAlignment="center"
                      />

              </LinearLayout>

          </androidx.cardview.widget.CardView>


text:
Q: URL issue with JSONObject I've the following code, but when I am saving below JSON in database its giving me wrong url like {"#url#":"https:\/\/www.test.com\/test"}
import org.json.simple.JSONObject;

public class DemoURL {
    private static String url = "https://www.test.com/test";
    public static void main(String[] args) {
        JSONObject msgJson = new JSONObject();
        msgJson.put("#url#", url);
        System.out.println(msgJson.toString());
    }
}

I want url like {"#url#":"https://www.test.com/test"}
Please suggest how to fix it?

A: Here is the solution:
public class App{
    private static String url = "https://www.test.com/test";
    public static void main(String[] args) {
        JSONObject msgJson = new JSONObject();
        msgJson.put("#url#", url);
        System.out.println(getCleanURL(msgJson.toString()));
    }

    private static String getCleanURL(String url){
        return url.replaceAll("\\\\", "").trim();
    }
}

This gives correct output, simply run this code. This will store exact value in the database.
{"#url#":"https://www.test.com/test"}

A: You are using org.json.simple JSON library. JSON-Simple escapes char from String.
You can't change this thing, as its not configurable.
But you can use org.json JSON library, this will not escape String, and good part is, you don't have to change your code, existing syntax will work fine.
e.g.
import org.json.JSONObject;

public class DemoURL {
    private static String url = "https://www.test.com/test";
    public static void main(String[] args) {
        JSONObject msgJson = new JSONObject();
        msgJson.put("#url#", url);
        System.out.println(msgJson.toString());
    }
}

output : {"#url#":"https://www.test.com/test"}

A: Try replacing slash(/) with unicode character \u2215 before passing it to JSON object.

A: try to quote the string with single quotes, something like this
    JSONObject msgJson = new JSONObject();
    msgJson.put("#url#", "\'"+url+"\'");
    System.out.println(msgJson.toString());


text:
Q: hyper_filter (tidync R package) seems not to work for grid with two variables I have a nc file with the following structure and I am trying to filter given a lat/lon range, but with no success.
Unfortunately, I beg your pardon, but I cannot share this nc files, and I could not find a similar nc file openly available on the web.
I am using version 0.2.4, and I fear I am facing this issue (from the tidync manual)
"Files with compound types are not yet supported and should fail gracefully. Groups are not yet supported."
Any help/solution about subsetting a nc based on lat/lon and variable name, with tidync or in case with ncdf4 is welcome.
tidync::tidync(file.in)

Grids (4) <dimension family> : <associated variables>

 [1]   D3,D2,D1,D5,D0 : var4    **ACTIVE GRID** ( 207360000  values per variable)
 [2]   D3,D2,D1,D0    : var1, var2, var3
 [3]   D3,D2          : lat, lon
 [4]   D4,D0          : Times

 Dimensions 6 (5 active):

   dim   name        length   min   max start count  dmin  dmax unlim coord_dim
   <chr> <chr>        <dbl> <dbl> <dbl> <int> <int> <dbl> <dbl> <lgl> <lgl>
 1 D0    Time           240     1   240     1   240     1   240 TRUE  FALSE
 2 D1    bottom_top       1     1     1     1     1     1     1 FALSE FALSE
 3 D2    south_north    300     1   300     1   300     1   300 FALSE FALSE
 4 D3    west_east      288     1   288     1   288     1   288 FALSE FALSE
 5 D5    nbins           10     1    10     1    10     1    10 FALSE FALSE

 Inactive dimensions:

   dim   name       length   min   max unlim coord_dim
   <chr> <chr>       <dbl> <dbl> <dbl> <lgl> <lgl>
 1 D4    DateStrLen     19     1    19 FALSE FALSE

when I try to filter across lat/lon I am getting the following error: any clue about what I am doing wrong?
tidync::tidync(file.in) %>%
    tidync::activate(., "D3,D2") %>%
    tidync::hyper_filter(lat = between(lat, 26.9, 27.1) )

>  Grids (4) <dimension family> : <associated variables>

 [1]   D3,D2,D1,D5,D0 : var4
 [2]   D3,D2,D1,D0    : var1, var2, var3
 [3]   D3,D2          : lat, lon    **ACTIVE GRID** ( 86400  values per variable)
 [4]   D4,D0          : Times

 Dimensions 6 (2 active):

   dim   name        length   min   max start count  dmin  dmax unlim coord_dim
   <chr> <chr>        <dbl> <dbl> <dbl> <int> <int> <dbl> <dbl> <lgl> <lgl>
 1 D2    south_north    300     1   300     1   300     1   300 FALSE FALSE
 2 D3    west_east      288     1   288     1   288     1   288 FALSE FALSE

 Inactive dimensions:

   dim   name       length   min   max unlim coord_dim
   <chr> <chr>       <dbl> <dbl> <dbl> <lgl> <lgl>
 1 D0    Time          240     1   240 TRUE  FALSE
 2 D1    bottom_top      1     1     1 FALSE FALSE
 3 D4    DateStrLen     19     1    19 FALSE FALSE
 4 D5    nbins          10     1    10 FALSE FALSE
 Warning message:
 In hyper_filter.tidync(., lat = between(lat, 26.9, 27.1)) :
   'lat' not found in active grid, ignoring


text:
Q: started.FATAL: Log statements out of sync: current test suite 'TestTarget.xctest' not exists I have a Jenkins build server for my iOS project. I configured a job with the XCode integration plugin to launch unit test, but an error occurred when the first test is been launched:
started.FATAL: Log statements out of sync: current test suite 'Target_Test.xctest' not exists
Has anyone seen this console log before? Thanks for help.
Jenkins version: 2.46.3
Xcode Integration plugin version: 2.0.4

A: I had the same issue today, apparently it was because I had spaces in the product name of my test target. I changed them by '-' and now it seems working. Let me know if it was the same for you.


text:
Q: Unable to click on dropdown made by  using Selenium WebDriver HTML code

Discrepancy Type*

<input class="qx-abstract-field qx-placeholder-color" >
//On Below button there is one dropdown button on which i want to click but i cannot

<div class="qx-outSet" qxse..

Java Code
WebElement element = wd.findElement(By.className("qx-input-required"));
Actions actions = new Actions(wd);
actions.moveToElement(element).click().perform();
wd.findElement(By.xpath(".//*[@id='demindoRoot']/div[3]/div[2]/div[1]/div/div[2]/div[2]/div/div")).click(); // link through which i try to click
Thread.sleep(1000);

I also tried with below mention code
wd.findElement(By.xpath("//div[@class='qx-button'"));

Error :

Unable to locate element:

A: action.moveToElement(element).moveToElement(driver.findElement(By.Xpath(<Your path here>))).click().build().perform();

This performs the action more like a user would. They user first navigates to the menu, opens it, then navigates to the element they wish to click. Check out this question for more details:
https://stackoverflow.com/a/17294390/3537915

A: WebDriverWait wait = new WebDriverWait(d, 10);
    WebElement val = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath()));
    val.click();

    for(int i=0;i<=100;i++)
    {

        String value=val.getText();
        System.out.println("value is = "+value);
        String value1 = "Your dropdown value";
        if(value.equalsIgnoreCase(value1))
        {
            System.out.println("Got your dropdown value ");
            a.sendKeys(Keys.ENTER).build().perform();
            break;
        }
        a.sendKeys(Keys.DOWN,Keys.DOWN).build().perform();
        Thread.sleep(3000);
        a.sendKeys(Keys.ENTER).build().perform();
    }

xpath should be your dropdown box not of your dropdown value.

A: Basically when we works with anywebapplication which developed using any javascript freamwork at that w cannot get any proper element to interact.
We have to work with lots of  and .
So while selecting any value from dropdown we have to use sendkeys.
OR simple type single character and select value from suggestion list.
Above two solution works for me .
Thanks
-Dhaval


text:
Q: Comparing the active cell value to the value of the cell before it (VBA) First off, thank you for clicking into my question
I want the code to go through a list of values in a sheet called "Tests" and copy those values into a sheet called "List". The values in "Tests" are sometimes repeated though and I only want "List" to have unrepeated values.
Example:
"Tests" column A: dog, dog, cat, rabbit, rabbit, rabbit, turtle, turtle
"List" column A: dog, cat, rabbit, turtle
Can someone please point me in the right direction/ tell me where I went wrong? This is my code:
Option Explicit

Sub Main()

'create new sheet
' ActiveWorkbook.Sheets.Add

'adds a sheet and names it "List"
Sheets.Add.Name = "List"

'Select sheet1 (Tests)
Sheets("Tests").Activate

'Activate cell A2 in Tests -- not really necessary but ill leave it for now
Range("A2").Activate

'Create for loop for cells a2 through a1019
Dim cell As Integer
Dim listcell As Integer
listcell = 1

    For cell = 2 To 1019

    'create if statement for if Tests cell does match previous cell
    If (StrComp(ActiveCell.Value, ActiveCell.Offset(-1, 0).Value, vbTextCompare) = 0) Then

            ActiveWorkbook.Sheets("Tests").Range("A" & (cell + 1)).Select
            Sheets("List").Range("A" & listcell).Value = Sheets("Tests").Range("A" & cell).Value
            listcell = listcell + 1

    'else if doesn't match then write down and move to next cell in sheet
    ElseIf (StrComp(ActiveCell.Value, ActiveCell.Offset(-1, 0).Value, vbTextCompare) = 1) Then

            Application.Goto ActiveWorkbook.Sheets("List").Range("A" & cell)
            Sheets("List").Range("A" & listcell).Value = Sheets("Tests").Range("A" & cell).Value
            listcell = listcell + 1

    ElseIf (StrComp(ActiveCell.Value, ActiveCell.Offset(-1, 0).Value, vbTextCompare) = -1) Then

            Application.Goto ActiveWorkbook.Sheets("List").Range("A" & cell)
            Sheets("List").Range("A" & listcell).Value = Sheets("Tests").Range("A" & cell).Value
            listcell = listcell + 1

End If
Next
End Sub

A: If you need to use VBA as part of a bigger process that uses VBA or just don't like using functions that spill, then you can still use unique
Dim lArray As Variant
lArray = Application.WorksheetFunction.Unique(Thisworkbook.worksheets("Tests").range("A1:A1290"))

Then once you have it in a vba array, it is nearly trivial to put it somewhere else in your workbook.  You might have to trap for the case where only 1 value is unique, since that looks like it puts it in a 1D array instead of a 2D array.


text:
Q: How do you return text if a query is true in Google Sheets? I'm trying to return "Yes" if a value in Years!B:B matches a value in Pending!B:B, otherwise return "No". I've attemped this in Pending!A1 and received the error below:
"Function IF parameter 1 expects boolean values. But 'southeast asia' is a text and cannot be coerced to a boolean".
I had a partial success in Pending!A2, but I don't want to return the actual value if there is a match. Any ideas on how to curb the text/boolean issue?
Sample Sheet

A: =IF(<test>,<output if true>,<output if false>)

Therefore:
=IF(Pending!B1=Years!B1,"Yes","No") should work for you


text:
Q: User authentication with RESTAS and Hunchentoot (I use Hunchentoot and Restas, just thought that I would mention it up here too)
I don't really know how to do this stuff in general with HTTP, so I thought that maybe posting my code would be the simplest way to show my intent:
(define-route log-in ("/log-in/" :method :post)
  (multiple-value-bind (username pwd) (hunchentoot:authorization)
    (cond ((and (nth-value 1 (gethash username *users*)) ;; User exists
                (string= pwd (gethash username *users*)))) ;; Password is correct
          ;; Do something to keep track of logged in user
          )))

I basically just want to let a user log in, give him some sort of way to say "hey, it's me again" and some sort of way for me to say "Oh, hey! It is you again, here you go" and then serve the user a webpage.
I think that this should be done with cookies along with simply storing some value in a list that can be checked against the cookie.
How am I supposed to do this properly with Hunchentoot+Restas? Code and some explanation would be really awesome, I'm pretty lost here.

A: You might want to use (start-session) and then add a method like:
(defmethod handle-request :before ((acceptor acceptor) (request request))
   (unless (your-check-request-matches-login-page) ; skip session check on login page
       (if (null *session*)
          (redirect "/log-in")
          (progn
             (your-check-session-validity)
             (other-stuff)))))

The above method will work if you need to do authentication with a login page. But you need another way to get user and password from the user, as (authorization) will give you what the browser sent in the headers, and that is for basic-auth.
If you do really want to use basic-auth, then the browser will take care of poping-up a dialog to ask the user for credentials, so you don't need a login page. You need the following method, to intercept all requests and send the apropriate headers:
(defmethod handle-request :before ((acceptor acceptor) (request request))
    (multiple-value-bind (username pwd) (hunchentoot:authorization)
        (if (and (nth-value 1 (gethash username *users*)) ;; User exists
                 (string= pwd (gethash username *users*))) ;; Password is correct
            (progn
                ;; Do something here
            )

            (require-authorization "realm"))))


text:
Q: add revocation detail in pdf while signing same I am have digitally signed a pdf using digital token attached in pc using libarary itext sharp to append same, when i open same in adobe reader it shows revocation can not be performed and when i see details then it shows that one of the issuers certificate's revocation is not checked with error : error encountered while BER decoding.
path to my plain signed pdf: https://www.sendspace.com/file/vqgl53
As a solution i thought if i can add CRL information itself in document(my plain signed pdf) then i won't face this problem. So i added code mentioned in this ans : I want to sign a pdf document with ITextSharp and return ltv pdf enabled file
but I am getting exception on line : addLtvForChain(null, ocspClient, crlClient, getCrlHashKey(crlBytes));
IN SUBMETHOD getCrlHashKey ON FIRST LINE : X509Crl crl = new X509Crl(CertificateList.GetInstance(crlBytes));
Exception says :

Unknown object in GetInstance:
  Org.BouncyCastle.Asn1.DerApplicationSpecific Parameter name: obj

Kindly suggest further.

A: Extending AdobeLtvEnabling
The cause of the exception is that for one certificate the associated CRL is base64 encoded which the AdobeLtvEnabling class does not expect (the expectation here is to retrieve a binary version, no decoding required).
You can extend the AdobeLtvEnabling as follows to also be able to handle base64 encoded CRLs: search the AdobeLtvEnabling method addLtvForChain and replace the CRL handling loop
Console.WriteLine("  with {0} CRLs\n", crl.Count);
foreach (byte[] crlBytes in crl)
{
    validationData.crls.Add(crlBytes);
    addLtvForChain(null, ocspClient, crlClient, getCrlHashKey(crlBytes));
}

with this:
Console.WriteLine("  with {0} CRLs\n", crl.Count);
foreach (byte[] crlBytes in crl)
{
    PdfName hashKey = null;
    byte[] bytes = null;
    try
    {
        hashKey = getCrlHashKey(crlBytes);
        bytes = crlBytes;
    }
    catch (Exception e)
    {
        Console.WriteLine("  CRL decoding exception, assuming Base64 encoding, trying to decode - {0}\n", e.Message);
        bytes = Convert.FromBase64String(new String(Encoding.Default.GetChars(crlBytes)));
        hashKey = getCrlHashKey(bytes);
    }
    validationData.crls.Add(bytes);
    addLtvForChain(null, ocspClient, crlClient, hashKey);
}

Your signature, though
While revocation of the other non-root certificates in question now refers to embedded CRLs, for one certificate there still is an issue, the revocation tab for "SafeScrypt sub-CA for RCAI Class 2 2014 (SAFESCRYPTONLINE_15)" in Adobe Reader shows
CRL processing error
Issuer: cn=SafeScrypt CA 2014, houseIdentifier=II Floor, Tidel Park, street=No.4, Rajiv Gandhi Salai, Taramani, Chennai, st=Tamil Nadu, postalCode=600 113, ou=Certifying Authority, o=Sify Technologies Limited, c=IN
This update: 20180303183000Z
Next update: 20190303182959Z
CRL has expired or is not yet valid

Indeed, a CRL with a next update value of 20190303182959Z is expired and, therefore, cannot be used now for validation without appropriate POEs. So indeed, Adobe Reader ist completely correct in stating that based on that CRL (currently served by the PKI) it cannot determine non-Revocation.
But could it from other information? Well, there is an AIA attribute in the certificate for an OCSP responder that could alternatively be used. But an attempt to use it fails, http://ocsp.safescrypt.com currently accepts no requests. So this is no actual alternative.
All in all this makes the quality of service of this CA appear questionable. If this state continues, you might want to switch to a different CA.


text:
Q: Timestamp interval/window calculation - Pyspark I'm working on dataset where the signal is broken up every 10s even if it is continuously active with a counter that is continuous as well.
In this dataset I want know how long mode (x) was active (without a change to another mode) and how many times mode (x) was activated in a ID.
In this case the answer is.. mode (x) was activated twice. First one 23s and second 10s.I would like create two columns to show that per driveId.

ID
Timestamp(ms)
Counter
mode

A
1000
11
x

A
1010
12
x

A
1020
13
x

A
1023
7
y

A
1033
8
y

A
1037
21
x

A
1047
22
x

Result

ID
activations (x)
time1
time2

A
2
23
10

A: Did not get the way you are expecting the output. For example, if you are concerned with only how many times mode X was activated, or the timestamp is also required. Also, seems like when mode X is activated, it becomes mode Y as per your table. However, you can start with the following SQL. if you need further information, you can make this a cursor and then store the timestamp to a local/temporary variable to calculate the difference between the timestamp. Also, if you need the count, you can just use the count() function with this SQL
select * from table where counter <= 10 order by timestamp asc

A: You can achieve this by using lead on mode and checking for changes from
'x' --> 'y' and vice versa -
from pyspark import SparkContext
from pyspark.sql import SQLContext
from functools import reduce
import pyspark.sql.functions as F

from pyspark.sql import Window

sc = SparkContext.getOrCreate()
sql = SQLContext(sc)

input_list = [ ('A', 1000,'x')
              ,('A', 1010,'x')
              ,('A', 1020,'x')
              ,('A', 1023,'y')
              ,('A', 1033,'y')
              ,('A', 1037,'x')
              ,('A', 1047,'x')
            ]

sparkDF = sql.createDataFrame(input_list,['Driver_ID','Timestamp','mode'])

window = Window.partitionBy('Driver_ID').orderBy('Timestamp')

sparkDF = sparkDF.withColumn('mode_lead', F.lead(F.col('mode')).over(window))

### Condition to Identify mode change from 'x' --> 'y'
x_change_cond = ( (F.col('mode') == 'x')
                & (F.col('mode') != F.col('mode_lead'))
                )

### Condition to Identify mode change from 'y' --> 'x'
### Reason for equality is since the lag timestamp is required when mode changes from y to x

y_change_cond = ( (F.col('mode') == 'y')
                & (F.col('mode') == F.col('mode_lead'))
                )

sparkDF = sparkDF.withColumn('timestamp_diff_lead',F.lead(F.col('Timestamp')).over(window) - F.col('Timestamp'))

sparkDF = sparkDF.withColumn('timestamp_sum_x_change'
                             ,F.when(x_change_cond,F.sum(F.col('timestamp_diff_lead')).over(window)
                            ).otherwise(0)
                    )

sparkDF = sparkDF.withColumn('timestamp_sum_y_change',F.when(y_change_cond
                        ,F.sum(F.col('timestamp_diff_lead')).over(window.rowsBetween(0,Window.currentRow))
                    ).otherwise(0))

cols = ['Timestamp','mode','mode_lead','timestamp_diff_lead'
              ,'timestamp_sum_x_change','timestamp_sum_y_change']

sparkDF.select(*cols).show(truncate=False)

+---------+----+---------+-------------------+----------------------+----------------------+
|Timestamp|mode|mode_lead|timestamp_diff_lead|timestamp_sum_x_change|timestamp_sum_y_change|
+---------+----+---------+-------------------+----------------------+----------------------+
|1000     |x   |x        |10                 |0                     |0                     |
|1010     |x   |x        |10                 |0                     |0                     |
|1020     |x   |y        |3                  |23                    |0                     |
|1023     |y   |y        |10                 |0                     |10                    |
|1033     |y   |x        |4                  |0                     |0                     |
|1037     |x   |x        |10                 |0                     |0                     |
|1047     |x   |null     |null               |0                     |0                     |
+---------+----+---------+-------------------+----------------------+----------------------+

Using the above result set , you can filter on rows matching either (|) of the change conditions -
filter_cond = (F.col('timestamp_sum_x_change') != 0) | (F.col('timestamp_sum_y_change') != 0)

sparkDF.filter(filter_cond).select(*cols).show()

+---------+----+---------+-------------------+----------------------+----------------------+
|Timestamp|mode|mode_lead|timestamp_diff_lead|timestamp_sum_x_change|timestamp_sum_y_change|
+---------+----+---------+-------------------+----------------------+----------------------+
|     1020|   x|        y|                  3|                    23|                     0|
|     1023|   y|        y|                 10|                     0|                    10|
+---------+----+---------+-------------------+----------------------+----------------------+

Finally you can aggregate the filtered resultset to generate the output -
sparkDF.filter(filter_cond).groupby('Driver_ID').agg(*[ F.count(F.col('Driver_ID')).alias('activation(x)')
        ,F.max(F.col('timestamp_sum_x_change')).alias('time1')
        ,F.max(F.col('timestamp_sum_y_change')).alias('time2')
    ]
).show()

+---------+-------------+-----+-----+
|Driver_ID|activation(x)|time1|time2|
+---------+-------------+-----+-----+
|        A|            2|   23|   10|
+---------+-------------+-----+-----+


text:
Q: Chrome Javascript i have two spans on my page with class='hidden' and then some javascript to remove the class when a condition is met, its working fine in ie 9/10 and firefox but its not working in chrome when I run the function in the chrome JS console I get the message TypeError: Cannot read property 'attributes' of null
Anybody know whats going on?
<script type='text/javascript' >
function showhidden()   {

        var att =document.getElementById('hiddentextbox');
        att.attributes[0].value='';
        att =document.getElementById('hiddentextbox1');
        att.attributes[0].value='';
}</script>

Thanks

A: Try changing the class by using att.className = '' instead of what you're doing, which I have never seen before.
You might also want to check out jQuery, which has good built-in .show() and .hide() functions.

A: It can't find document.getElementById('hiddentextbox'); therefore it can't find attributes of null, because non-found element is null. I believe that is the problem.


text:
Q: checkSelfPermission is not working properly I'm trying to do a quick test app that allow me to turn on a off Bluetooth and I code the listeners for clicks in the buttons. This is the one that turn Bluetooth on:
mOnBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!mBlueAdapter.isEnabled()) {
                showToast("Turning On Bluetooth...");
                //intent to on BT
                Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                //Android Studio force me to do this check.
                if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    showToast("I'm stuck here");
                    return;
                }
                startActivityForResult(intent, REQUEST_ENABLE_BT);
            } else {
                showToast("Bluetooth is already on");
            }
        }
    });

The thing is that Android Studio force me to add the:
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
                    showToast("I'm stuck here");
                    return;
                }

check error but even I have all the permissions they asked me in AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />

<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.Bluetooth">
    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

the program always fails the check error and ended up in the "You're stuck message", what is happening here?

A: Turning bluetooth on and requesting `BLUETOOTH_CONNECT permission is a different thing.
Request permission like BLUETOOTH_CONNECT, see https://developer.android.com/training/permissions/requesting.
Turning bluetooth on
if (bluetoothAdapter?.isEnabled == false) {
  val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
  startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT)
}

If enabling Bluetooth succeeds, your activity receives the RESULT_OK result code in the onActivityResult() callback. If Bluetooth was not enabled due to an error (or the user responded "Deny") then the result code is RESULT_CANCELED.

See Set up Bluetooth for details.


text:
Q: Regex for two words I'm not able to create a regex for capture two separate words.
For example the pattern must contain the word (pizza)+ and (cheese|tomatoes)* like this:
I want eat a pizza with cheese
capture:
pizza, cheese

How can I do that?

A: Use re.findall. It will return all matched strings.
>>> import re
>>> re.findall(r'\b(pizza|cheese|tomatoes)\b', 'I want eat a pizza with cheese')
['pizza', 'cheese']


text:
Q: Configuring PHP for PostgreSQL and IIS I have PHP v7.2.7 and PostgreSQL v10 with IIS.
I am trying to get this to work following any advice I have been able to find on the web, but with no success. My configuration so far is as below.
PHP.ini extension list includes both php_pdo_pgsql.dll and php_pgsql.dll.
Both these dlls are located in the correct extensions directory according to phpinfo.
According to phpinfo the Configuration File Path is  "C:\Windows" and the Loaded Configuration File is  "C:\Program Files\PHP\v7.2\php.ini". I have the same php.ini file at both locations.
I have copied the version of libpq.dll from the lib folder of the postgresql installation to the root folder of the PHP installation.
I have added the bin folder of the postgresql installation to the Windows system search path.
Phpinfo shows that pdo_pgsql extension is loaded but not pgsql.
Can anyone please shed any light on what more I need to do?


text:
Q: IBM DevOps Pipeline: How to Access Artifacts from Previous Job? I have a build stage as shown below with two build jobs, a frontend and a backend job. How do I directly access the Build Archive Directory of the frontend job from the backend job's build script?
I need to access the frontend build artifacts in order to properly build the final archive. And I can see all the artifacts show up in the Artifacts tab for the frontend build. But how do I access that from the second job, i.e. backend build?
I saw here that there is an Environment variable to access the current job's archive dir, but I need to access the other jobs archive dir.

A: Currently, both jobs inside a stage are run in complete separate environments.  They do not have access to the artifacts of the other jobs in the stage.  The way to get around this is to create a new stage for the 'backend' job, and then set the input for that stage to be the build artifacts from the 'frontend' job


text:
Q: json object in javascript to get only the value where value is I have this objects
{"event":"auth success"}
{"event":"status","args":["running"]}
{"event":"console output","args":["openjdk version \"11.0.10\" 2021-01-19"]}
{"event":"console output","args":["OpenJDK Runtime Environment 18.9 (build 11.0.10+9)"]}
{"event":"console output","args":["OpenJDK 64-Bit Server VM 18.9 (build 11.0.10+9, mixed mode, sharing)"]}

I am use this in javascript
    var JSONObject = JSON.parse(event.data);
    var theDiv = document.getElementById("cli");
    theDiv.innerHTML += "
"+JSONObject["args"]+"
";

and the outcome is this
undefined
running
openjdk version "11.0.10" 2021-01-19
OpenJDK Runtime Environment 18.9 (build 11.0.10+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.10+9, mixed mode, sharing)

How can i get only the value of args where event = "console output"

A: Assuming you are getting the objects one by one in your event stream, you can do this:

var json = `{"event":"console output","args":["OpenJDK Runtime Environment 18.9 (build 11.0.10+9)"]}`;

var JSONObject = JSON.parse(json);
var theDiv = document.getElementById("cli");
if(JSONObject.event === "console output") {
  theDiv.innerHTML += "
" + JSONObject["args"] + "
";
}

On the other hand, if you are getting the objects in the exact format you've posted (which would be invalid JSON), then you need to split them by the newline character, then parse each object separately:
var JSONObjects = json.split("\n").map(line => JSON.parse(line));
console.log(JSONObjects);
JSONObjects.forEach(obj => {
  var theDiv = document.getElementById("cli");
  if (obj.event === "console output") {
    theDiv.innerHTML += "
" + JSONObject["args"] + "
";
  }
});

A: socket.onmessage = function (event) {
            var theDiv = document.getElementById("cli");
            var getCli = event.data.replaceAll("\u003e\u001b[2K\r", "");
            var JSONObject = JSON.parse(getCli);
            if(JSONObject.event === "console output") {
                theDiv.innerHTML += "
" + getCli + "
";

            }
        };

output
{"event":"console output","args":["\u003e\u001b[2K\r[16:11:16] [Server thread/INFO]: [Server] hoi"]}

Why is it not replacing?


text:
Q: Comparing two sets of cells within a row and highlighting same-row duplicates in Excel I've got a somewhat specific task I'm trying to accomplish in Excel that appears to be beyond my depth.  I've got a dataset with two five-word lists per each row/observation, like this example:

What I'm hoping to accomplish is to highlight all of the words that are in both 5-word lists within a single row.  The amount of overlap between these two five-words lists varies from one row to the next.  And I'm not concerned with identifying any duplicate entries across different rows.  That is, it'd be great if it's possible to create a macro that would give this:

I've searched quite a bit on this site and using google to figure out how to create a macro to do this.  I've found a number of similar macros, but every one that I've found is geared towards identifying all of the duplicates between two entire sheets, or two entire columns, or something similar, which doesn't quite match what I'm trying to do.  Based on the macros I have been able to find, I get the sense that doing what I want should be possible, but I don't know enough about visual basic to edit the macros I've found to suit my needs.
If it's possible to program a macro to do this, it'd save me quite a bit of time, since otherwise I'm looking at doing this duplicate-identification manually for two current datasets that I have (each with 150-200 observations), plus I plan on collecting data in the future that would require this same procedure.  Beyond that, any macro that's capable of helping me here may be able to help others with similar needs.
Thanks in advance for any help you're able to provide!

A: Try conditional formatting.
Select "table 2" (e.g. I2:Mn where n is the last row) with I2 (upper left corner) being the active cell.  Then use this formula:
=OR(I2=$C2:$G2)

A: I think using Conditional Formatting is maybe a simpler solution but one way to do this using VBA is as follows:
Sub HighlightDuplicates()
    Dim masterList(), highlightList(), rw As Long, col As Long

    masterList = Range("C1:G150")
    highlightList = Range("I1:M150")

    For rw = 1 To UBound(masterList, 1)
       For col = 1 To UBound(masterList, 2)
            If highlightList(rw, col) = masterList(rw, col) Then
                Cells(rw, col).Offset(0, 8).Interior.Color = vbRed
            End If
        Next col
    Next rw
End Sub

Here we read both lists in as arrays and then iterate over them to check for matches.
The Offset(0, 8) is a bit of a magic number (yikes!) which gets the correct cell highlighted based on your layout.


text:
Q: AppRTC is showing duplicate symbol for architecture x86_64 I've a unique problem. I'm including the AppRTC in my project via. podfile. It is successfully getting installed and along with it libjingle_peerconnection and SocketRocket libraries are also getting installed. However when I build my project it shows duplicate symbol error for libWebRTC.a and gives the following message -->

duplicate symbol _RTCFileName in:
      (My project path)/Pods/libjingle_peerconnection/libjingle_peerconnection/libWebRTC.a(libjingle_peerconnection_objc.RTCLogging.o)
       (My project path)/Pods/libjingle_peerconnection/libjingle_peerconnection/libWebRTC.a(rtc_base_objc.RTCLogging.o)
  duplicate symbol _RTCLogEx in:
       (My project path)/Pods/libjingle_peerconnection/libjingle_peerconnection/libWebRTC.a(libjingle_peerconnection_objc.RTCLogging.o)
       (My project path)/Pods/libjingle_peerconnection/libjingle_peerconnection/libWebRTC.a(rtc_base_objc.RTCLogging.o)
  duplicate symbol _RTCSetMinDebugLogLevel in:
       (My project path)/Pods/libjingle_peerconnection/libjingle_peerconnection/libWebRTC.a(libjingle_peerconnection_objc.RTCLogging.o)
       (My project path)/Pods/libjingle_peerconnection/libjingle_peerconnection/libWebRTC.a(rtc_base_objc.RTCLogging.o)
  duplicate symbol __Z27RTCGetNativeLoggingSeverity18RTCLoggingSeverity in:
       (My project path)/Pods/libjingle_peerconnection/libjingle_peerconnection/libWebRTC.a(libjingle_peerconnection_objc.RTCLogging.o)
       (My project path)/Pods/libjingle_peerconnection/libjingle_peerconnection/libWebRTC.a(rtc_base_objc.RTCLogging.o)
  ld: 4 duplicate symbols for architecture x86_64
  clang: error: linker command failed with exit code 1 (use -v to see invocation)

I've tried everything related to this but with no success. So please help me to solve it or atleast tell why this is happening.


text:
Q: Convert Event based pattern to async CTP pattern   _fbClient.GetCompleted += new EventHandler<FacebookApiEventArgs>(OnFetchPageNotification);
  _fbClient.GetAsync(_kNotificationPath, new Dictionary<string, object> { { "access_token", _kPageAccessToken } });

How to convert above code into awaitable code in wp7:
 object = await _fbClient.GetAsync(_kNotificationPath, new Dictionary<string, object> { { "access_token", _kPageAccessToken } });

I have CTP Installed and task parallel library also.

A: The Async CTP came with a document that describes how to adapt each existing pattern to the Task Based Async pattern. It says that the Event based one is more variable, but does give one example:
public static Task<string> DownloadStringAsync(Uri url)
{
    var tcs = new TaskCompletionSource<string>();
    var wc = new WebClient();
    wc.DownloadStringCompleted += (s,e) =>
    {
        if (e.Error != null) tcs.TrySetException(e.Error);
        else if (e.Cancelled) tcs.TrySetCanceled();
        else tcs.TrySetResult(e.Result);
    };
    wc.DownloadStringAsync(url);
    return tcs.Task;
}

Where the original function that's being wrapped is DownloadStringAsync, the parameters match the parameters being passed to this function, and DownloadStringCompleted is the event that is being monitored.

(The same document appears to be downloadable here - the above sample (and more description) are from "Tasks and the Event-based Asynchronous Pattern (EAP)")


text:
Q: Does SQLite support bulk-loading (sort-then-indexing)? When constructing indexing tree from existing data, there is a bulk-loading algorithm, like

*

*https://en.wikipedia.org/wiki/B%2B_tree#Bulk-loading

*https://www.youtube.com/watch?v=HJgXVxsO5YU
When creating an index for a non-empty table, does SQLite use bulk-loading or create indexing by insertions? From my performance test, it seems that SQLite uses insertion to create indexing because the time costs between inserting table after indexing and creating indexing after insertion are similar.
Do we know why bulk-loading is not used? Does it not work well in practice?

A: Bulk loading requires that the data is already sorted.
SQLite implements sorting by inserting the rows into a temporary index, so using it for bulk loading would not be productive.


text:
Q: GameScene not rendering correctly on iPhone 5/5S I am trying to show a background image in my GameScene. When I go to run it, it displays fine on every device except an iPhone 5/5S. Below are screenshots showing what it looks like on an iPhone 4s and an iPhone 5 from the simulator.

This is how I show the background image:
    // set background image
    let backgroundImage = SKSpriteNode(imageNamed: "bg")
    backgroundImage.position = CGPointMake(frame.size.width/2, frame.size.height/2)
    addChild(backgroundImage)

I've tested it on the simulator and actual devices and still have this problem.


text:
Q: show/hide dynamic content with parameter in Wordpress I am trying to create a second hidden page within my post which will be shown on specific parameters.
Here is the code I am using in singe.php

        <?php the_content(); ?>

<?php the_title(); ?>

content of section 1 is just for an example.
this is javascript jquery code,

I need to know, do I am going well. Is there any good way to do that?