text:
Q: Progressbar in Recyclerview I am working on a android project in which there will be a Recyclerview consisting of items(rows). At run time whenever item(row) is added to the Recyclerview, it starts uploading to server and updates the progressbar in that item(row). Each Item here is a file. Everything goes fine as long as the items are added till the size of the screen. Whenever items cross the screen limit, I would need to scroll. While scrolling, progressbar updating on different item. sometimes on two or more items. After googling a lot, I understood that it is because of the Recyclerview reusing already created viewholders.
here is my Adapter Code of recyclerview:
    public class MyViewHolder extends RecyclerView.ViewHolder {

    private TextView filename;

    private ProgressBar file_progressbar;

    public MyViewHolder(View v) {

        super(v);

        filename = (TextView) v.findViewById(R.id.filename);

        file_progressbar = (ProgressBar) v.findViewById(R.id.file_progressbar);

    }

}

    public void onBindViewHolder(final MyViewHolder holder, final int position) {

    final String fname = fDataset.get((fDataset.size() - 1) - position);

    File f = new File(fname);

    holder.filename.setText(f.getName());
             if(internetchek.isNetworkAvailable(this.ctx))
             {

                 holder.file_progressbar.setVisibility(View.VISIBLE);

                 upload up = new upload(this.ctx,fname,holder.file_progressbar,"uploadstart");

                 up.execute();
             }
            else {

                 Toast.makeText(this.ctx, "Offline", Toast.LENGTH_LONG).show();

             }

        }

I have passed holder.file_progressbar into upload class. So that the progressbar gets updated in Upload class. I am not getting any idea how to resolve this issue. Thanks in advance

A: Try to add separate flags for your data like this
private boolean isItemUpdating(int position) {
     return mDataUpdatingFlags[position];
}

private void setItemUpdating(int position, boolean isUpdating) {
     mDataUpdatingFlags[position] = isUpdating;
}

Then in your onBindViewHolder call these method to setup your progress correctly:
if (isItemUpdating(position) {
    holder.showProgressBar();
} else {
    holder.hideProgressBar();
}


text:
Q: как загрузить видео в google colab начал изучать нейросети. Можно ли в google colab загружать видео.
Хочу чтобы нейросеть определяла есть ли на видео кошка например.

A: На текущий момент, Вы можете размещать файлы на Google Drive
Обращаться к диску,
from google.colab import drive
drive.mount('/content/drive')

Вы его там увидите, напрямую или скачивать с него.
Можно так же постоянно предварительно скачивать файлы с другим мест на  локальный Colab диск среды, коротая Вам дается. Много времени это не занимает.
А вот отображением больших видео более 10Мб (если хотите на видео найденного кота посмотреть в Colab) нужна нормальная прямая URL ссылка на файл, которую получить трудно.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is Static Class a reference type or a value type? Whether static class is a reference type or a value type?
it would be really helpful if any one gives a good explanation

A: Value and Reference type is about instances of Types. A static class cannot be instantiated and hence this question is not relevant to static classes.
a static class can only contain static members and static members (like properties) are created once for the entire application, so if you change its value, it changes everywhere in your application.

A: Class is always a reference type irrespective of whether it is static or non-static.

A: i think what you are referring to are members of static class.. and they are reference types if they are actually objects otherwise they are simply value types.
a static class inself cannot be passed around as for as i know.
try running this code
class Program
    {
        static void Main(string[] args)
        {
            StaticClass.x = 89;
            Console.WriteLine(StaticClass.x);
            changeValue(StaticClass.x);
            Console.WriteLine(StaticClass.x);
            Console.ReadKey();
        }
        static void changeValue(int x)
        {
            x = x + 1;
        }
    }
{
    public static class StaticClass
    {
        public static int x { get; set; }
    }
}

EDIT:-
the output is 89 in both the cases
EDIT:-
and still if you dig a little deep a static class is basically a class with a private constructor and no state(Variables) associated with it(unlike the example i have provided). so YES in theory it is a reference type

A: I just want to add that a Static Class is both a Class and a Type. The static constructor is called one time so it is "created" by the CLR as a Type when first "referenced" in a program, and so is a true class reference type.
But I like to think of the implementation or rather "use" of a Static Class as an empty Type or "class name" only, as that's really how its members are accessed and how it performs. Therefore think of the created Static Class as a hollow pointer to its methods and properties only, not as a pointer to a real instantiated class object that contains those things as a true non-static class would.

A: Yes, static classes are considered as reference types as when you change a StaticClass.Property value within a method, this change will get populated everywhere you reference this class. It has only one memory address and can't be copied, so that when another method or property call will occur, this new value will prevail over the old one.

A: Non of them because you cannot copy it as value type and you cannot instantiate it as reference type. This question does not make sense but it does reside on stack like structs, int, double, but it does not allow you to be copied!


text:
Q: Web Link using DialogFragment I have this dialog fragment, but i'm trying to get it so that when a user clicks on the "My Other Apps" Button they get redirected to a web address. Is there any way of doing this.
Any help is appreciated
Thanks
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    // TODO Auto-generated method stub

    AlertDialog.Builder theDialog = new AlertDialog.Builder(getActivity());
    theDialog.setTitle("About");
    String d1 = "Thanks For Downloading! ";
    String d2 = "Made by ME";
    theDialog.setMessage(d1 +"\n"+ d2 );
    theDialog.setPositiveButton("My Other Apps", new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getActivity(), "Clicked My Other Apps",
                    Toast.LENGTH_SHORT).show();

        }

    });

    theDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){

        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(getActivity(), "Clicked Cancel",
                    Toast.LENGTH_SHORT).show();

        }

    });
    return theDialog.create();
  }
}

A: Do this on your button click:
 @Override
 public void onClick(DialogInterface dialog, int which) {
     String url = "http://www.example.com";
     Intent i = new Intent(Intent.ACTION_VIEW);
     i.setData(Uri.parse(url));
     startActivity(i);

 }

A: @Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub

AlertDialog.Builder theDialog = new AlertDialog.Builder(getActivity());
theDialog.setTitle("About");
String d1 = "Thanks For Downloading! ";
String d2 = "Made by ME";
theDialog.setMessage(d1 +"\n"+ d2 );
theDialog.setPositiveButton("My Other Apps", new DialogInterface.OnClickListener(){

@Override
public void onClick(DialogInterface dialog, int which) {
    String url = "http://www.example.com";
    Intent i = new Intent(Intent.ACTION_VIEW);
    i.setData(Uri.parse(url));
    startActivity(i);

}

});

theDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){

@Override
public void onClick(DialogInterface dialog, int which) {
    Toast.makeText(getActivity(), "Clicked Cancel",
    Toast.LENGTH_SHORT).show();

}

});
return theDialog.create();
}
}


text:
Q: Insert com dois selects diferentes Esse meu insert não está funcionando.
insert into t_cmo_oit1980 (id_oit, id_exm_rea)
    select max(id_oit) + 1 from t_cmo_oit1980,
    select id_exm_rea from t_cmo_Exame_Realizado where id_exm = 3936 and id_xfc = 39517;
    go

Fiz uma gambi e gerei na mão o valor do primeiro campo e mesmo assim não funcionou. Fiz assim:
insert into t_cmo_oit1980 (id_oit, id_exm_rea)
    6574,
    select id_exm_rea from t_cmo_Exame_Realizado where id_exm = 3936 and id_xfc = 39517;
    go

A: Faltou transformar seus sub-select em um select válido para a cláusula Values:
insert into t_cmo_oit1980 (id_oit, id_exm_rea)
    select
      (select max(id_oit) + 1 from t_cmo_oit1980),
      (select id_exm_rea from t_cmo_Exame_Realizado where id_exm = 3936 and id_xfc = 39517);
    go

Referência:
Adicionando linhas usando INSERT e SELECT


text:
Q: If we are using annotation based hibernate then do we require hbm.xml? I am new to hibernate.I saw in my project we are using annotation for hibernate and we have not defined mapping class anywhere.In this project we are using spring also.so my question is If we are using annotation based hibernate then do we require hbm.xml?

A: If you're referring to Hibernate XML mapping files, they're definitely not required if you're using Hibernate Annotations.
Hibernate Annotations is an alternative to Hibernate XML Mapping files. They've got the same goal, which is among other things to define how an Entity maps to database columns, and how it relates to other Entities.
Actually you'd need to decide for a model or the other (Annotations or XML mappings). It is also possible to use an hybrid model, where some Entities are mapped with Annotations and some are mapped with XML mapping files. As explained for instance in Is it possible to use both annotations and hbm.xml files in the same project in Hibernate?

A: There are 2 ways to map your entities(Objects) with relations(Tables). use of Xml files are now obsolete but i would say if you are using Xml files then you can have clean entities with no annotation at all so you can migrate to any other ORM framework and use these entities. refer here to learn http://docs.jboss.org/hibernate/orm/3.6/quickstart/en-US/html/hibernate-gsg-tutorial-basic.html#hibernate-gsg-tutorial-basic-mapping
You can also use annotation to map the entities thus it will require less code.Refer here to learn http://docs.jboss.org/hibernate/stable/annotations/reference/en/html_single/#entity-mapping-entity
finally no hbm.xml file required if you are using annotation for map your entities.

A: Traditionally, Hibernate relies on external XML files for its configuration: database mappings are defined in a set of XML mapping files and loaded at startup time.
There are many ways to create these mappings, either automatically, from an existing database schema or Java class model, or by hand.
In any case, you can end up with a considerable number of Hibernate mapping files.
Alternatively, you can use javadoc-style annotations, though this adds an extra step in your build process.
And You also do not require hbm.xml files if you are using annotations.
Here is the quick reference for all you need to know about mappings for hibernate


text:
Q: How can I create a polygon body in Box2D Android? I am new to androidBox2D and I want to create a polygon body such as a rectangle or a triangle
using Box2D in Android.
I was not getting the B2FixtureDef in my code when I was creating a body. What may be the reason for that?
But I am getting BBFixtureDef. What is the difference between B2FixtureDef and BBFixtureDef?

A: Here is the code for my Box2D (LibGDX box2D library):
CODE:
            protected static CCSprite _rect1 = null;
....
            _rect1 = CCSprite.sprite("NAMEOFIMAGE.png");
            _rect1.setPosition(CGPoint.make(-10, -10));
            this.addChild(_rect1);
            //Create box
            BodyDef Box1BodyDef = new BodyDef();
            Box1BodyDef.type = BodyType.DynamicBody;
            Box1BodyDef.position.set(350/PTM_RATIO, 80/PTM_RATIO);

            // The body is also added to the world.
            Body Box1Body = _world.createBody(Box1BodyDef);
            Box1Body.setUserData(_rect1);

            // Define the shape.
            PolygonShape Box1Box = new PolygonShape();

            Box1Box.setAsBox(10/PTM_RATIO, 50/PTM_RATIO);
            Box1Body.createFixture(Box1Box,1.5f);


