text:
Q: Decimal conversion number of the form x.xx to 0x.xx, sed? I have a file of the form
...
num  0.12 num num
num 25.53 num num
num  7.82 num num
...

and I want to convert the 2nd field of each line adding a "0" at the numbers >= 0 and < 10 so the output will have the form:
...
num 00.12 num num
num 25.53 num nnum
num 07.82 num num
...

I tried with
sed 's/ 7./07./2'

but it is not white space sensitive so it replaces any occurance of "7."

A: With awk:
$ awk '$2 = sprintf("%05.2f",$2)' file
num 00.12 num num
num 25.53 num num
num 07.82 num num

A: What you are after is probably something like:
sed 's/ \([0-9]\.\)/0\1/'

It matches a space followed by one digit from the range 0 to 9 followed by a dot and replaces the space by the 0. The parentheses \([0-9]\.\) mark a group which is referenced by \1 in the replacement part of the expression.

A: What if you use awk?
$ awk '$2>0 && $2<10 {$2="0"$2}1' file
num 00.12 num num
num 25.53 num num
num 07.82 num num

A: Pure shell:
while read a b rest; do
    b=$(printf "%05.2f" $b);
    echo "$a $b $rest";
done < file.txt


text:
Q: Setting MauiSplashScreen tag on MyMauiProject.csproj with a mp4 file throw null exception from Resizetizer/SkiaSharpBitmapTools, looks hardcoded trash Setting the MauiSplashScreen tag inside my net6.0 MyMauiProject.csproj pointing to a mp4 file makes it throw a null exception from Resizetizer/SkiaSharpBitmapTools. It looks like hardcoded trash from Microsoft. I don't even have a 'D:' drive on my machine, just 'C:', but the error points to D:\a\1\s\src\SingleProject\Resizetizer\src\SkiaSharpBitmapTools.cs:line 29 , a project I never created.
Was searching like a crazy on google, but there is nothing about it.
Even after it changes back to a gif and also changes to a svg, the error stays there.
Thinking about recreating the project and copying my source code to see if it fixes it, but I cant do it every time and that isn't a good solution.
I'm on a tight deadline project. I can't do in on Xamarin Forms because MS is discontinuing it and looks I can't do on MAUI too.
Severity    Code    Description Project File    Line    Suppression State
Error   MAUI0000    System.NullReferenceException: Object reference not set to an instance of an object.
   at Microsoft.Maui.Resizetizer.SkiaSharpBitmapTools.GetOriginalSize() in D:\a\1\s\src\SingleProject\Resizetizer\src\SkiaSharpBitmapTools.cs:line 29
   at Microsoft.Maui.Resizetizer.SkiaSharpTools.Resize(DpiPath dpi, String destination) in D:\a\1\s\src\SingleProject\Resizetizer\src\SkiaSharpTools.cs:line 47
   at Microsoft.Maui.Resizetizer.Resizer.Resize(DpiPath dpi, String inputsFile) in D:\a\1\s\src\SingleProject\Resizetizer\src\Resizer.cs:line 101
   at Microsoft.Maui.Resizetizer.ResizetizeImages.ProcessImageResize(ResizeImageInfo img, DpiPath[] dpis, ConcurrentBag`1 resizedImages) in D:\a\1\s\src\SingleProject\Resizetizer\src\ResizetizeImages.cs:line 172
   at Microsoft.Maui.Resizetizer.ResizetizeImages.<>c__DisplayClass26_0.<ExecuteAsync>b__0(ResizeImageInfo img) in D:\a\1\s\src\SingleProject\Resizetizer\src\ResizetizeImages.cs:line 88
   at Microsoft.Maui.Resizetizer.AsyncTaskExtensions.<>c__DisplayClass0_0`1.<ParallelForEach>b__0(TSource s) in D:\a\1\s\src\SingleProject\Resizetizer\src\AsyncTaskExtensions.cs:line 21   MyMauiProject   C:\Users\MySelf\.nuget\packages\microsoft.maui.resizetizer.sdk\6.0.101-preview.11.2349\build\Microsoft.Maui.Resizetizer.Sdk.targets 463

When clicking on the error, the IDE points to:
<!-- Resize the images -->
<ResizetizeImages
    PlatformType="$(ResizetizerPlatformType)"
    IntermediateOutputPath="$(_MauiIntermediateImages)"
    InputsFile="$(_ResizetizerInputsFile)"
    Images="@(MauiImage->Distinct())">
</ResizetizeImages>

I never ever touched on this block.
Closing and opening Visual Studio/Project doesnt fix it either.
It looks like it's pointing to here.

A: I had exactly the same issue.  The problem was that I had a non-image file (ie a file called list.txt) in the Resources/Images folder.
Removing the file fixed the issue and the code ran correctly.

A: Another person had a related error here, the solution was reinstall all environment.
I Think you realized the error isnt with your code but with: C:\Users\MySelf\.nuget\packages\microsoft.maui.resizetizer.sdk\6.0.101-preview.11.2349

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deploying a static site built from Create React App on Elastic Beanstalk Edit
Ok so I changed the run command to ls -la && serve -s build to make sure the build folder exists, and it turns out the folder doesn't exist and that's obviously why it was failing to serve.
Why is my build folder not coming through? I thought the build folder should be created during the build phase (like it does when i run npm build locally) and then forwarded to Elastic Beanstalk because I specified "**/*" in buildspec.yml.
Background
I'm trying to deploy my personal blog website created from create-react-app on elastic beanstalk on AWS. I've set up the code pipeline and code pipeline works (tested with the example application). With my own app, everything works (no red flag), except that the server is failing to serve the website for some reason. It shows 404 | The requested path could not be found error.
Basic Structure
The pipeline:
github -> aws codebuild -> aws elastic beanstalk
I have a very simple react app which is a simple website. I basically build this react app (npm run build), and serve using serve npm package using serve -s build command. I used to host this in Heroku and it worked fine. (If I upload the same codebase that does not work on Elastic Beanstalk to Heroku, it works fine.)
What I tried
So if I look at the logs, it all works fine and log even says: Accepting connections at http://localhost:8080. Logs:
Jan 19 03:26:12 ip-172-31-37-45 web: > my-blog@0.1.0 serve /var/app/current
Jan 19 03:26:12 ip-172-31-37-45 web: > serve -s ./
Jan 19 03:26:13 ip-172-31-37-45 web: INFO: Accepting connections at http://localhost:8080
Jan 19 03:31:25 ip-172-31-37-45 web: INFO: Gracefully shutting down. Please wait...
Jan 19 03:31:29 ip-172-31-37-45 web: > my-blog@0.1.0 serve /var/app/current
Jan 19 03:31:29 ip-172-31-37-45 web: > serve -s ./build
Jan 19 03:31:29 ip-172-31-37-45 web: INFO: Accepting connections at http://localhost:8080

So I tried to just put a very simple index.html file in the root directory, and tried to serve it using the same structure except now the serve command is serve -s ./ to serve from the root. And it worked!
But if I change serve command to serve -s build then it shows 404 | The requested path could not be found error.
serve command serves index.html in the folder, and the build folder has it... not sure what is wrong. Any help will be greatly appreciated!!
ETC
In case my buildspec is wrong:
version: 0.2

phases:
  install:
    commands:
      - echo Installing source NPM dependencies...
      - npm install
  build:
    commands:
      - echo Build started on `date`
      - npm run build
  post_build:
    commands:
      - echo Build completed on `date`
artifacts:
  files:
    - '**/*'

I'm just sending all files to elastic beanstalk for now.

A: Okay, so it was my configuration in code pipeline. In the sequence of Source -> Build -> Deploy, we define for each stage, what input data to use. In my case, my Deploy step was still using output from Source stage, not the build artifact. What I had to do is:

*

*Go to AWS pipeline settings

*Edit the build stage: I gave a name to the output of build stage (in case of me I named it to be build). FYI, initially it was empty.

*Edit the deploy stage: I switched the input source from the output of Source to the output of build (which is the name you used in Step 2).

Then all was well.
In my case, when I created my pipeline I only created Source and Deploy steps at first, and then added the build stage later. So I guess deploy was initialised to take input from Source.
So it was pretty much just my mistake and lack of understanding of how pipeline works. Ouch.
Hope it helps someone, somewhere, someday.


text:
Q: Google autocomplete, multiple pages I've come across a little problem with autocomplete. I use a base.jsp page which has the following in a init function:
var input = document.getElementById('addressField');
var autocomplete = new google.maps.places.Autocomplete(input, {
    types: ["geocode"]
});

autocomplete.bindTo('bounds', map);

I got two pages, one.jsp and two.jsp.
ons.jsp contains the following input type, which is tied to the autocomplete. This one works.
<input type="text" class="form-control" name="address"  aria-label="..." id="addressField" value="">

two.jsp as the exacty same. But this one does not work?
<input type="text" class="form-control" name="address" aria-label="..." id="addressField"  value="">

I do not understand how two identical input fields can have one working and one not. Both share the same base, and the autocomplete initialization.
What can possible cause this? I've got no idea where to look-

A: Here's where I'd start:
var input = document.getElementById('addressField');
console.log(input);
var autocomplete = new google.maps.places.Autocomplete(input, {
    types: ["geocode"]
});
console.log(autocomplete);
console.log(map);
autocomplete.bindTo('bounds', map);
console.log('--------------- Done -----------');
console.log(input);

Then look at the output of the browser log and see what's different.  Computers only do what we tell them :-)


text:
Q: Command from java program package src;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Command
{
    public static void main(String args[])
    {
        try
        {
            Process p=Runtime.getRuntime().exec("cmd /c dir");
            p.waitFor();
            BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line=reader.readLine();
            while(line!=null)
            {
                System.out.println(line);
                line=reader.readLine();
            }

        }
        catch(IOException e1) {}
        catch(InterruptedException e2) {}

        System.out.println("Done");
    }
}

I tried to run this code but it is not able to execute anything. Are there some classpath or other settings i need to do to make this work?

A: remark the line:
p.waitFor();

and re-run.
You also might want to read this


text:
Q: Data is lost after deleting the vault-0 pod for hashivault We are deploying vault as helm based deployment. We have configure/enabled the server datastorage mountpath also.
After deployment a new pvc is also getting created and getting bound to local-storage PV.
data-vault-0   Bound    local-pv-f69fbb0   10Gi       RWO            local-storage   69s
local-pv-f69fbb0          10Gi       RWO            Delete           Bound         vault/data-vault-0                                local-storage            2m55s

But when we are deleting the pod vault-0 and once it comes back, then we are loosing all the data(secrets, configurations,policies) we created in vault.
Even though pv,pvc remains intact after deleting the pod.
vault-0 server config
 Mlock: supported: true, enabled: false
       Recovery Mode: false
             Storage: file
             Version: Vault v1.11.3, built 2022-08-26T10:27:10Z


text:
Q: Сортировка многомерного ассоциативного массива по возрастанию значения ключа У меня есть этот массив:
$arr['success'][] = array(

    "id"        => $out[$c_id],
    "nick"      => $out[$c_nick],
    "inv"       => $out[$c_inv]

);

Мне необходимо отсортировать по возрастанию вывод из "inv", как это можно реализовать?

A: function cmp ($ALeft, $Aright) {
  if ($ALeft['inv'] < $Aright['inv'])
    return -1;
  if ($ALeft['inv'] == $Aright['inv'])
    return 0;
  return 1;
}

usort($arr['success'], 'cmp');


text:
Q: Open an ASCII file wtih textscan matlab I am trying to open an ASCII file in MATLAB using textfile. It's a very large file with 13 rows of string headers and a 1399 by 1399 matrix of floating point numbers. Some value are blank but I cannot know which ones. The file has comma separated values.
fid = fopen (filename);
Zs = textscan (fid, '%f' , 'Bufsize' ,1000000 , 'Delimiter' , ',' , 'EmptyValue',0);
fclose (fid);

Zs is only a 1*1 matrix with the first number. I would really appreciate some indications which can help me.


text:
Q: Select points in a ZedGraph graph by dragging the mouse I would like to select points on my curve by dragging a square with my mouse. Of course I can build this myself, but I was wondering if it can be done easier?

A: Unfortunately not. You would have to do it by yourself. ZG doesn't provide any more sophisticated tools for interaction.
You would probably need to subscribe for "mouse down" and "mouse up" events, perform the reverse transform of found points and then find all points in range (i.e. by searching inside the Points collection of your curve(s)).
Just remember, that the action you described is by default connected width zooming and you would have to disable it.


text:
Q: How do I find the properties of a resource with azure resource manager How can I see the configuration of a resource in a resource group? I've provisioned a database through the portal and I'd like to see what that configuration is in the template language.

A: You can use the Azure Resource Manager REST API to list the template deployments for your resource group. A reference to the API is here.
Near the top of the response is a templateLink that you can follow to get the deployment template. For example, this is what I get back for one of my deployments where I used the Web App + SQL Database configuration from the Azure Portal to create a new web app.


text:
Q: window.showModalDialog returnvalue is undefined in localhost but is working when deployed in server I have a very old asp.net application where we are using window.showModalDialog for popups. The return value is always undefined when running from localhost (either using visual studio 2013 or deployed in IIS 7.0) but the same code when deployed in server (2008 R2), all the popups are returning values and is working fine. I do not have any error that I can paste here.
Tried running application using ip address and localhost.
I have looked at other links where they have an opposite issue - working in localhost but return value undefined in server.


text:
Q: What is the purpose of AccountManager (android)? Does it bypass the need to use OAUTH or OPENID for authentication on an android app?

A: Purpose of this class it to help organize access and manage accounts stored on particular phone. Those accounts does not have to be connected in any way to some internet accounts/services. Accounts might be used to distinguish different phone users.
Also AccountManager does not provide any ease of authentication methods, you need to make them by yourself and by different class.
Please have a look here
http://www.finalconcept.com.au/article/view/android-account-manager-step-by-step
and here
http://developer.android.com/reference/android/accounts/AbstractAccountAuthenticator.html


text:
Q: Eliminar datos duplicado en columnas sql tengo los siguientes datos que recolecto de una tabla temporal como ven son los días en la cual realizan sus labores el problema se da básicamente desde el día lunes al domingo cuando realizan mas de 2 labores ya sea por hora o por avance y el resultado es lo visto en la imagen con el código 2256 y aquí es donde tengo la necesidad de poder eliminar estos duplicados porque posteriormente se hace una agrupación para un listado de persona que asistieron a laborar.

Aquí coloco el código que me trae los datos a la tabla temporal, el problema estaría en la vista que hago previo a seleccionar los datos
IF OBJECT_ID('TEMPDB..#CUADROCOMP') IS NOT NULL
BEGIN
    DROP TABLE #CUADROCOMP;
END

SET LANGUAGE SPANISH;
CREATE TABLE #CUADROCOMP (
EMPLCOD INT,
SUPERVISOR VARCHAR(50),
AREA VARCHAR(50),
LUNES VARCHAR(50),
MARTES VARCHAR(50),
MIERCOLES VARCHAR(50),
JUEVES VARCHAR(50),
VIERNES VARCHAR(50),
SABADO VARCHAR(50),
DOMINGO VARCHAR(50));

