问:
How to train PPO using actions from matches already played?
The idea is to initially calibrate the neural network with some prior knowledge before releasing the algorithm to evolve on its own.
To make the question simpler, imagine that an agent can take 10 actions (discrete space). Instead of training the PPO algorithm to figure out by itself which actions are best for each state, I would like to perform a training by considering that some actions were performed in some states.
I'm using Stable Baselines with Gym.

I thought about creating an action wrapper like this:

```<code>class RandomActionWrapper(gym.ActionWrapper):
            def __init__(self, env):
            super(RandomActionWrapper, self).__init__(env)
            def action(self, action):
                a = self.env.action_space.sample()
                return a
</code>```

Ps: this wrapper is just a proof of concept, choosing random actions all the time, but the model just doesn't learn that way (I simulated many iterations in ridiculously simple to learn custom environments, something like: "action 2 always results in reward=1 while other actions result in reward=0).
Apparently the updates on the network are being made considering the actions that the model chose (the model always predicts actions by itself) while the rewards are being calculated based on the actions defined in my wrapper. This mismatch makes learning impossible.

答: I think you are looking for some kind of action mask implementation. In several games/enviroments, some actions are invalid in a particular state (it is not your case, but it could be the first approach). You can check this paper and the github</p>

Body:
The idea is to initially calibrate the neural network with some prior knowledge before releasing the algorithm to evolve on its own.
To make the question simpler, imagine that an agent can take 10 actions (discrete space). Instead of training the PPO algorithm to figure out by itself which actions are best for each state, I would like to perform a training by considering that some actions were performed in some states.
I'm using Stable Baselines with Gym.

I thought about creating an action wrapper like this:

class RandomActionWrapper(gym.ActionWrapper):
            def __init__(self, env):
            super(RandomActionWrapper, self).__init__(env)
            def action(self, action):
                a = self.env.action_space.sample()
                return a

Ps: this wrapper is just a proof of concept, choosing random actions all the time, but the model just doesn't learn that way (I simulated many iterations in ridiculously simple to learn custom environments, something like: "action 2 always results in reward=1 while other actions result in reward=0).
Apparently the updates on the network are being made considering the actions that the model chose (the model always predicts actions by itself) while the rewards are being calculated based on the actions defined in my wrapper. This mismatch makes learning impossible.


来源: stackexchange

问:
How to make radar spider chart with pentagon grid using matplotlib and python?
I have a radar chart. Need to change the grid from circle-form to pentagon-form. Currently, I have this output:

Whereas I expect smth like this:

Here's the info about the system i have: Windows 10 (64-bit); Python - 3.8.0 (32-bit); matplotlib - 3.3.3.
This question i've seen here: How to make a polygon radar (spider) chart in python but it doesn't resolve my question.
But it doesn't work for me and i can't understand why. I can simply copy the code, but the result is - outer border changes to pentagon-form, but the inner gridlines remain circular. But it works for other people!

The code of the program is below:

import numpy as np

import matplotlib.pyplot as plt
from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from matplotlib.projections.polar import PolarAxes
from matplotlib.projections import register_projection
from matplotlib.spines import Spine
from matplotlib.transforms import Affine2D

def radar_factory(num_vars, frame='circle'):
    """Create a radar chart with `num_vars` axes.

    This function creates a RadarAxes projection and registers it.

    Parameters
    ----------
    num_vars : int
        Number of variables for radar chart.
    frame : {'circle' | 'polygon'}
        Shape of frame surrounding axes.

    """
    # calculate evenly-spaced axis angles
    theta = np.linspace(0, 2*np.pi, num_vars, endpoint=False)

    class RadarAxes(PolarAxes):

        name = 'radar'

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            # rotate plot such that the first axis is at the top
            self.set_theta_zero_location('N')

        def fill(self, *args, closed=True, **kwargs):
            """Override fill so that line is closed by default"""
            return super().fill(closed=closed, *args, **kwargs)

        def plot(self, *args, **kwargs):
            """Override plot so that line is closed by default"""
            lines = super().plot(*args, **kwargs)
            for line in lines:
                self._close_line(line)

        def _close_line(self, line):
            x, y = line.get_data()
            # FIXME: markers at x[0], y[0] get doubled-up
            if x[0] != x[-1]:
                x = np.concatenate((x, [x[0]]))
                y = np.concatenate((y, [y[0]]))
                line.set_data(x, y)

        def set_varlabels(self, labels):
            self.set_thetagrids(np.degrees(theta), labels)

        def _gen_axes_patch(self):
            # The Axes patch must be centered at (0.5, 0.5) and of radius 0.5
            # in axes coordinates.
            if frame == 'circle':
                return Circle((0.5, 0.5), 0.5)
            elif frame == 'polygon':
                return RegularPolygon((0.5, 0.5), num_vars, radius=0.5, edgecolor="k")
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

        def draw(self, renderer):
            """ Draw. If frame is polygon, make gridlines polygon-shaped """
            if frame == 'polygon':
                gridlines = self.yaxis.get_gridlines()
                for gl in gridlines:
                    gl.get_path()._interpolation_steps = num_vars
            super().draw(renderer)

        def _gen_axes_spines(self):
            if frame == 'circle':
                return super()._gen_axes_spines()
            elif frame == 'polygon':
                # spine_type must be 'left'/'right'/'top'/'bottom'/'circle'.
                spine = Spine(axes=self,
                              spine_type='circle',
                              path=Path.unit_regular_polygon(num_vars))
                # unit_regular_polygon gives a polygon of radius 1 centered at
                # (0, 0) but we want a polygon of radius 0.5 centered at (0.5,
                # 0.5) in axes coordinates.
                spine.set_transform(Affine2D().scale(.5).translate(.5, .5)
                                    + self.transAxes)
                return {'polar': spine}
            else:
                raise ValueError("unknown value for 'frame': %s" % frame)

    register_projection(RadarAxes)
    return theta

data = [['O1', 'O2', 'O3', 'O4', 'O5'],
        ('Title', [
                    [4, 3.5, 4, 2, 3,],
                    [1.07, 5.95, 2.04, 1.05, 0.00,],
                  ]
        )]

N = len(data[0])
theta = radar_factory(N, frame='polygon')                                     # polygon  !!!

spoke_labels = data.pop(0)
title, case_data = data[0]
fig, ax = plt.subplots(figsize=(5, 5), subplot_kw=dict(projection='radar'))
fig.subplots_adjust(top=0.85, bottom=0.05)
ax.set_rgrids([0, 1, 2.0, 3.0, 4.0, 5.0, 6])
ax.set_title(title,  position=(0.5, 1.1), ha='center')

for d in case_data:
    line = ax.plot(theta, d)
    ax.fill(theta, d,  alpha=0.25)
ax.set_varlabels(spoke_labels)

plt.show()

```

答:
I don't have enough reputation to add a comment so I'll put this down as an answer.
An update to the code that can serve as a workaround and works on Matplotlib > 3.5 has been recently added to issue 19981 by prohde.
You can check it here:
https://github.com/matplotlib/matplotlib/issues/19981</p>

ContentLicense: CC BY-SA 4.0


问:
Need to render Routes component only once while keeping conditional rendering of layout
So my app has a home page and some nav links. The navbar isn't visible on the home page but it's visible on everything else. The way I did it is by checking the location.pathname and if it's not / I'll render the routes with a navbar and inside a specific page layout which is made only for the inner pages and not the home page.

Like this:

```<code>function App() {
  const location = useLocation()

  return (
      <Layout>
        {
          location.pathname !== "/" ?
          <PageLayout>
            <NavBar />
            <DefaultRoutes />
          </PageLayout> :
          <DefaultRoutes />
        }

      </Layout>

  );
}
</code>```

Default routes:

```<code>const DefaultRoutes = () => {
  return (
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="about" element={<About />} />
        <Route path="projects" element={<Projects />} />
      </Routes>
    );
};
</code>```

This works, however, I want to incorporate some exit animations between all routes, and they currently only work within every other link other than / because the <DefaultRoutes/> component is unmounted and mounted again every time I go to the home page. My question is how do I render the DefaultRoutes component only once while keeping the functionality of the navbar and layout for specific routes

答:
Fixed this by just creating a wrapper/layout element called NavLayout and then nesting my nav routes inside it

```<code>const NavLayout = () => {
  return (
    <PageLayout>
      <NavBar />
      <Outlet />
    </PageLayout>
  )
}
</code>```

Routes:

```<code>const DefaultRoutes = () => {

  return (
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/" element={<NavLayout />}>
          <Route path="about" element={<About />} />
          <Route path="projects" element={<Projects />} />
        </Route>
      </Routes>
    );
};
</code>```

Now there is no conditional rendering and i just render <DefaultRoutes /> once in App.

Body:
So my app has a home page and some nav links. The navbar isn't visible on the home page but it's visible on everything else. The way I did it is by checking the location.pathname and if it's not / I'll render the routes with a navbar and inside a specific page layout which is made only for the inner pages and not the home page.

Like this:

function App() {
  const location = useLocation()

  return (
      <Layout>
        {
          location.pathname !== "/" ?
          <PageLayout>
            <NavBar />
            <DefaultRoutes />
          </PageLayout> :
          <DefaultRoutes />
        }

      </Layout>

  );
}

Default routes:

const DefaultRoutes = () => {
  return (
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="about" element={<About />} />
        <Route path="projects" element={<Projects />} />
      </Routes>
    );
};

This works, however, I want to incorporate some exit animations between all routes, and they currently only work within every other link other than / because the <DefaultRoutes/> component is unmounted and mounted again every time I go to the home page. My question is how do I render the DefaultRoutes component only once while keeping the functionality of the navbar and layout for specific routes

Body:
Fixed this by just creating a wrapper/layout element called NavLayout and then nesting my nav routes inside it

const NavLayout = () => {
  return (
    <PageLayout>
      <NavBar />
      <Outlet />
    </PageLayout>
  )
}

Routes:

const DefaultRoutes = () => {

  return (
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/" element={<NavLayout />}>
          <Route path="about" element={<About />} />
          <Route path="projects" element={<Projects />} />
        </Route>
      </Routes>
    );
};

Now there is no conditional rendering and i just render <DefaultRoutes /> once in App.


问:
Python: loop doing the same thing to one item n-times as opposed doing it once to n-items
Here is the example:
I am trying to grab a series of XML pages, and then extract data from them.

It downloads each individual page, as the while loop was designed to do but the tester() function prints the data from the first file it downloads V number of times despite it downloading and clearing the file after each time it loops through.

This is killing me what am I doing wrong?

```<code>def tester():
    with open('raw.txt') as myFile:
        test = linecache.getline('raw.txt', 12)
        print test
        test = ""
        myFile.close

