text:
Q: How to count one column and compare it to another With 2 Inner joins I have the following
Tables:
Cursistcursus
Emailadres
Cursuscode

SoortCursus
SoortCode
Cursussoort
Prijs
Maxcursisten

Cursus
Cursuscode
Begindatum
Einddatum
Soortcode
This is my current Query:
SELECT DISTINCT Cursus.Cursuscode, SoortCursus.SoortCode, SoortCursus.Maxcursisten, Cursus.Soortcode, COUNT(Cursistcursus.Cursuscode) as Bezetting, Cursus.Begindatum, Cursus.Einddatum, SoortCursus.Cursussoort, SoortCursus.Prijs
FROM Cursistcursus,Cursus
     INNER JOIN SoortCursus
                ON SoortCursus.SoortCode = Cursus.Soortcode
WHERE (SELECT COUNT(Cursuscode) FROM Cursistcursus) <= SoortCursus.Maxcursisten";

What it needs to do is the following:
I want to get the Cursussoort from Soortcursus where the Soortcode is the same. I Want to count the amount of Cursistcursus per each Cursuscode. So that I can check if there is less CursistCursus with the same Cursuscode then Maxcursisten.
I Have been trying for over 4 hours now!
Sample Data:
Cursus
(1, 2016-11-13, 2016-11-19, BEG)
(2, 2016-11-13, 2016-11-19, GEV)
(3, 2016-11-13, 2016-11-19, WAD)
SoortCursus
(BEG, Beginnerscursus, 700.00, 7)
(GEV, Gevorderdencursus, 800.00, 5)
(WAD, Waddentocht, 900.00, 10)
CursistCursus
(1, Test@test.com)
(1, Test@test.com)
(1, Test@test.com)
(1, Test@test.com)
(1, Test@test.com)
(1, Test@test.com)
(1, Test@test.com)
(2, Test2@test.com)
SELECT DISTINCT Cursus.Cursuscode, SoortCursus.SoortCode, SoortCursus.Maxcursisten, Cursus.Soortcode, Cursus.Begindatum, Cursus.Einddatum, SoortCursus.Cursussoort, SoortCursus.Prijs FROM Cursus INNER JOIN SoortCursus
                ON SoortCursus.SoortCode = Cursus.Soortcode WHERE (SELECT COUNT(Cursuscode) AS Bezetting FROM Cursistcursus) < SoortCursus.Maxcursisten GROUP BY Cursuscode

This gives me the right Cursussoort but then every Maxcursisten gets 7!

A: Do you need use THAT names? ._.
Looks like a riddle.
However, give us some more info. What's the PK in each table?
If you do this (more info and clearly names), maybe we can help you better.


text:
Q: When exactly is `componentDidMount` fired? This is a recurring problem I have with React. The componentDidMount method is guaranteed to be fired when the component is rendered for the first time so it seems like a natural place to take DOM measurements like heights and offsets.
However, many times I receive wrong style readings at this point of the component's lifecycle. The component is in the DOM, when I break with the debugger, but it's not yet painted on the screen. I get this problem with elements that have width/height set to 100% mostly.
When I take measurements in componentDidUpdate - everything works fine, but this method will not fire at the initial render of the component.
So my question is - when exactly is componentDidMount fired because it's obviously not fired after all the browser paints are done.
EDIT:
This Stackoverflow issue deals with the same subject:
It also references this github conversation that explains what happens

A: As you may know, componentDidMount is triggered only once immediately after the initial rendering.
Since you are taking measurements, it would seem you would want to also trigger your measuring when componentDidUpdate in case your measurements change when your component updates.
Please note that componentDidUpdate does not occur for the initial render so you likely need both lifecycle events to trigger your measurement handling. See if this second event triggers for you and if it has different measurements.
In my opinion you should avoid using setTimeout or requestAnimationFrame when possible.
React Lifecycle Reference.

A: It is called only once when the component mounted. That's the perfect time to do an asynchronous request to fetch data from an API. The fetched data would
get stored in the internal component state to display it in the render() lifecycle method.
Simple: It Run After Render Functions

A: Inside a react component tree, componentDidMount() is fired after all children components have also been mounted. This means, that any component's componentDidMount() is fired before its parent has been mounted.
So if you want to measure DOM position and sizes etc, using componentDidMount() of a child component is an unsafe place/ time to do this.
In your case: to get accurate reading from 100% width/height components, a safe place to take such measurements would be inside the componentDidMount() of the top react component.
100% is a width/height relative to the parent/ container. So measurements can only be taken after the parent has been mounted too.

A: If you want to respond to something being mounted in the DOM, the most reliable way to do that is with a ref callback. For example:
render() {
  return (
    <div
      ref={(el) => {
        if (el) {
          // el is the <div> in the DOM. Do your calculations here!
        }
      }}
    ></div>
  );
}

A: you can try delaying logic in componentDidMount() with requestAnimationFrame(). the logic should occur after the next paint.
however, we'd need to know more about your code to see why the nodes haven't been painted. i've never hit that problem. componentDidMount() fires right after the dom nodes are added to the page, but not necessarily after they have been painted.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Public Suffix List C# parser Does anyone have Public Suffix List (getting real domain) parser in c#.
It was available on  code.google.com /p/domainname-parser/ (remove space before p in name) , however project has probably been removed from google code, since I cannot access project folders and source anymore.

A: I couldn't get the code in gary's answer to pass the mozilla test cases, so hacked these mods together based on the original and the algorithm described here. Hopefully it's of use to someone if the domainname-parser code dissapears from the web.
namespace DomainName.Parser
{
  using System.Collections.Generic;
  using System.Linq;
  using System;

  public class DomainName
  {
    public DomainName(string rawDomainName, string publicSuffix, string registerableDomainName)
    {
      this.RawDomainName = rawDomainName;
      this.PublicSuffix = publicSuffix;
      this.RegisterableDomainName = registerableDomainName;
    }

    public string RawDomainName { get; private set; }

    public string PublicSuffix { get; private set; }

    public string RegisterableDomainName { get; private set; }

    public static bool TryParse(string rawDomainName, PublicSuffixRuleCache ruleCache, out DomainName domainName)
    {
      if (string.IsNullOrEmpty(rawDomainName) || !rawDomainName.Contains('.') || rawDomainName.StartsWith("."))
      {
        domainName = new DomainName(rawDomainName, null, null);
        return true;
      }

      try
      {
        rawDomainName = rawDomainName.ToLower();

        //  Split our domain into parts (based on the '.')
        //  We'll be checking rules from the right-most part of the domain
        var domainLabels = rawDomainName.Trim().Split('.').ToList();
        domainLabels.Reverse();

        // If no rules match, the prevailing rule is "*"
        var prevailingRule = FindMatchingRule(domainLabels, ruleCache) ?? new PublicSuffixRule("*");

        // If the prevailing rule is an exception rule, modify it by removing the leftmost label.
        if (prevailingRule.Type == PublicSuffixRule.RuleType.Exception)
        {
          var labels = prevailingRule.Labels;
          labels.Reverse();
          labels.RemoveAt(0);

          prevailingRule = new PublicSuffixRule(string.Join(".", labels));
        }

        // The public suffix is the set of labels from the domain which directly match the labels of the prevailing rule (joined by dots).
        var publicSuffix = Enumerable.Range(0, prevailingRule.Labels.Count).Aggregate(string.Empty, (current, i) => string.Format("{0}.{1}", domainLabels[i], current).Trim('.'));

        // The registered or registrable domain is the public suffix plus one additional label.
        var registrableDomain = string.Format("{0}.{1}", domainLabels[prevailingRule.Labels.Count], publicSuffix);

        domainName = new DomainName(rawDomainName, publicSuffix, registrableDomain);
        return true;
      }
      catch
      {
        domainName = null;
        return false;
      }
    }

    private static PublicSuffixRule FindMatchingRule(List<string> domainLabels, PublicSuffixRuleCache ruleCache)
    {
      var ruleMatches = ruleCache.PublicSuffixRules.Where(r => r.AppliesTo(domainLabels)).ToList();

      // If there is only one match, return it.
      if (ruleMatches.Count() == 1)
      {
        return ruleMatches[0];
      }

      // If more than one rule matches, the prevailing rule is the one which is an exception rule.
      var exceptionRules = ruleMatches.Where(r => r.Type == PublicSuffixRule.RuleType.Exception).ToList();
      if (exceptionRules.Count() == 1)
      {
        return exceptionRules[0];
      }
      if (exceptionRules.Count() > 1)
      {
        throw new ApplicationException("Unexpectedly found multiple matching exception rules.");
      }

      // If there is no matching exception rule, the prevailing rule is the one with the most labels.
      var prevailingRule = ruleMatches.OrderByDescending(r => r.Labels.Count).Take(1).SingleOrDefault();
      return prevailingRule;
    }
  }

  public class PublicSuffixRule
  {
    /// <summary>
    /// Construct a rule based on a single line from the www.publicsuffix.org list
    /// </summary>
    /// <param name="ruleLine">The rule line.</param>
    public PublicSuffixRule(string ruleLine)
    {
      if (string.IsNullOrEmpty(ruleLine) || string.IsNullOrWhiteSpace(ruleLine))
      {
        throw new ArgumentNullException("ruleLine");
      }

      //  Parse the rule and set properties accordingly:
      string ruleName;

      if (ruleLine.StartsWith("*", StringComparison.InvariantCultureIgnoreCase))
      {
        this.Type = RuleType.Wildcard;
        ruleName = ruleLine;
      }
      else if (ruleLine.StartsWith("!", StringComparison.InvariantCultureIgnoreCase))
      {
        this.Type = RuleType.Exception;
        ruleName = ruleLine.Substring(1);
      }
      else
      {
        this.Type = RuleType.Normal;
        ruleName = ruleLine;
      }

      this.Name = ruleName.Split(' ')[0];

      var labels = this.Name.Split('.').ToList();
      labels.Reverse();

      this.Labels = labels;
    }

    public string Name { get; private set; }

    public RuleType Type { get; private set; }

    public List<string> Labels { get; private set; }

    public bool AppliesTo(List<string> domainLabels)
    {
      if (this.Labels.Count > domainLabels.Count)
      {
        return false;
      }

      foreach (var position in Enumerable.Range(0, this.Labels.Count))
      {
        if (this.Labels[position] == "*")
        {
          return true;
        }

        if (this.Labels[position] != domainLabels[position])
        {
          return false;
        }
      }

      return true;
    }

    /// <summary>
    /// Rule type
    /// </summary>
    public enum RuleType
    {
      /// <summary>
      /// A normal rule
      /// </summary>
      Normal,

      /// <summary>
      /// A wildcard rule, as defined by www.publicsuffix.org
      /// </summary>
      Wildcard,

      /// <summary>
      /// An exception rule, as defined by www.publicsuffix.org
      /// </summary>
      Exception
    }
  }

  public class PublicSuffixRuleCache
  {
    public PublicSuffixRuleCache(string publicSuffixRulesFileLocation)
    {
      if (string.IsNullOrEmpty(publicSuffixRulesFileLocation))
      {
        throw new ArgumentNullException("publicSuffixRulesFileLocation");
      }

      this.PublicSuffixRules = GetRules(publicSuffixRulesFileLocation);
    }

    public PublicSuffixRuleCache(IEnumerable<string> publicSuffixRules)
    {
      this.PublicSuffixRules = GetRules(publicSuffixRules);
    }

    public List<PublicSuffixRule> PublicSuffixRules { get; private set; }