INSERT INTO #CUADROCOMP(AREA,SUPERVISOR,LUNES,MARTES,MIERCOLES,JUEVES,VIERNES,SABADO,DOMINGO,EMPLCOD)
         SELECT
          (SELECT ISNULL(CASE WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='EMPAQUE MANUAL PAGO POR DIA') THEN 'EMPAQUE            '
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='EMPAQUE NORMAL') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='EMPAQUE MANUAL 2') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='EMPAQUE MANUAL') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='COCINA PAGO POR DIA') THEN 'COCINA'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='COCINA POR HORA') THEN 'COCINA'
                             WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='CAMARA PAGO POR DIA') THEN 'CAMARA' END,
         (SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)))AS AREA,
        (SELECT DISTINCT(S.NOM_SUPERVISOR) FROM
  TBL_SECCION D
  INNER JOIN
  TBL_SUPERVISOR S
  ON S.COD_AREA= D.ID_CODIGO AND E.AREA = S.COD_AREA) AS SUPERVISOR ,
        E.LUNES AS LUNES,
        E.MARTES AS MARTES,
        E.MIERCOLES AS MIERCOLES,
        E.JUEVES AS JUEVES,
        E.VIERNES AS VIERNES,
        E.SABADO AS SABADO,
        E.DOMINGO AS DOMINGO,
        E.COD AS COD
        FROM HIS_MOV_PROD MH INNER JOIN
        (SELECT E.EMPL_AREA AS AREA,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA='06/01/2020'))  AS LUNES,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA='07/01/2020')) AS MARTES,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA='08/01/2020')) AS MIERCOLES,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA='09/01/2020')) AS JUEVES,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA='10/01/2020')) AS VIERNES,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA='11/01/2020')) AS SABADO,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA='12/01/2020')) AS DOMINGO,
        E.EMPL_FECH_AF AS EMPL_FEC,
        (SELECT DISTINCT E.EMPL_COD )AS COD
        FROM TBL_EMPLEADO E INNER JOIN HIS_MOV_PROD MH ON MH.Mov_CodEmpleado=E.EMPL_COD AND E.EMPL_FECH_AF=0 AND (MH.Mov_Fecha='06/01/2020' OR MH.Mov_Fecha='07/01/2020' OR MH.Mov_Fecha='08/01/2020'
        OR MH.Mov_Fecha='09/01/2020' OR MH.Mov_Fecha='10/01/2020' OR MH.Mov_Fecha='11/01/2020' OR MH.Mov_Fecha='12/01/2020')
        GROUP BY E.EMPL_COD,E.EMPL_FECH_AF,E.EMPL_AREA)
        E ON MH.Mov_CodEmpleado = E.COD
        GROUP BY E.AREA,E.COD,E.LUNES,E.MARTES,E.MIERCOLES,E.JUEVES,E.VIERNES,E.SABADO,E.DOMINGO
        ORDER BY AREA

INSERT INTO #CUADROCOMP(AREA,SUPERVISOR,LUNES,MARTES,MIERCOLES,JUEVES,VIERNES,SABADO,DOMINGO,EMPLCOD)
         SELECT
          (SELECT ISNULL(CASE WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='EMPAQUE MANUAL PAGO POR DIA') THEN 'EMPAQUE            '
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='EMPAQUE NORMAL') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='EMPAQUE MANUAL 2') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='EMPAQUE MANUAL') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='COCINA PAGO POR DIA') THEN 'COCINA'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='COCINA POR HORA') THEN 'COCINA'
                             WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='CAMARA PAGO POR DIA') THEN 'CAMARA'    END,
         (SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )))AS AREA,
        (SELECT DISTINCT(S.NOM_SUPERVISOR) FROM
  TBL_SECCION D
  INNER JOIN
  TBL_SUPERVISOR S
  ON S.COD_AREA= D.ID_CODIGO AND E.AREA = S.COD_AREA) AS SUPERVISOR ,
        E.LUNES AS LUNES,
        E.MARTES AS MARTES,
        E.MIERCOLES AS MIERCOLES,
        E.JUEVES AS JUEVES,
        E.VIERNES AS VIERNES,
        E.SABADO AS SABADO,
        E.DOMINGO AS DOMINGO,
        E.COD AS COD
        FROM HIS_MOV_HORA MH INNER JOIN
        (SELECT E.EMPL_AREA AS AREA,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA='06/01/2020'))  AS LUNES,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA='07/01/2020')) AS MARTES,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA='08/01/2020')) AS MIERCOLES,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA='09/01/2020')) AS JUEVES,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA='10/01/2020')) AS VIERNES,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA='11/01/2020')) AS SABADO,
        (SELECT DISTINCT Mov_CodEmpleado FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA='12/01/2020')) AS DOMINGO,
        E.EMPL_FECH_AF AS EMPL_FEC,
        (SELECT DISTINCT E.EMPL_COD )AS COD
        FROM TBL_EMPLEADO E INNER JOIN HIS_MOV_HORA MH ON MH.Mov_CodEmpleado=E.EMPL_COD AND E.EMPL_FECH_AF=0 AND (MH.Mov_Fecha='06/01/2020' OR MH.Mov_Fecha='07/01/2020' OR MH.Mov_Fecha='08/01/2020'
        OR MH.Mov_Fecha='09/01/2020' OR MH.Mov_Fecha='10/01/2020' OR MH.Mov_Fecha='11/01/2020' OR MH.Mov_Fecha='12/01/2020')
        GROUP BY E.EMPL_COD,E.EMPL_FECH_AF,E.EMPL_AREA)
        E ON MH.Mov_CodEmpleado=E.COD
        GROUP BY E.AREA,E.EMPL_FEC,E.COD,E.LUNES,E.MARTES,E.MIERCOLES,E.JUEVES,E.VIERNES,E.SABADO,E.DOMINGO

; WITH VISTA AS (SELECT

    AREA,
 SUPERVISOR,
LUNES AS LUNES,
MARTES AS MARTES,
MIERCOLES AS MIERCOLES,
 JUEVES AS JUEVES,
VIERNES AS VIERNES,
SABADO AS SABADO,
DOMINGO AS DOMINGO
FROM
    #CUADROCOMP
    )

SELECT
DISTINCT * FROM VISTA ORDER BY SUPERVISOR

De antemano agradezco su colaboración.

A: Después de varios días tratando de obtener la solución termine dando con ella y como buen compañero adjunto el código ya implementado como procedimiento y con su respectiva captura de que realiza lo solicitado.
ALTER PROCEDURE [dbo].[CuadroComparativoEventualHis]
@FECHAL VARCHAR(10),
@FECHAMA VARCHAR(10),
@FECHAMI VARCHAR(10),
@FECHAJU VARCHAR(10),
@FECHAVI VARCHAR(10),
@FECHASA VARCHAR(10),
@FECHADO VARCHAR(10)
AS
IF OBJECT_ID('TEMPDB..#CUADROCOMP') IS NOT NULL
BEGIN
    DROP TABLE #CUADROCOMP;
END

SET LANGUAGE SPANISH;
CREATE TABLE #CUADROCOMP (
EMPLCOD INT,
SUPERVISOR VARCHAR(50),
AREA VARCHAR(50),
LUNES VARCHAR(50),
MARTES VARCHAR(50),
MIERCOLES VARCHAR(50),
JUEVES VARCHAR(50),
VIERNES VARCHAR(50),
SABADO VARCHAR(50),
DOMINGO VARCHAR(50));

