text:
Q: how to invisible a Layout control in android i'm using following code to set "visibility=gone" for a linear layout
      //onCreate method
      //setcontentview
        . . . .
      LinearLayout rlayout1 = (LinearLayout) findViewById(R.id.readerBottomLayout);
       rlayout1.setVisibility(2);

But the controls are still visible when activity runs.why? any idea?

A: you can also do something like this:
Get Parent layout object through its id
Get layout which you want to remove/hide through its id

parentlayout.remove(childlayout);

A: set rlayout1.setVisibility(View.INVISIBLE)

A: Yes, view.GONE and view.INVISIBLE will work. The reason it didn't work before is because two (2) is the incorrect integer value.
The correct values for set.Visibility are:
0 = visible
4 = invisible
8 = gone


text:
Q: Remove whitespace from an argument into a JS function I'm trying to remove whitespace from an argument passed by a HTML form into a function using the trim() method. The function then lists the addresses that match that postcode.
var postCodes = {
  N48LP: {
    address: ['59, White Gardens', '54, White Gardens', '52, White Gardens', '55, White Gardens']
  }
};

function searchCode(arg2){
  arg2.trim();
if(typeof postCodes[arg2] === 'undefined') {
  document.getElementById('oldpa').innerHTML = 'Postcode not found';
} else {
// code here which prints the list of addresses
     }}};

This doesn't work. Where 'N48LP' works, 'N4 8LP' or 'N 48LP' will result in 'Postcode not found'. Could anyone tell me why? Many thanks.

A: Try replace instead of trim.
arg2.replace(/\s+/, "");

A: you are looking for: arg2.split(' ').join(''). trim function remove spaces from start and from end of strings only

A: There are several problems in your code. One is that trim() does not trim the string in-place, this means that it does not mutate the original string. The second one is that trim() does not remove spaces in between characters.
To solve this, you can use replace() with a regex that replaces all occurence of all spaces as empty strings, and then assign such value as an index to be used when checking the postCodes object.

var postCodes = {
  N48LP: {
    address: ['59, White Gardens', '54, White Gardens', '52, White Gardens', '55, White Gardens']
  }
};

function searchCode(arg2) {
  // note that you have to make the regex to perform
  // a global search to make it function as a trim as well
  var index = arg2.replace(/\s+/g, '');
  if (typeof postCodes[index] === 'undefined') {
    document.getElementById('oldpa').innerHTML += 'Postcode not found';
  } else {
    // code here which prints the list of addresses
    document.getElementById('oldpa').innerHTML += [
      'input: ', arg2.replace(/\s+/g, ' '), '',
      '
', JSON.stringify(postCodes[index], 0, 4), '
'
    ].join('');
  }
}

searchCode('N 48LP');
searchCode('  N48LP  ');
searchCode('  N 4 8 L P  ');

A: Problem is here arg2.trim();. As @DontRelaX said trim() methods does not remove white spaces in the middle of the string. And another problem, considering that this would be a problem, that trim() returns modified string, but does not effect the value of the sting itself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: XML comparison for checking whether same or different window applications I have two XML file sitemap.xml and mouse.xml which look like below.Here the thing is that
i need to compare sitemap.xml with mouse.xml in such a way that the tag
<Name></Name>.I need to compare both xml file whether the content
coming inside <Name></Name> tag is same or not in c# code
Here the <Name></Name> tag are different means sitemap.xml contain "test
" and mouse.xml contain "exam".
<?xml version="1.0" standalone="yes"?>
    <ObjectClass>
    <Image>00000000-0000-0000-0000-000000000000</Image>
    <Description />
    <Name>test</Name>
    <DefaultApp>00000000-0000-0000-0000-000000000000</DefaultApp>
    <ID>464930eb-e518-4d0c-b80b-184c97c7dd27</ID>
    <ParentClassID>00000000-0000-0000-0000-000000000002</ParentClassID>
    <DynamicPopulation>false</DynamicPopulation>
    <TimeoutPeriod>0</TimeoutPeriod>
    <Persist>false</Persist>
    <ClassVersion>1</ClassVersion>
    <Reinitialize>false</Reinitialize>
  </ObjectClass>

this is mouse.xml
 <?xml version="1.0" standalone="yes"?>
    <ObjectClass>
    <Image>00000000-0000-0000-0000-000000000000</Image>
    <Description />
    <Name>exam</Name>
    <DefaultApp>00000000-0000-0000-0000-000000000000</DefaultApp>
    <ID>464930eb-e518-4d0c-b80b-184c97c7dd27</ID>
    <ParentClassID>00000000-0000-0000-0000-000000000002</ParentClassID>
    <DynamicPopulation>false</DynamicPopulation>
    <TimeoutPeriod>0</TimeoutPeriod>
    <Persist>false</Persist>
    <ClassVersion>1</ClassVersion>
    <Reinitialize>false</Reinitialize>
  </ObjectClass>

A: Try the Microsoft XML diff API.

A: Try,
 XmlDocument doc1 = new XmlDocument();
    XmlDocument doc2 = new XmlDocument();
    doc1.Load(@"c:\myproject\WindowsApplication1\sitemap.xml");
    doc2.Load(@"c:\myproject\WindowsApplication1\mouse.xml");

    XmlNodeList a = doc1.GetElementsByTagName("Name");
    XmlNodeList b = doc2.GetElementsByTagName("Name");
    if (a.Count == 1 && b.Count == 1)
    {
        if (a[0].InnerText == b[0].InnerText)
            Console.WriteLine("Equal");
        else
            Console.WriteLine("Not Equal");
    }

A: XMLUnit is awesome for xml comparison. Primarily Java based but there is a .Net port there too (I've only used the Java one): http://xmlunit.sourceforge.net/


text:
Q: If I run an application, ~/.application is created. Is it safe to delete? How do I stop it for creating such folders...
eg..if I open the application say - Stellarium, then
in the home - a folder ".Stellarium" gets created
This was not being created before...What can do to prevent such folders on being created. I am using Ubuntu 13.10 since 2 years.

A: Those folders definitely were created before, but you probably hit Ctrl+H accidentally (the key combination to toggle visibility of folders and files with a name starting with a dot), so you can see them now.
What these folders are for
Usually applications store all kinds of (user specific-) settings & configuration files, profiles etc. in these hidden folders. In general, you can remove them safely, but then possibly changed settings, stored in such folders, will be lost. Also: on the next run, they simply will be re- created.
Be careful
Deleting these folders can however have bigger consequences: if you delete e.g. the folder .thunderbird, all your mail wil be lost.
Possible reasons to remove these directories

*

*Not really your question, but related: many times in case an application starts acting weird or with errors, removing (or temporarily renaming-) this folder is the first thing you would like to try, to force the application to recreate its settings file(s).

*Sometimes settings files of newer application versions are incompatible with older settings files. If you install a newer version of an application (e.g. when you upgrade your Ubuntu version), remaining outdated settings files can act up.

*If you have application settings of applications you don't use anymore.

A: This folder contains your settings and preferences for that particular application. You can delete it if you really want, but the application will start with default settings.
If you are seeing these folders and don't want to, you have probably selected Show Hidden Folders. Try pressing CTRL +H to toggle this.


text:
Q: Basic Drag and Drop uitableview Cell in another view I just want to tableview drag in any uiview then call one web services.
Please help me out. And if it's possible I'd like to enable the drag by a long press on tableview.
in table view
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:cell action:nil];
        longPress.delegate = self;
        [cell addGestureRecognizer:longPress];

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer{
    if([gestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]){
        [gestureRecognizer addTarget:self action:@selector(longGestureAction:)];
    }
    return YES;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer{
    return YES;
}

-(void)longGestureAction:(UILongPressGestureRecognizer *)gesture{
    UITableViewCell *cell= (UITableViewCell *)[gesture view];

   }


text:
Q: How to accommodate image shape according to image view? I have an ImageView with rounded corners, but when I add the bitmap to it, the image doesn't have rounded corners
I have a module where I capture images, I want these images to always take the shape of the ImageView, in this case, the rounded corners, as seen in the image below.

XML (this is the card)
`
<LinearLayout
    android:layout_width="185dp"
    android:layout_height="185dp"
    android:background="@drawable/bg_rounded_corners"
    android:orientation="vertical">

        <ImageView
            android:id="@+id/im_producto"
            android:layout_weight=".8"
            android:layout_height="0dp"
            android:layout_width="fill_parent"
            android:layout_gravity="center"
            android:scaleType="fitXY"
            android:background="@drawable/bg_rounded_corners_top"
            android:orientation="horizontal"/>

        <Button
            android:id="@+id/btn_eliminar_fotografía"
            android:layout_width="match_parent"
            android:layout_height="0dp"
            android:layout_weight=".2"
            android:text="Eliminar"
            android:background="@drawable/bg_rounded_corners_bottom"
            android:backgroundTint="@color/purple_two"
            android:textSize="17sp"
            android:textStyle="bold"/>

</LinearLayout>

`
JAVA
in the java part, I just use the set bitmap method and add the bitmap of the image


text:
Q: What is the physics behind the high damping capacity of magnesium? the definition of Damping Capacity is:
"The ability of metal to absorb energy (stress energy) by converting it into heat" .And I cannot interpret why some metals absorb the applied stress energy on them and the other metals not !! So I cannot understand this definition.


text:
Q: Open SAS Enterprise Guide 7.1 egp file using Excel VBA Does anyone know how I can open a SAS EG 7.1 egp file using Excel VBA? Any help would be much appreciated.

A: It is much easier to deal with as C#. I have to disagree with Joe here but I don't think any part of VBA is .NET: it is old COM code.
Let me go through how to handle:

*

*Rename the EGP file to a .zip extension. That will let you look at it to understand the structure.

*Use .NET Core (2.2 is latest) and Visual Studio Code (free). Core will allow you to run it on any system and is MS' direction.

*Look up how to read a zip file using C#. Here is some code to get you started:

       private XDocument ReadZipFile(string testFile, bool writeFile)
        {
            var xd = new XDocument();
            using (FileStream zipToOpen = new FileStream(testFile, FileMode.Open))
            {
                using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Read))
                {
                    var entry = archive.Entries.First(x => x.Name.ToLower() == "project.xml");
                    using (var sr = new StreamReader(entry.Open(), Encoding.UTF8))
                    {
                        var xmlFile = sr.ReadToEnd();
                        if (writeFile)
                        {
                            using (var sw =
                                new StreamWriter(@"X:\Data\projects\Savian.SasWorkflowReader\Data\project.xml"))
                            {
                                sw.Write(xmlFile);
                            }
                        }
                        xd = XDocument.Parse(xmlFile);
                    }
                }
            }
            return xd;
        }