    /// <summary>
    /// Gets the list of TLD rules from the cache
    /// </summary>
    /// <returns></returns>
    private static List<PublicSuffixRule> GetRules(string publicSuffixRulesFileLocation)
    {
      var results = new List<PublicSuffixRule>();

      //  If the cached suffix rules file exists...
      if (File.Exists(publicSuffixRulesFileLocation))
      {
        //  Load the rules from the cached text file
        var ruleStrings = File.ReadAllLines(publicSuffixRulesFileLocation, Encoding.UTF8).ToList();
        results = GetRules(ruleStrings);
      }

      return results;
    }

    private static List<PublicSuffixRule> GetRules(IEnumerable<string> publicSuffixRules)
    {
      // Strip out any lines that are a comment or blank.
      return
        publicSuffixRules.Where(
          ruleString =>
            ruleString.Trim().Length != 0
            && !ruleString.StartsWith("//", StringComparison.InvariantCultureIgnoreCase)).Select(ruleString => new PublicSuffixRule(ruleString)).ToList();
    }
  }
}

Unit tests:
namespace DomainName.Library.Tests
{
  using FluentAssertions;

  using Xunit;

  using DomainName.Parser;

  public class CheckPublicSuffixTest2
  {
    public bool CheckRegisterableDomain(string domainName, string registerableDomain)
    {
      var ruleCache = new PublicSuffixRuleCache(@"C:\publicsuffix.txt");

      DomainName outDomain;
      if (DomainName.TryParse(domainName, ruleCache, out outDomain))
      {
        return outDomain.RegisterableDomainName == registerableDomain;
      }

      return registerableDomain == null;
    }

    [Fact]
    public void TestCheckPublicSuffix()
    {
      // Any copyright is dedicated to the Public Domain.
      // http://creativecommons.org/publicdomain/zero/1.0/

      // null input.
      this.CheckRegisterableDomain(null, null).Should().BeTrue();

      // Mixed case.
      this.CheckRegisterableDomain("COM", null).Should().BeTrue();
      this.CheckRegisterableDomain("example.COM", "example.com").Should().BeTrue();
      this.CheckRegisterableDomain("WwW.example.COM", "example.com").Should().BeTrue();

      // Leading dot.
      this.CheckRegisterableDomain(".com", null).Should().BeTrue();
      this.CheckRegisterableDomain(".example", null).Should().BeTrue();
      this.CheckRegisterableDomain(".example.com", null).Should().BeTrue();
      this.CheckRegisterableDomain(".example.example", null).Should().BeTrue();

      // Unlisted TLD.
      this.CheckRegisterableDomain("example", null).Should().BeTrue();
      this.CheckRegisterableDomain("example.example", "example.example").Should().BeTrue();
      this.CheckRegisterableDomain("b.example.example", "example.example").Should().BeTrue();
      this.CheckRegisterableDomain("a.b.example.example", "example.example").Should().BeTrue();

      // TLD with only 1 rule.
      this.CheckRegisterableDomain("biz", null).Should().BeTrue();
      this.CheckRegisterableDomain("domain.biz", "domain.biz").Should().BeTrue();
      this.CheckRegisterableDomain("b.domain.biz", "domain.biz").Should().BeTrue();
      this.CheckRegisterableDomain("a.b.domain.biz", "domain.biz").Should().BeTrue();

      // TLD with some 2-level rules.
      this.CheckRegisterableDomain("com", null).Should().BeTrue();
      this.CheckRegisterableDomain("example.com", "example.com").Should().BeTrue();
      this.CheckRegisterableDomain("b.example.com", "example.com").Should().BeTrue();
      this.CheckRegisterableDomain("a.b.example.com", "example.com").Should().BeTrue();
      this.CheckRegisterableDomain("uk.com", null).Should().BeTrue();
      this.CheckRegisterableDomain("example.uk.com", "example.uk.com").Should().BeTrue();
      this.CheckRegisterableDomain("b.example.uk.com", "example.uk.com").Should().BeTrue();
      this.CheckRegisterableDomain("a.b.example.uk.com", "example.uk.com").Should().BeTrue();
      this.CheckRegisterableDomain("test.ac", "test.ac").Should().BeTrue();

      // TLD with only 1 (wildcard) rule.
      this.CheckRegisterableDomain("cy", null).Should().BeTrue();
      this.CheckRegisterableDomain("c.cy", null).Should().BeTrue();
      this.CheckRegisterableDomain("b.c.cy", "b.c.cy").Should().BeTrue();
      this.CheckRegisterableDomain("a.b.c.cy", "b.c.cy").Should().BeTrue();

      // More complex TLD.
      this.CheckRegisterableDomain("jp", null).Should().BeTrue();
      this.CheckRegisterableDomain("test.jp", "test.jp").Should().BeTrue();
      this.CheckRegisterableDomain("www.test.jp", "test.jp").Should().BeTrue();
      this.CheckRegisterableDomain("ac.jp", null).Should().BeTrue();
      this.CheckRegisterableDomain("test.ac.jp", "test.ac.jp").Should().BeTrue();
      this.CheckRegisterableDomain("www.test.ac.jp", "test.ac.jp").Should().BeTrue();
      this.CheckRegisterableDomain("kyoto.jp", null).Should().BeTrue();
      this.CheckRegisterableDomain("test.kyoto.jp", "test.kyoto.jp").Should().BeTrue();
      this.CheckRegisterableDomain("ide.kyoto.jp", null).Should().BeTrue();
      this.CheckRegisterableDomain("b.ide.kyoto.jp", "b.ide.kyoto.jp").Should().BeTrue();
      this.CheckRegisterableDomain("a.b.ide.kyoto.jp", "b.ide.kyoto.jp").Should().BeTrue();
      this.CheckRegisterableDomain("c.kobe.jp", null).Should().BeTrue();
      this.CheckRegisterableDomain("b.c.kobe.jp", "b.c.kobe.jp").Should().BeTrue();
      this.CheckRegisterableDomain("a.b.c.kobe.jp", "b.c.kobe.jp").Should().BeTrue();
      this.CheckRegisterableDomain("city.kobe.jp", "city.kobe.jp").Should().BeTrue();
      this.CheckRegisterableDomain("www.city.kobe.jp", "city.kobe.jp").Should().BeTrue();

      // TLD with a wildcard rule and exceptions.
      this.CheckRegisterableDomain("om", null).Should().BeTrue();
      this.CheckRegisterableDomain("test.om", null).Should().BeTrue();
      this.CheckRegisterableDomain("b.test.om", "b.test.om").Should().BeTrue();
      this.CheckRegisterableDomain("a.b.test.om", "b.test.om").Should().BeTrue();
      this.CheckRegisterableDomain("songfest.om", "songfest.om").Should().BeTrue();
      this.CheckRegisterableDomain("www.songfest.om", "songfest.om").Should().BeTrue();

      // US K12.
      this.CheckRegisterableDomain("us", null).Should().BeTrue();
      this.CheckRegisterableDomain("test.us", "test.us").Should().BeTrue();
      this.CheckRegisterableDomain("www.test.us", "test.us").Should().BeTrue();
      this.CheckRegisterableDomain("ak.us", null).Should().BeTrue();
      this.CheckRegisterableDomain("test.ak.us", "test.ak.us").Should().BeTrue();
      this.CheckRegisterableDomain("www.test.ak.us", "test.ak.us").Should().BeTrue();
      this.CheckRegisterableDomain("k12.ak.us", null).Should().BeTrue();
      this.CheckRegisterableDomain("test.k12.ak.us", "test.k12.ak.us").Should().BeTrue();
      this.CheckRegisterableDomain("www.test.k12.ak.us", "test.k12.ak.us").Should().BeTrue();
    }
  }
}

A: Was just looking for this myself, it seems to still be available -
https://github.com/tinohager/Nager.PublicSuffix


text:
Q: Cucumber - Serenity execute directly pass all test but execute with command line compile with error I try to introduce me in Cucumber and Serenity with Java using IntelliJ.
I try to execute the class that contains directly and apparently it works fine as you can see
But when I open the report it show 3 test but with the broken scenario in this example
I try to figure out but I see the configuration is correct and when I run with mvn clean verify command the data in example section don't work I'll show the structure of folders in this image and show the output of the command line in this
I really really appreciate any contribution and help and I don't find any solution of this.
Thanks in advance


text: Q: How can I see the labels of equations in the pdf format? I would like to see the labels for every equations in pdf format? this is easier to refere later by looking for the labels in pdf format not in text file.


text:
Q: Using Artifactory plugin for Jenkins, is there a way to search repos for images with a property? I'm using the Artifactory plugin in Jenkins. I have a situation where I need to pull docker images from Artifactory which have a particular property set. I can search for them using the REST API, but I have not found a way to do this using the Jenkins plugin. Anybody know if there is a way?
Thanks.

A: This is the download spec schema from the documentation:
{
  "files": [
     {
       "pattern" or "aql": "[Mandatory]",
       "target": "[Mandatory]",
       "props": "[Optional]",
       "recursive": "[Optional, Default: true]",
       "flat" : "[Optional, Default: false]"
     }
   ]
 }

Where from my point of view you have a couple of options to search by propeties; one would be using aql where you have such option. Second one would be directly using props, which main purpose seems to be exactly that:

