text:
Q: How can I teleport players to start if they touch these blocks? I'm making a flying map where players are not allowed to touch grass, quartz, or leaves. If they do, I need them to be teleported to the start. How can I do that? By the way, this is 15w47c map.

A: Try this:
execute @a ~ ~ ~ detect ~ ~-1 ~ minecraft:grass -1 tp @a[c=1] <x> <y> <z>

That checks if the player is on top of a grass block. Just change the relative coordinates (the ~ ~-1 ~) in order to check above, right, etc. And, obviously, change minecraft:grass to whatever block you want to check. If you have issues with the relative coords, check them out here.

A: The OnGround byte tag specifies whether or not the player is on the ground. You can assign a score based on its value and target the player based on that score:
/scoreboard objectives add OnGround dummy

/scoreboard players set @a OnGround 1 {OnGround:1b}
/scoreboard players set @a OnGround 0 {OnGround:0b}

/tp @a[score_OnGround_min=1] X Y Z

Another method is to detect whether there is air at the player's current feet position, but keep in mind that this method is flawed when it comes to players standing on non-full blocks such as slabs:
/scoreboard players set @a OnGround 1
/execute @a ~ ~ ~ detect ~ ~ ~ minecraft:air 0 scoreboard players set @a[c=1] OnGround 0

For 15w47c+, you can use the "tags" feature to avoid having to use scoreboard objectives:
/scoreboard players tag @a[tag=!OnGround] add OnGround {OnGround:1b}
/scoreboard players tag @a[tag=OnGround] remove OnGround {OnGround:0b}

/tp @a[tag=OnGround] X Y Z


text:
Q: How "ping" an interface without IP address? I need to check if an ethernet interface is "up and running" even if it doesn't have an IP address associated and ARP is not supported. I know only its MAC address: do you have an idea on how to "ping" this interface?
I was thinking to perform this ping by sending something based on "Ethertype" values: I don't know what I could obtain if I send a no-supported Ethertype value to Linux.
It is only an idea, probably not the best one.
Any suggestion?

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# MVC Route to different Controller map I have 2 routes.
1e route for normal pages. 2e route for my json response controller (api with session auth)
public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "myApi",
            url: "myApi/{controller}/{action}/{id}",
            defaults: new { Controller = "AddressController", id = UrlParameter.Optional },
            new[] { "myfactory_WebPortal.ControllersApi" } <-- different namespace/folder
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
            new[] { "myfactory_WebPortal.Controllers" }  <-- different namespace/folder
        );
    }

The 'default' route is just default. The 'myApi' should point to a different folder/namespace with its own controllers and a different url starting with 'myapi/...'
Sadly all my routes work on both routes.
HomeController in 'controllers' namespace/folder works both on url 'myapi/home/contact' and '/home/contact'
Same for my controller AddressController in 'controllersApi' namespace/folder works both on url 'myapi/adress/search' and 'address/search'.

What should I do to separate these routes/controller to work properly.


text:
Q: Only able to get Combobox selectedValue when down key is pressed I have made a WPF Autocomplete Combobox, and the problem which i am facing is that i am only able to get SelectedValue of ComboBox when i press Down Key.
Problem is in below BindComboBox Method, and comboBox5.SelectedValue only works when down Key is pressd.
 public void BindComboBox3(ComboBox comboBox3) //BatchCombobox
    {
        SqlDataAdapter da = new SqlDataAdapter("Select id,batch_id FROM batch where product_id_fk='" + Convert.ToInt32(comboBox5.SelectedValue) + "' and left_qty>0", con);
        DataSet ds = new DataSet();
        da.Fill(ds, "batch");
        comboBox3.ItemsSource = ds.Tables[0].DefaultView;
        comboBox3.DisplayMemberPath = ds.Tables[0].Columns["batch_id"].ToString();
        comboBox3.SelectedValuePath = ds.Tables[0].Columns["id"].ToString();
    }

But in Below code comboBox5.SelectedValue is properly Working.
private void comboBox5_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        comboBox3.IsEnabled = true;
        BindComboBox3(comboBox3); //Problem is in this Function

        con.Open();
        SqlCommand cmd1 = new SqlCommand("SELECT med_type,fk_com_id FROM products where p_id_pk='" + Convert.ToInt32(comboBox5.SelectedValue) + "'", con);

        SqlDataReader med_oftype = null;

        med_oftype = cmd1.ExecuteReader();

        while (med_oftype.Read())
        {
            get_med_type = med_oftype["med_type"].ToString();
            cmpny_id = Convert.ToInt32(med_oftype["fk_com_id"]);
        }

        con.Close();

    }

private void ProductsComboBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        if (((ComboBox)sender).Text != "")
        {
            SqlDataAdapter da = new SqlDataAdapter("Select p_id_pk,p_name FROM products", con);
            DataSet ds = new DataSet();
            da.Fill(ds, "products");
            comboBox5.ItemsSource = ds.Tables[0].DefaultView.RowFilter = "p_name like '" + ((ComboBox)sender).Text + "'+'%'";
            comboBox5.ItemsSource = ds.Tables[0].DefaultView;
            comboBox5.DisplayMemberPath = ds.Tables[0].Columns["p_name"].ToString();
            comboBox5.SelectedValuePath = ds.Tables[0].Columns["p_id_pk"].ToString();
        }
        else
        {
            comboBox5.ItemsSource = null;
        }
    }

Summary is that in one event handler comboBox5.SelectedValue is working and in other comboBox5.SelectedValue is not working. Dont know what is causing this problem.

A: *

*if you can share your .xaml code this would be helpful

*also if you can clarify why you send (comboBox3) as a parameter
although it is accessible any where in the view

*as a quick solution you can pass SelectedValue as a parameter to
BindComboBox3 method


text:
Q: Upgrade Angular 12 to 13 - Compile error in mjs file We are trying to upgrade our angular from 12 to 13 with node 14.15.0 and facing the below error while giving npm start
ERROR in ./node_modules/@angular/platform-browser-dynamic/fesm2015/platform-browser-dynamic.mjs
Module not found: Error: Can't resolve '@angular/common' in '..\node_modules\@angular\platform-browser-dynamic\fesm2015'

ERROR in ./node_modules/@angular/platform-browser/fesm2015/platform-browser.mjs
Module not found: Error: Can't resolve '@angular/common' in '..\node_modules\@angular\platform-browser\fesm2015'

ERROR in ./node_modules/@angular/router/fesm2015/router.mjs
Module not found: Error: Can't resolve '@angular/common' in '..\@angular\router\fesm2015'

ERROR in ./node_modules/@angular/platform-browser-dynamic/fesm2015/platform-browser-dynamic.mjs
Module not found: Error: Can't resolve '@angular/compiler' in '..\node_modules\@angular\platform-browser-dynamic\fesm2015'

ERROR in ./node_modules/@angular/common/fesm2015/common.mjs
Module not found: Error: Can't resolve '@angular/core' in '..\node_modules\@angular\common\fesm2015'

ERROR in ./node_modules/@angular/platform-browser-dynamic/fesm2015/platform-browser-dynamic.mjs
Module not found: Error: Can't resolve '@angular/core' in '..\node_modules\@angular\platform-browser-dynamic\fesm2015'

ERROR in ./node_modules/@angular/platform-browser/fesm2015/platform-browser.mjs
Module not found: Error: Can't resolve '@angular/core' in '..\node_modules\@angular\platform-browser\fesm2015'
ERROR in ./node_modules/@angular/router/fesm2015/router.mjs

Module not found: Error: Can't resolve '@angular/core' in '..\node_modules\@angular\router\fesm2015'

ERROR in ./node_modules/@angular/platform-browser-dynamic/fesm2015/platform-browser-dynamic.mjs
Module not found: Error: Can't resolve '@angular/platform-browser' in '..\node_modules\@angular\platform-browser-dynamic\fesm2015'

i 「wdm」: Failed to compile.

Package.json
"dependencies": {
    "@angular/animations": "^13.2.3",
    "@angular/cdk": "^13.2.3",
    "@angular/common": "^13.2.3",
    "@angular/compiler": "^13.2.3",
    "@angular/core": "^13.2.3",
    "@angular/forms": "^13.2.3",
    "@angular/http": "^7.2.15",
    "@angular/material": "^13.2.3",
    "@angular/platform-browser": "^13.2.3",
    "@angular/platform-browser-dynamic": "^13.2.3",
    "@angular/platform-server": "^13.2.3",
    "@angular/router": "^13.2.3",
    "@aspnet/signalr": "^1.1.4",
    "@juggle/resize-observer": "^3.2.0",
    "@ng-bootstrap/ng-bootstrap": "^10.0.0",
    "@progress/kendo-angular-buttons": "^5.0.1",
    "@progress/kendo-angular-charts": "^4.1.2",
    "@progress/kendo-angular-common": "^1.2.1",
    "@progress/kendo-angular-dateinputs": "^4.2.0",
    "@progress/kendo-angular-dropdowns": "^4.2.3",
    "@progress/kendo-angular-excel-export": "^3.0.1",
    "@progress/kendo-angular-grid": "^4.5.0",
    "@progress/kendo-angular-inputs": "^6.3.1",
    "@progress/kendo-angular-l10n": "^2.0.0",
    "@progress/kendo-angular-pdf-export": "^2.0.0",
    "@progress/kendo-angular-popup": "^3.0.4",
    "@progress/kendo-drawing": "^1.6.0",
    "@progress/kendo-file-saver": "^1.0.7",
    "@progress/kendo-theme-default": "^4.9.0",
    "applicationinsights-js": "^1.0.20",
    "bootstrap": "^5.1.2",
    "core-js": "^3.21.1",
    "expose-loader": "^0.7.5",
    "hammerjs": "^2.0.8",
    "jquery": "^3.6.0",
    "mat-currency-format": "0.0.7",
    "moment": "^2.24.0",
    "moment-timezone": "^0.5.27",
    "ngx-bootstrap": "^5.6.2",
    "ngx-perfect-scrollbar": "^8.0.0",
    "ngx-restangular": "^5.0.0",
    "ngx-swiper-wrapper": "^8.0.2",
    "regenerator-runtime": "^0.13.3",
    "rxjs": "^7.5.4",
    "rxjs-compat": "^6.5.3",
    "sass": "^1.45.2",
    "zone.js": "^0.11.4"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^13.2.4",
    "@angular/cli": "^13.2.4",
    "@angular/compiler-cli": "^13.2.3",
    "@angular/language-service": "^13.2.3",
    "@ngtools/webpack": "^8.3.20",
    "@progress/kendo-angular-intl": "^2.0.0",
    "@progress/kendo-data-query": "^1.5.2",
    "@types/angular": "^1.6.57",
    "@types/angular-animate": "^1.5.10",
    "@types/angular-mocks": "^1.7.0",
    "@types/angular-resource": "^1.5.15",
    "@types/angular-route": "^1.7.0",
    "@types/angular-sanitize": "^1.7.0",
    "@types/applicationinsights-js": "^1.0.9",
    "@types/google.analytics": "^0.0.40",
    "@types/jasmine": "^3.10.3",
    "@types/jquery": "^3.3.31",
    "@types/lodash": "^4.14.149",
    "@types/moment": "^2.13.0",
    "@types/moment-timezone": "^0.5.12",
    "@types/node": "^17.0.18",
    "@types/webpack-env": "^1.14.1",
    "angular-router-loader": "^0.8.5",
    "angular2-template-loader": "^0.6.2",
    "canonical-path": "^1.0.0",
    "codelyzer": "^6.0.2",
    "concurrently": "^5.0.1",
    "copy-webpack-plugin": "^5.1.0",
    "css-loader": "^3.3.0",
    "extract-text-webpack-plugin": "^4.0.0-beta.0",
    "file-loader": "^5.0.2",
    "file-saver": "^2.0.2",
    "gsap": "^3.7.1",
    "html-loader": "^0.5.5",
    "html-webpack-plugin": "^3.2.0",
    "http-server": "^0.12.0",
    "install": "^0.13.0",
    "jasmine-core": "^4.0.0",
    "jasmine-spec-reporter": "^7.0.0",
    "karma": "^6.3.16",
    "karma-chrome-launcher": "^3.1.0",
    "karma-cli": "^2.0.0",
    "karma-jasmine": "^4.0.1",
    "karma-jasmine-html-reporter": "^1.7.0",
    "lodash": "^4.17.21",
    "ng2-odometer": "^1.1.3",
    "ngx-countdown": "^8.0.3",
    "ngx-modialog": "^5.0.1",
    "null-loader": "^3.0.0",
    "protractor": "^7.0.0",
    "raw-loader": "^4.0.0",
    "rimraf": "^3.0.0",
    "rollup": "^1.27.11",
    "rollup-plugin-commonjs": "^10.1.0",
    "rollup-plugin-node-resolve": "^5.2.0",
    "rollup-plugin-uglify": "^6.0.4",
    "rxjs-tslint": "^0.1.8",
    "sass-loader": "^8.0.0",
    "style-loader": "^1.0.1",
    "terser-webpack-plugin": "^2.3.0",
    "to-string-loader": "^1.1.6",
    "ts-loader": "^6.2.1",
    "ts-node": "~8.5.4",
    "tslint": "^6.1.3",
    "typescript": "^4.4",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.9.0",
    "webpack-merge": "^4.2.2",
    "xlsx": "^0.17.2"
  }
}

