text:
Q: is there a way to get an Angular AST from a template (with ng-ast)? I'd like to build an app that can read source files of an Angular application and then work with the ASTs of the template files.
Here's a standalone node script that can reproduce the problem:
const Path = require('path');
const fs = require('fs');
const { WorkspaceSymbols } = require('ngast');

try { fs.mkdirSync("./foo") } catch (e) {};
try { fs.mkdirSync("./foo/src") } catch (e) {};
try { fs.mkdirSync("./foo/src/app") } catch (e) {};

const files = {
    "README.md": "# angular-ivy-scfsqv\n\n[Edit on StackBlitz ⚡](https://stackblitz.com/edit/angular-ivy-scfsqv)",
    "angular.json": "{\n  \"$schema\": \"./node_modules/@angular/cli/lib/config/schema.json\",\n  \"version\": 1,\n  \"newProjectRoot\": \"projects\",\n  \"projects\": {\n    \"demo\": {\n      \"root\": \"\",\n      \"sourceRoot\": \"src\",\n      \"projectType\": \"application\",\n      \"prefix\": \"app\",\n      \"schematics\": {},\n      \"architect\": {\n        \"build\": {\n          \"builder\": \"@angular-devkit/build-angular:browser\",\n          \"options\": {\n            \"outputPath\": \"dist/demo\",\n            \"index\": \"src/index.html\",\n            \"main\": \"src/main.ts\",\n            \"polyfills\": \"src/polyfills.ts\",\n            \"tsConfig\": \"src/tsconfig.app.json\",\n            \"assets\": [\n              \"src/favicon.ico\",\n              \"src/assets\"\n            ],\n            \"styles\": [\n              \"src/styles.css\"\n            ],\n            \"scripts\": []\n          },\n          \"configurations\": {\n            \"production\": {\n              \"fileReplacements\": [\n                {\n                  \"replace\": \"src/environments/environment.ts\",\n                  \"with\": \"src/environments/environment.prod.ts\"\n                }\n              ],\n              \"optimization\": true,\n              \"outputHashing\": \"all\",\n              \"sourceMap\": false,\n              \"extractCss\": true,\n              \"namedChunks\": false,\n              \"aot\": true,\n              \"extractLicenses\": true,\n              \"vendorChunk\": false,\n              \"buildOptimizer\": true\n            }\n          }\n        },\n        \"serve\": {\n          \"builder\": \"@angular-devkit/build-angular:dev-server\",\n          \"options\": {\n            \"browserTarget\": \"demo:build\"\n          },\n          \"configurations\": {\n            \"production\": {\n              \"browserTarget\": \"demo:build:production\"\n            }\n          }\n        },\n        \"extract-i18n\": {\n          \"builder\": \"@angular-devkit/build-angular:extract-i18n\",\n          \"options\": {\n            \"browserTarget\": \"demo:build\"\n          }\n        },\n        \"test\": {\n          \"builder\": \"@angular-devkit/build-angular:karma\",\n          \"options\": {\n            \"main\": \"src/test.ts\",\n            \"polyfills\": \"src/polyfills.ts\",\n            \"tsConfig\": \"src/tsconfig.spec.json\",\n            \"karmaConfig\": \"src/karma.conf.js\",\n            \"styles\": [\n              \"styles.css\"\n            ],\n            \"scripts\": [],\n            \"assets\": [\n              \"src/favicon.ico\",\n              \"src/assets\"\n            ]\n          }\n        },\n        \"lint\": {\n          \"builder\": \"@angular-devkit/build-angular:tslint\",\n          \"options\": {\n            \"tsConfig\": [\n              \"src/tsconfig.app.json\",\n              \"src/tsconfig.spec.json\"\n            ],\n            \"exclude\": [\n              \"**/node_modules/**\"\n            ]\n          }\n        }\n      }\n    }\n  },\n  \"defaultProject\": \"demo\"\n}",
    "package.json": "{\n  \"name\": \"angular\",\n  \"version\": \"0.0.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"@angular/animations\": \"^11.0.8\",\n    \"@angular/common\": \"^11.0.8\",\n    \"@angular/compiler\": \"^11.0.8\",\n    \"@angular/core\": \"^11.0.8\",\n    \"@angular/forms\": \"^11.0.8\",\n    \"@angular/platform-browser\": \"^11.0.8\",\n    \"@angular/platform-browser-dynamic\": \"^11.0.8\",\n    \"@angular/router\": \"^11.0.8\",\n    \"rxjs\": \"^6.6.3\",\n    \"tslib\": \"^2.1.0\",\n    \"zone.js\": \"^0.11.3\"\n  },\n  \"scripts\": {\n    \"ng\": \"ng\",\n    \"start\": \"ng serve\",\n    \"build\": \"ng build\",\n    \"test\": \"ng test\",\n    \"lint\": \"ng lint\",\n    \"e2e\": \"ng e2e\"\n  },\n  \"devDependencies\": {\n    \"@angular-devkit/build-angular\": \"~0.1100.4\",\n    \"@angular/cli\": \"~11.0.4\",\n    \"@angular/compiler-cli\": \"~11.0.4\",\n    \"@types/jasmine\": \"~3.6.0\",\n    \"@types/node\": \"^12.11.1\",\n    \"codelyzer\": \"^6.0.0\",\n    \"jasmine-core\": \"~3.6.0\",\n    \"jasmine-spec-reporter\": \"~5.0.0\",\n    \"karma\": \"~5.1.0\",\n    \"karma-chrome-launcher\": \"~3.1.0\",\n    \"karma-coverage\": \"~2.0.3\",\n    \"karma-jasmine\": \"~4.0.0\",\n    \"karma-jasmine-html-reporter\": \"^1.5.0\",\n    \"protractor\": \"~7.0.0\",\n    \"ts-node\": \"~8.3.0\",\n    \"tslint\": \"~6.1.0\",\n    \"typescript\": \"~4.0.2\"\n  }\n}",
    "tsconfig.json": "{\n  \"compileOnSave\": false,\n  \"compilerOptions\": {\n    \"baseUrl\": \"./\",\n    \"outDir\": \"./dist/out-tsc\",\n    \"sourceMap\": true,\n    \"declaration\": false,\n    \"downlevelIteration\": true,\n    \"experimentalDecorators\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"importHelpers\": true,\n    \"target\": \"es2015\",\n    \"typeRoots\": [\n      \"node_modules/@types\"\n    ],\n    \"lib\": [\n      \"es2018\",\n      \"dom\"\n    ]\n  },\n  \"angularCompilerOptions\": {\n    \"enableIvy\": true,\n    \"fullTemplateTypeCheck\": true,\n    \"strictInjectionParameters\": true\n  }\n}",
    "src/index.html": "<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\">\n<my-app>loading</my-app>",
    "src/main.ts": "import './polyfills';\n\nimport { enableProdMode } from '@angular/core';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\nimport { AppModule } from './app/app.module';\n\nplatformBrowserDynamic().bootstrapModule(AppModule).then(ref => {\n  // Ensure Angular destroys itself on hot reloads.\n  if (window['ngRef']) {\n    window['ngRef'].destroy();\n  }\n  window['ngRef'] = ref;\n\n  // Otherwise, log the boot error\n}).catch(err => console.error(err));",
    "src/polyfills.ts": "/**\n * This file includes polyfills needed by Angular and is loaded before the app.\n * You can add your own extra polyfills to this file.\n *\n * This file is divided into 2 sections:\n *   1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.\n *   2. Application imports. Files imported after ZoneJS that should be loaded before your main\n *      file.\n *\n * The current setup is for so-called \"evergreen\" browsers; the last versions of browsers that\n * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),\n * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.\n *\n * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html\n */\n\n/***************************************************************************************************\n * BROWSER POLYFILLS\n */\n\n/** IE9, IE10 and IE11 requires all of the following polyfills. **/\n// import 'core-js/es6/symbol';\n// import 'core-js/es6/object';\n// import 'core-js/es6/function';\n// import 'core-js/es6/parse-int';\n// import 'core-js/es6/parse-float';\n// import 'core-js/es6/number';\n// import 'core-js/es6/math';\n// import 'core-js/es6/string';\n// import 'core-js/es6/date';\n// import 'core-js/es6/array';\n// import 'core-js/es6/regexp';\n// import 'core-js/es6/map';\n// import 'core-js/es6/set';\n\n/** IE10 and IE11 requires the following for NgClass support on SVG elements */\n// import 'classlist.js';  // Run `npm install --save classlist.js`.\n\n/** IE10 and IE11 requires the following to support `@angular/animation`. */\n// import 'web-animations-js';  // Run `npm install --save web-animations-js`.\n\n\n/** Evergreen browsers require these. **/\n// import 'core-js/es6/reflect';\n// import 'core-js/es7/reflect';\n\n\n/**\n * Web Animations `@angular/platform-browser/animations`\n * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.\n * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).\n */\n// import 'web-animations-js';  // Run `npm install --save web-animations-js`.\n\n\n\n/***************************************************************************************************\n * Zone JS is required by Angular itself.\n */\nimport 'zone.js/dist/zone';  // Included with Angular CLI.\n\n\n/***************************************************************************************************\n * APPLICATION IMPORTS\n */\n\n/**\n * Date, currency, decimal and percent pipes.\n * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10\n */\n// import 'intl';  // Run `npm install --save intl`.",
    "src/styles.css": "/* Add application styles & imports to this file! */",
    "src/app/app.component.html": "
\n
\n\t
\n\t\t
Invoice
\n\t\t
\n\t\t\t
\n\t\t\t\tClient\n\t\t\t\t
\n\t\t\t\t\t<input type=\"text\" id=\"client\" class=\"form-control\">\n
\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\tAmount\n\t\t\t\t\t
\n\t\t\t\t\t\t<input type=\"number\" id=\"amount\" class=\"form-control\">\n
\n\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t\t\tDate\n\t\t\t\t\t\t
\n\t\t\t\t\t\t\t<input type=\"date\" id=\"date\" class=\"form-control\">\n
\n\t\t\t\t\t\t
\n\t\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t
\n\t\t\t\t\t
Preview
\n\t\t\t\t\t
Client: TODO
\n\t\t\t\t\t
Amount: TODO
\n\t\t\t\t\t
Date: TODO
\n\t\t\t\t
\n\t\t\t

",
    "src/app/app.component.ts": "import { Component, VERSION } from \"@angular/core\";\n\n@Component({\n  selector: \"my-app\",\n  templateUrl: \"./app.component.html\",\n  styleUrls: []\n})\nexport class AppComponent {\n  name = \"Angular \" + VERSION.major;\n}\n",
    "src/app/app.module.ts": "import { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { FormsModule } from '@angular/forms';\n\nimport { AppComponent } from './app.component';\n\n@NgModule({\n  imports:      [ BrowserModule, FormsModule ],\n  declarations: [ AppComponent ],\n  bootstrap:    [ AppComponent ]\n})\nexport class AppModule { }\n"
};

Object.entries(files).forEach(([path, contents]) => {
    fs.writeFileSync(Path.join(__dirname, `./foo/${path}`), contents);
});

const config = Path.join(process.cwd(), './foo/tsconfig.json');
const workspace = new WorkspaceSymbols(config);
console.log(workspace.getAllComponents()[0].getTemplateAst());

At the end there, workspace.getAllComponents()[0].getTemplateAst() returns null even though there is an app.component.html template present.
I don't really need to compile the entire project - I just need a way to take a single Angular HTML file and get an AST from it. Is that possible?