props: List of "key=value" pairs separated by a semi-colon. (For
  example, "key1=value1;key2=value2;key3=value3). Only artifacts with
  all of the specified properties and values will be downloaded.


text:
Q: How to add a new view to the Field Explorer in Crystal Reports I have created a new view and want to add it to an existing crystal report.  In the Database Expert there are options to add a new table but not a new view.  I want to select fields from the view, not the tables.

A: Views are also allowed to be added in the Database Expert. Look into the Crystal Reports Options in the Crystal Reports menu. (Are you using Crystal Reports or Visual Studio?). There will be options to select object types in the database options.
If you create a view after you connect to the database from the Crystal Reports, you may not see the new views. For the views to be visible, go to Database menu and click verify. This will make the new views visible to you.
Otherwise, see if the user you are using to connect to the SQL server has adequate grants to see, use the views or not.

A: If the new view is not visible from within Crystal then try following this menu path:
Database->Verify Database - This will refresh the database.  Then select Database->Add Database to Report...this will open the data explorer and the new view should be visible.


text:
Q: Two errors with FIPS when trying to deploy to device from Xcode 11.1 after upgrading to MacOS Catalina 10.15 I use Blackberry Dynamics SDK in my app and after upgrading to the new MacOS 10.15 Catalina I have issues deploying to a physical device. I cleaned the build folder, cleared the cache, cleared derived data, uninstalled/reinstalled all pods, but I still get the following error:
FINGERTYPE is [path]/FIPS_module/arm64.sdk/bin/../bin/fips_standalone_sha1
CANISTER_O is [path]/FIPS_module/arm64.sdk/bin/../lib/fipscanister.o
[path]/FIPS_module/arm64.sdk/bin/gd_fipsld: line 219: [path]/FIPS_module/arm64.sdk/bin/../bin/fips_standalone_sha1: Bad CPU type in executable
1d0
< HMAC-SHA1(fipscanister.o)= [key]
[path]/FIPS_module/arm64.sdk/bin/../lib/fipscanister.o fingerprint mismatch
Command Ld failed with a nonzero exit code

It builds and deploys fine to a simulator as well as if deployed in an earlier version of MacOS. Not sure where to go from here.

A: While compiling a Blackberry Dynamics app the command fips_standalone_sha1 is called. The fips_standalone_sha1 binary in the Blackberry Dynamics framework is a 32-bit binary. That is not going to work on Catalina.
Mojave still supported 32 bit applications, but it was deprecated, in Catalina 32-bit applications won't run anymore.
You can use a Mojave system, or wait for an update of Blackberry Dynamics SDK that supports Catalina.
EDIT: Blackberry Dynamics has been updated, make sure you are using the latest version

A: Blackberry Dynamics SDK for iOS 6.2 and above supports MacOS Catalina.
I had the same problem but could solve it by updating the SDK.


text:
Q: SED and REGEX for EXIF renaming I was unable to comment on this old post,
How can I rename photos, given the EXIF data?
but it had a comment that seemed exactly what I needed so I started a new post, I hope not bad form.
I get what the code does, the piping from jhead through grep and SED...
for i in *.JPG; do
  j=`jhead "$i" | grep date | sed 's/^File date[^:]\+: \(.\+\)$/\1/'`.jpg
  echo mv -i "$i" "$j"
done

I want a very similar outcome but I'd like to grunge the date a bit, ie. rename/output of:
yyyymmdd-hhmmss
but I can't figure out (translate) the SED regex.
I tried
sed 's/^File date[^:]\+: \(\d{4}\):\(\d\d\):\(\d\d\) \(\d\d\):\(\d\d\):\(\d\d\)$/\1\2\3-\4\5\6/'

but all I get is
File date   :  yyyy:mm:yy hh:mm:ss

I would very much like to understand SED and the regex's that make it work, I realise it is quite powerful for stream editing. I particularly do not understand this part [^:]
I think that sometimes the caret signifies BOL just as $ is EOL ...
But, as I try to post this and I see other SED posts I learn (again?) that "^" is perhaps meaning "not" so
[^:] means "match NOT :" .. ? But then just after that IS a :
anyway, lost I am.

A: AFAICT, it looks like you want to change the space in the date string to a - character?
That's actually pretty easy....but, first, there are some problems with that shell script.  Firstly, it uses backticks for command substitution instead of $( and ).   Secondly, it uses grep unnecessarily (sed can do what grep's doing here).  Thirdly, the regex search and replace you want to do is much easier to do in two steps than one (first remove the "File date" part of the line, then modify the remaining date string).
Here's an improved version of that script:
for i in *.JPG; do
  j=$(jhead "$i" | sed -n -E '/^File date/ { s/^File date +: +//; s/ /-/p}').jpg
  echo mv -i "$i" "$j"
done

In English:  the output of the jhead command is piped into sed.  The sed option -n tell sed not to output any lines unless told to by a p (print) statement.  The -E option tells it to use Extended Regular Expressions (ERE) instead of Basic Regular Expressions (BRE)...this is mostly so I can use the + modifier to match one-or-more spaces.
The sed script itself first checks if the line begins with "File date".  If it does, it executes a block of sed commands (i.e. two or more commands wrapped in { and }).
The first command in the block removes "File date" followed by one-or-more space, a colon, and then one-or-more spaces from the line.  This will result in the line containing just the date.
The second command changes the first (and only) space character with a dash -.   There is a p at the end of this s/// command, which tells sed to print the modified line.
Example run:
$ ls -l *.JPG
-rw-r--r-- 1 cas cas 1110176 Oct 20 14:04 abc.JPG
-rw-r--r-- 1 cas cas 1132711 Oct 20 14:04 def.JPG
-rw-r--r-- 1 cas cas 1061121 Oct 20 14:04 ghi.JPG

$ for i in *.JPG; do
  j="$(jhead "$i" |sed -n -E '/^File date/ { s/^File date +: +//; s/ /-/p }').jpg"
  echo mv -i "$i" "$j"
done
mv -i abc.JPG 2021:10:20-14:04:08.jpg
mv -i def.JPG 2021:10:20-14:04:09.jpg
mv -i ghi.JPG 2021:10:20-14:04:10.jpg

BTW, this script is not particularly safe.  It doesn't, for example, take into account the fact that two different jpeg files can have exactly the same timestamp.
Something like the following is far from perfect, but would be safer/better:
for i in *.JPG; do
  j="$(jhead "$i" | sed -n -E '/^File date/ { s/^File date +: +//; s/ /-/p }')"

  c=1
  while [ -e "$j-$c.jpg" ] ; do
    let c+=1
  done
  j="$j-$c"

  mv -iv "$i" "$j.jpg"
done

(note: this version actually renames files, it doesn't just echo what it would do.  This was necessary for testing because if it didn't do that, it wouldn't know when to increment the counter variable, $c)
Example output:
renamed 'abc.JPG' -> '2021:10:20-14:04:08-1.jpg'
renamed 'def.JPG' -> '2021:10:20-14:04:08-2.jpg'
renamed 'ghi.JPG' -> '2021:10:20-14:04:08-3.jpg'

BTW, if you're likely to have more than 9 jpeg files with the same timestamp, you can use printf to make sure the counter is two or three digits and zero-padded. e.g.
for i in *.JPG; do
  j="$(jhead "$i" | sed -n -E '/^File date/ { s/^File date +: +//; s/ /-/p }')"

  c=1
  while [ -e "$(printf "%s-%03i.jpg" "$j" "$c")" ] ; do
    let c+=1
  done
  j="$(printf "%s-%03i.jpg" "$j" "$c")"

  mv -iv "$i" "$j"
done

renamed 'abc.JPG' -> '2021:10:20-14:04:08-001.jpg'
renamed 'def.JPG' -> '2021:10:20-14:04:08-002.jpg'
renamed 'ghi.JPG' -> '2021:10:20-14:04:08-003.jpg'

RE: your questions about the caret ^ character.
Outside of a bracket expression, it's a beginning-of-line anchor - e.g. ^File date matches "File date" only at the start of a line.
Inside a bracket expression, it negates/inverts the meaning of the expression.  e.g. where [A-Z] matches all characters from A to Z, [^A-Z] matches all characters which are not between A and Z.

A: Why reinvent the wheel?
jhead has an option to do exactly what you want.

-n[format_string]
This option causes files to be renamed and/ or mmoved [sic!] using the date information from the Exif header "DateTimeOriginal" field.

Even multiple photos with the same time stamp are considered:

If the target name already exists, the name will be appended with "a", "b", "c", etc, unless the name ends with a letter, in which case it will be appended with "0", "1", "2", etc.

Example:
jhead -n%Y%m%d-%H%M%S *.JPG

A: Thank you all so much. I worry about asking dumb questions but I wish to learn so I plop them right out there. Which is why, even though this may have been reinventing the wheel, I did learn something. Much as Jhead might have done it all itself, thank you @pLumo , it was the machinations of SED and (forgetting) regex that had me piqued.
I did see, on more thought, that the [^:]+ was search for one or more characters that are NOT ":"
(thank you @cas) sadly I was too slow to grok that before. And I also was not aware of SED's syntax of using [[:digit:]]. So the line I was trying to build looks like this
j=`jhead "$i" | grep date | sed 's/^File date[^:]\+: \([[:digit:]]\{4\}\):\([[:digit:]]\{2\}\):\([[:digit:]]\{2\}\) \([[:digit:]]\{2\}\):\([[:digit:]]\{2\}\):\([[:digit:]]\{2\}\)$/\1\2\3-\4\5\6/'`.jpg

@cas in this instance yes I was changing to spaces but also removing the ":"s. By learning how to get SED to match the digits allows me to configure any format/pattern  I like rather than just substitute out the delimiters.
My biggest mental block seemed to come from having so many operands being escaped (I hope that's the correct terminology) ie. the backslash before .. everything ! I just couldn't grok it like that.
All your suggestions have given me more coding tools/techniques, I endeavor to make notes so that I can find them before asking more newbie questions!. Big Thanks
We had a lightning storm just after I posted so even though I found my way through I was unable to post a reply sooner - I have to disconnect my desktop and can just do some browsing using my phone, not much for trying to write an essay on the mobile though.

A: Using Raku (formerly known as Perl_6)
for i in *.JPG; do

  j="$(exiftool "$i" |\
    raku -e 'for lines.grep(/"File Modification Date/Time"/).split(":", 2).map(*.trim) -> $k,$v {
      put( $v.subst(":", "-", :x(1..2)).subst(" ", "T").DateTime ~ ".JPG")
      };'
  )";

echo cp -iv "$i" "$j";
done

Sample Input:
footer_divider_test1.JPG footer_divider_test2.JPG

Sample Output (removing echo):
overwrite 2021-10-21T21:01:31-07:00.JPG? (y/n [n]) y
footer_divider_test1.JPG -> 2021-10-21T21:01:31-07:00.JPG
overwrite 2021-10-21T21:01:31-07:00.JPG? (y/n [n]) y
footer_divider_test2.JPG -> 2021-10-21T21:01:31-07:00.JPG

Here's an approach using Raku, the language formerly known as Perl6--released as Perl6 in 2015; renamed Raku in 2019. Hoping for a challenge, the input .JPG file(s) I'm starting with are graphics that actually have three rows of Date/Time information (data is extracted from the line File Modification Date/Time, above). The above code starts with exiftool output (sorry no jhead here). And because no iterator is included, the caveats mentioned by @cas still apply.
The exiftool output is piped into Raku, which implements a classic idiom: lines containing the string-literal ("File Modification Date/Time") are grep-ped out, these lines are split on : colon into a maximum of 2 elements, and each element is trim-med to remove whitespace.
Element pairs are assigned to variables $k,$v, and the second ($v) containing the date/time is passed through two subst() routines. These routines A). convert the :x(1..2) first-and-second (date) : colons into - hyphens, and B). convert a " " blank space into T. The reason to do these last two tweaks is because afterwards, Raku's .DateTime routine recognizes the input as a valid ISO 8601 timestamp.
Why do all this work as compared to sed? Well, the benefits of using a valid ISO 8601 timestamp are huge because Raku provides built-in support for these objects (no external libraries necessary). The most obvious result (first of all) is that \([[:digit:]]\{4\}\):\([[:digit:]]\{2\}\):\([[:digit:]]\{2\}\) grunging is eliminated.
Second of all, now you have access to Raku's built-in DateTime routines, such as:

*

*method year, method month, method day, method formatter, method is-leap-year, method day-of-month, method day-of-week, method day-of-year, method days-in-month, method week, method week-number, method week-year, method weekday-of-month, method yyyy-mm-dd, method mm-dd-yyyy, method dd-mm-yyyy, method daycount, method IO, method earlier, method later.

So, lets say you want only the date in YYYY-MM-DD format (ISO 8601). That's easy: just insert the .yyyy-mm-dd routine in the method chain after .DateTime. Or how about the day-of-year? just insert the .day-of-year routine in the method chain after .DateTime. (Or a custom date format? Use the date .formatter to design your own). Short example:
STD (ISO 8601):
~$ exiftool footer_divider_test1.JPG | raku -e 'for lines.grep(/"Date/Time"/).map(*.split(":", 2 )) { for .map(*.trim) -> $k,$v { say($k => $v.values.subst(":", "-", :x(1..2)).subst(" ", "T").DateTime ) }; };'
File Modification Date/Time => 2021-10-21T21:01:31-07:00
File Access Date/Time => 2021-10-23T09:38:33-07:00
File Inode Change Date/Time => 2021-10-22T23:10:27-07:00

