text:
Q: can maven assembly plugin replace maven jar plugin I have this pom.xml file bellow that I'm using for a spark scala project:
The plugin I commented is:
<!--            <plugin>-->
<!--                <groupId>org.apache.maven.plugins</groupId>-->
<!--                <artifactId>maven-jar-plugin</artifactId>-->
<!--                <version>3.2.2</version>-->

<!--                <configuration>-->
<!--                    <archive>-->
<!--                        <manifest>-->
<!--                            <mainClass>com.obs.dqsckpi.MySM_SLA_DQ_App</mainClass>-->
<!--                            <addClasspath>true</addClasspath>-->
<!--                        </manifest>-->
<!--                    </archive>-->
<!--                </configuration>-->
<!--            </plugin>-->

The assembly plugin config:
    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>3.1.0</version>
        <configuration>
            <finalName>dqsc-mysm-sla-dq-assembly-${project.version}</finalName>
            <appendAssemblyId>false</appendAssemblyId>
            <descriptors>
                <descriptor>src/assembly/delivery.xml</descriptor>
            </descriptors>
            <attach>false</attach>
            <archive>
                <manifest>
                    <mainClass>com.obs.dqsckpi.MySM_SLA_DQ_App</mainClass>
                    <addClasspath>true</addClasspath>
                    <classpathPrefix>lib/</classpathPrefix>
                </manifest>
            </archive>
        </configuration>
        <executions>
            <execution>
                <phase>package</phase>
                <goals>
                    <goal>single</goal>
                </goals>
            </execution>
        </executions>
    </plugin>

I want to know if I can get ride of jar-plugin because I'm having some errors related to it and also because I'm only using the output of the assembly-plugin to start my jobs.


text:
Q: Problem With the Edges When Clipping Raster The following code clips the TIFF images based on the GeoJson file. However, when clipping the tiles that has half image and half nothing (white area in QGIS), the nothing half changes to black, which is what I want but the half that has the real image turns to white. How can I get the half that has the real image to have the same thing (data) while the half that has nothing to turn to the black color?
import os
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from shapely.geometry import mapping
import geopandas as gpd
import rasterio as rio
from rasterio.plot import plotting_extent
from rasterio.mask import mask
import earthpy as et
import earthpy.spatial as es
import earthpy.plot as ep

shape_file = '/.../abc.geojson'
crop_extent = gpd.read_file(shape_file)

lidar_chm_path = '/.../reprojected.tif'
output = '/.../Data/'
if not os.path.exists(output):
    os.mkdir(output)
i, j = 0, 0
while i < crop_extent.shape[0]:
    with rio.open(lidar_chm_path) as lidar_chm:
        try:
            lidar_chm_crop, lidar_chm_crop_meta = es.crop_image(lidar_chm,[crop_extent.iloc[i]['geometry']])
            lidar_chm_crop_affine = lidar_chm_crop_meta["transform"]
            j += 1
            lidar_chm_crop_meta.update({'transform': lidar_chm_crop_affine,
                       'height': lidar_chm_crop.shape[1],
                       'width': lidar_chm_crop.shape[2],
                       'nodata': -999.99})
            name = output + str(crop_extent.iloc[1][2]) + '_image_' + str(j) + '.tif'
            with rio.open(name, 'w', **lidar_chm_crop_meta) as ff:
                ff.write(lidar_chm_crop[0], 1)
        except:
            None
    i += 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: My HTML has different spacing I'm really confused about this. I have same shortcode but different spacing which causes the second shortcode to fail.
[button link="#"]btn[/button]
[button link="#"]btn[/button]

They look identical but when runing on a compare tool, there's a difference in space before link.
Please see here:
http://www.diff-online.com/view/589710128ca13
How is that possible? Any idea? Thanks.

A: You can check what character it is at What Unicode Characters it is
You would have realized that the first one is:
U+0020 : SPACE [SP]
While second is:
U+00A0 : NO-BREAK SPACE [NBSP]
Just because they look same doesn't necessary mean they are same character.


text:
Q: apt-get upgrade fails, unmet dependencies So I seemed to have messed up my system. My last resort is to reinstall Ubuntu, but I'm hoping I can get some suggestions on how to avoid that.
I'm unable to install applications via apt, upgrade fails, and all steps that I've attempted have pulled up other issues.
So its starts off when I attempt to run sudo apt-get upgrade I get this
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 libc6-dbg : Depends: libc6 (= 2.23-0ubuntu11) but 2.23-0ubuntu10 is installed
 libc6-dev : Depends: libc6 (= 2.23-0ubuntu11) but 2.23-0ubuntu10 is installed
 libc6-i386 : Depends: libc6 (= 2.23-0ubuntu11) but 2.23-0ubuntu10 is installed
 libc6-x32 : Depends: libc6 (= 2.23-0ubuntu11) but 2.23-0ubuntu10 is installed
E: Unmet dependencies. Try using -f.

so using the suggestions I next attempt apt-get -f install and I get this
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following additional packages will be installed:
  libc6 libc6:i386
Suggested packages:
  glibc-doc glibc-doc:i386 locales:i386
The following packages will be upgraded:
  libc6 libc6:i386
2 upgraded, 0 newly installed, 0 to remove and 425 not upgraded.
9 not fully installed or removed.
Need to get 0 B/4,838 kB of archives.
After this operation, 0 B of additional disk space will be used.
Preconfiguring packages ...
(Reading database ... 499265 files and directories currently installed.)
Preparing to unpack .../libc6_2.23-0ubuntu11_amd64.deb ...
De-configuring libc6:i386 (2.23-0ubuntu10) ...

LD_LIBRARY_PATH contains the traditional /lib directory,
but not the multiarch directory /lib/x86_64-linux-gnu.
It is not safe to upgrade the C library in this situation;
please remove the /lib/directory from LD_LIBRARY_PATH and
try again.

dpkg: error processing archive /var/cache/apt/archives/libc6_2.23-0ubuntu11_amd64.deb (--unpack):
 subprocess new pre-installation script returned error exit status 1
Preparing to unpack .../libc6_2.23-0ubuntu11_i386.deb ...
De-configuring libc6:amd64 (2.23-0ubuntu10) ...

LD_LIBRARY_PATH contains the traditional /lib directory,
but not the multiarch directory /lib/i386-linux-gnu.
It is not safe to upgrade the C library in this situation;
please remove the /lib/directory from LD_LIBRARY_PATH and
try again.

dpkg: error processing archive /var/cache/apt/archives/libc6_2.23-0ubuntu11_i386.deb (--unpack):
 subprocess new pre-installation script returned error exit status 1
Processing triggers for libc-bin (2.23-0ubuntu10) ...
Errors were encountered while processing:
 /var/cache/apt/archives/libc6_2.23-0ubuntu11_amd64.deb
 /var/cache/apt/archives/libc6_2.23-0ubuntu11_i386.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

I've found suggestions regarding unset LD_LIBRARY_PATH. i've re-written the LD_LIBRARY_PATH with suggestions from other links. I've removed libc6* and attempted to reinstall and nothing seems to work.
~$ echo $LD_LIBRARY_PATH
/lib:/usr/lib:/usr/local/lib

~$ sudo apt-get check
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 libc6-dbg : Depends: libc6 (= 2.23-0ubuntu11) but 2.23-0ubuntu10 is installed
 libc6-dev : Depends: libc6 (= 2.23-0ubuntu11) but 2.23-0ubuntu10 is installed
 libc6-i386 : Depends: libc6 (= 2.23-0ubuntu11) but 2.23-0ubuntu10 is installed
 libc6-x32 : Depends: libc6 (= 2.23-0ubuntu11) but 2.23-0ubuntu10 is installed
E: Unmet dependencies. Try using -f.

Does anyone have any suggestions, or should I just reinstall Ubuntu?

A: Did you try to use apt-get update if it didn't work then try apt-get check to see if your dependecies aren't harmed


text:
Q: FormData append not working I wrote this to upload an image to my local Apache webserver using input element in HTML. The file is logged as not empty, but why is the form_data completely empty?
$('#upload-image').change(function(e){
    var file = e.target.files[0];
    var imageType = /image.*/;
    if (!file.type.match(imageType))
        return;
    console.log(file);
    var form_data = new FormData();
    form_data.append('file', file);
    console.log(form_data);
    $.ajax({
        url: 'http://localhost/upload.php',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'POST',
        success: function(response){
            console.log(response);
        },
        error: function(error){
            console.log(error);
        }
    });

});

This is my upload.php on local webserver
<?php
    header('Access-Control-Allow-Origin: *');
    if ( 0 < $_FILES['file']['error'] ) {
        echo 'Error: ' . $_FILES['file']['error'] . '<br>';
    }
    else {
        move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
        $target_path = $_SERVER['DOCUMENT_ROOT'] . "/uploads/" . $_FILES['file']['name'];
        echo $target_path;
    }
?>

The console.log(response) logs all the code lines of PHP file, instead of the returned result of echo

A: When logging a formData object with just console.log(formData) it always returns empty, as you can't log formData.
If you just have to log it before sending it, you can use entries() to get the entries in the formData object
$('#upload-image').change(function(e) {
    var file = e.target.files[0];
    var imageType = /image.*/;

    if (!file.type.match(imageType)) return;

    var form_data = new FormData();
    form_data.append('file', file);

    for (var key of form_data.entries()) {
        console.log(key[0] + ', ' + key[1]);
    }

    $.ajax({
        url: 'http://localhost/upload.php',
        cache: false,
        contentType: false,
        processData: false,
        data: form_data,
        type: 'POST',
        success: function(response) {
            console.log(response);
        },
        error: function(error) {
            console.log(error);
        }
    });

});

A: I've noticed myself that the contentType: false will only work on jQuery 1.7.0 and above. So make sure that you're using the right jQuery version.


text:
Q: How to control whether an object is related to a model or not in Django? There are several models that are related to User model:

class User(AbstractUser):
  # Its fields

class Model_1(models.Model)
  user = models.OneToOneField('User', on_delete=models.CASCADE)
  # other fields

class Model_2(models.Model)
  user = models.OneToOneField('User', on_delete=models.CASCADE)
  # other fields

class Model_3(models.Model)
  user = models.OneToOneField('User', on_delete=models.CASCADE)
  # other fields

class Model_4(models.Model)
  user = models.OneToOneField('User', on_delete=models.CASCADE)
  # other fields

and in the view:
def index(request):
    # If the user is related to model one, do something
    # If the user is related to model two, do something
    # If the user is related to model three, do something
    # If the user is related to model four, do something
    # Otherwise return to the home page

After the user sends the request to View, how do I determine which of these models it belongs to?

Thank you in advance.

A: Just check for the existence of your model in the user instance
class Model_4(models.Model)
  user = models.OneToOneField('User',
                              related_name='model_4',
                              on_delete=models.CASCADE)

def index(request):
    if request.user.model_4 is not None:
        pass  # Do something