Please someone suggest me.

A: Also in angular 12, the path mentioned in the above error had js file but after upgrading to 13, it is coming as mjs file

A: This is probably due to custom webpack config .
Please attach the code related to your custom webpack config in here . One of the ways to fix this can be to add your mjs rule to your custom config .
    {
      test: /\.mjs$/,
      include: /node_modules/,
      type: "javascript/auto"
    }

If that does not work , you may have to make appropriate changes to upgrade the webpack libraries to a higher version (webpack 5).

A: Previously, I was also facing multiple dependency conflicts while updating Angular version from 11 to 14. I even tried deleting package lock, but there were still conflicting dependencies. I also used npm i with --force and --legacy-peer-deps, but nothing worked.
In the end, I followed these steps below and it finally worked.

*

*Make a list of all of the additional libraries that you have added, and remove these from your package.json file.

*Delete your package-lock.json and do npm i one more time.

*Now, run the following command to update Angular:
ng update @angular/cli@^<major_version> @angular/core@^<major_version>

*Once done, install the additional dependencies that you have added one-by-one and only install the latest version.

*You might need to update your TypeScript version too.
Now, I don't know if this is the best way or not, but only this approach worked for me.

A: Does it need to be Node v14? I upgraded from Angular 12 to Angular 13 while also updating Node to v16. Worked for me

A: This could be a nodejs issue, you probably need to add an entry
"type": "module" in your package.json file
check this thread for details:
https://github.com/angular/angular-cli/issues/20785

A: I'd suggest to have a clean install of the packages without package-lock.json present in your folder.
angular-cli has as well some folder linking with your global packages, so I'm assuming as well that your global @angular/angular-cli is corrupted.
From my understanding, when you attempt to run your Angular project for the first time after installation, there's will be a compilation process of the Angular libraries and for some reason, your packages fail to exist or have a correct build

A: Try replacing package-lock.json complete content with empty {} along with deleting node_module.


text:
Q: Python pyinstaller onefile executable problem with image I have created an .exe with some tabs, plots, input and outputs.
It compiles perfectly in pycharm with pyinstaller and the command: pyinstaller -w -F -file_name.py and it works in every windows computer.
The problem started when I tried to insert an image in the program and add an icon through the pyinstaller command -i \path.
In both cases the executable doesn't run and returns an error.
I think the problem could be in the way I refer to the path of the image and icon file; is there a proper way to do it?
Sorry if the question may sound basic but I just started programming and except from some matlab knowledge this is completely new for me.


text:
Q: Link stays on its hover property when target="_blank" Whenever I set a link to open up into a new window and return to the previous one the hover properties set for it stick but when I mouse back in to the window it changes back to normal. How can I fix this without using Javascript?
HTML:
Google

CSS:
a:link, a:visited, a:active {color: blue;}

a:hover {color: red;}

JSFiddle
http://jsfiddle.net/5EXFB/

A: I had a similar issue with a link styled as a button that was keeping its hover font color when the click action was to open a new window. The issue is that the link retains focus (which holds the hover style) until you click on something else, which is apparently an accessibility thing. The workaround I came up with is to add a :focus style and a :focus:hover style to mimic the regular a and a:hover styles.
a, a:focus { color: blue }
a:hover, a:focus:hover { color: white }

A: Update: It doesn't look like there is a way to do it in Chrome.  Even setting focus to another element behind the scenes doesn't

<input type='text'>Click this: </input>
yahoo

Update: My code below doesn't work in IE or Chrome. In IE, when you switch back to the window, the active focus is already gone and in Chrome the mouseover definitely removes the active focus.  In fact, I think the active focus is already gone once the target window opens, it is just that IE repaints immediately and Chrome repaints later.
=======================
Move the :active to be the same as the :hover:
a:link, a:visited, {color: blue;}

a:hover, a:active {color: red;}

That should work in the situation you describe which is to mouseover the window again.  If, however, you click in the window, the link will no longer be the active element, so the style will be lost as well.

A: I had the same problem. :visited worked for me while :focus did not. With visited, it selects the link that has already been visited by the current browser. Focus is for those who used keyboard navigation to get to the link. :focus will select links that are the current focus of the keyboard.
&:visited { color: $color--tory-blue;
background-color: $color--white;}

&:hover{color: $color--white;
background-color: $color--tory-blue;}


text:
Q: bootstrap.css doesn't show up in the browser I am setting up a project with angular 2 and gulp using this tutorial. http://blog.codeleak.pl/2016/03/quickstart-angular2-with-typescript-and.html
The only change I made is I added bootstrap to the package.json, but it doesn't show in the browser. It shows in the node_modules and the lib folder in my project in the IDE. But the bootstrap classes don't get applied if I use them. The bootstrap.min.css file doesn't show in the browser either.
I added the 2 lines about bootstrap to my gulp file
gulp.task("libs", () => {
    return gulp.src([
        'es6-shim/es6-shim.min.js',
        'systemjs/dist/system-polyfills.js',
        'systemjs/dist/system.src.js',
        'reflect-metadata/Reflect.js',
        'rxjs/**',
        'zone.js/dist/**',
        '@angular/**',
        'bootstrap/dist/js/bootstrap.min.js',
        'bootstrap/dist/css/bootstrap.min.css'
    ], {cwd: "node_modules/**"}) /* Glob required here. */
    .pipe(gulp.dest("build/lib"));
});

I added this line in index.html to include it
 <link rel="stylesheet" type="text/css" src="lib/bootstrap/dist/css/bootstrap.min.css">

Here is my project structure

EDIT: Just to clarify, I see the bootstrap.css files copied over in the lib folder in the IDE, but I don't see it in the browser. See screenshot below from Chrome dev tools

Any clue as to what I may be missing? Github repo - https://github.com/richa008/Angular-starter-app-with-gulp

A: This should import all relevant files and directories:
    gulp.task("libs", () => {
        return gulp.src([
            'es6-shim/es6-shim.min.js',
            'systemjs/dist/system-polyfills.js',
            'systemjs/dist/system.src.js',
            'reflect-metadata/Reflect.js',
            'rxjs/**',
            'zone.js/dist/**',
            '@angular/**',
            'bootstrap/dist/**/*.+(js|css.map|css|eot|svg|ttf|woff|woff2)'

        ], { cwd: "node_modules/**" }) /* Glob required here. */
            .pipe(gulp.dest("build/lib"));
    });


text:
Q: Batch script to remove "duplicate" files I have a list of files named:

file.txt
file (1).txt
file (2).txt

etc.

Where the greater (number) is the last file updated.
I want a .bat script that allows get the content of file (maxnumer).txt to file.txt.

A: dir /B /OD /TW file*.txt lists file names in sort order of last written time (cf. dir /?).
Next commented batch script could do the job for you:
@echo OFF
SETLOCAL EnableExtensions
rem delete empty `_lastfile` variable
set "_lastfile="
rem store file name of last written time into `_lastfile` variable
for /F "delims=" %%G in ('dir /B /OD /TW file*.txt 2^>NUL') do set "_lastfile=%%~G"
rem                                                ↑↑↑↑↑↑ suppress errors
rem check the `_lastfile` variable
rem is defined?
rem                  AND is different from "file.txt"?
if defined _lastfile if /I "%_lastfile%" NEQ "file.txt" copy /Y "%_lastfile%" "file.txt"

Resources (required reading):

*

*(command reference) An A-Z Index of the Windows CMD command line

*(additional particularities) Windows CMD Shell Command Line Syntax

*(%~G etc. special page) Command Line arguments (Parameters)

*(2>NUL etc. special page) Redirection

A: Here is a bit of a hacky answer.
This script will move all files from file (1).txt up to file (10).txt to file.txt , leaving only file.txt which now contains the text that was in file (10).txt
Doing it in ascending order will ensure the highest number that exists is the last one to be moved.
@echo off
set /P name=Enter name of file without extension:
echo enter extension:
set /P ext=.
echo. & echo.
echo these actions will be performed: & echo.
FOR /L %%A IN (1,1,10) DO @echo move /y "%name% (%%A).%ext%" "%name%.%ext%"
echo. & pause & echo.
FOR /L %%A IN (1,1,10) DO       move /y "%name% (%%A).%ext%" "%name%.%ext%"
pause

You could use IF EXIST %name% (%%A).%ext% To stop the script from trying to move files that don't exist, but it doesn't really affect anything to do that, so I didn't bother.
The script above will do it for a specific named file.  To do it for all files in a directory will be possible, here are some hints to get you going
use a dir /b >filenames.txt to get all files in a directory listed in a text file
to perform an action for every line in a textfile do
for /f "usebackq delims= tokens=* %%a in (`filenames.txt`)" DO (
    ::some stuff here
)

The way I would go about it would be to get filenames.txt , manually delete all the (n) files so you just have a list of the "non-duplicate" filenames, and use that as your input.  You
There are probably more elegant solutions out there, but with all the peculiarities of batch I wouldn't be surprised to find they are pages and pages long.
If you want to keep all the original files not just end up with the final file.txt with no copies, then I you want to use COPY
If you want to keep all the original files, then you would want to use COPY not MOVE.
In that case, to remove all superfluous operations (i.e. only copy the highest numbered file, not copy all the files in order) then something like IF NOT EXIST %name% (!B!).%ext%  where !B!=%%A+1 within your (now multiline) for loop and use Setlocal EnableDelayedExpansion on to make the arithmetic work properly.  But it's not really necessary, copying 1, then 2, then 3, then 4 does the same thing if a little slower than skipping 1 2 and 3 and just doing 4.
I hope this helps enough to point you in the right direction, feel free to ask questions if this isn't clear.