text:
Q: Как сделать, чтобы анимацию нельзя было прекратить? Как сделать, чтобы анимацию нельзя было прекратить? У меня есть анимация смерти и на последнем кадре игрок уничтожается со сцены, но из этой анимации можно перейти в другую и тем самым до последнего кадра не доходит и игрок не удаляется.

A: Можно использовать параметры аниматора.
Создаем новый параметр с именем IsLive типа bool со значением по умолчанию true.

При смерти нам будет необходимо поменять значение этого параметра на false.
Можно сделать таким образом:

*

*Выбираем стейт Death

*Щелкаем по AddBehavior

*Добавляем такой скрипт

using UnityEngine;

public class Death : StateMachineBehaviour
{
    override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        animator.SetBool("IsLive",false);
    }

}

Если у вас есть метод смерти где-то в другом месте, вы можете прописать animator.SetBool("IsLive",false); там, предварительно сохранив ссылку на нужный Animator где-нибудь в старте.
Ну и дальше для всех ваших переходов из AnyState просто добавляем условие IsLive == true


text:
Q: i have an inventory program, and it wont load my results i have this inventory program, but i cant get the information to load. I'm pretty new to programming. i think its either the for loop in the load method. or it could be the myinven[I] = new Item(iID); in the load method.
public class Inventory {
    int count = 0;
    int max = 4;
    Item[] myinven = new Item[max];
    Scanner input = new Scanner(System.in);