*Parse it once it is in text format using RegEx.

A: Enterprise Guide is scriptable using .Net, which is fortunate as VBA also uses similar syntax to .Net for the most part, though it's not actually .Net.  You may have an easier time using VB.Net or Powershell than VBA, but the principle should be at least roughly the same if you're aware of how to call .Net from Excel/VBA (see this question/answer for starters).  (I highly recommend Powershell, as it's easy to learn and very much suited for this sort of thing.)
You can get a quick start with Chris Hemedinger's guide, though that's quite old (I think that's 4.3), but the concepts and names should still be at least (mostly) the same.
You can also schedule a task inside Enterprise Guide using the windows scheduler (File-> Schedule [projname]).  What it does when you tell it to do that is create a .VBS file (visual basic script), which you can then open to see how it works, and cannibalize the code for your own purposes.


text:
Q: Calling a structure method inside a non-default structure constructor  I have this very simple example that I am using to learn structs in C#:
struct ScreenPosition
{
    // These are the two private members of the structure
    private int x;
    private int y;

    private int RangeCheckedX(int xPos)
    {
        if (xPos < 0 || xPos > 1280)
        {
            throw new ArgumentOutOfRangeException("X");
        }
        return xPos;
    }

    private int RangeCheckedY(int yPos)
    {
        if (yPos < 0 || yPos > 1024)
        {
            throw new ArgumentOutOfRangeException("Y");
        }
        return yPos;
    }

    // Declaring the non-default constructor
    public ScreenPosition(int X, int Y)
    {
        this.x = RangeCheckedX(X); // ERROR HERE
        this.y = RangeCheckedY(Y); // ERROR HERE
    }

    // Declaring  the property X - Follows a syntax. See the C# quick reference sheet
    public int X
    {
        get
        {
            return this.x;
        }

        set
        {
            this.x = RangeCheckedX(value);
        }
    }
    // Declaring  the property X - Follows a syntax. See the C# quick reference sheet
    public int Y
    {
        get
        {
            return this.y;
        }

        set
        {
            this.y = RangeCheckedY(value);
        }
    }
}

I am getting this error at the "ERROR HERE" comment lines:

The 'this' object cannot be used before all of its fields are assigned to

Is it illegal to call a structure method in the non-default constructor to assign values to the structure members?

A: You can make those methods static and it will work, but you cannot call a non-static method until all the fields have been assigned.

A: It is not allowed to call methods on structs until all fields (properties) are populated.
I know its a hack but this would work.
 struct ScreenPosition
{
    // These are the two private members of the structure
    private int x;
    private int y;

    private int RangeCheckedX(int xPos)
    {
        if (xPos < 0 || xPos > 1280)
        {
            throw new ArgumentOutOfRangeException("X");
        }
        return xPos;
    }

    private int RangeCheckedY(int yPos)
    {
        if (yPos < 0 || yPos > 1024)
        {
            throw new ArgumentOutOfRangeException("Y");
        }
        return yPos;
    }

    // Declaring the non-default constructor
    public ScreenPosition(int X, int Y)
    {
        this.x = X;
        this.y = Y;
        this.x = RangeCheckedX(X);
        this.y = RangeCheckedY(Y);
    }

    // Declaring  the property X - Follows a syntax. See the C# quick reference sheet
    public int X
    {
        get
        {
            return this.x;
        }

        set
        {
            this.x = RangeCheckedX(value);
        }
    }
    // Declaring  the property X - Follows a syntax. See the C# quick reference sheet
    public int Y
    {
        get
        {
            return this.y;
        }

        set
        {
            this.y = RangeCheckedY(value);
        }
    }
}

A: GBegen has the right idea - make the range check methods static.
Not only will this fix the problem, but it'll make the code clearer, too: the methods don't rely on the state of the structure at all, and they're not acting polymorphically, so they shouldn't be instance methods.

A: You could set each of the fields to zero before validating the inputs. This makes some sense because the default constructer will set them to zero anyway, so that's a case that has to be handled in your program anyway. Once the values are set, you can call whatever methods you want, even in the constructor.
But the correct solution is what everyone else is saying: make the range checks static methods. In fact, in this case they are pure functions (no side effects and operating only on the parameters rather than static or instance fields). Pure functions can always be static. And static pure functions are chocolate-covered-awesome from the perspectives of debugging, multi-threading, performance, etc.


text:
Q: How to pass an index to the name of an object in a for loop in R? I am trying to figure out how to have R accept my index within a for loop. As a simple example, I would like each new matrix to have a name index that is different than the one before:
for(i in 1:5){
new.matrix.i <- matrix(NA, nrow = i, ncol = i)
}

From this loop, I know it obviously doesn't work, but was wondering how I could create 5 new matrices, with the first being a one-by-one matrix of NA, and the second a two-by-two matrix of NA's, all the way to a five-by-five matrix with all NA's.
In other words, I am wondering how to have R treat

new.matrix.i

with i as a dynamic name instead of just a regular name for a matrix? Thanks!

A: We can use lapply to create a list of matrices
lst <- lapply(1:5, function(i)  matrix(NA, nrow = i, ncol = i))

Or we proceed with for loop, initialize the new.matrix.i as a list
new.matrix.i <- vector("list", 5)
for(i in 1:5){
    new.matrix.i[[i]] <- matrix(NA, nrow = i, ncol = i)
}

NOTE: It is better not to create multiple objects in the global environment.  A list of matrix (or other objects) are easier and convenient to use


text:
Q: What are the different licenses available in GitHub Android library? Recently i added some code from GitHub repository for my android application.Though it's a Open Source Library, it shows different licenses like MIT,Apache etc... I am trying to get information about licenses. Can someone give notes about different licenses and how to use it?

A: https://help.github.com/articles/open-source-licensing/ provides you way to use any of the available licence for projects.
There are so many types of software licences present.

Microsoft Reciprocal License

A Microsoft open license and a free software license . Allows for distribution of derived code so long as the modified source files are included and retain the Ms-RL.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: True
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

The Code Project Open License (CPOL)

The main points subject to the terms of the License are:
Source Code and Executable Files can be used in commercial applications;
Source Code and Executable Files can be redistributed; and
Source Code can be modified to create derivative works.
No claim of suitability, guarantee, or any warranty whatsoever is provided. The software is provided "as-is".
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: True
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

The Common Development and Distribution License (CDDL)

Based on the Mozilla Public License (MPL) that makes it more applicable for use outside the Mozilla Foundation.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: True
Provides an explicit patent license: True
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

The Microsoft Public License (Ms-PL)

Used by Microsoft. Compiled derived code can be distributed, for both commercial and non-commercial use. If the source code is to be redistributed then a complete copy of this license must be included in the redistribution.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: True
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

The Mozilla Public License 1.1 (MPL 1.1)

Used by Mozilla and Firefox, among others. The patent clauses are not acceptable to some.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: True
Provides an explicit patent license: True
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

The Common Public License Version 1.0 (CPL)

Derived from the IBM Public License and influenced by the Mozilla Public License, and used by some Microsoft projects on SourceForge.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: True
Provides an explicit patent license: True
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

The Eclipse Public License 1.0

A newer version of the Common Public License that is in some cases more acceptable to business.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: True
Provides an explicit patent license: True
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

The MIT License

A very old license with essentially no restrictions on the use of the code. It also provides very little in the way of protection for authors or users. It is the same as the BSD license without the 'no endorsement' clause.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: False
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

The BSD License

A very old license with essentially no restrictions on the use of the code. It also provides very little in the way of protection for authors or users. It is the same as the MIT license except that it includes a clause preventing the use of the author's name for endorsement.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: False
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

The Apache License, Version 2.0

Slightly more restrictive (but still very open) version of the BSD or MIT license that adds patent clauses. Read carefully.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: True
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

The Creative Commons Attribution-ShareAlike 2.5 License

A license that requires a link be visible on works that use this license. "Share alike" is what it sounds like, you can share this work as long as that work has a license similar to this one.
It is recommended that this license not be used for software.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: False
Can be used in proprietary (closed source) applications: False
Is a viral licence: True

The zlib/libpng License

A license with an emphasis on freedom of use and re-use, with a few restrictions.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: False
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

A Public Domain dedication

Not a license, but a dedication to the public domain. All rights are given up and anyone can do anything they wish with the code. Please note this is not a license and provides no guarantees for the user and no indemnities for the author.
Provides copyright protection: False
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: False
Can be used in proprietary (closed source) applications: True
Is a viral licence: False

The Creative Commons Attribution 3.0 Unported License

This license lets others distribute, remix, tweak, and build upon your work, even commercially, as long as they credit you for the original creation. It is recommended that this license not be used for software.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: False
Can be used in proprietary (closed source) applications: False
Is a viral licence: True

The Creative Commons Attribution-Share Alike 3.0 Unported License

A license that requires a link be visible on works that use this license. "Share alike" is what it sounds like; you can share this work as long as that work has a license similar to this one. It is recommended that this license not be used for software.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: False
Can be used in proprietary (closed source) applications: False
Is a viral licence: True

The Creative Commons Attribution-NoDerivatives 3.0 Unported

A license which specifies that if you remix, transform, or build upon the material, you may not distribute the modified material. It is recommended that this license not be used for software.The Creative Commons Attribution-NoDerivatives 3.0 Unported
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: False
Provides an explicit patent license: False
Can be used in proprietary (closed source) applications: False
Is a viral licence: True

The GNU Lesser General Public License (LGPLv3)

A derivative of the GPL that was intended to allow non-GPL code to work with, and call GPL code. The author of this license asks that you only use this license if you are licensing functionality already commonly available.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: True
Provides an explicit patent license: False
Can be used in proprietary (closed source) applications: True
Is a viral licence: True

The GNU General Public License (GPLv3)

A common but misunderstood license. This allows developers to freely use the software as long as they use the same (or an even less restrictive) license for parts of the program that they wrote themselves. Viral in nature. Read carefully and make sure you understand the implications of using this license. Unacceptable to many.
You can write commercial software using software licensed with the GPL, but you cannot write proprietary software (meaning software for which the code is not freely available). You can sell GPL code, even if it's already being given away, or you can sell services attached to the code such as support contracts.
Any software written using GPL'd code must itself be licensed using the GPL (or less restrictive license) meaning it cannot be proprietary. This means that developers writing commercial software may not be able to use GPL code if they do not wish to provide the code.
One important note: The GPL doesn't require you to publish the source to the world. Only the recipient of the software needs to have the source. If you have a customer, write GPLed software for a specific purpose and only give the binary to this customer, then only this customer must have access to the source code, not everybody and not the public; just the recipient of the (binary) code. This is in full agreement to the GPL. The main advantage is to play with open cards and not create a "blackmail" situation.
Provides copyright protection: True
Can be used in commercial applications: True
Bug fixes / extensions must be released to the public domain: True
Provides an explicit patent license: False
Can be used in proprietary (closed source) applications: False
Is a viral licence: True


text:
Q: graphql + apollo-server-express, how to handle auth error in express authMiddleware? I can't figure out how to handle auth error in my authMiddleware function.
Here is my authMiddleware function with traditional express way error handling.
const jwt = require('jsonwebtoken');
const { appConfig } = require('../config');

function authMiddleware(req, res, next) {
  let token;
  const parts = req.headers.authorization.split(' ');

  if (parts.length === 2) {
    const schema = parts[0];
    const credentials = parts[1];

    if (/^Bearer$/i.test(schema)) {
      token = credentials;
    } else {
      // throw new Error();
      next(new Error('credentials_bad_scheme: Format is Authorization: Bearer [token]'));
    }
  }

  try {
    const { user } = jwt.verify(token, appConfig.JWT_SCERET);
    req.user = user;
  } catch (error) {
    // console.log(error);
    next(error);
  }
  next();
}

exports.authMiddleware = authMiddleware;

But with apollo-server-express and graphql system. The error passed into next function does not work fine. Which means it seems the express error handling way is not working any more when use graphql tool stack.
The error in authMiddleware will not pass below express error handling middleware
app.use((err, req, res) => {
  console.log('error handler: ', err);
});

If I use return res.status(401).json({code: 1001, msg: 'Authorization failed'}) or throw new Error('xxx') in catch when auth failed. The request will stop here forever which means will never go down to graphqlExpressHandler. In order to let request go down to graphqlExpressHandler, only thing I can do for the errors is to use console.log to print them.
And there is no way to use express-jwt unless method or credentialsRequired property. Because when use graphql, there is only one route named '/graphql'. So, you can't unless /graphql route
One way to solve this is: make restful api for auth and handle it in traditonal way. Make graphql api for data query.

A: Late answer, but may help someone facing the same issue.
Here is how we solved it:
graphql + apollo-server-express expose only the /graphql route, so the easy and good way is to expose authentication endpoint as a graphql mutation, and do token validation (what your authMiddleware does) in the context function passed to ApolloServer instance.
Example:

*

*Define token mutation.

// graphql.ts
import { gql } from 'apollo-server-express';
import AuthnHandler from './handlers/authn_handler';

export const typeDefs = gql`
  type Mutation {
    token(username: String, password: String): String
  }
`

const authnHandler = new AuthnHandler();

export const resolvers = {
  Mutation: {
    token: authnHandler.tokenResolver
  }
};

*Define token mutation resolver that validates credentials and issues token.

// handlers/authn_handler.ts
import { AuthenticationError } from 'apollo-server-express';

export default class AuthnHandler {
  public async tokenResolver(parent: any, args: any, context: any, info: any): Promise<any> {
    const username = args.username;
    const password = args.password;
    // pseudo-code here, replace with your token issuing implementation.
    // if credentials are valid, return Promise.resolve(token);
    // else throw new AuthenticationError('Invalid credentials.');
  }
}

*Define context function that validates token in authorization header (what your authMiddleware function does).

// server.ts
import express from 'express';
import { ApolloServer, ApolloServerExpressConfig } from 'apollo-server-express';
import { typeDefs, resolvers } from './graphql';
import { authMiddleware } from './auth_middleware';

const expressApp = express();

const apolloServer = new ApolloServer({
  typeDefs,
  resolvers,
  context: authMiddleware
} as ApolloServerExpressConfig);

apolloServer.applyMiddleware({ app: expressApp });

expressApp.listen(3000, () => {
  console.log('server listening on port 3000');
});

Your authMiddleware function signature changes as per the context function requirement, and in this case it returns the request object itself when success.
// auth_middleware.ts
const jwt = require('jsonwebtoken');
const { appConfig } = require('../config');

function authMiddleware({ req }) {
  let token;
  const parts = req.headers.authorization.split(' ');

  if (parts.length === 2) {
    const schema = parts[0];
    const credentials = parts[1];

    if (/^Bearer$/i.test(schema)) {
      token = credentials;
    } else {
      throw new Error();
    }
  }

  try {
    const { user } = jwt.verify(token, appConfig.JWT_SCERET);
    req.user = user;
  } catch (error) {
    throw new Error();
  }
  return { req };
}

exports.authMiddleware = authMiddleware;

The authentication section in the apollo-server documentation provides a detailed explanation of this way of implementation.


text:
Q: How to make Parcel build without JavaScript We have a small static site based on Tailwind, PostCSS and PostHTML that doesn't contain any JS/TS code or <script>-tag whatsoever.
However, building with Parcel 2.6.0 yields a 19kb large javascript file (+ a 28kb large map file) in the /dist-folder that is included in the generated index.html, which is pointless and generates unnecessary payload and requests.
I could not find anything in the documentation regarding this, also simply setting "transformers" to false or similar in .parcelrc did not work to disable this behaviour.
How can i get a generated bundle in the /dist-folder free of any JavaScript?


text:
Q: Filtering numbers above a certain threshold for multiple columns in R I have a data set with with 600+ variables and I would like to only keep the rows where the values in multiple columns are above a certain threshold, in my case >= 5,000,000.
For a single column I would filter like this:
df <- df %>%
  filter(variable.2019.03 >= 5000000)

I could do it for multiple columns like this:
df <- df %>%
  filter(variable.2019.03 >= 5000000 & variable.2019.04 >= 5000000 &
         variable.2019.05 >= 5000000)

However, I want to do this for 30+ columns so I was hoping there is a more elegant way. My understanding is that I should be able to do this using the filter() function in combination with if_all(), but I was only able to find example where these functions are used to filter character columns nor numeric ones. Similar to the examples here, I have tried:
  filter(if_all(>= 5000000), variable.2019.03:variable.2022.03)

which only yielded this error message:
Error: unexpected '>=' in:
"df <- df %>%
  filter(if_all(>="

Any suggestions on achieving the desired outcome?

A: We need to specify the columns (.cols) within the if_all.  By default it is everything(), so we change to match only the columns that starts with (^) 'variable' followed by a dot (.), four digits (\\d{4})..., within the matches (that uses regular expression to match the column names)
library(dplyr)
df %>%
   filter(if_all(matches('^variable\\.\\d{4}\\.d{2}$'), ~ .x >= 5000000))

If the columns are adjacent, we can use :
df %>%
    filter(if_all(variable.2019.03:variable.2022.03, ~ .x >= 5000000))


text:
Q: Having an issue getting an ActionResult that uses parameters to return specific queryable items I am trying to get this Action Result to use the parameters given (Year, Qtr, Div) and only return those results. I use something similar to this in other ActionResults, but they do not return results in Json. I am not quite sure what I need to do in order to get this result to return only the results that match the parameters given. What it is doing is returning all records instead of filtering them by the parameters.
    public ActionResult GLAcctsISDs_Read([DataSourceRequest]  DataSourceRequest request, int? Year, int? Qtr, string Div)
    {
        var glacctsisds = db.GLAcctsISDs.AsQueryable();
        if (Year.HasValue)
            glacctsisds = glacctsisds.Where(x => x.Year == Year);
        if (Qtr.HasValue)
            glacctsisds = glacctsisds.Where(x => x.Qtr == Qtr);
        if (!string.IsNullOrEmpty(Div))
            glacctsisds = glacctsisds.Where(x => x.Div == Div);

        DataSourceResult result = glacctsisds.ToDataSourceResult(request, gLAcctsISD => new {

            ID = gLAcctsISD.ID,
            Div = gLAcctsISD.Div,
            Year = gLAcctsISD.Year,
            Qtr = gLAcctsISD.Qtr,
            GLAcct = gLAcctsISD.GLAcct,
            GLDescr = gLAcctsISD.GLDescr,
            TBDebit = gLAcctsISD.TBDebit,
            TBCredit = gLAcctsISD.TBCredit,
            IncExpAdjDebit = gLAcctsISD.IncExpAdjDebit,
            IncExpAdjCredit = gLAcctsISD.IncExpAdjCredit,
            AdlTrialDebit = gLAcctsISD.AdlTrialDebit,
            AdjTrialCredit = gLAcctsISD.AdjTrialCredit,
            RemainExpDebit = gLAcctsISD.RemainExpDebit,
            PendingIncomeCredit = gLAcctsISD.PendingIncomeCredit,
            ProjRemainExpDebit = gLAcctsISD.ProjRemainExpDebit,
            NetIncomeCredit = gLAcctsISD.NetIncomeCredit,
            DivGLNotes = gLAcctsISD.DivGLNotes
        });

        return Json(result);
    }

Thanks in advance for the help.

A: try serializing "result" object to json.
string jsonString = Newtonsoft.Json.JsonConvert.SerializeObject(result);

return Json(jsonString);

A: For anyone who wants to know how to do this here you go:
Parameters are passed in to the controller as year, qtr, and div:
 public ActionResult KenodGLAcctISDList( int? year, int? qtr, string div)
    {
        ViewBag.YYear = year;
        ViewBag.QQtr = qtr;
        ViewBag.DDiv = div;
        return View();
    }

    public ActionResult GLAcctsISDs_Read([DataSourceRequest]DataSourceRequest request)
    {

        var glacctsisds = db.GLAcctsISDs.AsQueryable();
        DataSourceResult result = glacctsisds.ToDataSourceResult(request, gLAcctsISD => new {

            ID = gLAcctsISD.ID,
            Div = gLAcctsISD.Div,
            Year = gLAcctsISD.Year,
            Qtr = gLAcctsISD.Qtr,
            GLAcct = gLAcctsISD.GLAcct,
            GLDescr = gLAcctsISD.GLDescr,
            TBDebit = gLAcctsISD.TBDebit,
            TBCredit = gLAcctsISD.TBCredit,
            IncExpAdjDebit = gLAcctsISD.IncExpAdjDebit,
            IncExpAdjCredit = gLAcctsISD.IncExpAdjCredit,
            AdlTrialDebit = gLAcctsISD.AdlTrialDebit,
            AdjTrialCredit = gLAcctsISD.AdjTrialCredit,
            RemainExpDebit = gLAcctsISD.RemainExpDebit,
            PendingIncomeCredit = gLAcctsISD.PendingIncomeCredit,
            ProjRemainExpDebit = gLAcctsISD.ProjRemainExpDebit,
            NetIncomeCredit = gLAcctsISD.NetIncomeCredit,
            DivGLNotes = gLAcctsISD.DivGLNotes
        });

        return Json(result);
    }

Then passed to the view as Viewbags and sorted by the KendoUI Grid code
.Read(read => read.Action("GLAcctsISDs_Read", "KendoGLAcctISD"))
      .Filter(filter =>
              {
                  filter.Add(f => f.Year).IsEqualTo(ViewBag.YYear);
                  filter.Add(f => f.Qtr).IsEqualTo(ViewBag.QQtr);

              })
      .Update(update => update.Action("GLAcctsISDs_Update", "KendoGLAcctISD"))


text:
Q: Global operator along a single dimension in Keras? Let's say I have a dataset comprising greyscale videos. The length and size of each video can vary so I am representing the data in three dimensions via the following shape:

Batch size
time
y
x
channels

None
None
None
None
1

I want to extract features (say 16 of them) from the temporal dimension while keeping the same spatial dimensions, which would give me the following output shape:

Batch size
y
x
filters

None
None
None
16

Notably, the shape of the data has been reduced by one dimension. In my head, I should be able to accomplish this with a Conv3D operator (feature generation) followed by some aggregating operation (global/average pooling or some linear operator) over the time dimension only. The resulting shape would be (None, 1, None, None, 16) which I believe I could reduce to (None, None, None, 16) using this answer.
My problem is that I cannot figure out how to apply any of Keras's global operators along a single dimension. Since the size of the time dimension is unknown, I cannot specify the window size (unknown, 1, 1) for a MaxPooling or convolutional layer that would span the entire time dimension. On the other hand, the GlobalMaxPooling layer doesn't accept an argument for specifying which dimensions to operate on.
Do I have to implement some complicated custom layer for this, or does a solution already exist? I've taken a look at the Reshape layer with MaxPooling1D, but I run into the same problem of not knowing the size of the x and y dimensions to reassemble the spatial structure after the pooling operation.

A: I believe you could do something like following if you don't want using custom layer:
x = Input(shape=(Batch_size, time, y, x, 1))
# Process data wrt time and spaciall info, as many layer as you want
x = Conv3D(filters_num_0, kernel_size_0, strides=1, padding="same", activation=activation_0)(x) # (Batch_size, time, y, x, filters_num_0)
x = Conv3D(filters_num_1, kernel_size_1, strides=1, padding="same", activation=activation_1)(x) # (Batch_size, time, y, x, filters_num_1)
# # Aggregate channel info
x = Conv3D(1, kernel_size_2, strides=1, padding="same", activation=activation_2)(x) # (Batch_size, time, y, x, 1)
# Reshape for dimension reduce
x = Reshape(target_shape=(Batch_size, y, x, time))(x)
# Aggregate time info
x = Conv2D(16, kernel_size_3, strides=1, padding="same", activation=activation_3 ) # (Batch_size, y, x, 16)

Using custom layer to doing for global average pool across time:
class GlobalAvgPoolAcrossTime(layers.Layer):
    def __init__(self, **kwargs):
        super(GlobalAvgPoolAcrossTime, self).__init__(**kwargs)

    # (Batch_size, time, y, x, channels) -> (Batch_size, 1, y, x, channels)
    def call(self, inputs):
        return keras.backend.mean(inputs, axis=1, keepdims=True)

x = Input(shape=(Batch_size, time, y, x, 1))
# Process data wrt time and spaciall info, as many layer as you want
x = Conv3D(filters_num_0, kernel_size_0, strides=1, padding="same", activation=activation_0)(x) # (Batch_size, time, y, x, filters_num_0)
x = Conv3D(filters_num_1, kernel_size_1, strides=1, padding="same", activation=activation_1)(x) # (Batch_size, time, y, x, filters_num_1)
x = GlobalAvgPoolAcrossTime()(x) # (Batch_size, 1, y, x, filters_num_1)
# Reshape for dimension reduce
x = Reshape(target_shape=(Batch_size, y, x, filters_num_1))(x)
x = Conv2D(16, kernel_size_2, strides=1, padding="same", activation=activation_3 ) # (Batch_size, y, x, 16)


text:
Q: What can be done to stop losing resources and unify Mercurial and Git? Both Mercurial and Git were created as a replacement for the same program and to solve the same problem which you can read about in Martin Beckett's answer to How did Git and Mercurial develop so similarly at the same time? question.
These two tools are very similar and borrow from each other according to Scott Chacon in his
Hg and Git: Can't we all just get along? presentation at PyCon 2010.
I think we, the people, do waste huge amount of resources by having these two tools which do the same, yet operate differently. Is it possible to unify Mercurial and Git and stop wasting our resources? What actions should be taken?

A: The problem with Git as summarized by Joel Spolsky is that Linus Torvalds refuses to add any features to Git that would benefit Windows. So you'd get less traction with Windows guys if you merge toward the Git arm. And Torvalds evidently doesn't want to support Windows stuff so merging toward Mercurial wouldn't work either. So what do we do? Meet in the middle? How and where?

A: You'd have a lot more of a chance if they weren't so similar. No one is screaming out for a combination. This is the first time I've heard an argument that the existence of two products wastes anything and you haven't provided evidence of that.
The only successful open-source merges I can think of off the top of my head are Rails with Merb and Selenium with WebDriver. In both cases, this was because the two products solved very different problems and people were crying out for a product that solved both.


text:
Q: How remove paddings and align to start position bars in chartjs? How remove paddings beetwen bars and align from start(fix all bars to left) in chartjs?
I know about empty strings in labels for fill empty area, but i need correct way to resolve this problem (if it is)enter image description here


text:
Q: WAF Not Blocking Hitleap I've tried every possible Filter for blocking hitleap and the fake traffic is still getting through:
 Header 'user-agent' contains: "HitLeap" after removing whitespace characters.

 Header 'user-agent' contains: "hitleap" after converting to lowercase.

 Header 'user-agent' matches exactly to: "HitLeap Viewer 2.8".

 Header 'user-agent' contains: "HitLeap".

I just don't get it because the User Agent is quite clearly "HitLeap Viewer 2.8"
I've assigned all the rules properly and added it to my cloudfront distribution. What am I missing here?


text:
Q: RotationModifier revert sprite to initial value. how to avoid it? I'm trying to rotate sprite of certain angle and keep it in that way. I simply call sprite.registerEntityModifier(new RotationModifier(5,0,180))
This rotates sprite and reverts it to initial (0) angle after finish.
I was also trying to call sprite.setRotation() in onModifierFinish() method, it didn't helped.
Anyway - what is the proper way to rotate sprite / keep effects of modifier after it finish?

A: Resolved. I was unnecesarry attaching physics to this sprite. Sprite without physics rotates as i wanted and stays it this way


text:
Q: make button clickable below recycler view Hi I have a layout as follows:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:animateLayoutChanges="true"
    android:orientation="vertical">

    <com.widgets.AppSwipeRefreshLayout
        android:id="@+id/swipe_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:fitsSystemWindows="true">

        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <com.widgets.AppRecyclerView
                android:id="@+id/recyclerView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:scrollbars="vertical"
                app:layoutManager="androidx.recyclerview.widget.GridLayoutManager" />

            <androidx.appcompat.widget.AppCompatButton
                android:elevation="0dp"
                android:id="@+id/test"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="left|start|center_vertical"
                android:clickable="true"
                android:descendantFocusability="beforeDescendants"
                android:focusable="true"
                android:focusableInTouchMode="true"
                android:text="TEST" />

        </FrameLayout>

    </com.widgets.AppSwipeRefreshLayout>

</LinearLayout>

My recycler view has 2 types of items, 1 is a regular item, 1 an item with transparent background to show the button. My problem is, when transparent item is screen and button is visible, button doesn't receive click events. I thought it's probably because of elevation and changed elevation, but it didn't solve the issue. How can I make button to receive click events?


text:
Q: Showing $\bigcup_{k}\{(a_{1},...,a_{k}):a_{j}\in [0,1]\cap \mathbb{Q} ,\sum^{k} a_{j}=1\}$ is countable Showing  $M=\bigcup_{k}\{(a_{1},...,a_{k}):a_{j}\in [0,1]\cap \mathbb{Q} ,\sum^{k}  a_{j}=1\}$ is countable.
I find this hard to believe because say for fixed k and any $b,c\in [0,1]\cap \mathbb{Q}$, we have $(\frac{1}{k-2},...,\frac{1}{k-2},b,c)\in M$. So I can embed in M any element of $ P([0,1]\cap \mathbb{Q})$,  which is uncountable.
thanks

A: Fix $k$. The set $\{(a_1,...,a_k); a_j\in [0,1]\cap \mathbb{Q}, \sum_ja_j=1\}\subset \mathbb{Q}^k$. Therefore it is countable. Countable union of countable sets in countable.

A: The cartesian product of two countable sets is countable (think of the zig-zag-across-numerators-and-denominators argument used to show that $\mathbb Q$ itself is countable). Therefore $\mathbb Q^2$, $\mathbb Q^3=\mathbb Q^2\times \mathbb Q$, $\mathbb Q^4=\mathbb Q^3\times \mathbb Q$, etc. are countable. Each $(a_1,\ldots,a_k)$ is certainly in thge countable set  $\mathbb Q^k$. Hence $M$ is the countable union of countable sets, which is once again countable (by the same argument that countable times countable is countable: Each element is in at least one way the $n$th element of the $m$th set on the right ...).


text:
Q: Use player's score as amount in /give I have a objective called DIFF. When a player hits a button, I would like to give them items based on their DIFF count multiplied by two. For instance: if DIFF is 1 then give them 2 items, if DIFF is 2 then give them 4 items, etc.
My current command (without multiplication):
/give @p minecraft:emerald {"score":{"name":"@p","objective":"DIFF"}}

But it says "score" is not a valid number. How can I use the player's score to determine the number of items when using /give?

A: Yeah, commands don't work like that.  They're highly structured, and don't allow you to replace expected integers with expressions.  You're going to have to do this the hard way.  You'll also want to be using 1.9 for command block simplicity, although this solution will also work in 1.8 with well structured 20Hz clocks.
First, we need to set up another scoreboard objective that represents the number of items to give; let's call it NumItems:
/scoreboard objectives add NumItems dummy

We also need an intermediate scoreboard objective to avoid race conditions in the latter stages.  This objective is what is going to multiply the DIFF score, so we'll call it Multiplier:
/scoreboard objectives add Multiplier dummy

Now, when a player hits the button, they need their NumItems score set to two times their DIFF score.  We do that with the following commands:
/scoreboard players set @p Multiplier 2
/scoreboard players operation @p Multiplier *= @p DIFF
/scoreboard players operation @p NumItems = @p Multiplier

Great, now we have a number of items to give, we just need to give them... one at a time.  Well, we can be a little more efficient than that, but we can't just give an arbitrary number of items.  We'll break it down into giving 1 item, 10 items, and a stack of 64 items.  Create a chain of command blocks off a repeating command block (or use a 20Hz clock) for these commands, edited to meet your needed specifics:
/give @a[score_NumItems_min=64] <item> 64 [...]
/scoreboard players remove @a[score_NumItems_min=64] NumItems 64
/give @a[score_NumItems_min=10] <item> 10 [...]
/scoreboard players remove @a[score_NumItems_min=10] NumItems 10
/give @a[score_NumItems_min=1] <item> 1 [...]
/scoreboard players remove @a[score_NumItems_min=1] NumItems 1

This is only one possible distribution of give values, and can easily be improved by choosing a geometric sequence like 2n (1, 2, 4, 8...), which should complete all give operations for item counts up to 128 in 1 or 2 ticks.

It should be apparent why we need the Multiplier objective, but in case it's not, it's so that we don't start giving items before DIFF has been doubled.  As such, we should only write to the NumItems once when the button is pressed.  Even though the likelihood of encountering a race condition error is low without using the Multiplier objective, it's best to avoid the problem entirely.


text:
Q: What => means in property declaration (not a lambda expression)? public override double TotalSpecialPower => 1000;

What does the => operator mean?
I know that => is a lambda expression, but I don't know what it means in public override double TotalSpecialPower => 1000;.
And also can anyone explain to me the get and set and how they work in the following code?
private int _health = 100;
public int Health
{
    get => _health;
    set { _health = value; CaluateHeath(); }
}

A: => is used for lambda-functions as you mentioned. It's also used for expression-bodied members.
The documentation on expression-bodied members is available here: https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members

*

*C# 6.0 in 2015 added support for expression-bodied methods.

*C# 7.0 in 2016 added support for expression-bodied properties and other members.

*In methods and property get blocks, it's equivalent to { return X; }.

*In properties:

*

*If the property has a single expression-body, then it's equivalent to declaring a getter-only get { return X; } property.

*If the proeprty has an explicit get, then it's equivalent to ``

So this:
public int Health
{
    get => _health;
    set {  _health = value; CaluateHeath(); }
}

Is equivalent to:
public int Health
{
    get { return _health };
    set {  _health = value; CaluateHeath(); }
}

And this:
public override double TotalSpecialPower => 1000;

Is equivalent to:
public override double TotalSpecialPower
{
    get { return 1000; }
}

And this (note the parentheses):
public override double TotalSpecialPower() => 1000;

Is equivalent to:
public override double TotalSpecialPower()
{
    return 1000;
}

A: It's all about Expression Bodies. Properties are just syntactic sugar to make method calls look like normal field assignments and gets.
A normal property had a get and set with curly backs to a block of code. That can be a lot of syntax for a one liner. So I'm the most recent versions of the C# language, you can use Expression Bodies (fat arrows), like with lambdas, for your getters and setters.
I hope that helps.
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/statements-expressions-operators/expression-bodied-members


text:
Q: Spring. Выдернуть url в string Возможно ли осуществить в спринге такое, что я допустим обращаюсь по url localhost:8080/myproject/request/123/123/123/123.txt
и после слова request выдернуть вот эту строку в string? /123/123/123/123.txt

A: @RequestMapping("/request/{path:.*}")
public void handle(@PathVariable String path) {
    ...
}


text:
Q: Get branch commits in a Github action Given a Github Action for a pull request, I would like to get the list of all the commits in that PR / branch. I can do git log master.. but it fails in the Action:
steps:
  - uses: actions/checkout@v2
    with:
      ref: ${{ github.event.pull_request.head.sha }}
      fetch-depth: 0
  - run: git log ${{ github.event.pull_request.base.ref }}..

fatal: bad revision 'master'

Any hint why that fails?

A: This action misses a git fetch. The other branches can then be accessed with the origin/ prefix.
steps:
  - uses: actions/checkout@v2
    with:
      ref: ${{ github.event.pull_request.head.sha }}
      fetch-depth: 0
  - run: git fetch
  - run: git log origin/${{ github.event.pull_request.base.ref }}..


text:
Q: Reading txt file in vb.net level:
OL0-18-11-540
OL0-18-11-540
0L0-18-11-540
level for him:
ULL
NULL
NULL
number:
MZYS7CE09241
serial num:
MZYS7CE09241
FA
from OLDCAR
?xm] vers ion-""1. 0" encoding-"uTF-8"?> <fa xmins="http://bmw.com/2005/ps dz. data.fa"
BMW CAR
/fa
FA from NEW:
NULL

I have a text file that I would like to extract from it the value of FA from NEW: and the value of level for him: as strings. Thanks in advance
I have tried using stream reader but didn't extract value, it extracted the full text.


text:
Q: Rotating an image array in Numpy I have a 2D array that represents the values of an image that can be viewed with the imshow() command in matplotlib. I would like to rotate the values of this array ("Rotate the image") and have not found a way to do so with a typical NxN array. Anyone know how to do this?
Thanks for your time

A: How about scipy.ndimage.interpolation.rotate()?

A: You should be able to use rot90 on the array to rotate it and then imshow.


text:
Q: C++ fastest cin for reading stdin? I've profiled a computationally-heavy C++ program on Linux using cachegrind. Surprisingly, it turns out the bottleneck of my program is not in any sorting or computational method ... it's in reading the input.
Here is a screenshot of cachegrind, in case I'm mis-interpreting the profiler results (see scanf()):

I hope I'm right in saying that scanf() is taking 80.92% of my running time.
I read input using cin >> int_variable_here, like so:
std::ios_base::sync_with_stdio (false); // Supposedly makes I/O faster
cin >> NumberOfCities;
cin >> NumberOfOldRoads;
Roads = new Road[NumberOfOldRoads];

for (int i = 0; i < NumberOfOldRoads; i++)
{
    int cityA, cityB, length;

    cin >> cityA;
    //scanf("%d", &cityA);    // scanf() and cin are both too slow
    cin >> cityB;
    //scanf("%d", &cityB);
    cin >> length;
    //scanf("%d", &length);

    Roads[i] = Road(cityA, cityB, length);
}

If you don't spot any issues with this input reading code, could you please recommend a faster way to read input? I'm thinking of trying getline() (working on it while I wait for responses). My guess is getline() may run faster because it has to do less conversion and it parses the stream a less total number of times (just my guess, though I'd have to parse the strings as integers eventually too).
What I mean by "too slow" is, this is part of a larger homework assignment that gets timed out after a certain period of time (I believe it is 90 seconds). I'm pretty confident the bottleneck is here because I purposely commented out a major portion of the rest of my program and it still timed out. I don't know what test cases the instructor runs through my program, but it must be a huge input file. So, what can I use to read input fastest?
The input format is strict: 3 integers separated by one space for each line, for many lines:
Sample Input:
7 8 3
7 9 2
8 9 1
0 1 28
0 5 10
1 2 16

I need to make a Road out of the integers in each line.
Also please not that input is redirected to my program to the standard input (myprogram < whatever_test_case.txt). I'm not reading a specific file. I just read from cin.
Update
Using Slava's method:
Input reading seems to be taking less time, but its still timing out (may not be due to input reading anymore). Slava's method is implemented in the Road() ctor (2 down from main). So now it takes 22% of the time as opposed to 80%. I'm thinking of optimizing SortRoadsComparator() as it's called 26,000,000 times.

Comparator Code:
// The complexity is sort of required for the whole min() max(), based off assignment instructions
bool SortRoadsComparator(const Road& a, const Road& b)
{
    if (a.Length > b.Length)
        return false;

    else if (b.Length > a.Length)
        return true;

    else
    {
        // Non-determinism case
        return ( (min(a.CityA, a.CityB) < min(b.CityA, b.CityB)) ||
            (
            (min(a.CityA, a.CityB) == min(b.CityA, b.CityB)) && max(a.CityA, a.CityB) < max(b.CityA, b.CityB)
            )
            );
    }
}

Using enhzflep's method

Considering solved
I'm going to consider this problem solved because the bottleneck is no longer in reading input. Slava's method was the fastest for me.

A: Streams pretty well know to be very slow. It is not a big surprise though - they need to handle localizations, conditions etc. One possible solution would be to read file line by line by std::getline( std:::cin, str ) and convert string to numbers by something like this:
std::vector<int> getNumbers( const std::string &str )
{
   std::vector<int> res;
   int value = 0;
   bool gotValue = false;
   for( int i = 0; i < str.length(); ++i ) {
      if( str[i] == ' ' ) {
         if( gotValue ) res.push_back( value );
         value = 0;
         gotValue = false;
         continue;
      }
      value = value * 10 + str[i] - '0';
      gotValue = true;
   }
   if( gotValue ) res.push_back( value );
   return res;
}

I did not test this code, wrote it to show the idea. I assume you do not expect to get anything in input but spaces and numbers, so it does not validate the input.
To optimize sorting first of all you should check if you really need to sort whole sequence. For comparator I would write methods getMin() getMax() and store that values in object (not to calculate them all the time):
bool SortRoadsComparator(const Road& a, const Road& b)
{
    if( a.Length != b.Length ) return a.Length < b.length;
    if( a.getMin() != b.getMin() ) return a.getMin() < b.getMin();
    return a.getMax() < b.getMax();
}

if I understood how you current comparator works correctly.

A: As Slava says, streams (i.e cin) are absolute pigs in terms of performance (and executable file size)
Consider the following two approaches:
start = clock();
std::ios_base::sync_with_stdio (false); // Supposedly makes I/O faster
cin >> NumberOfCities >> NumberOfOldRoads;
Roads = new Road[NumberOfOldRoads];
for (int i = 0; i < NumberOfOldRoads; i++)
{
    int cityA, cityB, length;
    cin >> cityA >> cityB >> length;
    Roads[i] = Road(cityA, cityB, length);
}
stop = clock();
printf ("time: %d\n", stop-start);

and
start = clock();
fp = stdin;
fscanf(fp, "%d\n%d\n", &NumberOfCities, &NumberOfOldRoads);
Roads = new Road[NumberOfOldRoads];
for (int i = 0; i < NumberOfOldRoads; i++)
{
    int cityA, cityB, length;
    fscanf(fp, "%d %d %d\n", &cityA, &cityB, &length);
    Roads[i] = Road(cityA, cityB, length);
}
stop = clock();
printf ("time: %d\n", stop-start);

Running each way 5 times (with an input file of 1,000,000 entries + the first 2 'control' lines) gives us these results:

*

*Using cin without the direction to not sync with stdio
8291, 8501, 8720, 8918, 7164 (avg 8318.3)

*Using cin with the direction to not sync with stdio
4875, 4674, 4921, 4782, 5171 (avg 4884.6)

*Using fscanf
1681, 1676, 1536, 1644, 1675 (avg 1642.4)
So, clearly, one can see that the sync_with_stdio(false) direction does help. One can also see that fscanf beats the pants off each approach with cin. In fact, the fscanf approach is nearly 3 times faster than the better of the cin approaches and a whopping 5 times faster than cin when not told to avoid syncing with stdio.

A: inline void S( int x ) {
x=0;
while((ch<'0' || ch>'9') && ch!='-' && ch!=EOF) ch=getchar_unlocked();
if (ch=='-')
sign=-1 , ch=getchar_unlocked();
    else
sign=1;
do
x = (x<<3) + (x<<1) + ch-'0';
while((ch=getchar_unlocked())>='0' && ch<='9');
x*=sign;
}

you can use this function for any type of number input, just change the paramater type.
This will run pretty faster than std scanf.
If you want to save more time best thing will be to use fread() and fwrite() but in that case you have to manipulate the input by yourself.
To save time you should use fread() to read a large chunk of data from standard input stream in one call.That will decrease the number of I/O calls hence you will see a large difference in time.


text:
Q: Header active class isn't being set correctly On my website when you click on one of the navbar links it goes to the correct area of the html document but it shows on the navbar the wrong active class. But when you scroll down a tiny bit it will change to the correct color / class.
I tried changing the -40 to -9 in custom.js line 45 and it works correctly but the title is now slightly cut off.
My github

A: The reason is in your website, when you click on the navbar links, it doesn't scroll completely to that section, because of the navbar height. You have used a template, so according to how they have written the page-scroll code, they have purposely scrolled a little above the section considering the height of the navbar. To avoid this
Solution 1
1 - Go to your custom.js line number 45.
2 - Increase the value of scrollTop: target.offset().top - 40 to scrollTop: target.offset().top or may be more, depending on you.
But if you do this obviously the title of the section will be hidden behind the navbar. I have suggested another cleaner solution below.
Solution 2
You can simply add a margin-top: 80px; to each section (statistics, overview etc.).


text:
Q: Laravel with vuejs unit test mocha-webpack script error I am going to test vue components in Laravel application environment.
My package.json "scripts" are following:
   "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "test": "mocha-webpack --webpack-config=node_modules/laravel-mix/setup/webpack.config.js --require tests/Vue/setup.js tests/Vue/**/*.spec.js"
    },

When I ran "npm run test" it shows a callstack with following error. Did I do anything wrong?

npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ test: `mocha-webpack --webpack-config=node_modules/laravel-mix/setup/webpack.config.js --require tests/Vue/setup.js tests/Vue/**/*.spec.js`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ test script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

A: I think you have to setup laravel-mix webpackConfig.
Ex.

resolve: {
    alias: {
        '@': path.resolve(__dirname, 'resources/assets/'),
    },
},


text:
Q: How to check for EL syntax errors in Oozie workflow? I have an Oozie workflow and have implemented a decision control node to check the values of MapReduce counters. If the values are incorrect an action of sending notification email is invoked.
Now I want to create another decision to send an email in case there are syntax errors in the EL expression itself like ${hadoop:counters("mr-action")["FirstMapper"]["Saved records"] gt 5}. But the most challenging question that I still haven't solved and need an advice with - is how should I implement checking for syntax errors?
Here is my current decision node:
<decision name="check-counters">
        <switch>
            <case to="incorrect-counters-email">${hadoop:counters("mr-action")["FirstMapper"]["Saved records"] gt 5}</case>
            <default to="end"/>
        </switch>
</decision>


text:
Q: Can electronics be damaged by undervolting it? I was wondering if there are some particularly important mechanism by which one can break electronics, when undervolting it. Its pretty obvious that lots of electronics will not work properly if undervolted, but what about permanent damage? The question was motivated by repair work. I was wondering about what sorts of secondary effects one should look for when a damaged power supply was involved.
I imagine motors could be damaged if they stalled due to undervolting.
So what are specific mechanisms for permemenant damage due to undervolting (or better put undersupplying)? Are there even any?
To add to the question, what are components or simple circuits that fail when undersupplied?

A: Wouter has some good information, but there are more scenarios where not providing a high enough voltage can damage a device.
Some higher end display screens require multiple voltage sources, and failing to power one source to a high enough level, or fast enough, before a second source, can cause damage to the screen or controller.
Some devices with internal mosfet can be damaged by underpowering the source. As was explained by a TI employee about a current controlled led driver, if the VLed source is too low to provide the selected current through a channel, the logic in that channel will try to drive the channel's mosfet harder to try to sink more current. Eventually, the mosfet will burn out, if not other parts of the chip. I wish I could find that discussion and link it.
While not directly causing damage to the device being underpowered, failing to provide the right voltage to a heating element could cause what is being heated to not heat up correctly/fast enough. Winter Water Pipe heaters, electric stoves, microwaves (for a loose meaning of "heater"), certain car parts. Worse, medical devices or heating in artic environments. Same for cooling solutions, like fans or ACs or pelters. A underperforming fan due to voltage issues can cause it's target to overheat. Water pumps as well. And all three can be damaged by the side effects of it. Water pumps normally use the moving water to cool themselves. A lower voltage will cause it to move water, but might not be fast enough to cool itself down. Underperforming fans might be cooked by the device it could not cool down. Heaters themselves might freeze if they cannot get hot enough.
And last I can think of, battery chargers. A malfunctioning charger, or simply badly designed one, as part of a larger circuit, could cause a lower voltage in a charging state. A battery could feed back into the circuit when it shouldn't.

A: Damage by undervoltage is not as common as by overvoltage, but it is not unheard of.
An example: a simple circuit that has a power mosfet driving a motor. The intention is that the mosfet is either completely on or completely off. In both cases the power dissipated by the mosfet is very low:

*

*when it is on the power is low because the o-fully-on resistance of the mosfet is very low, hence the voltage across it is also very low, so the power (V*I) is low.

*when it is off the full voltage of the power is across the mosfet, but the current is almost zero, hence the power is almost zero too.

A mosfet needs a certain voltage at its gate to turn fully on. 8V is a typical value. A simple driver circuit could get this voltage directly from the power that also feeds the motor. When this voltage is too low to turn the mosfet fully on a dangerous situation (from the point of view of the moseft) can arise: when it is half-on, both the current through it and the voltage across it can be substantial, resulting in a dissipation that can kill it. Death by undervoltage.
Note that I started by assuming a simple circuit. In practice a serious circuit like this would have an undervoltage protection.

A: It depends on your load.
If it's a resistive load, lowering voltage means it will conduct less current and dissipate less heat. Nothing wrong here.
If you drop the voltage on the gate/base of a transistor and it may not fully saturate and have a larger voltage drop. As power dissipation is P=U*I; the voltage drop on the transistor could double (from 0.5V to 1V) while the current may stay more or less the same (for e.g. 1000mA to 800mA). You effectively doubled the power dissipation and that could lead to damage!
If the device uses a linear regulator, the regulator will have to regulate less voltage. This will lead to lower power dissipation.
Of course there is a limit at which the regulator cannot maintain regulation anymore and the output voltage will drop too. This output may shutdown or stop working at a certain point.
Switch mode power supplies are a constant power load. If you assume the output to draw a constant power ; for example 3.3V 1A. This equals to 3.3W which means whatever the input voltage is, it will always draw 3.3W. In practice you have efficiency (which can vary) and limits to the voltage region, but it will try to draw 3.3W.
If the input voltage drops the input current increases. If parts like inductors, diodes or MOSFETs cannot handle the higher current (heat dissipation or exceeding saturation/peak currents) it can cause damage.
However, in that case you're probably exceeding a certain operation window. For example, a product may have a input voltage requirement of 9-15V. Although the switching regulator would work fine on (for example) 7V, it may exceed the current on some part and become unreliable.
Sometimes you see "Undervoltage lock-out" on these devices. This is a voltage at which the switch mode supply will shutdown because it cannot guarantee reliable operation.

A: One example of a specific failure mode of certain electronic systems is Latch-Up.
https://en.wikipedia.org/wiki/Latch-up
Quote from the above link...

This frequently happens in circuits which use multiple supply voltages
  that do not come up in the required sequence on power-up, leading to
  voltages on data lines exceeding the input rating of parts that have
  not yet reached a nominal supply voltage.

Often this can be resolved by simply power-cycling the system, but if that system is controlling some other mechanism it can cause further failure or even physical damage as an indirect side-effect.

A: The general term for low-voltage events is "brownout"; there are lots of ways of incorporating brownout prevention into your power supply design.


text:
Q: How can I fit a rhombus optimally into a generic triangle and calculate its sidelength I have the following task: calculate largest possible side length of a rhombus inside a generic triangle with side lengths $a, b, c$. And all points of the rhombus need to be on the sides of the triangle. Also one point of the rhomboid is on the point C of the triangle
I have no idea how to even sketch that, let alone calculate its length.
Can somebody tell me how to start? How to optimally fit a rhombus inside a triangle?
I have no idea how I should look at this problem.

A: Let D be the point on AB such that CD is the angle bisector of $\angle ACB$.
Let the perpendicular bisector of CD cut CA and CB at M and N.
CMDN is the only rhombus that meets the requirement can be constructed.


text:
Q: RIA Service EF creating a MessageObject with Lists of Entities as properties I have created a message object with three properties that are three list of three different entity types.  I created the message class because I am trying to do a search all that will return all the entities that fit the search criteria.  I would like to do this in one call, not three (one for each entity) separate calls.  It compiles and the client side designer is generating the entities, the service's Search All method, the message object class, but not the message object properties.
Is this possible with RIA Services? and if so what can you explain what I am doing wrong and why?  Thanks!
Server side class declaration:
[Serializable]
[DataContract(IsReference = true)]
public class SearchAllMessage
{
    [DataMember]
    public List<Entity1> Entity1List { get; set; }
    [DataMember]
    public List<Entity2> Entity2List { get; set; }
    [DataMember]
    public List<Entity3> Entity3List { get; set; }
}

Client side designer generated code:
/// <summary>
/// The 'SearchAllMessage' class.
/// </summary>
[DataContract(Namespace="http://schemas.datacontract.org/2004/07/SharebackMaintenance.RiaService.Web")]
public sealed partial class SearchAllMessage : ComplexObject
{

    #region Extensibility Method Definitions

    /// <summary>
    /// This method is invoked from the constructor once initialization is complete and
    /// can be used for further object setup.
    /// </summary>
    partial void OnCreated();

    #endregion

    /// <summary>
    /// Initializes a new instance of the <see cref="SearchAllMessage"/> class.
    /// </summary>
    public SearchAllMessage()
    {
        this.OnCreated();
    }
}

Service's method signature:
 [Invoke]
 public SearchAllMessage SearchAll(string fiterA, string filterB, int filterC)

A: Assuming your SearchAllMessage and its contained items are read-only, you should mark it up as a ComplexType. All you have to do is add an attribute to each of the classes involved (SearchAllMessage, Entity1, etc.)
[Serializable]
[DataContract(IsReference = true)]
[ComplexType]
public class SearchAllMessage
{
    [DataMember]
    public List<Entity1> Entity1List { get; set; }
    [DataMember]
    public List<Entity2> Entity2List { get; set; }
    [DataMember]
    public List<Entity3> Entity3List { get; set; }
}

The ComplexTypeAttribute is a member of the EntityFramework assembly.
If you are intending to make the entities queryable and updatable, then you'll need to go down the path of using [Association(...)], [Include], and [Composition].


text:
Q: Gnome: Map AltGr key to Alt I have an annoying UK keyboard which has an Alt Gr key where the right Alt key is on a US keyboard. This is really annoying when using Gnome which makes heavy use of the Alt/Meta key.
Does anyone know how I can map the Alt Gr key to the Alt key?

A: For those UK users still pulling their hairs out, this worked for me:
xmodmap -e "clear mod5"
xmodmap -e "keycode 108 = Alt_L"

Explanation: The first line removes the current behaviour of your AltGr (which is assigned to the mod5 modifier). The second takes the AltGr key (which on my keyboard produces a keycode of 108), and maps that to whatever keycode your Alt_L key is mapped to.
If you have no idea what is going on with keycodes and keysyms, I found this xmodmap introduction very useful.

A: gnome-tweak-tool lets you do this with a GUI:
Typing -> Key to choose 3rd level -> Right Alt key never chooses 3rd level

A: xmodmap
The 'shift, lock, control, modN' on the left are what X sees and cares about.  The keysyms on the right map to them.  Mode_switch is your AltGr key.  Move it to join the others at mod1:
xmodmap -e 'clear mod5'
xmodmap -e 'add mod1 = Mode_switch'

A: If the above answers still do not work you then run xev -event keyboard (you may need to install it first) and press AltGr with the Event Tester window in focus. You should see something like the following in the shell.
KeyPress event, serial 163, synthetic NO, window 0x1600001,
    root 0x119, subw 0x0, time 21667560, (151,737), root:(1111,764),
    state 0x10, keycode 108 (keysym 0xfe03, ISO_Level3_Shift), same_screen YES,
    XKeysymToKeycode returns keycode: 92
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

On the third line it gives you the keycode and keysym name, which in my case is ISO_Level3_Shift. Now run xmodmap and check the output before doing
xmodmap -e "remove mod5 = ISO_Level3_Shift"
xmodmap -e "add mod1 = ISO_Level3_Shift"

where ISO_Level3_Shift should be replaced with the correct key symbol if necessary. Finally you need to add this to your user rc script to make it persistent.


text:
Q: How to get image ID based on get_theme_mod image URL? I'm trying to use wp_get_attachment_image function to insert image. For that I need use image ID. So now I need to know how to get this ID by image URL taken from get_theme_mod from WP Customization API.
So:
$image_src = get_theme_mod('header_logo', '');
$image_id = HOW TO GET ID FROM $image_src ??
echo wp_get_attachment_image( $image_id, 'logo' );

I found this solution https://stackoverflow.com/questions/25671108/get-attachment-id-by-file-path-in-wordpress/31743463 so I was trying:
// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
    global $wpdb;
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url ));
        return $attachment[0];
}