text:
Q: Link Windows .obj file with c++ project using NetBeans/GCC/NASM Posted: Mon Nov 22, 2010 2:30 am    Post subject: How to link an assembly object with a c++ project
Hello,
I'm trying to link an assembly program with my c++ program. I'm using NASM to generate the .obj file with the command "nasm -fobj myprogram.asm". The .obj file is created, but I'm not sure how to link this with my project. I tried adding the file to Linker->Dependencies, but I still get the error that my external assembly function is not defined. Maybe the .obj file is in the wrong directory(it's in the root project folder, along with the .cpp files)?
Can anyone give a simple explanation about how to link an assembly language .obj file with my project?
Thanks,
-KB

A: Make sure you mangle the name appropriately in the assembler code.
IIRC, __stdcall is used by default in 32 bit MSVC and it prepends an underscore and appends @[bytes of arguments].
So, size_t strlen( const char *str ), if compiled __stdcall would be mangled to
_strlen@4.
Look here or here for more details.


text:
Q: How to add a common view in all view controllers at the bottom above tab bar I need to add a view that has some buttons and appears in all the view controllers. The view should contain a horizontal scrollview in which all the buttons are placed.
The view needs to be on top of the tab bar. Similar to the one in the imageThe player in the apple music application, on top of the tab bar in the bottom
Any help is appreciated. Thanks!

A: Try this:
This is Swift 3 code.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

    view.frame = CGRect(x: 0, y: UIScreen.main.bounds.height-100, width: UIScreen.main.bounds.width , height: 100)
    //window?.willRemoveSubview(view)

    //Add ScrollView to View
    let scrollview = UIScrollView(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: view.frame.size.height))
    scrollview.contentSize = CGSize( width: view.frame.size.width*2, height: view.frame.size.height)
    scrollview.backgroundColor = UIColor.blue
    scrollview.removeFromSuperview()
    view.addSubview(scrollview)

    //Add Button to Scrollview
    let btn = UIButton(frame: CGRect(x: scrollview.frame.size.width/3, y: scrollview.frame.size.height/2, width: 50, height: 30))
    btn.setTitle("Heloo", for: UIControlState.normal)
    btn.setTitleColor(UIColor.red, for: UIControlState.normal)
    let btn2 = UIButton(frame: CGRect(x: scrollview.frame.size.width/2, y: scrollview.frame.size.height/2, width: 50, height: 30))
    btn2.setTitle("Hiiii", for: UIControlState.normal)
    btn2.setTitleColor(UIColor.red, for: UIControlState.normal)
    scrollview.addSubview(btn)
    scrollview.addSubview(btn2)

    window?.makeKeyAndVisible()
    window?.insertSubview(view, at: 0)
    window?.bringSubview(toFront: view)

    return true
}

Hope this help

A: If you need to place the view, that needs to show on top of all controller's views at all times of running application, add subview to window in your App delegate.
Pros:

*

*it's fast if done proplerly

*brevity of code

Cons:

*

*needs you to make your own delegates (methods resposible for actions
with buttons)

*harder work with constraints for autolayout

*lot if design work

*hard do handle the situation, when you want to hide/show that bar, or just to hide it in certain view controllers

OR:
If you just need to extend UITabBar with ability to scroll , better would be to set tabbar conforming tabbar delegates and extend it using some library, for example:
https://github.com/kumapo/ScrollableTabs
Pros of using library:

*

*already prepared delegates

*issues with usage are well debugged

Cons:

*

*installation works


text:
Q: How to resolve 'mdb-accordion' is not a known element: error in Angular app? I am trying to add the Material Design Bootstrap Accordion to my angular app using this example.
Here is my HTML:
<mdb-accordion [multiple]="false">
    <mdb-accordion-item [collapsed]="false">
      <mdb-accordion-item-head>Collapsible Group Item #1</mdb-accordion-item-head>
      <mdb-accordion-item-body>
        Anim pariatur cliche reprehenderit, enim eiusmod high life accusamus terry richardson ad squid. 3 wolf moon officia aute,
        aliqua put a bird on it squid single-origin coffee nulla assumenda shoreditch et. Nihil anim keffiyeh helvetica, craft
      </mdb-accordion-item-body>
</mdb-accordion-item>
</mdb-accordion>

Here is the error message I am getting:

'mdb-accordion' is not a known element:

*

*If 'mdb-accordion' is an Angular component, then verify that it is part of this module.

*If 'mdb-accordion' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message.ng(0)

Here is what I have in my Angular.json:
"styles": [
          "node_modules/@fortawesome/fontawesome-free/scss/fontawesome.scss",
          "node_modules/@fortawesome/fontawesome-free/scss/solid.scss",
          "node_modules/@fortawesome/fontawesome-free/scss/regular.scss",
          "node_modules/@fortawesome/fontawesome-free/scss/brands.scss",
          "node_modules/angular-bootstrap-md/assets/scss/bootstrap/bootstrap.scss",
          "node_modules/angular-bootstrap-md/assets/scss/mdb.scss",
          "./node_modules/quill/dist/quill.core.css",
          "./node_modules/quill/dist/quill.snow.css",
          "node_modules/animate.css/animate.css",
          "src/styles.css"
        ],
"scripts": [
          "node_modules/chart.js/dist/Chart.js",
          "node_modules/hammerjs/hammer.min.js",
          "./node_modules/quill/dist/quill.js"
         ]

And I have the following in my App Module:
import { MDBBootstrapModule } from 'angular-bootstrap-md';

@NgModule({
imports: [
    MDBBootstrapModule.forRoot(),
],
})
export class AppModule { }

I tried adding something like MDBootstrapAccordion to the import in App Module, but nothing was appearing.
Can someone please tell me what I'm missing to get the accordion displaying?

A: You use MDB Free and mdb-accordion is not available in this version. You would need to purchase PRO version in order to use it in your project.
As you can see, there is a 'MDB Pro component' label in the documentation:
https://mdbootstrap.com/docs/angular/advanced/accordion/


text:
Q: Converting class component to functional component TypeError: users.filter is not a function Making a employee directory and I'm trying to convert class component into functional component. The nav, search, and table will render but the call to the api isn't working. Getting a
TypeError: users.filter is not a function Here is the class component that works and the in progress functional component. I can't figure out what is different.
import React, { Component } from "react";
import DataTable from "./DataTable";
import Nav from "./Nav";
import API from "../utils/API";
import "../styles/DataArea.css";

export default class DataArea extends Component {
  state = {
    users: [{}],
    order: "descend",
    filteredUsers: [{}]
  }

  headings = [
    { name: "Image", width: "10%" },
    { name: "Name", width: "10%" },
    { name: "Phone", width: "20%" },
    { name: "Email", width: "20%" },
    { name: "DOB", width: "10%" }
  ]

  handleSort = heading => {
    if (this.state.order === "descend") {
      this.setState({
        order: "ascend"
      })
    } else {
      this.setState({
        order: "descend"
      })
    }

    const compareFnc = (a, b) => {
      if (this.state.order === "ascend") {
        // account for missing values
        if (a[heading] === undefined) {
          return 1;
        } else if (b[heading] === undefined) {
          return -1;
        }
        // numerically
        else if (heading === "name") {
          return a[heading].first.localeCompare(b[heading].first);
        } else {
          return a[heading] - b[heading];
        }
      } else {
        // account for missing values
        if (a[heading] === undefined) {
          return 1;
        } else if (b[heading] === undefined) {
          return -1;
        }
        // numerically
        else if (heading === "name") {
          return b[heading].first.localeCompare(a[heading].first);
        } else {
          return b[heading] - a[heading];
        }
      }

    }
    const sortedUsers = this.state.filteredUsers.sort(compareFnc);
    this.setState({ filteredUsers: sortedUsers });
  }

  handleSearchChange = event => {
    console.log(event.target.value);
    const filter = event.target.value;
    const filteredList = this.state.users.filter(item => {
      // merge data together, then see if user input is anywhere inside
      let values = Object.values(item)
        .join("")
        .toLowerCase();
      return values.indexOf(filter.toLowerCase()) !== -1;
    });
    this.setState({ filteredUsers: filteredList });
  }

  componentDidMount() {
    API.getUsers().then(results => {
      this.setState({
        users: results.data.results,
        filteredUsers: results.data.results
      });
    });
  }

  render() {
    return (
      <>

          <DataTable
            headings={this.headings}
            users={this.state.filteredUsers}
            handleSort={this.handleSort}
          />

      </>
    );
  }
}

import React, { useState, useEffect } from "react";
import DataTable from "./DataTable";
import Nav from "./Nav";
import API from "../utils/API";
import "../styles/DataArea.css";

const DataArea = () => {

  const [users, setUsers] = useState([{}]);
  const [order, setOrder] = useState("descend");
  const [filteredUsers, setFilteredUsers] = useState([{}]);

  const headings = [
    { name: "Image", width: "10%" },
    { name: "Name", width: "10%" },
    { name: "Phone", width: "20%" },
    { name: "Email", width: "20%" },
    { name: "DOB", width: "10%" },
  ];

  const handleSort = (heading) => {

    if (order === "descend") {
      setOrder((order = "ascend"));
    } else {
      setOrder((order = "descend"));
    }

    const compareFnc = (a, b) => {
      if (order === "ascend") {
        // account for missing values
        if (a[heading] === undefined) {
          return 1;
        } else if (b[heading] === undefined) {
          return -1;
        }
        // numerically
        else if (heading === "name") {
          return a[heading].first.localeCompare(b[heading].first);
        } else {
          return a[heading] - b[heading];
        }
      } else {
        // account for missing values
        if (a[heading] === undefined) {
          return 1;
        } else if (b[heading] === undefined) {
          return -1;
        }
        // numerically
        else if (heading === "name") {
          return b[heading].first.localeCompare(a[heading].first);
        } else {
          return b[heading] - a[heading];
        }
      }
    };

    const sortedUsers = filteredUsers.sort(compareFnc);
    setFilteredUsers({ filteredUsers: sortedUsers });
  };

  let handleSearchChange = (event) => {
    console.log(event.target.value);
    const filtered = event.target.value;
    const filteredList = users.filter((item) => {
      // merge data together, then see if user input is anywhere inside
      let values = Object.values(item).join("").toLowerCase();
      return values.indexOf(filtered.toLowerCase()) !== -1;
    });
    setFilteredUsers((filteredUsers = filteredList));
  };

  useEffect(() => {
    API.getUsers().then((results) => {
      setUsers({
        users: results.data.results,
        filteredUsers: results.data.results,
      });
    });

  }, []);
  return (
    <>

        <DataTable
          headings={headings}
          users={filteredUsers}
          handleSort={handleSort}
        />

    </>
  );
};

export default DataArea;

A: The issue is in your useEffect hook where you shoehorn both users and filteredUsers into your users state.
useEffect(() => {
  API.getUsers().then((results) => {
    setUsers({
      users: results.data.results,
      filteredUsers: results.data.results,
    });
  });
}, []);

It should be
useEffect(() => {
  API.getUsers().then((results) => {
    setUsers(results.data.results);
    setFilteredUsers(results.data.results),
  });
}, []);

You want to populate both the users state, and separately the filteredUsers state.
An issue with setting the sorting order, you are mutating the order state:
if (order === "descend") {
  setOrder((order = "ascend")); // <-- mutates
} else {
  setOrder((order = "descend")); // <-- mutates
}

You can simply toggle between the two:
setOrder(order => order === 'ascend' ? 'descend' : 'ascend');

Another issue is at the end of your handleSort function:
const sortedUsers = filteredUsers.sort(compareFnc);
setFilteredUsers({ filteredUsers: sortedUsers });

This will nest the filteredUsers array, and also mutates the array in-place, it should probably use a functional state update to update from the previous state, use array.slice to make a copy, and then call sort.
setFilteredUsers(filteredUsers => filteredUsers.slice().sort(compareFnc));


