text:
Q: get virtual path from url in asp net mvc 5 I want to convert a URL like http://localhost/app/Uploads/file.png to my application virtual path, i.e., ~/Uploads/file.txt.
My question is how can it be done in asp net mvc?
EDIT: some explanation on my scenario for further clarification.
I have a "Create" form. In this form, the user sets up its profile and can upload a photo to the server. This photo can be previewed by async uploading it to the server. This is accomplished by the action Post() of the FileUploadController, which is an ApiController. This action simply saves the uploaded file to the virtual path "~/Uploads/" and then returns the full URL to the saved file, something like http://localhost/app/Uploads/file.png. Then, the javascript on the page catches this url and updates a <img> tag to display the picture and sets the value of an hidden input field with this URL. This works fine.
Now, I have to implement the Submit action of this "Create" form. Among other things, the action viewmodel receives the URL of the photo, i.e., http://localhost/app/Uploads/file.png, which should be used to copy the file 'file.png' from the temporary location "~/Uploads/file.png" to another location. However, to Copy this file, I need the local path to it and all I have is the URL.

A: You can do something like this.
Write this in your razor view to get the root-relative path
<script type="text/javascript">
   var baseUrl = '@Url.Content("~")';
</script>

Then in your submit button's client action you can access and pass localpath to controller's action method for file copy.
$("#submit").click(function () {
    var localpath = baseUrl + "Uploads/file.png";
    ...
    ...
});

Here is the link to my another post to almost a similar problem.


text:
Q: React-konva double connected objects with arrow I'm trying to expand the Connected Objects demo by allowing two nodes (shapes of Circle class) to be double referenced (A connects to B with Arrow1 and B connects to A with Arrow2). I work with react-konva package.
I have implemented a demo on Code Sandbox with some basic functionality.
On line 5, 6 you'll find the Nodes info, on line 21 there exists a high-order component that creates the Arrow based on the start Node and end Node position.
In the default example, the arrows are working as expected. If you try to set the value of redNode.x to 300 the arrows overlap. The same happens when blueNode.x is equal to -100. This has something to do with the way I calculate the arrows (I suspect the equations on line 38).
Also note that as redNode.x moves to value 300, the two arrows approach each other (this happens on other values too), which is something I do not want to happen. I expect the arrows to have the same shape when the two nodes change position and not to overlap or approach each other. Unfortunately, my lack of mathematics does not help me solve the problem. I also tried to create a custom shape using quadraticCurveTo method without success.
Thanks in advance for the help. I appreciate all the solutions.

A: There are many ways to make curved lines. Here is my attempt to make it better:
import React from "react";
import ReactDOM from "react-dom";
import { Stage, Layer, Circle, Arrow, Text } from "react-konva";

const BLUE_DEFAULTS = {
  x: 100,
  y: 100,
  fill: "blue",
  width: 30,
  height: 30,
  draggable: true
};

const RED_DEFAULTS = {
  x: 100,
  y: 300,
  fill: "red",
  width: 30,
  height: 30,
  draggable: true
};

const Edge = ({ node1, node2 }) => {
  const dx = node1.x - node2.x;
  const dy = node1.y - node2.y;
  let angle = Math.atan2(-dy, dx);

  const radius = 20;
  const curvePower = 30;

  const arrowStart = {
    x: node2.x + -radius * Math.cos(angle + Math.PI),
    y: node2.y + radius * Math.sin(angle + Math.PI)
  };

  const arrowEnd = {
    x: node1.x + -radius * Math.cos(angle),
    y: node1.y + radius * Math.sin(angle)
  };

  const arrowCurve = {
    x:
      (arrowStart.x + arrowEnd.x) / 2 +
      curvePower * Math.cos(angle + Math.PI / 2),
    y:
      (arrowStart.y + arrowEnd.y) / 2 +
      curvePower * Math.sin(angle - Math.PI / 2)
  };

  return (
    <Arrow
      tension={0.2}
      points={[
        arrowStart.x,
        arrowStart.y,
        arrowCurve.x,
        arrowCurve.y,
        arrowEnd.x,
        arrowEnd.y
      ]}
      stroke="#000"
      fill="#000"
      strokeWidth={3}
      pointerWidth={6}
    />
  );
};

const App = () => {
  const [blueNode, updateBlueNode] = React.useState(BLUE_DEFAULTS);
  const [redNode, updateRedNode] = React.useState(RED_DEFAULTS);

  return (
    <Stage width={window.innerWidth} height={window.innerHeight}>
      <Layer>
        <Text text="Drag any node to see connections change" />
        <Edge node1={blueNode} node2={redNode} />
        <Edge node1={redNode} node2={blueNode} />
        <Circle
          {...blueNode}
          onDragMove={e => {
            updateBlueNode({ ...blueNode, ...e.target.position() });
          }}
        />
        <Circle
          {...redNode}
          onDragMove={e => {
            updateRedNode({ ...redNode, ...e.target.position() });
          }}
        />
      </Layer>
    </Stage>
  );
};

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Demo: https://codesandbox.io/s/react-konva-double-connected-objects-m5g22

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL multiple values join to one table - better query? is possible solve this task better way?
I have two mysql tables.
1) z_import_kategorie
id - kategorieHOME - kategoriePP - kategorieP
1  - 2             - 3          -  5
2  - 2             - 4          -  8
3  - 2             - 6          -  7

2) tm_category_lang
id_category - name - lang_id
2           - HOME - 1
2           - Uvod - 2
3           - Bikes - 1
3           - Kola - 2
4           - Windows - 1
4           - Okna - 2
5           - Cars - 1
5           - Auta - 2
6           - Wheels - 1
6           - Disky - 2
7           - Lights - 1
7           - Svetla - 2
8           - Doors - 1
8           - Dvere - 2

I need join kategorieHOME, kategoriePP and kategorieP from table z_import_kategorie to category name from table tm_category_lang in single query.
My query for this is:
SELECT z.*,k1.name AS katHOME,k2.name AS katPP,k3.name AS katP
FROM z_import_kategorie AS z
LEFT JOIN tm_category_lang AS k1 ON(k1.id_category = z.kategorieHOME)
LEFT JOIN tm_category_lang AS k2 ON(k2.id_category = z.kategoriePP)
LEFT JOIN tm_category_lang AS k3 ON(k3.id_category = z.kategorieP)
GROUP BY z.id
ORDER BY z.id ASC

RESULT of query is:

1 - HOME - Bikes - Cars
2 - HOME - Windows - Doors
3 - HOME - Wheels - Lights

Is possible design this query better? My query is working but I dont think that is good.
Thank you.

A: There is no need to use GROUP BY in your query  to fetch the category names so remove it then your query will work.
Try this:
SELECT z.*, k1.name AS katHOME, k2.name AS katPP, k3.name AS katP
FROM z_import_kategorie AS z
LEFT JOIN tm_category_lang AS k1 ON k1.id_category = z.kategorieHOME AND k1.lang_id = 1
LEFT JOIN tm_category_lang AS k2 ON k2.id_category = z.kategoriePP AND k2.lang_id = 1
LEFT JOIN tm_category_lang AS k3 ON k3.id_category = z.kategorieP AND k3.lang_id = 1
ORDER BY z.id ASC


text:
Q: Erasing smaller polygons within bigger in the same layer using PyQGIS I want to erase features by using PyQGIS. I have written this code. So far, it gives me the geometry of each feature polygon layer, but I don't know how to erase it through PyQGIS.
layer = iface.activeLayer() #get active layer
for f in layer.getFeatures():
  geom = f.geometry()
  print(geom.asPolygon()) #get polygon

As the picture suggested, a big polygon contains a small polygon. I want to erase all small polygons in that same layer so if I move a small polygon after erasing hallow will be shown in the big polygon.

A: Let's assume there is a polygon vector layer with several features within other features, see the image below.

Please pay attention, that bigger features do not contain holes.

Using the following code it is possible to delete features whose geometries are within the geometries of bigger features:
layer = iface.activeLayer()

layer.startEditing()

for feat1 in layer.getFeatures():
    geom1 = feat1.geometry()
    for feat2 in layer.getFeatures():
        geom2 = feat2.geometry()
        if geom2.within(geom1) and not geom1.equals(geom2):
            layer.deleteFeature(feat2.id())

layer.commitChanges()

then you can get the following output:


text:
Q: Realtime scrape a chat using Nodejs What I want to do is to build a scraping application on NodeJs from which it m*onitors on Realtime a chat and store certain messages within any database?
What I am wanting to do is the following, I am wanting to capture data from the chat platforms streaming, and thus capture some useful information that helps those who are doing the streaming service;
But I do not know how to start doing this using NodeJs,
What I have been able to do so far has been to capture the data of the messages, however I can not monitor in realtime new messages,
any help in this regard?
What i did so far:
server.js
var express     = require('express');
var fs          = require('fs');
var request     = require('request');
var puppeteer = require('puppeteer');
var app         = express();

app.get('/', function(req, res){

    url = 'https://www.nimo.tv/live/6035521326';

    (async() => {

        const browser = await puppeteer.launch();

        const page = await browser.newPage();
        await page.goto(url);
        await page.waitForSelector('.msg-nickname');

        const messages = await page.evaluate(() => {
            return Array.from(document.querySelectorAll('.msg-nickname'))
                    .map(item => item.innerText);
        });

        console.log(messages);
    })();
    res.send('Check your console!')

});

app.listen('8081')
console.log('Magic happens on port 8081');
exports = module.exports = app;

With this, I get the Nicknames of Users messages and put in an Array, I want to make my application run and receive new Nicknames automatically when the input is done in the chat,
Any help with this challenge?
Maybe I'm going to need to use WebSocket

A: If possible you should use the API, the chat is using. Try to open the network tab inside the Chrome developer tools and try to figure out which network requests are happening.

If that is not possible, you can use a MutationObserver to monitor DOM changes. Expose a function via page.exposeFunction and then listen to relevant changes. You can then insert the obtained data into a database.
Here is some example code to get you started:
const puppeteer = require('puppeteer');
const { Client } = require('pg');

(async () => {
    const client = new Client(/* ... */);
    await client.connect(); // connect to database

    const browser = await puppeteer.launch({ headless: false });
    const [page] = await browser.pages();

    // call a handler when a mutation happens
    async function mutationListener(addedText) {
        console.log(`Added text: ${addedText}`);

        // insert data into database
        await client.query('INSERT INTO users(text) VALUES($1)', [addedText]);
    }
    page.exposeFunction('mutationListener', mutationListener);

    await page.goto('http://...');
    await page.waitForSelector('.msg-nickname');

    await page.evaluate(() => {
        // wait for any mutations inside a specific element (e.g. the chatbox)
        const observerTarget = document.querySelector('ELEMENT-TO-MONITOR');
        const mutationObserver = new MutationObserver((mutationsList) => {
            // handle change by checking which elements were added and which were deleted
            for (const mutation of mutationsList) {
                const { removedNodes, addedNodes } = mutation;
                // example: pass innerText of first added element to our mutationListener
                mutationListener(addedNodes[0].innerText);
            }
        });
        mutationObserver.observe( // start observer
            observerTarget,
            { childList: true }, // wait for new child nodes to be added/removed
        );
    });
})();