// set the image url
$image_url = get_theme_mod('header_logo', '');

// store the image ID in a var
$image_id = pippin_get_image_id($image_url);

// print the id
echo $image_id;

// final image
echo wp_get_attachment_image( $image_id, 'logo' );

but still nothing. Any ideas?

A: WordPress has a built-in function for this: attachment_url_to_postid().
More info from a Stack Overflow question: Get Attachment ID by File Path in WordPress.


text:
Q: Residue at infinity without singularity I'm sorry if this question is a duplicate but I really have not found anything online that says this and I need a confirmation. My problem is the following: for a function on the complex plane to have a residue at a point there must be a singularity. This because the residue is defined to be the coefficient $a_{-1}$ of the Laurent series and therefore if the Laurent series has no negative terms there is no residue (or the residue is zero). However the situation on the Riemann sphere is different, that is to say it seems to me that the point at infinity might have a residue even without being a singularity.
Take for example $f(z) = \frac{1}{z}$. A simple calculation (using the definition) shows that the residue at infinity is -1. However, this function has a 0 at infinity and not a singularity. This can be seen both by taking the limit and by using the fact that a function $f$ has a pole at infinity iff $f(\frac{1}{z})$ has a pole at 0 and this is not the case. Moreover, the function has to have a nonzero residue at infinity because the sum of residues of a meromorphic function on the Rieman sphere must be zero. This is counterintuitive to me but I'm quite convinced this is how it is. Can someone confirm this to me (that the point at infinity is radically different from other points)? Moreover, if this is the case, is there any profound reason why the point at infinity behaves so differently?