text:
Q: Ajax In Magento I've been reading about ajax in magento and their is alot of talk about modules and controllers, so after managing to setup a custom module, controller and frontend router
i'm now having problems, at the moment i just want my ajax call to return an category page and its products depending on what id/param is posted to the controller. I dont know alot about PHP so i looked around and came cross this
The Controller

public function indexAction() {
        $id = $this->getRequest()->getParam('id');

        if($id) {
            $_category = Mage::getModel('catalog/category')->load($id);
            $product = Mage::getModel('catalog/product');

            //load the category's products as a collection
            $_productCollection = $product->getCollection()
                ->addAttributeToSelect('*')
                ->addCategoryFilter($_category)
                ->load();

            // build an array for conversion
            $json_products = array();
            foreach ($_productCollection as $_product) {
                $_product->getData();
                $json_products[] = array(
                            'name' => ''.$helper->htmlEscape($_product->getName()).'',
                            'url' => ''.$_product->getProductUrl().'',
                            'description' => ''.nl2br($_product->getShortDescription()).'',
                            'price' => ''.$_product->getFormatedPrice().'');
            }

            $data = json_encode($items);

            echo $data;
        }
     $this->loadLayout(array('helloworld_index_index'));
     $this->renderLayout();
    }
}

i know this is not exactly what i need but im having trouble coming to grips ajax in magento
what i had in mind is that:

*

*in a ajax call i send the ID of the category to the controller

*the controller then arrays the products of the selected the category

*the array of products is sent/styled to the template file which is then sent back

if anyone can please help me i would be truly greatful
Thank you

A: This extension can help you work with AJAX in Magento: Magento Ajax Scroll Catalog
It loads product lists through Ajax/JSON in category pages, search results and advanced search results pages.

A: There is this one module that may help you in working in Ajax
http://www.magentocommerce.com/magento-connect/ajaxify-8411.html

A: From your code, you render the layout of the page finally through:
$this->renderLayout();

That's what your problem is. Try to organize the data in an array encode into Json format.
$this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));

And return.

A: You can use
http://github.com/hws47a/VF_EasyAjax
Allows frontend developers send ajax requests for every page and get Json response.
You don't need to work with app/code section of Manento and change any PHP code.
Make all what you need works via Ajax using only layout xmls, theme templates and javascript.
In the Json response frontend developers can receive:

*

*All messages that were added to session

*Some blocks from current page layout

*Any block that should be added to special layout xml

redpajama_set_name: RedPajamaStackExchange


text:
Q: Long SQL query fails This query I retrieved from another forum fails. When running it in Sequel PRO I get this error message:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'AS bar
)
SELECT
    q.id
FROM
    questions q
INNER JOIN
    concat_data cd
ON
 ' at line 27

This I the query I'm trying to run:
WITH raw_data AS (
    SELECT
        q.id AS id
      , q.description AS description
      , q.source AS source
      , q.image AS image
      , GROUP_CONCAT(c.choice ORDER BY c.choice) AS foo
    FROM
        questions q
    INNER JOIN
        choices c
    ON
        c.question_id = q.id
    GROUP BY
        q.id
      , q.description
      , q.source
      , q.image
),
concat_data AS (
    SELECT
        MIN(id) AS min_id
      , CONCAT(description, source, image, foo) AS bar
    FROM
        raw_data
    GROUP BY
        CONCAT(description, source, image, foo) AS bar
)
SELECT
    q.id
FROM
    questions q
INNER JOIN
    concat_data cd
ON
    cd.min_id = q.id;

And for the sake of it. Im trying to find duplicates from questions table that has a pivot table choices. Remove the duplicates and keep the the "original".

A: While you need "as bar" in the select portion (to make the alias "bar" for that concatenation), you do NOT need the "AS bar" in the GROUP BY clause.
GROUP BY
    CONCAT(description, source, image, foo)

should do.


text:
Q: It is possible to orthogonalize a set of linearly independent vectors via SVD? Let's say I have a set of linearly independent vectors, collected in a square matrix $\mathbf{M}$.
I know that I could orthogonalize these vectors with the QR decomposition,
$\mathbf{M} = \mathbf{QR}$
where $\mathbf{Q}$ is my orthogonal set of vectors.
I'm curious if it is possible to do the same with the SVD, but I cannot figure out how.
I want to know how to go from $\mathbf{M}$ to $\mathbf{Q}$, using SVD instead of QR.
If this is not possible, I'd like to know as well.

A: If $M$ is a matrix of $k$ linearly independent columns with SVD $M = U \Sigma V^H$, then the first $k$ columns of $U$ form an orthonormal basis for the span of the columns of $M$.

A: If $E$ is full rank (and it will be if $M$ is square and full rank), you can take the square root of it
$$UEV^H$$
$$=UE^{1/2}IE^{1/2}V^H$$
And so you can just absorb $E^{1/2}$ into $U$ and $V$.
It should go without saying that this is no longer a singular value decomposition and may lose all the nice properties SVD enjoys.


text:
Q: CF convention and GDAL projection I'm trying to create some NETCDF4 CF compliant files from some code that generates GDAL compatible files. I was wondering whether there is a simple translation from GDAL (or proj4) projection information and geotransform and what netcdf/CF expects.
I am using Python, GDAL (1.11.2), and the python NetCDF4 bindings, and it is safe to assume that I have an e.g. Proj4 string and a GDAL GeoTransform array available. The projections can range from the standard no projection WGS84 kind of data, to local a bunch of local, equal area types (e.g. UTM, or MODIS sinusoidal).


text:
Q: windbg source code debug ,can not see local variable in locals window I am using  windbg to process a remote debug, everything is ok, i can use  f10 or f11 to step debug. My debug eviroment is win7,language is c++.
there's one problem ,i can not see the local varialbe in function , it  shows as the following picture.
why is this situation happened? in my opinion , if i can see all registers of the process , i must can see the local variables of bRet.
can some one help me? thanks a lot.
Here is the code
bool CNBAGFxFont::Init()
{
    bool bret = true;
    m_pFontlib = *new GFxFontLib();
    if (m_pFontlib)
    {
        bret = m_pFontlib->Init();
    }
    if (!bret)
    {
          m_pFontlib = NULL;
          m_pGFxLoader->SetFontProvider(NULL);
          return bret;
    }
    //m_pFontMC = *m_pGFxLoader->CreateMovie("gfxfontlib.swf");
    //m_pFontlib->AddFontsFrom(m_pFontMC, true)
  }

here is the screen shot when debuging

A: The program was compiled with optimization.
From OP's comment:

If I disabled the optimization, WinDbg works and I can see the local variables in the window


text:
Q: Randomly dropping needles in a circle?
If we were to randomly drop $n$ needles of random length in a circle,
  what would be the odds of finding $k$ intersections? This can be asked
  as:
Randomly place $n$ line segments in a circle. Their length and position is
  determined by $2$ random points uniformly and independently set in that circle. What are the odds
  that we will find $k$ intersections?

After seeing the main part of the calculation for what I believe to be the solution for $P(2,1)$, I gave up on calculating $P(n,k)$ because the things behind it are out of my scope (we barely started mentioning integrals).
But I still want to find the $P(n,k)$.

Trying to first calculate the same thing, but with points always being on the circle, seems like a simpler thing to do first: Connecting random points on a circle?


text:
Q: How to remove the "\r\t\t" escape characters from XmlReader Reading outer Xml from an XmlReader, how do I remove whitespaces("\n\t\t") in my output?
using (XmlReader reader = XmlReader.Create(new FileStream(archivePath, FileMode.Open)))
{
    while (reader.Read())
    {
        if (reader.NodeType == XmlNodeType.Element)
        {
            if (reader.Depth == 1)
            {
                var xe = XNode.ReadFrom(reader) as XElement;
                XElement.Parse(xe.ToString(), LoadOptions.None);

                var reader2 = xe.CreateReader();
                reader2.MoveToContent();
                var content = reader2.ReadOuterXml();
            }
        }
    }
}

A: Try using XmlReaderSettings:
var readerSettings = new XmlReaderSettings
{
    IgnoreWhitespace = true,
};

using (XmlReader reader = XmlReader.Create(new FileStream(archivePath, FileMode.Open), readerSettings))
{
    //...
}

A: string.Replace(@"\n\t\t", "");

A: Try this function:
edit: Not a function; I have no idea what was going through my head.
reader.WhitespaceHandling = WhitespaceHandling.None;


text:
Q: Clustered Standard Errors in SUR - sureg or gsem in Stata I am trying to estimate vote shares of different parties. So, I have 3 parties, each having its own column in the data set. Hence, the sum of vote shares is 1, and hence the errors are correlated and I have to use Seemingly Unrelated Regressions (SUR) to estimate my system of equations. So, I can estimate only two equations, because otherwise I will get a singular matrix.
So, I have a system of 3 equations and I am using --sureg-- to estimate it.
sureg (voteshare_party1 voteshare_party2 = X_variables i.fixedeffectvariable1), isure

However, I want to cluster the standard errors at the area level. But I understand from the previous posts on this forum that this is not possible. If this is possible, then please let me know how should I proceed with it.
So, I used --gsem-- command (cannot use --sem-- because I need to add fixed effects), and my code now is:
gsem (voteshare_party1 <- X_variables i.fixedeffectvariable1) (voteshare_party2 <- X_variables i.fixedeffectvariable1), covstruct(e.voteshare_party1 e.voteshare_party2, unstructured) nocapslatent vce(cluster Area_level_variable)

I had to use -nocapslatent- because I did not want to include any other variable, apart from those mentioned in the regression in estimation.
However, this kept on running and showing the same likelihood value and (not concave), and so, I had to use iterate(20). Does stopping the iteration in-between give correct results?
My questions:
Can we cluster standard errors in --sureg--?
Will --gsem-- be a more efficient way to estimate the equations in my case?
Does stopping the iteration in-between give correct results?
I am relatively new to Stata, and so, I would really really appreciate your guidance on this.
I am happy to share more context if I haven't explained myself clearly.
Thank You

A: You could try using suregr as a postestimation step after using sureg quitely. suregr provides robust standard errors by default. However, for your case, you can provide cluster(area) option to obtain cluster-robust standard errors.
Check the recent paper by Gueorgui Kolev in state for reference.


text:
Q: Does deleting your own question when it has 0 or more reputation and zero answers hurt you? If, for some reason, I wanted to delete my question after I posted it, with the following info in mind, would my account be hurt in any way?

*

*It has 0 or more reputation attached to it

*It has no flags

*It has no answers

Would it be as if I never posted it?

A: The exact rules are not publicized and subject to change without notice. As a rule of thumb, if...

*

*No one else has put significant effort into your question, or

*It is more than 30 days old

...then you can delete it without penalty, provided the system allows it.
If the question has been answered or critiqued, you're better off doing what you can to improve it first. This isn't always possible, but folks who make a habit of posting poor questions and then deleting them will tend to find themselves in trouble.

A: The algorithm of the question ban is secret. Your question falls under that category. In other words

The developers could tell you but then they'd have to kill you.

And you should always think twice before asking to make sure only good questions being asked on the network.

A: Why not just leave it how it is...it could potentially earn you a nice shiny badge:  Tumbleweed (bronze)

Asked a question with no votes, no answers, no comments, and low views for a week


text:
Q: Error: Error in parsing: ... Line 212: Unexpected token => while doing gulp serve Facing an issue while using =>
incomingDemandCodes.findIndex(record => record.a === b[0].a);