text:
Q: NO DUPLICATE (Group by) Field 1 loop with field 2 in horizontal line Assuming I have table called "dp"
Year      | Month     | Payment|  Payer_ID | Payment_Recipient |
2008/2009 | July      | 100000 |     1     |        John       |
2008/2009 | August    | 200000 |     1     |        Jane       |
2009/2010 | August    | 150000 |     1     |        Jane       |
2009/2010 | September | 175000 |     1     |        John       |

In mysql view :
Year      |  July  | August | September |
2008/2009 | 100000 | 200000 |    0      |
2009/2010 |    0   | 150000 |  175000   |

I need output like this in my php page :
    Year      |       July     |      August   |     September |
    2008/2009 | 100000 | John  | 200000 | Jane |    0   |   -  |
    2009/2010 |    0   |   -   | 150000 | Jane | 175000 | John |

I use some of this code :
    $query_Recordset1 = "SELECT
   year
 , SUM(IF(Month='July', Payment, 0)) As 'July'
 , SUM(IF(Month='August', Payment, 0)) As 'August'
 , SUM(IF(Month='September', Payment, 0)) As 'September'
FROM
 dp
WHERE
 Payer_ID = 1
GROUP BY
 Year";

    <?php do { ?>

          <?php echo $row_Recordset1['year']; ?>
          <?php
          $monthfilter=$row_Recordset1['month'];
          $valuefromfilter=$row_Recordset1['payment'];
          if ($monthfilter == 'July')
              {
              echo $valuefromfilter;
              }
              else
              {
              echo "";
              echo "0";
              echo "
";
              }
           ?>
          script for august
          script for september

        <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>

and it ended up like this :
    Year      |  July  | August | September |
    2008/2009 |    *   |   *    |    *      |
    2009/2010 |    *   |   *    |    *      |

*

*= Undefined Index ....

Any solution for output in php page ?

A: MySQL doens't support PIVOT so you need to use an workaround
Note you need to add an SUM rule for every month
SELECT
   Year
 , SUM(IF(Month='July', Payment, 0)) As 'July'
 , SUM(IF(Month='August', Payment, 0)) As 'August'
 , SUM(IF(Month='September', Payment, 0)) As 'September'
FROM
 dp
WHERE
 Payer_ID = 1
GROUP BY
 Year

see demo http://sqlfiddle.com/#!2/37cd5/11
Note for an large table you should use this index on (Payer_ID, Year) to remove the need for an temporary table and an sorting pass
Edit check the query below this will make the PHP client code very easy
SELECT
   'Year'
 , 'July'
 , 'August'
 , 'September'
UNION ALL
SELECT
   Year
 , SUM(IF(Month='July', Payment, 0)) As 'July'
 , SUM(IF(Month='August', Payment, 0)) As 'August'
 , SUM(IF(Month='September', Payment, 0)) As 'September'
FROM
 dp
WHERE
 Payer_ID = 1
GROUP BY
 Year

see http://sqlfiddle.com/#!2/37cd5/13
Note for an large table you should use this index on (Payer_ID, Year) to remove the need for an temporary table and an sorting pass


text:
Q: Angular Universal meta tags not being seen by Facebook I'm trying to get the relevant meta tags to show on my article pages for Facebook sharing. I'm using Angular Universal and it's Server-side rendering. Google Indexing works, and the meta tags appear in the page source, so I know SSR is working, However, the Facebook Crawler for reason can't see them.
Solutions I've tried are using the Meta module from @angular/platform-browser
import { Meta } from '@angular/platform-browser';

this.meta.updateTag({ property: 'og:type', content: 'article' });
this.meta.updateTag({ property: 'og:site_name', content: 'AdriaOffer' });
this.meta.updateTag({ property: 'og:title', content: config.title });
this.meta.updateTag({ property: 'og:description', content: config.description });
this.meta.updateTag({ property: 'og:image', content: config.image });
this.meta.updateTag({ property: 'og:url', content: config.slug });

I also found ngx-meta - https://github.com/fulls1z3/ngx-meta/
Which worked if you added the meta data within the route, e.g (taken from their npm page)
...
import { MetaGuard } from '@ngx-meta/core';
...
export const routes: Routes = [
  {
    path: '',
    canActivateChild: [MetaGuard],
    children: [
      {
        path: 'home',
        component: HomeComponent,
        data: {
          meta: {
            title: 'Sweet home',
            description: 'Home, home sweet home... and what?'
          }
        }
      },
      {
        path: 'duck',
        component: DuckComponent,
        data: {
          meta: {
            title: 'Rubber duckie',
            description: 'Have you seen my rubber duckie?'
          }
        }
      },
      {
        path: 'toothpaste',
        component: ToothpasteComponent,
        data: {
          meta: {
            title: 'Toothpaste',
            override: true, // prevents appending/prepending the application name to the title attribute
            description: 'Eating toothpaste is considered to be too healthy!'
          }
        }
      }
    ]
  }
  ...
];

But this solution doesn't work for me, as I need the data to be added dynamically, which seems to be a known issue - https://github.com/fulls1z3/ngx-meta/issues/118, or at least someone else has reported the same problem.
I've spent far too long on this, and an interim hack solution would also be fine, thinking my server.ts (which was automatically generated) could be updated somehow?
server.ts file for reference
import 'zone.js/dist/zone-node';
    import 'reflect-metadata';
    import {enableProdMode} from '@angular/core';
    import {ngExpressEngine} from '@nguniversal/express-engine';
    import {provideModuleMap} from '@nguniversal/module-map-ngfactory-loader';

    import * as express from 'express';
    import * as bodyParser from 'body-parser';
    import * as cors from 'cors';
    import * as compression from 'compression';
    import {join} from 'path';

    enableProdMode();

    export const app = express();

    app.use(compression());
    app.use(cors());
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: true }));

    // const DIST_FOLDER = join(process.cwd(), 'dist');

    const {AppServerModuleNgFactory, LAZY_MODULE_MAP} = require('./dist/server/main');

    app.engine('html', ngExpressEngine({
      bootstrap: AppServerModuleNgFactory,
      providers: [
        provideModuleMap(LAZY_MODULE_MAP)
      ]
    }));

    app.set('view engine', 'html');
    app.set('views', './dist/browser');

    app.get('/redirect/**', (req, res) => {
      const location = req.url.substring(10);
      res.redirect(301, location);
    });

    app.route('/sitemap.xml')
    .get((req, res) => {
      const DIST_FOLDER = join(process.cwd(), 'dist');
      res.sendFile(join(DIST_FOLDER,'sitemap.xml'));
    });

    app.get('*.*', express.static('./dist/browser', {
      maxAge: '1y'
    }));

    app.get('/*', (req, res) => {
      res.render('index', {req, res}, (err, html) => {
        if (html) {
          res.send(html);
        } else {
          console.error(err);
          res.send(err);
        }
      });
    });

A: ngx-meta work only for root urls not for dynamics urls, like you isn't work for facebook linkedin, ... .
But Meta of @angular/platform-browser work better when inspecting my générated page i find my metas.


text:
Q: Unable to uninstall, modifiy or repair visual studio 2015 I didn't not install Visual Studio 2015 to the C: (it's my ssd drive and its pretty small).  I choose to install VS2015 to G: and G drive has died and most of the files do not exist, such as:
G:\Program Files (x86)\Microsoft Visual Studio 14.0*
I would like to reinstall, but at this point, when I run the uninstaller, I am unable to repair, modify or uninstall VS2015, it fails with error:
"Cannot continue because some of the required components failed."
I am unable to install VS again, because of the same errors.  I looked at a force uninstall, but the files do not exists to force the uninstall.
I really don't want to reinstall windows10.  Any other ideas?

A: In my scenario, I had just performed a user migration from one PC to an AWS instance and was not able to use VS 2015 Enterprise edition upon migration.  I attempted to run a repair from "programs and features", run setup.exe from the ISO mounted to a drive on windows and even tried to run it from a disk and I couldn't get anything to run.  What I had found was a reg key that led me to an idea of how to repair VS from an internal installer.  The reg key that I found was:
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall{4983E758-4064-3D74-BB77-75C3F86C34B3}
which provided me with an install source for the currently installed version of visual studio.  Within this registry key I found the "InstallSource" portion and followed it's location to other installers and uninstallers for Visual studio and other programs found at this location:
C:\ProgramData\Package Cache{14D1CABE-2B5A-3AED-B3A7-42315D062965}v14.0.23107\packages\enterprisecore
From here I went through each of the folders with a listing for v14.0...etc and was able to find the location for the vs_enterprisecore windows installer.  From here I right-clicked the installer and ran a repair(you can choose to install, uninstall, or repair).
vs_enterprisecore functions
This allowed me to repair visual studio and inevitably re-update my licensing information on visual studio.  Prior to doing this I was receiving a dialog to sign in and that my license was invalid no matter how many attempts I made at logging in with my enterprise issued MSDN account.  As you can see below my VS2015 is operational again with Enterprise 2015 setup and is able to check for an updated key once again!  This took alot of work, spent at least 8-12 hours working on this to avoid a complete re-image!  I hope this helps someone later on down the road!
Visual Studio (Repaired)

A: I ended up just reinstalling windows, bummer.

A: You may have to remove any trace of what is left of it yourself. Even though the files of the installation are gone, the registry entries will still be lingering. You could try CCleaner to clean the registry. Typically when there isn't anything left and you try to uninstall from 'Programs and Features', Windows will ask you if you want to remove it from that list.
You can also use Revo, it has a 30 day trial period. CCleaner used to be free and you can still get the free version or a trial I believe.
Edit:
There are also some free ones that attempt to scan for leftovers:
IoBit Uninstaller, also at: Portable Apps
GeekUninstaller - Portable
Wise Program Uninstaller and Wise Registery Cleaner, - Portable Versions: Downloads Page

A: I had met with the same problem, while I found the solution after 1 day of research.
If you are seeing the fatal error for Built Tools x86. that's where I stuck with.
First of all, remember your previous version of Visual Studio Installed in your PC. And search for online to download the build tools for the specific version of Visual Studio.
Secondly, install the same and try to uninstall VS2015 with force command in an Admin privileged Cmd prompt.
vs_enterprise.exe /uninstall /force
You could find the above file in my case 'vs_enterprise.exe' from the package cache under ProgramData/PackageCache and respective package version number which you need to explore online. If you couldn't find the above simply uninstall vs2015 from Program and features under Control Panel.


text:
Q: RegEx with capturing groups not working in Java I have strings that have a pattern like the following ones:

*

*PSHELF-2[PSHELF-MF-6RU]

*SHELF-5[SHELF-M6]

*SHELF-6[SHELF-M15]

*SHELF-6[SHELF-M15]

I'd like to get the info highlighted.
To do so I use the following regex:
(.*SHELF)-(.*)\[.*SHELF-(.*)\]

I tested it with regex101
If I try to implement the same login on Java
Pattern pattern = Pattern.compile("(.*SHELF)-(.*)\\[.*SHELF-(.*)\\]");
Matcher matcher = pattern.matcher(inputString);
String group1 = matcher.group(1);
String group2 = matcher.group(2);
String group3 = matcher.group(3);