text:
Q: Typescript arrow functions overloads error 2322 This code below is working fine, but it gives an error for the resolve constant.
const resolve: Resolve
Type '(param: "case 1" | "case 2" | "case 3") => boolean | "string" | 1000' is not assignable to type 'Resolve'.(2322)

// Overloads
type Resolve = {
    (): false;
    (param: 'case 1'): string;
    (param: 'case 2'): number;
    (param: 'case 3'): true;
};

const resolve: Resolve = (param) => {
    switch (param) {
        case 'case 1':
            return 'string';
        case 'case 2':
            return 1000;
        case 'case 3':
            return true;
        default:
            return false;
    }
};

const result = {
    first: resolve('case 1'),
    second: resolve('case 2'),
    third: resolve('case 3'),
    none: resolve()
};

Any idea how to resolve it ?

A: It's often the case that an overloaded function's implementation signature isn't fully compatible with the overload signatures. When you're using overload syntax, TypeScript uses relaxed rules for compatibility.
In your case, since you're not using overload syntax, you'll have to use a type assertion (after making sure that the function behaves correctly for the overloads):
const resolve = ((param?: "case 1" | "case 2" | "case 3"): string | number | true | false => {
    switch (param) {
        case "case 1":
            return "string";
        case "case 2":
            return 1000;
        case "case 3":
            return true;
        default:
            return false;
    }
}) as Resolve;

(I've also added a type annotation to param and a return type annotation, just for good measure, though it's not uncommon to be really loose in the implementation signature.)
Playground example

Just FWIW, using function overload syntax instead (playground link):
function resolve(param: "case 1"): string;
function resolve(param: "case 2"): number;
function resolve(param: "case 3"): true;
function resolve(): false;
function resolve(param?: "case 1" | "case 2" | "case 3"): string | number | true | false {
    switch (param) {
        case "case 1":
            return "string";
        case "case 2":
            return 1000;
        case "case 3":
            return true;
        default:
            return false;
    }
};

type Resolve = typeof resolve;

...but that's not always possible, it's not uncommon to have to define the type without ever actually implementing it (for instance, in a callback type for an API).


text:
Q: extract weights from a RWeka SMOreg model I am using the awesome RWeka package in order to fit a SMOreg model as implemented in Weka. While everything is working fine, I have some problem extracting the weights from the fitted model.
As all Weka classifier object, my model has a nice print method that shows me all the features and their relative weights.  However, I am not able to extract this weights in any way.
You can see for yourself by running the following code:
library(RWeka)
data("mtcars")
SMOreg_classifier <- make_Weka_classifier("weka/classifiers/functions/SMOreg")
model_SMOreg <- SMOreg_classifier(mpg ~ ., data = mtcars)

Now, if you simply call the model
model_SMOreg

you'll see that it prints all the features used in the model with their relative weight. I would like to access those weights as a vector or, even better, as a 2-columns table with one column containing the names of the features and the other containing the weights.
I am working on a Windows 7 x64 system, using RStudio Version 1.0.153, R 3.4.2 Short Summer and RWeka 0.4-35.
Does someone know how to do this ?

A: I think you cannot get this in numeric format.
attr(model_SMOreg, "meta")$class                      #  "Weka_classifier"

getAnywhere("print.Weka_classifier")

Result:
A single object matching 'print.Weka_classifier' was found
It was found in the following places
  registered S3 method for print from namespace RWeka
  namespace:RWeka
with value

function (x, ...)
{
    writeLines(.jcall(x$classifier, "S", "toString"))
    invisible(x)
}
<bytecode: 0x8328630>
<environment: namespace:RWeka>

So we see: print.Weka_classifier() makes a  .writeLines() call which in turn makes a rJava::.jcall call, which returns a string.
Thus, I think you need to parse the weights yourself, perhaps by calling the capture.output() method.

A: Based on the suggestion of @knb I have wrote a function to extract the weights from a SMOreg model and return a tibble with one column for the features name and one for the features weight, with the row arranged following the absolute value of the weight.
Note that this function only works for the SMOreg classifier, as the output of other classifiers is slightly different in terms of layout. However, I think the function can be easily adapted for other classifiers.
library(stringr)
library(tidyverse)

extract_weights_from_SMOreg <- function(model) {

  oldw <- getOption("warn")
  options(warn = -1)

  raw_output <- capture.output(model)
  trimmed_output <- raw_output[-c(1:3,(length(raw_output) - 4): length(raw_output))]
  df <- data_frame(features_name = vector(length = length(trimmed_output) + 1, "character"),
                   features_weight = vector(length = length(trimmed_output) + 1, "numeric"))

  for (line in 1:length(trimmed_output)) {

    string_as_vector <- trimmed_output[line] %>%
      str_split(string = ., pattern = " ") %>%
      unlist(.)

    numeric_element <- trimmed_output[line] %>%
      str_split(string = ., pattern = " ") %>%
      unlist(.) %>%
      as.numeric(.)

    position_mul <- string_as_vector[is.na(numeric_element)] %>%
      str_detect(string = ., pattern = "[*]") %>%
      which(.)

    numeric_element <- numeric_element %>%
      `[`(., c(1:position_mul))

    text_element <- string_as_vector[is.na(numeric_element)]

    there_is_plus <- string_as_vector[is.na(numeric_element)] %>%
      str_detect(string = ., pattern = "[+]") %>%
      sum(.)

    if (there_is_plus) { sign_is <- "+"} else { sign_is <- "-"}

    feature_weight <- numeric_element[!is.na(numeric_element)]

    if (sign_is == "-") {df[line, "features_weight"] <- feature_weight * -1} else {df[line, "features_weight"] <- numeric_element[!(is.na(numeric_element))]}

    df[line, "features_name"] <- paste(text_element[(position_mul + 1): length(text_element)], collapse = " ")

  }

  intercept_line <- raw_output[length(raw_output) - 4]

  there_is_plus_intercept <- intercept_line %>%
    str_detect(string = ., pattern = "[+]") %>%
    sum(.)

  if (there_is_plus_intercept) { intercept_sign_is <- "+"} else { intercept_sign_is <- "-"}

  numeric_intercept <- intercept_line %>%
    str_split(string = ., pattern = " ") %>%
    unlist(.) %>%
    as.numeric(.) %>%
    `[`(., length(.))

  df[nrow(df), "features_name"] <- "intercept"

  if (intercept_sign_is == "-") {df[nrow(df), "features_weight"] <- numeric_intercept * -1} else {df[nrow(df), "features_weight"] <- numeric_intercept}

  options(warn = oldw)

  df <- df %>%
    arrange(desc(abs(features_weight)))

  return(df)
}

Here an example for one model
library(RWeka)
data("mtcars")
SMOreg_classifier <- make_Weka_classifier("weka/classifiers/functions/SMOreg")
mpg_model_weights <- extract_weights_from_SMOreg(SMOreg_classifier(data = mtcars, mpg ~ .))
mpg_model_weights


text:
Q: Ubuntu PHP5/Apache2 - Displaying 500 error instead of error message The following script is not outputting error messages to the browser. Instead it results in an HTTP Error 500 response.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 'On');

phpinfo();

echo "test" asdf // This should error
?>

Ideas? This is a basic php5/apache2 install on ubuntu. httpd.conf is blank, no .htaccess file.
The error.log file displays the error message:

syntax error, unexpected T_STRING, expecting ',' or ';'

which is correct.

A: If the script has a parse error that prevents it from running, this also prevents it from changing a PHP setting.


text:
Q: Hyper-V VM guest can't ping any machine So I got
Host: Hyper-v enabled machine with four NICs, only one enabled.
Network type: External
IP configuration are correct for both host and guest (getting it from the DHCP of the company network)
The same configuration works on a machine with single NIC
But With this other machine, with 4 NICs, there is no Internet in the guest, actually it can't ping any IP expect the host (pings host IP only, not the name)
I searched the Internet and did every solution, more than once, with no success.

A: Have you tried manually configuring the NIC inside the VM?
It sounds like a mis-configured Virtual Network, have you confirmed that the correct NIC is bound to the Virtual Network Switch. I have a Dell server, that is very confusing to tell that on.


text:
Q: Can I connect the wifi and create hotspot with only 1 wireless card? It seems that with one wireless network card, I can either connect the wifi or create hotspot. But in windows, I can connect the wifi, create hostspot and share the network with the hotspot as the same time. In the ubuntu, what should I do?

A: Also in Linux this should be possible.
In the terminal type in
sudo iw list

and look for the part, where interface combinations are mentioned.
This will tell you about the capabilities of your WiFi hardware/driver.
You get info about which modes can be used in parallel (if supported) and how many channels are available for this (on most standard HW you will be limited to a single channel).
I have not tried it myself, but here is one possible way to setup an AP in parallel to being connected to another AP in Ubuntu.

A: Update on @HIMANSHU GARG answer with installation steps.
Step 1:
First, check whether your wireless card can create a hotspot or not while connected to a wifi network. (as mentioned by @oh.dae.su)
-> run sudo iw list and look for valid interface combinations: in output

*

*My output screenshot (I have 2 channels):

Step 2:
Install Linux Wifi Hotspot. This one provides both command line and GUI based interfaces. (Reference: Github repository link)

*

*Install ubuntu package dependencies and make package:
sudo apt install -y libgtk-3-dev build-essential gcc g++ pkg-config make hostapd libqrencode-dev libpng-dev

*Follow these commands in terminal:
git clone https://github.com/lakinduakash/linux-wifi-hotspot
cd linux-wifi-hotspot
make
sudo make install
Output screenshots:

*