in place of
incomingDemandCodes.findIndex(function (record){
  return  record.a === b[0].a;
});

where b & incomingDemandCodes are the arrays a as one property.
and the error that I receive during the Gulp serve is

internal/streams/legacy.js:59
  throw er; // Unhandled stream error in pipe.
  ^

Error: Error in parsing: "bay-status\editDemand-dialog.controller.js", Line 212: Unexpected token =>


text:
Q: REGEXP_SUBSTR Hex range in Oracle 11g and Oracle 12c I am trying to check for certain invalid non-UTF8 characters. From one of the post in this forum, I found this query:
SELECT REGEXP_SUBSTR('This will be my first time visiting Seattle. ',
       UNISTR('[\FFFF-\DBFF\DFFF]')) as str FROM dual;

Which gives the following output:
str
-------------------------------------------

But the thing here is when I run the above query on Oracle 12c version, it works totally fine, but when I run the same on Oracle 11g(11.2.0.4) version, I get the following error:
ORA-12728: invalid range in regular expression
12728. 00000 -  "invalid range in regular expression"
*Cause:    An invalid range was found in the regular expression.
*Action:   Ensure a valid range is being used.

Kindly provide your suggestions as to what is wrong that I am doing here.

A: Your range [X-Y] in the pattern is wrong, since:
X=\FFFF is greater than Y=\DBFF (I don't know what \DBFF\DFFF is supossed to do).
By analogy - this regular expression [a-b] is right because a < b:
REGEXP_SUBSTR( 'some text', '[a-b]')

but this regular expression [b-a] is wrong because b > a:
REGEXP_SUBSTR( 'some text', '[b-a]')

and you will get the same error in this case:
SELECT REGEXP_SUBSTR('This will be my first time visiting Seattle.','[b-a]' ) FROM dual;
ORA-12728: invalid range in regular expression

----------
EDIT
----------

But then why the query executes fine in 12c and gives an error in 11g?

I am trying on Oracle 12.1.0.2.0, and get the same error
SELECT * FROM V$VERSION;

SELECT REGEXP_SUBSTR('This will be my first time visiting Seattle. ',
       UNISTR('[\FFFF-\DBFF\DFFF]')) as str FROM dual;

BANNER                                                                               CON_ID
-------------------------------------------------------------------------------- ----------
Oracle Database 12c Enterprise Edition Release 12.1.0.2.0 - 64bit Production              0
PL/SQL Release 12.1.0.2.0 - Production                                                    0
CORE    12.1.0.2.0  Production                                                                  0
TNS for 64-bit Windows: Version 12.1.0.2.0 - Production                                   0
NLSRTL Version 12.1.0.2.0 - Production                                                    0

Error starting at line : 3 in command -
SELECT REGEXP_SUBSTR('This will be my first time visiting Seattle. ',
       UNISTR('[\FFFF-\DBFF\DFFF]')) as str FROM dual
Error report -
ORA-12728: invalid range in regular expression


text:
Q: Google Maps gives error in IE when loading via https I'm trying to load a map via https into an iframe. In Firefox it works fine(and so does in IE when not using https), but in IE it gives the following error:

Webpage error details
User Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E)
  Timestamp: Wed, 14 Sep 2011 10:29:24 UTC
Message: Object doesn't support this property or method
  Line: 2449
  Char: 9
  Code: 0
  URI: https://maps.gstatic.com/cat_js/intl/en_ALL/mapfiles/365b/maps2/%7Bmain,mod_util,mod_act,mod_actbr,mod_adf,mod_appiw,mod_dir,mod_hover,mod_mssvt,mod_poly,mod_qdt,mod_rst%7D.js

Here is my code:
<iframe width="600" height="500" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="https://maps.google.com/maps?f=dhl=en&ie=UTF8&z=12&output=embed#urlParam#"></iframe>

Does anyone have a fix for this?


text:
Q: IspObjectToken::DisplayUI I tried to use IspObjectToken::DisplayUI from SAPI 5.4 in C# and I don't know what are the exact parameters for that.
void ISpObjectToken.DisplayUI(ref _RemotableHandle HWndParent, string pszTitle, string pszTypeOfUI,IntPtr pvExtraData, uint cbExtraData,object punkObject)

I know that we should put null for pszTitle, and for pszTypeOfUI we should use one of supported UI like MicTraining or AddRemoveWord , But I know nothing about the rest of it. I'm using windows 7 on my laptop.
Edit: This is the code that I wrote and obviously it's not working.
private void button1_Click(object sender, EventArgs e)
    {
        int pfSupported;
        string extradata = "test\0";
        IntPtr pvExtraData = Marshal.StringToHGlobalUni(extradata);
        uint cbExtraData = (uint)extradata.Length * sizeof(Char);
        Speechlib._RemotableHandle rh = new Speechlib._RemotableHandle();
        rh = getRemotableHandle(this.Handle);
        ISpObjectToken isot = (ISpObjectToken)new SpObjectToken();

        isot.IsUISupported("AddRemoveWord", pvExtraData, cbExtraData, null, out pfSupported);
        if (pfSupported == 1)
        {
            isot.DisplayUI(ref rh, null, "AddRemoveWord", pvExtraData, cbExtraData, null);
        }
    }
    SpeechLib._RemotableHandle getRemotableHandle(IntPtr handle)
    {
        IntPtr address = Marshal.AllocHGlobal(IntPtr.Size);
        Marshal.WriteIntPtr(address, handle);
        return (SpeechLib._RemotableHandle)Marshal.PtrToStructure(address, typeof(SpeechLib._RemotableHandle));
    }

A: You can always pass nulls and 0 (as appropriate) to get the default behavior for the type of UI.
If you want specific behavior, then what you pass depends on the type of UI, and on the underlying engine.
For the Microsoft Desktop SR engine, the pUnkObject parameter should always be NULL.  There are no (interesting) valid non-null values for this parameter.
pvExtraData and cbExtraData can be non-NULL if pszTypeOfUI is either SPDUI_UserTraining or SPDUI_AddRemoveWord.
When pszTypeOfUI is SPDUI_AddRemoveWord, then pvExtraData can be a standard null-terminated string containing the word to add to the lexicon.  cbExtraData should be the size of the string in bytes, including the terminating null.
When pszTypeOfUI is SPDUI_UserTraining, then pvExtraData should be a double-null-terminated string containing a set of training sentences.  cbExtraData should be the size of the entire string in bytes, including both terminating nulls.
I go into a bit more detail on my blog.

A: Seems like your code is a bit over complicated. With the right references, inclusion of System.Speech and SpeechLib I got the following to work and launch the AddRemoveWord dialog.
using SpeechLib;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
private void button1_Click(object sender, EventArgs e)
        {
            SpSharedRecoContext spSharedRecoCtx = new SpSharedRecoContext();
            ISpeechRecognizer ispSpeechReco = spSharedRecoCtx.Recognizer;
            if (ispSpeechReco.IsUISupported("AddRemoveWord", null))
            {
                ispSpeechReco.DisplayUI(this.Handle.ToInt32(), "Additional Training", "AddRemoveWord", "Example");
            }
        }

Eric also covers how to do custom grammar training using DisplayUI() here


text:
Q: Openrefine: cross.cell for similar but not identical values I have two dataset:

*

*one dataset has names of countries, but dirty ones like
Gaule Cisalpine (province romaine)
Gaule belgique
Gaule , Histoire
Gaule
ecc.

*the second dataset has two columns with the names of countries (clean) and a code like
Gaule | 1DDF
Is there a way to use cell.cross with value.contains() ? I tried to use reconcile-csv but it didn't work properly (it matches just the exact ones).

A: I've not been able to think of a great way of doing this, but given the substring you want to match between the two files is always the first thing in the 'messy' string, and if you want to do this in OpenRefine, I can see a way that might work by creating a 'match' column in each project for the cross matching.
In the 'clean' project use 'Add column based on this column' on the 'Country name' column, and in the GREL transform use:
value.fingerprint()

The 'fingerprint' transformation is the same as the one used when doing clustering with key collision/fingerprint and basically I'm just using it here to get rid of any minor differences between country names (like upper/lower case or special characters)
Then in the 'messy' project create a new column based on the dirty 'name of country' column again using the 'Add column based on this column' but in this case use the GREL transform something like:
value.split(/[\s,-\.\(\)]/)[0].fingerprint()

The first part of this "value.split(/[\s,-.()]/)" splits the string into individual words (using space, comma, fullstop, open or closed bracket as a separator). Then the '[0]' takes the first string (so the first word in the cell), then again uses the fingerprint algorithm.
Now you have columns in each of the projects which should match on the exact cell content. You can use this to do the look up between the two projects.
This isn't going to be completely ideal - for example if you have some country names which consist of multiple words it isn't going to work. However you could add some additional key columns to the 'messy' project which use the first 2,3,4 strings etc. rather than just the first one as given here.
e.g.
filter(value.split(/[\s,-\.\(\)]/),v,isNonBlank(v)).get(0,2).join(" ").fingerprint()

filter(value.split(/[\s,-\.\(\)]/),v,isNonBlank(v)).get(0,3).join(" ").fingerprint()

etc. (I've done a bit more work here to make sure blank entries are ignored - it's the get() command that's the key bit for getting the different numbers of words).
I'm guessing that most country names are going to be only a few words long, so it would only be a few columns needed.
I've not been able to come up with a better approach so far. I'll post some more here if I come up with anything else. You could also try asking on the OpenRefine forum https://groups.google.com/forum/#!forum/openrefine


text:
Q: More appropriate statement for the SHM I know that the energy of SHM is given by
$$E=\frac 12 kA^2$$
So which of these is more appropriate to say?

*

*Energy is increases because amplitude is increased.

*Amplitude is increased because energy is increased.

A: There is no 'because' in an equation.  $a=b$ does not imply $a \to b$ or $b \leftarrow a$.
If you increase the energy of an oscillator, you will increase its amplitude. If you increase its amplitude you will increase its energy.
This is brought out neatly in our use of Ohm's law.   $V=IR$ is usually read and used as 'If you apply $V$ volts across $R$ ohms you get $I$ amps.' But sometimes (for example in a potential divider)  you use it as 'There is a current of $I$ amps flowing through $R$ ohms so that gives $V$ volts".

A: It depends on the context of the question you're asked to solve using this formula. The formula you've written is that of the total energy of a simple harmonic oscillator, such as a block attached to a spring.

At the maximum displacement, there is no kinetic energy and the potential energy is hence given by $\frac 12 kA^2$. Note that from this, $E \propto A^2$.
Now, if we pull the block so that its amplitude increases, we are giving energy to the system. This means that the energy and the amplitude both increase.
Do note that we can't say one happened because of another, it really depends on the case you're looking at. (A parallel you can draw is, in $\vec F=m \vec a$, if you increase the force applied, the body's acceleration will increase, and if you note an increase in the body's acceleration, of course the force must be increasing.)
In most cases, however, we usually are able to easily change the amplitude manually, because of which the energy of the system changes. Changing the amplitude is the way in which we increase the energy. In that sense, the energy increase happened because we changed the amplitude.


text:
Q: Is it possible to disable/override a ScriptResourceMapping requirement? I upgraded a WebForms project to .net 4.5, and received this error:

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping
  for 'jquery'. Please add a ScriptResourceMapping named
  jquery(case-sensitive).

I'd like to enable UnobtrusiveValidation, but I'm using Combres for Javascript resources, so I don't want the ScriptManager to try to download it again. Is it possible to tell the ScriptManager to just trust me that it will be loaded? In other words, I want to add a mapping for "jquery" that does nothing. It's apparently not possible to add a ScriptResourceDefinition with a name but no paths. Is there any other way?

A: As far as I can tell the answer is no.
This question has been asked on http://connect.microsoft.com/VisualStudio/feedback/details/735928/in-asp-net-web-application-visual-basic-the-requiredfieldvalidator-doest-work and on http://forums.asp.net/t/1850831.aspx/1 with no answers.
As a quick and nasty workaround to this problem I have added an empty file called DummyJQuery.js into the solution put the code below into application_start:
 Dim jQuery As New ScriptResourceDefinition()
 jQuery.Path = "~/js/DummyJQuery.js"
 jQuery.DebugPath = "~/js/DummyJQuery.js"
 ScriptManager.ScriptResourceMapping.AddDefinition("jquery", jQuery)

A: Answer described here: http://www.codeproject.com/Articles/465613/WebForms-UnobtrusiveValidationMode-requires-a


text:
Q: TextFormField disappears on click I have form to grab info from User. But when I tap on TextFormField and keyboard shows it disappears.
https://youtu.be/UhVL2hqWOlQ
Here is my code:
class _AddInfoState extends State<AddInfo>{

  static final GlobalKey<FormState> _key = new GlobalKey();
  bool _validate = false;
  String strTitle;
  File fileImage;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      body:new Container(
        child: new Form(
          key: _key,
          autovalidate: _validate,
          child: formUI(),
        ),
      ),
    );
  }

  Widget formUI(){
    return new ListView(
      children: <Widget>[
        //Title Field
        new Container(
          padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 0.0),
          child:new TextFormField(
            style: styleTextField,
            keyboardType: TextInputType.text,
            autofocus: true,
            maxLength: 45,
            decoration: InputDecoration(
                hintText: 'Enter Title',
                prefixIcon: Icon(
                  Icons.title,
                  size: 30.0,
                  color: blueColor,
                )
            ),
            validator: validateTitle,
            onSaved: (String val) {
              strTitle = val;
            },
          ),
        ),
      ],
      physics: new ClampingScrollPhysics(),
    );
  }