INSERT INTO #CUADROCOMP(AREA,SUPERVISOR,LUNES,MARTES,MIERCOLES,JUEVES,VIERNES,SABADO,DOMINGO,EMPLCOD)
         SELECT
          (SELECT ISNULL(CASE WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='EMPAQUE MANUAL PAGO POR DIA') THEN 'EMPAQUE            '
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='EMPAQUE NORMAL') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='EMPAQUE MANUAL 2') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='EMPAQUE MANUAL') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='COCINA PAGO POR DIA') THEN 'COCINA'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='COCINA POR HORA') THEN 'COCINA'
                             WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='CAMARA PAGO POR DIA') THEN 'CAMARA' END,
         (SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)))AS AREA,
        (SELECT DISTINCT(S.NOM_SUPERVISOR) FROM
  TBL_SECCION D
  INNER JOIN
  TBL_SUPERVISOR S
  ON S.COD_AREA= D.ID_CODIGO AND E.AREA = S.COD_AREA) AS SUPERVISOR ,
E.LUNES AS LUNES,
        E.MARTES AS MARTES,
        E.MIERCOLES AS MIERCOLES,
        E.JUEVES AS JUEVES,
        E.VIERNES AS VIERNES,
        E.SABADO AS SABADO,
        E.DOMINGO AS DOMINGO,
        E.COD AS COD
        FROM HIS_MOV_PROD MH INNER JOIN
        (SELECT E.EMPL_AREA AS AREA,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHAL))  AS LUNES,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHAMA)) AS MARTES,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHAMI)) AS MIERCOLES,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHAJU)) AS JUEVES,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHAVI)) AS VIERNES,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHASA)) AS SABADO,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_PROD WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHADO)) AS DOMINGO,
        E.EMPL_FECH_AF AS EMPL_FEC,
        E.EMPL_COD AS COD
        FROM TBL_EMPLEADO E INNER JOIN HIS_MOV_PROD MH ON MH.Mov_CodEmpleado=E.EMPL_COD AND E.EMPL_FECH_AF=0 AND E.EMPL_COD != 1543 AND (MH.Mov_Fecha=@FECHAL OR MH.Mov_Fecha=@FECHAMA OR MH.Mov_Fecha=@FECHAMI
        OR MH.Mov_Fecha=@FECHAJU OR MH.Mov_Fecha=@FECHAVI OR MH.Mov_Fecha=@FECHASA OR MH.Mov_Fecha=@FECHADO)
        GROUP BY E.EMPL_COD,E.EMPL_FECH_AF,E.EMPL_AREA)
        E ON MH.Mov_CodEmpleado = E.COD
        GROUP BY E.AREA,E.COD,E.LUNES,E.MARTES,E.MIERCOLES,E.JUEVES,E.VIERNES,E.SABADO,E.DOMINGO
        ORDER BY AREA

INSERT INTO #CUADROCOMP(AREA,SUPERVISOR,LUNES,MARTES,MIERCOLES,JUEVES,VIERNES,SABADO,DOMINGO,EMPLCOD)
         SELECT
          (SELECT ISNULL(CASE WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA)='EMPAQUE MANUAL PAGO POR DIA') THEN 'EMPAQUE            '
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='EMPAQUE NORMAL') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='EMPAQUE MANUAL 2') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='EMPAQUE MANUAL') THEN 'EMPAQUE'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='COCINA PAGO POR DIA') THEN 'COCINA'
         WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='COCINA POR HORA') THEN 'COCINA'
                             WHEN ((SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )='CAMARA PAGO POR DIA') THEN 'CAMARA'    END,
         (SELECT DISTINCT S.SECCION FROM TBL_SECCION S WHERE S.ID_CODIGO=E.AREA )))AS AREA,
        (SELECT DISTINCT(S.NOM_SUPERVISOR) FROM
  TBL_SECCION D
  INNER JOIN
  TBL_SUPERVISOR S
  ON S.COD_AREA= D.ID_CODIGO AND E.AREA = S.COD_AREA) AS SUPERVISOR ,
E.LUNES AS LUNES,
        E.MARTES AS MARTES,
        E.MIERCOLES AS MIERCOLES,
        E.JUEVES AS JUEVES,
        E.VIERNES AS VIERNES,
        E.SABADO AS SABADO,
        E.DOMINGO AS DOMINGO,
        E.COD AS COD
        FROM HIS_MOV_HORA MH INNER JOIN
        (SELECT E.EMPL_AREA AS AREA,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0)  AND (MOV_FECHA=@FECHAL))  AS LUNES,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHAMA)) AS MARTES,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHAMI)) AS MIERCOLES,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHAJU)) AS JUEVES,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHAVI)) AS VIERNES,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHASA)) AS SABADO,
        (SELECT DISTINCT Mov_Fecha FROM HIS_MOV_HORA WHERE (MOV_CODEMPLEADO=E.EMPL_COD AND  E.EMPL_FECH_AF=0) AND (MOV_FECHA=@FECHADO)) AS DOMINGO,
        E.EMPL_FECH_AF AS EMPL_FEC,
        E.EMPL_COD AS COD
        FROM TBL_EMPLEADO E INNER JOIN HIS_MOV_HORA MH ON MH.Mov_CodEmpleado=E.EMPL_COD AND E.EMPL_FECH_AF=0 AND E.EMPL_COD != 1543 AND (MH.Mov_Fecha=@FECHAL OR MH.Mov_Fecha=@FECHAMA OR MH.Mov_Fecha=@FECHAMI
        OR MH.Mov_Fecha=@FECHAJU OR MH.Mov_Fecha=@FECHAVI OR MH.Mov_Fecha=@FECHASA OR MH.Mov_Fecha=@FECHADO)
        GROUP BY E.EMPL_COD,E.EMPL_FECH_AF,E.EMPL_AREA)
        E ON MH.Mov_CodEmpleado=E.COD
        GROUP BY E.AREA,E.COD,E.LUNES,E.MARTES,E.MIERCOLES,E.JUEVES,E.VIERNES,E.SABADO,E.DOMINGO