def grab_data(Year, rcvote):
    link = "XXX/%s/roll%s.xml" % (Year, rc)
    site = urllib2.urlopen(link)
    localFile = open('raw.txt', 'w')
    localFile.write(site.read(100000))
    localFile.close()
    tester()

while (V !=0):
    rc = str(V)
    if (len(rc) == 2):
        rc = "0%s" % (rc)
    elif (len(rc) == 1):
        rc = "00%s" % (rc)
    else:
        rc = rc
    grab_data(Year, rc)
    V = V - 1
</code>```

答:
The problem is the linecache module.  It assumes that same-named files are the same.

But why write the data to a file just to read it again anyway?

```<code>def tester(text):
    line12 = text.splitlines()[11]
    print line12

def grab_data(year, rcvote):
    link = "XXX/%s/roll%03d.xml" % (year, rcvote)
    site = urllib2.urlopen(link)
    tester(site.read(100000))

while v:
    grab_data(year, rc)
    v -= 1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is the example:
I am trying to grab a series of XML pages, and then extract data from them.

It downloads each individual page, as the while loop was designed to do but the tester() function prints the data from the first file it downloads V number of times despite it downloading and clearing the file after each time it loops through.

This is killing me what am I doing wrong?

def tester():
    with open('raw.txt') as myFile:
        test = linecache.getline('raw.txt', 12)
        print test
        test = ""
        myFile.close

def grab_data(Year, rcvote):
    link = "XXX/%s/roll%s.xml" % (Year, rc)
    site = urllib2.urlopen(link)
    localFile = open('raw.txt', 'w')
    localFile.write(site.read(100000))
    localFile.close()
    tester()

while (V !=0):
    rc = str(V)
    if (len(rc) == 2):
        rc = "0%s" % (rc)
    elif (len(rc) == 1):
        rc = "00%s" % (rc)
    else:
        rc = rc
    grab_data(Year, rc)
    V = V - 1

Body:
The problem is the linecache module.  It assumes that same-named files are the same.

But why write the data to a file just to read it again anyway?

def tester(text):
    line12 = text.splitlines()[11]
    print line12

def grab_data(year, rcvote):
    link = "XXX/%s/roll%03d.xml" % (year, rcvote)
    site = urllib2.urlopen(link)
    tester(site.read(100000))

while v:
    grab_data(year, rc)
    v -= 1


问:
CodeBuild IAM Role Assume Role Leveraging terraform jsoncode
I currently have my policy working with assume_role_policy  = <<POLICY which imports the Json inline.  I want to leverage jsonencode instead and I have written the role below with the jsonecode policy.  This fails every time which has me wondering if its the principal syntax but I can't seem to find an example running more than one service.  As far as the error goes, terraform just tells me it's an error with the resource in line one which isn't much.  Grateful for any assistance here.</p>
```<code>resource "aws_iam_role" "codebuild_service_role" {
  name                = "codebuildservicerole"
  assume_role_policy  = jsonencode ({
    version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Sid = ""
        Effect = "Allow"
        Principal = {
          Service = ["codebuild.amazonaws.com","codepipeline.amazonaws.com"]
        }
      },

    ]

  })
}
</code>```

答:
Multiple service principals are comma-delimited in the IAM schema, and not an array/list:</p>
```<code>assume_role_policy = jsonencode({
  version = "2012-10-17"
  Statement = [
    {
      Action = "sts:AssumeRole"
      Sid = ""
      Effect = "Allow"
      Principal = {
        Service = "codebuild.amazonaws.com,codepipeline.amazonaws.com"
      }
    },
  ]
})
</code>```

Body:
I currently have my policy working with assume_role_policy  = <<POLICY which imports the Json inline.  I want to leverage jsonencode instead and I have written the role below with the jsonecode policy.  This fails every time which has me wondering if its the principal syntax but I can't seem to find an example running more than one service.  As far as the error goes, terraform just tells me it's an error with the resource in line one which isn't much.  Grateful for any assistance here.

resource "aws_iam_role" "codebuild_service_role" {
  name                = "codebuildservicerole"
  assume_role_policy  = jsonencode ({
    version = "2012-10-17"
    Statement = [
      {
        Action = "sts:AssumeRole"
        Sid = ""
        Effect = "Allow"
        Principal = {
          Service = ["codebuild.amazonaws.com","codepipeline.amazonaws.com"]
        }
      },

    ]

  })
}

Body:
Multiple service principals are comma-delimited in the IAM schema, and not an array/list:

assume_role_policy = jsonencode({
  version = "2012-10-17"
  Statement = [
    {
      Action = "sts:AssumeRole"
      Sid = ""
      Effect = "Allow"
      Principal = {
        Service = "codebuild.amazonaws.com,codepipeline.amazonaws.com"
      }
    },
  ]
})


问:
Check if list<t> contains any of another list
I have a list of parameters like this:

```<code>public class parameter
{
    public string name {get; set;}
    public string paramtype {get; set;}
    public string source {get; set;}
}

IEnumerable<Parameter> parameters;
</code>```

And a array of strings i want to check it against.

```<code>string[] myStrings = new string[] { "one", "two"};
</code>```

I want to iterate over the parameter list and check if the source property is equal to any of the myStrings array. I can do this with nested foreach's but i would like to learn how to do it in a nicer way as i have been playing around with linq and like the extension methods on enumerable like where etc so nested foreachs just feel wrong. Is there a more elegant preferred linq/lambda/delegete way to do this.

Thanks

答:
```<code>list1.Select(l1 => l1.Id).Intersect(list2.Select(l2 => l2.Id)).ToList();
</code>```

```<code>var list1 = await _service1.GetAll();
var list2 = await _service2.GetAll();

// Create a list of Ids from list1
var list1_Ids = list1.Select(l => l.Id).ToList();

// filter list2 according to list1 Ids
var list2 = list2.Where(l => list1_Ids.Contains(l.Id)).ToList();
</code>```

Body:
I have a list of parameters like this:

public class parameter
{
    public string name {get; set;}
    public string paramtype {get; set;}
    public string source {get; set;}
}

IEnumerable<Parameter> parameters;

And a array of strings i want to check it against.

string[] myStrings = new string[] { "one", "two"};

I want to iterate over the parameter list and check if the source property is equal to any of the myStrings array. I can do this with nested foreach's but i would like to learn how to do it in a nicer way as i have been playing around with linq and like the extension methods on enumerable like where etc so nested foreachs just feel wrong. Is there a more elegant preferred linq/lambda/delegete way to do this.

Thanks

Body:
list1.Select(l1 => l1.Id).Intersect(list2.Select(l2 => l2.Id)).ToList();

var list1 = await _service1.GetAll();
var list2 = await _service2.GetAll();

// Create a list of Ids from list1
var list1_Ids = list1.Select(l => l.Id).ToList();

// filter list2 according to list1 Ids
var list2 = list2.Where(l => list1_Ids.Contains(l.Id)).ToList();


问:
Dompdf is writing on top of other html elements - Laravel 6 - PHP 8
I'm writing a function to create and display a pdf file using Dompdf in a Laravel 6 project using PHP 8. I tried with many tutorials and even the official documentation from GitHub for the normal Dompdf version and it's wrapper for Laravel. Here is my pdf generator function code:

```<code>private function generate_pdf(){
    $html = '
        <html>
            <body>
                <h1>Hello Dompdf</h1>
                <h2>MDF</h2>
            </body>
        </html>
    ';
    $pdf = PDF::loadHTML($html);
    return $pdf->stream('welcome.pdf');
}
</code>```

It works fine but here is the result of the function:

As you can see the elements are overlapping itself on top of each others. I looked for answers but I can't find anything related. Does somebody knows why is this happening?

答: The problem is compatibility with PHP 8 itself. I had the same issue and downgrading to PHP 7.4 has worked on my server. Not sure where the incompatibility may be, but immediately after updating to PHP 8.0 DOMPDF stopped interpreting the HTML properly and started placing items on top of each other.

Body:
I'm writing a function to create and display a pdf file using Dompdf in a Laravel 6 project using PHP 8. I tried with many tutorials and even the official documentation from GitHub for the normal Dompdf version and it's wrapper for Laravel. Here is my pdf generator function code:

private function generate_pdf(){
    $html = '

Hello Dompdf

MDF

    ';
    $pdf = PDF::loadHTML($html);
    return $pdf->stream('welcome.pdf');
}

It works fine but here is the result of the function:

As you can see the elements are overlapping itself on top of each others. I looked for answers but I can't find anything related. Does somebody knows why is this happening?


问:
MongoDB Aggregate - How to implement match and lookup
I need to get the data from two collections (expenses, accounts). The data must be between the given date range and amount range.

date, amount, currency, type is in Expenses collection and accountId is in account collection as _id.
I tried the following query but it's not returning anything.