A: By my understanding from the video, since you have used a scrollable ListView inside your form, the list is scrolling upward once the keyboard appears hence it disappears.
Try setting resizeToAvoidBottomPadding: false in your Scaffold. This will make the keyboard appear as an overlay and won't push the content upward.
Example:
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      resizeToAvoidBottomPadding: false,
      body:new Container(
        child: new Form(
          key: _key,
          autovalidate: _validate,
          child: formUI(),
        ),
      ),
    );
  }

Let me know if this helps!

A: Wrap the Container which has the TextFormField in a SizedBox :
                new Form(
                autovalidate: false,
                key: _formKey,
                child: new Container(
                  height: orientation == Orientation.portrait ?  MediaQuery.of(context).size.height :  MediaQuery.of(context).size.width/1.2 ,
                  padding: EdgeInsets.only(left: 10.0, right: 10.0),
                  child:  new Column(
                    //mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: <Widget>[
                       Container(
                        padding: EdgeInsets.only(top: 20.0),
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                          children: <Widget>[
                            new SizedBox(
                            width: MediaQuery.of(context).size.width,
                            height: 100.0,
                            child: new Container(
                            padding: EdgeInsets.fromLTRB(20.0, 10.0, 20.0, 0.0),
                             child:new TextFormField(
                             style: styleTextField,
                             keyboardType: TextInputType.text,
                             autofocus: true,
                             maxLength: 45,
                             decoration: InputDecoration(
                             hintText: 'Enter Title',
                             prefixIcon: Icon(
                             Icons.title,
                             size: 30.0,
                             color: blueColor,
                           )
                         ),
                         validator: validateTitle,
                         onSaved: (String val) {
                           strTitle = val;
                         },
                       ),
                     ),
                   )

                           ]
                         )
                       )
                     ]
                   )
                 )
               )

A: Set the resizeToAvoidBottomPadding: false and then change the Column to a ListView


text:
Q: sql oracle max(x) returning row with higher x I know there are several Qs on the MAX() topic with very fancy queries but i still cant solve this...
I need help with this Query on an Oracle DB:
select ID, Object, Result
from STable
where Date='01012000'
and Object='testobject'
and ID='002'
union select  '002' as ID, 'testobject' as Object, 0 as Result from dual

returning
ID   OBJECT     RESULT
002  testobject  0
002  testobject  42

i need the row with the higher result
Expected Output:
002  testobject  42

so my Idea was:
select ID, Object, max(Result) as maxresult
from(
select ID, Object, Result
from STable
where Date='01012000'
and Object='testobject'
and ID='002'
union select  '002' as ID, 'testobject' as Object, 0 as Result from dual
) group by ID, Object

which returns the same as above... but
select  max(Result) as maxresult
from(
select ID, Object, Result
from STable
where Date='01012000'
and Object='testobject'
and ID='002'
union select  '002' as ID, 'testobject' as Object, 0 as Result from dual
)

returning
MAXRESULT

42

and seems to work fine.
What do i miss? any help is greatly appreciated

A: Your first query returns 2 rows because of the GROUP BY. You can apply ORDER BY after UNION and get the first row.

A: My guess? Either ID or object contains spaces since it should have been grouped by, so something is different between the first 002 and the second..
Try:
select trim(ID), trim(Object), max(Result) as maxresult
from(
select ID, Object, Result
from STable
where Date='01012000'
and Object='testobject'
and ID='002'
union select  '002' as ID, 'testobject' as Object, 0 as Result from dual
) group by trim(ID), trim(Object)


text:
Q: sublime text VS os terminal I am an absolute beginner using (actually trying to) Mac High Sierra with Sublime3 and Python2.7. Just installed them.
When I test Sublime on terminal, here's what I get:
pc37:desktop flop$ one
-bash: one: command not found

I setup Sublime to write in Python and saved the file "one.py" on my desktop.
Does it come from Sublime or the OS?
I read a few debugging articles on the subject but didn't understand half of it... Didn't want to make the situation worst using wrong command lines.
Could someone help please? Thank you! Flo

A: You need to use valid Bash command syntax for executing Python scripts in Terminal:
python one.py

...or...
./one.py

Of course this requires you cd to ~/Desktop first.


text:
Q: monitor the network traffic into a specific directory I'm aware that iftop monitors the network traffic on the current host, but is there a program that monitors the network traffic to a specified directory on the filesystem?