*check your wifi/internet adapter name using ifconfig (e.g. for me it's wlp6s0)

*Wifi hotspot running in parallel with wifi connected

System specs:

*

*Tested on: Ubuntu 20.04

*My wifi card info (run sudo lshw -C network):
Description: Wireless interface
Product: Wi-Fi 6 AX200
Vendor: Intel Corporation

A: Far as I know you can't. In Linux.
You can connect your PC with a cable and then make wifi card as hot-spot.
Or connect, for example, with eternal wifi and make external/USB as hot-spot.

A: Note :- (Tried on Ubuntu 18.04 and can be used only for linux)
To turn on Wifi hotspot to share the intenet without disconnecting from WiFi (means both are running at same time). This tool can be helpful for this. Follow the steps given there. This tool has a nice GUI and easy to use.
GUI Image

A: Here is a solution that worked for me on my Laptop running Ubuntu 18.04:
https://github.com/oblique/create_ap
It's not beeing maintained anymore, but it workes like a charm and is simple to run.
Open up a terminal and enter the following:

*

*git clone https://github.com/oblique/create_ap.git

*cd create_ap/

*make install

*sudo create_ap wlan0 wlan0 MyAccessPoint MyPassPhrase

Line 4 will create a hotspot, if you close the terminal the hotspot will shutdown.
wlan0 is my wireless adapter, find yours with using "ip addr" in a terminal. "MyAccesspoint" and "MyPassPhrase" can be changed to what you would like.


text:
Q: Submitting a variable amount of fields with jQuery ajax  What is the quickest way using jQuery to build a JSON string with a constantly changing amount of fields?
I've searched high and low and have seen a few ways to do this, but none seem to be labeled as better or faster.
The code below looks to be the quickest to write, but does it have any drawbacks? It also looks like you can't append any additional data you might need that doesn't have an input field for it. Or can you?
$.ajax({
  type: 'post',
  url: url,
  data: inputs,
  success: function(result) {
     $('.change').html(result);
   }
});

Is using .each and creating the string yourself better in any way? Anyone who can shed some light on how to go about designing the best method?

A: See my answer to this very similar question.
If you're populating your data from the contents of form fields, there are several ways. You could:

*

*apply some particular class to each element and select against it, appending the value of each matching element to your object literal

*if you have the DOM ids of all relevant fields, loop through them

*if all of the target elements are sibling children of a given element, select against that element's children
...are three possibilities that come to mind. Most of the time, though, you'll find it's less error-prone to pass an object literal and let jQuery worry about the shipping and handling than it is to build a string yourself.


text:
Q: different git history in develop and master due to git squash We follow the Gitflow pattern and have develop, release and master branches. We merge the feature branches into develop. We checkout the release branch from develop and merge into the master during the release time. We had set the squash and merge setting in the github.
We have a situation due to squash settings.
Let's say we have commits c1, c2, c3,..c100 commits in develop branch. we checkout out release branch from it and added few more small commits d1, d2, d3. when we merged the release branch into master, it squashed all the commits into one commit CM1. Now the master has only one commit. Since we needed d2, d2, d3 in develop also, we tried to merge release branch. Now it shows lots of file changes since they have different commit history.
We realized we should not have squash settings while merging into the master branch. Now the question is how can we bring develop and master in sync again. I wanted to discuss which of the option would be best. I can think of one. Let me know if there are other better options.

*

*Merge release branch into master again without the squash settings. This will make develop and master same.

A: As you realized, it's not a good idea to use squash merges on long-running branches.  The GitHub documentation explains why this is.  Right now, you have two possible options to consider:

*

*Perform a merge as normal.  If the two sides have not changed much since the squash merge, then this will probably just work.

*If the two sides have diverged significantly or the above option causes significant conflicts, you can revert the squash merge and perform the merge again.  This may have conflicts of its own, so the first option is better.

I would try the first option, and if it seems really awful, then try the second option and see if it's better.


text:
Q: Problema na inicialização do Tomcat Como medida paliativa para este erro, instalei o XAMPP e o coloquei (o Tomcat) como container para o NetBeans. Porém quando vou executar algum projeto no NetBeans, o seguinte erro aparece no console do Tomcat na IDE:
Iniciando a partir da falha do Tomcat:

'127.0.0.1' nÆo ' reconhecido como um comando interno
ou externo, um programa oper vel ou um arquivo em lotes.

E o processo de implantação do projeto é interrompido.
Acho isso estranho, porque quando tento iniciar o Tomcat diretamente pelo XAMPP, ele o faz normalmente. Tentei iniciar o NetBeans como administrador, mas não funcionou. Como posso resolvê-lo?

A: Por algum motivo esse problema tem a ver com as configurações de proxy do Netbeans.
Se você for no menu Ferramentas -> Opções e marcar a opção "Sem Proxy" nas "Definições de Proxy" deve iniciar corretamente o tomcat.


text:
Q: PHP foreach - parsed json from an array inside an array Here is a part of the json file:
{
  "status": {
     "http_code": 200
  },
  "contents": [
    {
      "FabrikatNavn": "Jaguar",
      "ModelNavn": "420G",
      "PrisDetailDkk": 119900,
      "StatusTyper": [
        {
          "StatusId": -5,
          "StatusNavn": "Benzin"
        },
        {
          "StatusId": -15,
          "StatusNavn": "Momsfri"
        },
        {
          "StatusId": -11,
          "StatusNavn": "100-120.000"
        }
      ],

      "ImageIds": [
        {
          "Id": 79359
        },
        {
          "Id": 79360
        },
        {
          "Id": 79361
        },
        {
          "Id": 79370
        }
      ]
    },
    {
      "FabrikatNavn": "Opel",
      "ModelNavn": "Corsa",
      "PrisDetailDkk": 135900,
      "StatusTyper": [
        {
          "StatusId": -4,
          "StatusNavn": "Diesel"
        },
        {
          "StatusId": -15,
          "StatusNavn": "Momsfri"
        },
        {
          "StatusId": -12,
          "StatusNavn": "120-140.000"
        }
      ],

      "ImageIds": [
        {
          "Id": 225794
        },
        {
          "Id": 225795
        },
        {
          "Id": 225796
        },
        {
          "Id": 225797
        }
      ]
    },
    {
      "FabrikatNavn": "Hyundai",
      "ModelNavn": "H1",
      "PrisDetailDkk": 14999,
      "StatusTyper": [
        {
          "StatusId": 13,
          "StatusNavn": "Afhentning"
        },
        {
          "StatusId": -4,
          "StatusNavn": "Diesel"
        },
        {
          "StatusId": -8,
          "StatusNavn": "0-60.000"
        }
      ],

      "ImageIds": [
        {
          "Id": 415605
        },
        {
          "Id": 415606
        },
        {
          "Id": 415607
        },
        {
          "Id": 415979
        }
      ]
    }
  ]
}

And here's the PHP
<?php

$url = 'http://banen.klintmx.dk/json/ba-simple-proxy.php?url=api.autoit.dk/car/GetCarsExtended/59efc61e-ceb2-463b-af39-80348d771999';
$json= file_get_contents($url);

$data = json_decode($json);
$rows = $data->{'contents'};
foreach ($rows as $row) {
    echo '
';
    $FabrikatNavn = $row->FabrikatNavn;
    $ModelNavn = $row->ModelNavn;
    $PrisDetailDkk = $row->PrisDetailDkk;

    // tried this, but it don't work -->
    foreach($row->StatusTyper as $StatusTyper) {
        $StausId = $StatusTyper->StatusId;
        if ($StausId == '-15') { $Moms = 'mm'; }
        else { $Moms = 'um'; }
    }

    echo '
 ';
    echo $FabrikatNavn . $ModelNavn . ' Pris ' . $PrisDetailDkk;
    echo '
';
    echo '
';
}

As you can see, the values in the "StatusTyper" different, so here I have tried with if else, but I can not get it to work - It returns'um' everytime
What's wrong?

A: This is because the loop always picks the value of last condition met. You need to somehow tell PHP to break the loop if it founds the match $StausId == "-15" otherwise it will continue to match $StausId != "-15" which always assigns the value "um" to $Moms.
foreach($row->StatusTyper as $StatusTyper) {
    $StausId = $StatusTyper->StatusId;

    if ($StausId == "-15") {
        // Found the match
        $Moms = 'mm';
        // End the execution of current loop
        break;
    } else {
        // $StausId value is not equal to -15
        // So it was picking this
        $Moms = 'um';
    }

}


text:
Q: How to conditionally display HTML with EJS Template? I tried following condition that's works fine,
<% if (user) { %>

 Success

<% } else { %>

 Failure

 <% } %>

but I want to check the condition like below,
<% if (user.verified == true ) { %>

 Success

<% } else { %>

 Failure

 <% } %>

Its not working, showing error.
Please anyone help me to fix the issue.

A: You need to check user is undefined or not. So the code should be:
<% if (user && user.verified == true) { %>

 Success

<% } else { %>

 Failure

<% } %>

A: Finally, I got a solution !!
<% if(typeof (user) != "undefined"){ %>

User Exists

<% } %>

Mind that undefined is placed inside " " (quotes).
Just FYI :

Undefined, null, "" (empty string) are  considered as a false in
  Javascript but still here I was getting error due to undefined in ejs
  file.

Hope that helps !


text:
Q: zend framework 2 (zfcadmin) and routing I want to create admin panel using ZfcAdmin module. I want to create routing, to manage users. Here is it:
<?php
    return array(
        'controllers' => array(
            'invokables' => array(
                'AdminUser\Controller\AdminUser' => 'AdminUser\Controller\AdminUserController',
            ),
        ),
        'view_manager' => array(
            'template_path_stack' => array(
                'admin-user' => __DIR__ . '/../view',
            ),
        ),

        'router' => array(
            'routes' => array(
                'zfcadmin' => array(
                    'may_terminate' => true,
                    'child_routes' => array(
                        'user' => array(
                            'type' => 'segment',
                            'options' => array(
                                'route' => '/user',
                                'defaults' => array(
                                    'controller' => 'AdminUser\Controller\AdminUser',
                                    'action'     => 'index',
                                ),
                            ),
                            'may_terminate' => true,
                            'child_routes' =>array(
                                'edit' => array(
                                    'type' => 'segment',
                                    'options' => array(
                                        'route' => '/edit/:user_id',
                                        'defaults' => array(
                                            'controller' => 'AdminUser\Controller\AdminUser',
                                            'action'     => 'edit',
                                        ),
                                    ),
                                ),
                            ),
                        ),
                    ),
                ),
            ),
        ),
    );

I request: /admin/user and it's ok, but when I want to receive URL like: /admin/user/edit/1 I always get /admin/user I create the link this way:
<?php $this->url('zfcadmin/user/edit', array(
                    'action'  => 'edit',
                    'user_id' => $user['user_id'],
                )) ?>
why? what's wrong?

A: The first argument in the ZF2 Url view helper is a $name.  Have you tried using 'edit' like you've specified in your config?
I also think you may need to echo the value.
<?php echo $this->url('edit', array('action' => 'edit', 'user_id' => $user['user_id'],)); ?>


text:
Q: Calling Firefox XPCOM component from Thunderbird extension I'm doing a Thunderbird extension that will get the stored username/password in Firefox and import those accounts into Thunderbird. This results in the need of nsILoginManager, but I'm not sure how to make it work from a Thunderbird extension. Is it possible to do so?

A: You pretty much cannot. In addition to XPCOM simply not working across different processes, the complications are:

*

*What if Firefox isn't running?

*What if the password storage is encrypted with a master password?

*What if there is more than one Firefox profile?

The best you could do would be:

*

*Start Firefox with a command line like firefox -url file://foo/bar/extension.xpi - make sure that Firefox is running and the user is asked to install extension.xpi. It should be a bootstrapped extension so that no browser restart is required.

*That extension gets the necessary data from nsILoginManager (which involves a password prompt if the user has a master password defined) and sends it back to Thunderbird.

*After that this extension uses the Add-on Manager API to uninstall itself.

This is far from being a smooth user experience of course. As to how the two extensions (one in Thunderbird, the other in Firefox) would communicate - TCP sockets would probably be the easiest way. The Thunderbird extension would create a server socket and wait for the Firefox extension to connect to it.


text:
Q: How to display images which is stored outside the folder? I want to display images which is stored outside the root folder in asp.net
like :
Image1.ImagUrl="C:\temp\Images\img1.jpg"
but it is not helpful for me. So Please help me.

A: The path you are supplying is not a URL. You need to supply the virtual path to the file, not the absolute (file system) path.
Image1.ImagUrl="~/Images/img1.jpg"

The browser is incapable of reading files on your local file system.
You can map a virtual directory to any directory on your file system so it has a virtual path. Let's say you want to make the physical directory C:\temp\Images\ into a virtual directory called /Images/ and you are using IIS 7.

*

*Open Internet Information Services (IIS) Manager.

*Under sites, navigate to the site you wish to place the virtual directory in.

*Right click on the site node, and click "Add Virtual Directory...".

*For the alias, type Images.

*For the Physical Path, type C:\temp\Images\.

*Click OK.

Now you can access your image through the virtual directory /Images/img1.jpg.
Image1.ImagUrl="~/Images/img1.jpg"

A: Image1.ImagUrl=@"C:\temp\Images\img1.jpg"

put a @ before the path string


text:
Q: Timers In A Game Im trying to code a 2D java game. I have init(), render(), update() methods as usual. The thing I want to figure out is, I would like to have timers attached to objects. For example a powerup randomly spawns in the map, but it should exist for 5 seconds. Or when the user hits the "Play" button, I would like to make him wait for 3 seconds, and at the same time do the background work (load resources, create the scene etc). I mean I would like to have the time counters work at the background, while I'm doing the stuff normally in the game at the same time. How can I implement this? Any helps, even simple ideas would be appreciated!
Edit: I'm using slick2D library and Graphics class for drawing to the screen.

A: There are a few ways to "pause" execution. These are two:

*

*you can use delay(milliseconds) from the Robot class

*or the static method Thread.sleep(milliseconds)

A: If you want to use a timer there are multiple ways to do so, as stated previously there is the:
Thread.sleep(milli);
or another way I commonly use is to create a new class and make a Timer there using a while loop:
public class Timer implements Runnable {

    private long startTime, runTime;

    public Timer(long runTime){//set runtime
         this.runTime = runTime;
    }

    public void run(){
       startTime = System.currentTimeMillis();//gets system's current time in milliseconds
       while(System.currentTimeMillis() - startTime < runTime ){//loops until the current time - the start time is less then the specified run time.
        //Runs this
       }
    }
}


text:
Q: Error while Running NodeJs on ARMv7 IMX6Q Board, How to fix it? What I Want : I want to run nodejs on ARMv7 freescale imx6q board with no internet but network connectivity.
What I did  : I took pre built binary from nodejs official download. extracted them and tried to run node binary. But it throws error "No such file or directory". I have tried changing permissions also. Have a look at logs below.
mx6q:/node/node-v5.9.0-linux-armv7l/bin# ls
node  npm
mx6q:/node/node-v5.9.0-linux-armv7l/bin# ./node
bash: ./node: No such file or directory
mx6q:/node/node-v5.9.0-linux-armv7l/bin# ls -l
total 22084
-rwxr-xr-x    1 root     root      22612411 Jan  1 03:37 node
lrwxrwxrwx    1 root     root            38 Jan  1 01:04 npm -> ../lib/node_modules/npm/bin/npm-cli.js
mx6q:/node/node-v5.9.0-linux-armv7l/bin# cat /proc/cpuinfo
processor       : 0
model name      : ARMv7 Processor rev 10 (v7l)
BogoMIPS        : 1988.29
Features        : swp half thumb fastmult vfp edsp neon vfpv3 tls vfpd32
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x2
CPU part        : 0xc09
CPU revision    : 10

processor       : 1
model name      : ARMv7 Processor rev 10 (v7l)
BogoMIPS        : 1988.29
Features        : swp half thumb fastmult vfp edsp neon vfpv3 tls vfpd32
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x2
CPU part        : 0xc09
CPU revision    : 10

processor       : 2
model name      : ARMv7 Processor rev 10 (v7l)
BogoMIPS        : 1988.29
Features        : swp half thumb fastmult vfp edsp neon vfpv3 tls vfpd32
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x2
CPU part        : 0xc09
CPU revision    : 10

processor       : 3
model name      : ARMv7 Processor rev 10 (v7l)
BogoMIPS        : 1988.29
Features        : swp half thumb fastmult vfp edsp neon vfpv3 tls vfpd32
CPU implementer : 0x41
CPU architecture: 7
CPU variant     : 0x2
CPU part        : 0xc09
CPU revision    : 10

Hardware        : Freescale i.MX6 Quad/DualLite (Device Tree)
Revision        : 63012
Serial          : d4111f0ec91719d8
mx6q:/node/node-v5.9.0-linux-armv7l/bin# file node
node: ELF 32-bit LSB executable, ARM, EABI5 version 1 (GNU/Linux), dynamically linked (uses shared libs), for GNU/Linux 2.6.26, BuildID[sha1]=e7c667ffc2519bf31b963b29954863c673be6fba, not stripped
mx6q:/node/node-v5.9.0-linux-armv7l/bin#

Anybody who has worked on the same or have any lead, How to overcome this error ?

A: As  @Notlikethat suggested, Pre-built binary was looking for /lib/ld-linux-armhf.so.3 and was not available.
Compiling source code in my own environment worked fine.


text:
Q: Гибернация и hiberfil.sys Сразу к делу.
Компьютер ушел в гибернацию, потом включение компьютера.. заставка "Восстановление Windows". Загрузился, ок - всё.
Вопрос. Можно ли второй раз запустить "Восстановление Windows" знаю, что на C:\ лежит файл куда всё пишется hiberfil.sys.


text:
Q: All the statements are not executing in for ...in loop I'm trying to run several statements inside for loop of object, but only first line of code is executing inside the for loop, rest lines are not executing.
addFinalQuestionDetail (items) {
var checkEmpty = false; // Check weather all the data is filled to perform further action
console.log(items);
for (var item in items)
  console.log(item);
  console.log(items[item]);
  console.log(typeof(items[item]));
}

Here items are the object name passed in the function, writtem below:-
This is my object:
addQuestionValueDetails = {
    questionTemplateType: " ",
    questionTemplateName: " " ,
    questionTemplateId: " " ,
    questionTitle: " ",
    questionOptionCount: 0,
    questionDuration: "",
    questionOptionList: [ ],
    questionBlankList: [ ],
    correctOptionList: [ ],
    questionDifficulty: 0,
    questionTags: " ",
    isNewQuestion: false,
    isEditedOption: false
  }

Only first console.log is executing properly, then rest two lines are not executing desired times loop is running.
If I'm commenting first statement, then 2nd line is executing total number of times as expected, and 3rd is not working, and so on.
This is the output, when all the statement are uncommented

This is the output, when first line is commented, and two lines are uncommented

This is the output, when first and second line is commented, and last line are uncommented

This function displays output from edit-submodule.component.ts:863 in the screenshots.

A: Youre missing the braces in the for loop, so it's currently parsing this as:
for (var item in items) {
  console.log(item);
}
console.log(items[item]);
console.log(typeof(items[item]));


text:
Q: Copy one database to another database How to copy from one database to another database.
Database name visco
I want to copy all the table from visco database to new database name as neptune
I was created one database with out any tables, then i try to restore the database from database1.bak file, then it is showing error as
You are attempting to overwrite an existing database.  Check the force restore over existing database option to
overwrite the existing database.

Need Query Help

A: Using the SQL Server Management Studio:
Option 1
-> Right click on the database you want to copy
-> Choose 'Tasks' > 'Generate scripts'
-> 'Select specific database objects'
-> Check 'Tables'
-> Mark 'Save to new query window'
-> Click 'Advanced'
-> Set 'Types of data to script' to 'Schema and data'
-> Next, Next :)
You can now run the generated query on the new database.
Option 2
-> Right click on the database you want to copy
-> 'Tasks' > 'Export Data'
-> Next, Next :)
-> Choose the database to copy the tables to
-> Mark 'Copy data from one or more tables or views'
-> Choose the tables you want to copy
-> Finish