;WITH VISTA AS(
 SELECT

(SELECT DISTINCT AREA) AS AREA,
        (SELECT DISTINCT SUPERVISOR) AS SUPERVISOR
 ,(SELECT DISTINCT ISNULL(CASE WHEN (COUNT(LUNES) != '0') THEN '1' END ,0)) AS LUNES
 ,(SELECT DISTINCT ISNULL(CASE WHEN (COUNT(MARTES) != '0') THEN '1' END ,0)) AS MARTES
 ,(SELECT DISTINCT ISNULL(CASE WHEN (COUNT(MIERCOLES) != '0') THEN '1' END ,0)) AS MIERCOLES
 ,(SELECT DISTINCT ISNULL(CASE WHEN (COUNT(JUEVES) != '0') THEN '1' END ,0)) AS JUEVES
 ,(SELECT DISTINCT ISNULL(CASE WHEN (COUNT(VIERNES) != '0') THEN '1' END ,0)) AS VIERNES
 ,(SELECT DISTINCT ISNULL(CASE WHEN (COUNT(SABADO) != '0') THEN '1' END ,0)) AS SABADO
 ,(SELECT DISTINCT ISNULL(CASE WHEN (COUNT(DOMINGO) != '0') THEN '1' END ,0)) AS DOMINGO
FROM #CUADROCOMP GROUP BY EMPLCOD,AREA,SUPERVISOR)

SELECT DISTINCT AREA,
SUPERVISOR,
SUM(CONVERT(INT,(LUNES))) AS LUNES,
SUM(CONVERT (INT,(MARTES))) AS MARTES,
SUM(CONVERT (INT,(MIERCOLES))) AS MIERCOLES,
 SUM(CONVERT (INT,(JUEVES))) AS JUEVES,
SUM(CONVERT (INT,(VIERNES))) AS VIERNES,
SUM(CONVERT (INT,(SABADO))) AS SABADO,
SUM(CONVERT (INT,(DOMINGO))) AS DOMINGO
 FROM VISTA
GROUP BY AREA,SUPERVISOR ORDER BY AREA


text:
Q: Entity Framework 0..1 to 0..1 Association Is this possible?
I have User and Provider entities. A User may or may not be a Provider (could just be an Assistant) and a Provider may or may not be a User (it could be a Location).
The designer lets me model this, but it won't validate because of the key properties. Is this possible to achieve with EF?

A: No it is not because one-to-one relation in EF is always modeled through the primary key. Dependent entity must have foreign key constraint to principal entity placed on its primary key. It always result in 0..1 to 1 where principal can have one or none dependent but dependent must have a principal because it must have a primary key value and that value has referential constraint to principal entity.
Btw. I'm not sure if this can be even modeled in the database because even with unique key null value is still considered as one of unique values so only single record can have a value set to null when you also have unique index on that column.


text:
Q: App Engine ndb parallel fetch by key I'm retrieving a batch of items using their keys, with something like this:
from google.appengine.ext.ndb import model

# …
keys = [model.Key('Card', id, namespace=ns) id in ids]
cards = yield model.get_multi_async(keys)

The result of that in appstats is this:

The reverse-waterfall thing seems to be caused by keys being sent one by one in parallel, each in its own RPC.
My question is, is there a way to retrieve multiple objects by keys with a single RPC call? (Assuming that would speed up the overall response time of the app).

A: Quoting guido response in the thread linked by lecstor.

You can always try issuing fewer RPCs by passing
  max_entity_groups_per_rpc=N to the get_multi_async() call

Multiple parallel rpcs should be more efficient than a single multi-key RPC.

The engineers responsible for the HRD implementation assure me this is more
  efficient than issuing a single multi-key Get RPC


text:
Q: Remove bullet points in RadioSelect Widget in django I have a form that inherits from a model in Django that is rendered with a RadioSelect widget.
I would like to remove the bullet points.
Mi form is like this:
class FormFromModel(forms.ModelForm):
    c1 = [(1, 'Answer 1'), (2, 'Ans2'), (3, 'Ans3'), (4, 'Ans4'), ]
    q1 = forms.IntegerField(label='Question.... ?',
                            widget=forms.RadioSelect(choices=c1), initial=4)

And in the HTML I'm doing:

     1. {{Inputs.q1.label}}

     {{Inputs.q1}}

I have something like:
What currently have
And I will like:
What I want
Any help is appreciated, Thanks


text:
Q: How to loosen DC barrel jack to fit with 12 V adapter? I have a DC jack such as this:

The lot that I bought are all too tight to fit a 12 V Adapter plug into them. Plug:

How do I loosen the jack? Are they always stiff when new? Should I buy new ones? The same jack is on a board (HW-131) and it fits perfectly. Kindly help me out.

A: There are two especially common (one might even say de facto standard) sizes for barrel jacks¹, that look like they ought to be intercompatible, but aren't. These are 5.5/2.1 mm and 5.5/2.5 mm. It's likely you have a 5.5/2.5 mm jack and a 5.5/2.1 mm plug.
The first number in the size (note that it isn't always formatted like this; this is just how I'm writing it. It may be the second number.), 5.5 in both cases here, is the outer diameter of the barrel plug. This is the dimension that's easiest to see from looking at it.
The second number, here 2.1 or 2.5, is the diameter of the pin in the center of the jack. (though "2.1" jacks seem to have a 2.0 mm pin much of the time, going by a very brief survey of parts available on digikey.)
A plug with a hole for a 2.1 mm pin can't accept a 2.5 mm pin without damage, even though the outer diameter looks the same. A plug for a 2.5 mm pin might physically fit over a 2.1 mm pin, but the electrical contact will be poor.

Also of note, though possibly not relevant to your question, is that there is no standard for whether the center contact is positive or negative. Most devices with barrel jacks expect the center contact to be positive, but some (notably Sony branded devices) expect the center to be negative. Make sure you have the polarity right, or you might damage whatever you plug it into!

¹There are, of course, many other common sizes. These two seem to be the most common, however.


text:
Q: How large does site-to-site VPN subnet need to be? Users on the data VLAN in our HQ and future remote office(s) will need to access files, floating network licenses etc. from distant servers, so we will need a site-to-site VPN for the data network(s). When setting up our HQ I thought I was being clever by using a large (class B aka 255.255.0.0) subnet for the data VLAN and that a site-to-site VPN would simply allow us to expand the same subnet across all future offices and have users anywhere seamlessly connect to any of the servers in any of the locations. However, now that I come to set up the VPN, I have read that this is bad practice due to the latency involved with broadcast traffic across the internet.
I have a pair of  rack boxes each running pfSense in a Hyper-V VM. These will become the firewalls for each site with a site-to-site VPN between them. The pfSense configuration options for a site-to-site VPN (I'm assuming OpenVPN in SSL/TLS mode is the most-secure option) asks for three networks, the tunnel network, remote network and local network. My question is how large does the tunnel network need to be? Can it be a class C (255.255.255.0) network with one IP for each office or does it need to be large enough to provide an address for every device across all the offices? If the latter, I clearly wouldn't be able to give each office a 255.255.0.0 subnet (not that I think that would be needed), but would I have to reduce the size of the HQ subnet (it probably has under 500 hosts currently despite having tens of thousands of IP addresses available) that was originally intended to be our global network?

A: A site-to-site VPN usually is fully routed network.  Meaning there is no NAT or anything.  The subnet used for the VPN only needs addresses for the connected routers.
So the minimum size of the subnet, that you would need between only two sites is a /30, or possibly a /31. Of course,  you might add more sites in the future, so allocating something larger /24 to the VPN wouldn't be a bad idea, depending on your specific VPN technology and how it handles routing.  How you allocated your subnets in something like wireguard, may be different, compared to OpenVPN, or something with IPSec.


text:
Q: AngularJS, changing the data in a view without div disappearing I'm making a little wizard/survey in AngularJS which loads in data to a variable, $scope.styles. I've set up a plunkr for ease of use here:
http://plnkr.co/edit/1S542YE7xlO2P4zyhzu0?p=preview
Pretty simple. I show each object to the user in succession, which loads in the pertinent images and displays them for the user. clicking "yes/no" at the bottom of the images it loads in the next gallery. There is a big of lag between the refresh here (Plunkr seems to be loading it quite quickly, but this is not the case on my production server so it's even more noticable) which causes the window size to momentarily be much smaller plus all the content below the ng-repeat jumps to the top of the screen.
What's the best way to prevent this from happening? Is CSS the only solution here?

A: Your problem is that the <img> elements have a size of 0 until the user's browser loads the image file.  Try changing the image tag to <img ng-src="{{img}}" width="100" height="100"/> and you'll notice no more flicker.  If possible, have the server return these attributes with the image url data.

A: You can add height to the images wrapper div ( style="height:300px" or, better, as a class).
That way the wrapper will stay fixed sized when images change and when you have less then three rows of images.


text:
Q: mmap() RWX page on MacOS (ARM64 architecture)? I've been trying to map a page that both writable AND executable.
    mov x0, 0                   // start address
    mov x1, 4096                // length
    mov x2, 7                   // rwx
    mov x3, 0x1001              // flags
    mov x4, -1                  // file descriptor
    mov x5, 0                   // offset
    movl x16, 0x200005c         // mmap
    svc 0

This gives me a 0xD error code (EACCESS, which the documentation unhelpfully blames on an invalid file descriptor, although same documentation says to use '-1'). I think the code is correct, it returns a valid mmap if I just pass 'r--' for permissions.
I know the same code works in Catalina and x64 architecture. I tested the same error happens when SIP mode is disabled.
For more context, I'm trying to port a FORTH implementation to MacOs/ARM64, and this FORTH, like many others, heavily uses self modifying code/assembling code at runtime. And the code that is doing the assembling/compiling resides in the middle of the newly created code (in fact part the compiler will be generated in machine language as part of running FORTH), so it's very hard/infeasible to separate the FORTH JIT compiler (if you call it that) from the generated code.
Now, I'd really don't want to end up with the answer: "Apple thinks they know better than you, no FORTH for you!", but that is what it looks like so far. Thanks for any help!

A: You need to toggle the thread between being writable or executable, it can not be both at the same time. I think it is actually possible to do both with the same memory using 2 different threads but I haven't tried.
Before you write to the memory you mmap, call this:
pthread_jit_write_protect_np(0);
sys_icache_invalidate(addr, size);

Then when you are done writing to it you can switch back again like this:
pthread_jit_write_protect_np(1);
sys_icache_invalidate(addr, size);

This is the full code I am using right now
#include <stdio.h>
#include <sys/mman.h>
#include <pthread.h>
#include <libkern/OSCacheControl.h>
#include <stdlib.h>
#include <stdint.h>

uint32_t* c_get_memory(uint32_t size) {
    int prot = PROT_READ | PROT_WRITE | PROT_EXEC;
    int flags = MAP_PRIVATE | MAP_ANONYMOUS | MAP_JIT;
    int fd = -1;
    int offset = 0;
    uint32_t* addr = 0;

    addr = (uint32_t*)mmap(0, size, prot, flags, fd, offset);
    if (addr == MAP_FAILED){
        printf("failure detected\n");
        exit(-1);
    }

    pthread_jit_write_protect_np(0);
    sys_icache_invalidate(addr, size);

    return addr;
}

void c_jit(uint32_t* addr, uint32_t size) {
    pthread_jit_write_protect_np(1);
    sys_icache_invalidate(addr, size);

    void (*foo)(void) = (void (*)())addr;
    foo();
}

A: Just came across this in the OSX v12 mmap man page entry:
"When the hardened runtime is enabled (See the links in the SEE ALSO section), the protections cannot be both
PROT_WRITE and PROT_EXEC without also having the flag MAP_JIT and the process possessing the
com.apple.security.cs.allow-jit entitlement"
So the issue may be your process entitlements are not setup as needed (meaning you need to codesign with the appropriate entitlements file to burn in the entitlements in a way the OS understands, so you do not need to turn SIP off)
The man page also mentions other entitlements that you might find useful, such as com.apple.security.cs.allow-unsigned-executable-memory and com.apple.security.cs.disable-executable-page-protection


text:
Q: Python type hints and `*args` Assume I have a function like this:
def foo(*args):
    for x in args:
        print(x)

and let's say I want to say that all the elements of args are int; what is the right way to express it as of PEP 0484? Should I do something like
from typing import Tuple

def foo(*args: Tuple[int, ...]) -> None:
    for x in args:
        print(x)

or something like
def foo(*args: int) -> None:
    for x in args:
        print(x)

or something else entirely?
In particular, I'm trying to use type hints effectively in PyCharm, and none of the solutions I've thought of seems to help PyCharm understand that x should be an int.

A: According to PEP-484:

Arbitrary argument lists can as well be type annotated, so that the definition:
def foo(*args: str, **kwds: int): ...

is acceptable and it means that, e.g., all of the following represent function calls with valid types of arguments:
foo('a', 'b', 'c')
foo(x=1, y=2)
foo('', z=0)

In the body of function foo, the type of variable args is deduced as Tuple[str, ...] and the type of variable kwds is Dict[str, int].

The correct way to annotate the foo function from your example is:
def foo(*args: int) -> None:
    for x in args:
        print(x)

In Python 2:
def foo(*args):
    # type: (*int) -> None
    for x in args:
        print(x)

A: You should have a look at the docstrings. PyCharm allows you to define your arguments in docstrings, with or without the types. If you define the types, the hints will take into consideration the type of the arguments.
def foo(*args):
    """
    General information about foo
    :param [int] args: info about args
    """

    for x in args:
        print(x)


text:
Q: Reading XML CDATA section with ]] in it I'm coding a RSS reader in Javascript using XMLHttpRequest.
For some RSS Feeds I had no problems but in some cases the xmlDocument.firstChild attribute was always NULL
After trying to see the differences between the XML that worked and the ones that didn't worked I found that the following is the cause of the error.
<item>
    <description>
        <![CDATA[This is a description for a test [...]]]>
    </description>
</item>

Because that in this description tag I have a closing bracket followed by the closing brackets of the CDATA is causing my error, I've made a code with C# using LINQ for the same XML and everything worked.
The closing bracket that is just before the closing brackets of CDATA is causing this strange behaviour. As a test I've tried to read the same XML using C# and LINQ, everything worked okay.
Then I tried to add a space between the closing brackets, like the following
<![CDATA[This is a description for a test [...] ]]>
And it worked!
my javascript code
function LoadRSS() {
    http_request.onreadystatechange = function () { showContent(http_request); };
    http_request.open("GET", "./feeds/test.xml", true);
    http_request.send(false);
}

function showContent(http_request) {
    if (http_request.readyState == 4) {
        if (http_request.status == 200) {
            var parser = new DOMParser();
            var xml_doc = parser.parseFromString(http_request.responseText, "text/xml");
            alert(xml_doc.firstChild)
        }
        else {
            xml_doc = null;
        }
    }
}

Does anyone have faced something similar? Now I really don't know how to proceed any comments and suggestions are welcomed.

A: Whatever browser you're using seems to be parsing CDATA sections incorrectly -- only ]]> marks the end of the section, any other square brackets should not affect this at all.

A: As for "how to proceed"...why not just include a space before the end of the CDATA block always? Do you not have control over the generated XML? If so, you could use JS to:
var xml = http_request.responseText.replace( /\]\]>/g, ' ]]>' );
var xml_doc = parser.parseFromString(xml, "text/xml");


text:
Q: Two equal segments, two known angles, find angle in triangle
This is the problem. I have tried the obvious without success. Drawing some perpendiculars (from A for example), I only know the angle $\sphericalangle ADC = 54 ^{\circ}$. How can I use the equality $AB = DC$?

A: Let's reformulate the problem.

Let $\triangle ABC$ be such that $\angle ABC = 24^{\circ}$ and $\angle ACB = 30^{\circ}$ and $D$ is on $BC$ so that $AB = CD$.
We have to prove $\angle BAD = 30^{\circ}$

Solution: Rotate $B$ around $A$ for $60^{\circ}$ to new point $E$. Then since $EA=EB$ and $$\angle AEB = 2\angle BCA$$ we see that $C$ is on circle with center at $E$ and radius $EA=EB = EC$. Then $CD = CE$, so $$\angle BCE = \angle CBE = 34^{\circ} \implies \angle EDC = \angle DEC = 72^{\circ}$$
Now this means that $$\angle BDE = 108^{\circ} \implies \angle BED = \angle EBD = 36^{\circ}$$
This means $BD = ED$, so so $\triangle ABD$ and $\triangle ADE$ are congruent (sss) and thus $\angle BAD = 30 ^{\circ}$.

A: By the law of sines we obtain:
$$\frac{AD}{\sin{x}}=\frac{DC}{\sin(126^{\circ}-x)}$$ and
$$\frac{AD}{\sin24^{\circ}}=\frac{AB}{\sin54^{\circ}}$$ and since $AB=DC$, we obtain:
$$\frac{\sin{x}}{\sin24^{\circ}}=\frac{\sin(126^{\circ}-x)}{\sin54^{\circ}}.$$
Can you end it now?
I got $x=30^{\circ}.$