text:
Q: How is data supposed to be retrieved in ASP NET Core MVC? I am working on an ASP NET Core MVC Project (using entity framework and Identity if that makes a difference in this answer) and I am a bit confused between everything I am reading on different sites. Some say that business logic is supposed to be in the model but then others show a databasecontext.cs being created and the business logic being in there. It makes sense to me to have it in the model but my problem now is that the database is set up in startup.cs services, so right now options are being sent in from services and I can't really create a new connection for every method call.
For reference:
Startup.cs
services.AddDbContext<DatabaseContext>( options =>
{
     options.UseSqlServer(
          Configuration.GetConnectionString("DefaultConnection"),
          b => b.MigrationsAssembly(typeof(DatabaseContext).Assembly.FullName)
     );
});

Model - User.cs
namespace SPPP.Models
{
    public class User : IdentityUser
    {
        [Required(ErrorMessage = "Full Name Required")]
        [MaxLength(80)]
        public string FullName { get; set; }

        [Required(ErrorMessage = "Role Required")]
        [MaxLength(10)]
        public string Role { get; set; }

        [Required(ErrorMessage = "Status Required")]
        [MaxLength(10)]
        public string Status { get; set; }

        public IList<User_Group> User_group { get; set; }

        public User()
        {

        }
    }
}

DatabaseContext.cs
namespace SPPP.Data
{
    public class DatabaseContext : IdentityDbContext
    {

        public DbSet<User> Users { get; set; }
        public DbSet<Group> Groups { get; set; }
        public DbSet<File> Files { get; set; }
        public DbSet<User_Group> User_groups { get; set; }

        public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
        {

        }

        protected override void OnModelCreating(ModelBuilder builder)
        {
            ...
        }
    }
}

Is there a reference anywhere to how I can set it up so that the business logic happens in the Model?

A: You should not be doing business logic in the model when it comes to ASP.NET MVC. Your business logic should be kept within service classes. Although you could structure it in different ways. Here is a common example:
EX:
public class UserService : IUserService
{
    private readonly DatabaseContext _context;

    pubic UserService(DatabaseContext context)
    {
        _context = context;
    }

    public async Task<User> GetUsersAsync()
    {
        // Do some business logic here

        // Get data from DB like this:
        var users = await _context.Users.ToListAsync();

    }
}

Your controller would then inject the IUserService within the constructor. You can then call any method from your service class within your controllers.
Don't forget to register your service in the startup.cs ConfigureServices() method.
You could also separate the logic to get data within a separate class like a DataAccess layer if you dont want to mix business logic with getting data from the dbcontext in the same place. Some people like to use a repository pattern as well which is ok but there is no need since EF by default already implements a repository pattern internally.


text:
Q: An ice cream parlor has 28 different ice cream flavors. How many different ways are there to choose 6 scoops of ice cream if at least An ice cream parlor has $28$ different ice cream flavors. How many
different ways are there to choose $6$ scoops of ice cream if at least $2$ scoops
must be chocolate?
My attempt
I used the formula $\binom {n+r-1}{r}$ and here $n=28, r=6$
$\binom {33}{6}-\binom{28}{1}$
Can anyone please explain me this

A: Since there must be atleast 2 scoops of chocolate lets take two scoops of chocolate. Now we need to pick 4 flavors from 28. Number of ways of choosing this are are you have correctly pointed out $\binom{n+r-1}{r}$ with $n=28, r=4$, that is $\binom{31}{4}$.

A: First take $2$ scoops of chocolate. Now for the remaining $4$ scoops we have to count the number of $\geq0$ solutions of the system
$$x_1+x_2+\ldots+x_{27}+x_{28}=4\ .$$
For this count we need $4$ circles $\bigcirc$ for the scoops and $27$ separating  bars $|\>$. The result is ${31\choose4}=31\,465$.

A: No of ways of selecting scoops such that atleast 2 scoops must be chocolate
= total no of ways(S) - containing no chocolate(A) - containing exactly 1 chocolate(B)
There are 2 different answers depending on whether the arranging  order from bottom to top  matter  or not
1)  Order matters
S = $28^6$ since for every scoop you have 28 options
A = $27^6$ since we are excluding chocolate
B = There is exactly one chocolate which can be arranged in 6 places the rest of the places can be filled by $26^5$ ways = $6*26^5$
Answer = $S - A - B  =  28^6 - 27^6 - (6*26^5)$
2) Order doesn't matter i.e. we are only interested in different number of combinations(example ABBB,BABB,BBAB,BBBA counts as 1 case instead of 4)
The simpler way to solve this using stars and bars method
$X_1+X_2+X_3+.......X_{28} = 6$ where $X_i$ represents the flavour of icecream
Non negative solution of above equation is given by $\binom{28+6-1}{6-1}$ =$\binom{33}{5}$
S = $\binom{33}{5}$
A = containing no chocolate = $X_1+X_2+X_3+.......X_{27} = 6$ == $\binom{27+6-1}{6-1}$ =$\binom{32}{5}$
B =  containing exactly one chocolate =
$X_1+X_2+X_3+.......X_{27} + 1 = 6$ ($X_{28} = 1$)
=$X_1+X_2+X_3+.......X_{27} = 5$
Solutions =  $\binom{27+5-1}{5-1}$ =$\binom{31}{4}$
Answer = $S-A-B$ = $\binom{33}{5}$ - $\binom{32}{5}$ - $\binom{31}{4}$ = 4495
Alternative way:
atleast 2 chocolate
$X_1+X_2+X_3+.......X_{28} = 6$
let $X_{28}$ be chocolate such that $X_{28}$ >=2
Let $X_{28}$ = $Y_{28}$ +2
$X_1+X_2+X_3+.......X_{27} +Y_{28} + 2 = 6$
=$X_1+X_2+X_3+.......X_{27} +Y_{28} = 4$
Solution of above equation = $\binom{28+4-1}{4-1}$ =$\binom{31}{3}$ = 4495


text:
Q: Parameterized v-for directive I'm using v-for to produce a set of vuetify v-timeline-item with elements being customized based on values stored in a customization object:
<v-timeline-item
   v-for="target in targetsList"
     :key="target.uid"
     :color="typesConfig[target.format].color"
     :icon="target.icon"
     large
     fill-dot
>