YYYY-MM-DD (ISO 8601):
~$ exiftool footer_divider_test1.JPG | raku -e 'for lines.grep(/"Date/Time"/).map(*.split(":", 2 )) { for .map(*.trim) -> $k,$v { say($k => $v.values.subst(":", "-", :x(1..2)).subst(" ", "T").DateTime.yyyy-mm-dd ) }; };'
File Modification Date/Time => 2021-10-21
File Access Date/Time => 2021-10-23
File Inode Change Date/Time => 2021-10-22

Finally, while some programmers may prefer shell scripting, Raku does provide a dir() routine for pulling out file names, as well as a rename() routine for renaming files and directories. These functions may be useful to implement a script on platforms where classic shell-mediated file-globbing is limited and/or absent (see SO link below).
https://en.wikipedia.org/wiki/ISO_8601
https://docs.raku.org/language/temporal
https://docs.raku.org/type/Dateish
https://stackoverflow.com/questions/69384754/how-do-i-use-raku-e-and-n-with-multiple-file-glob/69400187
https://raku.org


text:
Q: What Are Some Quirks/Surprises with Using .mm Files in Objective-C? I want to use some C++ STL collections in my Objective-C iPhone app.  Apparently this is possible by giving files the extension ".mm" .  What are some of the quirks/surprises associated with this?
I want to use the basic containers that I'm familiar with (vector, queue, set, ...)
Cheers!

A: See Using C++ With Objective-C for a detailed list of what you can and can't do.  You can do most things that you would expect.  You just can't do things like have a C++ class inherit from an Objective-C class or vice-versa, you can't mix C++ exceptions with Objective-C exceptions, and C++ introduces several new keywords not present in Objective-C.

A: The major quirk of Objective-C++ is that if you don't pass -fobjc-call-cxx-cdtors to g++, it won't call the constructor and destructor of C++ instance variables in of ObjC objects. So remember to turn that option on and you should be good.

A: The files will be compiled with the Objective-C++ compiler, so things will behave more like g++ than gcc, but since that's what you want it probably doesn't count as a surprise. From the Objective-C side, I'm not aware of any gotchas, and I've worked on several large projects that made significant used of Objective-C++. Just keep in mind that Objective-C reserved words are reserved in Objective-C++ as well, so you can occasionally run into issues with third-party C++ libraries (e.g., if they use "id" as a parameter in a public interface).

A: You'd be surprised how well it works. I haven't really gotten into any problems intermixing Obj-C and C++ in a .mm file.


text:
Q: C - Code after 'if' (and inside a 'while') does not execute A bit of background for this question, I have a linked list with names, in which I wan't to find a user input name. For convenience purposes, I copy the name (if found) to the same buffer, like so:
  aux = filtCountriesHead;  //head of my list
  while (aux != NULL){
    if (strstr(aux->data.name, buffer) != NULL){
      strcpy(buffer, aux->data.name);
      foundName = 1;
      break;
    }
      aux = aux->next;  //this is skipped for some reason
  }

When I run this, it enters an infinite loop, because it does not execute the aux = aux->next line, which I found by running in the debugger. It doesn't execute anything in the 'if' (and even if it did, the 'break;' would make it exit the cycle, not run it again) so I'm all out of ideas. Anyone have an explanation?
Thanks in advance!

A: Without more data, such as observations about aux's values, there is no way to be sure about the core issue. But here's a likely explanation...

If you observe an infinite loop where aux = aux->next; appears to do nothing, that must mean aux->next equals aux, i.e., aux points to itself. Typically the tail of a linked list points to NULL instead.
Of course, the cyclic list structure would need to be fixed elsewhere, since the list isn't being created in the provided code.


text:
Q: How to embed a ruby gem into a C# project and require it from an embedded IronRuby script? I have a C# project in which I have embedded an IronRuby program. The project (including my  ruby script) is compiled to an .exe file in Visual Studio 2010 for distribution. I'm using a pattern similar to this for bootstrapping the IronRuby script: http://pastebin.com/NKes1cyc (and Jimmy Schementi goes into more detail here: http://blog.jimmy.schementi.com/2009/12/ironruby-rubyconf-2009-part-35.html).
My problem: I would like to embed a gem (json_pure) in my C# assembly and call it from the ruby script.
Some resources I've found:

*

*In JRuby, you can easily package a gem into a jar file and then simply require the jar file at runtime - http://blog.nicksieger.com/articles/2009/01/10/jruby-1-1-6-gems-in-a-jar