text:
Q: pl/pgsql array as input to an aggregate function i am writing pl/pgsql function that does some statistics processing. using 8.2 of postgres. i want to use this handy aggregate function:
regr_slope(Y, X)
but, i have my X and Y data stored as local arrays in the pl/pgsql function:
  y double precision[];
  x double precision[];
trouble is when i use this as a line in the pl/pgsql function:
slope := regr_slope(y, x);
i get an error saying that function isn't available or has the wrong arguments. i suspect it's because the inputs are supposed to be selected as columns from a table instead of being passed as double precision arrays.
is there a way to make the regr_slope function with local arrays? (ie, some way to cast the array to be a valid input to an aggregate function?)
thank you.

A: SELECT regr_slope(x,y) INTO slope FROM (SELECT unnest(ARRAY[1,2,3,4]) as x, unnest(ARRAY[5,6,7,8]) AS y) AS z;


text:
Q: JSON Android login validation via mysql I am making a login screen and when testing the code,it always validates both wrong and right inputs and enters the home screen.The PHP works as it can tell which data are found in the database.Heres the code:
loginActivity.java
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.provider.CalendarContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

public class loginDosen extends AppCompatActivity {
    EditText txKodeDosen,txPassword;
    String KodeDosen,password;
    RequestQueue requestQueue;
    String loginURL ="http://192.168.43.217/test/DosenPublikasi/loginDosen.php";
    StringRequest request;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login_dosen);

    txKodeDosen = (EditText)findViewById(R.id.txKodeDosen);
    txPassword = (EditText)findViewById(R.id.txPassword);
    requestQueue = Volley.newRequestQueue(loginDosen.this);
}

public void Login(View view) {
    if(txKodeDosen.getText().toString().equals("") ){
        Toast.makeText(this,"Kode Dosen Field is empty",Toast.LENGTH_SHORT).show();
    }
    else if(txKodeDosen.getText().toString().charAt(0)!='D'){
        Toast.makeText(this,"Must have D in the start",Toast.LENGTH_SHORT).show();
    }else if(txKodeDosen.length() !=5 ){
        Toast.makeText(this,"Must be 5 characters long",Toast.LENGTH_SHORT).show();
    }
    else if(txPassword.getText().toString().equals("")){
        Toast.makeText(this,"Password Field is empty",Toast.LENGTH_SHORT).show();
    }
    else {
        JSONObject Login = new JSONObject();
        try {
            Login.put("kodeDosen", txKodeDosen.getText().toString());
            Login.put("password", txPassword.getText().toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }

        JsonObjectRequest jsonobjectrequest = new JsonObjectRequest(Request.Method.POST, loginURL, Login,
                new Response.Listener<JSONObject>()

                {
                    @Override
                    public void onResponse(JSONObject response) {
                        Toast.makeText(loginDosen.this, response.toString(), Toast.LENGTH_SHORT).show();
                        SharedPreferences DataDosen = getSharedPreferences("Dosen", Context.MODE_PRIVATE);
                        SharedPreferences.Editor editor = DataDosen.edit();
                        editor.putString("kodeDosen", txKodeDosen.getText().toString());
                        editor.putString("password", txPassword.getText().toString());
                        editor.commit();
                        Intent intent = new Intent(loginDosen.this, homepageDosen.class);
                        startActivity(intent);
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        Toast.makeText(loginDosen.this, error.toString(), Toast.LENGTH_LONG).show();
                    }

                });
        requestQueue.add(jsonobjectrequest);
    }

}

public void Back(View view) {
    Intent intent = new Intent(loginDosen.this, registrasiDosen.class);
    startActivity(intent);
}

}
heres the php
<?php
include 'connectdb.php';

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

$kodeDosen =$data["kodeDosen"];
$password = $data["password"];

$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");

$sql = "SELECT * FROM tbl_dosen WHERE kodeDosen ='$kodeDosen' and password = '$password'";

//echo $kodeDosen;

$result = mysqli_query($conn,$sql);
$row = mysqli_fetch_array($result,MYSQLI_ASSOC);

$count = mysqli_num_rows($result);

// If result matched $myusername and $mypassword, table row must be 1 row

if($count == 1) {
    echo json_encode($message);
}else {
    echo json_encode($failure);
}
?>

the json works but when the login button is used,it will always enter the next screen even if the input doesnt match any data from the database

A: You should put in the response block the following condition
@Override
public void onResponse(JSONObject response) {
   if(response.getString("message").equals("Data found")){
    Toast.makeText(loginDosen.this, response.toString(), Toast.LENGTH_SHORT).show();
    SharedPreferences DataDosen = getSharedPreferences("Dosen", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = DataDosen.edit();
    editor.putString("kodeDosen", txKodeDosen.getText().toString());
    editor.putString("password", txPassword.getText().toString());
    editor.commit();
    Intent intent = new Intent(loginDosen.this, homepageDosen.class);
    startActivity(intent);
   }else{
    Toast.makeText(loginDosen.this, response.toString(), Toast.LENGTH_SHORT).show();
   }
}

A: 1.Seems like you saved the plain password.It's a big loophole to the sytem.try to use password-hashing to protect your password.
2.Try to use prepared statements to prevent from SQL INJECTION.The current code is wide-open for it.
3.Check data is coming or not at Android-end and then proceed further accordingly.
Do like below:-
PHP end:-
<?php
include 'connectdb.php';

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

$kodeDosen =$data["kodeDosen"];
$password = $data["password"];

$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");

if ($stmt = mysqli_prepare($conn, "SELECT * FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {

   /* bind parameters for markers */
   mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);

   /* execute query */
   mysqli_stmt_execute($stmt);

   /* store result */
   mysqli_stmt_store_result($stmt);

   if(mysqli_stmt_num_rows($stmt) > 0) {
      echo json_encode($message);
   }else {
      echo json_encode($failure);
   }

}
?>

Android end (i am not an android coder so I am giving simple logic only):-
@Override
public void onResponse(JSONObject response) {
   if(check that message is "data found"){
     // if yes then proceed further
   }else if(check that message is "Data not found")){
     //if yes show some error message and do further process
   }
}


text:
Q: Adjectives in the introductory there structure can come after nouns? I have seen in some grammar book the following pattern, which allows to place an adjective after a noun:

A shelf is empty.
➔ There is a shelf empty.

I want to know whether the above pattern is a general rule for the introductory there (if so, please also mention the reason because we do not have such a thing in similar structures; for example, we do not say "it is a book good") so that we can have similar examples like
"there is a man nice",
or it only applies to some certain class of adjectives (including "empty")?


text:
Q: Selenium web driver: unable to locate element I am New to selenium: I have this source and am trying click on a button using xpath with selenium webdriver. This is the button(last line in the html) that am trying to click on:

I use this xpath: "//div[@id='innerBody']/div[4]/div/div/ul/li[3]/button"
and it gives me unable to locate element.
Any idea why and how I should go about it.
<document>

<link rel="stylesheet" href="/cache/sf/_App/Home/HomeShell.css"/>
<link rel="stylesheet" href="/cache/sf/css/lib/joyride-2.1.css"/>

Bestandsvak voor satish vanahalli

<link href="/cache/f69bb3f534fb459062226526576bc4dea7e8fe7e/css/lib/jqui/jquery-ui-1.10.0.sf.css" type="text/css" rel="stylesheet"/>

***<button class="txt context-action" data-bind="click: Click">***

A: As per your comments for question, if you want to click on the 3rd button in the list, please try below xpath; I have just tweaked @Saritha's :
(//button[@class='txt context-action'])[3]

This will click on the 3rd button in the page (in the chronological order of DOM representation) with class as txt context-action.

A: Try this xpath:
   //ul[@class='context-actions']/li[3]/button[@class='txt context-action][3]

A: Try this xpath:
//*[@id="innerBody"]/div/div/div/div/div/div/ul/li[3]/button


text:
Q: Use annotations on Pytnon 3.6.5 I'm working on a project where I was asked to code some validations using Chain of Responsibility.
I am currently using python 3.9.2 on my machine, but the project on docker is on 3.6.5
This piece of code works nice on my machine, but it breaks on Docker:
from __future__ import annotations
from abc import ABC, abstractmethod
from typing import Any, Optional

class Handler(ABC):
    """
    The Handler interface declares a method for building the chain of handlers.
    It also declares a method for executing a request.
    """

    @abstractmethod
    def set_next(self, handler: Handler) -> Handler:
        pass

    @abstractmethod
    def handle(self, request) -> Optional[str]:
        pass

The error that shows is the following:
 from __future__ import annotations
django_1    |     ^
django_1    | SyntaxError: future feature annotations is not defined

Is there a way to make the code work on python 3.6.5?

A: I've found this answer on github and I'm reposting it in case anyone ends up here like me.
As pointed out by @ForceBru annotations as part of __future__ was introduced with Python 3.7+, so you'll need to add de dependency manually (or move up the python version, which I would recommend)
To add the dependency do the following:
git clone -b legacy_py3.6 https://github.com/QUVA-Lab/e2cnn.git
cd e2cnn
python setup.py install


text:
Q: Unable to implement RTSP server in Android I'm trying to implement a lightweight RTSP server in Android to live-stream my camera feed to VLC media player. For this, I'm using libstreaming library. I successfully imported the library in Android Studio and managed to compile and run the skeleton code for server side. Unfortunately, the program is not working as expected. The camera preview fails to load and I'm unable to read the MRL in VLC media player. Has anyone faced this issue before? Any help would be appreciated! Thanks in advance. Here is what I've tried so far:
    public class MainActivity extends Activity {

    private final static String TAG = "MainActivity";

    private SurfaceView mSurfaceView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        mSurfaceView = (SurfaceView) findViewById(R.id.surface);

        // Sets the port of the RTSP server to 1234
        Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
        editor.putString(RtspServer.KEY_PORT, String.valueOf(1234));
        editor.commit();

        // Configures the SessionBuilder
        SessionBuilder.getInstance()
                .setSurfaceView(mSurfaceView)
                .setPreviewOrientation(90)
                .setContext(getApplicationContext())
                .setAudioEncoder(SessionBuilder.AUDIO_NONE)
                .setVideoEncoder(SessionBuilder.VIDEO_H264);

        // Starts the RTSP server
        this.startService(new Intent(this,RtspServer.class));

    }

}

I'm trying to access the MRL: rtsp://192.168.2.3:1234/

A: The code you are trying is good. The URL needs to have specific format,
URL in VLC player should be rtsp://phone_local_ip:1234?h264=200-20-320-240
200 =  buf | 20 = fps | 320 = width | 240 = height