I would like to pick a color from the typesConfig object based on the value of target.format.
typesConfig is a computed property that looks like this:
const typesConfig = {
    doc: {
       color: 'red lighten-2',
       icon: 'mdi-star',
    }, etc...

I'm having trouble figuring out how to grab the color value from the object and assign it to :color. I have tried all sorts of things including string literals with no luck :(
I hope the above is clear and your help would be appreciated.
thank you.

A: You said typesConfig is a computed property that looks like this: ... but that's not what a computed property looks like.
It looks like you have defined a constant outside of the Vue object.
I mocked up your component with typesConfig as a data property and the template you have works perfectly.
You would only need a computed property if you were computing from something else, say targetsList, but you intend to remove color and icon from those objects.
So, it's likely you just need a data property that is initialized from your const, something like
const typesConfig = {
  doc: {
    color: 'red lighten-2',
    icon: 'mdi-star',
  },
}

export default {
  data: () => ({
    targetsList: [
      { uid: 'ABC', subject: 'S1', format: 'doc', notes: "some notes", date: 'Feb 10, 2020' },
      { uid: 'def', subject: 'S1', format: 'doc', notes: "some notes", date: 'Feb 10, 2020' },
      { uid: 'ghi', subject: 'S1', format: 'doc', notes: "some notes", date: 'Feb 10, 2020' }
    ],
    typesConfig: typesConfig
  })
};


text:
Q: Deployment slot not working in ASE in azure When we try to deploy web app to a deployment slot in app service plan(created inside app service environment) it removes the existing code in both production and staging slot and then it deploys the code in staging slot. Because of this our old code is not available in staging slot when we swap. Are we not supposed to use slot in ASE ? If yes, how can we fix this issue ?

A: We faced the same issue which was resolved after changing the task version of Azure App Service deploy task in the release pipeline. Earlier we were using the task version 4 which has option 'Deploy to slot or  ASE' which seems to cause the issue. When you select task version 3, you will get the option 'Deploy to slot' after which the release works fine and the code is not deleted  from staging or prod slot.

A: Deployment slots are pretty standard and easy to use.
It sounds like your deployment process is broken and is not properly deploying in the correct sequence which is causing this issue.
I would suggest investigating your deployment process and taking it step by step and validating each step manually.
Edit:
The documentation you linked below is somewhat confusing to me however this looks to be the configuration you should try:
DeployToSlotOrASEFlag = TRUE
(We want to deploy to an ASE, so we must set TRUE)
SlotName = staging
(Required, if DeployToSlotOrASEFlag = true)
Default value: production


text:
Q: Fast inversion of a triangular matrix I need to inverse a matrix $A$ given its $QR$ decomposition. It's a numerical task.
It is told that the inversion should be "possibly cheap". But it does not look like I can do something more efficient than computing $R^{-1}$ and multiplying (if one needs a matrix, not a product of two matrices) it by $Q^{T}$. However, even if a product is OK (no multiplication needed), I'm still ineffective, because I don't know how to inverse a triangular matrix faster than in cubic time.
Are there any tricky algorithms doing that (I'm not asking about something like fast matrix multiplication, it's a stupid homework) or the task only sounds wise but all I have to do is to invert a triangular matrix as it is taught in linear algebra course or using back substitution?
EDIT: I emphasise that the task is to invert a matrix, not to find a solution of a linear system.

A: Any $N \times N$ triangular system can be solved in $\mathcal{O}(N^2)$.
For instance, if it is an upper triangular system, start from the last equation $(N^{th}$  equation) which requires only one division to get the $N^{th}$ unknown. Once you have this go to the previous equation $((N-1)^{th}$  equation) which requires only one multiplication, one subtraction and one division to get the $(N-1)^{th}$ unknown. Go to the $(N-2)^{nd}$ equation which requires $2$ multiplications, $2$ subtractions and $1$ division. In general, the $(N-k)^{th}$ equation requires $k$ multiplications, $k$ subtractions and $1$ division. Hence, the total cost is $$1+2+3+\cdots+(N-1) = \frac{N(N-1)}{2} \text{ multiplications}$$ $$1+2+3+\cdots+(N-1) = \frac{N(N-1)}{2} \text{ subtractions}$$ $$N \text{ divisions}$$
The same idea works for lower triangular systems as well (in which case you start from the first equation and proceed all the way down).
In fact, the idea behind all matrix decomposition algorithms is to make the solving part cheaper so that given  a linear system even if the right hand side were to change you can solve it in a relatively inexpensive way once you have the decomposition of the matrix. The two main decomposition algorithms which are used satisfy this requirement.

*

*$A=LU$. Factoring $A$ into a lower triangular times an upper triangular. The factorization cost is $\mathcal{O}(N^3)$. But once this is done solving $Ax = b$ requires solving $Ly = b$ and $UX = y$ both costing $\mathcal{O}(N^2)$ since both are triangular systems.

*$A = QR$. Factoring $A$ into an orthonormal matrix times an upper triangular matrix. The factorization cost is $\mathcal{O}(N^3)$. But once this is done solving $Ax = b$ requires solving $Qy = b$ and $RX = y$. The nice thing about orthonormal matrices is that the inverse is nothing but the transpose. Hence, $y=Q^Tb$ which is nothing but a matrix vector product which costs $\mathcal{O}(N^2)$. Solving $Rx = y$ costs $\mathcal{O}(N^2)$ since it is a triangular system.

Other decomposition algorithms like the SVD where $A = U \Sigma V^T$ where $U$ and $V$ are orthonormal and $\Sigma$ is a diagonal also satisfy the requirement. Once we have $A = U \Sigma V^T$, solving $Ax = b$ is equivalent to solving $Uy = b$, whose solution is given by $y = U^Tb$ and costs $\mathcal{O}(N^2)$, $\Sigma z = y$, which can be easily inverted since $\Sigma$ is just a diagonal matrix and hence costs $\mathcal{O}(N)$, and $V^Tx = z$, whose solution is given by $x = Vz$ and costs $\mathcal{O}(N^2)$.
EDIT
In case you want the inverse of the lower triangular operator, you proceed as follows. (In numerical linear algebra it is one of the cardinal sins to find the inverse explicitly. In any application you will never need to find the inverse explicitly.) $$L = \begin{pmatrix}1 & 0 & 0 & 0 & \cdots & 0 \\ l_{21} & 1 & 0 & 0 & \cdots & 0 \\  l_{31} & l_{32} & 1 & 0 & \cdots & 0 \\  l_{41} & l_{42} & l_{43} & 1 & \cdots & 0 \\  \vdots & \vdots & \vdots & \vdots & \ddots & \vdots \\  l_{n1} & l_{n2} & l_{n3} & l_{n4} & \cdots & l_{nn} \\ \end{pmatrix}$$
We can write $L$ as $$L = L_1 L_2 L_3 \cdots L_{n-1}$$ where $$L_k = \begin{pmatrix}1 & 0 & 0 & 0 & \cdots & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & \cdots & 0 & 0 & 0 & 0 \\ \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots\\ 0 & 0 & \cdots & 1 & \vdots & \vdots & \vdots & \vdots & \vdots \\  0 & 0 & \cdots & l_{k+1,k} & 1 & \vdots & \vdots & \vdots & \vdots  \\  0 & 0 & \cdots & l_{k+2,k} & 0 & \ddots & \vdots & \vdots & \vdots \\ 0 & 0 & \cdots & l_{k+3,k} & 0 & \cdots & \ddots  & \vdots & \vdots  \\ 0 & 0 & \cdots & \vdots & 0 & \cdots & \cdots & \ddots  & \vdots\\ 0 & 0 & \cdots & l_{n,k} & 0 & \cdots & \cdots & \cdots & 1 \end{pmatrix}$$
Then
$$L^{-1} = L_{n-1}^{-1}L_{n-2}^{-1}L_{n-3}^{-1} \cdots L_{1}^{-1}$$
where
$$L_k^{-1} = \begin{pmatrix}1 & 0 & 0 & 0 & \cdots & 0 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 & \cdots & 0 & 0 & 0 & 0 \\ \vdots & \vdots & \ddots & \vdots & \vdots & \vdots & \vdots & \vdots & \vdots\\ 0 & 0 & \cdots & 1 & \vdots & \vdots & \vdots & \vdots & \vdots \\  0 & 0 & \cdots & -l_{k+1,k} & 1 & \vdots & \vdots & \vdots & \vdots  \\  0 & 0 & \cdots & -l_{k+2,k} & 0 & \ddots & \vdots & \vdots & \vdots \\ 0 & 0 & \cdots & -l_{k+3,k} & 0 & \cdots & \ddots  & \vdots & \vdots  \\ 0 & 0 & \cdots & \vdots & 0 & \cdots & \cdots & \ddots  & \vdots\\ 0 & 0 & \cdots & -l_{n,k} & 0 & \cdots & \cdots & \cdots & 1 \end{pmatrix}$$

A: I agree with Sivaram's assessment that an actual matrix inversion is almost never needed (except in some applications, like forming the variance-covariance matrix in statistics). That being said, there is an $O(n^3)$ method to invert a triangular matrix in place (but note that it takes less effort than the inversion of a general matrix). Pete Stewart shows the lower-triangular version in his book (the version given there is for lower triangular matrices; I hope the needed modifications for the upper triangular version are transparent to you), and there is a FORTRAN implementation in LAPACK.
As a final note, since you said that this is part of a QR decomposition: if you used Householder matrices for generating the orthogonal factor, you should know that it is usually much better to keep the components of the Householder vectors around than the multiplied-out orthogonal matrix. (The usual storage format for QR decompositions is to use the upper triangle of the original for storing the triangular factor, and the lower triangle (and also possibly an auxiliary array) for the Householder vectors that form the orthogonal factor.) See Golub and Van Loan, for instance.


text:
Q: (Angular upgrade) reference upgraded service function as callback without needing to bind context I am in the process of upgrading an AngularJS app to Angular and I have come across as small problem when upgrading a Service.
There is an error service which is used throughout the AngularJS app like below:
.subscribe(
    onNextFunction,
    ErrorService.onExecutionError,
    onCompleteFunction
);

What the function does in the service isn't important, but once the function is executed the context is incorrect. So in the upgraded service if the function tries to call another function in the service like below, then an error is thrown that isCertainTypeOfError is not defined:
onExecutionError(err) {
    if (this.isCertainTypeOfError(err)) {
        ...
    }
}

The context is not correct, so the two solutions I can see is to either change every call to this function to be like this:
err => ErrorService.onExecutionError(err),

Or like this:
ErrorService.onExecutionError.bind(ErrorService),

I would like to avoid these two options, as this Service is used a lot throughout the angularjs part of the app in the same way so it would involve me changing a lot of files.
My question is, do I have any other options where I can avoid making so many changes? Is there something I can change in the upgraded service?


text:
Q: MVC - How to ModelBind a list an objects with this unusual post data format? Normally when you ModelBind a list of objects with MVC, the action looks like so:
    public ActionResult Hello(List<DocumentViewModel> viewModels)
    {

And the Post data looks something like:
[0].Id 1
[0].Name Bob
[1].Id 2
[1].Name Jane

But, how could I get the following post data to work?
0[Id] 1
0[Name] Bob
1[Id] 2
1[Name] Jane

The Post data is being provided by Kendo UI, so I don't imagine I have much flexibility to change it.
Update Thanks Petur for the answer. To expand on his answer, this function:
common.MvcSerializeArray = function (array, prefix) {
    var result = {};

    if (!prefix) {
        prefix = '';
    }

    if (array) {
        for (var i = 0; i < array.length; i++) {
            if ($.isPlainObject(array[i])) {
                for (var property in array[i]) {
                    result[prefix + "[" + i + "]." + property] = array[i][property];
                }
            } else {
                result[prefix + "[" + i + "]"] = array[i];
            }
        }
    }

    return result;
};

should wrap arrays before being returned to Kendo's Data method:
    .DataSource(dataSource => dataSource
        .Ajax()
        .Read(read => read
            .Action("PickerDocuments", "DocumentRepository")
            .Data(@<text>function(e) { return MyApp.Common.MvcSerializeArray(@Html.Raw(Json.Encode(Model))); }</text>)))

And voila, I get post data MVC ModelBinds with ease:
[0].Id 1
[0].Name Bob
[1].Id 2
[1].Name Jane

A: You cannot change it but you can add the desired format by sending addiotional parameters like explained here for the Ajax Grid. Same approach is used in this code library (you can get the magic function inside of the code, it is used to send the multi-select values)


text:
Q: Getting Error While starting lite-server i did a fresh "npm init".
put entry point : "index.html"
then installed lite-server : npm install lite-server --save-dev
also updated the package.json
    {
  "name": "newjs",
  "version": "1.0.0",
  "description": "nothing",
  "main": "index.html",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start" : "npm run lite",
    "lite" : "lite-server"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "lite-server": "^2.3.0"
  }
}

But when I did "npm start" , getting this error
D:\mudit\newjs>npm start

newjs@1.0.0 start D:\mudit\newjs
  npm run lite

> newjs@1.0.0 lite D:\mudit\newjs
> lite-server

Did not detect a `bs-config.json` or `bs-config.js` override file. Using lite-server defaults...
** browser-sync config **
{ injectChanges: false,
  files: [ './**/*.{html,htm,css,js}' ],
  watchOptions: { ignored: 'node_modules' },
  server: { baseDir: './', middleware: [ [Function], [Function] ] } }
D:\mudit\newjs\node_modules\lite-server\node_modules\browser-sync\node_modules\socket.io\node_modules\engine.io\node_modules\ws\index.js:9
const WebSocket = require('./lib/WebSocket');
^^^^^
SyntaxError: Use of const in strict mode.
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Server.init (D:\mudit\newjs\node_modules\lite-server\node_modules\browser-sync\node_modules\socket.io\node_modules\engine.io\lib\server.js:115:16)
    at new Server (D:\mudit\newjs\node_modules\lite-server\node_modules\browser-sync\node_modules\socket.io\node_modules\engine.io\lib\server.js:65:8)
    at Function.attach (D:\mudit\newjs\node_modules\lite-server\node_modules\browser-sync\node_modules\socket.io\node_modules\engine.io\lib\engine.io.js:123:16)

npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "run" "lite"
npm ERR! node v0.12.7
npm ERR! npm  v2.11.3
npm ERR! code ELIFECYCLE
npm ERR! newjs@1.0.0 lite: `lite-server`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the newjs@1.0.0 lite script 'lite-server'.
npm ERR! This is most likely a problem with the newjs package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     lite-server
npm ERR! You can get their info via:
npm ERR!     npm owner ls newjs
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     D:\mudit\newjs\npm-debug.log

npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "start"
npm ERR! node v0.12.7
npm ERR! npm  v2.11.3
npm ERR! code ELIFECYCLE
npm ERR! newjs@1.0.0 start: `npm run lite`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the newjs@1.0.0 start script 'npm run lite'.
npm ERR! This is most likely a problem with the newjs package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     npm run lite
npm ERR! You can get their info via:
npm ERR!     npm owner ls newjs
npm ERR! There is likely additional logging output above.

npm ERR! Please include the following file with any support request:
npm ERR!     D:\mudit\newjs\npm-debug.log

Please Help as I am not even able to get the lite-server running.
thanks in advance.


text:
Q: How to reverse improper .less class, which uses the ":not"-selector I'm stuggeling with a .less problem, where a rule is applied to nearly all elements of my web application using the :not-sector. A collegue applied the following rule:
:not(.expanded) {
  animation: fadeIn 1s;
}

As you might notice: All elements, which do not have the .expanded-Class will be animated. Originally the rule should have been applied for a special .css-Class and it's subclasses and of course not to all elements using this very unspecific rule.
Nevertheless: A new release will take some time, so I can not wait for the next release.
Now I'm trying to reverse the less rule, which could be easy using the following:
:not(.expanded) {
    animation: none !important;
}

This works flawlessly - too flawlessly. No animation is performed as all animations are set to "none". Of course this is not my goal, since other elements should be animated.
Is there any clever way to fix my problem?
I'm open for every option using .css, less or JavaScript (including the Dojo-Framework).


text:
Q: Jenkins pipeline to build multiple projects in sequence? I am a novice when it comes to Jenkins. I would like to be able to take different projects and build them in sequence with each other with a Pipeline. I have noticed that Jenkins can run various stages in sequence or in parallel via a Pipeline. Is there a way for this to happen with running projects in sequence or in parallel that exists on the same node?

A: I know this question is a bit old. But in case there's someone out there that might be searching for an answer, follow these steps (Remember the names of the Jobs as you need to type them)

*

*Create a "Multijob Project"

*In the "Build" section, type the Name of your first Job.

*Again In the "Build" section, "Add build step" type the next Job name.

In both builds, "Block until the triggered projects finish" should be ticked.
Save & Build your Multijob Project.

A: Yes, you can use build step to trigger any project (job) you want in Jenkins. See https://jenkins.io/doc/pipeline/steps/pipeline-build-step/


text:
Q: display table not working in IE7 i have this div perfectly positioned in IE8 and Mozilla Firefox

but falling down in IE7. I have heard display table doesn't work in IE7 but the whole div is going haywire in IE7.

A: As you already said yourself what you are doing is unsupported in IE7
Here is the w3Schools Document
You will need to use conditional comments and handle it differently for IE7 or rethink your design

A: Display table is not natively supported in IE7.
You could use an htc like this one here to realize it.


text:
Q: Libreoffice converting word to pdf issue I am facing issue when converting microsoft word to PDF.
When I am converting word file to PDF with the help of libreoffice from command line command, there issue with the content in converted PDF file.
The background of the page in word resized and position of ellipse is changed.
Please find attached sample screen shot of word file(word.png) which I am trying to convert into PDF and PDF(pdf.png) in which I am facing issue.
Command which I am using,

libreoffice --headless --convert-to html WORDFILE.docx


text:
Q: Problem with observer class not found Preconditions
Magento 2.1.9
Php 7.0
Steps to reproduce
Like your documentation i have created a module for redirect user.
http://devdocs.magento.com/guides/v2.0/extension-dev-guide/events-and-observers.html
Détail about my config file is avaible here : https://github.com/magento/magento2/issues/11629
When i go to the frontend, it's show an error about the observer class does not exist :(
Expected result
No error
Actual result
1 exception(s):

Exception #0 (ReflectionException): Class Athena\RedirectToLanguage\Observer\AthenaObserverRedirect does not exist

Exception #0 (ReflectionException): Class Athena\RedirectToLanguage\Observer\AthenaObserverRedirect does not exist

0 /var/www/html/athenacomputing/vendor/magento/framework/Code/Reader/ClassReader.php(19): ReflectionClass->__construct('Athena\Redirect...')

1 /var/www/html/athenacomputing/vendor/magento/framework/ObjectManager/Definition/Runtime.php(44): Magento\Framework\Code\Reader\ClassReader->getConstructor('Athena\Redirect...')

2 /var/www/html/athenacomputing/vendor/magento/framework/ObjectManager/Factory/Dynamic/Developer.php(71): Magento\Framework\ObjectManager\Definition\Runtime->getParameters('Athena\Redirect...')

3 /var/www/html/athenacomputing/vendor/magento/framework/ObjectManager/ObjectManager.php(71): Magento\Framework\ObjectManager\Factory\Dynamic\Developer->create('Athena\Redirect...')

4 /var/www/html/athenacomputing/vendor/magento/framework/Event/ObserverFactory.php(33): Magento\Framework\ObjectManager\ObjectManager->get('Athena\Redirect...')

5 /var/www/html/athenacomputing/vendor/magento/framework/Event/Invoker/InvokerDefault.php(59): Magento\Framework\Event\ObserverFactory->get('Athena\Redirect...')

6 /var/www/html/athenacomputing/vendor/magento/framework/Event/Manager.php(66): Magento\Framework\Event\Invoker\InvokerDefault->dispatch(Array, Object(Magento\Framework\Event\Observer))

7 /var/www/html/athenacomputing/var/generation/Magento/Framework/Event/Manager/Proxy.php(95): Magento\Framework\Event\Manager->dispatch('controller_acti...', Array)

8 /var/www/html/athenacomputing/vendor/magento/framework/App/Action/Action.php(91): Magento\Framework\Event\Manager\Proxy->dispatch('controller_acti...', Array)

9 /var/www/html/athenacomputing/vendor/magento/framework/Interception/Interceptor.php(74): Magento\Framework\App\Action\Action->dispatch(Object(Magento\Framework\App\Request\Http))


text:
Q: How to only allow scrolling in SingleChildScrollView with two fingers with dart I have a drawing app with a PaintingBoard. Is there a way to disable scrolling when interacting with the PaintingBoard. And only allow the page to scroll when the user uses two fingers to scroll?
I've set the available space to draw 5 x the hight of the screen. I want to user to paint normally, and when they want more space they can scroll down with two fingers
import 'package:flutter/material.dart';
import 'package:flutter_painting_tools/flutter_painting_tools.dart';

class WhiteBoardScreen extends StatefulWidget {
  const WhiteBoardScreen({Key? key}) : super(key: key);

  @override
  State<WhiteBoardScreen> createState() => _WhiteBoardScreenState();
}

class _WhiteBoardScreenState extends State<WhiteBoardScreen> {
  final GlobalKey _paintingBoardKey = GlobalKey();
  final PaintingBoardController _controller = PaintingBoardController();
  bool _lightMode = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        physics: const ClampingScrollPhysics(),
        child: PaintingBoard(
          key: _paintingBoardKey,
          boardBackgroundColor: _lightMode ? Colors.white : Colors.black54,
          boardHeight: MediaQuery.of(context).size.height * 5,
          controller: _controller,
        ),
      ),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
}