    public void save() {
        PrintWriter outputStream = null;
        try {
            outputStream = new PrintWriter(new FileOutputStream("Inventory.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("Error opening the file");
        }
        for (int I = 0; I <= count - 1; I++)
            if (outputStream != null) {
                outputStream.println(myinven[I].getID());
                outputStream.println(myinven[I].getname());
                outputStream.println(myinven[I].getdescription());
                outputStream.println(myinven[I].getonhand());
                outputStream.println(myinven[I].getunitprice());
                outputStream.close();
            }
    }

    public void load() {
        Scanner inputStream = null;
        try {
            inputStream = new Scanner(new FileInputStream("Inventory.txt"));
        } catch (FileNotFoundException e) {
            System.out.println("The File was not found");
        }

        for (int I = 0; I <= count - 1; I++) {
            if (inputStream != null) {
                while (inputStream.hasNext()) {
                    myinven[I] = new Item(inputStream.nextInt());
                    myinven[I].setname(inputStream.nextLine());
                    myinven[I].setdescription(inputStream.nextLine());
                    myinven[I].setonhand(inputStream.nextInt());
                    myinven[I].setunitprice(inputStream.nextDouble());
                    inputStream.close();
                }
            }
        }
    }
}


text:
Q: Scripting to remove specific characters in ArcGIS 10.4 I am unable to find in the Help / Resource the script if there is one, to remove certain characters in a column. Example  MPRR-BLK39-T4S-29-01. I want to get rid of T4S for 25 parcels. Instead of going to each individual parcel and manually edit, is there a certain script that will delete out "T4S"?

A: I assume the dataset is an ESRI format.  If so, you can use arcpy.UpdateCursor.
import arcpy

ds = r'path_to_dataset'

with arcpy.da.UpdateCursor(ds, ['Field1']) as cursor:
    for row in cursor:
        if 'T4S' in row[0]:
            row[0] = row[0].replace('T4S', '')
            cursor.updateRow(row)

del cursor

A: This isn't a scripting solution, more of a workaround...
You could export your table to a csv and make the edit in something like notepad++ or excel doing a simple "Find and Replace".
I would suggest at this point, if you have exported all columns, to delete them all except for the one you have edited and a column that holds a unique identifier for each record.
You could then join this csv file back to your dataset in ArcGIS using your unique identifier field and either delete the original column (the one with the incorrect values) or use the Field Calculator to update the original column with the values from the newly imported column.


text:
Q: JavaScript onclick event failing I am generating html with append() and then
I am trying to simply alert on click button, but it is failing.
My JavaScript Before Appending
$(document).ready(function() {

    function testFunction() {
        alert("simplty alert");
    }

    $('#selUsersToSendMail').click(function() {
        var selUsersArray = [];

        $(".tableBodyConfirmUser1").html('');

        $(".selUsersClass:checked").each(function() {
            var ids = $(this).attr('value');
            $(".tableBodyConfirmUser1").append("
" + $("#selUserId_" + ids).html() + "
");

            selUsersArray.push(ids);
        });

        $(".tableBodyConfirmUser1").append("
<input type='button' style='width:50px;' name='sendMailBtn' id='sendMailBtn' class='sendMailBtn' value='Select' onclick='testFunction();'/>
");

    });

});

My HTML after appending

            Select
            Name
            Email

            <input type="checkbox" name='selUsr' value = "3" class='selUsersClass'/>
            saurav
            saurav1214@gmail.com

            <input type="checkbox" name='selUsr' value = "4" class='selUsersClass'/>
            bhupinder
            bhupi@gmail.com

            <input type="button" style='width:50px;'name='sendMailBtn' id='sendMailBtn' value='Select' onclick='testFunction();'/>

A: Change the line
$(".tableBodyConfirmUser1").append("
<input type='button' style='width:50px;' name='sendMailBtn' id='sendMailBtn' class='sendMailBtn' value='Select' onclick='testFunction();'/>
");

to
$(".tableBodyConfirmUser1").append("
<input type='button' style='width:50px;' name='sendMailBtn' id='sendMailBtn' class='sendMailBtn' value='Select'/>
");

ie. remove the onclick and write this:
$(document).ready(function() {

     // delegate event handler for upcoming dom element
     // aka live event

     $('.tableBodyConfirmUser1').on('click', '#sendMailBtn', function() {
        alert('Button clicked');
     });

     // your code
});

A: You have to bind click event for the button :-
 $("#sendMailBtn").click(function() {
      alert("Handler for .click() called.");
    });

So your code will basically should be like :-
$(document).ready(function() {

    $("#sendMailBtn").click(function() {
      alert("Handler for .click() called.");
    });

    $('#selUsersToSendMail').click(function(){
                var selUsersArray = [];

                $(".tableBodyConfirmUser1").html('');

                $(".selUsersClass:checked").each(function () {
                    var ids = $(this).attr('value');
                    $(".tableBodyConfirmUser1").append("
"+$("#selUserId_"+ids).html()+"
");

                    selUsersArray.push(ids);
                });

                $(".tableBodyConfirmUser1").append("
<input type='button' style='width:50px;' name='sendMailBtn' id='sendMailBtn' class='sendMailBtn' value='Select'/>
");

            });

});

Check the updated fiddle
Note:- i have removed testFunction() from HTML.


text:
Q: Git push takes forever When I am trying to push to my remote git repository, but it is taking forever and nothing happens. I waited for so long, but push is never getting finished. My OS is Ubuntu 12.10. Thank you.

A: Ensure you're using the right protocol.
Depending on how you have your local configurations set up, you might need to use https to connect.  To do so, switch the protocol for the remote repository from the git@github.com:[user]/[repo] protocol to the https://github.com/[user]/[repo].git protocol.
Also, it's worth trying vice versa, if you're unable to use the https protocol. On older configurations, the older git@github user authentication will often allow you to connect as a fallback.

A: Try using the --verbose option to see what actually happens. Even if you did small changes, some internal things might cause git to push a lot more data.
Have a look at git gc. It cleans up your local repository and might speed up things, depending on you issue. Backup strongly advised.

A: I have faced a similar issue using git bash. Using these commands helped.
git config --global core.preloadindex true
git config --global core.fscache true
git config --global gc.auto 256

https://blog.praveen.science/solution-to-git-bash-is-very-slow-in-windows/

A: Ensure you are authenticated to github: For me, it was my authentication. I was running the command with git bash on windows and for some reason, it didn't prompt me to authenticate.
when I ran it with the command prompt, I got this
Select an authentication method for 'https://github.com/':
1. Web browser (default)
2. Personal access token
option (enter for default):

after I successfully authenticated, it worked fine

A: Please check the permission rights on the remote dir. In my case, after setting the correct permissions by chown -R user.group /dir, the commit is correctly finished:
$ git push --verbose
Pushing to ssh://user@domain.zone:port/dir
user@domain.zone's password:
Counting objects: ...
...
Total 123 (delta 21), reused 16 (delta 12)
To ssh://domain.zone:port/dir
 * [new branch]      master -> master
updating local tracking ref 'refs/remotes/origin/master'

A: I had the same problem. If you are using Bitbucket.org, I don't know why, but disabling IPV6 connection fixed the problem.

A: One possibility might be that you have large binary file(s) commited in the latest commit. git is not good at working with binary file. If commiting binary files was a mistake, you can refer to following answer for getting rid of binary file in commit.
https://stackoverflow.com/a/58987943/8694152

A: Every time I reinstall or upgrade Ubuntu (all 3-4 times), I had to go to the DNS settings of my internet connection (both Ethernet and Wifi), remove Automatic and add 8.8.8.8 and 1.1.1.1. After a reset git push and all other git-origin-accessing commands go down from 1 minute to a few seconds.

A: For people cloning repositories and then pushing to a new remote -
If you are starting a new project from a clone, (from the CLI without a fork) when you push to a blank remote you are pushing the entire history of the project you just cloned. This is going to take some time. If you just need the clone as it stands and you don't want the history, delete the .git directory after you clone it, then re-initialize the local repo with git init and push it to your new remote. Should push quickly.

A: Delete every settings file related to the keywords "vcs" and "git" in these directories (Serach "vcs" and "git" in the search bar and delete every file you see in the results):

*

*C:/Users/%USER%/AppData/Local/Google/AndroidStudio%VERSION%

*C:/Users/%USER%/AppData/Roaming/Google/AndroidStudio%VERSION%
And then restart the IDE!

A: For me it was vpn. When i disconnected from vpn it resolved.

A: I resolved my problem by rebasing my branch with the develop branch (working in a team). Here is how rebasing works.


text:
Q: storing variables when diverting to paypal for use on return url mvc4 I have a mobile web app written using mvc4, I am using it to take payments through paypal, basically, I connect to the web app which is hosted on our server, I then log in, which actually logs into a server held in the work place, which returns a username, and balance etc, which I store into a model, this is fine, I can pass this through all the views, right up to the point that the app redirects to paypal, I finish off the express checkout, and all is good, but when I return to my app I would like to display the username, amount deposited and new balance, I also have to store the amount in the server using the username etc at this point, but am unable to do so, as I lose the model when it directs away ?/
is there a way to keep hold of these variables using cookies or sessions etc ?? this is my last little bit so any advice would be very much appreciated.
Thanks

A: You could use a cookie, server-side session, or server-side database to store the data under a key that is the EC token returned by the SetEC request.  Then redirect to PayPal and, on return, you'll have that same token in the Get string and can use it as a lookup.


text:
Q: Setting variable to subfolder name based on user selection My code prompts the user to select a file. I want to set a variable to the folder name of the file location but the file is located in a subfolder.
I have this code to open the file.
fileAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.csv), _
*.csv", Title:="Select a file")
If fileAndPath = False Then Exit Sub

This is the filepath C:\Store Location\Employees\Contact Information\Phone Numbers\11373
I want to extract the 11373 part and store it as a variable

A: Okay, So you want to set a default folder for getOpenFileName.
Precede getOpenFileName with ChDir "D:\Test". If the drive is other than C: then precede ChDir with ChDrive "DriveLetter:"
Sub test()
ChDrive "D:"
Application.DefaultFilePath = "D:\Test"

fileAndPath = Application.GetOpenFilename(FileFilter:="Excel Files (*.csv),*.csv", Title:="Select a file")
If fileAndPath = False Then
Exit Sub
End If
folderPath = Left(fileAndPath, InStrRev(fileAndPath, "\") - 1)
MsgBox (Mid(folderPath, InStrRev(folderPath, "\") + 1))
End Sub


text:
Q: recompose's withPropsOnChange for inner props variable I wonder how can I user withPropsOnChange for inner variables ?
I have the object person which contains 2 objects inside that I want withPropsOnChange to run only if they (specifically changed)
{ name: 'dave', location: 'usa', age: 31 }

for this object example, I would like withPropsOnChange only if name and/or location was changed, so how do I do it ?
here an example of how I tried to play with it,
https://codepen.io/anon/pen/xWvrLV?editors=1111
as you will see the console.log doe's show the update (like the son component will receive the prop change but withPropsOnChange won't catch it) not sure how to do it the right way.
thanks


text:
Q: ImageMagick V7 and Cropping Tool I'm trying to crop an image using ImageMagick V7 on Linux CentOS 7 via the following command-line:
$convert -crop 256x256+224+384 test2.png Cropped.png

My input image is test2.png, my output image is Cropped.png. The input image is 480x640, and I want to crop it to 256x256.
The general form of the command-line is given by:
$convert -crop x_sizexy_size+x_offset+y_offset inputfile outputfile

ImageMagick cropping diagram:

My original image looks like this:

My cropped image looks like this:

You can see there's whitespace in my original image, what I want is to remove that.

A: It works OK for me but your dimensions are a bit off - for the result I think you wanted.
Note V7 uses magick and not convert; convert uses a V6 legacy version.
You should read the input image ( in most cases ) before any operation. In V7 if you use the commands in the wrong order it can fail.
I used:
$magick test2.png -crop 256x256+224+384 Cropped.png

In this case if you only wanted to remove the white area you could use -trim:
$magick test2.png -trim Cropped.png

A: It looks to me like you are trying to trim whitespace, in which case you'd be better using -trim as it will trim correctly regardless of colour (provided it is solid) and regardless of the amount of trimming required:
magick input.png -trim +repage result.png

I have added a red border purely for display purposes so you can see the extent of the cropped image even on Stack Overflow's white background.


text:
Q: polars categorical feature and lazy api doesn't work like expected I'm trying to join two Dataframes with the help of categorical features and the lazy API. I tried to do it the way it was decribed in the user guide(https://pola-rs.github.io/polars-book/user-guide/performance/strings.html)
count = admin_df.groupby(['admin','EVENT_DATE']).pivot(pivot_column='FIVE_TYPE',values_column='count').first().lazy()
fatalities = admin_df.groupby(['admin','EVENT_DATE']).pivot(pivot_column='FIVE_TYPE',values_column='FATALITIES').first().lazy()
fatalities = fatalities.with_column(pl.col("admin").cast(pl.Categorical))
count = count.with_column(pl.col("admin").cast(pl.Categorical))
admin_df = fatalities.join(count,on=['admin','EVENT_DATE']).collect()

but i get the following Error:
    Traceback (most recent call last):
  File "country_level.py", line 33, in <module>
    country_level('/c/Users/Sebastian/feast/fluent_sunfish/data/ACLED_geocoded.parquet')
  File "country_level.py", line 10, in country_level
    country_df=aggregate_by_date(df)
  File "country_level.py", line 29, in aggregate_by_date
    admin_df = fatalities.join(count,on=['admin','EVENT_DATE']).collect()
  File "/home/sebastian/.local/lib/python3.8/site-packages/polars/internals/lazy_frame.py", line 293, in collect
    return pli.wrap_df(ldf.collect())
RuntimeError: Any(ValueError("joins on categorical dtypes can only happen if they are created under the same global string cache"))

with the usage of with pl.StringCache(): everything works fine, altough the user guide says it isn't needed if you use the lazy API, do i missing something or is this a bug?

A: The user guide is incorrect. You need to set a global string cache.
You can set a global string cache with pl.StringCache(): or with pl.Config.set_global_string_cache.

import polars as pl
pl.Config.set_global_string_cache()

lf1 = pl.DataFrame({
    "a": ["foo", "bar", "ham"],
    "b": [1, 2, 3]
}).lazy()
lf2 = pl.DataFrame({
    "a": ["foo", "spam", "eggs"],
    "c": [3, 2, 2]
}).lazy()

lf1 = lf1.with_column(pl.col("a").cast(pl.Categorical))
lf2 = lf2.with_column(pl.col("a").cast(pl.Categorical))

lf1.join(df2, on="a", how="inner").collect()

Outputs:
shape: (1, 3)
┌───────┬─────┬─────┐
│ a     ┆ b   ┆ c   │
│ ---   ┆ --- ┆ --- │
│ cat   ┆ i64 ┆ i64 │
╞═══════╪═════╪═════╡
│ "foo" ┆ 1   ┆ 3   │
└───────┴─────┴─────┘


text:
Q: Differentiate $e^{-\frac{x^2}{4Dt}}$ How to differentiate $$ \exp \left( -\frac{x^2}{4Dt} \right)$$
?
(A step by step solution is sought)

A: Make the simple substitution $u=-\frac{x^2}{4Dt}=-\frac{1}{4}x^2D^{-1}t^{-1}$ and let $z=\mathrm{exp}(u)$. Then...
$$\frac{\partial z}{\partial x} = \frac{dz}{du}\frac{\partial u}{\partial x} = \mathrm{exp}(u) \cdot \left(-\frac{1}{2}xD^{-1}t^{-1} \right) = -\frac{x\cdot \mathrm{exp}\left(-\frac{x^2}{4Dt}\right)}{2Dt}$$
$$\frac{\partial z}{\partial t} = \frac{dz}{du}\frac{\partial u}{\partial t} = \mathrm{exp}(u) \cdot \left(\frac{1}{4}x^2D^{-1}t^{-2} \right) = \frac{x^2\cdot \mathrm{exp}\left(-\frac{x^2}{4Dt}\right)}{4Dt^2}$$
If $D$ is meant to be a variable, we'd also have...
$$\frac{\partial z}{\partial D} = \frac{dz}{du}\frac{\partial u}{\partial D} = \mathrm{exp}(u) \cdot \left(\frac{1}{4}x^2D^{-2}t^{-1} \right) = \frac{x^2\cdot \mathrm{exp}\left(-\frac{x^2}{4Dt}\right)}{4D^2t}$$
Now what if $D$ is constant, $x$ is a function of $t$? Then we have...
$$\frac{dz}{dt} = \frac{dz}{du}\frac{\partial u}{\partial x}\frac{dx}{dt} + \frac{dz}{du}\frac{\partial u}{\partial t}\frac{dt}{dt} =
 -\frac{x\cdot \mathrm{exp}\left(-\frac{x^2}{4Dt}\right)}{2Dt}\cdot x'(t) +
\frac{x^2\cdot \mathrm{exp}\left(-\frac{x^2}{4Dt}\right)}{4Dt^2}\cdot 1$$
Assumptions about dependencies among variables (and what is a variable) can make a big difference.


text:
Q: How to map graphQL query property to different response property? I have a graphQL type defined in a .graphql file for a nestjs schema first application. The type is:
type address {
  id: String
  Title: String
  Url: String
}

Now, using nestjs I have a resolver function as
@Query('address')
async getAll(): Promise<any> {
  return await this.addressService.getAll();
}

The result from the await this.addressService.getAll() is an array of objects with the properties having _ in them like:
[
  {
    id: 1,
    address_title: 'title',
    address_url: 'url'

  }
]

I am also using @nestjs/graphql library for the @Query, @ResolveField and such. My problem is, how can I map the response properties to the graphql properties that I have written as a SDL in the .graphql file in nestjs framework? Is there any way we can map the graphql query properties to the result properties using nestjs?
I looked at the graphql alias, also mentioned here but that is not useful for me. Any help on this is highly appreciated.

A: You may use direct approach:
@Query('address')
getAll(): Promise<any> {
  return this.addressService.getAll().map(this.addressMapper);
}

private addressMapper(address: any): address {
  return {id: address.id, Title: address.address_title, Url: address_url};
}

Or use NestJS pipes.


text:
Q: $\textrm{GL}_2(\mathbb{Z}/p^2\mathbb{Z}) \to \textrm{GL}_2(\mathbb{Z}/p\mathbb{Z})$ has no section for $p > 3$ Let $p > 3$ be a prime. I want to show that the exact sequence
$$1 \to \ker \pi \to \textrm{GL}_2(\mathbb{Z}/p^2\mathbb{Z}) \xrightarrow{\pi} \textrm{GL}_2(\mathbb{Z}/p\mathbb{Z}) \to 1$$
is not split. It's easy to check that $A = \ker\pi$ is abelian, thus $G = \textrm{GL}_2(\mathbb{Z}/p\mathbb{Z})$ acts on $K$ by conjugation, making $A$ a $G$-module. If
$$s \colon \textrm{GL}_2(\mathbb{Z}/p\mathbb{Z}) \to \textrm{GL}_2(\mathbb{Z}/p^2\mathbb{Z})$$
is a set-theoretic section of $\pi$, then
$$\alpha_s(g,h) = s(g)s(h)s(gh)^{-1}$$
defines a $2$-cocyle $G \times G \to A$ whose class in $H^2(G,A)$ is independent of the choice of section. Since $\alpha_s$ is trivial if $s$ is a homomorphism, it suffices to show that $\alpha_s$ is not a coboundary, i.e. there does not exist a function $\phi \colon G \to A$ such that
$$s(g)s(h)s(gh)^{-1} = s(g)\phi(h)s(g)^{-1}\phi(gh)^{-1}\phi(h)$$
for all $g,h \in G$.
I tried supposing such a $\phi$ exists and looking at the subgroup of $U$ unipotent matrices. Every element of $A$ is $p$-torsion, so $\alpha_s$ is a $p$-torsion elemeent of $H^2(G,A$). Since $U$ is the $p$-Sylow subgroup of $G$, the restriction map $H^2(G,A) \to H^2(U,A)$ is injective on the $p$-part of $H^2(G,A)$, so looking at the restriction of $\alpha_s$ to $U \times U$ should be sufficient.
Choose the section $s$ so that it maps $U$ to unipotent matrices in $\textrm{GL}_2(\mathbb{Z}/p^2\mathbb{Z})$. After playing around with the coboundary condition, I found that $\phi(g)$ and $s(g)$ should commute for all $g \in U$. Since $s(g)$ is unipotent, this means
$$\phi(g) = \begin{pmatrix} 1 + a_gp & b_gp \\ 0 & 1 + a_gp \end{pmatrix}$$
for some $a_g,b_g \in \mathbb{Z}/p^2\mathbb{Z}$, well-defined modulo $p$. If $s_g$ denotes the upper-right entry of $s(g)$ for $g \in U$, then the coboundary condition tells us that $g \to a_g$ is a homomorphism and
$$(b_g - b_{gh} + b_h)p = s_g - s_{gh} + s_h$$
for all $g,h \in U$. So we get a system of linear equations over $\mathbb{Z}/p\mathbb{Z}$ with $p$ variables. It's not clear to me how to show that this system is inconsistent, or how to use the hypothesis that $p > 3$. Moreover, lifting $0,1,-1$ in $\mathbb{Z}/3\mathbb{Z}$ to $0,1,-1$ in $\mathbb{Z}/9\mathbb{Z}$, I checked that this system is inconsistent over $\mathbb{Z}/3\mathbb{Z}$. But I thought that the exact sequence was supposed to be split in the case $p = 3$. So I'm unsure where I went wrong and also unsure how to proceed.

A: Let $S=\pmatrix{1&1\\0&1}\in\text{GL}_2(\Bbb Z/p\Bbb Z)$. This has order $p$,
and one's intuition suggests that any lifting to $\text{GL}_2(\Bbb Z/p^2\Bbb Z)$
should have order $p^2$, meaning that there's no section for $\pi$. But is this true?
A lifting of $S$ has the form $S'=I+A$ where
$$A=\pmatrix{ap&1+bp\\cp&dp}\in\text{GL}_2(\Bbb Z/p^2\Bbb Z).$$
Then
$$A^2=\pmatrix{cp&(a+d)p\\0&cp},$$
$$A^3=\pmatrix{0&cp\\0&0}$$
and $A^4=0$. For $p\ge5$ then
$$S'^p=I+pA+\binom p2A^2+\binom p3A^3=I+\pmatrix{0&p\\0&0}$$
which does mean that $S'$ does not have order $p$ in $\text{GL}_2(\Bbb Z/p^2\Bbb Z)$.
This argument breaks down for $p\in\{2,3\}$. For instance with $p=3$ one
has
$$S'^3=I+3A+3A^2+A^3=I+\pmatrix{0&(c+1)p\\0&0}$$
so one can take $c=-1$. Of course this is somewhat shy of proving that in
this case $\pi$ has a section, but it shows that this argument does not refute it.

A: Here is a different proof that uses more theory and less calculation.
There is a class of $p$-groups called regular $p$-groups that have various nice properties. All groups of order $p^n$ for $n \le p$ are regular, and one of the properties of regular $p$-groups is that, for any fixed $k$, the elements of order dividing $p^k$ form a subgroup.
If the extension in the question were split, then a Sylow $p$-subgroup $P$ would also split. Now $|P|=p^5$, so $P$ is regular when $p \ge 5$.
Since $\ker \pi$ is elementary abelian, if the extension split, then $P$ would be generated by elements of order $p$, and hence $P$ would have exponent $p$. But that is clearly false, because the element
$\left( \begin{array}{cc}1&1\\\ 0&1\end{array}\right)$
has order $p^2$. So the extension is non-split.


text:
Q: Running JuMP example I am trying to run this example on a fresh julia installation (Version 1.0.2 (2018-11-08)):
https://github.com/JuliaOpt/JuMP.jl/blob/master/examples/basic.jl
But I always get this error.
julia> using JuMP, Clp

julia> m = Model(with_optimizer(Clp.Optimizer))
ERROR: UndefVarError: with_optimizer not defined
Stacktrace:
 [1] top-level scope at none:0

What am I doing wrong? It seems such a simple example should run quite easily.

A: You are looking at the example from master branch from the GitHub repository. There are breaking changes in JuMP API since its last release.
You should look at basic.jl file in your local repository. It should be located in a directory location like ~/.julia/packages/JuMP/Xvn0n/examples/basic.jl (the Xvn0n part might be different in your case but the path pattern should be the same; if you are on Windows then ~ is a directory of your user profile).
The example you are referring to looks like this in the released version of the package:
using JuMP, Clp

m = Model(solver = ClpSolver())

@variable(m, 0 <= x <= 2)
@variable(m, 0 <= y <= 30)

@objective(m, Max, 5x + 3y)
@constraint(m, 1x + 5y <= 3.0)

print(m)

status = solve(m)

println("Objective value: ", getobjectivevalue(m))
println("x = ", getvalue(x))
println("y = ", getvalue(y))

You can also find the zipped sources of the latest release here https://github.com/JuliaOpt/JuMP.jl/releases/tag/v0.18.4, but of course as new releases are published the number will change so the most reliable place to look at the codes are examples that JuMP has on your local machine.


text:
Q: Error debugging in thread memory. ex: 0x1125e404b <+1114> movl I apologize if this is an answer that can be easily found online. I tried searching but probably I do not know the right terminology.
Sometimes xcode gives errors like in this screenshot.

Now in this specific case we can see that it's a EXC_BAD_ACCESS error which means that the application can't access this specific block of memory. Most likely because the code is sending a message to an object that has already been released.
What I'm missing is a more detailed summary of the screenshot. I have some assumptions about how to read it.
line 298:
0x1125e404b //Address in memory?
<+1114> //size?
movl = //... ?
%edx, (%rax) = //....?

Would really appreciate if anybody could point me to the right documentation or explain it here.
Also, is there a practical use for it? Perhaps inspecting the referenced block of memory?

A: That is a disassembly of the machine code that was executing when the crash occurred. I used to do a lot of assembler but haven't tried to work with ARM on iOS devices, but I'll give you an idea:
The first number is the absolute address in memory of the code that's executing.
The second number (I think) is the offset from the begging of the function. This is useful in tying machine code to the source code it was built from.
The next bit, movl, is the machine instruction, a move of a longword. It looks like it's moving a value from the edx register to a memory address pointed to by rax. (I don't know the ARM register notation so I'm doing a little guessing.
The crash likely occurs because the value in rax is not an accessible address.
Figuring out what it means is harder. You'd have to trace back to the beginning of the function and figure out how the different registers are used and where the value in rax comes from. To do that you'd need to study ARM assembler and the parameter passing conventions the compiler uses.
It's probably not worth the effort. Better to analyze your source code and figure out what's going on.


text:
Q: Subtracting counts (DataFrame.count()) from a DataFrame entry in Pandas I have a counts on df1 that I want to subtract from an entry in df2.
Specifically, I want to subtract the number of customers having zero income from the 2018 row in df2 :
count = df1[df1['income']==0].count()

df2.loc('2018', 'income') -= count

I get the warning:
"A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation: http://pandas.pydata.org/pandas-
docs/stable/indexing.html#indexing-view-versus-copy "
The problem seems to be that DataFrame.counts() returns a Series and not a number. Any ideas?

A: You need len for length of DataFrame:
count = len(df1[df1['income']==0])

But better is sum Trues in condition, Trues are processes like 1:
count = (df1['income']==0).sum()


text:
Q: How to update windows explorer's shell extension without rebooting There is a windows explorer extension dll.
This dll can be update automatically if there is new one in our server.
I rename the origin dll and download the new dll.
But Windows Explorer never reload a new one.
So I kill the windows explorer and relaunch.
But this is looked very ugly.
And I don't want to recommend a user should reboot.
How can I tell Windows Explorer to reload a new one?

A: For those still looking for a quicker way, you can try and close all explorer.exe processes and restart one afterwards. This also updates all shell integrated dll's

A: DLLs are loaded by the program loader, so only at process boot time.
You can make a program that explicitely opens and uses a DLL, and add a command that will close it, reopen it, rebind everything. But you need support of the program for that, so you would need Explorer to support it, or to change its code.
So, with 99% certitude, you can't do what you want without restarting windows explorer. At all.


text:
Q: cant add array number in dynamic cakephp form I am trying to make a dynamic form in CakePHP, but it seems not to work.
What can I do to make it work; I can't get data[AppliedCourses][0][institution], can't get data[AppliedCourses][1][institution], data[AppliedCourses][2][institution], etc.

            <button type="button" title="Click Here to remove Institution Applied" style="display: none;">-</button>

                Institution Name
                <input name="data[AppliedCourses][0][institution]" type="text" id="AppliedCourses0Institution" />

                Course Of Interest
                <select name="data[AppliedCourses][0][course_id]" id="AppliedCourses0CourseId">
                    <option value="1">Applied Sciences</option>
                    <option value="2">Architecture & Built Enviroment</option>
                    <option value="3">Art & Design</option>
                    <option value="4">Business / Commerce</option>
                    <option value="5">Computing & IT</option>
                    <option value="6">Communication & Media Studies</option>
                    <option value="7">Education & Language</option>
                    <option value="8">Engineering</option>
                    <option value="9">Environmental Science</option>
                    <option value="10">Health Sciences</option>
                    <option value="11">Hospitality & Tourism</option>
                    <option value="12">Humanities & Social Sciences</option>
                    <option value="13">Law & Legal Studies</option>
                    <option value="14">Music</option>
                    <option value="15">Others</option>
                </select>

                Major Field Of Course
                <input name="data[AppliedCourse][0][major]" maxlength="255" type="text" id="AppliedCourse0Major" />

                Intake
                <select name="data[AppliedCourses][0][intake][month]" id="AppliedCourses0IntakeMonth">
                    <option value="01">January</option>
                    <option value="02">February</option>
                    <option value="03" selected="selected">March</option>
                    <option value="04">April</option>
                    <option value="05">May</option>
                    <option value="06">June</option>
                    <option value="07">July</option>
                    <option value="08">August</option>
                    <option value="09">September</option>
                    <option value="10">October</option>
                    <option value="11">November</option>
                    <option value="12">December</option>
                </select>-
                <select name="data[AppliedCourses][0][intake][year]" id="AppliedCourses0IntakeYear">
                    <option value="2035">2035</option>
                    <option value="2034">2034</option>
                    <option value="2033">2033</option>
                    <option value="2032">2032</option>
                    <option value="2031">2031</option>
                    <option value="2030">2030</option>
                    <option value="2029">2029</option>
                    <option value="2028">2028</option>
                    <option value="2027">2027</option>
                    <option value="2026">2026</option>
                    <option value="2025">2025</option>
                    <option value="2024">2024</option>
                    <option value="2023">2023</option>
                    <option value="2022">2022</option>
                    <option value="2021">2021</option>
                    <option value="2020">2020</option>
                    <option value="2019">2019</option>
                    <option value="2018">2018</option>
                    <option value="2017">2017</option>
                    <option value="2016">2016</option>
                    <option value="2015" selected="selected">2015</option>
                    <option value="2014">2014</option>
                    <option value="2013">2013</option>
                    <option value="2012">2012</option>
                    <option value="2011">2011</option>
                    <option value="2010">2010</option>
                    <option value="2009">2009</option>
                    <option value="2008">2008</option>
                    <option value="2007">2007</option>
                    <option value="2006">2006</option>
                    <option value="2005">2005</option>
                    <option value="2004">2004</option>
                    <option value="2003">2003</option>
                    <option value="2002">2002</option>
                    <option value="2001">2001</option>
                    <option value="2000">2000</option>
                    <option value="1999">1999</option>
                    <option value="1998">1998</option>
                    <option value="1997">1997</option>
                    <option value="1996">1996</option>
                    <option value="1995">1995</option>
                </select>

                Submission Date
                <select name="data[AppliedCourses][0][submission_date][day]" id="AppliedCourses0SubmissionDateDay">
                    <option value="01">1</option>
                    <option value="02" selected="selected">2</option>
                    <option value="03">3</option>
                    <option value="04">4</option>
                    <option value="05">5</option>
                    <option value="06">6</option>
                    <option value="07">7</option>
                    <option value="08">8</option>
                    <option value="09">9</option>
                    <option value="10">10</option>
                    <option value="11">11</option>
                    <option value="12">12</option>
                    <option value="13">13</option>
                    <option value="14">14</option>
                    <option value="15">15</option>
                    <option value="16">16</option>
                    <option value="17">17</option>
                    <option value="18">18</option>
                    <option value="19">19</option>
                    <option value="20">20</option>
                    <option value="21">21</option>
                    <option value="22">22</option>
                    <option value="23">23</option>
                    <option value="24">24</option>
                    <option value="25">25</option>
                    <option value="26">26</option>
                    <option value="27">27</option>
                    <option value="28">28</option>
                    <option value="29">29</option>
                    <option value="30">30</option>
                    <option value="31">31</option>
                </select>-
                <select name="data[AppliedCourses][0][submission_date][month]" id="AppliedCourses0SubmissionDateMonth">
                    <option value="01">January</option>
                    <option value="02">February</option>
                    <option value="03" selected="selected">March</option>
                    <option value="04">April</option>
                    <option value="05">May</option>
                    <option value="06">June</option>
                    <option value="07">July</option>
                    <option value="08">August</option>
                    <option value="09">September</option>
                    <option value="10">October</option>
                    <option value="11">November</option>
                    <option value="12">December</option>
                </select>-
                <select name="data[AppliedCourses][0][submission_date][year]" id="AppliedCourses0SubmissionDateYear">
                    <option value="2035">2035</option>
                    <option value="2034">2034</option>
                    <option value="2033">2033</option>
                    <option value="2032">2032</option>
                    <option value="2031">2031</option>
                    <option value="2030">2030</option>
                    <option value="2029">2029</option>
                    <option value="2028">2028</option>
                    <option value="2027">2027</option>
                    <option value="2026">2026</option>
                    <option value="2025">2025</option>
                    <option value="2024">2024</option>
                    <option value="2023">2023</option>
                    <option value="2022">2022</option>
                    <option value="2021">2021</option>
                    <option value="2020">2020</option>
                    <option value="2019">2019</option>
                    <option value="2018">2018</option>
                    <option value="2017">2017</option>
                    <option value="2016">2016</option>
                    <option value="2015" selected="selected">2015</option>
                    <option value="2014">2014</option>
                    <option value="2013">2013</option>
                    <option value="2012">2012</option>
                    <option value="2011">2011</option>
                    <option value="2010">2010</option>
                    <option value="2009">2009</option>
                    <option value="2008">2008</option>
                    <option value="2007">2007</option>
                    <option value="2006">2006</option>
                    <option value="2005">2005</option>
                    <option value="2004">2004</option>
                    <option value="2003">2003</option>
                    <option value="2002">2002</option>
                    <option value="2001">2001</option>
                    <option value="2000">2000</option>
                    <option value="1999">1999</option>
                    <option value="1998">1998</option>
                    <option value="1997">1997</option>
                    <option value="1996">1996</option>
                    <option value="1995">1995</option>
                </select>

            <button type="button" title="Click Here to add another Institution" onclick="addInstitution()">+</button>

and the JS


text:
Q: Trying to run old makefile, "missing separator" I've looked through the other posts similar to mine, which have been resolved by fixing a tab or spaces, but that didn't work for me (or I'm not looking in the right place). I'm trying to download the Swarm software, whose last stable release was in the early 2000s. Maybe this is a lost cause (or I might just have to suck it up and run this in a virtual machine) but I'm getting the error "Makefile.am:1: *** missing separator.  Stop." The first part of my makefile code is:
if USEBUILTINAVCALL
SUBDIRS = $(LIBOBJCDIR) avcall etc src tools java COM m4 tests
else
SUBDIRS = $(LIBOBJCDIR) etc src tools java COM m4 tests
endif

EXTRA_DIST = VERSION macosx/buildlibs.sh macosx/ChangeLog macosx/configure.sh macosx/INSTALL.MacOSX macosx/README.MacOSX macosx/swarm.xcode/project.pbxproj

SWARM_INSTALL = @SWARM_INSTALL@

install-data-local:
    $(mkinstalldirs) $(DESTDIR)$(includedir)
    $(INSTALL_DATA) swarmconfig.h $(DESTDIR)$(includedir)
    $(INSTALL_DATA) externvar.h $(DESTDIR)$(includedir)
    $(mkinstalldirs) $(DESTDIR)$(bindir) $(DESTDIR)$(datadir)/swarm
    $(INSTALL_PROGRAM) $(top_builddir)/libtool $(DESTDIR)$(bindir)/libtool-swarm
    if test $(SWARM_INSTALL) = install-sh; then $(INSTALL_PROGRAM) $(srcdir)/install-sh $(DESTDIR)$(bindir); fi

install-recursive: install-data-local

A: This looks to me like a Makefile.in file, not a Makefile.  That is, it's intended to be converted by configure or automake.
GNU make doesn't support an if statement (it has ifdef and ifeq and ifneq, but not if).  And tokens like @SWARM_INSTALL@ are meant to be replaced.


text:
Q: perl6 How to match a character only under some conditions? I have a file in the format:
- foo bar - baz
  one two three - or four
  and another line

- next job
  do this - and that

and my grammar is
grammar tasks {
    regex TOP        { \n* <oneTask>+ \n* }
    regex oneTask    { ^^ \- (<oneSection> <endSection>)+ }
    regex oneSection { \N+ } # this is not quite working
    regex endSection { \n+ }

}
in the regex oneSection, how do I code the fact that "I want to match a '-' only when it is not at the beginning of a line"?
I put the file into a string and parse this string:
my $content = slurp("taskFile");
my $result = tasks.parse($content);

This is not quite working.
<[\N] - [\-]> does not make the match conditional.

Thanks !!

A: It is easier to put down what you want to match rather than try to exclude something.
What you are looking for is one character at the start of a line that is not a newline or a dash, followed by any number of not newlines. Or you are looking for at least one character that is not a newline that does not come after a newline.
regex oneSection {

    || ^^            # beginning of line
       <-[\n-]>      # not newline or dash
       \N*           # any number of not newlines

    || <!before ^^>  # check the position before this is not the start of a line
       \N+

}

(This is so complex because you are trying to put the complexity in the wrong spot in the grammar)

You could also match like you are currently and add a test that fails if it starts with a -.
regex oneSection {
    \N+

    <!{ # fail if the following is True
        $/.starts-with('-')
    }>
}

A Grammar is a type of Class and a Regex/Token/Rule is a type of Method. So you should probably be writing them that way by adding newlines and comments.
Writing grammars gets much nicer if you learn how to use the % and %% regex operators.
( the difference is %% can match a trailing separator )
Using % effectively can take some getting used to, so I am going to show you how I would have used it to match your file.
I also changed the separator of the sections from just a newline to a newline and two spaces. This will remove the spaces from what a section matches, which will simplify any further processing.
While you are learning I would recommend using Grammar::Debugger and Grammar::Tracer.
grammar Tasks {
    # use token for its :ratchet behaviour
    # ( more performant than regex because it doesn't backtrack )
    token TOP {
        \n*       # ignore any preceding empty lines

        <task>+   # at least one task
        %         # separated by
        \n+       # at least one newline

        \n*       # ignore trailing empty lines
    }

    token task {
      ^^ '- '     # a task starts with 「- 」 at the beginning of a line

      <section>+  # has at least one section
      %           # separated by
      "\n  "      # a newline and two spaces
    }

    token section { \N+ }
}

my $test = q:to/END/;
- foo bar - baz
  one two three - or four
  and another line

- next job
  do this - and that
END

put Tasks.parse( $test, :actions(class {
  method TOP     ($/) { make @<task>».made.List }
  method task    ($/) { make @<section>».made.List }
  method section ($/) {
    make ~$/  # don't do any processing, just make it a Str
  }
})).made.perl;

# (("foo bar - baz", "one two three - or four", "and another line"),
#  ("next job", "do this - and that"))

If I had put use Grammar::Tracer; at the top this is what it would output:
TOP
|  task
|  |  section
|  |  * MATCH "foo bar - baz"
|  |  section
|  |  * MATCH "one two three - or four"
|  |  section
|  |  * MATCH "and another line"
|  * MATCH "- foo bar - baz\n  one two three - or four\n  and another l"
|  task
|  |  section
|  |  * MATCH "next job"
|  |  section
|  |  * MATCH "do this - and that"
|  * MATCH "- next job\n  do this - and that"
|  task
|  * FAIL
* MATCH "- foo bar - baz\n  one two three - or four\n  and another line"

That FAIL is expected because there was a trailing newline and it could be followed by a task as far as the grammar knows.

A: Match anything that's not the start of the string, followed by a dash
[^$]-


text:
Q: Datetime manipulation with lists This is hard to explain but I will try to represent this in a small example:
NDD = 11/1/2018

number of payments:
1 0 2 0 2 1 1 0 2 1 1 1

Since the first month starts with 11 in NDD then the first element of my list will be 11, to compute the next element I take the first month (11) and subtract the first payment 1 and then the second element is 10. This proceeds and the pattern is clear if you follow the logic so I will have
11 10 10 8 8 6 5 4 4 2 1 12

To make it even more clear:
number_of_payments = [1 0 2 0 2 1 1 0 2 1 1 1]

Algorithm:
Step 1 - Create an empty list:
dates = []

Step 2 - Append the first month of NDD to the first index of dates
dates.append(NDD.month)

Step 3 - Now perform this formula:
for i in range(1,12):
dates[i] = (dates[i-1] + 12 - number_of_payments[i-1]) % 12

Step 4 - The final result will be
dates = [11 10 10 8 8 6 5 4 4 2 1 12]

Although I was able to do this I need to factor in the years of what NDD started with so what I want to have is THE RESULT SHOULD BE:
11/18 10/18 10/18 8/18 8/18 6/18 5/18 4/18 4/18 2/18 1/18 12/17

Now to go with what I have. This is what I have for NDD:
print(type(NDD))

Here is a view values from NDD
print(NDD[0:3])
0   2018-08-01
1   2018-07-01
2   2018-11-01

Here are the number_of_payments information:
print(type(number_of_payments))
<class 'list'>

Here is the first row (same as the example above)
print(number_of_payments[0])
[ 0.  1.  0.  1.  1.  1.  0.  5.  1.  0.  2.  1.]

This is what I am trying to do to get the result but it does not work:
dates = []
for i in range(len(number_of_payments)):
    dates.append([NDD[i]])
    for j in range(1, len(number_of_payments[i])):
        dates[i].append((dates[i][j-1] + 12 - number_of_payments[i][j-1]) % 12)
for date_row in dates:
    for n, i in enumerate(date_row):
        if i == 0:
            date_row[n] = 12
print(dates[0])

I get this error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-123-907a0962fd65> in <module>()
      4     dates.append([NDD[i]])
      5     for j in range(1, len(number_of_payments[i])):
----> 6         dates[i].append((dates[i][j-1] + 12 - number_of_payments[i][j-1]) % 12)
      7 for date_row in dates:
      8     for n, i in enumerate(date_row):

pandas/_libs/tslib.pyx in pandas._libs.tslib._Timestamp.__add__ (pandas\_libs\tslib.c:22331)()

ValueError: Cannot add integral value to Timestamp without freq.

I hope this is clear.
Entire Code:
# In[9]:

# Import modules
import numpy as np
import pandas as pd
import datetime as dt
from functools import reduce
import datetime
from dateutil.relativedelta import *

# In[10]:

# Import data file
df = pd.read_csv("Paystring Data.csv")
df.head()

# In[11]:

# Get column data into a list
x = list(df)

# In[12]:

# Append column data into cpi, NDD, and as of dates
NDD = df['NDD 8/31']
cpi = df['Contractual PI']
as_of_date = pd.Series(pd.to_datetime(df.columns.str[:8], errors='coerce'))
as_of_date = as_of_date[1:13]
payment_months =  pd.to_datetime(as_of_date, errors = 'coerce').dt.month.tolist()

# In[13]:

# Get cash flows
cf = df.iloc[:,1:13].replace('[^0-9.]', '', regex=True).astype(float)
cf = cf.values

# In[14]:

# Calculate number of payments
number_of_payments = []
i = 0
while i < len(cpi):
    number_of_payments.append(np.round_(cf[:i + 1] / cpi[i]))
    i = i + 1

# In[15]:

# Calculate the new NDD dates
# dates = []
# for i in range(len(number_of_payments)):
#     dates.append([NDD_month[i]])
#     for j in range(1, len(number_of_payments[i][0])):
#         dates[i].append((dates[i][j-1] + 12 - number_of_payments[i][0][j-1]) % 12)
# print(dates[0])
d = []
for i in range(len(number_of_payments)):
    d.append(datetime.datetime.strptime(NDD[i], '%m/%d/%Y'))
def calc_payment(previous_payment,i):
    return previous_payment+relativedelta(months=(-1*i))
dates = [d]
for p in number_of_payments:
    dates += [calc_payment(result[-1],p)]

# In[ ]:

# Calculate paystring
paystring = []
for i in range(len(payment_months)):
    for j in range(len(dates[i])):
        if payment_months[i] < dates[i][j]:
            paystring.append(0)
        elif NDD_day[j] > 1:
            paystring.append((payment_months[i] + 12 - dates[i][j]) % 12)
        else:
            paystring.append( (payment_months[i] + 12 - dates[i][j]) + 1) % 12)
print(paystring[0])

I am currently stuck on implementing Arnon Rotem-Gal-Oz solution to adapt to this. Here is also a screen shot of the data frame. Please let me know if more information would help.
Update:
I cannot seem to get any good answers since the only person that had a close solution deleted it. I have now posted this to https://www.codementor.io/u/dashboard/my-requests/5p8xirscop?from=active. Paying 100 USD for anyone to give me a complete solution and I mean totally complete not just sort of complete.

Edit:
I try to run this code
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
from functools import reduce
from dateutil.relativedelta import *
df=pd.read_csv('Paystring Data.csv')
cpi=df['Contractual PI']
start=df['NDD 8/31'].apply(pd.to_datetime).astype(datetime)
cf = df.iloc[:,1:13].replace('[^0-9.]', '', regex=True).astype(float)
payments =  cf.apply(lambda p: round(p/cpi))
diffs=payments.cumsum(axis=1).applymap(lambda i: relativedelta(months=(-1*i)))
payments=diffs.apply(lambda x: start+x)
result=pd.concat([start,payments],axis=1)

and I am getting this error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\ops.py in na_op(x, y)
    657             result = expressions.evaluate(op, str_rep, x, y,
--> 658                                           raise_on_error=True, **eval_kwargs)
    659         except TypeError:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\computation\expressions.py in evaluate(op, op_str, a, b, raise_on_error, use_numexpr, **eval_kwargs)
    210         return _evaluate(op, op_str, a, b, raise_on_error=raise_on_error,
--> 211                          **eval_kwargs)
    212     return _evaluate_standard(op, op_str, a, b, raise_on_error=raise_on_error)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_numexpr(op, op_str, a, b, raise_on_error, truediv, reversed, **eval_kwargs)
    121     if result is None:
--> 122         result = _evaluate_standard(op, op_str, a, b, raise_on_error)
    123

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\computation\expressions.py in _evaluate_standard(op, op_str, a, b, raise_on_error, **eval_kwargs)
     63     with np.errstate(all='ignore'):
---> 64         return op(a, b)
     65

~\AppData\Local\Continuum\anaconda3\lib\site-packages\dateutil\relativedelta.py in __radd__(self, other)
    390     def __radd__(self, other):
--> 391         return self.__add__(other)
    392

~\AppData\Local\Continuum\anaconda3\lib\site-packages\dateutil\relativedelta.py in __add__(self, other)
    362                 month += 12
--> 363         day = min(calendar.monthrange(year, month)[1],
    364                   self.day or other.day)

~\AppData\Local\Continuum\anaconda3\lib\calendar.py in monthrange(year, month)
    123         raise IllegalMonthError(month)
--> 124     day1 = weekday(year, month, 1)
    125     ndays = mdays[month] + (month == February and isleap(year))

~\AppData\Local\Continuum\anaconda3\lib\calendar.py in weekday(year, month, day)
    115        day (1-31)."""
--> 116     return datetime.date(year, month, day).weekday()
    117

TypeError: integer argument expected, got float

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\ops.py in safe_na_op(lvalues, rvalues)
    681             with np.errstate(all='ignore'):
--> 682                 return na_op(lvalues, rvalues)
    683         except Exception:

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\ops.py in na_op(x, y)
    663                 mask = notnull(x) & notnull(y)
--> 664                 result[mask] = op(x[mask], _values_from_object(y[mask]))
    665             elif isinstance(x, np.ndarray):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\dateutil\relativedelta.py in __radd__(self, other)
    390     def __radd__(self, other):
--> 391         return self.__add__(other)
    392

~\AppData\Local\Continuum\anaconda3\lib\site-packages\dateutil\relativedelta.py in __add__(self, other)
    362                 month += 12
--> 363         day = min(calendar.monthrange(year, month)[1],
    364                   self.day or other.day)

~\AppData\Local\Continuum\anaconda3\lib\calendar.py in monthrange(year, month)
    123         raise IllegalMonthError(month)
--> 124     day1 = weekday(year, month, 1)
    125     ndays = mdays[month] + (month == February and isleap(year))

~\AppData\Local\Continuum\anaconda3\lib\calendar.py in weekday(year, month, day)
    115        day (1-31)."""
--> 116     return datetime.date(year, month, day).weekday()
    117

TypeError: integer argument expected, got float

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)
<ipython-input-1-6cf75731780d> in <module>()
     10 payments =  cf.apply(lambda p: round(p/cpi))
     11 diffs=payments.cumsum(axis=1).applymap(lambda i: relativedelta(months=(-1*i)))
---> 12 payments=diffs.apply(lambda x: start+x)
     13 result=pd.concat([start,payments],axis=1)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in apply(self, func, axis, broadcast, raw, reduce, args, **kwds)
   4260                         f, axis,
   4261                         reduce=reduce,
-> 4262                         ignore_failures=ignore_failures)
   4263             else:
   4264                 return self._apply_broadcast(f, axis)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\frame.py in _apply_standard(self, func, axis, ignore_failures, reduce)
   4356             try:
   4357                 for i, v in enumerate(series_gen):
-> 4358                     results[i] = func(v)
   4359                     keys.append(v.name)
   4360             except Exception as e:

<ipython-input-1-6cf75731780d> in <lambda>(x)
     10 payments =  cf.apply(lambda p: round(p/cpi))
     11 diffs=payments.cumsum(axis=1).applymap(lambda i: relativedelta(months=(-1*i)))
---> 12 payments=diffs.apply(lambda x: start+x)
     13 result=pd.concat([start,payments],axis=1)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\ops.py in wrapper(left, right, name, na_op)
    719                 lvalues = lvalues.values
    720
--> 721         result = wrap_results(safe_na_op(lvalues, rvalues))
    722         return construct_result(
    723             left,

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\ops.py in safe_na_op(lvalues, rvalues)
    690                 if is_object_dtype(lvalues):
    691                     return libalgos.arrmap_object(lvalues,
--> 692                                                   lambda x: op(x, rvalues))
    693             raise
    694

pandas\_libs\algos_common_helper.pxi in pandas._libs.algos.arrmap_object()

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\ops.py in <lambda>(x)
    690                 if is_object_dtype(lvalues):
    691                     return libalgos.arrmap_object(lvalues,
--> 692                                                   lambda x: op(x, rvalues))
    693             raise
    694

~\AppData\Local\Continuum\anaconda3\lib\site-packages\dateutil\relativedelta.py in __radd__(self, other)
    389
    390     def __radd__(self, other):
--> 391         return self.__add__(other)
    392
    393     def __rsub__(self, other):

~\AppData\Local\Continuum\anaconda3\lib\site-packages\dateutil\relativedelta.py in __add__(self, other)
    361                 year -= 1
    362                 month += 12
--> 363         day = min(calendar.monthrange(year, month)[1],
    364                   self.day or other.day)
    365         repl = {"year": year, "month": month, "day": day}

~\AppData\Local\Continuum\anaconda3\lib\calendar.py in monthrange(year, month)
    122     if not 1 <= month <= 12:
    123         raise IllegalMonthError(month)
--> 124     day1 = weekday(year, month, 1)
    125     ndays = mdays[month] + (month == February and isleap(year))
    126     return day1, ndays

~\AppData\Local\Continuum\anaconda3\lib\calendar.py in weekday(year, month, day)
    114     """Return weekday (0-6 ~ Mon-Sun) for year (1970-...), month (1-12),
    115        day (1-31)."""
--> 116     return datetime.date(year, month, day).weekday()
    117
    118

TypeError: ('integer argument expected, got float', 'occurred at index Aug 2018(P&I Applied)')

A: This is for Python 3 (you need to pip install python-dateutil).
(edited per comments)
df=pd.read_csv('Paystring Data.csv')
cpi=df['Contractual PI']
start=df['NDD 8/31'].apply(pd.to_datetime).astype(datetime)
cf = df.iloc[:,1:13].replace('[^0-9.]', '', regex=True).astype(float)
payments =  cf.apply(lambda p: round(p/cpi))
diffs=payments.cumsum(axis=1).applymap(lambda i: relativedelta(months=(-1*i)))
payments=diffs.apply(lambda x: start+x)
result=pd.concat([start,payments],axis=1)

A: pd.to_datetime + np.cumsum
Since you are using Pandas, I recommend you take advantage of the vectorised methods available to Pandas / NumPy. In this case, it seems like you wish to subtract the cumulative sum of a list from a fixed starting point.
import pandas as pd
import numpy as np

NDD = '11/1/2018'
date = pd.to_datetime(NDD)
number_of_payments = [1, 0, 2, 0, 2, 1, 1, 0, 2, 1, 1, 1]

res = date.month - np.cumsum([0] + number_of_payments[:-1])
res[res <= 0] += 12

print(res)

array([11, 10, 10,  8,  8,  6,  5,  4,  4,  2,  1, 12], dtype=int32)

You haven't provided an input dataframe, so it's difficult to determine exactly what help you need to implement the above logic, but it is easily extendable to larger data sets.

A: Python3 (datetime & list)
Comments are in-lined.
from datetime import datetime, timedelta

def calc_payments(ndd: str, num_of_payments: list):
    def subtract_months(month: datetime, num: int):
        # Make sure given month is at 1 day of month
        month = month.replace(day=1)
        for _ in range(num):
            # Subtract the date by 1 day to calc prev month last day
            # Change the calculated prev month last day to 1st day
            month = (month - timedelta(days=1)).replace(day=1)
        return month

    ndd_date: datetime = datetime.strptime(ndd, '%m/%d/%Y')
    payments = list()

    payments.append(ndd_date)

    # Loop/logic as described in Step 3 by OP
    for i in range(1, len(num_of_payments)):
        ndd_date = subtract_months(ndd_date, num_of_payments[i - 1])
        payments.append(ndd_date)

    return payments

if __name__ == '__main__':
    NDD = "11/1/2018"
    number_of_payments = [1, 0, 2, 0, 2, 1, 1, 0, 2, 1, 1, 1]
    for f in calc_payments(NDD, number_of_payments):
        # Format date to month/2-digit-year
        print(f"{f.month}/{f.strftime('%y')}", end=" ")


text:
Q: Missing "Site Pages" Library Here's the issue I've had presented to me today. A user possibly deleted the "Site Pages" library by accident. When navigating to the site http://url.sitepages/home.aspx it returned a 404. Even attempting to navigate to the http://url.sitepages/ returned a 404. Upon looking up All Site Content, the "Site Pages" was not displayed; all of which lead me to believe the library itself was deleted. Somehow now the Site Pages library is showing, but there are not pages within. I've checked the recycling bin at site and site collection level and did not find anything. Any ideas on this? I just don't understand how it could be deleted but not appear anyway in order to restore. Thanks everyone!

A: This feature must be active "Wiki Page Home Page" feature to have the sitepages enabled.
http://sanketinfo.blogspot.in/2012/12/how-to-enable-site-pages-document.html
Site-Level feature comes when Pages and other style library is not present and also if you want to customize the look and feel of the site in site setting page.
If you need them, you have a few options:
Activate the "Wiki Page Home Page" feature. The feature will create
those libraries and will also create a wiki page and set it as the
home (welcome) page for your site.
If you only need the libraries and don't want your home page changed,
you can have SharePoint Designer 2010 create the libraries for you:
Open SharePoint Designer.
In the "Site Objects" pane on the left, click "Site Pages." SP Designer will load the contents of the Site Pages library and tell you it's empty.
However, it also creates the Site Pages library for you in the process.
Do the same thing for "Site Assets" (also in the Site Objects pane). If you have code that depends on the existence of these libraries
(such as a feature receiver),
you can use two methods on the SPListCollection
class to ensure the libraries are there:

EnsureSitePagesLibrary()
EnsureSiteAssetsLibrary()

A: If the user has deleted anything in the site, it will be in recycle bin. But if the file is removed from the recycle bin, then it will be stored anywhere.
If you are looking for default pages from the "site pages" library, then it is not a problem. You  can get it from the another site/ site collection "site pages" library which is using the same site definition.


text:
Q: Counting number of cases available from datetime in pandas I have a dataframe of start date and closed date of cases. I want to do a count of how many cases are available at the start of each case.
caseNo  startDate   closedDate
1       2019-01-01  2019-01-03
2       2019-01-02  2019-01-10
3       2019-01-03  2019-01-04
4       2019-01-05  2019-01-10
5       2019-01-06  2019-01-10
6       2019-01-07  2019-01-12
7       2019-01-11  2019-01-15

Output will be:
caseNo  startDate   closedDate   numCases
1       2019-01-01  2019-01-03   0
2       2019-01-02  2019-01-10   1
3       2019-01-03  2019-01-04   1
4       2019-01-05  2019-01-10   1
5       2019-01-06  2019-01-10   2
6       2019-01-07  2019-01-12   3
7       2019-01-11  2019-01-15   1

For example, for case 6, cases 2,4,5 still have not been closed. So there are 3 cases outstanding.
Also, the dates are actually datetimes rather than just date. I have only included the date here for brevity.

A: Use:
res = []
temp = pd.to_datetime(df['closedDate'])
for i, row in df.iterrows():
    temp_res = np.sum(row['startDate']<temp.iloc[:i])
    print(temp_res)
    res.append(temp_res)

output:

Then you can add the result as a df column:

A: Solution in numba should increase performance (best test in real data):
from numba import jit

@jit(nopython=True)
def nb_func(x, y):
    res = np.empty(x.size, dtype=np.int64)
    for i in range(x.size):
        res[i] = np.sum(x[:i] > y[i])
    return res

df['case'] = nb_func(df['closedDate'].to_numpy(), df['startDate'].to_numpy())
print (df)
   caseNo  startDate closedDate  case
0       1 2019-01-01 2019-01-03     0
1       2 2019-01-02 2019-01-10     1
2       3 2019-01-03 2019-01-04     1
3       4 2019-01-05 2019-01-10     1
4       5 2019-01-06 2019-01-10     2
5       6 2019-01-07 2019-01-12     3
6       7 2019-01-11 2019-01-15     1


text:
Q: React is running on Docker however isn't accessible to public IP Basically, I'm running a webapp with this stack:
Backend: FastAPI (python) which depends on database
Database: MySQL (being connected with via python-connector)
Frontend: React Functional (rn it's dependency is set to backend, but technically no dependencies)
The backend is connecting to the database via localhost, and is being served on the public ip  I can access it at just fine at mydomain.com:8000/api
However when I'm trying to access mydomain.com, docker is setup to forward port 3000 to port 80, however it can't request react and, I get the ERR_CONNECTION_REFUSED error
In alot of similar issues people forget to forward port 3000 to 80 however i'm doing this...
Also, when I install npm & the react project on my Ubuntu Server, the frontend is accessible via mydomain.com:3000
In the docker-compose.yml when I change the ports from "REACT_PORT : 80 " To "3000 : 3000 " And that's accessible via our public ip.
Should I just port forward 3000 to 80 on the main linux server? how to do?
Docker Files
Frontend docker file
# pull official base image for node
FROM node:16-buster-slim

# set working directory
WORKDIR /app

# add `/app/node_modules/.bin` to PATH
ENV PATH /app/node_modules/.bin:$PATH

# install dependencies
COPY package.json ./
COPY package-lock.json ./
RUN npm i -g npm@latest
RUN npm install

# copy all src files to the container
COPY . .

# Expose port
EXPOSE 3000
EXPOSE 80

# start the web app
CMD ["npm", "run", "start"]

docker-compose.yml
version: "3.9"

services:
  db:
    image: mysql:${MYSQL_VERSION}
    restart: always
    environment:
      - MYSQL_DATABASE=${MYSQL_DB}
      - MYSQL_USER=${MYSQL_USERNAME}
      - MYSQL_PASSWORD=${MYSQL_PASSWORD}
      - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
    ports:
      - "${MYSQL_PORT}:${MYSQL_PORT}"
    expose:
      - "${MYSQL_PORT}"
    volumes:
      - db:/var/lib/mysql
    networks:
      - mysql_network

  backend:
    container_name: fastapi-backend
    build: ./backend/app
    volumes:
      - ./backend:/code
    ports:
      - "${FASTAPI_PORT}:${FASTAPI_PORT}"
    env_file:
      - .env
    depends_on:
      - db
    networks:
      - mysql_network
      - backend
    restart: always

  frontend:
    container_name: react-frontend
    build: ./frontend/client
    ports:
#This doesn't work for some reason?
      - "${REACT_PORT}:80"
#When I do this, I can access react via public ip just fine..:
      - "3000:3000"
    depends_on:
      - backend
    networks:
      - backend
    restart: always

volumes:
  db:
    driver: local

networks:
  backend:
    driver: bridge
  mysql_network:
    driver: bridge

React/NPM Files
package.json
{
  "name": "client",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@reduxjs/toolkit": "^1.8.2",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.1.1",
    "@testing-library/user-event": "^13.5.0",
    "bootstrap": "^5.1.3",
    "react": "^18.0.0",
    "react-dom": "^18.0.0",
    "react-redux": "^8.0.2",
    "react-router-dom": "^6.3.0",
    "react-scripts": "5.0.1",
    "universal-cookie": "^4.0.4",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

Ubuntu UFW status
root@localhost:~/director# ufw status verbose
Status: active
Logging: on (low)
Default: deny (incoming), allow (outgoing), deny (routed)
New profiles: skip

To                         Action      From
--                         ------      ----
3306/tcp                   ALLOW IN    Anywhere
22/tcp                     ALLOW IN    Anywhere
80/tcp                     ALLOW IN    Anywhere
443                        ALLOW IN    Anywhere
3000                       ALLOW IN    Anywhere
3306/tcp (v6)              ALLOW IN    Anywhere (v6)
22/tcp (v6)                ALLOW IN    Anywhere (v6)
80/tcp (v6)                ALLOW IN    Anywhere (v6)
443 (v6)                   ALLOW IN    Anywhere (v6)
3000 (v6)                  ALLOW IN    Anywhere (v6)

doing curl -l mydomain.com:8000
curl -l domain.com:8000
{"detail":"Not authenticated"}

Our backend is working and public
docker inspect react_frontend
[
    {
        "Id": "533f96d538bcf28827d5ad5ead69dc97b97c79bfef1d1e31e3847f15ceb0621f",
        "Created": "2022-06-27T04:00:18.459838372Z",
        "Path": "docker-entrypoint.sh",
        "Args": [
            "npm",
            "start"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 57578,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2022-06-27T04:00:20.253120387Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:698f3ce60c6ba12f39dcf371bd4be556c1cb4aac9c7f95fd4589c079ec4e337b",
        "ResolvConfPath": "/var/lib/docker/containers/533f96d538bcf28827d5ad5ead69dc97b97c79bfef1d1e31e3847f15ceb0621f/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/533f96d538bcf28827d5ad5ead69dc97b97c79bfef1d1e31e3847f15ceb0621f/hostname",
        "HostsPath": "/var/lib/docker/containers/533f96d538bcf28827d5ad5ead69dc97b97c79bfef1d1e31e3847f15ceb0621f/hosts",
        "LogPath": "/var/lib/docker/containers/533f96d538bcf28827d5ad5ead69dc97b97c79bfef1d1e31e3847f15ceb0621f/533f96d538bcf28827d5ad5ead69dc97b97c79bfef1d1e31e3847f15ceb0621f-json.log",
        "Name": "/react-frontend",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": [],
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "scheduleplatform_backend",
            "PortBindings": {
                "80/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "3000"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "always",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": [],
            "CapAdd": null,
            "CapDrop": null,
            "CgroupnsMode": "private",
            "Dns": null,
            "DnsOptions": null,
            "DnsSearch": null,
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": null,
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": null,
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": null,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/f9449860ca28f3641e74ef010fa6bb54383a33a975dce28519f5cfe609ff61d2-init/diff:/var/lib/docker/overlay2/7d8ad12b25cf6e4e0093e811370194cc6c1f72aa443d7d8f0ab69e97715f4c82/diff:/var/lib/docker/overlay2/b530ee218be07eb3a58df7a2f134b4e23cd22ad04b35dc7cbb75f3f07a206280/diff:/var/lib/docker/overlay2/94b5584c91af3dda4376092abdb9b7ff80937311741b96deca22e4b3aaf3a7c7/diff:/var/lib/docker/overlay2/4d8194094b484dfd94ca7473e3e13bfa5962879fd81942710f0aa096199a87c3/diff:/var/lib/docker/overlay2/aeb4c3cd54338efa1d44e1fc24c8a8f91bf672e47771fd0e308b3f65ab753f07/diff:/var/lib/docker/overlay2/9ddac11aa66b2d843b2391c3ad0798f8e372adfffeaec87882322de663b398e5/diff:/var/lib/docker/overlay2/e874192d15482d34ed8a80ef205b55005c84fcad0a7726822de258963191ec10/diff:/var/lib/docker/overlay2/8b162bdb3415e166a91518df47e1bed0bfff2d89568a2653f74e66cb3931773a/diff:/var/lib/docker/overlay2/a18946af0ee112612099819a9db0a3cbef5d1e2264904e6a8405868ab111634a/diff:/var/lib/docker/overlay2/b94b4e7d1af7280ad586d6f3366a161ec0d5cf9f858f0f20139b2ab0a72acfb7/diff:/var/lib/docker/overlay2/052c70a96ef76a7c32d609b98ec679ad7c6a74a28623b870bd729447bbc6086c/diff",
                "MergedDir": "/var/lib/docker/overlay2/f9449860ca28f3641e74ef010fa6bb54383a33a975dce28519f5cfe609ff61d2/merged",
                "UpperDir": "/var/lib/docker/overlay2/f9449860ca28f3641e74ef010fa6bb54383a33a975dce28519f5cfe609ff61d2/diff",
                "WorkDir": "/var/lib/docker/overlay2/f9449860ca28f3641e74ef010fa6bb54383a33a975dce28519f5cfe609ff61d2/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "533f96d538bc",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "3000/tcp": {},
                "80/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/app/node_modules/.bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "NODE_VERSION=16.15.1",
                "YARN_VERSION=1.22.19"
            ],
            "Cmd": [
                "npm",
                "start"
            ],
            "Image": "scheduleplatform_frontend",
            "Volumes": null,
            "WorkingDir": "/app",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {
                "com.docker.compose.config-hash": "a02c886422905cf77d66a479bb9967d4a85bdd8c3ed0369665dae6afc9b34099",
                "com.docker.compose.container-number": "1",
                "com.docker.compose.oneoff": "False",
                "com.docker.compose.project": "scheduleplatform",
                "com.docker.compose.project.config_files": "docker-compose.yml",
                "com.docker.compose.project.working_dir": "/root/SchedulePlatform",
                "com.docker.compose.service": "frontend",
                "com.docker.compose.version": "1.29.2"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "014cba17fd5ce070c42b6257a05149d7c78b7556d941d5f790c8c0f27e70a8b1",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "3000/tcp": null,
                "80/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "3000"
                    },
                    {
                        "HostIp": "::",
                        "HostPort": "3000"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/014cba17fd5c",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "scheduleplatform_backend": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": [
                        "533f96d538bc",
                        "frontend"
                    ],
                    "NetworkID": "9a6ff7cb0c0d725de46e21e309cd0e5708995faffb00f099c8980127f8a9c68c",
                    "EndpointID": "c6c22efd535ee4beaa732730143268a4d372d2cecb2537f00013a7b057416852",
                    "Gateway": "172.20.0.1",
                    "IPAddress": "172.20.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:14:00:03",
                    "DriverOpts": null
                }
            }
        }
    }
]

A: I gave up with docker and now use NGINX to point port 80 to 3000...
Basically, in my docker-compose.yml I point the react port to itself like:
  frontend:
    container_name: react-frontend
    build: ./frontend/client
    ports:
      - "${REACT_PORT}:${REACT_PORT}"
    depends_on:
      - backend
    networks:
      - backend
    restart: always

And with NGINX, I edit the config file doing:
nano etc/nginx/nginx.conf
then in the http {} section of this config, I removed include /etc/nginx/sites-enabled/*;
and added
server {
        listen 80;
        location / {proxy_pass http://localhost:3000/; }
        }

and then reloaded nginx, now docker is forwarding at port 3000 and nginx is pointing 80 to that port.
This method works, I still don't understand why Docker wasn't able to port forward that, I even checked my netstat and nothing was running on port 80...
weird...


text:
Q: Microsoft Bot Framework Privacy/Encryption On looking at privacy for the bot I built using Microsoft Bot Framework I noticed this:

to provide the I/O service, the Bot Framework transmits your message and message content (including your ID), from the chat service you used to the bot.

I'm concerned about any messages that are sent to my bot being sent in the clear.
Has anyone considered and/or implemented encryption in order to maintain the privacy of the messages in their bot? Or does anyone have any other solution?

A: When you register your chatbot, it requires an https endpoint. So, your message won't be sent in the clear. Additionally, you must generate an API key and a private password key for secure access to your chatbot so that only the Bot Connector can communicate. Make sure you secure your private keys so no one else can access your chatbot.


text:
Q: Detecting EM radiation using android app I wrote a simple android app that shows the magnetic field(using the magnetic field sensor in the phone) in the current location.
When I place a two inch steel screw on the top of the phone (which is running the app), there is a change in magnetic field for a while. I'm guessing that it's due to the induced voltage in the screw due to the EM radiation, flowing in my room. However, after a few seconds, the magnetic field stops to change and stabilizes to a value. I am not sure why.
My doubt is, since EM is generally alternating radio waves, shouldn't it induce an alternating voltage in the screw and result in the magnetic field changing continuously?
If the induced voltage is too small, then why did the magnetic field reading change for a while?

A: There are 2 types of magnetic fields coming from phone:

*

*DC, from smartphone circuitry

*AC, from chip transmission (for each chip, if they are different,e.g Wi-Fi, Bluetooth, GSM. You will see different radiation pattern)

It's better to say that voltage induced due to emission of your smartphone, electronics emission is DC. When you put screw you disturb system balance, so it takes some time to stabilize.
Also, your smartphone emits every 30 seconds small id burst to BTS  generating a magnetic field in its location, this time it passes an alternating current through the screw. Same goes for transmission, you will see huge fluctuations of EM field.
This kind of sensors used primary for navigation. DC or "static" lines of magnetic flux naturally emanate from the earth and provide a sensor with the ability to indicate "Magnetic North". There is standard calculation model and Google used it too.