I got the following error:
java.lang.IllegalStateException: No match found

Why is that?

A: This post answers your original question.

This expression creates capturing groups and returns your desired outputs in multiple forms:
(([A-Z]+)-([0-9]+))\[([A-Z]+)-([A-Z0-9-]+)(\])

which you can additionally simplify it, if you wish.

Java Test
import java.util.regex.Matcher;
import java.util.regex.Pattern;

final String regex = "(([A-Z]+)-([0-9]+))\\[([A-Z]+)-([A-Z0-9-]+)(\\])";
final String string = "PSHELF-2[PSHELF-MF-6RU]\n"
     + "SHELF-5[SHELF-M6]\n"
     + "SHELF-6[SHELF-M15]\n"
     + "SHELF-6[SHELF-M15]";
final String subst = "\\1 \\4";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println("Substitution result: " + result);

JavaScript Demo

const regex = /(([A-Z]+)-([0-9]+))\[([A-Z]+)-([A-Z0-9-]+)(\])/gm;
const str = `PSHELF-2[PSHELF-MF-6RU]
SHELF-5[SHELF-M6]
SHELF-6[SHELF-M15]
SHELF-6[SHELF-M15]`;
const subst = `\nGroup 1: $1\nGroup 2: $2\nGroup3: $3\nGroup 4: $4\nGroup 5: $5`;

// The substituted value will be contained in the result variable
const result = str.replace(regex, subst);

console.log('Substitution result: ', result);

RegEx Descriptive Graph
This graph shows how the expression would work and you can visualize other expressions in this link:

Basic Performance Test
This JavaScript snippet shows the expression performance using a simple 1-million times for loop.

const repeat = 1000000;
const start = Date.now();

for (var i = repeat; i >= 0; i--) {
 const string = 'PSHELF-2[PSHELF-MF-6RU]';
 const regex = /(([A-Z]+)-([0-9]+))\[([A-Z]+)-([A-Z0-9-]+)(\])/gm;
 var match = string.replace(regex, "\nGroup #1: $1\nGroup #2: $2 \nGroup #3: $3 \nGroup #4: $4\nGroup #5: $5\n");
}

const end = Date.now() - start;
console.log("YAAAY! \"" + match + "\" is a match  ");
console.log(end / 1000 + " is the runtime of " + repeat + " times benchmark test.  ");


text:
Q: How to return IList from my repository with ordered queries in LINQ/EF My repository layer has been working fine, exposing IList<T> for lists of things like GetAll() etc.  However, I tried to use OrderBy on one of my LINQ queries.  Then I ran into real big problems because the LINQ query cannot be converted to an IList.  It wants to return an IOrderedEnumerable.
This is a big problem because I want to keep my repo self contained and NOT expose IQueryable to my services.  Why should I change my repo architecture just because of an 'orderby'!
So, despite this I set about converting my repository layer to returning IEnumerable so that I can at least return sorted data.  I then ran into more problems because I then needed to convert my data classes to IEnumerable so I can map easily between my view model and data model classes.  (This is using AutoMapper).
Then I realised that code-first doesn't like IEnumerable and won't build relationships between tables if not defined using at least an IList (and am also told ICollection??).
So my question is what do I from here?  All I want to do is return data to the client (in this case the services), in an ordered fashion without changing return types all the way through my application.

A: This for instance works and it sorts and returns an IList<T>:
public class Customer
{
    public int CustomerId { get; set; }
    public string Name { get; set; }
    public string City { get; set; }
}

public IList<Customer> GetSortedListOfCustomersInCity(string city)
{
    return context.Customers
        .Where(c => c.City == city)
        .OrderBy(c => c.Name)
        .ToList();
}

(I think this is also what Reed Copsey in his answer meant.) I guess, your problem is of another kind, since it is too obvious that this example works. But I couldn't derive from your questions where exactly your issue is. A piece of your not working code is appreciated.

A:
So my question is what do I from here? All I want to do is return data to the client (in this case the services), in an ordered fashion without changing return types all the way through my application.

When you create your queries, you can always return results.ToList(), which will evaluate them and convert them into an IList<T> for you.
This is, in many cases, advantageous if your query is an IQueryable<T> internally in any case, as it will fully evaluate the query, and prevent issues that can arise if you close your internal data context, then try to enumerate your results.


text:
Q: style bootstrap multiselect to look like a normal select I am using bootstrap-multiselect to add dropdown multiselect functionaility to selects but I do not like the way it looks and can't seem to overide the style.
I would like it to look like a normal bootstrap form control but adding these classes does nothing.

Normal BS select

  <select class="form-control form-control-sm" id="select1">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
  </select>

Bootstrap multiselect

  <select class="form-control form-control-sm" id="select2" multiple="multiple">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
  </select>

I have created a JSfiddle to show the difference.
I have also tried to change the bootstrap-multiselect stylesheet but again nothing I change seems to work
EDIT:- It is the grey background and lack of border of the bootstrap-multiselect that I do not like

A: Bootstrap Multiselect is creating a button there which receives certain styles applied by classes like .multiselect. You can pretty easily override these in a way like the following:
button.multiselect {
  background-color: initial;
  border: 1px solid #ced4da;
}

Here, I'm resetting the background color of the button generated by Multiselect by going to its initial value, but you can set it to #ffffff; or something else. The border style is copied from the Bootstrap default for the .form-control class.
If you're not familiar with debugging with Devtools, you can start with Chrome's Devtools overview, or look specifically for tutorials on how to use the devtools or inspector for your browser of choice.
Here it is applied to your fiddle:
https://jsfiddle.net/qzdnkwos/36/
You can tweak as needed.


text:
Q: Increasing value for key which is existing in dictionary I'm trying to create concordance.
I have dictionary, where key -  is word and value - is frequency of this word
If word exist in dictionary  I need to increase value for this word.
I'm using ContainsKey to check if word exists, bot don't understand how to increase value
    string[] words = SplitWords(lines);

    foreach (var  word in words)
    {
            int i = 0;
            if (!concordanceDictionary.ContainsKey(word))
            {
                concordanceDictionary.Add(word, i);
            }
            else
            {

            }
            foreach (KeyValuePair<string, int> pair in concordanceDictionary)
            {
                Console.WriteLine("{0}:{1}",pair.Key, pair.Value);
           }
        }

A: You need to use the indexer property:
if (!concordanceDictionary.ContainsKey(word))
{
    concordanceDictionary.Add(word, 1);
}
else
{
    concordanceDictionary[word]++;
}

A: just do
else
{
    concordanceDictionary[word]++;
}

A: If the test for ContainsKeys fails and after adding the key, just increment the value.
There is no need of the else block
string[] words = SplitWords(lines);
foreach (var  word in words)
{
    if (!concordanceDictionary.ContainsKey(word))
       concordanceDictionary.Add(word, 0);
    concordanceDictionary[word]++;
}


text:
Q: Why am I not getting a warning by my compiler, although I've added these compiler options in tasks.json? I am using VSCode and have followed this tutorial: https://code.visualstudio.com/docs/cpp/config-mingw
In my tasks.json file, I have added the two command line arguments "-Wall" ,"-fsanitize=undefined" and -fsanitize=address.
The file looks like this now:
{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "shell",
            "label": "C/C++: g++.exe build active file",
            "command": "C:\\Program Files\\mingw-w64\\x86_64-8.1.0-posix-seh-rt_v6-rev0\\mingw64\\bin\\g++.exe",
            "args": [
                "-g",
                "-Wall",
                "-fsanitize=undefined",
                "-fsanitize=address",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${workspaceFolder}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            }
        }
    ]
}

If I run the simple piece of code below, I do not get any warning, although I'm trying to access the element at index 3 of a vector with size 1. What do I have to do in order to get a warning/error?
#include <iostream>
#include <vector>

int main()
{
    std::vector<int> a(1);
    std::cout << a[3];
}

A: There isn't a way to guarantee a warning or error for out of bounds access of a vector.
What you can do though is switch from using [] to using at like
int main()
{
    std::vector<int> a(1);
    std::cout << a.at(3);
}

which will generate an exception at run time and you can write code to handle that exception.


text:
Q: trouble with scope related variables Hello fellow programmers, I'm developing a simple interface application in Python that will enable easy and intuitive entry of inventory forms in an access database.
I currently have a function as follows:
def spawnerror(self, errormsg):
    self.running = False
    content = Button(text=errormsg)
    popup = Popup(title='ERROR!', content=content, auto_dismiss=False)
    content.bind(on_press=popup.dismiss)
    popup.open()

And I have appropriate error handling done, and the application uses this function as intended. For example, if someone doesn't enter in a required field, it calls this function and spawns an error page with an error and informs the user.
My issue that I run into is that, it needs to set the class variable running to False, because at the end of the main function "submit" it checks for that and if self.running == False, then it needs to skip the execution of data entry in the access database.
Why is this function not setting the class variable of running to false?

A: Solution - using App.get_running_app()
In the example, a class attribute, running is defined as BooleanProperty. In the spawnerror() function, it uses App.get_running_app() function to get an instance of App class and then access variable, running.
Note
If running, spawnerror() function and submit() function are in different classes then work out the relation of the classes and pass a direct reference between them.
Example
main.py
from kivy.app import App
from kivy.uix.popup import Popup
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ObjectProperty

class RootWidget(BoxLayout):
    instance = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        self.instance = App.get_running_app()
        self.spawnerror('Testing')

    def spawnerror(self, errormsg):
        self.instance.running = False
        content = Button(text=errormsg)
        popup = Popup(title='ERROR!', content=content, auto_dismiss=False)
        content.bind(on_press=popup.dismiss)
        popup.open()

class TestApp(App):
    running = BooleanProperty(True)

    def build(self):
        print("\nbuild:")
        self.display_attributes()
        return RootWidget()

    def on_stop(self):
        print("\non_stop:")
        self.display_attributes()

    def display_attributes(self):
        print("\tApp.running =", self.running)

if __name__ == "__main__":
    TestApp().run()

Output


text:
Q: Google scripts only run manually, but not automatically I found similar questions, but none that answer my question that I can tell. I have 5 triggers on a google sheet. Four are copy functions, the other is a mail function. The mail function works fine, but none of the copy functions work unless you force them to run manually. I'm sure it's a code problem, but not sure what. Any help would be appreciated. Here is a copy of my code.
function Copy3()   {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ss = sss.getSheetByName('Consolidation Client Names 6'); //replace with
source Sheet tab name
var range = ss.getRange('A1:K1000'); //assign the range you want to copy
var data = range.getValues();

var ss = SpreadsheetApp.getActiveSpreadsheet();
var ts = tss.getSheetByName('Copied as Values 7'); //replace with
destination Sheet tab name
ts.getRange(1, 1, data.length, data[0].length).setValues(data);
}

A: Both times when you try to fetch the sheet by the name, you do it with a reference to a variable that was never created/initiated.
var ss = sss.getSheetByName('Consolidation Client Names 6');
var ts = tss.getSheetByName('Copied as Values 7');