const response = await Expense.aggregate( [
   { $match: {
       $and: [
           {
               currency: "1",
               expenseType: "1"
           },
           {
               date: {
                   $gte: new Date(date.value.from) , $lte: new Date(date.value.to)
               },
               amount: {
                   $gt: parseFloat(amount.value.from) , $lt: parseFloat(amount.value.to)
               }
           }
       ],
   } },
   {
       $lookup: {
           from: "accounts",
           localField: "accountId",
           foreignField: "_id",
           as: "account"
       }
   }
] )
```

This is the schema of expenses collection:

Document of expense collection:

Document of account collection:

答:
From the attached expense document, the amount field was a String type but not a Number type.

Data

```<code>amount: "20000"
</code>```

Schema

```<code>amount: {
  type: Number,
  required: true
}
</code>```

You should revise your Expense document in MongoDB with your schema.

From your Aggregation Query, you need to convert amount from String to Decimal to compare.

Solution 1: With $expr

```<code>db.expense.aggregate([
  {
    $match: {
      $and: [
        {
          currency: "1",
          expenseType: "1"
        },
        {
          date: {
            $gte: new Date(date.value.from),
            $lte: new Date(date.value.to)
          },

        },
        {
          $expr: {
            $and: [
              {
                $gt: [
                  {
                    "$toDecimal": "$amount"
                  },
                  parseFloat(amount.value.from)
                ]
              },
              {
                $lt: [
                  {
                    "$toDecimal": "$amount"
                  },
                  parseFloat(amount.value.to)
                ]
              }
            ]
          }
        }
      ],

    }
  },
  {
    $lookup: {
      from: "accounts",
      localField: "accountId",
      foreignField: "_id",
      as: "account"
    }
  }
])
</code>```

Solution 1 on Mongo Playground

Solution 2: Add $set as first stage

```<code>db.expense.aggregate([
  {
    $set: {
      amount: {
        "$toDecimal": "$amount"
      }
    }
  },
  {
    $match: {
      $and: [
        {
          currency: "1",
          expenseType: "1"
        },
        {
          date: {
            $gte: new Date(date.value.from),
            $lte: new Date(date.value.to)
          },
          amount: {
            $gt: parseFloat(amount.value.from),
            $lt: parseFloat(amount.value.to)
          }
        }
      ]
    }
  },
  {
    $lookup: {
      from: "accounts",
      localField: "accountId",
      foreignField: "_id",
      as: "account"
    }
  }
])
</code>```

Solution 2 on Mongo Playground

Body:
I need to get the data from two collections (expenses, accounts). The data must be between the given date range and amount range.

date, amount, currency, type is in Expenses collection and accountId is in account collection as _id.
I tried the following query but it's not returning anything.

const response = await Expense.aggregate( [
   { $match: {
       $and: [
           {
               currency: "1",
               expenseType: "1"
           },
           {
               date: {
                   $gte: new Date(date.value.from) , $lte: new Date(date.value.to)
               },
               amount: {
                   $gt: parseFloat(amount.value.from) , $lt: parseFloat(amount.value.to)
               }
           }
       ],
   } },
   {
       $lookup: {
           from: "accounts",
           localField: "accountId",
           foreignField: "_id",
           as: "account"
       }
   }
] )

This is the schema of expenses collection:

Document of expense collection:

Document of account collection:

Body:
From the attached expense document, the amount field was a String type but not a Number type.

Data

amount: "20000"

Schema

amount: {
  type: Number,
  required: true
}

You should revise your Expense document in MongoDB with your schema.

From your Aggregation Query, you need to convert amount from String to Decimal to compare.

Solution 1: With $expr

db.expense.aggregate([
  {
    $match: {
      $and: [
        {
          currency: "1",
          expenseType: "1"
        },
        {
          date: {
            $gte: new Date(date.value.from),
            $lte: new Date(date.value.to)
          },

        },
        {
          $expr: {
            $and: [
              {
                $gt: [
                  {
                    "$toDecimal": "$amount"
                  },
                  parseFloat(amount.value.from)
                ]
              },
              {
                $lt: [
                  {
                    "$toDecimal": "$amount"
                  },
                  parseFloat(amount.value.to)
                ]
              }
            ]
          }
        }
      ],

    }
  },
  {
    $lookup: {
      from: "accounts",
      localField: "accountId",
      foreignField: "_id",
      as: "account"
    }
  }
])

Solution 1 on Mongo Playground

Solution 2: Add $set as first stage

db.expense.aggregate([
  {
    $set: {
      amount: {
        "$toDecimal": "$amount"
      }
    }
  },
  {
    $match: {
      $and: [
        {
          currency: "1",
          expenseType: "1"
        },
        {
          date: {
            $gte: new Date(date.value.from),
            $lte: new Date(date.value.to)
          },
          amount: {
            $gt: parseFloat(amount.value.from),
            $lt: parseFloat(amount.value.to)
          }
        }
      ]
    }
  },
  {
    $lookup: {
      from: "accounts",
      localField: "accountId",
      foreignField: "_id",
      as: "account"
    }
  }
])

Solution 2 on Mongo Playground


问:
How to get how much left on gcp free tier?
I am trying to create a script to get the amount free tier left. I have a GCP account with $300 free tier after that amount is over my applications will be shut down by Google. My question is how to get the about of left free tier using API or Python so I can send a notification to my chatting system to be aware when to migrate my application

I did go over all Stack Overflow questions and can't find the answer

答:
There are a couple of ways.

0 - Budgets programmatic notifications

I think flow from link below illustrates what you need.
https://cloud.google.com/billing/docs/how-to/budgets-programmatic-notifications
From budget alert > to pub/sub > to cloud function which you can program to do what you want including pinging slack/discord etc would have to use their APIs in cloud function. Example flow below from documentation:

1. Extracting your billing data to bigquery

https://cloud.google.com/billing/docs/how-to/export-data-bigquery
From there you could monitor billing by project and product, however I am not sure how instant it is, but you can imagine from there scheduling a BQ job or airflow to to check for statuses and ping pub/sub or cloud function to shut off what ever needs to be shut off or send messages like above

2. Set up budget alerts to yourself / other --- manual

https://cloud.google.com/billing/docs/how-to/budgets
You can set up alerts on when you are coming close to or exceeding your specified budget.

In google cloud console go to billing

Select your billing account (if multiple)

Then go to  Budgets & alerts.
I think you can publish these alerts to pub sub and go from there with whatever you need to shut down or migrate (like mentioned in 0.)

3. Budgets API

https://cloud.google.com/billing/docs/how-to/budget-api
There are some other cool things you can assemble from here for your solution.


问:
Not using decimals but got Object of type Decimal is not JSON serializable
my view is working perfectly, but when i try to store a ModelForm result on session

it's stored but got Object of type Decimal is not JSON serializable

it doesn't make sens beceause i'm not storing Decimals on session

PS: i'm storing the ModelForm result on session because i have to redirect the user to an external url after he come back i need that data stored on session

here is the view

```<code> def cart_detail(request):
    cart = Cart(request)
    order_form = OrderCreateForm()
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'override': True})

    if cart.__len__() :
        if request.method == 'POST':
            order_form = OrderCreateForm(request.POST)
            if order_form.is_valid():
                order = order_form.save(commit=False)

                for item in order_form.cleaned_data.items():
                    request.session[str(item[0])] = str(item[1])

                    print(request.session[str(item[0])])

                #also tried this way and same result
                # request.session['order_data'] = order_form.cleaned_data
                #also tried this way and same result

                # request.session['first_name'] = order_form.cleaned_data['first_name']
                # request.session['order_phone'] = str(order_form.cleaned_data['phone'])
                # print('type => ', request.session['order_phone'])

                if request.user.is_authenticated:
                    order.user = request.user
                order.save()
                for item in cart:
                    OrderItem.objects.create(order=order,product=item['product'],price=item['price'],quantity=item['quantity'],attribute_1 = ['attrbute_1'], attribute_2 = ['attrbute_2'], attribute_3 = ['attrbute_3'])
                context = {
                    'order': order,
                    'total_price': total_price,
                    'delivery': order.delivery_cost,
                    'total_price_with_delivery': total_price_with_delivery,
                }

                print('here i am')

                return render(request, 'created.html', context)
            else:
                print('errorforms', order_form.errors)
                messages.error(request, order_form.errors)
                return render(request, 'cart.html', {'cart':cart, 'form' : order_form, 'wilayas': wilayas, 'communes': communes})
        else:
            order_form = OrderCreateForm()
            if request.user.is_authenticated:
                initial_data = {
                    'first_name' : request.user.first_name,
                    'email' : request.user.email,
                    'phone' : request.user.profile.phone_number,
                    'address' : request.user.profile.address,
                }
                print('the form is not valid')
                order_form = OrderCreateForm(request.POST or None, initial=initial_data)
    context = {
        'cart': cart,
        'form' : order_form,
    }
    return render(request, 'cart.html', context)
</code>```

** THE FORM **

```<code>class OrderCreateForm(forms.ModelForm):

class Meta:
    model = Order
    fields = ['first_name',  'address', 'campany', 'email', 'phone', 'wilaya', 'commune', 'note']
    required = ('phone',)
</code>```

i don't think the problem is on session

i also commented out all methods on the Order Model

i don't even now where the problem actually is

when i remove this block all works fine

```<code>            for item in order_form.cleaned_data.items():
                request.session['order_data_'+str(item[0])] = str(item[1])
                print(request.session[str(item[0])])
</code>```

but when it's here the print works

EDIT

here is cart.py

```<code>from decimal import Decimal
from django.conf import settings
from core.models import Product
from coupons.models import Coupon

class Cart(object):

def __init__(self, request):
    self.session = request.session

    #get the current cart
    cart = self.session.get(settings.CART_SESSION_ID)
    if not cart:
        cart = self.session[settings.CART_SESSION_ID] = {}
    self.cart = cart
    #get current applied coupon
    self.coupon_id = self.session.get('coupon_id')

    """
This method is defined as a property. If the cart contains
a coupon_id attribute, the Coupon object with the given ID is returned.
"""

@property
def coupon(self):
    if self.coupon_id:
        try:
            return Coupon.objects.get(id=self.coupon_id, stock__gt=0)
        except Coupon.DoesNotExist:
            pass
    return None

def get_discount(self):
    if self.coupon:
        if self.coupon.discount_amount:
            return self.coupon.discount_amount
        else:
            discount = (self.coupon.discount_percentage / Decimal(100)) * self.get_total_price()
            return discount
    return Decimal(0)