A: For a function $f$ analytic on $\Bbb{C}$ minus finitely many points, the residue at $\infty$ is what you need to obtain $\sum_a Res(f(z),a) = 0$.
For $r$ large enough $f$ is analytic for $|z| \ge r$ so that $$\frac{1}{2i\pi}\int_{|z| = r} f(z)dz = \sum_{a \ne \infty} Res(f(z),a)$$ and
$$\begin{align}
Res(f(z),\infty) &\overset{def}  =-\frac{1}{2i\pi}\int_{|z| = r} f(z)dz \\
&= \frac{1}{2i\pi}\int_{|s| = 1/r} f(1/s)d(1/s) \\
&= \frac{1}{2i\pi}\int_{|s| = 1/r} \frac{f(1/s)}{-s^2}ds \\
&= Res(\frac{f(1/s)}{-s^2},0)
\end{align}$$
Then for the compact Riemann surface viewpoint : the residues of $f(z)$ are chart dependent so they are ill-defined. To make it chart independent think to $f(z)dz$ as a 1-form on the Riemann sphere, holomorphic at all but finitely many points, we can define it in every chart it will become $f(\phi(u))d\phi(u)$ and the residue $Res(f(z)dz,\phi(a))=\frac{1}{2i\pi}\int_{|u-a|=r} f(\phi(u))d\phi(u)$ doesn't depend on the chosen chart, the sum of all residues is $0$.