Neither sss nor tss have been declared.
Furthermore, you try to declare the ss variable three times (two times to save the Active Spreadsheet, and once to save the sheet that you're fetching). I would advise you to give all of them different names (I suppose you wanted to call them sss and tss).


text:
Q: Spring - Logback catch logging events I am new to Spring and logging.
My aim is it to create a custom repository containing the data of the Logback loggers e.g logger.name / logger.level / logger.message
which will then be mapped to a MySQL DB.
The problem is I dont know how to catch the logging events.
I tried to instantiate LoggingEvent (ILoggingEvent). But this returns me always "null".
I dont want to use the typical "Spring-logback-way" because I am creating a custom MySQL-DB with Custom named tables / attributes.
Which Interface/Class i have to use to catch the actual loggingEvent?

A: step 1: First you to have to include log4j.jar in your project.
step 2.Configure JDBCAppender in log4j.properties file as bellow to store
       logging in database.

log4j.properties:

    # Define the root logger with file appender
    log4j.rootLogger = DEBUG, sql

    # Define the file appender
    log4j.appender.sql=org.apache.log4j.jdbc.JDBCAppender
    log4j.appender.sql.URL=jdbc:mysql://localhost/test
    # Set Database Driver
    log4j.appender.sql.driver=com.mysql.jdbc.Driver
    # Set database user name and password
    log4j.appender.sql.user=root
    log4j.appender.sql.password=password
    # Set the SQL statement to be executed.
    log4j.appender.sql.sql=INSERT INTO LOGS VALUES ('%x', now()
        ,'%C','%p','%m')
    # Define the xml layout for file appender
    log4j.appender.sql.layout=org.apache.log4j.PatternLayout

Step 3: Log4jJDBCExample to configure log4j and ites priority level message

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;

public class Log4jJDBCExample
{
    static Logger log = Logger.getLogger(Log4jJDBCExample.class);

    public static void main(String[] args)
    {
        PropertyConfigurator.configure("log4j.properties");

        log.debug("Sample debug message");
        log.info("Sample info message");
        log.error("Sample error message");
        log.fatal("Sample fatal message");
    }
}

Step 4: Create the table in database and test the application

    Create the database table LOGS, in schema test.

    CREATE TABLE LOGS
    (
        USER_ID VARCHAR(20) NOT NULL,
        DATED   DATETIME NOT NULL,
        LOGGER  VARCHAR(50) NOT NULL,
        LEVEL   VARCHAR(10) NOT NULL,
        MESSAGE VARCHAR(1000) NOT NULL
    );

Explination:

  log4j.appender.sql.sql=INSERT INTO LOGS VALUES ('%x', now() ,'%C','%p','%m')

  Here now()--> inserts currentdate
          %c--> Class Name
          %p--> Priority (level)
          %m--> Message

Result like bellow:


text:
Q: Sets and Sequences My question is basically: true or false? I'm told this is false, but don't understand why.

*

*Set: A set is an unordered group of related elements which are
distinct.

*Sequence: A sequence is a list of related elements which
occur in a particular order.

A: A set doesn't have a specified order.  The two element set $\{1,2\}$ is the same as $\{2,1\}$.
A sequence is a list of values. You can think of a finite sequence of length $n$ as a function on the set $\{1,2,\ldots,n\}$.  An infinite sequence is a function on the set of natural numbers $\mathbb{N}$.

A: The definition of a set is a somewhat complicated discussion as evident by Russel's paradox.The definition by Cantor (as taken from wikipedia) is "A set is a gathering together into a whole of definite, distinct objects of our perception or of our thought—which are called elements of the set." .The formality about what is a set can be explored through the axioms proposed by Ernst Zermelo and Abraham Fraenkel.
A sequence can be defined to be a function $f:\mathbb{N}\rightarrow A$ where $A$ is a set.


text:
Q: Convert word doc text to HTML div through contenteditable DIV I am trying to convert the word doc text to HTML like below

*

*Making a DIV with contenteditable = true

*Pasting the word text to the editable DIV, as it allows pasting formatting also.

*Next I am getting the innerHTML of DIV

But with this approach I am not getting the proper HTML. Apart from hell lot of dirty MS Word formatting, sometimes it is replacing space value of text with new line.
Is there any better way to do the above thing and why it is replacing it with new line.

A: I use TinyMCE for this. They have a "paste from Word" option that allows you to strip out all of the MS stuff. The same option exists in CKEditor, which some of the sites I work on use  it or fck (old version).


text:
Q: Oxyplot distance between ticks How to decrease distance between ticks? I want to place candles more closely.
And i cannot find any property in LinearAxis XAxis that respond for distance.

Code:
namespace WpfApplication20
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
///
public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
        DataContext = new PlotClass();
    }

}
public class PlotClass
{
    public PlotModel PlotModel { get; set; }
    public PlotClass()
    {
        Random rnd = new Random();
        PlotModel = new PlotModel();
        LineSeries LS = new LineSeries();
        LinearAxis XAxis = new LinearAxis
        {
            Position = AxisPosition.Bottom,
            MinorStep=1,
            MajorStep=1

        };
        LinearAxis YAxis = new LinearAxis()
        {
            Position = AxisPosition.Left
        };
        for (int i=0;i<10;i++)
        {
            LS.Points.Add(new DataPoint(i,rnd.Next(1,10)));
        }
        PlotModel.Axes.Add(YAxis);
        PlotModel.Axes.Add(XAxis);
        PlotModel.Series.Add(LS);
        ChangeToCandles();
        WhatTypeOfSeries();
    }
    public void ChangeToCandles()
    {
        Random rnd = new Random();
        PlotModel.Series.Clear();
        CandleStickSeries CSS = new CandleStickSeries();
        for (int i = 0; i < 10;i++ )
        {
            CSS.Items.Add(new HighLowItem { X = i, Close = rnd.NextDouble(), High = rnd.NextDouble(), Low = rnd.NextDouble(), Open = rnd.NextDouble() });
        }
        PlotModel.Series.Add(CSS);
    }
    public void WhatTypeOfSeries()
    {
        var temp = PlotModel.Series[0].GetType();
        Console.WriteLine(temp);
    }
}
}

xaml:
 <Grid>
    <oxy:Plot Model="{Binding PlotModel}"/>
</Grid>

A: Try zooming:
XAxis.Zoom(-5, 15);

EDIT>>>>
You have a for loop from 0 to 10, you just have to add some adjust values. For that limits for being more generic:
int lowerIndex = 0;
int upperIndex = 10;
int zoomValue = 5;

for (int i=lowerIndex;i<upperIndex;i++)
{
    LS.Points.Add(new DataPoint(i,rnd.Next(1,10)));
}

XAxis.Zoom(lowerIndex-zoomValue, upperIndex+zoomValue);

A: Try to play with CandleStickSeries.CandleWidth property:

*

*If it is set to 1, then there will be no space between candles.

*If it is set to value > 1, then candles will overlap.

*If it is set to value < 1, then there will be a gap between candles. The smaller value, the bigger gap.


text:
Q: How do I call in a method in a Form when a property of a class referenced in that form changes? I have a form and i created a new class for it.but i cant call Invalidate() inside the class
My Code -
  public partial class CustomForm : Form
  {
      private bool showBorderLine;
      private Color borderLineColor;
      private int borderLineWidth;

    public CustomForm()
    {
        InitializeComponent();

        this.DoubleBuffered = true;
        this.ResizeRedraw = true;
        this.SetStyle(ControlStyles.ResizeRedraw, true);
        this.FormBorderStyle = FormBorderStyle.None;

        borderLineColor = Color.DodgerBlue;
        borderLineWidth = 1;
        showBorderLine = true;
    }

    [Category("Form Editor")]
    public bool ShowBorderLine
    {
        get { return showBorderLine; }
        set
        {
            showBorderLine = value; // Here I can able to call invalidate
                                    // and it works perfectly
            this.Invalidate(true);
        }
    }

    private ResizeOptions resizeOptions = new ResizeOptions();

    [Category("Form Editor")]
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
    public ResizeOptions ResizeOptions
    {
        get { return resizeOptions; }
        set
        {
            resizeOptions = value;
            this.Invalidate(true); // when I call invalidate here.it won't working. I hope I need to invalidate it in the Resize option Class for work perfectly
        }
    }
}

[TypeConverter(typeof(ExpandableObjectConverter))]
public class ResizeOptions // Inside this class i cant able to use invalidate method
{
    private bool resizeTop;
    private bool resizeBottom;
    // more fields

    public ResizeOptions()
    {
        resizeTop = true;
        resizeBottom = true;
        // more fields initialized
    }

    [Category("Form Editor")]
    public bool ResizeTop
    {
        get { return resizeTop; }
        set { resizeTop = value; } // I want to call invalidate method here
    }

    [Category("Form Editor")]
    public bool ResizeBottom
    {
        get { return resizeBottom; }
        set { resizeBottom = value; } // I want to call invalidate method here
    }

    // more of the same
}

You can see the invalidate method is possible inside the Form Class but i cant able to use it in ResizeOptions Class
i call invalidate method for get design time support for properties.
if you want i can provide the full code
please help me.

A: ResizeOptions is just a class that contains values. Even though you're using it in connection with a Form, it has no "awareness" that it is used within a form, and it shouldn't. It shouldn't need to know that when its values change, there is a form somewhere that should have its Invalidate() method called.
What's more, how can we even be sure there is a form to invalidate? We could do this:
var resizeOptions = new ResizeOptions();

Now there is no form at all. If we could somehow call Invalidate() from within this class, would would it invalidate?
What it can do is, when its values are changed, raise an event that says, "Hello, my values have changed!" and then other components, such as the form, can decide what they should do with that information.
To accomplish that you can create a delegate:
public delegate void ResizeOptionsChangedEventHandler(ResizeOptions sender);

Add an event in ResizeOptions:
public event ResizeOptionsChangedEventHandler ResizeOptionsChanged;

Raise it when you need to:
public bool ResizeTop
{
    get { return resizeTop; }
    set
    {
        resizeTop = value;
        ResizeOptionsChanged?.Invoke(this);
    }
}

Now ResizeOptions has done its part by letting anyone who cares know that it has changed. What, if anything, another class does with that information is up to that other class.
Now, in your form, you can subscribe to the event in the constructor:
public CustomForm()
{
    // other constructor stuff
    resizeOptions.ResizeOptionsChanged += ResizeOptions_ResizeOptionsChanged;
}

and in the property:
public ResizeOptions ResizeOptions
{
    get { return resizeOptions; }
    set
    {
        if (resizeOptions != null)
            resizeOptions.ResizeOptionsChanged -= ResizeOptions_ResizeOptionsChanged;
        resizeOptions = value;
        resizeOptions.ResizeOptionsChanged += ResizeOptions_ResizeOptionsChanged;
        this.Invalidate(true);
    }
}

using this event handler:
private void ResizeOptions_ResizeOptionsChanged(ResizeOptions sender)
{
    Invalidate(true);
}


text:
Q: applescript 'Can't make current application into type string' I am creating my first simple apple script.
Basically to start a shell script which will start running a program.
So I placed the shell script into the Resources/Scripts and am now trying to run this apple script:
do shell script (path to resource) & "Scripts/startWindows7.sh"