# total price after discount = total price - discount price

def get_total_price_after_discount(self):
    price = self.get_total_price() - self.get_discount()
    if price < 0:
        price = 0
    return price

def save(self):
    self.session.modified = True

def add(self, product, quantity=1, override_quantity=False,attribute_1=False,attribute_2=False,attribute_3=False):
    product_id = str(product.id)
    if product_id not in self.cart:
        self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}

    if override_quantity:
        self.cart[product_id]['quantity'] = quantity
    else:
        self.cart[product_id]['quantity'] = quantity

    self.save()

def remove(self, product):
    product_id = str(product.id)
    if product_id in self.cart:
        del self.cart[product_id]
        self.save()

def update(self, product, quantity):
    print('im on update cart view')
    product_id = str(product.id)
    self.cart[product_id]['quantity'] = quantity
    self.save()

def __iter__(self):
    product_ids = self.cart.keys()
    products = Product.published.filter(id__in=product_ids)
    cart = self.cart.copy()
    for product in products:
        cart[str(product.id)]['product'] = product
    for item in cart.values():
        item['price'] = Decimal(item['price'])
        item['total_price'] = item['price'] * item['quantity']
        yield item

def __len__(self):
    return sum(item['quantity'] for item in self.cart.values())

def get_total_price(self):
    return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())

def clear(self):
    del self.session[settings.CART_SESSION_ID]
    self.save()
</code>```

Traceback

```<code>  Internal Server Error: /fr/cart/