A: Hard truth
What you are requesting cannot be exactly done: you could write a software that could approximate that but that's about it.
Why?
The "network" cannot write anything in a folder: you must use a program for that like curl or firefox. The problem with a program such as firefox is that you have no idea, from the outside of it, whether a specific file it wrote is coming from the internet or not.
Having accurate information regarding that matter would require that every such program (i.e. able to write to disk from the network) actually report what they are doing somewhere. Unfortunately, this is not the case.
Approximation
An approximation of what you need would be to categorize programs as "internet writers" and "local writers" and then look at which program, in which category writes what and where. But as you may guess, this is no guarantee that the files written actually come from the internet.
Implementations
As far as I know, there are no implementations of such monitoring software though it is definitely possible to write one using inotify for instance to monitor changes in a specific folder and some logic about what is writing there (in order to categorize as "coming from the internet) and how much it writes (in order to have an idea of the traffic there).


text:
Q: Identify consecutive integers from a list of list I have the following lists and I'd like to get the consecutive integers from all the list.
list = [[3, 10, 15, 88],
[4, 11, 30],
[1, 6, 12, 50, 74]]

It should return [10, 11, 12].
If there are more than one consecutive list like
list = [[3, 10, 15, 88],
[4, 11, 30],
[5, 6, 12, 50, 74]]

It should return both [3,4,5] and [10,11,12].
I'd like to know the most efficient solution. Thank you.

A: l = [[3, 10, 15, 88],
    [4, 11, 30],
    [5, 6, 12, 50, 74]]

result = [[elem-1,elem,elem+1] for elem in l[1] if (elem+1) in l[2] and (elem-1) in l[0] ]

[[3, 4, 5], [10, 11, 12]]

for elem in l[1] : we are going to iterate over middle list and check if elem+1in the next list and elem-1 in previous list

A: Try this in just one line using product:
from itertools import product

l = [[3, 10, 15, 88],
    [4, 11, 30],
    [5, 6, 12, 50, 74]]

result = [[i,j,k] for i,j,k in product(*l) if k==j+1 and j==i+1]

The result will be:
In [7]: result
Out[7]: [[3, 4, 5], [10, 11, 12]]

Note that: Do not use list as a variable name. it is predefined in python and you will override its main functionality.

A: you can simply do this to get the required answer
from operator import itemgetter
data = [ 1,4,5,6,10,15,16,17,18,22,25,26,27,28]
for k, g in groupby(enumerate(data), lambda (i, x): i-x):
   print map(itemgetter(1), g)

Result:
[1]
[4, 5, 6]
[10]
[15, 16, 17, 18]
[22]
[25, 26, 27, 28]

A: with simple reasoning
l = [[3, 10, 15, 88],
[4, 11, 30],
[5, 6, 12, 50, 74]]

l2 = [(index,j) for index,i in enumerate(l) for j in i] # flattening the list
l2 = sorted(l2, key= lambda x: x[1]) # sorting the list
# the sorted list has the below structure (sublist_number, item)

output = []
current_group = []
temp = []

for i in l2:
    if(len(temp) == 0):
        temp.append(i[1])
        current_group.append(i[0])
    else:
        if(i[1] - temp[-1] != 1): # that means not consecutive
            if(len(temp) == 3):
                output.append(temp.copy())
            temp.clear()
            current_group.clear()
            temp.append(i[1])
            current_group.append(i[0])
        else:
            if(i[0] not in current_group):
                temp.append(i[1])
                current_group.append(i[0])

print(output)

[[3, 4, 5], [10, 11, 12]]


text:
Q: Check for key in hash maps while checking user input I am trying to compare the key values of a hashmap with user input but I'm not sure of what approach should be taken.
This is the current code I have:
Scanner scan = new Scanner(System.in);
    System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
    String input = scan.nextLine();

    HashMap helloMap = new HashMap<>();
    helloMap.put("hello", "you typed hello");

    HashMap goodbyeMap = new HashMap<>();
    goodbyeMap.put("goodbe", "you typed goodbye");

    if(input.equals(helloMap)){

        String helloOutput = (String) helloMap.get("hello");
        System.out.println(helloOutput);

    }
    else if (input.equals(goodbyeMap)){
        String goodbyeOutput = (String) goodbyeMap.get("goodbye");
        System.out.println(goodbyeOutput);

    }
    else{
        System.out.println("Invalid input");
    }

The issue that I've ran into is that when I try to use this program it always defaults to the else clause and this is because I'm used to using .equals to compare it to a String value but I know this is different! Does anyone know the solution for this? Ok so I found a solution for it... It works but is it good enough?
 String goodbyeCommand = String.valueOf(goodbyeMap.keySet()).replace("[^a-zA-Z0-9]", "").trim();

 String helloCommand = String.valueOf(helloMap.keySet()).replaceAll("[^a-zA-Z0-9]", "").trim();

A: The problem
You are comparing the input String with the HashMap object. String object is not equal to HashMap object, which is why the boolean expression is always false.
The solution
Please have a look at the following sample:
Map<String, String> outputMap = new HashMap<>();
outputMap.put("hello", "you typed hello");
outputMap.put("goodbye", "you typed goodbye");

System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
Scanner scan = new Scanner(System.in);
String input = scan.nextLine();
scan.close();

String output = outputMap.get(input);
if (output == null) {
    System.out.println("Invalid input");
} else {
    System.out.println(output);
}

Breakdown

*

*We define a Map<String, String> containing the program's response mapped to predefined user inputs.

*We ask the user for input. When you are done using Scanner, it is good practice to close it by calling .close().

*We retrieve the response from the map based on the user input.

*We check for null: if it is null, it means the user input was not a valid key for outputMap.

*Print the result.

A: Yes, you need to compare to the actual element of your map instead of the map itself:
Scanner scan = new Scanner(System.in);
    System.out.println("Type an instruction from the list \n 1. hello \n 2. goodbye");
    String input = scan.nextLine();

    HashMap helloMap = new HashMap<>();
    helloMap.put("hello", "you typed hello");

    HashMap goodbyeMap = new HashMap<>();
    goodbyeMap.put("goodbe", "you typed goodbye");

    if(input.equals(helloMap.get("hello"))){

        String helloOutput = (String) helloMap.get("hello");
        System.out.println(helloOutput);

    }
    else if (input.equals(goodbyeMap.get("goodbe"))){
        String goodbyeOutput = (String) goodbyeMap.get("goodbye");
        System.out.println(goodbyeOutput);

    }
    else{
        System.out.println("Invalid input");
    }


text:
Q: How to create sub-class in my program (Shapes Area Calculator | JAVA) I need help because I do have a problem on creating a sub-class in my program. I do only have a main-class as you can see below. I don't know how to create a sub-class for my formula to seperate it from my main class.
import javax.swing.JOptionPane;
import java.util.*;

public class shapes {

public static void main(String[] args) {

    String inputStr = JOptionPane.showInputDialog("Type 1 for the area of Circle \nType 2 for area of Triangle \nType 3 for Square \nType 4 for Rectangle \nType 5 for Octagon \nType 0 to exit.");

    int i = Integer.parseInt(inputStr);

    if (i == 1) {
        String inpu = JOptionPane.showInputDialog("Enter radius of a circle: ");
        double radius = Integer.parseInt(inpu);
        b.areaCircle(radius);
    }
    if (i == 2) {
        String input = JOptionPane.showInputDialog("Enter the base of a triangle: ");
        int n1 = Integer.parseInt(input);
        String inp = JOptionPane.showInputDialog("Enter the height of a triangle: ");
        int n2 = Integer.parseInt(inp);
        areaTriangle(n1, n2);
    }

    if (i == 3) {
        String sq = JOptionPane.showInputDialog("Enter the width of a square: ");
        int sqno1 = Integer.parseInt(sq);
        String sq2 = JOptionPane.showInputDialog("Enter the height of a square: ");
        int sqno2 = Integer.parseInt(sq2);
        areaSquare(sqno1, sqno2);
    }

    if (i == 4) {
        String inp = JOptionPane.showInputDialog("Enter the length of a rectangle: ");
        int m1 = Integer.parseInt(inp);
        String inp2 = JOptionPane.showInputDialog("Enter the width of a rectangle: ");
        int m2 = Integer.parseInt(inp2);
        areaRectangle(m1, m2);
    }

    if (i == 5) {
        String oct = JOptionPane.showInputDialog("Enter the side of octagon: ");
        double octno = Double.parseDouble(oct);
        areaOctagon(octno);
    }

    else {
        return;
    }
}

public static void areaCircle(double radius) {
    double areac = Math.PI * (radius * radius); // MATH PI is equivalent of pi = 3.14159
    JOptionPane.showMessageDialog(null, "The area of a circle is: " + areac);
}

public static void areaTriangle(int n1, int n2) {
    int areat = (n1 * n2) / 2;
    JOptionPane.showMessageDialog(null, "The area of a triangle is: " + areat);
}

public static void areaSquare(int sqno1, int sqno2) {
    int asquare = (sqno1 * sqno2);
    JOptionPane.showMessageDialog(null, "The area of square is " + asquare);
}

public static void areaRectangle(int m1, int m2) {
    int arear = (m1 * m2);
    JOptionPane.showMessageDialog(null, "The area of a rectangle is: " + arear);

}

public static void areaOctagon(double octno) {
    double aoct = (2 * 2.414 * octno);
    JOptionPane.showMessageDialog(null, "The area of a octagon is: " + aoct);

}

}

Can you help me to create a new sub-class for my program? Thanks


text:
Q: fluent-bit lua parse by namespace I have multiple namespaces and I want the data from each namespace to be sent to a different topic
Example namespaces:
 011231564
 012387455
 ...

I have code in lua
if the namespace starts with "00"
function namespace(tag, timestamp, record)
if string.sub(record["kubernetes"]["namespace"], 1, 10) == "0" then
record["topic"] = "cluster-0" .. string.sub(record["kubernetes"]["namespace"], 4)
return 1, timestamp, record
end
return 0, 0, 0
end

But the above code ends with a substring error


text:
Q: how to throw an alert saying " please turn off the pop up blocker"
Possible Duplicate:
How can I detect if a browser is blocking a popup?

hi iam trying to open a child window with disabled toolbar.......
how to check whether the child window is opened or not and then display this alert??
can someone help with code.........

A: When you create a new window using window.open(), it returns a handle to the (theoretically) opened window.  You can then test that handle to determine whether the window is open:
var child = window.open("mypopup.html");

// some popup blockers prevent the window from being created (!child) and
// others just close them before they're displayed (child.closed)

if (!child || child.closed) {
    // tell the user to turn off their popup blocker
}

Popups are very intrusive, however, and you should consider trying to display the "popup" information within the page.  In particular, have a look at "dialog" scripts.  If you're using jQuery, a very nice Dialog widget is included in the jQuery UI library.

A: I think, if popups are blocked, window.open() will return a null, not a window object. You can read it in an MSDN article:

If you are not sure whether a pop-up
  window is blocked, check your
  functions that return a window object.
  You can tell if a pop-up window has
  been blocked if these functions return
  null. In particular, you need to check
  the value of window.open to avoid
  script errors when your pop-up windows
  are blocked.

Also, this will give you some hints about detection of popup blockers: http://www.visitor-stats.com/articles/detect-popup-blocker.php

A: You need to give us the Javascript you are using so that we can help. You will need an 'if' statement.
Display alerts like this in javascript:
alert('Please turn off your pop-up blocker');


text:
Q: php sqlsrv_fetch_object performance Greetings!
I am attempting to solve a few performance issues which are cropping up on our site.  As part of this effort I have begun profiling our most trafficed pages according to GA.
Essentially I have determined, as I originally suspected, the majority of time spent is in database related traffic... makes sense.  Unfortunately, when looking closer, what I found DOESN'T make quite as much sense.
For example, this particular call, MyAlganon_Model_Library_Item::fetchItemTooltipsByItemIdArray() takes 580.41ms to return on my staging platform.
Upon diving into it 47.27ms of that time is spent on sqlsrv_query() while 533.12ms of it is spent in a fetchAll() function that simply loops doing sqlsrv_fetch_object:
$row = sqlsrv_fetch_object($this->query);

while ($row) {
  $results[] = $row;
  $row = sqlsrv_fetch_object($this->query);
}

return $results;

Looks like, on this particular page, there are 742 rows in the result set. Maybe it's just a matter of me not having a realistic handle on how long it takes to generate an StdClass object?  Does 533.12ms seem like a normal time to iterate across 742 results and turn them into an array of objects?

A: Depending on what you are doing the mssql_ is about 33-60 % faster than sqlsrv_ in my testing

A: As you said in your comment, you query 742 rows with 41 columns.
That's quite some data you're using. If you use all 41 columns, but just of a few of the rows, you could split your query. More queries is not always inefficient, if you can optimize to get less data in total.
Are the 41 columns of all 742 rows used? Maybe you can do a simple query to select which of the 742 rows you need all data for.

A: I've been trying to use sqlsrv too and found it can be really slow, sometimes taking several seconds to connect and perform a simple query - even on a table with a dozen rows and a handful of columns. It was faster on my development system (connecting to a local SQL Express) than on the destination host (real SQL Server, expensive premium hosting).
The web host even did some tests and said "This seems to suggest that the problem lies with the Microsoft SQL Server Driver for PHP, and not necessarily with the web or database servers or network conditions." He was comparing it to using ADODB: "Please note that this is an ODBC connection, this is not using the native PHP MSSQL driver which frankly, is unstable and should be avoided. [...] The test script above is routinely performing significantly better than the other test script that connects using the Microsoft SQL Server Driver for PHP."
However on my own system, sqlsrv_connect was a lot quicker to connect (usually between 0.1 ms and 100 ms) than $conn=ADONewConnection('odbc_mssql');$conn->Connect(); (usually between 30-200ms). Still testing other speeds: this project was more latency-sensitive than anything else.
A little note: you can update your provided snippet: (a little cleaner)
while (($row = sqlsrv_fetch_object($this->query))) {
  $results[] = $row;
}
return $results;


text:
Q: Laravel 7: Installing od FTP Server I installed Laravel 7 on my FTP server, but I get this message
Parse error: syntax error, unexpected ':', expecting '{' in /vendor/symfony/polyfill-php80/bootstrap.php on line 23

When I used localhost everything was fine. What is wrong?

A: Laravel 7 require PHP >= 7.2.5. Check version installed on server.


text:
Q: Download Phonegap or Cordova 3.1 I heard phonegap/cordova version 3.1 was released but I have yet to see how to download it. I have used the CLI command to check for 3.1 and all I see is 3.0.

A: Cordova 3.1 has just been released today.
You can get the latest version via npm: https://npmjs.org/package/cordova

A: According to Apache Cordova, the latest release is 3.0, not 3.1.
The Archive found here does not contain 3.1, and the Download link only shows 3.0.0 which is the latest.

A: To check your current version:
phonegap --version

or
phonegap -v

To see the latest version:
npm info phonegap version

Run this command to update:
npm update -g phonegap

Also, one way to get notified when it updates you can use npm-onupdate. To install npm-onupdate
npm install -g npm-onupdate
npm-onupdate add phonegap

To list out the packages you're signed up to get alerts for:
npm-onupdate ls

A: It' released, see docs here cordova.apache.org


text:
Q: TypeError: fit() got an unexpected keyword argument 'monitor' in mxnet python When I run the example/image-classification/train_mnist.py, I was told that TypeError: fit() got an unexpected keyword argument 'monitor'. I have change nothing in this file. And I have just download the latest version from the github.
example\image-classification>python train_mnist.py
INFO:root:start with arguments Namespace(batch_size=64, disp_batches=100, gpus=N
one, kv_store='device', load_epoch=None, lr=0.05, lr_factor=0.1, lr_step_epochs=
'10', model_prefix=None, mom=0.9, monitor=0, network='mlp', num_classes=10, num_
epochs=20, num_examples=60000, num_layers=None, optimizer='sgd', test_io=0, top_
k=0, wd=0.0001)
Traceback (most recent call last):
  File "train_mnist.py", line 76, in <module>
    fit.fit(args, sym, get_mnist_iter)
  File "D:\Zhenxingjian\MxNet\mxnet-0.9.3\mxnet-0.9.3\example\image-classificati
on\common\fit.py", line 183, in fit
    monitor            = monitor)