text:
Q: Django - can not send email to multiple recipients I'm trying to send mail to multiple recipients but I keep getting this error validation:

I'm using django-multi-email-field package and not certain this solution would help.
Please, see where I went wrong and guide me the right way.
Really appreciate your help!
Django: 1.10 and Python: 3.6

mail.py
from multi_email_field.forms import MultiEmailField

class mailHandler(forms.Form):
   subject = forms.CharField(required=False)
   receiver = MultiEmailField(label='Send to')
   message = forms.CharField(widget=forms.Textarea(attrs={'cols': 50}),
                          required=False)

   def __init__(self, *args, **kwargs):
       super(mailHandler, self).__init__(*args, **kwargs)
       self.helper = FormHelper()
       self.helper.form_method = 'post'
       self.helper.form_class = 'form'
       self.helper.layout = Layout(
           Field(
               None,
               Div(
                   HTML('''
                          {% if messages %}
                          {% for message in messages %}

{{ message }}
                          <button type="button" name="message" class="close" data-dismiss="alert" aria-hidden="true">×</button>

                          {% endfor %}{% endif %}
                           '''),
                   Div('subject',
                       Field('receiver', placeholder='Email address',
                             required=True),
                       'message',
                       FormActions(
                           Submit('submit', 'Send', css_class='btn btn-lg btn-block'),
                       ),
                       ),
               ),
           ),
       )

views.py
class mailPost(FormView):
   success_url = '.'
   form_class = mailHandler
   template_name = 'post/post.html'

   def form_valid(self, form):
       messages.add_message(self.request, messages.SUCCESS, 'Email Sent!')
       return super(mailPost, self).form_valid(form)

   def form_invalid(self, form):
       messages.add_message(self.request, messages.WARNING,
                         'Email not sent. Please try again.')
       return super(mailPost, self).form_invalid(form)

   def post(self, request, *args, **kwargs):
       form_class = self.get_form_class()
       form = self.get_form(form_class)

       if form.is_valid():
           sender = "noreply@domain.com"
           receiver = form.cleaned_data.get('receiver')
           subject = form.cleaned_data.get('subject')
           message = form.cleaned_data.get('message')
           time = datetime.now()
           asoc_pk = Association.objects.filter(asoc_name=self.request.user.association)
           asoc = Association.objects.get(id=asoc_pk)

           Email.objects.create(
               sender=sender,
               receiver=receiver,
               subject=subject,
               message=message,
               association=asoc,
               sentTime=time
           )

           msg = EmailMultiAlternatives(subject, message, sender, [receiver])
           msg.send()

           return self.form_valid(form)
       else:
           return self.form_invalid(form)

models.py
class Email(models.Model):
   sender = models.CharField(max_length=254)
   sentTime = models.DateTimeField(auto_now_add=True, blank=False)
   subject = models.CharField(max_length=254)
   receiver = models.CharField(max_length=254)
   message = models.TextField()
   association = models.ForeignKey(Association)

   class Meta:
       db_table = 'Email'


text:
Q: What does  mean in Collection? What meaning has <E> on the code Collection<E>?

A: It means that you're dealing with a collection of items with type E. Imagine you've got a cup of tea. Instead of tea, it could also hold coffee so it makes sense to describe the cup as a generic entity:
class Cup<T> { … }

now you could fill it, either with coffee or tea (or something else):
Cup<Tea> cuppa = new Cup<Tea>();
Cup<Coffee> foamee = new Cup<Coffee>();

In order for this to work, both Tea and Coffee would need to be types defined in your program as well.
This is a compile-time constraint on your code. Coming back from the (rather useless) cup example, collections (arrays, lists …) usually contain items of one type, e.g. integers or strings. Generics help you to express this in Java:
Collection<String> strList = new ArrayList<String>();
strList.add("Foobar"); // Works.
strList.add(42);       // Compile error!

Notice the compile error above? You only get this when using generics. The following code also works, but would not give the nice error message:
Collection strList = new ArrayList();
strList.add("Foobar"); // Works.
strList.add(42);       // Works now. Do we really want this?!

A: It's the use of generics. Check this intro out. And then don't forget to read this tutorial.
An excerpt follows (which compares the use of a cast versus the use of generics):

When you see the code <Type>, read it
  as "of Type"; the declaration above
  reads as "Collection of String c." The
  code using generics is clearer and
  safer. We have eliminated an unsafe
  cast and a number of extra
  parentheses. More importantly, we have
  moved part of the specification of the
  method from a comment to its
  signature, so the compiler can verify
  at compile time that the type
  constraints are not violated at run
  time. Because the program compiles
  without warnings, we can state with
  certainty that it will not throw a
  ClassCastException at run time. The
  net effect of using generics,
  especially in large programs, is
  improved readability and robustness.

For example, the interface of a List is
public interface List<E> {
    void add(E x);
    Iterator<E> iterator();
}

This means you can build a list whose contents are all of the same explicit type (not only of type Object), even if you have defined the type yourself. So, if you create a Name class you can write
List<Name> nameList = new ArrayList<>();

and then fill it with Name instances and directly retrieve Name instances from it without having to cast or otherwise worry about it because you'll always get either a Name instance or null back, never an instance of a different type.
More importantly, you cannot insert anything different from a Name instance in such a List, because it will fail at compile time.
nameList.add(false); //Fails!
nameList.add(new Name("John","Smith")); //Succeeds supposing Name has a
                                        //firstName, lastName constructor