*The irpack tool (at http://github.com/kumaryu/irpack) is capable of compiling Ruby into an .exe (I think it dynamically creates and compiles a C# project) while embedding the ruby standard library. But it looks like it is only embedding the pre-built IronRuby .dlls, not ruby .rb files. The approach this tool uses would work if I could figure out how to compile Ruby source files into a .dll.
How do I embed an IronRuby gem into a C# assembly (or compile an IronRuby gem to a .dll)?
EDIT:
Page 472 of IronRuby In Action ("Using External Libraries") explains how to require standard ruby libraries from within an embedded ruby file. It involves adding the folder(s) to the runtime search paths collection, as follows (edited for brevity and clarity):
ScriptEngine engine = IronRuby.Ruby.CreateEngine();
var searchPaths = engine.GetSearchPaths().Concat(new[]
{
    "C:\\Program Files (x86)\\IronRuby 1.1\\Lib\\ruby\\1.9.1",
    "C:\\Program Files (x86)\\IronRuby 1.1\\Lib\\ironruby"
});
engine.SetSearchPaths(searchPaths)

This approach assumes the host machine has IronRuby installed, but I want to embed ruby files (from a gem) into the assembly so it can be run without IronRuby pre-installed.
EDIT 2 (further research):
Reading through the source code of the irpack tool referenced above, I notice that Kumaryu is embedding resources into the final assembly via the System.IO.Packaging.Package class, and then passing the package into the call to msbuild (see https://github.com/kumaryu/irpack/blob/master/lib/irpack/packager.rb). Perhaps some further research into packaging files into an executable would lead to a solution. The problem I see is that ruby files in a gem require other ruby files... can a ruby file in an assembly package require other ruby files in the same package?
EDIT 3:
I haven't gotten any further to an answer yet, but I'd be interested to hear anyone's feedback, even if it's just a link or a suggestion about where to look. I'm new to msbuild, and the documentation is pretty hefty. An initial web search for "msbuild embed zip package" didn't reveal anything relevant.

A: Require is a method that can be overridden like any other ruby method. I think that is how the original ruby gems package worked, gems would simply override require.
If you can package the gem into your .exe somehow, you can override require to load from the assembly.

A: try this https://github.com/rifraf/IronRubyAppPackager#readme (or wait for me to report back on whether it works with the library I am trying to embed)
Reporting back:
The process I have gone to is...

*

*fork and submodule all the projects (IronRubyEmbeddedApps, IronRubyAppPackager, Serfs and Vendorize) from https://github.com/rifraf, and added them all into a VS solution. I updated all the projects to .NET4 and made them reference one another, rather than the included .net2 assemblies

*executed Vendorize to rip all the dependencies/gems D:\projects\SomeLibrary\lib_vendor_ by running:
D:\projects\SomeLibrary\lib>ruby -I..\..\Vendorize\lib -rvendorize some_lib.rb

*Generated a c# project at D:\projects\SomeLibrary\lib\_IRPackager_\some_lib.csproj by running:
D:\projects\SomeLibrary\lib>ruby -I..\..\IronRubyAppPackager\lib\IRPackager.rb some_lib.rb

*Added the some_lib.csproj to my solution, upgraded it to .net4 and fixed references

*At this point, you can run the project in .NET, standalone, by running

var Ruby = new EmbeddedRuby();
Ruby.Decoder = new Program.GZipDecoder();
Ruby.Mount("App");
Ruby.Run("gocardless.rb");

And it succeeded! Brilliant I thought!
Actually at this point I discovered that it had failed in step 2 to Vendorize every single required library. Vendorize works by intercepting require calls and then saving the called rb files off to the _Vendor_ - if require is not executed (so run all tests and hope test coverage is 100%) it won't be picked up.
For some reason, it wasn't picking up one of the required files, even though there was a require. In the end, I manually created the content for the vendor directory by copying my library in, and by using bundle install --deployment command. Repeat step 3 and 4 and I'm done... right?
Nope, I get some error about no such file to load -- json/pure when I run the generated project - I think this is something to do a combination of ironruby not having a native json implementation, me doing the manual vendorizing and me having to bodge things at several points today.
To conclude - this method very very nearly works, will work if your library and it dependencies work with ironruby properly, and you can get vendorize to work properly.
I'm giving up and porting the library to c# the old fashioned way.
edit: as mentioned below, rifraf is helping me and looking into updating the tools I was using. watch t(his) space!

A: I am working with https://stackoverflow.com/users/2086/mcintyre321 to get his library wrapped up into C#/IronRuby using my packaging code ( https://github.com/rifraf/IronRubyAppPackager#readme ).
There are some fixes needed in the vendorize step that are related to the later versions of Ruby having RubyGems embedded rather than loaded, but progress is being made.
His code requires 'json', and I have a trick to force it to use the Ruby implementation rather than the C-linkage .so files. This should mean that it will work with IronRuby ok. Will report back, or feel free to contact me with the source that you want to run.


text:
Q: sigsegv при взаимодействии с объектом структуры Я пытаюсь написать класс который хранил бы карту блоков. Написал пробный вариант. Правда оказалось что вариант совсем не работоспособный.

struct block{
    uint units{30};
    sf::Color color{128,128,128};
    int owner_id{-1};
    sf::ConvexShape cube;

    void updateCube(const int &size, const sf::Color &ccolor={128,128,128}){
        cube.setPointCount(4); //sigsegv
        cube.setPoint(0,sf::Vector2f(0,0));
        cube.setPoint(1,sf::Vector2f(0,size));
        cube.setPoint(2,sf::Vector2f(size,size));
        cube.setPoint(3,sf::Vector2f(size,0));
        color = ccolor;
    }
};

class blockmap{
    typedef std::vector<block> line;
    std::vector<line> map;

public:

    blockmap(std::size_t x, std::size_t y, const int size){
        map.resize(y);
        for(std::size_t i{0};i!=y;i++){
            map[i].resize(x);
            for(std::size_t d{0};d!=x;d++){
                map[i][x].updateCube(size);
                map[i][x].cube.setPosition(i*(size+4),x*(size+4));
            }
        }

    }

    std::vector<block>& operator[](const std::size_t index){
        return map[index];
    }

    void draw(sf::RenderWindow &window){
        for(std::size_t y{0};y!=map.size();y++)
            for(std::size_t x{0};x!=map[y].size();x++){
                window.draw(map[x][y].cube);
            }
    }

};

A: ох ох. внутренний цикл под d, а в индексе x. Логично, что выход за пределы
for(std::size_t d = 0;d<x;d++){
    map[i][d].updateCube(size);
    map[i][d].cube.setPosition(i*(size+4),x*(size+4));
}

и пишите нормально for. вот это d!=i когда то очень больно может ударить.


text:
Q: how can i use cuda with nodejs Cuda is Nivida provided api that lets c/c++ use gpu for some stuff, even though i don't what that some stuff is & would like to know, from what i saw the gains were remarkable. Also cuda only works for nivida gpus...
There does exist a module for nodejs, but it's only for 64bit version of windows, yet there exists cuda for 32bit version as well so only thing missing binding/extension for nodejs to cuda in c++. And There is no sign of documents anywhere on github or internet about that module. Last commits were like 1/2 year+ ago.
If it's all possible than it'd be very great. As nodejs would be able to use gpu for operations, putting it in the whole new level for web stuff, and other applications. Also given parallel nature of nodejs it fits perfectly with gpu's parallel nature.
Suppose there is no module that exists right now. What are my choices.
it's been done already by someone else: http://www.cs.cmu.edu/afs/cs/academic/class/15418-s12/www/competition/r2jitu.com/418/final_report.pdf

A: here is a binding.gyp file that will build a node extension using two source files
hello.cpp,  goodby.cu, and goodby1.cu
{
  ## for windows, be sure to do node-gyp rebuild -msvs_version=2013,
  ## and run under a msvs shell

  ## for all targets
  'conditions': [
    [ 'OS=="win"', {'variables': {'obj': 'obj'}},
    {'variables': {'obj': 'o'}}]],

  "targets": [
{
 "target_name": "hello",
 "sources": [ "hello.cpp", "goodby.cu", "goodby1.cu",],

 'rules': [{
     'extension': 'cu',
     'inputs': ['<(RULE_INPUT_PATH)'],
     'outputs':[ '<(INTERMEDIATE_DIR)/<(RULE_INPUT_ROOT).<(obj)'],
     'conditions': [
      [ 'OS=="win"',
        {'rule_name': 'cuda on windows',
         'message': "compile cuda file on windows",
         'process_outputs_as_sources': 0,
         'action': ['nvcc -c <(_inputs) -o  <(_outputs)'],
         },
       {'rule_name': 'cuda on linux',
         'message': "compile cuda file on linux",
         'process_outputs_as_sources': 1,
         'action': ['nvcc','-Xcompiler','-fpic','-c',
            '<@(_inputs)','-o','<@(_outputs)'],
    }]]}],

   'conditions': [
    [ 'OS=="mac"', {
      'libraries': ['-framework CUDA'],
      'include_dirs': ['/usr/local/include'],
      'library_dirs': ['/usr/local/lib'],
    }],
    [ 'OS=="linux"', {
      'libraries': ['-lcuda', '-lcudart'],
      'include_dirs': ['/usr/local/include'],
      'library_dirs': ['/usr/local/lib', '/usr/local/cuda/lib64'],
    }],
    [ 'OS=="win"', {
      'conditions': [
        ['target_arch=="x64"',
          {
            'variables': { 'arch': 'x64' }
          }, {
            'variables': { 'arch': 'Win32' }
          }
        ],
      ],
      'variables': {
        'cuda_root%': '$(CUDA_PATH)'
      },
      'libraries': [
        '-l<(cuda_root)/lib/<(arch)/cuda.lib',
        '-l<(cuda_root)/lib/<(arch)/cudart.lib',
      ],
      "include_dirs": [
        "<(cuda_root)/include",
      ],
    }, {
      "include_dirs": [
        "/usr/local/cuda/include"
      ],
    }]
  ]
}
]
}

A: The proper way to do this is to use the Nvidia CUDA toolkit to write your cuda app in C++ and then invoke it as a separate process from node. This way you can get the most from CUDA and draw on the power of node for controlling that process.
For example, if you have a cuda application and you want to scale it to, say, 32 computers, you would write the application in fast C or C++ and then use node to push it to all the PC's in the cluster and handle communication with each remote process over the network. Node shines in this area. Once each CUDA app instance finishes it's job, you join all the data with node and present it to the user.

A: The most natural way to hook up CUDA and Node.js would be through an "addon", which allows you to expose c++ code to your javascript programs running on node.
Node itself is a c++ app built on top of the v8 javascript engine, and addons are a way for you to write c++ libraries that can be used by javascript libraries in the same sort of way that node's own libraries do.
From the outside, an addon just looks like a module.  The c++ gets compiled into a dynamic library and then exposed to node like any other module.
e.g. my-addon.cc -> (compile) -> my-addon.dylib -> (node-gyp) -> my-addon.node -> var myFoo = require('my-addon').foo()
From inside the addon, you use the v8 and Node APIs to interface with the Javascript environment, and access CUDA with the the normal c++ APIs.
There are a lot of moving parts down at this level.  Something as simple as passing a value from one to the other means you need to worry about both c++ memory management and the javascript garbage collector while you wrap/unwrap javascript values to and from appropriate c++ types.
The good news is that most of the issues are fine individually, with great docs and supporting libraries abounding e.g. nan will get a skeleton addon running in no time, and on the CUDA side, you're talking about their normal c++ interface, with truckloads of of docs and tutorials.


text:
Q: How to read a specific string from a text file as output variable in SSIS? I am downloading a webpage as a text file in order to read a specific string to assign it as a variable/parameter in order to create an output file name. I would like to know how would I be able to look for a specific string and output as another variable for the rest of the package.

2015 Conforming Loan Limits

------------------------------------------------------------------------

      o _Loan Limits for Calendar Year 2015--All Counties  _[XLS]
        </DataTools/Downloads/Documents/Conforming-Loan-Limits/FullCountyLoanLimitList2015_HERA-BASED_FINAL_FLAT.xlsx>_ ,
        _[PDF]
        </DataTools/Downloads/Documents/Conforming-Loan-Limits/FullCountyLoanLimitList2015_HERA-BASED_FINAL.pdf>_

      o _List of 46 Counties with Increases in Loan Limits for 2015
        _[XLS]
        </DataTools/Downloads/Documents/Conforming-Loan-Limits/Counties_with_increases_cy2015_FLAT.xlsx>_
        , _[PDF]
        </DataTools/Downloads/Documents/Conforming-Loan-Limits/Counties_with_increases_cy2015.pdf>_

    Previous Announced Loan Limits

------------------------------------------------------------------------

*Description*  *Format*

Maximum Loan Limits for Loans (a) Acquired in Calendar Year 2014 and
(b) Originated after 9/30/2011 or Prior to 7/1/2007

 [XLS]
</DataTools/Downloads/Documents/Conforming-Loan-Limits/FullCountyLoanLimitList2014_HERA-BASED_FINAL_FLAT.xls>

Maximum Loan Limits for Loans (a) Acquired in Calendar Year 2013 and
(b) Originated after 9/30/2011 or Prior to 7/1/2007

[XLS]
</DataTools/Downloads/Documents/Conforming-Loan-Limits/FullCountyLoanLimitList2013_HERA-BASED_FINAL.xls>

Maximum Loan Limits for Loans (a) Acquired in Calendar Year 2012 and
(b) Originated after 9/30/2011 or Prior to 7/1/2007

[XLS]
</DataTools/Downloads/Documents/Conforming-Loan-Limits/FullCountyLoanLimitList2012_HERA-BASED_FINAL_Z.xls>

To explain it a more better way, I have a sample webpage text here. I should be searching for "FullCountyLoanLimitList" appended by the current year (like FullCountyLoanLimitList2015) and copy the entire file name in the text file and assign it to another variable so that I can download that specific file using WebClient connection.
Please let me know if you need more detailed information for you to help me.
Thanks so much!


text:
Q: Авторизация при проксировании nginx подскажите пожалуйста как можно реализовать авторизацию при проксировании. Есть два сервера(бекенд и фронт). По требованиям безопасности необходимо чтобы было проксирование с фронта на бек по защищенному соединению с авторизацией по сертификату. В данный момент реализовано только соединение.
location @laravel {
    proxy_pass https://test:9000;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote addr;
    proxy_ssl_verify on;
    proxy_ssl_session_reuse on;
    proxy_ssl_certificate /etc/nginx/certificates/test.cer;
    proxy_ssl_certificate_key /etc/nginx/certificates/test.key;
    proxy_ssl_trusted_certificate /etc/nginx/certificates/testca.cer;
    proxy_ssl_verify_depth 2;
    proxy ssl ciphers "ECDHE-ECDSA-AES256-GCM-SHA384: ECDHE-RSA-AES256-GCM-SHA384: ECDHE-ECDSA-CHACHA20-POLY1305: ECDHE-RSA-CHACHA20-POLY1305: ECDHE-RSA-AES128-SHA256";
}


text:
Q: ReactJs functions that need refractoring (if possible) I have a few functions I've written for a basic e-commerce store, but both seem a little lengthy to me.
Perhaps someone out there has some suggestions on how I might be able to refractor them?
Cheers.
1 - a function that had adds an item to the cart or wishlist based on an action:

 addToFunnelHandler = (uuid, price, title, action) => {
  let productToAdd = {}
      productToAdd.uuid = uuid
      productToAdd.price = price
      productToAdd.title = title
      if (action === 'bag') {
        let productsInBag = [...this.state.productsInBag]
        productsInBag.push(productToAdd)
        this.setState({ productsInBag: productsInBag, bagCount: this.state.bagCount + 1, bagTotal: this.state.bagTotal + price })
    } else if (action === 'wishlist') {
        let productsInWishlist = [...this.state.productsInWishlist]
        productsInWishlist.push(productToAdd)
        this.setState({ productsInWishlist: productsInWishlist, wishlistCount: this.state.wishlistCount + 1})
    }
  }

2 - Same but in reverse, removing an item from the funnel:

removeFromFunnelHandler = (uuid, price, action) => {
    if (action === 'bag') {
      let productsInBag = [...this.state.productsInBag]
      productsInBag.forEach((product, index) => {
      if (product.uuid === uuid) { productsInBag.splice(index, 1) }
     })
    this.setState({ productsInBag: productsInBag, bagCount: this.state.bagCount - 1, bagTotal: this.state.bagTotal - price  })
  } else if (action === 'wishlist') {
      let productsInWishlist = [...this.state.productsInWishlist]
      productsInWishlist.forEach( (product, index) => {
      if (product.uuid === uuid) { productsInWishlist.splice(index, 1) }
     })
    this.setState({ productsInWishlist: productsInWishlist, wishlistCount: this.state.wishlistCount - 1 })
    }
  }

A: As for the first function, you could remove most of the declarations:

*

*Declare productToAdd in one go

*Rather than pushing, just include the value in the array

addToFunnelHandler = (uuid, price, title, action) => {
  let productToAdd = { uuid, price, title }
  if (action === 'bag') {
    this.setState({ productsInBag: [...this.state.productsInBag, productToAdd], bagCount: this.state.bagCount + 1, bagTotal: this.state.bagTotal + price })
  } else if (action === 'wishlist') {
    this.setState({ productsInWishlist: [...this.state.productsInWishlist, productToAdd], wishlistCount: this.state.wishlistCount + 1 })
  }
}

For the second, there's not much to refactor without more context:

*

*Use inline if statements

*Use shorthand property assiging

*Use filter over forEach

removeFromFunnelHandler = (uuid, price, action) => {
  if (action === 'bag') {
    const productsInBag = [...this.state.productsInBag].filter(product => product.uuid !== uuid)
    this.setState({ productsInBag, bagCount: this.state.bagCount - 1, bagTotal: this.state.bagTotal - price })
  } else if (action === 'wishlist') {
    const productsInWishlist = [...this.state.productsInWishlist].filter(product => product.uuid !== uuid)
    this.setState({ productsInWishlist, wishlistCount: this.state.wishlistCount - 1 })
  }
}


text:
Q: Gtk.Bin derived class does not receive MotionNotifyEvent i am developing a Gtk# based application which uses a custom widget derived from Gtk.Bin. For some reason not known to me, it does not receive mouse movement events. The code below is never called:
    [GLib.ConnectBefore]
    protected override bool OnMotionNotifyEvent (Gdk.EventMotion evnt)
    {
        Console.Out.WriteLine( "Mouse move!" );

        return base.OnMotionNotifyEvent (evnt);
    }

I have also extended the Event mask of the widget to receive all events (in the constructor):
AddEvents(( int ) Gdk.EventMask.AllEventsMask );

Any ideas?

A: Gtk.Bin is a windowless container so it does not receive mouse events by default.
You can create a Gdk.Window manually in your subclass in order to receive mouse events, or the easier path is to subclass Gtk.EventBox, which is a Gtk.Bin subclass designed for this purpose by internally creating its own Gdk window.


text:
Q: How can I read and convert my pdf file stored as bytea in postgresql through flask I have one column in my postgreSQL table fails as email_pdf, in which I have saved my pdf file as bytea type. Now I wants to save/retrieve this through a function in my flask app.
I am getting error as seen in the image.

select email_pdf from fails where fail_id = 9

My flask function looks as below :
@app.route('/download_file')
def downloadFile ():
    cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
    s = "select email_pdf from fails where fail_id = 9"
    cur.execute(s)
    list_data = cur.fetchall()
    return send_file(BytesIO(list_data[0][0]), as_attachment=True,download_name="new.pdf")

I am able to save file when I redirect to /download_file but when I am opening it. it is showing nothing or error. Can someone please help me what is wrong in my code or how can I download and convert binary data into pdf file. Thanks in advance.


text:
Q: sql query to find table_name and count(table_name) in a schema sql query to find table_name and count(table_name) in a schema:
Example:
I get the table_name from this query:
SELECT * FROM USER_TABLES

and count(table_name) from
select count(*) from employee
select count(*) from dept
select count(*) from subjects

now i want to get the result like this:
table_name     count(table_name)
Employee        100
dept            21
subjects        56

A: Try like this
select
       table_name,
       to_number(
         extractvalue(
           xmltype(
             dbms_xmlgen.getxml('select count(*) c ' ||
                                ' from '||owner||'.'||table_name))
           ,'/ROWSET/ROW/C')) count
   from all_tables
  where table_name In (
  SELECT table_name from user_tables )

OR Using Join
select
       a.table_name,
       to_number(
         extractvalue(
           xmltype(
             dbms_xmlgen.getxml('select count(*) c ' ||
                                ' from '||owner||'.'||a.table_name))
           ,'/ROWSET/ROW/C')) count
   from all_tables a JOIN user_tables u ON
  a.table_name=u.table_name  AND a.owner = user

A: Looks like a typical use case for a simple UNION ALL:
select
  'Employee' table_name,
  count(*) from employee
union all
select
  'dept' table_name,
  count(*) from dept
union all
select
  'subjects' table_name,
  count(*) from subjects

If you want to automate this, you can iterate over USER_TABLES:
declare
  l_cnt pls_integer;
begin
  for cur in (select table_name from user_tables order by table_name)
  loop
    execute immediate 'select count(*) from ' || cur.table_name into l_cnt;
    dbms_output.put_line(cur.table_name || ' ' || l_cnt);
  end loop;
end;

Instead of simply printing the result, you can also build a SQL statement dynamically and use that afterwards:
declare
  l_sql varchar2(4000);
begin
  for cur in (select table_name from user_tables order by table_name)
  loop
    l_sql := l_sql || ' select ' || cur.table_name || ' as table_name, count(*) as cnt from ' || cur.table_name || ' union all';
  end loop;
  -- remove trailing UNION ALL
  l_sql := regexp_replace(l_sql, 'union all$', '');
  dbms_output.put_line(l_sql);
end;


text:
Q: Using variables in a PHP function Ok, so I've got three files.. for example purposes: config.php, functions.php and index.php
In config.php I have all the variables needed for the site to work, settings, db details, etc.
In functions.php, the function I'm trying to get to work is as follows:
function db_connect() {
    mysql_connect($app_config['mysql_server'], $app_config['mysql_username'], $app_config['mysql_password']) or db_die(__FILE__, __LINE__, mysql_error());
    mysql_select_db($app_config['mysql_database']) or db_die(__FILE__, __LINE__, mysql_error());

}

What this should be referencing, is variables set in config.php, eg:
$app_config['mysql_username'] = "root";
$app_config['mysql_password'] = "password";

Both config.php and functions.php are required in index.php, which uses the function, but in the PHP error log I get the following (more than once for the different instances):
[Mon May 28 02:02:46 2012] [error] [client <removed>] PHP Notice:  Undefined variable: app_config in /usr/home/<removed>/functions.php on line 11

I even tried including config.php in functions.php too, but to no avail. Any ideas as to why this isn't working? I'm sure it's relatively simple, but I just can't fathom it..

A: two options: by contract or global variables
function db_connect() {
    global $app_config;
    mysql_connect($app_config['mysql_server'], $app_config['mysql_username'], $app_config['mysql_password']) or db_die(__FILE__, __LINE__, mysql_error());
    mysql_select_db($app_config['mysql_database']) or db_die(__FILE__, __LINE__, mysql_error());
}

// contract
function db_connect(array $app_config) {
    mysql_connect($app_config['mysql_server'], $app_config['mysql_username'], $app_config['mysql_password']) or db_die(__FILE__, __LINE__, mysql_error());
    mysql_select_db($app_config['mysql_database']) or db_die(__FILE__, __LINE__, mysql_error());
}

although you could do something more "elegant" and create a class

A: global $app_config, you want to put that in the function, before using anything from that variable
That basically says retrieve the $app_config variable from the global namespace for use in this function. PHP globals, although available to all functions, are not involved in that function's namespace until you explicitly ask it to be. That's what's happening for you, you're using the variable before you've 'asked' for it.


text:
Q: Review audits for tag suggestions Nowadays, there are an excessive tag suggestions in Stack Overflow. But, currently we don't have any audits for suggested edits that only change tags.
Why shouldn't we have it?
Share your thoughts.


text:
Q: Where to get good old eclipse for android? First time using Android Studio made me want to die, so I think I won't be switching for a while. I want my eclipse back. I only have eclipse workspace backuped after windows reinstall, so where can I get eclipse and all other stuff required? Google removed download links in their website, they only give Android Studio now.

A: Open your Eclipse em go to Help > Eclipse Marketplace. Search for "Android Development Tools" in the search input text. Wait until Eclipse load and click on "Install" button.


text:
Q: Override de tipagem typescript Quero adicionar uma propriedade user para o request do Express. Para isso criei um arquivo chamado express.d.ts com o seguinte conteúdo:
declare namespace Express {
    export interface Request {
        user: {
           id: string;
        }
    }
}

Ao tentar acessar no meu middleware a propriedade request.user criada, tenho o seguinte erro:
- error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs>'.

Código da classe className.ts do middleware:
export default function methodName(request: Request, response: Response, next: NextFunction): void{
    request.user = {
        id: 10,
    }
}

Estrutura das pastas:
src
     @types
          express.d.ts
     middlewares
          className.ts

A: Tenta fazer assim no arquivo de declaração do express que você criou:
declare namespace Express {
export interface Request {
user?: {
id: string;
}
}
}
colocando como opcional

A: Add essa linha no seu scripts package.json
"dev:server": "ts-node-dev --inspect --transpile-only --ignore-watch node_modules src/server.ts",


text:
Q: Stored Procedure to generate IDs returning duplicate values I'm currently working in a legacy application that uses an Stored Procedure in a Sybase DB to generate some IDs incrementally. The procedure is defined as:
CREATE PROC getId
(@val int = -1 output)
AS
BEGIN
UPDATE ID_TABLE SET LAST_VALUE = LAST_VALUE + 1
SELECT @val = LAST_VALUE FROM ID_TABLE
RETURN @val
END

This procedure is being called from a Java application using Spring's TransactionTemplate to handle the transaction in a declarative manner.
public Integer getId() {
    TransactionTemplate txTemplate = new TransactionTemplate(txManager); // txManager is an autowired instance of PlatformTransactionManager.
    txTemplate.setIsolationLevel(TransactionDefinition.ISOLATION_SERIALIZABLE);
    txTemplate.setTimeout(-1);
    return (Integer) txTemplate.execute((TransactionCallback) status -> idDao.generateId());
}

Internally, idDao uses a JdbcTemplate to call the Stored Procedure using a CallableStatementCreatorFactory. Nothing too out of the ordinary there.
The Stored Procedure is called ~10k times/day. From time to time, we see some ID collisions. My understanding was that the isolation level being set to SERIALIZABLE should prevent this from happening, and I can't seem to reproduce this even calling getId simultaneously with several threads. Does anybody have a hint on what might be happening here?

A: I can't speak to the java/spring coding but on a purely SQL basis it looks and sounds like the update/select is not being performed within a transaction.
Without a transaction wrapper (eg, explicit begin/commit tran, autocommit=false, set chained on) the update/select is a prime target for a race condition and duplicate key errors.
NOTE: the isolation level has no effect if the update/select is performed outside of a transaction wrapper
Tracking down a 'missing transaction wrapper' issue is a good idea as there could be other pieces of SQL code suffering from poor/missing transaction management.  Having said that ...
For this particular case one easy fix would be to add a transaction wrapper in the proc, eg:
CREATE PROC getId
(@val int = -1 output)
AS
BEGIN

begin tran
    UPDATE ID_TABLE SET LAST_VALUE = LAST_VALUE + 1
    SELECT @val = LAST_VALUE FROM ID_TABLE
commit tran

RETURN @val
END

Even better would be a rewrite of the update that eliminates the need for the select, eg:
CREATE PROC getId
(@val int = -1 output)
AS
BEGIN

UPDATE ID_TABLE SET @val=LAST_VALUE+1, LAST_VALUE = LAST_VALUE + 1

RETURN @val
END

NOTE: as a standalone operation this eliminates the need for a transaction wrapper and should eliminate the generation of duplicate keys (assuming this proc is the root cause of the duplicate key issue)
Assuming this is Sybase ASE I'd want to look at making sure the table is configured to use datarows locking; with allpages locking, and to a limited extent datapages locking, there's a chance of a race condition on index updates (which in turn could lead to a deadlock scenario).


text:
Q: ExtJS with React, scope confusion In my app I use ExtJS with React. I've tried to override some functionalities but I faced some problems when defining custom Ext components. I suspect that this is caused by different scopes of "this".
There are 2 scenarios. The 1st one is working scenario, but achieved in non-elegant way. The 2nd scenario is desired but it doesn't work.

Scenario 1 - it works - codepen #1
index.js
// defined globally, it's not very nice
Ext.define('CustomContextMenu', {
    extend: 'Dummy.plugin.ContextMenu',
    createMenuItems: function() {
        return this.callParent() // keep standard behaviour
    }
});

ReactDOM.render(
    React.createElement(CustomScheduleApp),
    document.getElementById('schedule-app')
);

app.jsx
class CustomScheduleApp extends React.Component {
    ...
    render() {
        <CustomSchedule ...></CustomSchedule>
    }

}

schedule.jsx
class CustomSchedule extends React.Component {
    ...
    componentDidMount() {
        let taskContextMenu = Ext.create("CustomContextMenu");
        ...
    }
}

Scenario 2 - it doesn't work - codepen #2
index.js
ReactDOM.render(
    React.createElement(CustomScheduleApp),
    document.getElementById('schedule-app')
);

app.jsx
class CustomScheduleApp extends React.Component {
    ...
    render() {
        <CustomSchedule ...></CustomSchedule>
    }

}

schedule.jsx
class CustomSchedule extends React.Component {
    ...
    componentDidMount() {
        Ext.define('CustomContextMenu', {
            extend: 'Dummy.plugin.ContextMenu',
            createMenuItems: function() {
                return this.callParent() // keep standard behaviour
                // "this" has fewer keys in this scenario, some data is missing
            }
        });

        let taskContextMenu = Ext.create("CustomContextMenu");
        ...
    }
}

Error message for Scenario #2:
Uncaught TypeError: Cannot read property 'apply' of null

I have a basic knowledge about scopes, I'm not even sure if it's more React of JavaScript issue. Am I missing something in my code?

A: Because the way React works and you are setting your extended method inside a React prototype, ExtJS callParent is getting confused about where the event is called from, so you would have to specify this manually.
addBodyCls: function(cls) {
     // custom logic here
     console.log("inside addBodyCls");
     return this.superclass.addBodyCls.apply(this, arguments);
 }

should do the trick!


text:
Q: Use another source if external service is down In my project i'm using following small library for interacting with the external serivce:
class ExternalServiceInteraction
  include Singleton

    URL = Rails.env.production? ? 'https://first.production.url.com' : 'http://sandbox.url.com'
    API_KEY = Rails.env.production? ? 'qwerty' : 'qwerty'
    DOMAIN = Rails.env.production? ? 'prod.net' : 'stage.net'

  def connection
    conn = Faraday.new(url: URL) do |faraday|
      faraday.response :logger                  # log requests to STDOUT
      faraday.adapter  Faraday.default_adapter  # make requests with Net::HTTP
    end
  end

  def return_response(item=true)
    if @resp.status == 200
      response = item ? Hash.from_xml(@resp.body)['xml']['item'] : Hash.from_xml(@resp.body)['xml']
    else
      response =  Hash.from_xml(@resp.body)['xml']['error']
      Rails.logger.info "response_error=#{response}"
    end
    response
  end

  def get_subscribers
    path = 'subscribers'
    data = { 'X-API-KEY' => API_KEY, 'domain' => DOMAIN }
    @resp = connection.get(path, data)
    return_response
  end

  def get_subscriber(physical_id)
    path = 'subscriber'
    data = { 'X-API-KEY' => API_KEY, 'Physical_ID' => physical_id, 'domain' => DOMAIN }
    @resp = connection.get(path, data)
    return_response
  end
  # and so on
end

Now i want to use 'https://second.production.url.com' if the there are any error with interacting service via first url, how will be better to setup this?
At first i tried to ping / get 200 ok from server and if this fails, than i switch to the second URL. But there are situations when server is up and running, returns 200 OK, but API isn't reachable. My mains issue is that i don't see how i can catch error and re-run method with another URL from the library.

A: Create an ExternalServiceInteractionWithoutFallback which would accept a URL in the constructor. Then, move all API methods to this one, and in ExternalServiceInteraction you catch all API methods with method_missing and delegate to an "active" instance of ExternalServiceInteractionWithoutFallback, and if the call fails, you change the instance you delegate to.

A: I write my own HostBackup Faraday middleware for this case.
You are welcome to use it! https://github.com/dpsk/faraday_middleware
Here is an article: http://nikalyuk.in/blog/2013/06/25/faraday-using-backup-host-for-remote-request/


text:
Q: trying to connect two pug files but not able to do that I am trying to link two pug files but not able to do that and I am using koajs and mongodb
input(type='button', onclick="abc.pug", value='click here')

So can anyone help me?

A: You can't link to another Pug file. You would link to the HTML file that the desired Pug file compiles to. In your case, you need to link to abc.html instead of abc.pug.
EDIT: You're using the onclick attribute for the button, instead of using an anchor tag to create a link to another page. You need to use an a tag to link to another page, not a button.
Click here

onclick is reserved for running a JavaScript function when the button is clicked. If you need to make it a button and link to something, use CSS to visually style the anchor as if it were a button (e.g. class="button").


text:
Q: How to get the VHD of an Azure managed disk? I have created a VM with a managed disk. Managed disks are no longer stored into the blob storage by default. Problem is that I now need the vhd file of the osdisk, but I am unable to find a proper way to retrieve it.
The only method I found is to open the disk in the azure portal and press Export to create a download link to the vhd file. This method is undesired.

A: You can copy/export the VHD of a managed disk to a storage account with PowerShell
#Connect to Azure and set your azure subscription

#Declare Variables
$resourceGroupName = 'xxxxx-rg'
$snapshotName = 'xxxxxx.md'
$resourceGroupNameStorageAccount = 'xxxx-rg'
$storageAccountName = 'xxxx-storage'
$storageContainerName = 'xxxxx'
$destinationVHDFileName = 'xxxxxx.vhd'

#Get the Storage Account Key of the Destination Storage Account
$storageAccountKey = Get-AzStorageAccountKey -resourceGroupName $resourceGroupNameStorageAccount -AccountName $storageAccountName

#Generate the SAS for the snapshot
$sas = Grant-AzSnapshotAccess -ResourceGroupName $resourceGroupName -SnapshotName $snapshotName -DurationInSecond 3600 -Access Read

#Create the context of the destination storage account for the snapshot
$destinationContext = New-AzStorageContext -StorageAccountName $storageAccountName -StorageAccountKey ($storageAccountKey).Value[0]

#Copy the snapshot to the destination Storage Account
Start-AzStorageBlobCopy -AbsoluteUri $sas.AccessSAS -DestContainer $storageContainerName -DestContext $destinationContext -DestBlob $destinationVHDFileName

A: Make sure your AzureRM Powershell Module is up to date:
Install-Module AzureRM -allowclobber -force

Your Set-AzureRMVMOSDisk command should now have -ManagedDiskID. Just enter the resource ID for the managed disk and it should work.
Example
$NewVM = New-AzureRMVMConfig -VMName VMName - VMSize "Standard_A1_V2"
Set-AzureRMVMOSDisk -VM $NewVM -Name "DiskName" -CreateOption Attach -Caching ReadWrite -Windows -ManagedDiskID "ManagedDiskResourceID"
New-AzureRmVM -ResourceGroupName "ResourceGroupName" -VM $NewVM -Location CanadaEast

A: For managed disks you do not use a vhd.  Rather, for the disk section, you use a template like this
"osDisk": {
    "osType": "Linux",
    "name": "[parameters('VMName')]",
    "createOption": "FromImage",
    "caching": "ReadWrite",
    "managedDisk": {
        "id": "ManagedDiskID"
    }
}

You reference the disk by managed disk ID rather than uri


text:
Q: $T$ selfadjoint with nonnegative spectrum implies $T=S^2$ for some selfadjoint $S$ I have question regarding the following problem: Let $H$ be a Hilbert space and $T$ a bounded linear operator from $H$ to $H$. If we assume that $T$ is selfadjoint with spectrum in $[0,\infty)$ can we conclude that $T=S^2$ for some selfadjoint bounded operator $S$ (I know that this implies that $T$ is positive but I want to show the implication directly)?
I started to define $X = T-aI$ where $a \in (-\infty,0)$. Then $X$ is selfadjoint and invertible but I don't know how to proceed.

A: The answer is yes. The Theorem on page 265 in Frigyes Riesz and Béla Sz.-Nagy's Functional Analysis (Dover paperback 1990) states:

Every positive symmetric transformation $A$ possesses a positive symmetric square root, and only one, which we denote by $A^{1/2}$. It can be represented as the limit (in the strong sense) of a sequence of polynomials in $A$, and consequently is permutable with all transformations which are permutable with $A$.

What I like about their proof is that it is constructive, there is no compactness assumption, it works in real or complex Hilbert space and does not use the spectral theorem.

A: Let me summarize what I said in the comments.
If your self-adjoint operator $T$ is on a finite dimensional space, or otherwise is a compact operator, then the spectral theorem for compact operators says it has eigenvalues, real eigenvalues due to self-adjointness. And non-negative by hypothesis. Then we may define $S\colon e_i\mapsto \sqrt{\lambda_i}e_i,$ and we will have $S^2=T.$
If $T$ is assumed to be bounded, but not compact, then we are not guaranteed to have eigenvalues, but we still have a complete spectral decomposition. In this case the spectral theorem can take a few forms, in terms of spectral measure, projection-valued measure, and a multiplication operator.
In terms of the projection-valued measure, if we have $T=\int_{\sigma(T)}\lambda\,dE_\lambda$, we may construct $S=\int_{\sigma(T)}\sqrt{\lambda}\,dE_\lambda$ as our square root.
This is the general method by which you can apply any continuous function to an operator, via the Borel functional calculus.


text:
Q: Why doesn't show mongofiles my files? I have a MongoDB, with a password protected database 'files_db' on a 2 server replica set. When I login directly, using commandline options to give username / password it works, and I see the GridFS collection 'documents' (nonstandard name) with quite a lot of files. When I try to access them using Mongofiles however, I don't seem to get access to the files:
[username@mongoserver ~]$ mongo 1.2.3.4/files_db -u username -p 'password'
MongoDB shell version: 2.2.3
connecting to: 1.2.3.4/files_db
> db.documents.files.count()
392743
> exit
bye
[username@mongoserver ~]$mongofiles -vvv --host 1.2.3.4 -d 'files_db' -c 'documents' -u username -p 'password' list
Fri Jul 1 4:55:43 creating new connection to:1.2.3.4:27017
Fri Jul 1 4:55:43 BackgroundJob starting: ConnectBG
Fri Jul 1 4:55:43 connected connection!
connected to: 1.2.3.4
[username@mongoserver ~]$

I don't understand why. At first I had password issue, the user/pass was in another database, so I fixed that. It could be replica set related? I am sure I'm on the primary. I just want to retreive 2 or 3 files for examination.

A: -c is ignored. There's no argument to specify gridfs namespace.

A: refer Using mongofiles with GridFS in a meteor app - Stack Overflow, the collection option actually is prefix -> mongofiles --help show this:
--prefix=<prefix>     GridFS prefix to use (default is 'fs') (default: fs)

and refer list prefix :
list <prefix>
Lists the files in the GridFS store. The characters specified after list (e.g. <prefix>) optionally limit the list of returned items to files that begin with that string of characters.

your command should be:
mongofiles -vvv --host 1.2.3.4 -d files_db username -p password list documents


text:
Q: python manual fft botched Im trying to repoduce the fft functions in python. Iv'e seen a similar question Manual fft not giving me same results as fft here, but I'm having trouble seeing if i'm doing the same error or a different one.
import numpy as np
import numpy.random as npr

N=9 ### 10 -1
MC=10

###Genrate soem data
data=complex(1,0)*npr.uniform(size=(N,MC))+complex(0,1)*npr.uniform(size=(N,MC))

naive_fft=complex(1,0)*np.zeros((N,MC))
for K in range(N):
    for m in range(N):
        phase=(2*np.pi*K*m)/float(N+1)
        naive_fft[K,:]=naive_fft[K,:]+data[m,:]*np.exp(complex(0,1)*phase)

fft=np.fft.fft(data,axis=0)
ifft=np.fft.ifft(data,axis=0)
print('fft')
print(naive_fft-fft)
print('ifft')
print(naive_fft-ifft*(N+1.0))

Comparing my results to the numpy fft i cannot reproduce neither fft nor ifft (only the naive_fft[0,:] seem to match the fft[0,:] values.

A: There are several things to mention. First of all, in Python we use 1j to represent the imaginary unit, not complex(0, 1). If you would like to compare your result to numpy, then you have to check how numpy implements the fft. See the Numpy FFT docs for details. You'll find that numpy follows the most common fft definition, which uses a negative exponent. Furthermore, float(N+1) in your phase is simply wrong. It must read N.
All in all you have:
# ...
naive_fft = np.zeros((N,MC), dtype='complex')
for K in range(N):
    for m in range(N):
        phase=(-2*np.pi*K*m) / float(N)
        naive_fft[K] += data[m] * np.exp(phase*1j)

xfft = np.fft.fft(data, axis=0)
# ...

Test it with
>>> np.isclose(xfft, naive_fft).all()
    True

The inverse transformation works analogously but with a positive exponent.


text:
Q: Can I inject a CSS file programmatically using a content script js file? Can I inject a CSS file programmatically using a content script js file?
It is possible for me to inject the css when the js file is linked to my popup.html. The problem is I have to click on the button to open the popup to inject the css. I want it to happen automatically and in the background.
What happens in my code...

*

*Get a variable from a MySQL database through a XMLHttpRequest

*Call the function, "processdata()"

*"processdata" Will process the data from the XMLHttpRequest. More specifically, split the variable, put it into 2 different variables and make them global

*I call the function, "click()"

*"click" Then will set the css after 1250 milliseconds using setTimeout

*I use chrome.tabs.insertCSS to insert the css. The css name is the variable, "currenttheme"

As I mentioned before it does work using the popup. But the popup has to be opened before the CSS gets injected.
How do I make this all happen automatically, without any user interaction?
Here is my code:
    function getData() {
if (window.XMLHttpRequest)
      {// code for IE7+, Firefox, Chrome, Opera, Safari
      xmlhttp=new XMLHttpRequest();
      }
    else
      {// code for IE6, IE5
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
      }
    xmlhttp.onreadystatechange=function()
      {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
        user_data = xmlhttp.responseText;
        window.user_data = user_data;
        processdata();
        }
      }
    xmlhttp.open("GET","http://localhost:8888/g_dta.php",true);
    xmlhttp.send();
}

getData();

function processdata() {
  var downdata = user_data.split('|||||');
  var installedthemes = downdata[0];
  var currenttheme = downdata[1].toString();
  window.currenttheme = currenttheme;
  click();
  }

function click(e) {
      function setCSS() {
          chrome.tabs.insertCSS(null, {file:currenttheme + ".css"});
          }
      setTimeout(function(){setCSS()}, 1250);
      document.getElementById('iFrameLocation').innerHTML = "<iframe src='http://localhost:8888/wr_dta.php?newid="+e.target.id+"'></iframe>";
      getData();
}

document.addEventListener('DOMContentLoaded', function () {
  var divs = document.querySelectorAll('div');
  for (var i = 0; i < divs.length; i++) {
    divs[i].addEventListener('click', click);
  }
});

A: You can programmatically create a new <link> tag and add it to the <head> section just like JS files are loaded dynamically.
var link = document.createElement("link");
link.href = "http://example.com/mystyle.css";
link.type = "text/css";
link.rel = "stylesheet";
document.getElementsByTagName("head")[0].appendChild(link);

Here's an article on the topic.

A: Extension flicker
A trauma to the ecosystem that isn't hard to fix
Preface:
Among many ways to get your css added to a page, most of them cause the screen to flicker - initially showing the page without your css applied, and then later applying it. I've tried several ways, below are my findings.
The gist
You need to append a CSS <link> or a <style> tag in a Content script injected on document_start
That code looks like this:
var link = document.createElement('link');
link.href =  chrome.runtime.getURL('main.css');
  //chrome-extension://<extension id>/main.css
link.rel = 'stylesheet';
document.documentElement.insertBefore(link);

For some dynamic CSS code:
var customStyles = document.createElement('style');
customStyles.appendChild(document.createTextNode(
   'body { background-color: ' + localStorage.getItem('background-color') + '}'
));
document.documentElement.insertBefore(customStyles);

Doing this in a script on document_start ensures there is no flicker!
The reasoning
In this JavaScript file you can handle any number of programmatic things. The URL pattern matching offered in manifest.json is very limited, but here you can actually look at all the ?query_string and #hash of a url, and use full regular expressions and string operations to decide whether or not to inject CSS. That CSS can also be based on settings, and/or coordinate with messaging to the background page.
Parting words

*

*Don't use .insertCSS, you will notice a flicker.

A: It's to simple you could add to the manifest's permissions field : See web_accessible_resources
 , "web_accessible_resources": [
        "mystyle.css"
    ]

and also add this in content_scripts
"content_scripts": [
    {
        "matches": ["<all_urls>"],
        "css": ["mystyle.css"],
        "js": ["jquery-1.10.2.min.js","content.js","my.min.js"]
    }],

you also add same thing using Programmatic injection and insertCSS().
chrome.tabs.insertCSS(integer tabId, object details, function callback)


text:
Q: Could you tell me how to solve "No such slot listofblogs::map() in ../lab1/listofblogs.cpp:50" in QT I added a button in each row in TableView.
But, I keep getting this error when I click the button and I have no idea why.
I searched many sites and Q&A, but I could not solve it.
So could anyone help me?
The following code is a header file
//list of blog.h
#ifndef LISTOFBLOGS_H
#define LISTOFBLOGS_H

#include <QJsonArray>
#include <QDialog>
#include <QFont>
#include <QSignalMapper>

namespace Ui {
class listofblogs;
}

class listofblogs : public QDialog
{
    Q_OBJECT

public:
    explicit listofblogs(QWidget *parent = nullptr);
    ~listofblogs();
    void setuserID(QString userID);
    QString getuserID();

private slots:
    void on_pushButton_clicked();
    void doSomething(int row);

private:
    Ui::listofblogs *ui;
    QString UserID;
    QSignalMapper *signalMapper;
};

#endif // LISTOFBLOGS_H

Then, this is the c++ source code.
#include "listofblogs.h"
#include "ui_listofblogs.h"
#include "readandwritejson.h"
#include "blog.h"

void listofblogs::doSomething(int row){
    qDebug()<<row;
}

listofblogs::listofblogs(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::listofblogs)
{
    ui->setupUi(this);
    QFont font=ui->label_2->font();
    font.setPointSize(16);
    ui->label_2->setFont(font);
    QTableWidget *tw = ui->tableWidget;
    tw->clear();
    tw->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);
    QStringList columns;
    columns << "title" << "userID" << "time"<< "open content";
    QJsonArray bloglist=readbloglist();
    int row = bloglist.size();
    int col = columns.size();
    tw->setRowCount(row);
    tw->setColumnCount(col);
    for (int i = 0; i < col; ++i){
             tw->setHorizontalHeaderItem(i, new QTableWidgetItem(columns.at(i)));
    }
    signalMapper = new QSignalMapper(this);
    for( int i=0; i<row; i++ ) {
        QJsonObject temp = bloglist.at(i).toObject();
        for (int j = 0; j < col-1; j++){

            auto item = tw->model()->index(i, j);
            QString col_data = columns.at(j);
            tw->model()->setData(item, QVariant::fromValue(temp.value("blogData").toObject().value(col_data).toString()));

        }
        //make new button for this row
        auto item = tw->model()->index(i, columns.size()-1);
        QPushButton *cartButton = new QPushButton("open");
        cartButton->setMaximumWidth(50);
        tw->setIndexWidget(item, cartButton);

        connect(cartButton, SIGNAL(clicked(bool)), this, SLOT(map()));
        //connect(cartButton, &QPushButton::clicked, signalMapper, &QSignalMapper::map);
        signalMapper->setMapping(cartButton, i);
    }
    connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(doSomething(int)));
    for(int col = 0; col < columns.size(); col++) {
        tw->resizeColumnToContents(col);
    }
    tw->horizontalHeader()->setStretchLastSection(true);
    tw->setEditTriggers(QAbstractItemView::NoEditTriggers);
    tw->scrollToBottom();
    tw->verticalHeader()->hide();
    tw->setSelectionMode(QAbstractItemView::NoSelection);
    tw->resizeColumnsToContents();
}