However this results into this error:
"Can't make current application into type string." number -1700 from current application to string

I also tried to run this apple script:
do shell script (path to resource "Scripts/startWindows7.sh")

But this will result into an other error:
Can't make alias into type string." number -1700 from alias Contents:Resources:Scripts:startWindows7.sh" to string

So there must be a better way to do this,
however I can't find the right solution on Google, nor can I find the right solution here.

A: You can use POSIX path of (path to me) to get the path to the application:
do shell script POSIX path of (path to me) & "Contents/Resources/script.sh"

The script has to be executable and include an interpreter line:
echo $'#!/bin/bash\nsay a'>Desktop/Untitled.app/Contents/Resources/script.sh
chmod +x Desktop/Untitled.app/Contents/Resources/script.sh


text:
Q: определить количество рейсов в каждым водителем город SQL Необходимо записать запрос SQL подсчитать, в какие города осуществлял доставки каждый водитель и сколько доставок он совершил в каждый город. Отсортировать результаты для каждого водителя в порядке убывания количества рейсов в город.
пробовал так
SELECT Driver.driver_id
       Shipment.City_ID, City.City_name
       (SELECT COUNT(*) FROM Shipment
WHERE Shipment.city_id = Driver.driver_id) AS DriverOrdrers
       FROM Driver,Shipment, City
       WHERE DriverOrdrers > 1
       ORDER BY DriverOrdrers DESC


text:
Q: Нормали в Блендер 2.83 Скачала Блендер 2.83. Стала его изучать. И оказалось, что нормали вытянуты в одну сторону. Это происходит даже если создаешь новый файл. Пробовала все, чтобы их вывернуть на место. Что делать?

A: В стандартном интерфейсе Blender можно отображать три типа нормалей: нормали к вершинам, нормали к вершинам на грань и нормали к граням. Обычно розовым цветом отображаются нормали к вершинам на грань, но на представленной картинке это не соответствует, поскольку нормали выходят не из вершин. Поэтому по представленной картинке сложно судить о причинах происходящего, нужен файл с этим кубом.
Традиционно большинство проблем с нормалями в штатном режиме решается через пересчет нормалей.


text:
Q: Switch to alternate ViewController programmatically on iOS I am reasonably new to IOS below is a screenshot of my app structure -

There are various tableViewcontroller / uiviewcontrollers which connect to a tab bar controller - all pretty standard I guess.
The colourful shot is the homepage - I would like users to be able to click on one of the 4 tabs and navigate to one of the other pages - though i'm struggling on how to to this programatically.
I have attached all the buttons as ib-actions and have given all the screesn storyboard id's.
The following is my code so far -
- (IBAction)btnCult:(id)sender {

    UIViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"culture"];

    [self presentViewController:vc animated:YES completion:nil];
}

This does nothing - where am I going wrong?

A: Try add this it IBAction:
[self.tabBarController setSelectedIndex:0];

It should takes you to first tab, by changing index you change the tabs(views)


text:
Q: Magento 2 : How to access a custom attribute value of a simple product In Magento 2, I would like to access the value of custom attribute name material associated simple product from a configurable product.
At the moment, I am unable to get attribute value. For some reason it returns false but I can get other attribute values such a sku, price etc
Here is what I have tried to do so far:
../vendor/magento/module-catalog/view/frontend/templates/product/view/options.phtml

Then I have added this to get the simple products from the configurable products:
<?php $_product = $block->getProduct() ?>
<?php $_simpleProducts = $_product->getTypeInstance()->getUsedProducts($_product); ?>
<?php $attributeValues = explode(',', $_product->getResource()->getAttribute('material')->getFrontend()->getValue($_product)); ?>
<?php foreach ($_simpleProducts as $key => $simpleProduct): ?>
    <?php foreach ($attributeValues as $attributeValue): ?>
        <?php if ($attributeValue == $simpleProduct->getAttributeText('material')): ?>
            <?php echo $attributeValue ?>
        <?php endif; ?>
    <?php endforeach; ?>
<?php endforeach; ?>

I would like to do is set the material attribute for the configurable product then loop through the simple products to see if they have the same material but I can't get the value for material from the simple products.
Any ideas?
I can access it from the parent/configurable but when I try to get the value from the simple products it returns false

A: you need to make your attribute visible.
For that you need to go to the Storefront Properties tab of your attribute, then change the Visible on Catalog Pages on Storefront to Yes.
Depending on your configuration you might need to reindex.
For information this allows magento to optimize the pages, if it had to load all attributes for all pages where a product is displayed it would be to slow.

A: You are having this problem because when the product was loaded the code made it more efficient by only partially loading the data. This is much quicker when flat catalog is switched off since in that case each attribute is in a different table. I solve this problem by reloading the object.
First inject \Magento\Catalog\Model\ProductRepository $productRepository, into your block.
Then do this to reload the product, hopefully with all the attributes. It certainly has more attributes.
$product = $this->_productRepository->get($partialProduct->getSku());

I'll add the caveat that I'm not particularly enamoured with this method. I can't help but feel it would be more satisfactory to just populate the existing product.