text:
Q: Hide overflow of pseudo-elements I've made a fancy checkbox, which uses pseudo-elements to look nice, but unfortunately the overflow: hidden doesn't work well in its case. I don't know why.
Here's my code:

.wrapper {
  background: black;
}

.priority {
    display: none;

}
.priority, .priority:after, .priority:before, .priority *, .priority *:after, .priority *:before, .priority + .priority-btn {
    box-sizing: border-box;
}

.priority + .priority-btn {
    overflow: hidden;
    backface-visibility: hidden;
    transition: all 0.2s ease;
    background: #666;
    width: 100%;
    border-radius: 0.25rem;
    padding: .375rem .75rem;
    height: 2.375em;
}

.priority + .priority-btn::after, .priority + .priority-btn::before {
    display: inline-block;
    transition: all 0.2s ease;
    width: 100%;
    text-align: center;
    position: absolute;
    font-weight: bold;
    color: #fff;
}

.priority + .priority-btn::after {
    left: 100%;
    content: 'IMPORTANT';
}

.priority + .priority-btn::before {
    left: 0;
    content: 'UNIMPORTANT';
}

.priority + .priority-btn:active {
    background: #888;
}

.priority + .priority-btn:active::before {
    left: -10%;
}

.priority:checked + .priority-btn {
    background: #86d993;
}
.priority:checked + .priority-btn:before {
    left: -100%;
}
.priority:checked + .priority-btn:after {
    left: 0;
}
.priority:checked + .priority-btn:active:after {
    left: 10%;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>

        <input type="checkbox" ngModel name="priority" id="priority" class="priority">

As you can see the text comes out from the container label.

A: Give position: relative to the .priority-btn since its pseudo-elements have position: absolute:

.wrapper {
  background: black;
}

.priority {
    display: none;

}
.priority, .priority:after, .priority:before, .priority *, .priority *:after, .priority *:before, .priority + .priority-btn {
    box-sizing: border-box;
}

.priority + .priority-btn {
    overflow: hidden;
    backface-visibility: hidden;
    transition: all 0.2s ease;
    background: #666;
    width: 100%;
    border-radius: 0.25rem;
    padding: .375rem .75rem;
    height: 2.375em;
    position: relative;
}

.priority + .priority-btn::after, .priority + .priority-btn::before {
    display: inline-block;
    transition: all 0.2s ease;
    width: 100%;
    text-align: center;
    position: absolute;
    font-weight: bold;
    color: #fff;
    z-index: 11;
}

.priority + .priority-btn::after {
    left: 100%;
    content: 'IMPORTANT';
}

.priority + .priority-btn::before {
    left: 0;
    content: 'UNIMPORTANT';
}

.priority + .priority-btn:active {
    background: #888;
}

.priority + .priority-btn:active::before {
    left: -10%;
}

.priority:checked + .priority-btn {
    background: #86d993;
}
.priority:checked + .priority-btn:before {
    left: -100%;
}
.priority:checked + .priority-btn:after {
    left: 0;
}
.priority:checked + .priority-btn:active:after {
    left: 10%;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet"/>

        <input type="checkbox" ngModel name="priority" id="priority" class="priority">

A: Add overflow:hidden to your .col class
.col{
      overflow: hidden;

}


text:
Q: java function that changes negative number to 0 Is there a built-in function in java that would convert any negative number to a 0? what i'm wanting to do is subtract number from a variable, and ensure that it doesn't go below 0. is this possible with built-in functions or would i have to write my own?

A: You should use :
 Math.max(0, yourVar)

You don't need a built-in function for that.

A: You do not need any function to turn a negative into a zero. You can use a conditional declaration of the variable and turned the negative value into a zero.
In a conditional declaration, what goes before the question mark is the condition. If the condition evaluates to true, the first value after the question mark would be assigned to the variable.
If the condition evaluates to false, the value that goes after the column will be assigned to the variable. In the case below, a would be assigned the value of itself if it does not carry a value that is below zero.
int a = -1;
a = a < 0? 0 : a;


text:
Q: Translate unicode code points to specific strings in irssi Is there a command/setting/script to translate certain unicode code points to a different string in irssi? To be concrete, I would like to translate the emoji code points to ASCII smileys, as my font doesn't support them. This is mainly useful with the facebook messenger plugin. I've tried creating a perl script for this, but the documentation is somewhat sparse.

A: So, the problem was with my irssi being somewhat outdated, the bug has been fixed, and it is actually pretty simple to accomplish. For anyone wanting to do the same, you need something along these lines:
my %hash = (
    0x1f600 => ':)',
    # add smileys to taste here
);

sub transform ($$$$$$) {
    my ($server, $msg, $nick, $address, $target) = @_;
    my $transformed = '';

    $msg = decode('utf8', $msg);

    for (my $l = length($msg), my $i = 0; $i < $l; $i++) {
        my $chr = substr($msg, $i, 1);
        my $code = ord($chr);

        if (defined $hash{$code}) {
            $transformed .= $hash{$code};
        }
        else {
            $transformed .= $chr;
        }
    }
    Irssi::signal_continue($server, $transformed, $nick, $address, $target);
}

Irssi::signal_add_last('message public', 'transform');
Irssi::signal_add_last('message private', 'transform');

Note that I'm definitely not a Perl-expert, so there might be smarter/better ways to achieve this!


text:
Q: Can I recover a file deleted by Ant?
Possible Duplicate:
I need a program for recovering deleted files in Windows

Is there a way to recover files deleted by Ant?
I ran a script that deleted a file. However, it is not inside the recycle bin.

A: Yes.  Using software like  Restoration, Recover My Files or any of the programs reviewed by PC World.


text:
Q: Getting some odd javascript errors on a VF page I have a fairly simple Visual Force page: a bunch of inputFields, inputText, etc...  A couple of RemoteAction calls - and it works well - no complaints.
However, when I load the page, in Chrome's console, I get a bunch of errors that seemed to do with js being served by Salesforce.  Is there something I am missing here?

A: The first error is a red herring. It won't prevent the request from sending. The second error says that you're missing a session ID. That happens from time to time with the AJAX Toolkit. The usual fix is to add this line of code after it has been included:
<script>
sforce.connection.sessionId = '{!$Api.Session_ID}';
</script>

This should fix your error.


text:
Q: MVC3 Razor @Html.DropDownListFor I could use some help implementing @Html.DropDownListFor. My objective is to filter the list of Products by Category.
This code will display a list box:
@model IEnumerable<Sample.Models.Product>
@{
    List<Sample.Models.Category> list = ViewBag.Categories;
    var items = new SelectList(list, "CategoryID", "CategoryName");

}
@Html.DropDownList("CategoryID", items)

But I'm having trouble getting @Html.DropDownListFor to work:
@model IEnumerable<Sample.Models.Product>
@{
    List<Sample.Models.Category> list = ViewBag.Categories;
    var items = new SelectList(list, "CategoryID", "CategoryName");

}
@Html.DropDownListFor(???, @items)

I could use some help constructing the Linq portion of @Html.DropDownListFor.
Here is the model:
public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
    public int CategoryID { get; set; }
    public string QuantityPerUnit { get; set; }
    public Decimal? UnitPrice { get; set; }
    public short UnitsInStock { get; set; }

    public virtual Category Category { get; set; }
}

public class Category
{
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }

    public virtual ICollection<Product> Products { get; set; }

}

A: Your view is strongly typed to a collection of products so I suppose that you need a drop down for each product. If this is the case an editor template would work:
@model IEnumerable<Sample.Models.Product>
@Html.EditorForModel()

And then inside ~/Views/Shared/EditorTemplates/Product.cshtml
@model Sample.Models.Product
@{
    List<Sample.Models.Category> list = ViewBag.Categories;
    var items = new SelectList(list, "CategoryID", "CategoryName");
}
@Html.DropDownListFor(x => x.CategoryID, @items)

A: My recommendation:
Extend your LINQ data context class with a static function to return a SelectList of all categories, and use Html.DropDownList() to display this list.
Then, add a controller for this same Action that accepts category ID and return the IEnumerable<Product> list that corresponds to that category.

A: here is another way to do what you want.
In the model I have two entries
  public class Product
  {
     public int CategoryID { get; set; }
     public IEnumerable<SelectListItem> Category { get; set; }
  }

I then populate the SelectlestItem either from a database or statically.
In the Index.cs controller
   product model = new product();

   model.Category = <whereever you generated the data>;

   return View(model);