TypeError: fit() got an unexpected keyword argument 'monitor'

A: I was able to successfully run train_mnist.py example on v09.3, v0.9.5 and v0.10.0. If the problem still persists for you, maybe checkout the latest version and try again.


text:
Q: not able to .append  element? I'm not able to get the append (br) to work, but maybe it's because of the initial function?
But appending a (p) works fine.
$(window).width(function ()   {

    if ($(window).width() < 500) {
       $('#summary').append('
');
        $('span.orderType').css('margin-left','45px');
    }
    else if ($(window).width() > 500) {
        $('#summary').remove('
');
        $('span.orderType').css('margin-left','0');
    }
});

A: Unless you need to support IE8 or earlier, I'd scrap all of that and use this CSS:
@media (min-width: 500px) {
    .big-hide {
        display: none;
    }
}

...and put this br in your markup:

...and do something similar with the spans and their margin.
That uses a media query to hide the break if the browser window is 500px wide or wider. The browser does all the work, no JavaScript required.
If you need to support IE8, then use that same br markup and this:
$(window).resize(function ()   {

    $(".big-hide").toggle($(window).width() >= 500);

}).trigger("resize");

(And again, something similar with the span margin.)
That shows or hides elements using the big-hide class depending on whether the window is 500px wide, by responding to the window resize event. We also trigger the event to start with, so we show/hide when the page loads. Make sure the JavaScript is below any elements it's supposed to apply to (ideally, put it in a script tag just before the closing ).

A: Try using ..window).resize.. instead of ..window).width
https://api.jquery.com/resize/
So your function must look something like this
$(window).resize(function ()   {

    if ($(window).width() < 500) {
       ....
    }
    else if ($(window).width() > 500) {
        ....
    }
});


text:
Q: Am I using C# delegates in a useful way? I am doing a simple exercise using delegates in C#. The basic premise is that it simply performs calculations like addition and subtraction.
public class Calculator
{
    public static int Add(int num1, int num2)
    {
        return num1 + num2;
    }

    public static int Multiply(int num1, int num2)
    {
        return num1 * num2;
    }

    public static int Subtract(int num1, int num2)
    {
        return num1 - num2;
    }
}

And I have created a delegate that will call these functions in another class.
public delegate int CalculatorDelegate(int num1, int num2);

The implementation class looks like this:
public class Calculation
{
    public int PerformCalculation(int choice, int number1, int number2)
    {
        CalculatorDelegate cd;
        if (choice == 1)
        {
            cd = Calculator.Add;
            return cd(number1, number2);
        }
        else if (choice == 2)
        {
            cd = Calculator.Subtract;
            return cd(number1, number2);
        }
        else if (choice == 3)
        {
            cd = Calculator.Multiply;
            return cd(number1, number2);
        }
        else
        {
            cd = Calculator.Add;
            return cd(number1, number2);
        }
    }

}

What's confusing me about delegates is why not just do the following instead?
if (choice == 1)
{
    return Calculator.Add(number1,number2);
}

I think my confusion is surrounding the fact that if these methods are already static, what's the point of even making a delegate to them. I can simply just call them as static methods. If I try to make the methods non-static, then I cant have my delegate point to them in this other class, without creating some object of the other class.
I am all turned around on this example and what it even accomplishes and maybe someone can provide me some insight as to if I'm even using this remotely close to how it should be?

A: Delegates are types. Types that take a reference to a function, rather then some other value.
Delegates are there to hand functions as a argument to another function. Or to be used as the type for a generic class - mostly collections in practice. There are one of the many replacements for naked pointers that had to be invented, so .NET could shield you from having to handle naked pointers.
However they are also a case where the repalcement turned out to be better by a fair margin. For example, it is very possible to replace a switch/case with a Dictionary<caseLabel, delegateThatTakesAArgument>. If I gave you a int pointer in Native C++. you could not tell if this was a single variable I hand in by reference, the start of a array or a Function that returns int. With all those Pointer replacements, you know.
For this specific case, those functions themself are overkill. Delegates are even more overkill. That "PerformCalculation" function, sounds like it should be the User Input Interpreation part of a Console Application, not a function.
However there are not a lot of good, unambigious examples for Delegate use. So for learning it propably works okay. It is often a case where you have to make a judgement call between a switch/case with hardcoded operation and Delegates.
However Events are one of the rare clear cut case for Delegates I can think off. If you learn them for nothing else, learn them for Events.