text:
Q: Shifting focus to a new popup window that has a null ID and name I apologize if this question is redundant - I've seen a number of similar posts on this and other sites but none of them presented a solution that helped me.
I am using Selenium IDE to record a script that clicks a link (which opens a new window with a .shtml extension). I then need to switch focus to the new window and hit the save button to download a PDF.
I don't understand exactly how this works, but the url of the popup window is some generic url (https://www.theice.com/marketdata/reports/datawarehouse/ConsolidatedEndOfDayReportPDF.shtml) that hosts whatever report you generate on the previous page (https://www.theice.com/marketdata/reports/ReportCenter.shtml#report/142). If you try an openWindow command on the new URL it won't generate the report, you must open it through a link on the first page.
I want to refocus selenium to the new popup through selectWindow or selectPopup, but the issue is that the popup has no name, ID or title. Does anyone have a suggestion on how to avoid this issue?
Thanks,

A: Have not tried this out myself, but you could use this to find the window names and switch to it.

storeAllWindowNames
names

echo
${names}

.

selectWindow
<the name you find out>

.

You can try with storeAllWindowIds,storeAllWindowTitles. These three methods should return an array of windowids, something like this , bJHBGug2u8


text:
Q: Trying to access array offset on value of type null...in login details if ($row['email'] == $email && $row['password'] == $password) {
  echo "Login success Welcome".$row['username']; # code...
}
else{
  echo "failed to login";
}