A: There is not one, but several options to achieve what you want. Your question is not very specific in that respect.
You may find this article "SQL SERVER – 2008 – Copy Database With Data – Generate T-SQL For Inserting Data From One Table to Another Table" useful:
http://blog.sqlauthority.com/2009/07/29/sql-server-2008-copy-database-with-data-generate-t-sql-for-inserting-data-from-one-table-to-another-table/
If that leaves unanswered questions let us know.

A: Build an SSIS package and use the "Transfer SQL Server Objects Task"
Example
Documentation

A: Check out the products of Atlantis Interactive, free and licensed for commercial use
They are similar to Red Gate's products and have the ability to synchronize schema and data between databases.

A: You could export the tables and info and, that file, import it to the new data base. The file usually could be saved as a .sql
Check: http://msdn.microsoft.com/en-us/library/ms140052.aspx

A: One easy way would be to take a backup of the existing database and then restore that backup to a new database.
Check out this technet article for information on backing up and restoring databases using Enterprise Manager: Backup & Restore Database using Enterprise Manager


text:
Q: Joins in multiple table I want to fetch records (Class, Subject, Chapter, ModuleName, AccessTime, LoginTime, IpAddress and Email) from below tables, main fields of the tables are shown in bracket ().
 ct_user (user_Id, email)
 ct_user_log (user_id, ip_address, login_time, sessionId)
 ct_user_module_log (module_id, module_open_time,user_id, ip_address, sessionId)
 ct_user_module (module_id, module_name, subject_id, chapter_id, topic_id, board_class_id)
 ct_subject (subject_id, subject_name)
 ct_board_class (board_class_id, class_name, board_id, class_id)
 ct_class_subject_topic (topic_id, topic_name, board_class_id, topic_level)


text:
Q: Terraform: How to iterate over multiple values in object Im trying to create a resource with a name and a description. Both are strings
VARIABLES.TF
variable "leaf_int_prof_group"{
type = object({
    name = string
    description = string
})

}
TERRAFORM.TFVARS
leaf_int_prof_group = {
{
   name = "Leaf_101"
   description = "This is a Leaf101"
}
{
   name = "Leaf_102"
   description = "This is a Leaf102"
}
{
   name = "Leaf_103"
   description = "This is a Leaf103"
}

}
MAIN.TF
How would i define the variables in main.tf (below doesnt seem to work??)
resource "aci_leaf_interface_profile" "LN_group" {
for_each = var.leaf_int_prof_group
    name = var.leaf_int_prof_group.name
    description = var.leaf_int_prof_group.description

}

A: Your code is not a valid TF code. Perhaps  you want a list of objects:
variable "leaf_int_prof_group"{
    type = list(object({
        name = string
        description = string
    }))
}

then
leaf_int_prof_group =  [
    {
       name = "Leaf_101"
       description = "This is a Leaf101"
    },
    {
       name = "Leaf_102"
       description = "This is a Leaf102"
    },
    {
       name = "Leaf_103"
       description = "This is a Leaf103"
    }
]

and finally:
resource "some_resource" "some_name" {
    for_each    = {for idx, val in var.leaf_int_prof_group: idx => val}
    name        = each.value.name
    description = each.value.description
}


text:
Q: What does "Moral luck" mean? As an extension of my interest in Van Gogh's severed ear from Jeffrey Archer's "False Impression" that depicted mysterious odyssey of Van Gogh's self-portrait with bandage on his left ear, I was attracted to read Adam Gopnik's article titled, Van Gogh's ear – The Christmas Eve that changed modern art, that appeared in New Yorker magazine (Jan. 4 issue).
In his article, Gopnik introduces Moral Luck (1976), the essay of Bernard Williams on the relationship of Van Gogh and Paul Gauguin and their influence on modern art. Not only the title of William's book, the words Moral luck are repeated four times in the following sentence:

What Williams didn't entirely register, though, was that Gauguin isn't just one artist plucked at random out of time, a desperado in a line stretching back to Pygmalion. He's not just an instance of moral luck; he is an inventor of moral luck. He is a model modern artist, and modern art is in many ways about moral luck, about the search for it, about raising the stakes to see if it can happen. Modern art makes its own moral luck.

I don't understand the meaning of Moral luck. I checked the definition of luck with Cambridge Online Dictionary, which defines luck simply as:

*

*The force that causes things, especially good things, to happen to you by chance and not as a result of your own efforts or abilities. 2. Success.

Oxford Dictionary at hand defines it in the same way as 1. "Good things that happen to you by chance. 2. Chance. Period."
I cannot even guess the meaning of Moral luck from any of the above definitions. To me, Moral doesn't seem to sit well with Luck. Can you decode what Moral luck really means?

A: According to Wikipedia,

Moral luck describes circumstances whereby a moral agent is assigned
  moral blame or praise for an action or its consequences even though it
  is clear that said agent did not have full control over either the
  action or its consequences.