text:
Q: How do we determine if a subgroup of $S_n$ is normal? Ok, so I have $H = \{ e,(12),(34),(12)(34) \}$ being a subgroup of $S_4$.
How do I prove that it is also normal (or isn't)? Because I don't really want to check every case, and there must be a more elegant way.
Thanks in advance.

A: Elements in $S_n$ are conjugate if and only if they have the same cycle structure. In particular, $(12)$ and $(13)$ are conjugate, so since $(13) \not \in H$ then $H$ is not a normal subgroup of $S_4$.
$S_4$ does have a normal subgroup isomorphic to $H$, but it is generated by the permutations having cycle structure as follows: $(\cdot \cdot) (\cdot \cdot)$.

A: Any two elements with the same cycle structure are conjugate.  Thus, your subgroup $H$ is not inner automorphism invariant, and so not normal.  For instance, $(12)(34)$ and $(13)(24)$ are conjugate.


text:
Q: Proof by definition limit equals to infinity
Prove by definition $$\lim_{x \to 2} \frac{1}{(x-2)^3}=\infty$$

How should I approach this, if the limit is $\infty$?

A: For $$\lim_{x\to 2^+}\frac{1}{(x-2)^3}=+\infty, $$
if $0<x-2<1$, then $$(x-2)^3\leq (x-2)\implies \frac{1}{(x-2)^3}\geq \frac{1}{x-2}.$$
Then, if $M>0$, set $\delta=\min\{\frac{1}{M},1\}$, to get $$\frac{1}{(x-2)^3}>M$$
when $0<x-2<\delta$ what prove the claim. I let you do the case $$\lim_{x\to 2^-}\frac{1}{(x-2)^3}=-\infty .$$


text:
Q: MDX crossjoin with 5 dimensions Assuming we have the following dimension

*

*DATE

*CONTRACTOR

*COLOR

*SIZE

and a set of 6 measures, we want to get the 6 measures for every Semestrer, Trimester, Month, Contractor, Color and Size for a given Year.
Here is my MDX query:
SELECT
   {
         ... the 6 measures ...
   } ON COLUMNS,
    {
          (
                [Dim DATE].[year].[year].AllMembers *
                [Dim DATE].[SEMESTRE NOM].[SEMESTRE NOM].AllMembers *
                [Dim DATE].[TRIMESTRE NOM].[TRIMESTRE NOM].AllMembers *
                [Dim DATE].[MOIS NOM].[MOIS NOM].AllMembers *
                [Dim CONTRACTOR].[Name CONTRACTOR].AllMembers *
                [Dim COLOR].[Name COLOR].AllMembers *
                [Dim SIZE].[Name SIZE].AllMembers
         )
   } DIMENSION PROPERTIES MEMBER_CAPTION, MEMBER_UNIQUE_NAME ON ROWS

 FROM   (
   SELECT ( { StrToSet( "[Dim DATE].[year].[year].&[" + @Year + "]" , CONSTRAINED ) }

   ) ON COLUMNS
FROM [TheCube]

This is very slow (more than 20 minutes), with only 6 Contractors, 6 Color, 18 sizes... and what is the differences between .AllMembers and .Members ?

A: Depending on the actual number of years in your hierarchy, you might create a quite large set with the crossjoin. As icCube mentionned in the comment, why not using :
StrToSet( "[Dim DATE].[year].[year].&[" + @Year + "]" , CONSTRAINED )

in the crossjoin on the ROWS ?
AllMembers vs Members; here is a doc; allmembers include the calc. members; do you have any costly calc. members ?
How many members do you have in [Dim DATE].[MOIS NOM].[MOIS NOM].AllMembers ? trimestre, semestre ?


text:
Q: SwiftUI: fit SF Icon into line height When I try to display an icon next to a text, the Image adds unwanted space above, increasing the line height and I don't understand how I can control it. I tried frame, padding, resizable without success. I also tried the Label element, which my XCode does not recognize ("unresolved identifier Label").

The image shows the difference between an Image and Text, where the Image adds unwanted space.
Where is that extra space coming from and how can I control it?
VStack {
    Text("User Name").bold()
    HStack {
        Text("hello@contact.com")
        Image(systemName: "checkmark.seal.fill")
        .font(.system(size: 14))
            .foregroundColor(.blue)
    }
}

A:
The image shows the difference between an Image and Text, where the Image adds unwanted space.
Where is that extra space coming from and how can I control it?

It is all about default spacing... it is, yes, strange, use explicit, eg
VStack(spacing: 0) {
   // ... other your code
}


text:
Q: How to create frame index hierarchy in Deedle C# What is the correct way to produce a multi-level hierarchical index for a Deedle frame in C#?
Following the first snippet on this page which suggests applying GroupRowsBy() repeatedly for F#:

// Group by passanger class and port
let byClassAndPort =
  titanic
  |> Frame.groupRowsByInt "Pclass"
  |> Frame.groupRowsByString "Embarked"
  |> Frame.mapRowKeys Pair.flatten3

// Get just the Age series with the same row index
let ageByClassAndPort = byClassAndPort?Age

If you look at the type of byClassAndPort, you can see that it is Frame<(string * int * int),string>.

However the method Frame.mapRowKeys() does not exist in C# so the frame indexes cannot be flattened. Another option is to use Frame.IndexRowsUsing() but I am unsure if this results in the same thing as using GroupRowsBy() and also does not allow for preserving the original ordinal index.
An example of the snippet above written in C# would be perfect, or an explanation of the correct way to create such a frame in C#.
Thanks.


text:
Q: convert string which contains sub string to dictionary I am tring to convert particular strings which are in particular format to Python dictionary.
String format is like below,
st1 = 'key1 key2=value2 key3="key3.1, key3.2=value3.2 , key3.3 = value3.3, key3.4" key4'

I want to parse it and convert to dictionary as below,
dict1 {
    key1: None,
    key2: value2,
    key3: {
            key3.1: None,
            key3.2: value3.2,
            key3.3: value3.3,
            key3.2: None
          }
    key4: None,

I tried to use python re package and string split function. not able to acheive the result. I have thousands of string in same format, I am trying to automate it. could someone help.

A: If all your strings are consistent, and only have 1 layer of sub dict, this code below should do the trick, you may need to make tweaks/changes to it.
import json

st1 = 'key1 key2=item2 key3="key3.1, key3.2=item3.2 , key3.3 = item3.3, key3.4" key4'
st1 = st1.replace(' = ', '=')
st1 = st1.replace(' ,', ',')
new_dict = {}
no_keys=False

while not no_keys:
    st1 = st1.lstrip()

    if " " in st1:
        item = st1.split(" ")[0]
    else:
        item = st1

    if '=' in item:
        if '="' in item:
            item = item.split('=')[0]
            new_dict[item] = {}

            st1 = st1.replace(f'{item}=','')
            sub_items = st1.split('"')[1]
            sub_values = sub_items.split(',')

            for sub_item in sub_values:
                if "=" in sub_item:
                    sub_key, sub_value = sub_item.split('=')
                    new_dict[item].update({sub_key.strip():sub_value.strip()})
                else:
                    new_dict[item].update({sub_item.strip(): None})

            st1 = st1.replace(f'"{sub_items}"', '')
        else:
            key, value = item.split('=')
            new_dict.update({key:value})
            st1 = st1.replace(f"{item} ","")
    else:
        new_dict.update({item: None})
        st1 = st1.replace(f"{item}","")

    if st1 == "":
        no_keys=True

print(json.dumps(new_dict, indent=4))

A: Consider use parsing tool like lark. A simple example to your case:
_grammar = r'''
    ?start: value

    ?value: object
           | NON_SEPARATOR_STRING?

    object : "\"" [pair (_SEPARATOR pair)*] "\""
    pair : NON_SEPARATOR_STRING [_PAIRTOR] value

    NON_SEPARATOR_STRING: /[a-zA-z0-9\.]+/
    _SEPARATOR: /[,  ]+/
            | ","
    _PAIRTOR: " = "
            | "="
'''

parser = Lark(_grammar)

st1 = 'key1 key2=value2 key3="key3.1, key3.2=value3.2 , key3.3 = value3.3, key3.4" key4'

tree = parser.parse(f'"{st1}"')
print(tree.pretty())

"""
object
  pair
    key1
    value
  pair
    key2
    value2
  pair
    key3
    object
      pair
        key3.1
        value
      pair
        key3.2
        value3.2
      pair
        key3.3
        value3.3
      pair
        key3.4
        value
  pair
    key4
    value

"""

Then you can write your own Transformer to transform this tree to your desired date type.


text:
Q: Bash: Maintaining a set of files and their gzipped equivalent I have a directory tree in which there are some files and some subdirectories.
/
/file1.txt
/file2.png
/dir1
    /subfile1.gif

The objective is to have a script that generates a gzipped version of each file and saves it next to each file, with an added .gz suffix:
/
/file1.txt
/file1.txt.gz
/file2.png
/file2.png.gz
/dir1
    /subfile1.gif
    /subfile1.gif.gz

This would handle the creation of new .gz files.
Another part is deletion: Whenever a non-gzipped file is created, the script would need to delete the orphaned .gz version when it runs.
The last and trickiest part is modification: Whenever some (non-gzipped) files are changed, re-running the script would update the .gz version of only those changed files, based on file timestamp (mtime) comparison between a file and its gzipped version.
Is it possible to implement such a script in bash?
Edit: The goal of this is to have prepared compressed copies of each file for nginx to serve using the gzip_static module. It is not meant to be a background service which automatically compresses things as soon as anything changes, because nginx's gzip_static module is smart enough to serve content from the uncompressed version if no compressed version exists, or if the uncompressed version's timestamp is more recent than the gzipped version's timestamp. As such, this is a script that would run occasionally, whenever the server is not busy.

A: Here is my attempt at it:
#!/bin/bash
# you need to clean up .gz files when you remove things
find . -type f -perm -o=r -not -iname \*.gz | \
while read -r x
do
    if [ "$x" -nt "$x.gz" ]; then
        gzip -cn9 "$x" > "$x.gz"
        chown --reference="$x" "$x.gz"
        chmod --reference="$x" "$x.gz"
        touch --reference="$x" "$x.gz"
        if [ `stat -c %s "$x.gz"` -ge `stat -c %s "$x"` ]; then
            rm "$x.gz"
        fi
    fi
done

Stole most of it from here: https://superuser.com/questions/482787/gzip-all-files-without-deleting-them
Changes include:

*

*skipping .gz files

*adding -9 and -n to make the files smaller

*deleting files that ended up larger (unfortunately this means they will be retried every time you run the script.)

*made sure the owner, permissions, and timestamp on the compressed file matches the original

*only works on files that are readable by everyone

A: Something like this, maybe?
#!/bin/sh

case $1 in
  *.gz )
    # If it's an orphan, remove it
    test -f "${1%.gz}" || rm "$1" ;;
    # Otherwise, will be handled when the existing parent is handled
  * )
    make -f - <<'____HERE' "$1.gz"
%.gz: %
    # Make sure you have literal tab here!
    gzip -9 <$< >$@
____HERE
    ;;
esac

If you have a Makefile already, by all means use a literal file rather than a here document.
Integrating with find left as an exercise.  You might want to accept multiple target files and loop over them, if you want to save processes.


text:
Q: Checking keystore file in Android Studio I've changed my pc and reinstalled Android Studio as well as my old project.
I've copied my old keystore files in the following directory
"C:\Users\MyUserName.android"
But when I run the program it looks like the keystore is not recognized(not connecting to google services and so forth...)
How do I check if my keystore file is working properly?

A: There are two keystore files usually used.  One for debugging and one for doing release builds of your apps you plan to upload to an app store.  The debugging keystores can be generated anytime, so, it doesn't hurt to create a new one in your new IDE setup.  But for your release keystore, you will want to build a new version release of your app and export it, then try to upload it to your App Store.  If there is anything wrong with the signing, the App Store should reject it.

A: Just try to generate signed apk . If you got error than you keystore is not setup. If it generate then it's okk.


text:
Q: Page loading animation I want to display a loading animation while my page is loading, and when loading is complete then obviously hide it.
I am working in ASP.NET using Masterpages, just wondering there is a a simple way of doing this using JQuery?
Any pointers would be appreciated.
Thanks

A: Just place an image with the animated gif on the page. Give it an id of loadingImage and add the following script:
$(document).ready(function(){
    $('#loadingImage').hide();
});

Incidentally, how long is your page taking to load? Is it using AJAX calls to load data? Maybe you should look into this and in the callback handler, call the hide() function on your image.

A: Consider using UpdateProgress control

A: When both answers above were along the right lines, I could get either do exactly what I needed in my scenario.
However I found the following post that on SO that has provided me the solution I was after.
Colorbox: Show/simulate 'loading' animation for iframe content?
Thanks all for your input.

A: I made an animation in this way on my master page:

<asp:Image ID="loadingImage" runat="server"  ImageUrl="~/Images/loading.gif" />

and then I used jQuery in this way

I hope this will help.


text:
Q: Is it possible to programmatically add a web part to a page in a sharepoint hosted app (JS) I've been looking for a way to add a web part to a page using JSOM/CSOM or any other api available to sharepoint hosted apps.
The only solutions I have found so far are for custom sharepoint solutions. Could anyone confirm that this is (im)possible?
To be clear, I want to add a web part to a sharepoint page. Not to a page of my app.

A: How to add WebPart client object on page via JSOM
function addWebPart(webUrl, pageUrl,webPartXml,zoneId,zoneIndex, Success,Error){
    var context = new SP.ClientContext(webUrl);
    var web = context.get_web();

    var file = web.getFileByServerRelativeUrl(webUrl + pageUrl);
    var webPartMngr = file.getLimitedWebPartManager(SP.WebParts.PersonalizationScope.shared);
    var webPartDef = webPartMngr.importWebPart(webPartXml);
    var webPart = webPartDef.get_webPart();
    webPartMngr.addWebPart(webPart, zoneId, zoneIndex);

    context.load(webPart);
    context.executeQueryAsync(
      function() {
        Success(webPart);
      },
      Error
    );
}

Example: add Content Editor on root web
var webPartXml = '<?xml version="1.0" encoding="utf-8"?>' +
'<WebPart xmlns="http://schemas.microsoft.com/WebPart/v2">' +
    '<Assembly>Microsoft.SharePoint, Version=16.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>' +
    '<TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>' +
    '<Title>$Resources:core,ContentEditorWebPartTitle;</Title>' +
    '<Description>$Resources:core,ContentEditorWebPartDescription;</Description>' +
    '<PartImageLarge>/_layouts/15/images/mscontl.gif</PartImageLarge>' +
'</WebPart>';

addWebPart('/','Pages/default.aspx',webPartXml,'Left',1,function(webPart){
    console.log(webPart.get_title() + ' has been added');
},function(sender,args){
    console.log(args.get_message());
});


text:
Q: check if main actor is finished As i am creating actor system and creating main actor i.e. actorModel that creates about 15 other actors. Now, what happens that the true is returned before the completion of actorModel. I want the true to be returned from this method when the actorModel has finished its task or the actor system has finished its task. you know what i mean.! Help...
def doWork:Boolean ={
/* some code here....
 *
 */
val system=ActorSystem("system")
val actorModel=system.actorOf(Props(new ActorModel(userId,dateTimeId,form)),"actorModel")

true
}

A: One option is to ask the actorModel and Await the response.
val f = actorModel ? AreYouFinished
Await.ready(f, timeout)

The ActorModel would need to keep track of senders of the AreYouFinished message and respond to them when the task is finished.
case AreYouFinished =>
  finishedWaiters = sender :: finishedWaiters

case TaskFinished =>
  finishedWaiters foreach (_ ! TaskFinished)

This is a use case where ask and Await are useful: non-actor code waiting on the results of an actor.  You wouldn't normally wait to use Await in an actor.
Note that actor systems are fairly heavyweight.  You usually would have one for your whole application, rather than firing one up as needed in a function.  Also per waffle paradox you also need to make sure it is shut down.  But usually you would shut it down when your app shuts down.

A: Use system.awaitTermination() before return with true.


text:
Q: Array of unique JSON values I'm trying to get an array of unique JSON data based on the comparison of a key value.
In this example, I'm trying to remove any objects with duplicate category values.
Example:
 var products = [
        { category: 'fos', name: 'retek' },
        { category: 'fos', name: 'item' },
        { category: 'nyedva', name: 'blabla' },
        { category: 'fos', name: 'gihi' }
    ];

// array of hold unique values
var uniqueNames = [];

for(i = 0; i< products.length; i++){
    if(uniqueNames.indexOf(products[i].category) === -1){
        uniqueNames.push(products[i]);
    }
}

I'm trying to push to the array any object that doesn't have duplicate category values. Here is a live JSbin.
Please help!

A: There are several ways to do this, this is one of them: traverse all the items, and filter out the ones which we have already added with that category. For this we use an object to keep which categories we have seen and which ones are new, so we filter only the seen ones:
var seen = {}

var unique = products.filter(function(item){
    if(seen.hasOwnProperty(item.category)){
        return false;
    }else{
        seen[item.category] = true;
        return true;
    }
})

console.log(unique); // only 2 objects

A: Switch
for(i = 0; i< products.length; i++){
    if(uniqueNames.indexOf(products[i].category) === -1){
        uniqueNames.push(products[i]);
    }
}

To
for(i = 0; i< products.length; i++){
        if(uniqueNames.indexOf(products[i].category) === -1){
            uniqueNames.push(products[i].category);  // Push Name of category. Will now not place duplicates into UnqiueNames
        }
    }

Console
["fos", "nyedva"]

A: When I am trying to do this, I usually put all of the values into a map as keys, since the map data structure will only allow unique keys. So for this case:
var crops = [   {
    id:     0023,
    crop:   "corn"
},
{
    id:     0034,
    crop:   "corn"
},
{
    id:     0222,
    crop:   "wheat"
}
 ];
var cropsMap = {};
for(var i = 0; i < crops.length; i++) {
   cropsMap[crops[i].crop] = true;
}
var uniqueCrops = Object.keys(cropsMap);

I made a codepen if you want to check it out.

A: lookup = [];

for (var product, i = 0; product = products[i++];) {
   var cat = item.category;

   if (!(cat in lookup)) {
     lookup[cat] = 1;
     result.push(products[cat]);
   }
 }


text:
Q: Is there any tool with which I can upgrade my CE database to 4.0? I'm having trouble creating a .NET project. I already have some database with extension .sdf and whenever I intend to connect to it I get the following error:
The database file has been created by an earlier version of SQL Server Compact. Please upgrade using SqlCeEngine.Upgrade() method.

Moreover I tried upgrading my database using the following snippets:
@using System.Data.SqlServerCe
@{
    var connStringCI = "Data Source= CRM.sdf;";
    SqlCeEngine engine = new SqlCeEngine(connStringCI);
    engine.Upgrade(connStringCI);
}

This time I get the following compile error (Although I have included the .dll file in my project)
System.Data.SqlServerCe.SqlCeEngine' does not contain a definition for 'Upgrade' and no extension method 'Upgrade' accepting a first argument of type 'System.Data.SqlServerCe.SqlCeEngine' could be found (are you missing a using directive or an assembly reference?)

So I decided to use a third party tool that can do the upgrade for me. Can you introduce one?

A: You have to reference System.Data.SqlServerCe.dll version 4.0.0.0 in order to run Upgrade()


text:
Q: Need to avoid renaming large 90GB mongo database. Can I proxy one db name to another on the server? My org has a large mongo database, about 90GB, that we restore from production to staging every night with raw file backup. It is named one thing in production but needs to be named something else in staging and dev environments. The database is named "myorg-production" but we'd like to name it "myorg-staging" in other environments.
My team would like to have the database renamed in our staging environments so accidents don't happen on the real production database. If the names are the same and both say production it's likely to confuse at least 1 team member at some point and cost us.
Changing the name in Mongo (2.6 at least) is difficult especially with a large database. You essentially need to export and import a whole new db to achieve a simple rename.
We'd like to somehow proxy requests with a database name alias. Is there an app or tool out there, internal or external to mongo, that can proxy the traffic based on the db name?
Anyone have any idea how I could solve this without having to copy the entire database in the process?


text:
Q: Is open (topological) smooth embedding equivalent to injective local (homeomorphism) diffeomorphism? I could have sworn I saw a question like this before, but I can't find it. Anyway:
Let $F: N \to M$ be a (continuous) smooth map from (topological) smooth $n$-manifold $N$ to (topological) smooth $m$-manifold $M$.
Question 1: Is this true?

$F$ is open (topological) smooth embedding if and only if injective local (homeomorphism) diffeomorphism.

Question 2 and Context for Question 1: $A$ is a smooth embedded $k$-submanifold of $M$, with $0 \le k \le m$, if and only if inclusion $\iota: A \to M$ is a smooth embedding. (This is either a theorem or a definition.) When we have $k=m$ itself, $\iota$ must surely be more than just a smooth embedding. I believe $\iota$ is an open smooth embedding, equivalently an injective local diffeomorphism. Is this right? And then for continuous case: upgrade topological embedding to open topological embedding, i.e. injective local homeomorphism. (See here or here.)
Definitions, Notes (I moved proof to answer):

*

*Definition of topological embedding := The induced map $\tilde F: N \to F(N)$ is a homeomorphism = $F$ is injective, continuous and open onto its image. = $\tilde F$ is injective, continuous and open.

*Definition 1 of smooth embedding := topological embedding + immersion

*Definition 2 of smooth embedding: $F(N)$ is smooth embedded $m$-submanifold of $M$, and then the induced map $\tilde F: N \to F(N)$ is diffeomorphism. (or say $F(N)$ is smooth embedded $k$-submanifold with $0 \le k \le m$ and then $k$ will turn out $k=m$.)

*Definition of local (homeo) diffeo: For all $p \in N$, there exists open subset $p \in U$ of $N$ s.t. $F(U)$ is open in $M$ and $F|_U: U \to F(U)$ is a (homeomorphism) diffeomorphism.

*

*Note 1: By '$F|_U: U \to F(U)$', I of course mean: Let $H=F|_U: U \to M$. Then consider the induced map $G=\tilde H: U \to H(U)=F(U)$. Then '$F|_U: U \to F(U)$' refers to $G$ instead of $H$.

*Note 2: I understand '$F|_U: U \to F(U)$ is a diffeomorphism.' to be equivalent to '$F|_U: U \to M$ is a smooth embedding.' (In re Note 1: $G$ is diffeomorphism if and only if $H$ is smooth embedding.)

*Note 3: I understand the following conditions to be equivalent:

*

*Condition 3.1. $F(U)$ is open in $M$.

*Condition 3.2. $F(U)$ is a smooth $k$-submanifold of $M$, and $n=m$.

*Condition 3.3. $F(U)$ is a smooth $k$-submanifold of $M$, and $F(N)$ is open in $M$.

*Condition 3.4. $F(N)$ is smooth $k$-submanifold of $M$, and then $F(U)$ is open in $F(N)$.

A: For continuous case:

*

*If direction:

Local homeo is open onto its image: Open (see (1)) is actually stronger than open onto its image (and is equivalent to open onto its image + its image is open).

*

*Only if direction:

Open topological embedding is local homeo: Let $p \in N$. Choose $U = N$ itself.
For smooth case:

*

*If direction (using Definition 1):

*

*Local (homeo) diffeo is open.

*Local diffeo is immersion. (actually immersion = local smooth embedding. So, given that diffeo implies smooth embedding, we can think of adding 'local' to both sides of the implication.)

*(For continuous case)

*Injective local diffeo is (injective local homeo and thus a fortiori) a topological embedding.

*

*If direction (using Definition 2):

*

*Local diffeo is open.

*By (1), image is (topological) smooth embedded $m$-manifold of $M$. (The conclusion here is equivalent to that $\iota: F(N) \to M$ is a smooth embedding. However, we still wanna show $F$ is also a smooth embedding.)

*$\tilde F: N \to F(N)$ is diffeo:

*

*3.1. $\tilde F$ is open if and only if $F$ is open onto its image: '$F$ is open' is stronger than '$F$ is open onto its image' (and is equivalent to open onto its image + its image is open).

*3.2. $\tilde F$ is injective since $F$ is injective.

*3.3. $\tilde F$ is smooth: It's a rule that $F$ and $F(N)$ smooth $k$-submanifold (even if $k \ne m$) implies $\tilde F$ smooth.

*3.4. $\tilde F^{-1}$ is smooth: It's a rule that this is equivalent to that $F$ is an immersion. It's part of proving the equivalence of Definitions 1 and 2.

*Only if direction:

*

*Smooth embedding is (topological embedding and thus a fortiori) injective.

*Open smooth embedding is local diffeo: Let $p \in N$. Choose $U = N$ itself.


text:
Q: The type or namespace name 'Models' does not exist in the namespace 'FirstApp' (are you missing an assembly reference?) in visual studio 2013
The type or namespace name 'Models' does not exist in the namespace
'FirstApp' (are you missing an assembly reference?)   F:\ASP.NET
MVC\FirstApp\FirstApp\App_Start\IdentityConfig.cs 13  16  FirstApp

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using FirstApp.Models;

namespace FirstApp
{
    public class EmailService : IIdentityMessageService

    {
        public Task SendAsync(IdentityMessage message)
        {
            // Plug in your email service here to send an email.
            return Task.FromResult(0);
        }
    }
}

A: This is way late to the game, but as long as your code is correct, there is a bug in visual studio 2012 and 2013 that causes VS to loose intellisense and and other settings for no apparent reason. Oh, and MS refuses to fix it. Solution is to close vs, delete the .suo file then reopen vs.
https://connect.microsoft.com/VisualStudio/feedback/details/760443/visual-studio-2012-ide-loses-intellisense-and-reference-resolution


text:
Q: How to join multiple dataframes and if a unique key doesn't exist, add it as an additional row If I have 3 datasets:
**df1**
ID AMOUNT-2008
1  50
2  60
3  70
4  80
6  80

  **df2**
    ID AMOUNT-2009
    2  50
    3  60
    4  70
    5  80

  **df3**
    ID AMOUNT-2010
    6  60
    7  70
    2  80
    8  90

How would I join them so that the result would be
 **Combined**
  ID AMOUNT-2008   AMOUNT-2009   AMOUNT-2010
    1  50           0
    2  60           50             80
    3  70           60
    4  80           70
    5               80
    6  80                          60
    7                              70
    8                              90

left join doesnt seem to work because if the ID doesnt exist in one of the data frames, then it wont let me add a new row with the ID
PS sorry about formatting, still getting the hand of this

A: One method is a full join and I would suggest the using clause as well:
select id, df1.amount_2008, df2.amount_2009, df3.amount_2010
from df1 full join
     df2
     using (id) full join
     df3
     using (id);

A: Just use dplyr::full_join twice or dplyr::full_join with Reduce:
df1 <- read.table(text = "ID AMOUNT-2008
                          1  50
                          2  60
                          3  70
                          4  80
                          6  80", header=TRUE)

df2 <- read.table(text = "ID AMOUNT-2009
                          2  50
                          3  60
                          4  70
                          5  80", header=TRUE)

df3 <- read.table(text="ID AMOUNT-2010
                        6  60
                        7  70
                        2  80
                        8  90", header=TRUE)

dplyr::full_join(dplyr::full_join(df1, df2), df3)
Reduce(dplyr::full_join, list(df1, df2, df3))

This gives:
ID AMOUNT.2008 AMOUNT.2009 AMOUNT.2010
1  1          50          NA          NA
2  2          60          50          80
3  3          70          60          NA
4  4          80          70          NA
5  6          80          NA          60
6  5          NA          80          NA
7  7          NA          NA          70
8  8          NA          NA          90


text:
Q: C# Winforms show while loading from database into listView I am loading from a database into a listView but I need to show the population progress while loading.  Currently the data is displayed only after the loading is completed. This is what I have done so far, and thank you for any help:
string SQLCommand = "SELECT * FROM table";
using(SQLiteConnection con = new SQLiteConnection(connectionString))
{
    con.Open();
    using (SQLiteCommand cmd = new SQLiteCommand(SQLCommand, con))
    {
        using (SQLiteDataReader rdr = cmd.ExecuteReader())
        {
            while (rdr.Read())
            {
                var v1 = (rdr[3].ToString());
                var v2 = (rdr[4].ToString());
                var v3 = (rdr[5].ToString());
                var v4 = (rdr[6].ToString());

                ListViewItem item1 = new ListViewItem(v1);
                item1.SubItems.Add(v4);
                item1.SubItems.Add(v2);
                item1.SubItems.Add(v3);
                lvwDetails.Items.AddRange(new ListViewItem[] { item1 });
                System.Threading.Thread.Sleep(2000);
            }
        }
    }
}

A: You need to make the SQL processing happen in a background Thread or Task and the call the Dispatcher or UI thread to make the update.
Display the "Loading" info before starting the background task, then when the async task completes you should call the UI thread to update the UI with the data and also remove the loading info
I dont know all the context of you app but i assume that the code you show there is ran under the UI main thread, and putting Thread.Sleep isnt making it async, its just freezing your UI until the loading is done.


text:
Q: Allow only A-I 0-9 and the symbols $# (RegEX) I`m currently working on a student project in C#, and I want to check if a string contains only the following characters:
A-I
0-9
$
#
The original string:
string rawData ="$A008B20130503C103804D00000000E1022F0080G0128H022I022#";

My code is as follows:
string regEXstring = @"^[A-I0-9$#]+$";
Regex regex = new Regex(regEXstring);
if (regex.IsMatch(rawData))
   {
       dataOK = true;
   }
   else
       dataOK = false;

What am I doing wrong?

A: Fixing your rawdata/rawData typo, the code works fine. The dataOK variable becomes true with your example data, and false if one adds other characters to the string.
Judging from your example data, you can improve the verification so that you can also determinte that:

*

*the string starts with $

*the string ends with #

*the strings contains entities that consist of a single character followed by at least three digits

For that, use a pattern like:
string regEXstring = @"^\$([A-I]\d{3,})+#$";


text:
Q: Insert html form templates using angularjs I'm an angular js newbie, so this might sound trivial.
I'm trying to insert html form templates via a angularjs directive.Its like a user selects a particular form template and that template is then inserted into the page.
Being new to angularjs i have no idea how to achieve this.
Any pointers to implement this would be appreciated.

A: Read the AngularJS Directive Documentation - specifically, you'll be interested in the template and templateUrl parameters.
You can write out your template as a string, like template: '
foo
', or pass in the path to the file containing your html, like templateUrl: 'partials/mytemplate.html'.


text:
Q: The hypersurface is disconnected Let $F\in k[x_0,x_1,..,x_n]$, and $X=V(F)=\{p\in k^n: F(p)=0\}$. Let $A=\frac{k[x_1,..,x_n]}{(F)}$.
Suppose $A$ has a non-trivial idempotent, then prove that $X=X_1\sqcup X_2$, that is $X$ is disconnected.
This is the problem I am trying to work out, from Miles Reid book. This is my attempt.
Let $f\in A$ be the idempotent. Then if $g=1-f$, then $A$ can be written as $A=Af\oplus Ag$. Is it true that $X=V(F)=V(f)\sqcup V(g)$? Thank you.
In the book, we have not yet identified, $Spec A$ and $V(F)$.

A: In $\mathbb A_k^n$, we have the inclusion $X=V(F) \subset V(f) \cup V(g)$, because $fg=f-f^2 \in (F)$, i.e. any root of $F$ is a root of $fg$ and thus of $f$ or $g$.
Clearly $V(f) \cap V(g) = \emptyset$ by the virtue of $f+g=1$.
Thus, with $X_1 = X \cap V(f)$ and $X_2 = X \cap V(g)$, we have the desired $$X=X_1\sqcup X_2.$$


text:
Q: Left-align a multi-line label using plotly In the chart below, is there anyway to left-align all the text so that, for example, Total is located directly above Pct. Total, as shown below:

library(dplyr)
library(plotly)
library(scales)

dat <- data.frame(grp = c("A", "B", "C"),
                  val = c(100, 50, 50)) %>%
  mutate(label = paste0("Total: ", val, "\nPct. Total: ", percent(val/sum(val))))

         dat %>%
           plot_ly(x = ~val,
                   y = ~grp,
                   type = "bar",
                   text = ~label,
                   textposition = "outside") %>%
           layout(xaxis = list(range = c(0, 125)))

Edit: Solved
dat %>%
   plot_ly(x = ~val,
           y = ~grp,
           type = "bar") %>%
   layout(annotations = list(text = ~label,
                             y = ~grp,
                             x = ~val,
                             showarrow = F,
                             xanchor = "left",
                             align = "left"),
          xaxis = list(range = c(0, 125)))

A: Solution:
dat %>%
   plot_ly(x = ~val,
           y = ~grp,
           type = "bar") %>%
   layout(annotations = list(text = ~label,
                             y = ~grp,
                             x = ~val,
                             showarrow = F,
                             xanchor = "left",
                             align = "left"),
          xaxis = list(range = c(0, 125)))


text:
Q: Cross-region copy fails for Linode Object Storage We're using boto3 with Linode Object Storage, which is compatible with AWS S3 according to their documentation.
Everything seems to work well, except cross-region copy operation.
When I download an object from source region/bucket and then upload it to destination region/bucket, everything works well. Although, I'd like to avoid that unnecessary upload/download step.
I have the bucket named test-bucket on both regions. And I'd like to copy the object named test-object from us-east-1 to us-southeast-1 cluster.
Here is the example code I'm using:
from boto3 import client
from boto3.session import Session

sess = Session(
    aws_access_key_id='***',
    aws_secret_access_key='***'
)

s3_client_src = sess.client(
    service_name='s3',
    region_name='us-east-1',
    endpoint_url='https://us-east-1.linodeobjects.com'
)
# test-bucket and test-object are already exists.

s3_client_trg = sess.client(
    service_name='s3',
    region_name='us-southeast-1',
    endpoint_url='https://us-southeast-1.linodeobjects.com'
)

copy_source = {
    'Bucket': 'test-bucket',
    'Key': 'test-object'
}
s3_client_trg.copy(CopySource=copy_source, Bucket='test-bucket', Key='test-object', SourceClient=s3_client_src)

When I call:
s3_client_src.list_objects(Bucket='test-bucket')['Contents']

It shows me that the test-object exists, But when I run copy, then it throws following message:
An error occurred (NoSuchKey) when calling the CopyObject operation: Unknown
Any help is appreciated!