Traceback (most recent call last):
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\sentry_sdk\integrations\django\middleware.py", line 175, in __call__
    return f(*args, **kwargs)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\utils\deprecation.py", line 119, in __call__
    response = self.process_response(request, response)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\contrib\sessions\middleware.py", line 61, in process_response
    request.session.save()
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 83, in save
    obj = self.create_model_instance(data)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 70, in create_model_instance
    session_data=self.encode(data),
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 114, in encode
    return signing.dumps(
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\core\signing.py", line 110, in dumps
    return TimestampSigner(key, salt=salt).sign_object(obj, serializer=serializer, compress=compress)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\core\signing.py", line 172, in sign_object
    data = serializer().dumps(obj)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\core\signing.py", line 87, in dumps
    return json.dumps(obj, separators=(',', ':')).encode('latin-1')
  File "c:\python38\lib\json\__init__.py", line 234, in dumps
    return cls(
  File "c:\python38\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "c:\python38\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "c:\python38\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Product is not JSON serializable
[12/Feb/2022 10:40:07] "POST /fr/cart/ HTTP/1.1" 500 145079
</code>```

答:
I think your issue is this line in cart.py

```<code>cart = self.session[settings.CART_SESSION_ID] = {}
</code>```

You have set your cart to equal a value in your session dict and by doing so you are altering the session every time you change your cart. So by using Decimal or Product classes, Django is trying to serialize before you sanitize your data. You should  perform your logic before setting the session variable.

I think you would be better off using a model for what you’re trying to do though. You also will want to calculate your prices in cents (or smallest unit for whatever currency) to avoid rounding errors.

Edited for further clarification:

In cart.py you have the following line.

```<code>cart = self.session[settings.CART_SESSION_ID] = {}
</code>```

From right to left, you are assigning {} to self.session[settings.CART_SESSION_ID] and then self.session[settings.CART_SESSION_ID] to cart

So for example, looking at this block of code

```<code>def __iter__(self):
    ...
    for item in cart.values():
        item['price'] = Decimal(item['price'])
    ...
</code>```

You are not just changing cart.item.price. You are also changing self.session[setting.CART_SESSION_ID].item.price. The issue is that in Django, whenever you alter session, it serializes your changes to JSON. Since self.session references the user session (in __init__), Django is trying to serialize a Decimal object and gives you an error.

To fix this, you can change the relevant part of your __init__ from

```<code>cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
    cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart
</code>```

to

```<code>cart = self.session.get(settings.CART_SESSION_ID)
self.cart = cart.copy() if cart else {}
</code>```

and make your save() method

```<code>def save():
    self.session.modified=True
    self.session[settings.CART_SESSION_ID] = self.cart
</code>```

Body:
my view is working perfectly, but when i try to store a ModelForm result on session

it's stored but got Object of type Decimal is not JSON serializable

it doesn't make sens beceause i'm not storing Decimals on session

PS: i'm storing the ModelForm result on session because i have to redirect the user to an external url after he come back i need that data stored on session

here is the view

 def cart_detail(request):
    cart = Cart(request)
    order_form = OrderCreateForm()
    for item in cart:
        item['update_quantity_form'] = CartAddProductForm(initial={'quantity': item['quantity'], 'override': True})

    if cart.__len__() :
        if request.method == 'POST':
            order_form = OrderCreateForm(request.POST)
            if order_form.is_valid():
                order = order_form.save(commit=False)

                for item in order_form.cleaned_data.items():
                    request.session[str(item[0])] = str(item[1])

                    print(request.session[str(item[0])])

                #also tried this way and same result
                # request.session['order_data'] = order_form.cleaned_data
                #also tried this way and same result

                # request.session['first_name'] = order_form.cleaned_data['first_name']
                # request.session['order_phone'] = str(order_form.cleaned_data['phone'])
                # print('type => ', request.session['order_phone'])

                if request.user.is_authenticated:
                    order.user = request.user
                order.save()
                for item in cart:
                    OrderItem.objects.create(order=order,product=item['product'],price=item['price'],quantity=item['quantity'],attribute_1 = ['attrbute_1'], attribute_2 = ['attrbute_2'], attribute_3 = ['attrbute_3'])
                context = {
                    'order': order,
                    'total_price': total_price,
                    'delivery': order.delivery_cost,
                    'total_price_with_delivery': total_price_with_delivery,
                }

                print('here i am')

                return render(request, 'created.html', context)
            else:
                print('errorforms', order_form.errors)
                messages.error(request, order_form.errors)
                return render(request, 'cart.html', {'cart':cart, 'form' : order_form, 'wilayas': wilayas, 'communes': communes})
        else:
            order_form = OrderCreateForm()
            if request.user.is_authenticated:
                initial_data = {
                    'first_name' : request.user.first_name,
                    'email' : request.user.email,
                    'phone' : request.user.profile.phone_number,
                    'address' : request.user.profile.address,
                }
                print('the form is not valid')
                order_form = OrderCreateForm(request.POST or None, initial=initial_data)
    context = {
        'cart': cart,
        'form' : order_form,
    }
    return render(request, 'cart.html', context)

** THE FORM **

class OrderCreateForm(forms.ModelForm):

class Meta:
    model = Order
    fields = ['first_name',  'address', 'campany', 'email', 'phone', 'wilaya', 'commune', 'note']
    required = ('phone',)

i don't think the problem is on session

i also commented out all methods on the Order Model

i don't even now where the problem actually is

when i remove this block all works fine

            for item in order_form.cleaned_data.items():
                request.session['order_data_'+str(item[0])] = str(item[1])
                print(request.session[str(item[0])])

but when it's here the print works

EDIT

here is cart.py

from decimal import Decimal
from django.conf import settings
from core.models import Product
from coupons.models import Coupon

class Cart(object):

def __init__(self, request):
    self.session = request.session

    #get the current cart
    cart = self.session.get(settings.CART_SESSION_ID)
    if not cart:
        cart = self.session[settings.CART_SESSION_ID] = {}
    self.cart = cart
    #get current applied coupon
    self.coupon_id = self.session.get('coupon_id')

    """
This method is defined as a property. If the cart contains
a coupon_id attribute, the Coupon object with the given ID is returned.
"""

@property
def coupon(self):
    if self.coupon_id:
        try:
            return Coupon.objects.get(id=self.coupon_id, stock__gt=0)
        except Coupon.DoesNotExist:
            pass
    return None

def get_discount(self):
    if self.coupon:
        if self.coupon.discount_amount:
            return self.coupon.discount_amount
        else:
            discount = (self.coupon.discount_percentage / Decimal(100)) * self.get_total_price()
            return discount
    return Decimal(0)

# total price after discount = total price - discount price

def get_total_price_after_discount(self):
    price = self.get_total_price() - self.get_discount()
    if price < 0:
        price = 0
    return price

def save(self):
    self.session.modified = True

def add(self, product, quantity=1, override_quantity=False,attribute_1=False,attribute_2=False,attribute_3=False):
    product_id = str(product.id)
    if product_id not in self.cart:
        self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}

    if override_quantity:
        self.cart[product_id]['quantity'] = quantity
    else:
        self.cart[product_id]['quantity'] = quantity

    self.save()

def remove(self, product):
    product_id = str(product.id)
    if product_id in self.cart:
        del self.cart[product_id]
        self.save()

def update(self, product, quantity):
    print('im on update cart view')
    product_id = str(product.id)
    self.cart[product_id]['quantity'] = quantity
    self.save()

def __iter__(self):
    product_ids = self.cart.keys()
    products = Product.published.filter(id__in=product_ids)
    cart = self.cart.copy()
    for product in products:
        cart[str(product.id)]['product'] = product
    for item in cart.values():
        item['price'] = Decimal(item['price'])
        item['total_price'] = item['price'] * item['quantity']
        yield item

def __len__(self):
    return sum(item['quantity'] for item in self.cart.values())

def get_total_price(self):
    return sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values())

def clear(self):
    del self.session[settings.CART_SESSION_ID]
    self.save()

Traceback

  Internal Server Error: /fr/cart/

Traceback (most recent call last):
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\sentry_sdk\integrations\django\middleware.py", line 175, in __call__
    return f(*args, **kwargs)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\utils\deprecation.py", line 119, in __call__
    response = self.process_response(request, response)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\contrib\sessions\middleware.py", line 61, in process_response
    request.session.save()
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 83, in save
    obj = self.create_model_instance(data)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 70, in create_model_instance
    session_data=self.encode(data),
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 114, in encode
    return signing.dumps(
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\core\signing.py", line 110, in dumps
    return TimestampSigner(key, salt=salt).sign_object(obj, serializer=serializer, compress=compress)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\core\signing.py", line 172, in sign_object
    data = serializer().dumps(obj)
  File "C:\Users\inter\Desktop\sunlab\venv\lib\site-packages\django\core\signing.py", line 87, in dumps
    return json.dumps(obj, separators=(',', ':')).encode('latin-1')
  File "c:\python38\lib\json\__init__.py", line 234, in dumps
    return cls(
  File "c:\python38\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "c:\python38\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "c:\python38\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Product is not JSON serializable
[12/Feb/2022 10:40:07] "POST /fr/cart/ HTTP/1.1" 500 145079

Body:
I think your issue is this line in cart.py

cart = self.session[settings.CART_SESSION_ID] = {}

You have set your cart to equal a value in your session dict and by doing so you are altering the session every time you change your cart. So by using Decimal or Product classes, Django is trying to serialize before you sanitize your data. You should  perform your logic before setting the session variable.

I think you would be better off using a model for what you’re trying to do though. You also will want to calculate your prices in cents (or smallest unit for whatever currency) to avoid rounding errors.

Edited for further clarification:

In cart.py you have the following line.

cart = self.session[settings.CART_SESSION_ID] = {}

From right to left, you are assigning {} to self.session[settings.CART_SESSION_ID] and then self.session[settings.CART_SESSION_ID] to cart

So for example, looking at this block of code

def __iter__(self):
    ...
    for item in cart.values():
        item['price'] = Decimal(item['price'])
    ...

You are not just changing cart.item.price. You are also changing self.session[setting.CART_SESSION_ID].item.price. The issue is that in Django, whenever you alter session, it serializes your changes to JSON. Since self.session references the user session (in __init__), Django is trying to serialize a Decimal object and gives you an error.

To fix this, you can change the relevant part of your __init__ from

cart = self.session.get(settings.CART_SESSION_ID)
if not cart:
    cart = self.session[settings.CART_SESSION_ID] = {}
self.cart = cart

to

cart = self.session.get(settings.CART_SESSION_ID)
self.cart = cart.copy() if cart else {}

and make your save() method

def save():
    self.session.modified=True
    self.session[settings.CART_SESSION_ID] = self.cart


问:
Firebase JS: Why and When to unsubscribe onAuthStateChanged
I am working on a weird kind of site where I only need to send forms to firestore and save pdf files to firestorage.
Not even running any server-side code, just html and JS on the final client.
My organization will only give an apache server path to run html, CSS and JS.
Later I'll need to read but I'm the only user with read access so it's not a big deal because I will run that locally on my node.js CLI.

But I am looking forward to make my code as safe and efficient as possible even tho I have no idea what I'm doing 60% of the time.

Reading the docs and code online I realized that I am not doing unsubscribe() when I do my onAuthStateChanged().
By searching about memory leaks on JS I found a guy saying that if I meant to keep something live up in memory then I shouldn't unsubscribe from it. But as I said, I have no idea what I am doing.

Here is some of my .js and my login.html
I am worried about 4 things, here I go:

should I unsubscribe() after my sign-in-out  onAuthStateChanged ends? if so, where?

is it ok to set all this code inside window.onload ?

Should I split this code into modules so I can re-use the initializeApp() and other repetitive code or it is not recommendable since I am using CDN to import the firebase modules instead of using the import sentence.

Am I supposed to do the initializeApp() on every single one of my html pages? or doing it once on the login and forcing the user to login via vanilla JS will be the way to go?

```<code>window.onload = () => {
    //Config and init fb
    var firebaseConfig = {
        //...my config
    };
    if (!firebase.apps.length) {
        firebase.initializeApp(firebaseConfig)
    }
    const auth = firebase.auth();
    const provider = new firebase.auth.GoogleAuthProvider();
    //Get elements
    const signInBtn = document.getElementById("log-in-btn");
    //Listeners
    signInBtn.onclick = () => auth.signInWithPopup(provider);
    //Listeners require user
    //sign-in-out
    auth.onAuthStateChanged(user => {
        if (user) {
            // signed in
            if (!user.email.includes('@mydomain.com')) {
                auth.signOut();
                 //maybe delete the user, haven't test it
                alert('Porfavor utilice su correo institucional');
            } else {
                window.location.replace('dashboard.html');
            }
        } else {
            // not signed in you will always end up here
        }
    });
}
</code>```

html are all something like this but I have a JS file for each html, and each JS configs and inits firebase.

```<code><head>
    <meta charset="UTF-8">
    <title>Login </title>
    <!--Project CSS-->
    <!--Boostrap 5-->
    <!--Firebase Modules-->
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-firestore.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-auth.js"></script>
    <script src="https://www.gstatic.com/firebasejs/8.10.0/firebase-storage.js"></script>
    <!--Proyect Modules-->
    <script src="js/login.js" defer></script>
</head>
</code>```

and later in my dashboard this is my approach

```<code>window.onload = () => {
    var firebaseConfig = {
        //my config
    };
    if (!firebase.apps.length) {
        firebase.initializeApp(firebaseConfig)
    }
    const auth = firebase.auth();
    const provider = new firebase.auth.GoogleAuthProvider();
    //Get elements
    const signedIn = document.getElementById("toggle-w-log-in");
    const signedOff = document.getElementById("toggle-w-log-off");
    const signInBtn = document.getElementById("log-in-btn");
    const signOutBtn = document.getElementById("log-off-btn");
    const uname = document.getElementById("userName");
    const userDetails = document.getElementById("userDetails");
    //Events / Listeners
    signOutBtn.onclick = () => {
        auth.signOut();
              window.location.replace("login.html");
    };
    //Events / Listeners that require user
    //sign-in-out
    auth.onAuthStateChanged(user => {
        if (user) {
            // signed in
            signedIn.hidden = false;
            signedOff.hidden = true;
            userDetails.innerHTML = `<b>Sesión iniciada como ${user.displayName}</b>`;
            var contentImgUser = document.getElementById("img-Us");
            contentImgUser.setAttribute("src", user.photoURL);
        } else {
            // not signed in
            signedIn.hidden = true;
            signedOff.hidden = false;
            userDetails.innerHTML = '';
                  window.location.replace("login.html");
        }
    });
}
</code>```

finally the million dollar question: Am I going crazy with this code for my forms?

```<code>window.onload = () => {
    var firebaseConfig = {
        //my config
    };
    if (!firebase.apps.length) {
        firebase.initializeApp(firebaseConfig)
    }
    const auth = firebase.auth();
    const provider = new firebase.auth.GoogleAuthProvider();
    //Get elements from dom by id
    //Events / Listeners
    //sign-in-out
    signOutBtn.onclick = () => {
        auth.signOut();
        window.location.replace("login.html");
    };
    auth.onAuthStateChanged(user => {
        if (user) {
            // signed in
            signedIn.hidden = false;
            signedOff.hidden = true;
            //display the userDetails
            //display user name in the username field
            uname.value = user.displayName;
        } else {
            // not signed in
            signedIn.hidden = true;
            signedOff.hidden = false;
            userDetails.innerHTML = '';
            window.location.replace("login.html");
        }
    });
    //save file to Firestorage then save doc to Firestore
    //finally set a cooldown on the button
    auth.onAuthStateChanged(user => {
        saveBtn.addEventListener("click", (event) => {
            event.preventDefault();
            //check my required files
            if (requiredFields) {
                saveBtn.disabled = true;
                //some logic with my progressbar
                var metadata = {
                    contentType: 'application/pdf'
                };
                const files = document.getElementById("myfile").files;
                var storageRef = firebase.storage().ref();
                let file = files[0];
                // Upload file and metadata to the object 'pdf/filename.pdf'
                // Listen for state changes, errors, and completion of the upload.
                uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
                    (snapshot) => {
                        // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
                        //some logic with the progress to fill my progressbar
                        switch (snapshot.state) {
                            case firebase.storage.TaskState.PAUSED:
                                break;
                            case firebase.storage.TaskState.RUNNING:
                                break;
                        }
                    },
                    (error) => {
                        switch (error.code) {
                            case 'storage/unauthorized':
                                break;
                            case 'storage/canceled':
                                break;
                            case 'storage/unknown':
                                break;
                        }
                    },
                    () => {
                        // Upload completed successfully, now we can get the download URL
                        uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
                            const db = firebase.firestore().collection('mycollections');
                            const userUid = user.uid;
                            const timestamp = new Date().getTime();
                            try {
                                db.add({
                                    refEvi: downloadURL,
                                    userUid: userUid,
                                    //all my fields
                                }).then((docRef) => {
                                    artRes.innerHTML = "<b>Registro guardado con la referencia: </b>" + docRef.id;
                                });
                            } catch (error) {
                                console.log(error);
                                artRes.innerHTML = "<b>Problema al guardar registro en la base de datos.  </b>" + error;
                            } finally {
                                //a timer to enable my button a few secs after everything is done
                            }
                        });
                    }
                );
            }
        });
    });
}
</code>```

yes I just replaced some code with comments to make this post readable.
is there any point in my js where I should unsubscribe from the onAuthStateChanged?

答:
Subscribing to auth state depends on your use case.

If you want to develop your system in a reactive way, that is, your UI changes itself because it's subscribed to the auth state (no reloads or redirects). Then you should never unsubscribe to auth state.

The opposite case (you don't want to subscribe) in which you can listen to the auth state change event (response from Firebase after login form submitted) and do the proper changes to the UI. In that case, you should check the auth state every time the page loads. This way, you can reload or redirect since you'll be checking the auth state. You must also know when a user logs out of course.

Body:
I am working on a weird kind of site where I only need to send forms to firestore and save pdf files to firestorage.
Not even running any server-side code, just html and JS on the final client.
My organization will only give an apache server path to run html, CSS and JS.
Later I'll need to read but I'm the only user with read access so it's not a big deal because I will run that locally on my node.js CLI.

But I am looking forward to make my code as safe and efficient as possible even tho I have no idea what I'm doing 60% of the time.

Reading the docs and code online I realized that I am not doing unsubscribe() when I do my onAuthStateChanged().
By searching about memory leaks on JS I found a guy saying that if I meant to keep something live up in memory then I shouldn't unsubscribe from it. But as I said, I have no idea what I am doing.

Here is some of my .js and my login.html
I am worried about 4 things, here I go:

should I unsubscribe() after my sign-in-out  onAuthStateChanged ends? if so, where?

is it ok to set all this code inside window.onload ?

Should I split this code into modules so I can re-use the initializeApp() and other repetitive code or it is not recommendable since I am using CDN to import the firebase modules instead of using the import sentence.

Am I supposed to do the initializeApp() on every single one of my html pages? or doing it once on the login and forcing the user to login via vanilla JS will be the way to go?

window.onload = () => {
    //Config and init fb
    var firebaseConfig = {
        //...my config
    };
    if (!firebase.apps.length) {
        firebase.initializeApp(firebaseConfig)
    }
    const auth = firebase.auth();
    const provider = new firebase.auth.GoogleAuthProvider();
    //Get elements
    const signInBtn = document.getElementById("log-in-btn");
    //Listeners
    signInBtn.onclick = () => auth.signInWithPopup(provider);
    //Listeners require user
    //sign-in-out
    auth.onAuthStateChanged(user => {
        if (user) {
            // signed in
            if (!user.email.includes('@mydomain.com')) {
                auth.signOut();
                 //maybe delete the user, haven't test it
                alert('Porfavor utilice su correo institucional');
            } else {
                window.location.replace('dashboard.html');
            }
        } else {
            // not signed in you will always end up here
        }
    });
}

html are all something like this but I have a JS file for each html, and each JS configs and inits firebase.

    <meta charset="UTF-8">
    <title>Login </title>

and later in my dashboard this is my approach

window.onload = () => {
    var firebaseConfig = {
        //my config
    };
    if (!firebase.apps.length) {
        firebase.initializeApp(firebaseConfig)
    }
    const auth = firebase.auth();
    const provider = new firebase.auth.GoogleAuthProvider();
    //Get elements
    const signedIn = document.getElementById("toggle-w-log-in");
    const signedOff = document.getElementById("toggle-w-log-off");
    const signInBtn = document.getElementById("log-in-btn");
    const signOutBtn = document.getElementById("log-off-btn");
    const uname = document.getElementById("userName");
    const userDetails = document.getElementById("userDetails");
    //Events / Listeners
    signOutBtn.onclick = () => {
        auth.signOut();
              window.location.replace("login.html");
    };
    //Events / Listeners that require user
    //sign-in-out
    auth.onAuthStateChanged(user => {
        if (user) {
            // signed in
            signedIn.hidden = false;
            signedOff.hidden = true;
            userDetails.innerHTML = `<b>Sesión iniciada como ${user.displayName}</b>`;
            var contentImgUser = document.getElementById("img-Us");
            contentImgUser.setAttribute("src", user.photoURL);
        } else {
            // not signed in
            signedIn.hidden = true;
            signedOff.hidden = false;
            userDetails.innerHTML = '';
                  window.location.replace("login.html");
        }
    });
}

finally the million dollar question: Am I going crazy with this code for my forms?

window.onload = () => {
    var firebaseConfig = {
        //my config
    };
    if (!firebase.apps.length) {
        firebase.initializeApp(firebaseConfig)
    }
    const auth = firebase.auth();
    const provider = new firebase.auth.GoogleAuthProvider();
    //Get elements from dom by id
    //Events / Listeners
    //sign-in-out
    signOutBtn.onclick = () => {
        auth.signOut();
        window.location.replace("login.html");
    };
    auth.onAuthStateChanged(user => {
        if (user) {
            // signed in
            signedIn.hidden = false;
            signedOff.hidden = true;
            //display the userDetails
            //display user name in the username field
            uname.value = user.displayName;
        } else {
            // not signed in
            signedIn.hidden = true;
            signedOff.hidden = false;
            userDetails.innerHTML = '';
            window.location.replace("login.html");
        }
    });
    //save file to Firestorage then save doc to Firestore
    //finally set a cooldown on the button
    auth.onAuthStateChanged(user => {
        saveBtn.addEventListener("click", (event) => {
            event.preventDefault();
            //check my required files
            if (requiredFields) {
                saveBtn.disabled = true;
                //some logic with my progressbar
                var metadata = {
                    contentType: 'application/pdf'
                };
                const files = document.getElementById("myfile").files;
                var storageRef = firebase.storage().ref();
                let file = files[0];
                // Upload file and metadata to the object 'pdf/filename.pdf'
                // Listen for state changes, errors, and completion of the upload.
                uploadTask.on(firebase.storage.TaskEvent.STATE_CHANGED,
                    (snapshot) => {
                        // Get task progress, including the number of bytes uploaded and the total number of bytes to be uploaded
                        //some logic with the progress to fill my progressbar
                        switch (snapshot.state) {
                            case firebase.storage.TaskState.PAUSED:
                                break;
                            case firebase.storage.TaskState.RUNNING:
                                break;
                        }
                    },
                    (error) => {
                        switch (error.code) {
                            case 'storage/unauthorized':
                                break;
                            case 'storage/canceled':
                                break;
                            case 'storage/unknown':
                                break;
                        }
                    },
                    () => {
                        // Upload completed successfully, now we can get the download URL
                        uploadTask.snapshot.ref.getDownloadURL().then((downloadURL) => {
                            const db = firebase.firestore().collection('mycollections');
                            const userUid = user.uid;
                            const timestamp = new Date().getTime();
                            try {
                                db.add({
                                    refEvi: downloadURL,
                                    userUid: userUid,
                                    //all my fields
                                }).then((docRef) => {
                                    artRes.innerHTML = "Registro guardado con la referencia: " + docRef.id;
                                });
                            } catch (error) {
                                console.log(error);
                                artRes.innerHTML = "Problema al guardar registro en la base de datos.  " + error;
                            } finally {
                                //a timer to enable my button a few secs after everything is done
                            }
                        });
                    }
                );
            }
        });
    });
}

yes I just replaced some code with comments to make this post readable.
is there any point in my js where I should unsubscribe from the onAuthStateChanged?


问:
How do I auto-reload a Chrome extension I'm developing?
I'd like for my chrome extension to reload every time I save a file in the extension folder, without having to explicitly click "reload" in chrome://extensions/. Is this possible?

Edit: I'm aware I can update the interval at which Chrome reloads extensions, which is a half-way solution, but I'd rather either making my editor (emacs or textmate) trigger on-save a reload or asking Chrome to monitor the directory for changes.

答:
MAC ONLY

Using Extensions Reloader:

Using Typescript

Add the watcher of your to your project: yarn add tsc-watch

Add command to scripts to package.json

...
  "scripts": {
    "dev": "tsc-watch --onSuccess \"open -a '/Applications/Google Chrome.app' 'http://reload.extensions'\""
  },
...
```
<ol start="3">
<li>Run script <code>yarn dev</code></li>
</ol>
<h3>Using JavaScript</h3>
<ol>
<li><p>Add the watcher of your to your project: <code>yarn add watch-cli</code></p>
</li>
<li><p>Add command to <code>scripts</code> to <code>package.json</code></p>
</li>
</ol>
<pre class="lang-json prettyprint-override"><code>...
  "scripts": {
    "dev": "watch -p \"**/*.js\" -c \"open -a '/Applications/Google Chrome.app' 'http://reload.extensions'\""
  },