A: I've created a Repl demonstrating a Worker pattern utilizing basic delegates (Actions, a type of delegate built into the standard library that takes no parameters and returns nothing).
You can check it out here.
ETA: The most common use-case for delegates is asynchronous/threaded programming.
Threads require delegates to run as they do not know the code to be run beforehand, they simply carry it as a parameter into the newly created thread of execution, it would otherwise be impossible to create threads (well, without having lower-level access than C# provides)
Check out the MSDN docs on the Threading API
Similarly, in asynchronous programming, you will generally need a callback (which would be a delegate in C#) in order to defer execution of the code until pre-existing conditions are met. (A runloop for example, a common alternative to threading which uses a single thread to execute multiple tasks "concurrently" step-by-step)

A: Once way you could use delegates in your example is to have a mapping from choice to CalculatorDelegate, then you just lookup the desired calculation and perform it:
static List<CalculatorDelegate> ChoiceMap = new List<CalculatorDelegate> { Calculator.Add, Calculator.Subtract, Calculator.Multiply };

public class Calculation {
    public int PerformCalculation(int choice, int number1, int number2) =>
        ChoiceMap[choice-1](number1, number2);
}

But since delegates are converted automatically from lambdas (CalculatorDelegate is essentially Func<int,int,int>), you no longer need the Calculator class:
static List<CalculatorDelegate> ChoiceMap = new List<CalculatorDelegate> {
    (n1, n2) => n1+n2,
    (n1, n2) => n1-n2,
    (n1, n2) => n1*n2
};

Note that the types of n1 and n2 in each lambda are inferred from CalculatorDelegate. Now adding new operations to PerformCalculation is simply a matter of adding a new lambda to the ChoiceMap.
Hopefully you can see how you could use a more complicated type for ChoiceMap, such as a Dictionary<string,Func<int,int,int>> where each key is a string representing an operator (e.g. "+") and the value is the operation to perform, which makes mapping to a simple calculator easy.
I use a similar Dictionary in a command line switch management helper, where each entry has the command name, the number of arguments, the delegate (method) to call (which may be a lambda when simple enough), the command grouping and some help text, where help output is generated automatically from the same Dictionary.


text:
Q: How to automatically trigger build on pull request in Azure DevOps? I have created a build pipeline.
have master, develop and feature/* branches in my Azure repo.
I have created a branch policy to require a build for feature/* branches.
How do I trigger an automatic build on pull request? Or even how do I queue a build manually on the pull request?
I can't see such option on my pull request screen in DevOps.
As far as I know the build policy should appear above Work Items on the right hand side. My policy does not appear there and I have no even a possibility to trigger the build manually.

I am not sure what I am doing wrong? Or what is missing?

A: The screenshot you provided shows that the PR is for the develop branch. If you want a PR for develop to trigger a build, then set a policy on the develop branch.
Branch policies apply to the target branch, not the source branch.


text:
Q: Divisions between large numbers with long integers: how to bypass float conversion? I need to calculate a ratio between very large numbers as shown in the code:
import scipy.special

x=2000
n=range(8,x+1)
q=[]

for i in range(0,len(n)):

    q.append(((n[i]-6)*26**(n[i]-7)-scipy.special.binom(n[i]//7+n[i]%7,n[i]//7))*(26**n[i])**(-1))

I get errors since numbers are too large:
OverflowError: long int too large to convert to float

how can I handle such large numbers?

A: You can use scipy.special.comb with the exact kwd and replace *large^(-1) with /large:
import scipy.special

x=2000
n=range(8,x+1)
q=[]

for i in range(0,len(n)):

    q.append(((n[i]-6)*26**(n[i]-7)-scipy.special.comb(n[i]//7+n[i]%7,n[i]//7, exact=True))/(26**n[i]))

print(q[-10:])

# [2.4714229501232675e-07, 2.4726679994684175e-07, 2.473913048813568e-07, 2.4751580981587185e-07, 2.4764031475038685e-07, 2.477648196849019e-07, 2.478893246194169e-07, 2.4801382955393194e-07, 2.4813833448844694e-07, 2.48262839422962e-07]

Division itself doesn't seem to be a problem:
(3**100)/(4**88)
# 5.380792381981753e-06

Note: The above appplies to Python3. On Python2 division between ints defaults to return an int. You can either use __truediv__
    q.append(((n[i]-6)*26**(n[i]-7)-scipy.special.comb(n[i]//7+n[i]%7,n[i]//7, exact=True)).__truediv__((26**n[i])))

or use a future import
from __future__ import division


text:
Q: Access query - get latest date with criterias I have the following data in a table "tbldata"
Equipment Type  Starting date   Ending Date
420-413     T1     2019-06-10     2019-06-15
402-483     T2     2019-06-14     2019-06-29
446-439     T4     2019-07-20     2019-07-30
420-413     T3     2019-12-08     2019-12-12
428-421     T2     2019-08-01     2019-09-01
420-413     T2     2019-09-08     2019-10-04

I've made a query "qryunpair" to unpair all matches from Equipment resulting in:
UnpairEquipment
402
413
420
421
428
439
446
483

I'm trying to have the latest date of "Ending Date" for every Type for each equipments.
I have the following code:
SELECT
    qryinspection.UnpairEquipment AS Equipment,
    Max(t.[Ending Date]) AS T1,
    Max(t.[Ending Date]) AS T2,
    Max(t.[Ending Date]) AS T3,
    Max(t.[Ending Date]) AS T4
FROM
    qryunpair AS qryinspection,
    tbldata AS t
GROUP BY qryinspection.UnpairEquipment;

It's almost what I'm trying to achieve, but it doesn't take into account the type, I get the same date for every equipments/type:
 Equipment   T1        T2             T3           T4
 402    2019-06-29  2019-06-29  2019-06-29  2019-06-29
 413    2019-12-12  2019-12-12  2019-12-12  2019-12-12
 420    2019-12-12  2019-12-12  2019-12-12  2019-12-12
 421    2019-09-01  2019-09-01  2019-09-01  2019-09-01
 428    2019-09-01  2019-09-01  2019-09-01  2019-09-01
 439    2019-07-30  2019-07-30  2019-07-30  2019-07-30
 446    2019-07-30  2019-07-30  2019-07-30  2019-07-30
 483    2019-06-29  2019-06-29  2019-06-29  2019-06-29

Is there a fix to this?

A: You can use conditional aggregation, e.g.:
select
    q.unpairequipment as Equipment,
    max(iif(t.type='T1',[ending date],null)) as T1,
    max(iif(t.type='T2',[ending date],null)) as T2,
    max(iif(t.type='T3',[ending date],null)) as T3,
    max(iif(t.type='T4',[ending date],null)) as T4
from
    qryunpair as q inner join tbldata as t on '-' + t.equipment + '-' like '*-' +  q.unpairequipment + '-*'
group by
    q.unpairequipment

The above is based on the answer provided by @forpas to your last question.


text:
Q: Linear regression package result vs econometric result mismatch x <- c(151, 174, 138, 186, 128, 136, 179, 163, 152, 131)
y <- c(63, 81, 56, 91, 47, 57, 76, 72, 62, 48)
relation <- lm(y~x)
print(relation)
beta=solve(t(x)%*%x)%*%(t(x)%*%y)
print(beta)

Result from lm coeff = 0.6746
Result from beta econometrics = 0.4287
Why?

A: The results differ because you didn't include the intercept:
lm(y ~ 0 + x)
##
## Call:
## lm(formula = y ~ 0 + x)
##
## Coefficients:
##      x
## 0.4287

or
X <- cbind(Intercept = 1, x)
solve(t(X) %*% X) %*% (t(X) %*% y)
##                  [,1]
## Intercept -38.4550871
## x           0.6746104

This has nothing to do with econometrics and I doubt any econometrics handbook or course recommends not including intercept as it is a bad practice.


text:
Q: Algorithm to figure out if a list of words form a word square Apparently this was a question that was asked to a friend of mine from Google. The question is, given four 4-lettered words, determine if they form a word square. Then, expand it so it can be solved for any n n-letter words. An example of a word square would be:
C A T S
A B E O
T E L M
S O M E

The quickest way we could think of was O(n!) for trying out all possible permutations of word configurations, then O(n) to check if it forms a word square, which can be done by checking if one side of the diagonals equals the other.

A: (This is an algorithm that you would then use to make a program. This would be very easy to make in a program, but obviously if a person was able to draw it out, he would be able to quickly see if it does. If you like, I could write you a java program that will do this.)

*

*I would make a 2D Array of the first letters of each word being in the first column, and the first row is made up of the first word.
C A T S
A B E O
T E L M
S O M E

*Then check to see if the first column equals the first word, the second column equals the second word, and so on. (Since the first row literally is the first word, checking to see if the first column equals the first word will basically check to see if the first row equals the first column.)

A: A somewhat simplistic approach would be to form a multiset of all the first letters of each word, and then search for a word that contain the exact same letters and letter counts as the multiset of first letters. If a match is found, we remove the word from consideration. Next, we look for a word whose suffix (beginning at the second letter) matches the multiset of second letters of remaining words. If a match is found, we remove it, and then check third letters, and so forth.
Here's a Python implementation that makes use of the collections.Counter class in place of a multiset.
from collections import Counter

def word_square(words):
    words = list(words)
    n = len(words)
    assert all(len(w) == n for w in words)

    result = []

    for i in range(n):
        letters = Counter(w[i] for w in words)
        match = next((w for w in words if Counter(w[i:]) == letters), None)

        if not match:
            return None

        words.remove(match)
        result.append(match)

    return result

This solution is, if I not mistaken, is O(n^3), which isn't great, but it's an improvement over O(n!).

A: This is the most efficient way I can think of:
const validWordSquare = (words) => {
  if(words.length > 0) {
    let firstRow = words[0]
    if(firstRow.length !== words.length) {
      return false
    }

    for(let i = 0; i < firstRow.length; i++) {
      let verticalWord = ''
      for(let j = 0; j < words.length; j++) {
        verticalWord += words[j][i]
      }
      if(verticalWord !== words[i]) {
        return false
      }
    }
    return true
  }
  return false
}

A: This looks like a matrix transpose question. So if the original matrix and its transpose are equal then it forms a word square,


text:
Q: Event Capturing in Jquery How do we do event capturing in Jquery. I know all about event bubbling and event capturing in JavaScript but interested to know if Jquery has something similar for event capturing. If not, then how can I extend Jquery code for this additional functionality. Please guide. Thanks in adv.

A: jQuery events works with event bubbling and it doesn't support capturing. So, there's no sense to stop event capturing.
See this and this for more information.

A:
I found the comment
  Event Capturing in Jquery
  upto my satisfaction. Hence closing this question.


text:
Q: Print primes starting from 2 to the entered number and avoid the "n/2" logic I am a little bit confused. I want to print all the prime starting from 2 to the entered number in java using while loop and don't want to use n/2 logic.
I don't know what is wrong with my code. Please help me.
HERE IS THE CODE :-
import java.util.Scanner;
public class print_primes {
  public static void main(String[] args) {
  // TODO Auto-generated method stub
    Scanner scn = new Scanner(System.in);

    int n = scn.nextInt();
    int rem = 0;
    int i = 2;
    int flag = 0;
    int start = 3;
    System.out.println("2");
    while (start <= n) {
      i = 2;
      while (i <= start - 1) {
        rem = start % i;
        if (rem == 0) {
          flag = 1;
        }
        i = i + 1;
     }
     if (flag == 0) {
       System.out.println(start);
     }
     start++;
   }
 }
}

A: A much more simpler approach :
public class Test {

   // method to check if each number is prime
   public static boolean isPrime(int x) {
      for (int i = 2; i < x; i++)
         if (x % i == 0) {
            return false;
         }
      return true;
   }

   public static void main(String[] args) {
      Scanner scanner = new Scanner(System.in);

      System.out.println("Enter a number");
      int num = scanner.nextInt();

      // print out 2 as we wont be checking even numbers.
      System.out.println(2);

      // iterate till user input
      for (int i = 3; i < num; i = i + 2) {
        if (isPrime(i)) {
          System.out.println(i);
        }
      }
   }
}


text:
Q: How to prevent PWA from opening links and Auth0 single sign in authentication in new Safari Window I have an issue, I've created an angular PWA and my app uses auth0-lock as its authentication now my problem is.. when you click one of the single sign-in options like Google, for example, you get taken out of the PWA and into safari, Is there any way I can prevent this??
I have tried putting this code in my index.html
<!-- Prevent app from opening new safari page -->
<script type="text/javascript">
    (function(document,navigator,standalone) {
        // prevents links from apps from oppening in mobile safari
        // this javascript must be the first script in your <head>
        if ((standalone in navigator) && navigator[standalone]) {
            var curnode, location=document.location, stop=/^(a|html)$/i;
            document.addEventListener('click', function(e) {
                curnode=e.target;
                while (!(stop).test(curnode.nodeName)) {
                    curnode=curnode.parentNode;
                }
                // Condidions to do this only on links to your own app
                // if you want all links, use if('href' in curnode) instead.
                if('href' in curnode && ( curnode.href.indexOf('http') || ~curnode.href.indexOf(location.host) ) ) {
                    e.preventDefault();
                    location.href = curnode.href;
                }
            },false);
        }
    })(document,window.navigator,'standalone');
</script>

but that doesn't seem to be working, I have seen some other javascript hacks that can prevent this and I have still yet to find one that works in my angular application?
Does anyone have any experience with this??
Thanks

A: It's not particular to Angular but to PWA. Apple changed behaviour in iOS 11.3 following new PWA manifest rules.
The issue is known and Apple will be working on it.
Unfortunately, it means that there is not much to do in PWA for iOS 11.3…


text:
Q: Running guard init duplicates watcher lines I'm not sure how I've ended up here, but anytime I run guard init, it seems to go a bit overboard, and rather than adding coffeescript/sass/livereload once, it does each of them several times.
Here is what I get on the command line after running guard init:
WARN: Unresolved specs during Gem::Specification.reset:
      thor (>= 0.14.6)
      lumberjack (>= 1.0.2)
      ffi (>= 0.5.0)
WARN: Clearing out unresolved specs.
Please report a bug if this causes problems.
11:39:55 - INFO - Writing new Guardfile to /var/www/the-newbies-guide-to-test-driven-development/Guardfile
11:39:55 - INFO - coffeescript guard added to Guardfile, feel free to edit it
11:39:55 - INFO - coffeescript guard added to Guardfile, feel free to edit it
11:39:55 - INFO - coffeescript guard added to Guardfile, feel free to edit it
11:39:57 - INFO - compass guard added to Guardfile, feel free to edit it
11:39:57 - INFO - concat guard added to Guardfile, feel free to edit it
11:39:58 - INFO - livereload guard added to Guardfile, feel free to edit it
11:39:58 - INFO - livereload guard added to Guardfile, feel free to edit it
11:39:58 - INFO - There are 2 definitions in your Guardfile for 'livereload', you may want to clean up your Guardfile as this could cause issues.
11:39:58 - INFO - livereload guard added to Guardfile, feel free to edit it
11:39:58 - INFO - There are 3 definitions in your Guardfile for 'livereload', you may want to clean up your Guardfile as this could cause issues.
11:39:58 - INFO - phpunit guard added to Guardfile, feel free to edit it
11:39:58 - INFO - sass guard added to Guardfile, feel free to edit it
11:39:58 - INFO - sass guard added to Guardfile, feel free to edit it
11:39:58 - INFO - sass guard added to Guardfile, feel free to edit it
11:39:58 - INFO - sass guard added to Guardfile, feel free to edit it
11:39:58 - INFO - sass guard added to Guardfile, feel free to edit it
11:39:58 - INFO - uglify guard added to Guardfile, feel free to edit it

With this being the contents of my Guardfile:
# A sample Guardfile
# More info at https://github.com/guard/guard#readme

guard 'coffeescript', :input => 'app/assets/javascripts'

guard 'coffeescript', :input => 'app/assets/javascripts'

guard 'coffeescript', :input => 'app/assets/javascripts'

guard 'compass' do
  watch('^src/(.*)\.s[ac]ss')
end

# This will concatenate the javascript files specified in :files to public/js/all.js
guard :concat, type: "js", files: %w(), input_dir: "public/js", output: "public/js/all"

guard :concat, type: "css", files: %w(), input_dir: "public/css", output: "public/css/all"

guard 'livereload' do
  watch(%r{app/views/.+\.(erb|haml|slim)$})
  watch(%r{app/helpers/.+\.rb})
  watch(%r{public/.+\.(css|js|html)})
  watch(%r{config/locales/.+\.yml})
  # Rails Assets Pipeline
  watch(%r{(app|vendor)(/assets/\w+/(.+\.(css|js|html))).*}) { |m| "/assets/#{m[3]}" }
end

guard 'livereload' do
  watch(%r{app/views/.+\.(erb|haml|slim)$})
  watch(%r{app/helpers/.+\.rb})
  watch(%r{public/.+\.(css|js|html)})
  watch(%r{config/locales/.+\.yml})
  # Rails Assets Pipeline
  watch(%r{(app|vendor)(/assets/\w+/(.+\.(css|js|html))).*}) { |m| "/assets/#{m[3]}" }
end

guard 'livereload' do
  watch(%r{app/views/.+\.(erb|haml|slim)$})
  watch(%r{app/helpers/.+\.rb})
  watch(%r{public/.+\.(css|js|html)})
  watch(%r{config/locales/.+\.yml})
  # Rails Assets Pipeline
  watch(%r{(app|vendor)(/assets/\w+/(.+\.(css|js|html))).*}) { |m| "/assets/#{m[3]}" }
end

guard 'phpunit', :cli => '--colors' do
  watch(%r{^.+Test\.php$})
end

guard 'sass', :input => 'sass', :output => 'css'

guard 'sass', :input => 'sass', :output => 'css'

guard 'sass', :input => 'sass', :output => 'css'

guard 'sass', :input => 'sass', :output => 'css'

guard 'sass', :input => 'sass', :output => 'css'

guard 'uglify', :destination_file => "public/javascripts/application.js" do
  watch (%r{app/assets/javascripts/application.js})
end

Obviously I can just go in and remove the duplicated lines, but I was wondering why it happened in the first place.

A: It looks like guard will use all available versions of a plugin when running the init - not sure if it does this when actually running too (which would be worrying). I was having the same trouble and checked my gem list:
gem list | grep guard

This showed me how many versions of guard related plugins I had installed:
guard (1.8.2, 1.8.0, 1.7.0, 1.6.2, 1.6.1, 1.5.4, 1.0.3, 1.0.1)
guard-concat (0.0.3)
guard-rspec (3.0.0, 2.5.3, 2.4.1, 2.3.3, 2.1.2, 1.2.1, 0.7.2, 0.7.0)
guard-sass (1.3.2)
guard-spork (0.8.0)
guard-uglify (0.1.0)
terminal-notifier-guard (1.5.3)

Running gem cleanup on the guard plugin that gets repeated sorted it all out:
gem cleanup guard-rspec

gem list | grep guard

Which then showed:
guard (1.8.2, 1.8.0, 1.7.0, 1.6.2, 1.6.1, 1.5.4, 1.0.3, 1.0.1)
guard-concat (0.0.3)
guard-rspec (3.0.0)
guard-sass (1.3.2)
guard-spork (0.8.0)
guard-uglify (0.1.0)
terminal-notifier-guard (1.5.3)

When I run guard init now I do not have repeated code in my Guardfile.


text:
Q: Attach a tmux session to a remote machine I am using tmux on my local machine and usually have several sessions simultaneously.
What I usually do is I have a session with different windows to work locally and the other sessions in which I connect several windows to one host per session.
A session / window tree would look like this in the daily use I make of tmux:
(TMUX on my local machine)
 |
 +- session 1: local
 |  \_ window 1: local shell
 |  \_ window 2: local shell
 |  \_ ...
 |
 + session 2: somehost
 |  \_ window1: ssh user@somehost
 |  \_ window2: ssh user@somehost
 |  \_ ...
 |
 + session 3: someotherhost
    \_ window1: ssh user@someotherhost
    \_ window2: ssh user@someotherhost
    \_ ...

Is there a way to make session 2 & session 3 some sort of remote sessions connecting to a tmux session created on somehost & someotherhost?
The above tree would look like this:
(TMUX on my local machine)
 |
 +- session 1: local
 |  \_ window 1: local shell
 |  \_ window 2: local shell
 |  \_ ...
 |
 + session 2 linked to an existing session on somehost
 |  \_ window1: shell on somehost
 |  \_ window2: shell on somehost
 |  \_ ...
 |
 + session 3 linked to an existing session on someotherhost
    \_ window1: shell on someotherhost
    \_ window2: shell on someotherhost
    \_ ...

I found this topic but I am not sure this is what I want to do: Is sharing a tmux sockets between hosts possible?
I suppose what I am looking for would require me to have the same tmux configuration on my local machine, somehost & someotherhost but that would not be a problem.

A: If your main problem is that you have to type ssh remotehost everytime you open new window, the default-command session option may be a workaround.
It automatically execute the command you specify when you open new windows in the sessions you set it to.
A simple setting in .tmux.conf:
bind-key C-r new-session ssh remotehost \; set-option default-command "ssh remotehost"
This key binding Ctrl-r creates a new session where every newly opened window firstly execute ssh remotehost on behalf of you.
You can choose hosts to connnect at session creation time with the settings below:
bind-key C-r command-prompt "new-session -s %1 ssh %1 \; set-option default-command \"ssh %1\""

This one asks you the host you want to do ssh at each session creation (not at each window creation) and starts the session dedicated to that host.
It takes little time to execute many ssh if you enable SSH multiplexing in your ssh config.
The .ssh/config example is below:
Host remotehost
    ControlMaster auto
    ControlPath ~/.ssh/mux-%r@%h:%p
    ControlPersist 10

Note that this tmux setting does not create tmux sessions in remote hosts. If ssh connection is lost, affected tmux windows never return.

A: You can pass a command to ssh when connecting to a remote host. Include the -t option with tmux attach-session to connect to the remote tmux session:
ssh <remote host> -t tmux attach-session

This post on attaching to a tmux session via ssh explains it in more detail.

A: You could use a tool like socat to tunnel the unix domain socket used by tmux to your local machine. But you are really just swapping a tunnel (ssh) for another (socat) so it is not really better, and also insecure.

A: If you talking about remote shell, you mean that you can execute commands there, in other words, you have direct access. In this case you can simply use ssh connection for each remote window.
You can tell there something like:
"Hey, but there are no way to have multiple windows for each remote server!"
and it is true, due to ssh restrictions. But, you can start tmux session on each or your remote server. NOTE: in this case you need to rebind default Ctrl+b on local machine to prevent collisions.
Also I recomend you to use tmuxinator, it is very helpful tool if you rectreate your tmux session at least every day.


text:
Q: Linq - pulling data from two tables - efficiency - alternative linq queries I have two tables as part of a messaging system:
RECIPIENTS
RecipientId (PK)
RecipientMemberId (FK to user table)
MessageId (FK to message table)
...

MESSAGES
MessageId (PK)
...

and these two linq queries:
IEnumerable<int> myMessageIds = recipientRepository.Recipients.Where(x => x.RecipientMemberId == User.Identity.GetUserId()).Select(x => x.MessageId);

IEnumerable<Message> inboxMessages = messageRepository.Messages.Where(x => myMessageIds.Contains(x.MessageId));

which pull out a user's messages for their inbox.
THE QUESTION:
This works but I have a nasty feeling I'm doing it wrong. Is this inefficient? For fun, what are some alternative linq queries that would produce the same result more efficiently? Any other comments also appreciated.
Thank you.

A: There is nothing wrong in what you are doing. As long as you are querying a table using a primary key, an index or a foreign key it is perfectly optimized by the RDMS.
In your case:
IEnumerable<int> myMessageIds
      = recipientRepository.Recipients
        .Where(x => x.RecipientMemberId == User.Identity.GetUserId())
        .Select(x => x.MessageId);

you are using the RecipientMemberId which is a foreign key. You can rewrite the same query as follow if you want, using linq instead of lambda expressions:
var myMessageIds = from recipient in recipientRepository.Recipients
                  let userId = User.Identity.GetUserId() // done only once
                  where recipient.RecipientMemberId == userId
                  select recipient.MessageId;

Same thing for your second query:
var inboxMessages = from message in messageRepository.Messages
                  where myMessageIds.Contains(message.MessageId)
                  select message;

A: var userId = User.Identity.GetUserID();

IEnumerable<Message> inboxMessages = Context
       .Messages
       .Where(x => Context.Recipients
                          .Where(r => r.RecipientMemberId == userId)
                          .Any(r => x.MessageId == r.MessageId));

But Even more so, you should have Navigation Properties on Recipient and Message.
public class Recipient
{
    .....
    [Key]
    public int Id { get; set; } // If this is your PK

    public virtual ICollection<Message> Messages { get; set; } // navigational Property to Messages
}

and your Message:
public class Message
{
    .....
    [Key]
    public int Id { get; set; } // If this is your PK

    public int RecipientId { get; set; } // This would be FK
    public virtual Recipient Recipient { get; set; } // navigational property back to Recipient
}

Then you can do something like:
var recipient = Context.Recipients
                       .Where(x => x.RecipientMemberId == userId)
                       .FirstOrDefault()

var messages = recipient.Messages.ToList();

Note, this will make 2 calls to the database, one when you get the recipient. And another when you access the virtual messages property.
To optimize this, you can tell EF to "Include"  a navigational property in its query, which will then do a join.
E.g.
var recipient = Context.Recipients
                       .Include(x => x.Messages)
                       .Where(x => x.RecipientMemberId == userId)
                       .FirstOrDefault()

A: You can often access related data via a navigation property. If you created your tables via code first they would look something like this :
public class Recipient
{
     public int RecipientId { get; set; }
     public virtual Icollection<Message> Messages { get; set; }
     // etc
}

 public class Message
 {
     public int MessageId { get; set; }
     public virtual Recipient Recipient { get; set; }
     // etc
}

Similar properties would be generated by an edmx or dbml file.
IEnumerable<Message> myMessages = recipientRepository.Recipients.Where(x => x.RecipientMemberId == User.Identity.GetUserId()).SingleOrDefault().Messages;


text:
Q: How to get a customer's email address and transaction subject from the Authorize.net "unsettled transactions" API? I am using the Authorize.net API for PHP with the help of some of the online examples to iterate through all the transactions of today (or last 24 hours). So far I'm only able to obtain the submit time and the transaction amount (aka settle amount). How can I get the email of the customer as well as the transaction subject/description?
Inside the loop where the two spots are marked "/*  HERE */" I've tried several ways with no luck. What is the correct syntax?
require 'autoload.php';
require_once 'SampleCodeConstants.php';
use net\authorize\api\contract\v1 as AnetAPI;
use net\authorize\api\controller as AnetController;

/* Create a merchantAuthenticationType object with authentication details
retrieved from the constants file */
$merchantAuthentication = new AnetAPI\MerchantAuthenticationType();
$merchantAuthentication->setName(\SampleCodeConstants::MERCHANT_LOGIN_ID);
$merchantAuthentication->setTransactionKey(\SampleCodeConstants::MERCHANT_TRANSACTION_KEY);

// Set the transaction's refId
$refId = 'ref' . time();

$request = new AnetAPI\GetUnsettledTransactionListRequest();
$request->setMerchantAuthentication($merchantAuthentication);

$controller = new AnetController\GetUnsettledTransactionListController($request);
$response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::PRODUCTION);

if (($response != null) && ($response->getMessages()->getResultCode() == 'Ok')) {
    if (null != $response->getTransactions()) {
        foreach($response->getTransactions() as $tx) {
            echo 'SUCCESS: TransactionID: ' . $tx->getTransId() . "\n";

            $request = new AnetAPI\GetTransactionDetailsRequest();
            $request->setMerchantAuthentication($merchantAuthentication);
            $request->setTransId($tx->getTransId());

            $controller = new AnetController\GetTransactionDetailsController($request);
            $response = $controller->executeWithApiResponse( \net\authorize\api\constants\ANetEnvironment::PRODUCTION);

            echo "Submitted on (Local): " . date_format($tx->getSubmitTimeLocal(), 'Y-m-d H:i:s') . "\n";
            echo "Settle amount: " . number_format($tx->getSettleAmount(), 2, '.', '') . "\n";
            echo "Email: " . /* HERE */ . "\n";
            echo "Transaction subject: " . /* HERE */ . "\n";
        }
    } else {
        echo 'No unsettled transactions for the merchant.' . "\n";
    }
} else {
    echo 'ERROR :  Invalid response' . "\n";
    $errorMessages = $response->getMessages()->getMessage();
    echo 'Response : ' . $errorMessages[0]->getCode() . ' ' .$errorMessages[0]->getText() . "\n";
}

return $response;

A: getUnsettledTransactionListRequest does not return customer email nor order description, you can obtain these fields (for a given transaction), if you call getTransactionDetailsRequest, you can add the following to your getTransactiondetails script to get email/description:

*

*$response->getTransaction()->getCustomer()->getEmail()

*$response->getTransaction()->getOrder()->getDescription()


text:
Q: Combing two objects of class ranger in R for survival analysis I am working on the R package ranger which is an implementation of random forest ensemble. I want to grow several sub forests and then combine them as one object to use for predicting new data. There is a combine() function within the randomForest R package but I want to do this for the ranger R package.
An example of two sub forests could be
require(survival)
require(ranger)
rf1 <- ranger(Surv(time, status) ~ ., data = veteran,num.tree=10)
rf2 <- ranger(Surv(time, status) ~ ., data = veteran,num.tree=10)

rf <- a function to combine rf1 and rf2.

I need such a function. Can anybody help?