listofblogs::~listofblogs()
{
    delete ui;
}
void listofblogs::setuserID(QString userID){
    UserID=userID;
}

QString listofblogs::getuserID(){
    return UserID;
}
void listofblogs::on_pushButton_clicked()
{
    blog *Blog;
    Blog = new blog(this);
    Blog->setuserID(UserID);
    Blog->show();
}

I can compile this code, but when I clicked a button, the following error occurs.
qt.core.qobject.connect: QObject::connect: No such slot listofblogs::map() in ../lab1/listofblogs.cpp:50
qt.core.qobject.connect: QObject::connect:  (receiver name: 'listofblogs')
qt.core.qobject.connect: QObject::connect: No such slot listofblogs::map() in ../lab1/listofblogs.cpp:50
qt.core.qobject.connect: QObject::connect:  (receiver name: 'listofblogs')
qt.core.qobject.connect: QObject::connect: No such slot listofblogs::map() in ../lab1/listofblogs.cpp:50
qt.core.qobject.connect: QObject::connect:  (receiver name: 'listofblogs')
qt.core.qobject.connect: QObject::connect: No such slot listofblogs::map() in ../lab1/listofblogs.cpp:50
qt.core.qobject.connect: QObject::connect:  (receiver name: 'listofblogs')
qt.core.qobject.connect: QObject::connect: No such slot listofblogs::map() in ../lab1/listofblogs.cpp:50
qt.core.qobject.connect: QObject::connect:  (receiver name: 'listofblogs')
qt.core.qobject.connect: QObject::connect: No such slot listofblogs::map() in ../lab1/listofblogs.cpp:50
qt.core.qobject.connect: QObject::connect:  (receiver name: 'listofblogs')
qt.core.qobject.connect: QObject::connect: No such slot listofblogs::map() in ../lab1/listofblogs.cpp:50
qt.core.qobject.connect: QObject::connect:  (receiver name: 'listofblogs')
qt.core.qobject.connect: QObject::connect: No such signal QSignalMapper::mapped(int) in ../lab1/listofblogs.cpp:54
qt.core.qobject.connect: QObject::connect:  (receiver name: 'listofblogs')