...
</code>```

Run script yarn dev

Bonus: Turn on 'reload current tab' in Extensions Reloader options, so it reloads after a change was made:

Body:
MAC ONLY

Using Extensions Reloader:

Using Typescript

Add the watcher of your to your project: yarn add tsc-watch

Add command to scripts to package.json

...
  "scripts": {
    "dev": "tsc-watch --onSuccess \"open -a '/Applications/Google Chrome.app' 'http://reload.extensions'\""
  },
...

Run script yarn dev

Using JavaScript

Add the watcher of your to your project: yarn add watch-cli

Add command to scripts to package.json

...
  "scripts": {
    "dev": "watch -p \"**/*.js\" -c \"open -a '/Applications/Google Chrome.app' 'http://reload.extensions'\""
  },
...

Run script yarn dev

Bonus: Turn on 'reload current tab' in Extensions Reloader options, so it reloads after a change was made:


问:
Set lockscreen to "None" programmatically?
I have the requirement to disable the lock screen and set the lock screen type to "None". My device is rooted (can run with SU permission) + can run as a system application with system permissions (under /system/app).

I have tried a few things to no avail.

Try 1

This seems to be deprecated and not working.

```<code>KeyguardManager manager = (KeyguardManager) this.getSystemService(KEYGUARD_SERVICE);
KeyguardLock lock = manager.newKeyguardLock("abc");
lock.disableKeyguard();
</code>```

Try 2

This didn't work either.

Mount system partition as writable

Edit /data/data/com.android.providers.settings/databases/settings.db

Execute the following SQL.

INSERT OR REPLACE INTO system (name, value) VALUES ('lockscreen.disabled', '1');

INSERT OR REPLACE INTO secure (name, value) VALUES ('lockscreen.disabled', '1');

Try 3

Rebooted the machine but still no luck.

```<code>android.provider.Settings.Secure.putLong(mContentResolver, Settings.Secure.LOCK_PATTERN_ENABLED, false);`
android.provider.Settings.Secure.putLong(mContentResolver, "lockscreen.password_type", DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);`
android.provider.Settings.Secure.putLong(mContentResolver, "lockscreen.password_type_alternate", DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
android.provider.Settings.Secure.putLong(mContentResolver, "lockscreen.disabled", true);
</code>```

Is there anything else that I can try?

Please note that I do not want to disable the keyguard only when application is running.

答:
On rooted nexus 5,
In terminal via twrp recovery I simply
rm /data/system/locksettings.db
and reboot</p>

Body:
I have the requirement to disable the lock screen and set the lock screen type to "None". My device is rooted (can run with SU permission) + can run as a system application with system permissions (under /system/app).

I have tried a few things to no avail.

Try 1

This seems to be deprecated and not working.

KeyguardManager manager = (KeyguardManager) this.getSystemService(KEYGUARD_SERVICE);
KeyguardLock lock = manager.newKeyguardLock("abc");
lock.disableKeyguard();

Try 2

This didn't work either.

Mount system partition as writable

Edit /data/data/com.android.providers.settings/databases/settings.db

Execute the following SQL.

INSERT OR REPLACE INTO system (name, value) VALUES ('lockscreen.disabled', '1');

INSERT OR REPLACE INTO secure (name, value) VALUES ('lockscreen.disabled', '1');

Try 3

Rebooted the machine but still no luck.

android.provider.Settings.Secure.putLong(mContentResolver, Settings.Secure.LOCK_PATTERN_ENABLED, false);`
android.provider.Settings.Secure.putLong(mContentResolver, "lockscreen.password_type", DevicePolicyManager.PASSWORD_QUALITY_SOMETHING);`
android.provider.Settings.Secure.putLong(mContentResolver, "lockscreen.password_type_alternate", DevicePolicyManager.PASSWORD_QUALITY_UNSPECIFIED);
android.provider.Settings.Secure.putLong(mContentResolver, "lockscreen.disabled", true);

Is there anything else that I can try?

Please note that I do not want to disable the keyguard only when application is running.


问:
Is there any event generated when tag is added to an existing S3 object?
I'd like to have an AWS lambda triggered when a tag is added to an existing object in S3 bucket (in the same way as we can do it for object create and remove). Any way to do that?</p>

答:
Object tagging events are now supported:

```<code>s3:ObjectTagging:*
s3:ObjectTagging:Put
s3:ObjectTagging:Delete
</code>```

Docs:
https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-how-to-event-types-and-destinations.html

Body:
Object tagging events are now supported:

s3:ObjectTagging:*
s3:ObjectTagging:Put
s3:ObjectTagging:Delete

Docs:
https://docs.aws.amazon.com/AmazonS3/latest/userguide/notification-how-to-event-types-and-destinations.html


问:
dd stderr output CR ( ^M / 0xD ) at the end of the lines
I try to log dd's output to a file. For example:

dd if=/dev/sdc of=/dev/null status=progress 2> output.log

Then when I try to open output.log with a vim, I see one long line and ^M sign where newline should be.

```<code>2086523392 bytes (2,1 GB, 1,9 GiB) copied, 5 s, 417 MB/s^M2497234432 bytes (2,5 GB, 2,3 GiB) copied, 6 s, 416 MB/s^M
</code>```

I can properly view output.log in vim only doing search&replace :%s/\%x0D/\r/g, or this :e ++ff=mac

It seems that dd uses mac's CR symbol in output for line break, instead of unix's LF. Why?

答: CR stands for "carriage return". That implies moving a carriage of your "typewriter" all the way to the left without scrolling "a sheet of paper". In other words, it works as "home" key when program outputs text on terminal. So every new "progress output" erases the previous one. Of course, it only works like that in terminal, not when redirected to file. Quite probably, you are not supposed to have status=progress and redirection at the same time.

Body:
I try to log dd's output to a file. For example:

dd if=/dev/sdc of=/dev/null status=progress 2> output.log

Then when I try to open output.log with a vim, I see one long line and ^M sign where newline should be.

2086523392 bytes (2,1 GB, 1,9 GiB) copied, 5 s, 417 MB/s^M2497234432 bytes (2,5 GB, 2,3 GiB) copied, 6 s, 416 MB/s^M

I can properly view output.log in vim only doing search&replace :%s/\%x0D/\r/g, or this :e ++ff=mac

It seems that dd uses mac's CR symbol in output for line break, instead of unix's LF. Why?


问:
Cypress: possible to select random element with eq() dynamically?
is it possible to select a random element within the eq()?
I have the following use case:
There are several dropdowns with different dropdown options.
I want Cypress to open the dropdown, get the max number of dropdown options and then select a random option from the count.
I would like to avoid doing this with separate variables but rather directly dynamically within the command. This is what my current attempt looks like but it doesn't work:

```<code>cy.dropdownSelector().eq(0).click()
cy.dropdownOptions().eq(Math.floor(Math.random() * cy.dropdownOptions().length)).click()
</code>```

答:
There is no need to use eq()

You can use the sample method from Lodash which is baked in in Cypress. sample will pick a random item from the collection.

It makes the test shorter and more clear:

cy.get('selector').then(options => {
  cy.get(Cypress._.sample(options)).click()
})
```

Body:
is it possible to select a random element within the eq()?
I have the following use case:
There are several dropdowns with different dropdown options.
I want Cypress to open the dropdown, get the max number of dropdown options and then select a random option from the count.
I would like to avoid doing this with separate variables but rather directly dynamically within the command. This is what my current attempt looks like but it doesn't work:

cy.dropdownSelector().eq(0).click()
cy.dropdownOptions().eq(Math.floor(Math.random() * cy.dropdownOptions().length)).click()


问:
java.lang.ClassNotFoundException in a simple HelloWorld
I get the message after I try to start "java -cp . "HelloWorld"

Fehler: Hauptklasse .\HelloWorld konnte nicht gefunden oder geladen werden
Ursache: java.lang.ClassNotFoundException: /\HelloWorld

It's only a simple programm to check out, if the IDE is runnng correctly.

答:
check if java installed java -version

compile javac HelloWorld.java

run java Helloworld


问:
Post data to Outlook calendar using Django, Requests, and Microsoft Graph
I have a function where I am trying to make a post request to my outlook calendar using Microsoft’s Graph API.

def create_calendar_event(token, payload, **kwargs):
    """
    Creates a new calendar event
    :param payload: json str
    :param token: str
    :return: dict
    """
    graph_client = OAuth2Session(token=token)
    url_endpoint = "https://graph.microsoft.com/v1.0/me/events"
    events = graph_client.post(url=url_endpoint, json=payload)

    return events.json()
```

<p>In my view I am using a form to get the data from the user so I can in return post the user data to my Outlook calendar. The form looks something like this:</p>

<pre class="lang-py prettyprint-override"><code>class CalendarFormView(TemplateView):
    template_name = "event-form.html"

    def get(self, request, **kwargs):
        form = CalendarEventForm()
        return render(request, self.template_name, {"form": form})

    def post(self, request):
        form = CalendarEventForm(request.POST)
        token = client.get_token(request)  # does get the token correctly

        if form.is_valid():
            subject = form.cleaned_data["subject"]
            content = form.cleaned_data["body_content"]
            start = form.cleaned_data["start"]
            end = form.cleaned_data["end"]
            location = form.cleaned_data["location"]
            is_all_day = form.cleaned_data["is_all_day"]

            payload = {
                "subject": subject,
                "body": {"contentType": "html", "content": content},
                “start”: {
                    "dateTime": start.strftime("%Y-%m-%dT%H:%M:%S.%f"),
                    "timeZone": "UTC",
                },
                "end": {
                    "dateTime": end.strftime("%Y-%m-%dT%H:%M:%S.%f"),
                    "timeZone": "UTC",
                },
                "location": {"displayName": location},
                "isAllDay": is_all_day,
            }
            event = create_calendar_event(token, json.dumps(payload))
            print(event)

            return render(request, self.template_name, context=event)

        return render(request, "event-form.html", {"form": form})
</code>```

I am getting the access_token and the form data correctly passed into the payload dictionary, however, when I print out event I receive the following error message:

{u'error': {u'innerError': {u'date': u'2020-01-20T21:59:24', u'request-id': u'fxbxd5c1-myxx-reqx-idxx-1xxxxab91a'}, u'message': u'Empty Payload. JSON content expected.', u'code': u'BadRequest'}}
```

Everything is correctly set up on the Azure/Microsoft Graph side. I am able to GET my calendar events and POST requests when I use the Microsoft Graph Explorer. The problem is only with POSTing events to my calendar from my Django app.

Any thoughts on where I could be going wrong?

答: Actually i think your variable payload is formatted as json. Thats why you dont need to make use of json.dumps.

Body:
I have a function where I am trying to make a post request to my outlook calendar using Microsoft’s Graph API.

def create_calendar_event(token, payload, **kwargs):
    """
    Creates a new calendar event
    :param payload: json str
    :param token: str
    :return: dict
    """
    graph_client = OAuth2Session(token=token)
    url_endpoint = "https://graph.microsoft.com/v1.0/me/events"
    events = graph_client.post(url=url_endpoint, json=payload)

    return events.json()

In my view I am using a form to get the data from the user so I can in return post the user data to my Outlook calendar. The form looks something like this:

class CalendarFormView(TemplateView):
    template_name = "event-form.html"

    def get(self, request, **kwargs):
        form = CalendarEventForm()
        return render(request, self.template_name, {"form": form})

    def post(self, request):
        form = CalendarEventForm(request.POST)
        token = client.get_token(request)  # does get the token correctly

        if form.is_valid():
            subject = form.cleaned_data["subject"]
            content = form.cleaned_data["body_content"]
            start = form.cleaned_data["start"]
            end = form.cleaned_data["end"]
            location = form.cleaned_data["location"]
            is_all_day = form.cleaned_data["is_all_day"]

            payload = {
                "subject": subject,
                "body": {"contentType": "html", "content": content},
                “start”: {
                    "dateTime": start.strftime("%Y-%m-%dT%H:%M:%S.%f"),
                    "timeZone": "UTC",
                },
                "end": {
                    "dateTime": end.strftime("%Y-%m-%dT%H:%M:%S.%f"),
                    "timeZone": "UTC",
                },
                "location": {"displayName": location},
                "isAllDay": is_all_day,
            }
            event = create_calendar_event(token, json.dumps(payload))
            print(event)

            return render(request, self.template_name, context=event)

        return render(request, "event-form.html", {"form": form})

I am getting the access_token and the form data correctly passed into the payload dictionary, however, when I print out event I receive the following error message:

{u'error': {u'innerError': {u'date': u'2020-01-20T21:59:24', u'request-id': u'fxbxd5c1-myxx-reqx-idxx-1xxxxab91a'}, u'message': u'Empty Payload. JSON content expected.', u'code': u'BadRequest'}}

Everything is correctly set up on the Azure/Microsoft Graph side. I am able to GET my calendar events and POST requests when I use the Microsoft Graph Explorer. The problem is only with POSTing events to my calendar from my Django app.

Any thoughts on where I could be going wrong?


问:
how to replace the typescript alias when compile
I define the typescript alias in tsconfig.json like this:

```<code>"paths": {
      "@net/*":["net/*"],
      "@auth/*":["auth/*"],
    },
</code>```

then using this alias in index.ts like this:

```<code>import { ResponseHandler } from "@net/rest/ResponseHandler";
export { ResponseHandler };
</code>```

when compile the typescript project, I want to replace the alias @net to the project real path like this ../net/rest/ResponseHandler so that the project path could parse correctly when using in other project as a lib. how to replace the alias name? I have tried using tsc-alias by using this command after installed the tsc-alias lib:

```<code>"tscbuild": "tsc && tsc-alias",
</code>```

but it did not replace the @net, what should I do to replace the typescript alias success? any suggestion?

答:
I do not know how to replace the path using tsc-alias. But you can tried to install ttypescript:

```<code>yarn add ttypescript --save-dev
</code>```

and replace your tscbuild command like this:

```<code>"tscbuild": "ttsc",
</code>```

I have tried and it could succesfully replace the path like @net to ../src/net/.

Body:
I define the typescript alias in tsconfig.json like this:

"paths": {
      "@net/*":["net/*"],
      "@auth/*":["auth/*"],
    },

then using this alias in index.ts like this:

import { ResponseHandler } from "@net/rest/ResponseHandler";
export { ResponseHandler };

when compile the typescript project, I want to replace the alias @net to the project real path like this ../net/rest/ResponseHandler so that the project path could parse correctly when using in other project as a lib. how to replace the alias name? I have tried using tsc-alias by using this command after installed the tsc-alias lib:

"tscbuild": "tsc && tsc-alias",

but it did not replace the @net, what should I do to replace the typescript alias success? any suggestion?

Body:
I do not know how to replace the path using tsc-alias. But you can tried to install ttypescript:

yarn add ttypescript --save-dev

and replace your tscbuild command like this:

"tscbuild": "ttsc",

I have tried and it could succesfully replace the path like @net to ../src/net/.


问:
Send keypresses to backgrounded application
If I have a command line program executed as a backgrounded thread (AKA with ./program &) that interacts with the command line, how can I send commands to it? Is there a way (say, using 'pipe') to send characters as though they were being inputted on the command line?

Simplified command-line example:

Without & (normal case):

```<code>~/home/temp> ./testprogram

~/home/temp> Welcome to Testprogram. Enter command:

~/home/temp> Welcome to Testprogram. Enter command: quit

~/home/temp> Goodbye!
</code>```

With & (my case!):

```<code>~/home/temp> ./testprogram &

~/home/temp> Welcome to Testprogram. Enter command:

~/home/temp> quit

~/home/temp> Command not found.
</code>```

A ps -e | grep testprogram shows that it's still running, but now can never terminate outside of a 'kill' command.

What would be ideal is something like the following:

```<code>~/home/temp> ./testprogram &

~/home/temp> Welcome to Testprogram. Enter command:

~/home/temp> quit

~/home/temp> Command not found.

~/home/temp> quit | /cat/proc/testprogram

~/home/temp> Goodbye!
</code>```

How exactly do I do this?

答:
You can bring the program back using fg:

```<code>~/home/temp> ./testprogram &
Welcome to Testprogram. Enter command:
~/home/temp> ls /tmp  # do whatever else you want to do on the shell
# ... later
~/home/temp> jobs     # what was running?
[1]+  Running                 ./testprogram &
~/home/temp> fg       # Brings testprogram to foreground, does not re-prompt
quit
Goodbye!
~/home/temp>
</code>```

If you have more than one backgrounded jobs, you can choose which to foreground using "fg %1" "fg %2"...

Note: you can put a foregrounded job back into the background by stopping (Ctrl-z) the job then typing bg at the shell prompt.

Body:
If I have a command line program executed as a backgrounded thread (AKA with ./program &) that interacts with the command line, how can I send commands to it? Is there a way (say, using 'pipe') to send characters as though they were being inputted on the command line?

Simplified command-line example:

Without & (normal case):

~/home/temp> ./testprogram

~/home/temp> Welcome to Testprogram. Enter command:

~/home/temp> Welcome to Testprogram. Enter command: quit

~/home/temp> Goodbye!

With & (my case!):

~/home/temp> ./testprogram &

~/home/temp> Welcome to Testprogram. Enter command:

~/home/temp> quit

~/home/temp> Command not found.

A ps -e | grep testprogram shows that it's still running, but now can never terminate outside of a 'kill' command.

What would be ideal is something like the following:

~/home/temp> ./testprogram &

~/home/temp> Welcome to Testprogram. Enter command:

~/home/temp> quit

~/home/temp> Command not found.

~/home/temp> quit | /cat/proc/testprogram

~/home/temp> Goodbye!

How exactly do I do this?

Body:
You can bring the program back using fg:

~/home/temp> ./testprogram &
Welcome to Testprogram. Enter command:
~/home/temp> ls /tmp  # do whatever else you want to do on the shell
# ... later
~/home/temp> jobs     # what was running?
[1]+  Running                 ./testprogram &
~/home/temp> fg       # Brings testprogram to foreground, does not re-prompt
quit
Goodbye!
~/home/temp>

If you have more than one backgrounded jobs, you can choose which to foreground using "fg %1" "fg %2"...

Note: you can put a foregrounded job back into the background by stopping (Ctrl-z) the job then typing bg at the shell prompt.


问:
Failed to spawn: unable to find process with name 'o-paus'
what should i do,
when i do frida -U -f Telegram -l freda.js — -no-whale and it exits like
Failed to spawn: unable to find process with name 'o-paus'

答:
You can only start an app using it's package name but in your example you are using the app name "Telegram". The app name can only be used for attaching to running processes.

Considering this the correct command is:

```<code>frida -U -f org.telegram.messenger -l freda.js --no-pause
</code>```

Body:
You can only start an app using it's package name but in your example you are using the app name "Telegram". The app name can only be used for attaching to running processes.

Considering this the correct command is:

frida -U -f org.telegram.messenger -l freda.js --no-pause


问:
How do I delete folder that that was synced with Onedrive but refused to stop syncing?
There is this project folder that I am trying to delete but it keeps denying me even after I ran rm -force. It shows me this instead:

```<code>is an NTFS junction point. Use the Force parameter to delete or modify this object.
At line:1 char:1
+ rm .\db\
+ ~~~~~~~~
    + CategoryInfo          : WriteError: (C:\Users\KenGon...git\objects\db\:DirectoryInfo) [Remove-Item], IOException
    + FullyQualifiedErrorId : DirectoryNotEmpty,Microsoft.PowerShell.Commands.RemoveItemCommand
</code>```

.

```<code>rm : There is a mismatch between the tag specified in the request and the tag present in the reparse point
At line:1 char:1
+ rm .\db\ -force
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Remove-Item], Win32Exception
    + FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.RemoveItemCommand