text:
Q: Why do I need a wrapper function to recursively call with setTimeout Currently testing out some stuff with moving an element x amount of pixels in a looped call. I've created a recursive function, and added some delay to avoid the callback from overflowing. I've used setTimeout to create this delay. I'm wondering why I need to wrap my recursive function inside another function when using setTimeout. If I don't, the delay is not added and the browser does the callback has exceeded error in my console. Below is the code that I'm using. It's intended to make "the thing (a ball)" move across the div/box/screen from left to right, over and over.
(I understand requestAnimationFrame is typically used for this sort of thing, but I'm attempting to familiarize myself with javascript through different approaches).
function moveThing(pos){
    var currentPos = pos;

    currentPos += 5;

    theThing.style.left = currentPos + "px";

    if( Math.abs(currentPos) >= 900) {
        currentPos = -500;
    }

    console.log(currentPos);
    setTimeout(function(){moveThing(currentPos)}, 100);

}

moveThing(0);

Also, if I'm not using correct terminology, feel free to correct. Thanks in advance for your help!

A: Fundamentally, the answer is: Because you need to pass a function to setTimeout. setTimeout(moveThing(currentPos), 100) would call moveThing and pass its return value (which isn't a function) to setTimeout.
But note that on any vaguely-modern browser, you can pass moveThing itself, you don't need a wrapper. You can replacing your current setTimeout call with this:
setTimeout(moveThing, 100, currentPos);

...which tells setTimeout to call moveThing in 100ms (or so) passing currentPos as its first parameter.

A: If you did this:
setTimeout(moveThing(currentPos), 100);

You'd be invoking it immediately it would be effectively the same as this:
var x = moveThing(currentPos);
setTimeout(x, 100);

So the function is never delayed, and can never exit, and the call stack limit is eventually reached.

If you did this:
setTimeout(moveThing, 100);

Then it would be delayed, but since the currentPos variable is local to the function, it wouldn't get passed along, so it wouldn't work.

One option that doesn't involve passing a wrapper function every time would be to make moveThing close over the currentPos variable. Then the function can be passed directly, and it will always access that same var.

function makeMover(pos, theThing) {
  return function moveThing() {
    pos += 5;

    theThing.style.left = pos + "px";

    if (Math.abs(pos) >= 900) {
      pos = -500;
    }

    console.log(theThing.id, pos);
    setTimeout(moveThing, 100);
  }
}

var mover = makeMover(0, document.querySelector("#theThing"));
mover();

var mover2 = makeMover(0, document.querySelector("#theThing2"));
setTimeout(mover2, 1000);
.thing {
  position: relative;
  width: 30px;
  height: 30px;
  background-color: orange;
}
#theThing2 {
  background-color: blue;
}


text:
Q: How can I run a batch-file under windows git-bash console? How can I run a batch-file uder windows git-bash console.
When I run it I get:
user@DESKTOP-DF012sh MINGW64 /c/project-folder
$ util.bat
bash: util.bat: command not found

A: It should work if you mention where the bat is.
./util.bat

By default, a $PATH does not include the current folder.
I just tested executing a .bat script that way, and it worked just fine.


text:
Q: Permeability: is webers per ampere-turn meter (Wb / At.m) equivalent to henrys per meter (H / m)? Is webers per ampere-turn meter equal to henries per meter?
I.e. is \$\frac{Wb}{At.m}\$ equal to \$\frac{H}{m}\$?
-and if so, is there an easy way to picture the equivalence?

A: The definition of inductance per turn is total flux per amp of current: -
$$L = \dfrac{\Phi}{I}$$
Dividing both sides by length, d gives equivalence for a one turn winding: -
$$\dfrac{L}{d} = \dfrac{\Phi}{I\cdot d}$$


text:
Q: Show power series is solution to differential equation I am currently studying for my analysis 2 course, and I've run into a couple of questions from old exams regarding power series as solutions for differential equations which I have a trouble completing.
We have a specific power series i.e.
$$f(x)=\sum_{n=0}^{\infty} \frac{1}{(2n+1)!}x^{4n+3}$$
And we have to show this solves the differential equation,
$$x^2y''-3xy'+(3-4x^4)y=0$$
I have done some work to the left hand site, and gotten it to
$$\frac{-2x^{11}}{3}-7x^7+3x^3+\sum_{n=2}^{\infty}((\frac{16n^2+8n-4x^4}{(2n+1)!})x^{4n+3})$$
However I dont know how to continue from here in showing that the equation is equal to $0$. Of course we have the trivial solution for $x=0$, however how would I proceed for $x\neq0$?

A: I will get you started. The goal is to get an expression
$$
x^2y''-3xy'+(3-4x^2)y=\sum_{n=0}^\infty a_n x^n
$$
where $a_n$ is a function of $n$ alone. You sort of got that in your last equation, but you have $x^4$ in your expression for the coefficient of $x^{4n+3}$. If all goes well, you should have $a_n=0$ for all $n$. It helps to work piece by piece:
\begin{align}
x^2y''
&=\sum_n \frac{(4n+3)(4n+2)}{(2n+1)!} x^{4n+3}
\\
-3xy' &=-3\sum_n \frac{(4n+3)}{(2n+1)!} x^{4n+3}
\\
(3-4x^4)y
&=3\sum_n\frac1{(2n+1)!}x^{4n+3}-4\sum_{n=0}^\infty\frac1{(2n+1)!} x^{4n+7} \\
&=3\sum_n\frac1{(2n+1)!}x^{4n+3}-4\sum_{n=1}^\infty\frac1{(2n-1)!} x^{\color{blue}{4n+3}}
\end{align}
Notice how I re-indexed the last series so that everything was a coefficient times $x^{4n+3}$. This lets you combine everything together, except for the $n=0$ of the first three series, which will have to be pulled out and dealt with separately. The result is
\begin{align}
&x^2y''-3xy'+(3-4x^2)y=\\
&\big(\frac{3\cdot 2}{1!}-3\cdot \frac{3}{1!}+3\frac{1}{1!}\big)x^{4\cdot 0+3}+
\\&\sum_{n=1}^\infty \underbrace{\Big(\frac{(4n+3)(4n+2)}{(2n+1)!}-3\cdot \frac{(4n+3)}{(2n+1)!}+3\cdot \frac1{(2n+1)!}-4\frac1{(2n-1)!}\Big)}_{a_n}x^{4n+3}
\end{align}
Now you have a big complicated expression for $a_n$ you need to show is zero.

A: If$$f(x)=\sum_{n=0}^\infty\frac1{(2n+1)!}x^{4n+3},$$then$$f'(x)=\sum_{n=0}^\infty\frac{4n+3}{(2n+1)!}x^{4n+2}\quad\text{and}\quad f''(x)=\sum_{n=0}^\infty\frac{(4n+3)(4n+2)}{(2n+1)!}x^{4n+1}.$$It follows that$$x^2f''(x)=\sum_{n=0}^\infty\frac{(4n+3)(4n+2)}{(2n+1)!}x^{4n+3}\quad\text{and}\quad-3xf'(x)=\sum_{n=0}^\infty\frac{-12n-9}{(2n+1)!}x^{4n+3}.$$Therefore,$$x^2f''(x)-3xf'(x)=\sum_{n=0}^\infty\frac{16n^2+8n-3}{(2n+1)!}x^{4n+3}.\tag1$$On the other hand,$$3f(x)=\sum_{n=0}^\infty\frac3{(2n+1)!}x^{4n+3}$$and\begin{align}-4x^4f(x)&=-\sum_{n=0}^\infty\frac4{(2n+1)!}x^{4n+7}\\&=-\sum_{n=1}^\infty\frac4{(2n-1)!}x^{4n+3}.\end{align}So,\begin{align}(3-4x^2)f(x)&=3x^3+\sum_{n=1}^\infty\left(\frac3{(2n+1)!}-\frac4{(2n-1)!}\right)x^{4n+3}\\&=3x^3+\sum_{n=1}^\infty\frac{-16n^2-8n+3}{(2n+1)!}x^{4n+3}.\end{align}Since the RHS of $(1)$ is $-3x^3$ when $n=0$, we're done.


text:
Q: Is it possible to use VSCode to create a Webbased IDE I know about other such projects e.g. Theia which are based on Monaco editor similar to VSCode as well. However, does MSFT provide a way to use VSCode itself while developing a web based IDE?

A: This is also an example of something similar
https://github.com/cdr/code-server


text:
Q: Run separate processes in parallel - Python I use the python 'multiprocessing' module to run single processes on multiple cores but I want to run a couple of independent processes in parallel.
For example, Process-one parses large files, Process-two find patterns in different files and process three does some calculation; can all these three different processed that have different sets of arguments be run in parallel?
def Process1(largefile):
    Parse large file
    runtime 2hrs
    return parsed_file

def Process2(bigfile)
    Find pattern in big file
    runtime 2.5 hrs
    return pattern

def Process3(integer)
    Do astronomical calculation
    Run time 2.25 hrs
    return calculation_results

def FinalProcess(parsed,pattern,calc_results):
    Do analysis
    Runtime 10 min
    return final_results

def main():
parsed = Process1(largefile)
pattern = Process2(bigfile)
calc_res = Process3(integer)
Final = FinalProcess(parsed,pattern,calc_res)

if __name__ == __main__:
    main()
    sys.exit()

In the above pseudo-code Process1, Process2 and Process3 are single-core processes i.e they can't be run on multiple processors. These processes are run sequentially and take 2+2.5+2.25hrs = 6.75 hrs. Is it possible to run these three processes in parallel? So that they run at the same time on different processors/cores and when most time taking (Process2) finishes than we move to Final Process.

A: From 16.6.1.5. Using a pool of workers:
from multiprocessing import Pool

def f(x):
    return x*x

if __name__ == '__main__':
    pool = Pool(processes=4)              # start 4 worker processes
    result = pool.apply_async(f, [10])    # evaluate "f(10)" asynchronously
    print result.get(timeout=1)           # prints "100" unless your computer is *very* slow
    print pool.map(f, range(10))          # prints "[0, 1, 4,..., 81]"

You can, therefore, apply_async against a pool and get your results after everything is ready.
from multiprocessing import Pool

# all your methods declarations above go here
# (...)

def main():
    pool = Pool(processes=3)
    parsed = pool.apply_async(Process1, [largefile])
    pattern = pool.apply_async(Process2, [bigfile])
    calc_res = pool.apply_async(Process3, [integer])

    pool.close()
    pool.join()

    final = FinalProcess(parsed.get(), pattern.get(), calc_res.get())

# your __main__ handler goes here
# (...)


text:
Q: Android AppWidgetManager method updateAppWidget fails to set intents, load data. And it happens randomly My widget is comprised of 2 buttons and a listview displaying data. Most times, when the widget provider's onUpdate method is called, everything loads normally and everyone is happy.
However I've noticed sometimes after the update method is called, the widget just completely fails to load its data. The listview is empty, and all of the buttons are non-responsive. It's as if I initialized the layout into the widget, but none of the pending intents nor the adapter for list were set.
I logged everything and found that this isn't the case. The pending intents ARE created, as is the list adapter, every time, including the random time when it fails. For a long time I thought it had to do with how the list data is populated into the adapter, but seeing it work every single time, coupled with the fact that the button intents don't work as well leads me to believe the method updateAppWidget(ComponentName, RemoteViews) is what is failing. However, there are no error stacks to help me confirm this.
Here is the code which runs in a separate service called by the AppWidgetProvider's onUpdate method:
@SuppressWarnings("deprecation")
private void updateWidget(int[] ids) {

    AppWidgetManager widgetManager = AppWidgetManager.getInstance(this);
    int[] widgetIds = widgetManager.getAppWidgetIds(new ComponentName(this, WidgetReceiver.class));

    for (int currentWidgetId : widgetIds) {

        RemoteViews widget = new RemoteViews(this.getPackageName(), R.layout.widget_layout);

        Intent intent = new Intent(this, WidgetService.class);
        intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, currentWidgetId);
        intent.putExtra("random", randomNumber);
        randomNumber++;
        intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));

        widget.setRemoteAdapter(currentWidgetId, android.R.id.list, intent);

        Intent clickIntent = new Intent(this, DetailsActivity.class);
        PendingIntent pending = PendingIntent.getActivity(this, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        widget.setPendingIntentTemplate(android.R.id.list, pending);

        Intent settingsIntent = new Intent(this, WidgetSettingsActivity.class);
        settingsIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        settingsIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        PendingIntent settingsPending = PendingIntent.getActivity(this, 0, settingsIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        widget.setOnClickPendingIntent(R.id.widget_settings, settingsPending);

        Intent mainIntent = new Intent(this, MainActivity.class);
        PendingIntent mainPending = PendingIntent.getActivity(this, 0, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        widget.setOnClickPendingIntent(R.id.widget_logo, mainPending);

        ComponentName widgetCompName = new ComponentName(this, WidgetReceiver.class);
        widgetManager.updateAppWidget(widgetCompName, widget);
    }
}

What is most frustrating about this bug is that I can't reliably recreate it. Sometimes I get (un)lucky and it shows it ugly head, other times (the majority of the time) it works perfectly.
Another thing that I thought was interesting is that I've seen the same exact problem in Facebook's widget. Due to NDA I can't show a screen of my app when it fails, but I can show a screen of Facebook's identical problem:

When Facebook's widget looks like this, it has the exact same issues as mine. No data loaded, all buttons are unresponsive.
For both Facebook and my widget, a subsequent update interval will usually make the problem go away.
As much as I appreciate that I'm not the only one who is running into this, I still don't want to release until I fix this. Has anyone here run into this, and better yet found a solution, or even a cause of the problem? Thanks for helping.
EDIT: Something interesting. I ran an experiment where I set the update interval to a full day rather than every 30 minutes. My hypothesis was that maybe the update method wasn't the cause, it was something else which was causing the widget to become blank and unresponsive.
Sure enough, after about 2 hours, I checked my phone and the widget was dead, despite no update method being called. This would lead me to believe that something else is causing this problem, NOT widgetManager.updateAppWidget(widgetCompName, widget); like I previously thought.
I know that a configuration change can cause the widget to be rebuilt, and thus it is possible that it can fail. However, I already use the Service class's onConfigurationChanged method to reload the widget if necessary. Is there another case like configuration change which can cause the widget to destroy and recreate itself?

A: After a lot of blood, sweat, and tears I found the solution. I am going to hold off on confirming this answer for a few days to make sure that the error doesn't pop back up, but after a lot of observation I think it is resolved.
So I was right in my edited comments in the original question. It wasn't the update method of the AppWidgetManager that caused the problem, but rather some other Android process which caused the app widget to recreate itself. Unfortunately I couldn't isolate that trigger, but I did find a solution.
In my RemoteViewsFactory class (basically the wrapper which is used to load the data set), I had a block of code that looked like this:
RemoteViews views = new RemoteViews(mContext.getPackageName(), R.layout.widget_layout);
if(mItems.size() == 0)
    views.setViewVisibility(R.id.widget_empty, View.VISIBLE);
else
    views.setViewVisibility(R.id.widget_empty, View.GONE);

AppWidgetManager manager = AppWidgetManager.getInstance(mContext);
ComponentName widgetCompName = new ComponentName(mContext, WidgetReceiver.class);
manager.updateAppWidget(widgetCompName, views);

Basically, if the list was empty, I showed a Loading message that took up the entire area where the listview is located. If the list wasn't empty, I'd just hide that message.
So this is what was happening: When the factory was destroyed (presumably for memory purposes) the widget itself was not. So all of the code which sets the intents for the data and stuff was not run. However, the factory was recreated, which ran that block of code which updated the app widget with the new remote views object. This remote views object didn't do any of the methods that you see in my onUpdate() method I originally posted, so all of its features didn't work.
Moral of the story: DON'T use updateAppWidget in your RemoteViewsFactory class! Now it may work if you run all the necessary lines, but I can't confirm that.


text:
Q: Web App for Containers displayed only default page when deployed using docker image I created Container registry and then push the docker image of my web app to that registry. Created container instance and it is working fine.
Now i have to deploy this image to the Web App. There are two option which i found.
First i can choose 'Deploy to web app' option directly where docker image is stored.
Second i can create 'Web App for container' resource using the same docker image.
a.) When i tried first option : After deployed successfully when i run the web app it displayed default page. When i connected to the ftp to check the files in wwwroot folder. Only 'hostingstart.html' file is present.
b.) When i tried second option : After deployed successfully when i run the web app it displayed message displayed on page 'The Web App's container could not start. Please try again in few minutes. If you are an administrator of this Web App please verify your container settings and go to Azure Portal to review the diagnostic logs'
When i connected to the ftp to check the files in wwwroot folder. Only 'hostingstart.html' file is present.
Docker image has no issue as i am able to run it locally and on container instance.
My first question is : Is the above two methods are same thing beacuse in first method it looks like normal web app with kudu/app service editor option available but in second method i do not found kudu/app service editor support.
Second question is : I want to implement web app for container so only second option is the one i should go for?
Any idea what i am missing?