More simply, it is the idea that people are to be held responsible for an action even when they aren't the only force that caused it - even if it occurred accidentally.
This stands a bit in contrast to the typical sentiment that responsibility correlates with voluntary action. (Meaning, if you choose to do something and do it, you are responsible for it.)
There are some interesting problematic examples in the Wikipedia article you might want to check out.
I don't know enough about Gauguin to speculate as to why he's such a good example of moral luck, but hopefully knowledge of the term will make the book's argument clearer in context.

A: Scenario A. If I make or accept a call on my mobile phone whilst I am driving (without a proper hands-free kit installed in my car) I am breaking the law. However the chances are that if I do that nothing will happen, there will be no accident and the police will not find out about it.
Scenario B If however there should be an accident when I do this and somebody gets killed, and it emerges in evidence that I was using my mobile phone at the time of the accident, which was clearly my fault, I could be found guilty of dangerous driving and could be sent to prison.
The difference between Scenario A and Scenario B is determined by two things, a) my skill as a driver and b) pure chance, or luck.
All of us, to a greater or lesser degree rely on this 'moral luck' on a daily basis.
I heard of someone writing a PhD Philosophy thesis on this very subject.
That is my understanding of 'moral luck'.

A: In one word, I'd describe it as "karma"


text:
Q: Looking for the best Array method to compare objects in array Sample array
var myItems = [{height:500, width:400},{height:500, width:800},{height:500, width:700}]

Instead of doing
if(myItems[0].height !== myItems[1].height && myItems[0].height !== myItems[2].height && myItems[1].height !== myItems[2].height){
 // do smth about it
}

with larger arrays this code gonna get ridiculous, so I played with this
if (myItems.reduce((x,y)=>x.height!==y.height)){
 // do the same thing
}

The problem is, this always returns true even if the above values are in place, all items have same height value.

A: You can try converting this to a set for height and then compare the lengths for your array and the heightSet.

var myItems = [{height:500, width:400},{height:500, width:800},{height:500, width:700}];

var heightSet = [...new Set(myItems.map(x => x.height))];

console.log(myItems.length === heightSet.length);


text:
Q: Which kind of python setup is more portable? I am wondering and pondering what python setup to use. Portable in sense of Portable Python in Windows (but i need such for Linux).
I am working on python project with a lot of dependencies , including C/C++ libraries , reuses some perl scripts , and even Java Tika lib to parse multiple document types. I want to put them all in local folder and bundle it so that they do not have to re-install when i am going to set it up on different servers (which have different Linux Distro , Gentoo , Ubuntu and Redhat ).
I wont use python provided by distro because it causes many headaches.
From studying around , these are choices I got :
1 - VirtualENV (But it defeat my purpose as it is not designed to relocate).
2 - Statically Compiling Python (Not sure how it will work, I do not see many success stories on it)
3 - Local (Manually) Compiling Python  (Wont work at different Libc version right?)
Any other choices ? Please let me know..
Thanks in advance.

A: virtualenv is problematic, because it needs the libraries from the computer. Because nowadays most linux distros have python installed by default, the only case that'll be a problem is when the installed version on the computer is different than the one you're using.
However, I believe you can fix that by copying all the libs on PYTHONPATH that are placed on your local installation to the virtualenv folder.
I don't know about 2 or 3, but you could also try to manually compile python to your USB disk and pip your libraries.