A: You can check if(!is_null($row)) along with the other checks, or simply:
if( $row && $row['email']==$email && $row['password']==$password ) { ... };

This happens when you query your DB, and there is no match, so there's no result, so the result is empty/null..  which you seem not to be checking within your code..


text:
Q: How to iterate over the nested documents from MongoDB with Jinja2 and Flask I have the following MongoDB document schema:
phones.insert_one(
{
    "brand": "Samsung",
    "model": "Galaxy S14",
    "display": 7,
    "wireless": {
        "Bluetooth": 6.0,
        "WIFI": {
            "type": "Dual band",
            "2.5 GHz": True,
            "5 GHz": True,
        },
        "GPS": True,
        "Glonass": False,
    },
}
)

This is an endpoint code:
@main.route("/<brand>/<model>")
def get_single_model(brand: str, model: str):
    context = {
        "model_data": phones.find_one({"brand": brand, "model": model}, {"_id": False}),
        "model": model,
        "brand": brand,
    }
    return render_template("model.html", context=context)

In a html template I use code to iterate over the context data:

{% for k, v in context.model_data.items() %}

{{ k }}: {{ v }}

{% endfor %}

As a result in template I have:
brand: Samsung
model: Galaxy S14
display: 7
wireless: {'Bluetooth': 6.0, 'WIFI': {'type': 'Dual band', '2.5 GHz': True, '5 GHz': True}, 'GPS': True, 'Glonass': False}