</code>```

When is move into the folder, and tried to list the folder contents, it shows me this instead:

```<code>ls : The tag present in the reparse point buffer is invalid.
At line:1 char:1
+ ls
+ ~~
    + CategoryInfo          : ReadError: (C:\Users\KenGon....git\objects\db:String) [Get-ChildItem], IOException
    + FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand
</code>```

Is there any way in which I can delete this folder? I have already stopped syncing with OneDrive and restarted it multiple times. The advice I found on Microsoft's forums does not seem to help. Even after pausing the sync, the folders still show a blue circular arrows - still syncing?

答:
Alternative and potentially faster solution: Use Windows Subsystem for Linux (WSL), change to directory and delete files/folders</p>
```<code>rm -r -f mybrokenfolder
</code>```

Body:
There is this project folder that I am trying to delete but it keeps denying me even after I ran rm -force. It shows me this instead:

is an NTFS junction point. Use the Force parameter to delete or modify this object.
At line:1 char:1
+ rm .\db\
+ ~~~~~~~~
    + CategoryInfo          : WriteError: (C:\Users\KenGon...git\objects\db\:DirectoryInfo) [Remove-Item], IOException
    + FullyQualifiedErrorId : DirectoryNotEmpty,Microsoft.PowerShell.Commands.RemoveItemCommand

.

rm : There is a mismatch between the tag specified in the request and the tag present in the reparse point
At line:1 char:1
+ rm .\db\ -force
+ ~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Remove-Item], Win32Exception
    + FullyQualifiedErrorId : System.ComponentModel.Win32Exception,Microsoft.PowerShell.Commands.RemoveItemCommand

When is move into the folder, and tried to list the folder contents, it shows me this instead:

ls : The tag present in the reparse point buffer is invalid.
At line:1 char:1
+ ls
+ ~~
    + CategoryInfo          : ReadError: (C:\Users\KenGon....git\objects\db:String) [Get-ChildItem], IOException
    + FullyQualifiedErrorId : DirIOError,Microsoft.PowerShell.Commands.GetChildItemCommand

Is there any way in which I can delete this folder? I have already stopped syncing with OneDrive and restarted it multiple times. The advice I found on Microsoft's forums does not seem to help. Even after pausing the sync, the folders still show a blue circular arrows - still syncing?

Body:
Alternative and potentially faster solution: Use Windows Subsystem for Linux (WSL), change to directory and delete files/folders

rm -r -f mybrokenfolder