A: As shared by the original poster in the comments, retrying pushing the image to the container worked.


text:
Q: Building Autocomplete using Typescript but getting errors I am trying to build an Autocomplete drop down that shows a persons pronouns. But I am currently getting a few type errors and unsure how to fix them.
Here is the code:
import React from "react";
import { useState, useEffect, useRef } from "react";

const AutoComplete = ({ options = ["Him", "Her", "None"] }) => {
  const [value, setValue] = useState("");
  const [showSuggestions, setShowSuggestions] = useState(false);
  const suggestions = options.filter((option) =>
    option.toLowerCase().includes(value.toLowerCase())
  );

  const autocompleteRef = useRef();

  useEffect(() => {
    const handleClick = (event: any) => {
      if (
        autocompleteRef.current &&
        !autocompleteRef.current.contains(event.target)
      ) {
        setShowSuggestions(false);
      }
    };
    document.addEventListener("click", handleClick);
    return () => {
      document.removeEventListener("click", handleClick);
    };
  }, []);

  const handleChange = (event: any) => {
    setValue(event.target.value);
  };

  const handleSuggestionClick = (suggestion: React.SetStateAction<string>) => {
    setValue(suggestion);
    setShowSuggestions(false);
  };

  return (

      <input
        value={value}
        onChange={handleChange}
        placeholder="Search"
        onFocus={() => setShowSuggestions(true)}
      />
      {showSuggestions && (

          {suggestions.map((suggestion) => (

 handleSuggestionClick(suggestion)}
              key={suggestion}
            >
              {suggestion}

          ))}

      )}

  );
};

export default AutoComplete;

These are the two errors I have:
Property 'contains' does not exist on type 'never'.
On line 17 for .contains
and line 38 on ref:enter image description here

A: The first error, "Property 'contains' does not exist on type 'never'", occurs because the useRef hook needs to know the type of the element it is referencing. You can fix this by providing a type argument to the useRef function. In this case, you can use HTMLDivElement as the type argument since the autocompleteRef is referring to a div element. So change:
const autocompleteRef = useRef();

To
const autocompleteRef = useRef<HTMLDivElement>(null);