The question is - how do I can iterate over all nested documents like 'wireless', 'WIFI', etc? I need to make it in a nested loop, to make this approach reusable for any other collection.


text:
Q: IIS forgets virtual directory permissions - An error occurred loading a configuration file: Failed to start monitoring changes I have a website with a virtual directory that contains PDFs.
Users access the PDFs by using a URL such as http://myApp.com/PDFs/12345678.pdf, where PDFs is a virtual directory mapped to \\\actualPhysicalServerName\PDFsDirectory\.
This works.
I routinely re-deploy the application. Once the application is redeployed and the website restarted, users can no longer access the virtual directory until IIS is restarted.
Accessing the above URL gives the following error:

An error occurred loading a configuration file: Failed to start monitoring changes to \\\actualPhysicalServerName\PDFsDirectory\web.config because access is denied.
at System.Web.FileChangesMonitor.FindDirectoryMonitor(String dir, Boolean addIfNotFound, Boolean throwOnError)
at System.Web.FileChangesMonitor.StartMonitoringFile(String alias, FileChangeEventHandler callback)
at System.Web.Configuration.WebConfigurationHost.StartMonitoringStreamForChanges(String streamName, StreamChangeCallback callback)
at System.Configuration.BaseConfigurationRecord.MonitorStream(String configKey, String configSource, String streamname)
at System.Configuration.BaseConfigurationRecord.InitConfigFromFile()