I think it happens because of an error of "connect()" function.
Also, when I changed this part from
connect(signalMapper, SIGNAL(mapped(int)), this, SLOT(doSomething(int)));

to
connect(signalMapper, &QSignalMapper::mappedString,
                this, &listofblogs::doSomething(row));

I got this error and could not compile it.
listofblogs.cpp:51:9: error: no matching member function for call to 'connect'
qobject.h:197:36: note: candidate function not viable: no known conversion from 'void (QAbstractButton::*)(bool)' to 'const char *' for 2nd argument
qobject.h:200:36: note: candidate function not viable: no known conversion from 'void (QAbstractButton::*)(bool)' to 'const QMetaMethod' for 2nd argument
qobject.h:443:41: note: candidate function not viable: no known conversion from 'void (QAbstractButton::*)(bool)' to 'const char *' for 2nd argument
qobject.h:217:43: note: candidate template ignored: couldn't infer template argument 'Func2'
qobject.h:258:13: note: candidate template ignored: couldn't infer template argument 'Func2'
qobject.h:297:13: note: candidate template ignored: couldn't infer template argument 'Func2'
qobject.h:249:13: note: candidate function template not viable: requires 3 arguments, but 4 were provided
qobject.h:289:13: note: candidate function template not viable: requires 3 arguments, but 4 were provided