In the View
    @using (Html.BeginForm("Edit", "Subject", FormMethard.Post, new { id = "genform"}))
    {

@Html.DropDownListFor(m => m.CategoryID, model,Category)


text:
Q: using perl script to invoke cleartool commands using fmt I use Perl scripts to run commands for several users in several VOBs on ClearCase. I have a list of the VOBs which I read in from a text file. I then loop on that list and do whatever ClearCase command I am trying to do. However, this time the script does not seem to work. If I print out the command to the screen then go and copy and paste it at the prompt it works fine. It just will not executed from the Perl script. The only difference I saw was the fmt characters but even when I remove that it does not execute. I tried first putting the fmt on the line directly then tried setting them to variables. You will see the first comment line is the one that failed but I left it there as an example of what I tried. The last two comments are from another script that I run like this that does work.
Code:
#! /usr/local/bin/perl -w
use strict;

open(VOBS,"vobs.txt") || die "Can't open: !$\n";

my $u = '%u';
my $a ='%Ad';
my $n ='%N/n';
my $user='john';
my $ct = '/usr/atria/bin/cleartool';

while(my $newvobs=<VOBS>){

  chomp($newvobs);
  my $tag = $newvobs;
  print "\n $tag \n";
  print " $ct lstype -kind brtype -invob $tag | grep $user ";
  `$ct lstype -kind brtype -invob $tag | grep $user`;
  # `/usr/atria/bin/cleartool lstype -kind brtype -invob $tag -fmt '%u %Ad %N/\n' `;
  # print "\n cleartool rmtag -view  $tag \n";
  #`/usr/atria/bin/cleartool rmtag -view  $tag `;
}

close(VOBS);

A: For reference, here is a perl script which uses -fmt, "Finding the latest baseline for a component":
Example:
ccperl StreamComp.pl mystream@\pvobtag | findstr {component}

Script "streamcomp.pl":
#!/usr/bin/perl -w
my $cmdout = `cleartool desc -fmt '%[latest_bls]CXp' stream:$ARGV[0]`;
my @baselines = split(/,/,$cmdout);
foreach $baseline (@baselines)
{
  $compname=`cleartool desc -fmt '%[component]p' $baseline`;
  printf("%-30s \t %s\n", $compname, $baseline);
}

It is a program working for a ClearCase UCM environment, but it could give you an idea of the kind of working statements (try without grep first) you could try to reproduce in your own base ClearCase program.

A: Actually Your program runs, but is does not print anything.
Example:
#!/usr/bin/perl
use strict;
use warnings;
my $cmd = "cat";
`$cmd $0 | grep warning`;

Output: (nothing)

Easiest to fix. Last line
print `$cmd $0 | grep warning`

Output:

use warnings;
print `$cmd $0 | grep warning`;

If You need the exit code, replace last line with
my $exit = system("$cmd $0 | grep warning");
print $exit;

Output:

use warnings;
my $exit = system("$cmd $0 | grep warning");
0

Or use open to process output:
open my $fh, "$cmd $0 | grep warning|" or die;
while (<$fh>) { print $_; }
close $fh;

Output:

use warnings;
open my $fh, "$cmd $0 | grep warning|" or die;

But I could suggest something like bellow. Using AUTOLOAD the clearcase commands can be used as internal perl commands.
#!/usr/bin/perl
use strict;
use warnings;

sub AUTOLOAD {
    (my $sub = $::AUTOLOAD) =~ s/.*:://;
    print "---\n";
    system("time $sub @_");
    print "---\n";
}

my $cmd = "cat";
eval "$cmd($0)";

Output:

---
#!/usr/bin/perl

use strict;
use warnings;

sub AUTOLOAD {
    (my $sub = $::AUTOLOAD) =~ s/.*:://;
    print "---\n";
    system("time $sub @_");
    print "---\n";
}

cat($0);
0.00user 0.00system 0:00.00elapsed 400%CPU (0avgtext+0avgdata 2112maxresident)k
0inputs+0outputs (0major+174minor)pagefaults 0swaps
---


text:
Q: How to type hint a return value that's defined in the function's local scope? Given the following example:
class A:
    def __init__(self, num: int):
        self.num = num

    def bar(self, eggs: int):
        if eggs == self.num:
            raise ValueError

def foo(spam: bool) -> B:
    class B(A):
        def bar(self, eggs: int):
            try:
                super().bar(eggs)
            except ValueError as e:
                if not spam:
                    raise e
    return B

The base class A has a method named bar that raises a ValueError if eggs equals to self.num. I also have a function named foo that accepts an argument spam, it returns a subclass of A and overrides the bar method so that no ValueError will be raised if spam is non Falsey.
I'm trying to type hint the return value for the foo function. If I do -> B, B is undefined. If I do -> A, type B isn't exactly A. If I do -> "B", using future hinting, B is still not defined since it's in a local scope.
Is there anyway to type hint this? If not, is there a better way to rewrite my code?

A: Here's what I could think of from a quick scan of the docs. This isn't a good solution at all (I think), but it should do the job for you.
There's something called typing.TypeVar (docs). Its basically a generic type. So what you could possibly do is:
At the global level (after defining class A) define:
from typing import TypeVar
B = TypeVar('B', bound=A)

Now in the function signature of def foo you can say:
def foo(spam: bool) -> B:

Then inside the function you can continue to create a new class with the name B and return it.
I'm not even sure if this would work properly in all cases. If you find any problems with it, definitely correct me and post here.


text:
Q: Web image search API that allows to filter by license I'm trying to use an image search API to get images to use on my site, however I need to be able to filter by license, so that I can actually use the images! My first thought was "hey, I'll use google's image search API!", well that has been deprecated. Bing's API is horribly documented, however I finally got it to work, only to realize they don't let you filter by license (even though they do on the live site, sigh...). Google's custom search API seems like a complete mess and only limits you to 100 queries a day for free, however they DO allow you to filter by license.
Does anyone have any good ideas on what to use? It looks like Google Custom Search currently looks like the only one that will allow me to filter by license - but the API seems like it's trying to be a lot of things that it isn't and seems more for integrating a a custom search bar into the frontend of a site.

A: you can try flickr's api, which allows you to filter by license


text:
Q: Can't change Hyper Terminal Hardware Settings Anyone here any good with Hyperterminal?  Am having a nightmare trying to use it at work to update our telephone extensions.  The company who supply our PABX box have told me that XP does strange things to Hyperterminal and that I should use Win2k.  Which I did with the same result.
I have narrowed the problem dowwn to the Hardware Settings for the connection in Hyper Terminal.  No matter what I set (and I need 7E1) it defaults back to 8N1.  Has anyone seen this behaviour before and know of a simple way around it?  (Apart from buying a more expensive commercial version of Hyper Terminal, as suggested by our support people).
Edit: I should point out I have to connect via a phone line so a direct serial connection is not an option.
Cheers
Tim

A: You can have a try at ZOC Terminal too.  It's commercial, but I found it the most user friendly.

A: Try TeraTerm, a freeware terminal emulator. Much better then hyperterm.

A: Putty also does terminal emulation -- start it, and select the "Serial" radio button. Then enter your COM-port and voila!

A: In the end ditched XP and Hyper Terminal completely.  We use Wyse boxes at our company so was able to set one of those up to dial the correct extension and use an interactive terminal session while also giving me correct control of the Parity and Stop Bits etc.  Worked like a charm and means we no longer have to have a separate Laptop to perform this function.
Cheers for the suggestions.


text: Q: noVNC console on Openstack Dashboard is rendering garbled UI on RHEL7 I am running nova-compute on RHEL7. Openstack dashboard's noVNC console is rendering garbled UI for any instance having a UI console. Can somebody please help out? This is working just fine on RHEL65


text:
Q: Evaluating integrals in R^m Let $|\cdot|_m$ denote the Euclidean norm in $\mathbb{R}^m$.  Then
I wish to prove that
$\displaystyle\int\limits_{\mathbb{R}^m}|x|_me^{-|x|_m}dx<\infty$
It's kinda embarrassing to say this, but I don't really know where to start.  Probably spherical coordinates would help, but I don't recall how to handle spherical coordinates in m-dimension.

A: To avoid a more general measure-theoretic approach, we could always use a "shell-method" of sorts.
In particular, we start by noting that the $n$-dimensional surface area of the $n$-sphere is given by $V(r) = \alpha_n r^n$ (where the coefficient $\alpha_n$ is generally going to be some function of $\pi$).
We can then write this as
$$
\int_{\mathbb{R}^m}f(r(x))dx =\\
\int_{r=0}^\infty f(r(x))V_{n-1}(r(x))\,dx =\\
\alpha_{n-1} \int_{r=0}^\infty r^{n-1}f(r(x))\,dx
$$
which will be enough to get you your result.

A: Essentially all you need to know is that the "surface area" of the unit sphere in $\mathbb{R}^m$ is finite (Call it $S_m$). (what this actually means is doing the angular integrals, which are all of bounded functions on bounded intervals, so the result is bounded.)  Then the "surface area" of a sphere of radius $r$ is $S_m r^{m-1}$, by scaling considerations, and the volume is $S_m r^m/m$, by integrating. It follows that the volume of the space between two spheres is about
$$ \frac{1}{m}S_m (r+h)^{m}-\frac{1}{m}S_m r^{n} \sim S_m r^{n} h $$
as $h \to 0$. Therefore, since $r=|x|_m$, the integral becomes
$$ S_m \int_0^{\infty} r e^{-r} r^{m-1} \, dr, $$
which you can calculate using integration by parts to get $m! S_m$.


text:
Q: Android discreet seekbar not showing tickmarks for max values below 2 Setting the discreet seekbar attributes to android:max="1" does not show the tickmark on both ends of the seekbar even though its seekable.
But setting android:max="2" shows the three tickmarks.
How to make the tickmark appear for max value 0 and 1?

A: If you look at the source code for AbsSeekBar, you'll find this method:
/**
 * @hide
 */
protected void drawTickMarks(Canvas canvas) {
    if (mTickMark != null) {
        final int count = getMax() - getMin();
        if (count > 1) {
            final int w = mTickMark.getIntrinsicWidth();
            final int h = mTickMark.getIntrinsicHeight();
            final int halfW = w >= 0 ? w / 2 : 1;
            final int halfH = h >= 0 ? h / 2 : 1;
            mTickMark.setBounds(-halfW, -halfH, halfW, halfH);

            final float spacing = (getWidth() - mPaddingLeft - mPaddingRight) / (float) count;
            final int saveCount = canvas.save();
            canvas.translate(mPaddingLeft, getHeight() / 2);
            for (int i = 0; i <= count; i++) {
                mTickMark.draw(canvas);
                canvas.translate(spacing, 0);
            }
            canvas.restoreToCount(saveCount);
        }
    }
}

The important part is the line if (count > 1); for whatever reason, the Google team decided that tick marks shouldn't be shown if there were only two selectable values.
There's no great way to work around this.
You'd have to override this entire method, but it's annotated with @hide which means that the outside world shouldn't know about it. This won't actually stop you from doing it, but it means that you always have to worry about it breaking whenever Android is updated.
The other problem is that this method uses a lot of fields that you won't have access to. You can use getters to work around that but it's a little gnarly.
Put together, you can make this class:
public class MySeekBar extends SeekBar {

    public MySeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    protected void drawTickMarks(Canvas canvas) {
        if (getTickMark() != null) {
            final int count = getMax() - getMin();

            // this is the important part: you change this to 0 from 1

            if (count > 0) {
                final int w = getTickMark().getIntrinsicWidth();
                final int h = getTickMark().getIntrinsicHeight();
                final int halfW = w >= 0 ? w / 2 : 1;
                final int halfH = h >= 0 ? h / 2 : 1;
                getTickMark().setBounds(-halfW, -halfH, halfW, halfH);

                final float spacing = (getWidth() - getPaddingLeft() - getPaddingRight()) / (float) count;
                final int saveCount = canvas.save();
                canvas.translate(getPaddingLeft(), getHeight() / 2);
                for (int i = 0; i <= count; i++) {
                    getTickMark().draw(canvas);
                    canvas.translate(spacing, 0);
                }
                canvas.restoreToCount(saveCount);
            }
        }
    }
}


text:
Q: Integrating a jQuery plugin into NextJS I'm trying to integrate a six years old jQuery plug-in but I can't.
I tried to use findDOMNode module from react-dom, even then React Official Docs way to integrate a jQuery plug-in but none of them.
This is my plug-in --> https://www.jqueryscript.net/layout/Fancy-Responsive-jQuery-Diamond-Layout-Plugin-diamonds-js.html
I'm getting a couple of errors like

TypeError: jquery__WEBPACK_IMPORTED_MODULE_8___default(...)(...).Diamonds is not a function
ReferenceError: the window is not defined // I'm getting this error because library use the windows in the last line

I'm also showing you my snippet which I use to initialize the element.
componentDidMount() {
  //   $(".diamondswrap").diamonds({
  //     size : 200, // Size of diamonds in pixels. Both width and height.
  //     gap : 5, // Pixels between each square.
  //     hideIncompleteRow : false, // Hide last row if there are not enough items to fill it completely.
  //     autoRedraw : true, // Auto redraw diamonds when it detects resizing.
  //     itemSelector : ".item" // the css selector to use to select diamonds-items.
  // });

  if(typeof window !== 'undefined') {
    window.Diamonds = require('../assets/js/jquery.diamonds.js');
  }
  new Diamonds.Diamonds();
  }

Thanks, and sorry for my English!

A: I created a small Github repo where you can take a look: https://github.com/tudorgergely/jquery-plugin-nextjs/
Here is the working demo: https://jquery-plugin-nextjs.now.sh/
Basically you need a couple of things, first use dynamic without ssr for the component rendering jquery-diamonds:
const DynamicJqueryDiamonds = dynamic(
    () => import('../components/JqueryDiamonds'),
    { loading: () =>
...
, ssr: false }
);

Then inside that component load jquery/diamonds in componentDidMount/useEffect:
    useEffect(() => {
        window.jQuery = require('../public/jquery-latest.min');
        window.Diamonds = require('../public/jquery.diamonds.js');

        window.jQuery("#demo").diamonds({
            size : 100, // Size of diamonds in pixels. Both width and height.
            gap : 5, // Pixels between each square.
            hideIncompleteRow : false, // Hide last row if there are not enough items to fill it completely.
            autoRedraw : true, // Auto redraw diamonds when it detects resizing.
            itemSelector : `.${styles.item}` // the css selector to use to select diamonds-items.
        });
    }, []);

and last thing, don't forget to include your css inside pages/index.js:
e.g.:
export default function Index() {
    return (

                <title>Test</title>
                <link href="/diamonds.css" rel="stylesheet" key="test"/>

            <DynamicJqueryDiamonds/>

    );
}


text:
Q: how to set up the searchable fields in Lucene I have incoming queries and I want to only search in certains fields (author, book title) not in field (book content). How can I achieve this in Lucene?
another questions is that if how can I give a higher rank to documents that have matches in the author field. For example, doc1 have match in "book content", and doc2 has match in "author", how can I rank higher for doc2

A: You can combine multiple queries using BooleanQuery, and have Occur.Should (meaning OR). I also believe that you can boost specific queries in such a scenario, which means that matches in a specific field has higher relevance that for instance, content.
Example (C#):
var query = new BooleanQuery();
query.Add(new TermQuery("author", searchTerm), Occur.Should);
query.Add(new TermQuery("book title", searchTerm), OCcur.Should);


text:
Q: Why is X-axis not scaling to the data? (Novice and almost entirely self-taught, but can't seem to find anything here that addresses my issue)
I am adding a chart to a spreadsheet that tracks outstanding tasks for each day by type. I am using dates as horizontal labels. However, I wish to omit weekends and holidays, but want to include days I do not receive the data as empty cells e.g 12/04.
I have the range with the desired dates as the top row of my spreadsheet. The problem is that, if I choose the axis to be "Date Axis", I get this: (with weekends/holidays included, even though they are not in the source range.)
With date axis
But if I use a "Text Axis" I get this: (axis not running the length of the plot area)
with text axis
I can't figure out why the axis isn't scaling with the width of the chart area.

A: In my opinion, it is best to use a "Text Axis", you may enter the date as your needs manually. If you use "Date Axis", two days of the weekend would shown on the chart, it seems to be an expected behavior.
If you create a table, then insert a Line chart based on this table, every time you enter the date and the corresponding data at the bottom of the table, the value would be added into the table and the chart automatically.

A: OK, stumbled into an answer that makes no sense, but works. Posting because, eventually, someone will run into the same problem.
My date labels are in $C$1:$X$1, which is 23 cells. I had to change  the X-axis to a date axis, then give it the range 12/01/2020 to 12/23/2020, then change BACK to a text axis.


text:
Q: MS-Build: Displaying out-of-date dependencies I'm trying to debug an MS-Build in VS2010 setup that reports about a half-dozen projects are out-of-date on every build. I'm trying to trawl through the diagnostic output for a clue to what files are consider out-of-date and causing the rebuild.
Is there a simpler way to display the reason for dependencies to avoid looking for a needle in the proverbial haystack?
thanks
Dan

A: The answer to the question "VS2010 always thinks project is out of date but nothing has changed" shows you how to debug the dependencies checker of visual studio.


text:
Q: TypeError: __init__() got multiple values for keyword argument 'customer' customer = CustomerProfile.objects.get(pk=4)
ipdb> SimilarCustomerFinder(self, customer=customer, fields=self.fields)
*** TypeError: __init__() got multiple values for keyword argument 'customer'

In SimilarCustomerFinder class, I have
def __init__(self, customer, fields):
    self._matches = {}
    props = self.__class__.__dict__.keys()
    self.customer = customer
    self.fields = fields
    self.checks = [k for k in props if k.startswith('check_')]
    if customer:
        self.user_id = customer.user.pk
    else:
        self.user_id = -1

    for check in self.checks:
        c = check.replace('+', '_')
        getattr(self, c)()

I am struggling with this error. How could I fix it? If I remove customer=customer, I got *** AttributeError: 'CustomerUpdateForm' object has no attribute 'user', why?

A: Given the ipdb output it seems like you're trying to create an instance using this command:
SimilarCustomerFinder(self, customer=customer, fields=self.fields)

However self is an implicitly passed argument so you shouldn't pass it in explicitly. Like this:
SimilarCustomerFinder(customer=customer, fields=self.fields)

Or if you really intended to pass it in explicitly (which would be really weird and probably doesn't do what you intend - but who knows ...) you have to call the method explicitly on the class:
SimilarCustomerFinder.__init__(self, customer=customer, fields=self.fields)


text:
Q: Drag and drop image, returns wrong size Im using a pre-made script to drag images from computer folders, and into a div (see JSFiddle: http://jsfiddle.net/JtJ5N/1/). Script works fine, but I have a problem retrieving the image size - the first time for a new image.
What is weird, is that the first time i drag the image into the div, it returns height(24) and width(24), which is not correct. BUT, if I reload the page, and drag the same image again, the size is correct!
First time dragging a new picture into div:

Second time dragging the same picture, after reloading page:

Doesn't make any sense to me, as nothing should be saved. Please see JSFiddle example above, and the only additional code is the size-retrieval as following:
list.appendChild(img);
var imgheight = img.height;
var imgwidth = img.width;
alert("width: " + imgwidth + ", height: " + imgheight);

A: I think the problem lies in image not loading. When you refresh / reload the page, the image is in browser cache and hence, when the code executes to read its width x height, it already knows the image and gives you correct answer.
Please check the FIDDLE HERE for a solution. This code gives an alert whenever an image is dropped with image's different details.
Please look out for following code:
 var dummyimage = new Image();

and then
                dummyimage.src = e.target.result;
                dummyimage.onload = function() {
                    // to add loaded image to document
                    list.appendChild(dummyimage);
                    // various properties of image
                    alert('width:' + this.width + ' x height:' + this.height + ' --- ' + file.type + '  ' + file.name  + '  ' + file.size);
                };
                dummyimage.onerror= function() {
                    alert('Image could not be loaded');
                };

The code also let you know if there is a problem in loading an image. E.g. if a .doc file is dropped or something.
Let me know if you have any questions.


text:
Q: Reversible string compression PHP/C++ I would like to obfuscate some short text data, and make this compression learnable/memorizable.
So I'm looking for an algorithm achievable in PHP to compress a string (~25 characters long) into a ~8 character string, then reversible in C++.
Does anyone have an algo name or another idea ?
EDIT: Everything is lowcase, with two specials characters.

A: As the text data only consists of lowercase letters and two special characters, so we have only 28 different characters to consider.
We can design the hash function by property of bit representation. With all possible combination of 5 bits, we can uniquely represent 32 different symbols. So, to represent 28 different symbols, we only need 5 bits for each symbol.
a => 00000
b => 00001
c => 00010
......
......
......
y => 11000
z => 11001
special-character-1 => 11010
special-character-2 => 11011

With this encoding scheme, we only need 25 * 5 = 125 bits to represent the complete text data, which is 125 / 8 ~ 16 bytes or 16 characters (sorry its not 8 characters).
Now, you can retrieve the actual string from this 16 characters hash by applying the reverse mapping.
If you're satisfied with 16 characters reversible hashing, I can provide C++ implementation.

A: Impossible.
If we assume that the original strings only contains letters A-Z, there are 2625 ≈ 4.25 x 1037 (42 billion billion billion billion) possible input strings.
If we then generously allow the eight-character outputs to contain any letter, uppercase or lowercase, or digit (26 + 26 + 10 = 62 characters total), there are 628 ≈ 2.18 x 1014 (218 million billion) possible outputs.
This is roughly 1023 times fewer! By the pigeonhole principle, the compression scheme you're asking for is impossible -- there are many times more possible input strings than outputs, so there's no way to reversibly turn every one of the input strings into an output and back.


text:
Q: Quicksort WAY slower than Insertion and Selection Sort in Java? So I'm brushing up on my algorithms knowledge and testing runtimes of different sorts, and I've found that my implementation of quicksort is much, much slower than even insertion and selection sorts.  The algorithm looks right to me, and it looks identical in practice to several other implementations I found online.  But it has to be wrong somehow, because it's on the order of 500x slower than the O(N^2) sorts.  Timing the sorts on 3 (deep) copies of a  randomized 10000 element array gives:
Insertion Sort: (75355000 ns)
Selection Sort: (287367000 ns)
Quick Sort:     (44609075000 ns)
Here's the code:
public static void quickSort(Thing [] theThings, int left, int right) {
    int i= left; int j = right;
    int pivot = theThings[(int)(left + (right-left)*0.5)].getValue();

    while (i <= j) {
        while (theThings[i].getValue() < pivot)
            i++;
        while (theThings[j].getValue() > pivot)
            j--;

        if (i <= j) {
            Thing temp = theThings[i];
            theThings[i] = theThings[j];
            theThings[j] = temp;

            i++;
            j--;
        }

        if (left < j)
            quickSort(theThings, left, j);
        if (right > i)
            quickSort(theThings, i, right);
    }
}

The Thing class is just a dummy I made to play with in my algorithms.  It has an integer value generated by Random in the constructor, and not much else.
I've verified that the quicksort does correctly sort the array - just much slower than it should.  I've tried different pivot choosing methods.  I've tried everything I could think of.  Maybe I'm just too close to see it, but could anyone tell me what is killing my algorithm?

A: You should be recursing to quicksort each part of the array after the while loop is complete, not each time through the while loop.


text:
Q: When to use padding in Conv2d() and when to do ReflectionPad2d() Pytorch I have two PyTorch models that are equivalent (I think), the only difference between them is the padding:
import torch
import torch.nn as nn

i = torch.arange(9, dtype=torch.float).reshape(1,1,3,3)
# First model:
model1 = nn.Conv2d(1, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), padding_mode='reflection')
# tensor([[[[-0.6095, -0.0321,  2.2022],
#           [ 0.1018,  1.7650,  5.5392],
#           [ 1.7988,  3.9165,  5.6506]]]], grad_fn=<MkldnnConvolutionBackward>)

# Second model:
model2 = nn.Sequential(nn.ReflectionPad2d((1, 1, 1, 1)),
             nn.Conv2d(1, 1, kernel_size=3))
# tensor([[[[1.4751, 1.5513, 2.6566],
#           [4.0281, 4.1043, 5.2096],
#           [2.6149, 2.6911, 3.7964]]]], grad_fn=<MkldnnConvolutionBackward>)

I was wondering why and when you use both approaches, the output of both is different but as I see it they should be the same, because the padding is of type reflection.
Would appreciate some help in understanding it.
EDIT
After what @Ash said, I wanted to check wheter or not the weights had influence so I pinned all of them to the same value and still there is a difference between the 2 methods:
import torch
import torch.nn as nn

i = torch.arange(9, dtype=torch.float).reshape(1,1,3,3)
# First model:
model1 = nn.Conv2d(1, 1, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), padding_mode='reflection')
model1.weight.data = torch.full(model1.weight.data.shape, 0.4)
print(model1(i))
print(model1.weight)
# tensor([[[[ 3.4411,  6.2411,  5.0412],
#           [ 8.6411, 14.6411, 11.0412],
#           [ 8.2411, 13.4411,  9.8412]]]], grad_fn=<MkldnnConvolutionBackward>)
# Parameter containing:
# tensor([[[[0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000]]]], requires_grad=True)

# Second model:
model2 = [nn.ReflectionPad2d((1, 1, 1, 1)),
             nn.Conv2d(1, 1, kernel_size=3)]
model2[1].weight.data = torch.full(model2[1].weight.data.shape, 0.4)
model2 = nn.Sequential(*model2)
print(model2(i))
print(model2[1].weight)
# tensor([[[[ 9.8926, 11.0926, 12.2926],
#           [13.4926, 14.6926, 15.8926],
#           [17.0926, 18.2926, 19.4926]]]], grad_fn=<MkldnnConvolutionBackward>)
# Parameter containing:
# tensor([[[[0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000],
#           [0.4000, 0.4000, 0.4000]]]], requires_grad=True)

A:
the output of both is different but as I see it they should be the same

I don't think that the different outputs that you get are only related to how the reflective padding is implemented. In the code snippet that you provide, the values of the weights and biases of the convolutions from model1 and model2 differ, since they are initialized randomly and you don't seem to fix their values in the code.
EDIT:
Following your new edit, it seems that for versions prior to 1.5, looking at  the implementation of the forward pass in <your_torch_install>/nn/modules/conv.pyshows that "reflection" is not supported. It wont complain about arbitrary strings instead of "reflection" either, but will default to zero-padding.


text:
Q: How MySQL Group Replication get primary node ip address According to MYSQL 5.7 Reference Manual :

*

*http://dev.mysql.com/doc/refman/5.7/en/group-replication-find-primary.html

*http://dev.mysql.com/doc/refman/5.7/en/group-replication-monitoring.html
We can use the sql below to find the primary-node's hostname when group replication is deployed in single-mode :
mysql> SELECT * FROM performance_schema.replication_group_members WHERE MEMBER_ID = (SELECT VARIABLE_VALUE FROM performance_schema.global_status WHERE VARIABLE_NAME= 'group_replication_primary_member');
+---------------------------+--------------------------------------+-------------+-------------+--------------+
| CHANNEL_NAME              | MEMBER_ID                            | MEMBER_HOST | MEMBER_PORT | MEMBER_STATE |
+---------------------------+--------------------------------------+-------------+-------------+--------------+
| group_replication_applier | 9176f4d3-c7f6-11e6-bcf7-fa163ee40410 | myhost      |       24801 | ONLINE       |
+---------------------------+--------------------------------------+-------------+-------------+--------------+
1 row in set (0.00 sec)

the question is : How to get ip address instead of hostname ?

A: You cannot get any ipaddress of the hostnames. If you are connecting to some host then you know the ipaddress of that hostname. Here is the mailing list that is on mysql forum that would be helpful to you.

A: Ok, We can use the property named report_host to point to our ip address, eg:
In my own machine, I deploy three node(s1,s2,s3) to form one replication group, in all my.cnf, define it (10.202.7.88 is my ip address):
report_host=10.202.7.88

then restart all node and re-config three node to form the replication group, then query :
mysql> select * from performance_schema.replication_group_members;
+---------------------------+--------------------------------------+-------------+-------------+--------------+
| CHANNEL_NAME              | MEMBER_ID                            | MEMBER_HOST | MEMBER_PORT | MEMBER_STATE |
+---------------------------+--------------------------------------+-------------+-------------+--------------+
| group_replication_applier | 933a5345-d321-11e6-b971-fa163ee40410 | 10.202.7.88 |       24801 | ONLINE       |
| group_replication_applier | 9abe6249-d321-11e6-bb5c-fa163ee40410 | 10.202.7.88 |       24802 | ONLINE       |
| group_replication_applier | a1c89c34-d321-11e6-bbbc-fa163ee40410 | 10.202.7.88 |       24803 | ONLINE       |
+---------------------------+--------------------------------------+-------------+-------------+--------------+
3 rows in set (0.00 sec)

and then we can use the sql we memtion above to get the primary node ip address:
mysql> SELECT * FROM performance_schema.replication_group_members WHERE MEMBER_ID = (SELECT VARIABLE_VALUE FROM performance_schema.global_status WHERE VARIABLE_NAME= 'group_replication_primary_member');
+---------------------------+--------------------------------------+-------------+-------------+--------------+
| CHANNEL_NAME              | MEMBER_ID                            | MEMBER_HOST | MEMBER_PORT | MEMBER_STATE |
+---------------------------+--------------------------------------+-------------+-------------+--------------+
| group_replication_applier | 933a5345-d321-11e6-b971-fa163ee40410 | 10.202.7.88 |       24801 | ONLINE       |
+---------------------------+--------------------------------------+-------------+-------------+--------------+
1 row in set (0.00 sec)


text:
Q: How to implement summation (∑) on 3d xarray data? Assume I have two variables in a dataset in xarray format as follow:
import numpy as np
import pandas as pd
import xarray as xr
pre= 10 * np.random.rand(5, 4, 10)
temp = 15 * np.random.rand(5, 4, 10)
time = pd.date_range("2014-01", periods=10, freq='MS')

ds = xr.Dataset(
    data_vars=dict(
        temperature=(["lat", "lon", "time"], temp),
        precipitation=(["lat", "lon", "time"], pre),
    ),
    coords={"lon": [25, 25.5, 26, 26.5], "lat": [42.5, 43, 43.5, 44, 44.5], "time": time},
    attrs=dict(description="Weather related data."),)

I appreciate any help on how to calculate the following formula:

So far I am trying to solve it as follow:
ds_pre_std = ds.pre.std(dim="time", skipna=True)

Z1= xr.zeros_like(ds.pre)

for k in range(len(ds.time)):
    Z[k, :, :] = np.sum(ds.pre[k, :, :] - ds.temp[k, :, :]) ** 2 / ds_pre_std

Z2= xr.zeros_like(ds.pre)
for k in range(len(ds.time)):
    Z2[k, :, :] = np.sum(ds.pre[k, :, :] - ds.pre.mean("time")) ** 2 / ds_pre_std

Z = Z1 / Z2

But I am sure I am far a way from the correct results, particularly for the sum function which I think I have to define the first and last value based on the formula!

A: Thanks for the clear example.
If I'm interpreting the example correctly — and we want to reduce over the time dimension — then here's the first half, and the second half follows exactly.

In [1]: import numpy as np
   ...: import pandas as pd
   ...: import xarray as xr
   ...: pre= 10 * np.random.rand(5, 4, 10)
   ...: temp = 15 * np.random.rand(5, 4, 10)
   ...: time = pd.date_range("2014-01", periods=10, freq='MS')
   ...:
   ...: ds = xr.Dataset(
   ...:     data_vars=dict(
   ...:         temperature=(["lat", "lon", "time"], temp),
   ...:         precipitation=(["lat", "lon", "time"], pre),
   ...:     ),
   ...:     coords={"lon": [25, 25.5, 26, 26.5], "lat": [42.5, 43, 43.5, 44, 44.5], "time": time},
   ...:     attrs=dict(description="Weather related data."),)

In [2]: ds
Out[2]:
<xarray.Dataset>
Dimensions:        (lat: 5, lon: 4, time: 10)
Coordinates:
  * lon            (lon) float64 25.0 25.5 26.0 26.5
  * lat            (lat) float64 42.5 43.0 43.5 44.0 44.5
  * time           (time) datetime64[ns] 2014-01-01 2014-02-01 ... 2014-10-01
Data variables:
    temperature    (lat, lon, time) float64 0.5981 11.84 11.35 ... 4.074 12.49
    precipitation  (lat, lon, time) float64 7.012 7.678 9.634 ... 2.729 5.944
Attributes:
    description:  Weather related data.

In [3]: numer_1 = (ds['precipitation']) - ds['temperature']) ** 2

In [4]: denom_1 = ds['precipitation'].std('time')

In [5]: numer_1 / denom_1
Out[5]:
<xarray.DataArray (lat: 5, lon: 4)>
array([[6.65870313, 0.01847954, 1.35175245, 1.33186654],
       [4.37142192, 2.57042848, 5.10478184, 7.57213791],
       [0.33377772, 4.65275033, 0.05615346, 0.10104126],
       [2.05970793, 3.75681053, 9.89674346, 0.80563933],
       [3.57408137, 0.11641076, 4.55715038, 0.03830404]])
Coordinates:
  * lon      (lon) float64 25.0 25.5 26.0 26.5
  * lat      (lat) float64 42.5 43.0 43.5 44.0 44.5

...and similar for the second half.
Notably, there's no need to use python loops nor numpy functions — this sort of operation is well within xarray's comfort zone.

Edit: in response to your question, is the denominator (although you write numerator, so maybe I'm confused):
In [22]: (ds['precipitation'] - ds['precipitation'].mean('time')) / ds['precipitation'].std('time')

Out[22]:
<xarray.DataArray 'precipitation' (lat: 5, lon: 4, time: 10)>
array([[[-0.98966504, -0.11198979, -0.75832633,  1.3114296 ,
          1.14629021,  0.63349046, -1.07008682,  1.16006701,
         -0.25235464, -1.13866263]]])
Coordinates:
  * lon      (lon) float64 25.0 25.5 26.0 26.5
  * lat      (lat) float64 42.5 43.0 43.5 44.0 44.5
  * time     (time) datetime64[ns] 2014-01-01 2014-02-01 ... 2014-10-01


text:
Q: Is it possible to run GitHub action when a repo I fork releases a new release? Is it possible to run GitHub action on a fork, whenever the original forked project publishes a new release ?

A: You can use the [release] event but note that more than one activity can trigger it.
on:
  release:
    types: [published]

For the details of each event check the Webhook events, the one you need is [published] and repository key which is the repository where the event occurs.

A: As of Jun 2022, there is no trigger that runs the workflow when the upstream (the repo you forked) does something.
So what you'll have to do is create a workflow that runs on schedule, pull the upstream repository and check if there is something new.
If you just want to copy commits 1:1, then you could use the action aormsby/Fork-Sync-With-Upstream-action: https://github.com/aormsby/Fork-Sync-With-Upstream-action
If tags are good enough, you could take inspiration from the above action and compare the tags in your repository with the ones from upstream.
If you really need releases (GitHub Releases), then you're probably going to have to maintain some custom state somewhere to remember which releases you have already seen. Or alternatively, replicate all upstream releases in your repository. This would allow you to create a separate workflow that triggers on release, like so:

*

*Pull upstream repository

*Recreate all upstream releases in your repository (unless they exist already)

*Trigger a separate workflow on: release