The second error is due to a type mismatch between the handleSuggestionClick function parameter and the expected value type. The handleSuggestionClick function expects a string argument, but React.SetStateAction is a function that takes the current state as an argument and returns a new state value. You can fix this by changing the type of suggestion in the function parameter from React.SetStateAction to string. So change:
const handleSuggestionClick = (suggestion: React.SetStateAction<string>) => {

To
const handleSuggestionClick = (suggestion: string) => {

After making these changes, your code should work without any type errors.


text:
Q: Filter with a condition df <- data.frame(month_key = c(rep(201504, 2), rep(201505, 3)),
                 id = c(1, 2, 1, 2, 3))

I have a dataframe like df, for each month ID are not necessary distinct.
I want to filter my dataframe and keep only the ID with appears in the first month_key (in my exemple id = 1 and 2).
I don't want to select my id for the first month and inner_join with the other month ...
Thank you

A: ind <- df$id[df$month_key == df$month_key[1]]
df[df$id %in% ind,]
#  month_key id
#1    201504  1
#2    201504  2
#3    201505  1
#4    201505  2


text:
Q: can't convert T to baseEnt although have a where I have created a cycle manager using this code
 public class CycleManager
{
    private ConcurrentQueue<BaseCommand> m_Commands = new ConcurrentQueue<BaseCommand>();
    private EventContainer<BaseEvent> m_Container = new EventContainer<BaseEvent>();
    public void RunCommand(BaseCommand command)
    {
        m_Commands.Enqueue(command);
    }

    public void WaitForEvent<T>(Action<T> handler) where T : BaseEvent
    {
        m_Container.Add(handler);
    }
}

The event contain look like this:
public class EventContainer<TEvent> where TEvent : BaseEvent
{
    private Dictionary<Type, Action<TEvent>> m_eventHandlers = new Dictionary<Type, Action<TEvent>>();

    public void Add(Action<TEvent> handler)
    {
        m_eventHandlers.Add(typeof(TEvent), handler);
    }
}

I'm getting error
Argument 1: cannot convert from 'System.Action' to 'System.Action<CycleManagerTesting.Models.BaseEvent>'
in line m_Container.Add(handler);
I don't know how to do what I want . I just want to be able to do
var c = new CycleManager();
c.WaitForEvent<DoorOpenedEvent>(e =>
{
 // something with e.DoorID;
});

I know one of the solutions is:
    public void Add(Action<BaseEvent> handler)
    {
        m_eventHandlers.Add(typeof(TEvent), handler);
    }

but i don't want to cast everytime I'm using the method
var c = new CycleManager();
c.WaitForEvent<DoorOpenedEvent>(e =>
{
    var realevent = (DoorOpenedEvent)e;
});

 public class DoorOpenedEvent:BaseEvent
{
    public string DoorID { get; set; }
    public string Status { get; set; }
}

public class BaseEvent{}

A: The method EventContainer<BaseEvent>.Add expects a Action<BaseEvent> delegate.
However, the WaitForEvent method would accept and therefore try to add not only Action<BaseEvent>, but also Action<DerivedEvent> due the generic where T : BaseEvent constraint restricting T to be BaseEvent or any other possible type derived from BaseEvent (like class DerivedEvent : BaseEvent { }, for example).
But despite the WaitForEvent method accepting a delegate like Action<DerivedEvent>, it is simply impossible to pass on such a delegate to the EventContainer<BaseEvent>.Add method, because Action<DerivedEvent> is not convertible to Action<BaseEvent>.

One possible solution is to let the EventContainer<TEvent>.Add method accept not only Action<T>, but also "Action<derived from TEvent>". The latter will be wrapped in an anonymous or local function that itself accepts a TEvent parameter and thus is convertible to an Action<TEvent> (which then can be added to the dictionary). To enable this, a slight change in the signature of the Add method is required, making the method itself generic:
public class EventContainer<TEvent> where TEvent : BaseEvent
{
    ...

    public void Add<T>(Action<T> handler) where T : TEvent
    {
        m_eventHandlers.Add(
            typeof(T),
            (handler is Action<TEvent> handlerForTEvent)
                ? handlerForTEvent
                : InvokeHandlerWithDerivedEvent
        );

        void InvokeHandlerWithDerivedEvent(TEvent baseEvt)
        {
            if (baseEvt is T evt)
            {
                handler(evt);
            }
            else
            {
                // Ouch!
                // That is not supposed to happen.
                // Throw some exception or something...
            }
        }
    }


text:
Q: deep learning Denoisy Model with imageDataGenerator I have this code:
epochs =50
batch_size = 5
validation_split = 0.2

datagen = tf.keras.preprocessing.image.ImageDataGenerator(validation_split=validation_split )

train_generator = datagen.flow(
    X_train_noisy, y_train_denoisy, batch_size=batch_size,
    subset='training'
)

val_generator = datagen.flow(
    X_train_noisy, y_train_denoisy, batch_size=batch_size,
    subset='validation'
)

history = model.fit(train_generator,
         steps_per_epoch=(len(X_train_noisy)*(1-validation_split)) // batch_size, epochs=epochs,
                    validation_data = val_generator, validation_steps=(len(X_train_noisy)*validation_split)//batch_size)

X_train_noisy and y_train_denoisy are ndarray ([20,512,512,1]) p.e. But I get this error:
training and validation subsets have different number of classes after the split
How can I solve that?
thanks!

A: probably what happened is when the data is split for training and validation, the set of files selected for validation did not include any files in one or more of the classes. This can happen when your data set is small. Try increasing the validation_split to a larger value say like .5 and see if the problem goes away. It should. Then reduce the size of the validation split until the error reoccurs. That will determine the minimum split value you can use. Remember the split is randomized so set the split value at something above the minimum value.
Another (BETTER) alternative is to split the data using sklearn train_test_split. This function has a parameter stratify that splits the data but ensures that all classes are included in the two component. See code below
from sklearn.model_selection import train_test_split
X_train_noisy, X_valid_noisy, y_train_denoisy, y_valid_denoisy=train_test_split(X_train_noisy,
       y_train_denoisy, test_size=validation_split,
      shuffle=True, random_state=123,
      stratify=y_train_denoisy)

now use these split variable in model.fit


text:
Q: bcrypt with salt how? I'm kind of new when it comes to security, I've been reading up on php crypt and searching for good advice though no one really goes into detail about "how" you go about doing it in the most effective way.
I made a test login which uses something like this:
 //verify login from user input
$username = mysql_real_escape_string($_POST['username']);
$salt = '$2a$10$cdDegHjJLPUvVXYz23679.MOetNHBk9NTStpY9YjJWiL5ECfhHlSm';
$password = crypt(mysql_real_escape_string($_POST['password']), $salt);

(I'm sure there's lots I need to change to make it fully secure (e.g restrict password string length) please enlighten me with anything else you think would be of good practice)
I read somewhere that it's ideal to make a random salt and store it with the password, (I don't fully understand that concept of checking a number that doesn't relate to the password)
Then I read somewhere that it's pointless to do a random salt because it won't increase the security, and that a static salt would do pretty much the same.
I saw this tutorial usinga random salt with $_GET. (Tell me this is not right)
Can someone point me in the right direction of making my bcrypt as effective as possible.
Thanks

A: Using a random salt for each password is important. PHP's implementation of the crypt() function will include it automatically in the resulting hash value so there is no problem where to store it, but it should be generated correctly from a random source.
I wrote a small article about bcrypt in PHP, because i think it's important that one understands how the function works. As soon as we understand it, we can use a well established library like phpass.

A: See my old answer on this thread over here. There is one interesting article and a link to phpass.


text:
Q: Table border-collapse Issue I have border-collapse: collapse set for a table. It looks fine except that the bottom border is cut-off.
Is there a workaround for this?

A: try setting the table's height to auto.

A: I created a white pixel and used it as a repeating background-image on right instead of a white border, issue solved.


text:
Q: DLL Import corrupting memory I am receiving this error while using a dllimport Attempted to read or write protected memory. This is often an indication that other memory is corrupt
private const string dir2 = @"C:\NBioBSP.dll";

[System.Runtime.InteropServices.DllImport(dir2, SetLastError = true, CallingConvention = System.Runtime.InteropServices.CallingConvention.Cdecl)]
public static extern uint NBioAPI_FreeFIRHandle(IntPtr hHandle, IntPtr hFIR);

I call it like this
uint resultado = NBioAPI_FreeFIRHandle(handle, handle);

Anyone know what the issue can be

A: Two problems.
First, the calling convention is wrong. Per the header file that defines the function (as well as the supporting file that defines NBioAPI as __stdcall on the Win32 platform), you should be using CallingConvention.StdCall.
Second, in the header that defines the types used by the API, NBioAPI_HANDLE and NBioAPI_FIR_HANDLE are typedef'd to UINT, which is always 32 bits (four bytes) long. You're using IntPtr, which has a platform-dependent size (it will be 64 bits in a 64-bit process.) Change the function parameters to uint.


text:
Q: what is the best way to add DateTimePicker data to database Below is the code i am using for my bindings but is giving me an error and its to do with the datatimepicker as if i remove this and add a textbox i get no error!! So obviously its something i am doing, so what is the best way to get the data from the datatimepicker and insert it into the database and with that said, on form load what is the value i need to grab the new value from that row to the datatimepicker.
Insert code:
Private Sub AddOrder()
    If con.State = ConnectionState.Closed Then con.Open()
    cmd = New OleDbCommand
    cmd.Connection = con
    cmd.CommandText = "INSERT INTO tblo(SDate, EDate)VALUES(?, ?);"

    cmd.Parameters.Add("?", OleDbType.Date).Value = DTS.Value
    cmd.Parameters.Add("?", OleDbType.Date).Value = DTE.Value
    cmd.ExecuteNonQuery()

    con.Close()
End Sub

bindings:
DTS.DataBindings.Add("value", bsorder, "SDate")
    DTE.DataBindings.Add("value", bsorder, "EDate")

Is this the only way to do this? It gives me a error when i use this way, if i just use textboxes for adding time it works so its something to do with my way of doing this DataTimePicker,
Please help thanks!

A: It seems that when trying to databind to a DateTimePicker it didnt like the whole Value even though it is a valid property as there is no "Text" within this. Anyway, when i change it to:
DTS.DataBindings.Add("Text", bsorder, "SDate")
DTE.DataBindings.Add("Text", bsorder, "EDate")

My error/issue goes away! It use to be "Value" instead of text but some reason it likes text now Value. I dont have a detailed report as to why or how this works? I just trial and error it and worked a charm now!


text:
Q: Angular multiple http requests I want to make a http call to the backend but before that, I need to get a oauth access token from the ID server. I think I have some syntax error. Am I doing it correctly?
myFunction() {
    let params = new URLSearchParams();
    params.append('grant_type','password');
    params.append('client_id', "xxx");
    params.append('client_secret', 'yyy');

    params.append('username', 'zzz');
    params.append('password', 'aaa');

    let headers =
      new HttpHeaders({'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'});

    return this.http.post('http://localhost:8888/auth/realms/mytestrealm/protocol/openid-connect/token',
      params.toString(), { headers: headers })
      .pipe(
        tap((res) => {

          var headers2 = new HttpHeaders({
            'Content-type': 'application/json',
            'Authorization': 'Bearer ' + res.access_token
          });
          this.http.post("/api/list", params, {headers: headers2})
        }
        )
      )
}

This is a function in a service class
The calling side is to subscribe on the result

A: I would suggest something like this:
myFunction() {
    // URLSearchParams can be create from an object (readability)
    let params = new URLSearchParams({
      'grant_type': 'password',
      'client_id': "xxx",
      'client_secret': 'yyy',
      'username': 'zzz',
      'password': 'aaa'
    });

    const headers =
      new HttpHeaders({'Content-type': 'application/x-www-form-urlencoded; charset=utf-8'});

    return this.http.post('http://localhost:8888/auth/realms/mytestrealm/protocol/openid-connect/token',
      params.toString(), { headers })
      .pipe(
        catchError((err, caught) => /* Logic in case the request for token errors */),
        map((res) => {
          if (res.hasOwnProperty('access_token') {
            new HttpHeaders({
              'Content-type': 'application/json',
              'Authorization': 'Bearer ' + res.access_token
            }),
          } else {
            throw new Error('No token');
          }
        }),
        // switchMap will perform the request and return the result
        switchMap(headers => this.http.post("/api/list", params, {headers})),
        catchError((err, caught) => /* Logic in case the previous request errors */)
      )
}


text:
Q: Why does this code to create a new database not work? I have the following code at the start of a T-SQL script to declare some variables then check if a database exists and to create it if not, followed by a USE statement for the database. The database is not being created so the USE fails. What is the reason this does not work?
DECLARE @new_doctypes varchar(40) = 'my_new_doctypes';
DECLARE @new_phrases varchar(40) = 'my_new_phrases';
DECLARE @new_map varchar(40) = 'my_new_typephrase_map';
DECLARE @error bit = 0;

IF EXISTS (SELECT name FROM master.sys.databases WHERE name = N'AV_Maint_New')
    BEGIN
        PRINT 'Error: Database AV_Maint_New already exists.';
        SET @error = 1;
    END
ELSE
    BEGIN
        CREATE DATABASE AV_Maint_New;
    END
USE AV_Maint_New;

A: SSMS is parsing that the database doesn't exist, before you execute it, and it doesn't understand how to follow if paths.
You need a GO between the IF structure and the USE command:
...
ELSE
BEGIN
  CREATE DATABASE AV_Maint_New;
END
GO
USE AV_Maint_New;


text:
Q: Java - What are the vulnerabilities of a port-listening program? I've recently created a fairly simple IRC client and server in Java but to make it fully functional I had to port forward. It occurred to me that there were probably some security issues with opening ports so I did some research. Everywhere, I found people saying that 'the biggest vulnerability is the program listening to the port'.
So my questions are:

*

*What exactly can be exploited in a Java program which listens to a port and writes incoming data to a string?

*As the developer of the software, how can I prevent these vulnerabilities?

A: Opening a port, reading incoming bytes and storing them in a string is safe with Java. Just be prepared to get illegal or "malicious" content. Trivial example: an application uses the received bytes for database queries and someone sends "sql injection code"...
There's more risk with programming language where buffer overflow is possible. Then one could use the connection to inject and execute machine code - if the listening application is vulnerable.
Preventing is pretty easy: validate the input and drop every illegal message. Add some tests that send illegal content and check, if those inputs are properly rejected.

A: There are numerous ways an attacker can take advantage of a known open port ranging from exploiting bugs in TCP implementation, causing denial-of-service by tricking your server into performing expensive computation (remember recent 2.2250738585072012e-308 bug?), causing buffer overflows to crash your program or to even make it execute arbitrary code.
Platform security
There have been a few vulnerabilities in TCP implementation on some operating systems in which an attacker relied on knowing an open port on a target host, e.g. SYN flood attack. These have been largely mitigated in all major OSes out there, but whoever is responsible for the security of your host should be on a constant lookout for recent security issues in the platform.
Server security
Vulnerabilities in the OS and TCP implementation aside, there are also potential issues connected with the server itself. If your server can perform security-relevant operations in response to requests it receives, an attacker can take advantage of it. These include reading and writing files, allocating large chunks of memory, sending queries to databases etc.
From developer perspective
Ensuring that your server can run with low privileges and low resources, that it validates all input received from the user and escapes all output it sends to other systems and that it does not perform any unnecessary security-relevant actions are the first steps to making it secure. If you do need to perform security-related operations, you may want to encapsulate them in a separate process and use IPC. Extensive testing of your program is very hard, but critical to its security as well.
From admin perspective
Critical points are making sure recent security updates in the OS have been applied, that your server actually does run with lowest privileges possible and that it is unable to exhaust critical system resources (e.g. CPU, RAM, open file descriptors, open TCP connections etc).

A: The vulnerabilities are in unauthorized usage of your program. Theoretically "bad guy" may perform reverse engineering of you wire protocol, understand how does your program work and make it to do "bad" things. For example if you program is able to delete files on disk when it receives delete command the bad guy may send this command with parameter /, so the program will remove all files from disk.
You can imagine yourself other scenarios.
This is the reason that system administrators do not like to open ports for any server but only for well known ones.
To prevent such scenario you should design your protocol well, use authentication mechanism and (probably) encryption of wire protocol.

A: Another batch of attacks are DOS attacks.
This is not specific for java, but java IMO does not protect you against:
- Attacker can send huge/infinite input to crash your application.
- Attacker can send imput slowly to consume your resources.


text:
Q: при выполнении php artisan queue:work - ошибка UnexpectedValueException Все команды работают запустил php artisan queue:work - и ошибка

UnexpectedValueException

  The stream or file "/home/proect/www/storage/logs/laravel.log" could not be opened in append mode: failed to open stream: Permission denied

  at vendor/monolog/monolog/src/Monolog/Handler/StreamHandler.php:146
    142|             restore_error_handler();
    143|             if (!is_resource($stream)) {
    144|                 $this->stream = null;
    145|
  > 146|                 throw new \UnexpectedValueException(sprintf('The stream or file "%s" could not be opened in append mode: '.$this->errorMessage, $url));
    147|             }
    148|             stream_set_chunk_size($stream, $this->streamChunkSize);
    149|             $this->stream = $stream;
    150|         }

      +7 vendor frames
  8   app/Exceptions/Handler.php:39
      Illuminate\Foundation\Exceptions\Handler::report()

      +2 vendor frames
  11  [internal]:0
      Illuminate\Foundation\Bootstrap\HandleExceptions::handleException()


text:
Q: XSLT transformation and renaming node I am procesing XML which has several different tags. I am matching tag  and copying value of tag  into new tag . I have only one problem with this xslt. What if value info does not exists in tag  that i am processing? I always get empty text tag after xslt transformation. Can this somehow be avoided, so if info tag does not exists in XML, new text tags will be removed also? Hope i was clear what is my problem. Thanks for any suggestions.
My XSLT:
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()" />
    </xsl:copy>
</xsl:template>

<xsl:template match="test">
    <text>
        <xsl:apply-templates select="info/text()"/>
    </text>
</xsl:template>

A: Create an additional template to handle info elements:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()" />
        </xsl:copy>
    </xsl:template>
    <xsl:template match="test">
        <xsl:apply-templates select="info"/>
    </xsl:template>
    <xsl:template match="info">
        <text>
            <xsl:apply-templates select="."/>
        </text>
    </xsl:template>
</xsl:stylesheet>

For example, on this simple input:
<r>
    <test>
        <info>blah</info>
    </test>
    <test></test>
</r>

The following output is produced:
<r>
    <text>blah</text>
</r>

You have provided no sample input or output so it is very difficult to tell if this is exactly what you're looking for, but the general idea stands.

A: You can include the requirement in the match attribute of the template: simply add a predicate testing for the presence of the text node.
test[info/text()]

The above XPath expression will only match if the test element has a child element named info with nonempty text nodes in it.
Otherwise you can also use a xsl:if element and test for the presence of the text node.
<xsl:if test="info/text()">
    <text>
        <xsl:apply-templates select="info/text()"/>
    </text>
</xsl>


text:
Q: showing cached page on error with cfcache I am curious if there is a way to do this, basically I have a set of API calls that are cached with the dependson flag. Now this generally works as a way to expire cache for the client when they make an update, I basically use this as a cache key, if they update something on the back-end then we know to expire the cache.
Now this works great 99% of the time but recently I had an issue with a poor performing query and it caused the DB to slow way down, essentially causing the query for the cache key to time-out, well the timeout cased the entire page to basically 'catch' and display a null object. This is problomatic because now users were getting 'blank' objects.
My question is, is there a way to, on-error just show the previous cached page and not try and update it?

A: You could just update the cache after you know it works so:
<cfsavecontent variable="content">
<cfoutput>
<!--- create your content here. --->
</cfoutput>
</cfsavecontent>

<!--- Then write the content to cache. --->
My Caching code ..... goes here
<cfoutput>#content#</cfoutput>