Restarting the application pool does not help.
I have to restart IIS.
Once IIS is restarted, the virtual directory can be accessed as expected.
Is this expected behavior? Have I set up my virtual directories incorrectly?
I am using IIS 7.5, Windows 7 server, and .NET 4.5.

A: I had a Virtual directory pointing to images on UNC share. All was working fine until we updated parent app to .NET 4.5.
We had to convert the VirDir to Virtual Application with 4.0 Integrated Application Pool.

A: I solved this problem this way:

*

*Created new pool with "No managed code" and "Classic" settings.

*Converted virtual directory to application, connecting with a user account with permissions on the share

*Have application use the new pool

A: For anyone else frustrated with the same issue -  while I did not find the crux of the problem, I did figure out that this problem was related to the Identity of the Application Pool that the website was running under.
In my case, the solution was to change the App Pool identity from the ApplicationPoolIdentity Built-in account to a custom account that is an administrator on all of the machines involved.
To do this

*

*Right click on the application pool in IIS,  Choose Advanced Properties.

*Under ProcessModel->Identity , choose Identity. Choose Custom Account (Built-in account, Application Pool Identity is the default in IIS 7.5)

*Switch to using a Custom Domain account, that is an administrator on this machine, as well as the machine where the virtual directory is hosted.

*

*Restart the Application Pool.

A: Old topic but I was able to solve it by following these instructions (basically add ASPNET and IUSR to permissions:

*

*In Windows Explorer, browse to the application folder or to the virtual directory that contains the content (for example, c:\inetpub\wwwroot\xx).

*Right-click the folder, and then click Properties.

*On the Security tab, click Add.

*On the "Select Users or Groups" window, click on Advance

*Click on Find Now button, you will see List of users

*Select ASPNET and IUSR_(machinename) then click OK to close the"Select Users or Groups" window

*Allow the following permissions for the ASPNET and IUSR_(machinename) account:
-Read & Execute
-List Folder Content
-Read


text:
Q: logstash forwarder error in elk [root@sys2 logstash-forwarder]# rpm -qa | grep -i logstash logstash-forwarder-0.4.0-1.x86_64

I do get this error
2015/09/26 14:37:03.434672 Failed to tls handshake with 192.168.1.235 read tcp 192.168.1.235:5001: i/o timeout

A: An i/o timeout, aside from the usual networking issues, can also be a sign of a logstash that's overloaded.  Tune logstash (may guides to that on the web), and you can also try decreasing the batch size and increasing the timeout in logstash-forwarder.

A: This issue has been resolved thanks to google. I googled and found that upgrading elasticsearch to the latest version alleviates the issue. I also increased the logstash-forwarder timeout to 5 minutes(from 15 seconds). I now have three logstash forwarders supplying logs to the logstash server. I am however keeping my fingers crossed.
I followed this post:
https://github.com/elastic/logstash-forwarder/issues/360