text:
Q: Generic/template programming best practices: To limit types, or not to limit types That is my question.  I'm just curious what the consensus is on limiting the types that can be passed in to a generic function or class.  I thought I had read at some point, that if you're doing generic programming, it was generally better to leave things open instead of trying to close them down (don't recall the source).
I'm writing a library that has some internal generic functions, and I feel that they should only allow types within the library to be used with them, simply because that's how I mean for them to be used.  On the other hand, I'm not really sure my effort to lock things down is worth it.
Anybody maybe have some sources for statistics or authoritative commentary on this topic?  I'm also interested in sound opinions.  Hopefully that doesn't invalidate this question altogether :\
Also, are there any tags here on SO that equate to "best-practice"?  I didn't see that one specifically, but it seems like it'd be helpful to be able to bring up all best-practice info for a given SO topic... maybe not, just a thought.
Edit: One answer so far mentioned that the type of library I'm doing would be significant.  It's a database library that ends up working with STL containers, variadics (tuple), Boost Fusion, things of that nature.  I can see how that would be relevant, but I'd also be interested in rules of thumb for determining which way to go.

A: It's one of the strongest selling points of the STL that it's so open, and that its algorithms work with my data structures as well as with the one it provides itself, and that my algorithms work with its data structures as well as with mine.
Whether it makes sense to leave your algorithms open to all types or limit them to yours depends largely on the library you're writing, which we know nothing about.
(Initially I meant to answer that being widly open is what Generic Programming is all about, but now I see that there's always limits to genericity, and that you have to draw the line somewhere. It might just as well be limited to your types, if that makes sense.)

A: In my database framework, I decided to forgo templates and use a single base class.  Generic programming meant that any or all objects can be used.  The specific type classes outweighed the few generic operations.  For example, strings and numbers can be compared for equality; BLOBs (Binary Large OBjects) may want to use a different method (such as comparing MD5 checksums stored in a different record).
Also, there was an inheritance branch between strings and numeric types.
By using an inheritance hierarchy, I can refer to any field by using the Field class or to a specialized class such as Field_Int.

A: At least IMO, the right thing to do is roughly what concepts attempted: rather than attempting to verify that you're receiving the specified type (or one of the set of specified types), do your best to specify the requirements on the type, and verify that the type you've received has the right characteristics, and can meet the requirements of your template.
Much like with concepts, much of the motivation for that is to simply provide good, useful error messages when those requirements aren't met. Ultimately, the compiler will produce an error message if somebody attempts to instantiate your template over a type that doesn't meet its requirements. The problem is that, as likely as not, the error message won't by very helpful unless you take steps to ensure that it is.

A: The Problem
If you clients can see your internal functions in public headers, and if the names of these internal generic functions are "common", then you may be putting your clients at risk of accidentally calling your internal generic functions.
For example:
namespace Database
{

// internal API, not documented
template <class DatabaseItem>
void
store(DatabaseItem);
{
    // ...
}

struct SomeDataBaseType {};

}  // Database

namespace ClientCode
{

template <class T, class U>
struct base
{
};

// external API, documented
template <class T, class U>
void
store(base<T, U>)
{
    // ...
}

template <class T, class U>
struct derived
    : public base<T, U>
{
};

}  // ClientCode

int main()
{
    ClientCode::derived<int, Database::SomeDataBaseType> d;
    store(d);  // intended ClientCode::store
}

In this example the author of main doesn't even know Database::store exists.  He intends on calling ClientCode::store, and gets lazy, letting ADL choose the function instead of specifying ClientCode::store.  After all, his argument to store comes from the same namespace as store so it should just work.
It doesn't work.  This example calls Database::store.  Depending on the innards of Database::store this call may result in a compile-time error, or worse yet, a run time error.
How To Fix
The more generically you name your functions, the more likely this is to happen.  Give your internal functions (the ones that must appear in your headers) really non-generic names.  Or put them in a sub-namespace like details.  In the latter case you have to make sure your clients won't ever have details as an associated namespace for the purpose of ADL.  That's usually accomplished by not creating types that the client will use, either directly or indirectly, in namespace details.
If you want to get more paranoid, start locking things down with enable_if.
If perhaps you think your internal functions might be useful to your clients, then they are no longer internal.
The above example code is not far-fetched.  It has happened to me.  It has happened to functions in namespace std.  I call store in this example overly generic. std::advance and std::distance are classic examples of overly generic code.  It is something to guard against.  And it is a problem concepts attempted to fix.

A: Always leave it as open as possible - but make sure to

*

*document the required interface and behaviour for valid types to use with your generic code.

*use a type's interface characteristics (traits) to determine whether to allow/disallow it. Don't base your decision on the type name.

*produce reasonable diagnosis if
someone uses a wrong type. C++
templates are great at raising tons
of deeply-nested errors if they get instanced with
the wrong types - using type traits, static assertions and related techniques, one can easily produce more succinct error messages.


text:
Q: Name variables during multiple melt with data.table I have the following data.table that I want to perform a multiple column melt upon:
# Load library
library(data.table)

# Dummy data set
dt <- data.table(a = 1:10,
                 t_alpha = runif(10),
                 t_beta = runif(10),
                 t_gamma = runif(10),
                 s_alpha = runif(10),
                 s_beta = runif(10),
                 s_gamma = runif(10))

# Look at data table
dt
#>      a    t_alpha    t_beta    t_gamma    s_alpha     s_beta   s_gamma
#>  1:  1 0.73315322 0.7777962 0.13258401 0.12841353 0.20865995 0.8967482
#>  2:  2 0.10161042 0.9691244 0.23506277 0.35130324 0.36672933 0.9247026
#>  3:  3 0.95234142 0.7002526 0.07104051 0.85558314 0.39467530 0.8982107
#>  4:  4 0.48967202 0.3951288 0.72376459 0.58978334 0.47201394 0.8508710
#>  5:  5 0.22997537 0.3487354 0.58831312 0.63917860 0.12685815 0.5616682
#>  6:  6 0.01138277 0.0449675 0.79384717 0.28983485 0.98793013 0.6574457
#>  7:  7 0.32324941 0.3446745 0.66394161 0.16357679 0.14828451 0.2019661
#>  8:  8 0.78644407 0.4460397 0.76992857 0.78703793 0.46623055 0.3081812
#>  9:  9 0.90938120 0.4526063 0.47948163 0.03182248 0.63600496 0.3598600
#> 10: 10 0.11345349 0.1732653 0.59240218 0.95541944 0.06640378 0.9475107

So, I go ahead and melt, like so:
# Groups of columns to melt
m <- list(names(dt)[grepl("t_", names(dt))],
          names(dt)[grepl("s_", names(dt))])

# Perform melt
dt2 <- melt(dt, measure = m, value.name = c("t", "s"))

which gives,
# Examine results
dt2
#>      a variable          t          s
#>  1:  1        1 0.73315322 0.12841353
#>  2:  2        1 0.10161042 0.35130324
#>  3:  3        1 0.95234142 0.85558314
#>  4:  4        1 0.48967202 0.58978334
#>  5:  5        1 0.22997537 0.63917860
#>  6:  6        1 0.01138277 0.28983485
#>  7:  7        1 0.32324941 0.16357679
#>  8:  8        1 0.78644407 0.78703793
#>  9:  9        1 0.90938120 0.03182248
#> 10: 10        1 0.11345349 0.95541944
#> 11:  1        2 0.77779618 0.20865995
#> 12:  2        2 0.96912444 0.36672933
#> 13:  3        2 0.70025264 0.39467530
#> 14:  4        2 0.39512877 0.47201394
#> 15:  5        2 0.34873538 0.12685815
#> 16:  6        2 0.04496750 0.98793013
#> 17:  7        2 0.34467455 0.14828451
#> 18:  8        2 0.44603969 0.46623055
#> 19:  9        2 0.45260634 0.63600496
#> 20: 10        2 0.17326532 0.06640378
#> 21:  1        3 0.13258401 0.89674825
#> 22:  2        3 0.23506277 0.92470265
#> 23:  3        3 0.07104051 0.89821074
#> 24:  4        3 0.72376459 0.85087097
#> 25:  5        3 0.58831312 0.56166816
#> 26:  6        3 0.79384717 0.65744574
#> 27:  7        3 0.66394161 0.20196612
#> 28:  8        3 0.76992857 0.30818121
#> 29:  9        3 0.47948163 0.35986003
#> 30: 10        3 0.59240218 0.94751075
#>      a variable          t          s

That's great!
Now, notice an extra column, variable. That corresponds to each of my columns for t and s. Specifically, 1 = alpha, 2 = beta, and 3 = gamma. I can fix this variable as follows:
# Fix variable names
v_names <- c("alpha", "beta", "gamma")
dt2$variable <- v_names[dt2$variable]

producing,
# Examine results
dt2
#>      a variable          t          s
#>  1:  1    alpha 0.73315322 0.12841353
#>  2:  2    alpha 0.10161042 0.35130324
#>  3:  3    alpha 0.95234142 0.85558314
#>  4:  4    alpha 0.48967202 0.58978334
#>  5:  5    alpha 0.22997537 0.63917860
#>  6:  6    alpha 0.01138277 0.28983485
#>  7:  7    alpha 0.32324941 0.16357679
#>  8:  8    alpha 0.78644407 0.78703793
#>  9:  9    alpha 0.90938120 0.03182248
#> 10: 10    alpha 0.11345349 0.95541944
#> 11:  1     beta 0.77779618 0.20865995
#> 12:  2     beta 0.96912444 0.36672933
#> 13:  3     beta 0.70025264 0.39467530
#> 14:  4     beta 0.39512877 0.47201394
#> 15:  5     beta 0.34873538 0.12685815
#> 16:  6     beta 0.04496750 0.98793013
#> 17:  7     beta 0.34467455 0.14828451
#> 18:  8     beta 0.44603969 0.46623055
#> 19:  9     beta 0.45260634 0.63600496
#> 20: 10     beta 0.17326532 0.06640378
#> 21:  1    gamma 0.13258401 0.89674825
#> 22:  2    gamma 0.23506277 0.92470265
#> 23:  3    gamma 0.07104051 0.89821074
#> 24:  4    gamma 0.72376459 0.85087097
#> 25:  5    gamma 0.58831312 0.56166816
#> 26:  6    gamma 0.79384717 0.65744574
#> 27:  7    gamma 0.66394161 0.20196612
#> 28:  8    gamma 0.76992857 0.30818121
#> 29:  9    gamma 0.47948163 0.35986003
#> 30: 10    gamma 0.59240218 0.94751075
#>      a variable          t          s

Created on 2019-08-09 by the reprex package (v0.3.0)
This is my desired result. My question is, can I perform this operation (i.e., renaming of the values in the variable column) during the melt or do I just have to patch it up afterwards?

A: Here is an option in pivot_longer from the dev version of tidyr
library(tidyr)# '0.8.3.9000'
library(dplyr)
dt %>%
   pivot_longer(-a, names_to= c(".value", "variable"), names_sep = "_")
# A tibble: 30 x 4
#       a variable      t       s
#   <int> <chr>     <dbl>   <dbl>
# 1     1 alpha    0.592  0.0634
# 2     1 beta     0.316  0.339
# 3     1 gamma    0.760  0.751
# 4     2 alpha    0.936  0.445
# 5     2 beta     0.232  0.00250
# 6     2 gamma    0.0111 0.406
# 7     3 alpha    0.0950 0.102
# 8     3 beta     0.426  0.775
# 9     3 gamma    0.321  0.811
#10     4 alpha    0.884  0.0526
# … with 20 more rows

NOTE: The values are different as there was no set.seed


text:
Q: Accounting for changing radius of a paper roll to always unroll the same amount of paper So I'm building a Post-Turing Machine that's running a 5-state busy beaver. It has a 300ft roll of receipt paper at each end simulating an infinite tape.
Hypothetically the tape is divided into 'cells.'  So the machine writes or erases a 1 on the tape under the writing head, then the tape shifts either 2" to the right or 2" to the left.
I have a stepper motor (Nema 17) at each end hooked to each roll.
Finally, my question: As you can imagine turning both motors a given number of steps will initially will move the tape evenly 2", however now one roll has 2" more and the other, 2" less. Not such a big difference now but as it goes on one roll could have 500ft and the other 100ft, making the one with 500ft have a much larger radius, therefore turning the motor the same amount will release much more tape...Does anyone know a way to calculate these changing ratios so the motors will always work together in letting out/winding 2" of tape?
(by the way, programed in a counter variable, so "leftMotor = 3600 and rightMotor=3600" if it does a move right then leftMotor=3602 and rightMotor=3598)

A: We can approximate the paper on a roll by concentric circles.  Suppose the inner radius of a roll is $r$, and we have $n$ concentric circles, each of thickness $t$.  Then the total  radius will be $r+nt$, while the amount of paper on the roll will be
$(2\pi (r+t))+(2\pi (r+2t))+\cdots+(2\pi (r+nt))=2\pi (rn + t(1+2+\cdots+n))=2\pi (rn+t\frac{n(n+1)}{2})=2\pi n(r+t\frac{n+1}{2})$
If your controller keeps track of how much paper is on the roll, it can compute $n$ from the previous expression.  From $n$ it can compute the total radius, and from that the circumference. From the circumference, it can compute the angle of rotation to produce the desired length of paper.
Followup:
Let $p$ be the total paper on the roll, $p=2\pi n(r+\frac{t}{2}(n+1))=n^2(\pi t)+n(2\pi r+\pi t)$.  We rearrange to $n^2(\pi t)+n(2\pi r+\pi t)-p=0$.  To find $n$ we use the quadratic formula $n=\frac{-2\pi r -\pi t \pm\sqrt{(2\pi r+\pi t)^2+4\pi t p}}{2\pi t}$.  Since we know $n>0$ we take the $+$ rather than the $-$.  Hence $$n=\frac{-2\pi r -\pi t +\sqrt{(2\pi r+\pi t)^2+4\pi t p}}{2\pi t}$$

A: This sort of thing is commonly handled by making the connection between the motors and the take-up spools with a simple friction-clutch mechanism.
For example, on a cassette tape or real-to-real tape unit...
Both the "take-up" spool (reel) and the "source" spool are driven by a simple friction-clutch mechanism.
The "take-up" spool is slightly "over-driven", and the "source" spool is either slightly "under-driven", or is just controlled by friction (in normal forward operation).
The difference between the speeds of the two spools is accommodated by the friction-clutches, keeping tension on the tape on both spools.
The actual speed of the tape (in normal forward operation) is controlled by a "capstan" that pulls the tape off the "source" spool, and drives (pushes) the tape toward the "take-up" spool.
For cheaper units, there is only one motor that is running at a constant speed (in normal forward operation), and the drive is split to the three points buy multiple belts and pulleys. In this case, the difference in circumference between the "take-up" spool and the "source" spool is compensated for entirely by the friction-clutches. More expensive units might employ multiple variable speed direct drive motors, but usually would still use clutches and capstan drives to control accurate speed and tension.
In your case, the difference in circumference from "full" to "empty" might be too large to be totally compensated for by the friction-clutches because the heat and friction may cause them to wear out too quickly. On the other hand, if the speed is slow enough this would probably work fine.
Since you are using stepper motors for the two spools, you could drive the two spools at different speeds. If you tried to use these motors control the actual paper speed, you would have to have a fairly accurate way to measure the real time diameter of each roll to calculate and control the speed of each motor.
Depending on the paper speed and accuracy required, you could consider using the clutched conections to control tension, and a capstan drive to control accurate speed, and variable speed motors to drive the spools at approximately the correct speed and let the clutches compensate for the minor variations in drive speed.


text:
Q: How to plot this data in matlab? how can i plots in matlab this data
e field in (x,y,z)
       Time / us                E-field (X; -10 -10 -1) [pw]/real
                   0                  1.3767911e-006
      2.8537992e-006                  1.6630072e-006
      5.7075984e-006                  1.1496669e-006
      8.5613976e-006                  1.3562865e-006
      1.1415197e-005                   1.936412e-006
      1.4268996e-005                  1.6920654e-006
      1.7122795e-005                  1.2527399e-006
      1.9976594e-005                  1.5579486e-006
      2.2830393e-005                  2.0703696e-006
      2.5684193e-005                  2.4029719e-006

        Time / us                E-field (X; -10 -12 -1) [pw]/real
                   0                  1.3767911e-006
      2.8537992e-006                  1.6630072e-006
      5.7075984e-006                  1.1496669e-006
      8.5613976e-006                  1.3562865e-006
      1.1415197e-005                   1.936412e-006
      1.4268996e-005                  1.6920654e-006
      1.7122795e-005                  1.2527399e-006
      1.9976594e-005                  1.5579486e-006
      2.2830393e-005                  2.0703696e-006
      2.5684193e-005                  2.4029719e-006

        Time / us                E-field (X; -10 -14 -1) [pw]/real
                   0                  1.3767911e-006
      2.8537992e-006                  1.6630072e-006
      5.7075984e-006                  1.1496669e-006
      8.5613976e-006                  1.3562865e-006
      1.1415197e-005                   1.936412e-006
      1.4268996e-005                  1.6920654e-006
      1.7122795e-005                  1.2527399e-006
      1.9976594e-005                  1.5579486e-006
      2.2830393e-005                  2.0703696e-006
      2.5684193e-005                  2.4029719e-006

       Time / us                E-field (X; -10 -16 -1) [pw]/real
                   0                  1.3767911e-006
      2.8537992e-006                  1.6630072e-006
      5.7075984e-006                  1.1496669e-006
      8.5613976e-006                  1.3562865e-006
      1.1415197e-005                   1.936412e-006
      1.4268996e-005                  1.6920654e-006
      1.7122795e-005                  1.2527399e-006
      1.9976594e-005                  1.5579486e-006
      2.2830393e-005                  2.0703696e-006
      2.5684193e-005                  2.4029719e-006

.
.
.
thank you

A: A = [
               0                  1.3767911e-006
  2.8537992e-006                  1.6630072e-006
  5.7075984e-006                  1.1496669e-006
  8.5613976e-006                  1.3562865e-006
  1.1415197e-005                   1.936412e-006
  1.4268996e-005                  1.6920654e-006
  1.7122795e-005                  1.2527399e-006
  1.9976594e-005                  1.5579486e-006
  2.2830393e-005                  2.0703696e-006
  2.5684193e-005                  2.4029719e-006 ];
plot(A(:,1),A(:,2))

for more, see this.

A: I'm guessing that you're trying to plot the electric field strength at a point in space.  This is what I would try:
    aa = [ 0                  1.3767911e-006
  2.8537992e-006                  1.6630072e-006
  5.7075984e-006                  1.1496669e-006
  8.5613976e-006                  1.3562865e-006
  1.1415197e-005                   1.936412e-006
  1.4268996e-005                  1.6920654e-006
  1.7122795e-005                  1.2527399e-006
  1.9976594e-005                  1.5579486e-006
  2.2830393e-005                  2.0703696e-006
  2.5684193e-005                  2.4029719e-006];

  plot( aa(:,1)*1e6, aa(:,2)*1e6 )
  ylabel('E Field in \mu V/m');
  xlabel('Time in \mu s')

Is this what you're looking for?


text:
Q: Where do I access settings to change the layout and fields of the edit/create new contact dialogue in Outlook 2016? I have Outlook 2016 installed on 2 different computers.
On the first computer, if I try to create or edit a contact, the dialogue looks like this:

On the second computer, it looks like this:

The differences being:

*

*The alignment of the phone fields.

*The address field is a raw text field in the first one and you can
click the Business... button to bring up the Check Address
dialogue, while on the second computer, it is broken up into the
address elements.

Where can I access the settings to customize these fields to switch the Address fields between raw text and address element fields and to change the layout of the phone number fields?