Why do I get TypeError: _this.data.forEach is not a function

Question: I am trying to retrieve data from the backend. These are the relevant parts of my code:
API call
getData(PrimaryId:number):Observable<DataDto[]>{
  return this.httpClient.get(`${this.prefix}/<xyz>/${PrimaryId}/xyz`) as Observable<DataDto[]>
}

Component TypeScript
onRetrieveClicked() {
  this.xyzService.getData(this.PrimaryId).subscribe(
    (xyz: DataDto[]) => {
      this.xyz = xyz
      console.log(this.xyz)
      console.log(this.xyz.forEach((data)=>data.name)
  })
}

First console.log output
{content: Array(1), pageable: {…}, totalPages: 1, totalElements: 1, last: true, …}
       content: Array(1)
       0: {name: max, name: null, asset: null,  …}
       length: 1
       ..........

But when I try to print only the name in the second console, it says that forEach is not a function. How can I solve this
edit
Dto model
export interface DataDto {
name: string
asset: abcDto
status: StatusDto
tasks: efgDto[]
nextDate: string
}

Comment: assumingly you want to call `forEach` for `content` which is present in your data.....
Comment: It seems like the data you get might be a plain object, not an array. It *has* some arrays as values, though.
Comment: I tried accessing it this way.       this.xyz.content.map(data=>data.name)  I get the output but also in the iDE, there is an error saying content does not exist on  type DataDto[]
Comment: `xyz: DataDto[]` is misleading the TS compiler. If you are indeed getting a plain object at runtime, then TS doesn't know that, it *thinks* you are getting an array but it can only check that at compile time.
Comment: Check my answer, it explains entirely what's going on here, and how to fix it using Angular preferred operations.
Comment: Can you please post your DataDto model?
Comment: added the dto model
Comment: its really strange, model that you mention is totally different from what you are receiving in response. In that case how response will convert to model?
Comment: I think there's already a lot of answer to your question, you should accept one. Both Diego and mine's answers fully answer the question asked here. The fact that the 2nd console.log returns undefined is because Array.forEach doesn't return a value, you need Array.map for that.
Answer: The xyz variable that you type as DataDto[], an array, is actually an object. This can be seen in your console.log, an array would be enclosed in [], not {}
is an object --> {
  content: Array(1), pageable: {…}, totalPages: 1, totalElements: 1, last: true, …}
       content: Array(1)
       0: {name: max, name: null, asset: null,  …}
       length: 1
 }

The data you are looking for is most likely the response object's content so add an import for import {map} from 'rxjs/operators'; and transform the data you've gotten from the response:
this.xyzService.getData(this.PrimaryId).pipe(
  map((xyzResponse: any) => xyzResponse.content)
).subscribe(
  (xyz: DataDto[]) => {
    this.xyz = xyz;
    console.log(this.xyz);
    let dataNames = xyz.map(data => data.name);
    console.log(dataNames);
}

I've typed xyzResponse as any but you could ofcourse create a reusable type for it if the API always returns the object with content, pageable, totalPages, ...
Rxjs is the library that Angular uses to handle asynchronous programming, such as HTTP calls or component events. Rxjs chains asynchronous manipulations together in a pipe (hence the .pipe call). Inside of this pipe rxjs expects a chain of operators that will perform operations on the asynchronous data, one by one. The map operator takes the input value and returns a new value so that the value you subscribe to has been transformed from the HTTP response to the .content field of the HTTP response.
Working in this way fixes all TypeScript compiler errors and allows you to chain additional calls later, like retrying if the API times out, or catching errors, or merging in other HTTP calls.
Comment: it returns undefined
Comment: What does? The 2nd console.log? That's your code, but yea it'll print that, because forEach doesn't return a value :p
Comment: If you want to see each data.name use this: `this.xyz.forEach((data)=>{console.log(data.name)})`
Answer: It seems that your this.xyz is not an array, but has an array property called content, you should modify your response object in order to accept it.
You can check if your objects are arrays with the following method
Array.isArray(obj)

Update your code to this.
this.xyzService.getData(this.PrimaryId).subscribe(
  (xyz: NewObject) => {
    this.xyz = xyz
    console.log(this.xyz)
    //If you have doubts of what is comming is nice to check if your property is an array
    if(Array.isArray(this.xhy.content) {
        console.log(this.xyz.content.forEach((data)=>data.name) });
    }
}

Create a new object in order to support your response
class NewObject {
    content: Array<DataDto>
    // other values here
}

Another approach is like @Robin says in the comment
this.xyzService.getData(this.PrimaryId).subscribe((xyz: {content: DataDto[]}) =>
        {
        this.xyz = xyz
        console.log(this.xyz)
        //If you have doubts of what is comming is nice to check if your property is an array
        if(Array.isArray(this.xhy.content) {
            console.log(this.xyz.content.forEach((data)=>data.name) });
        }
    }

Comment: Well if you wanna cut corners you could just do: `.subscribe((xyz: {content: DataDto[]}) => {console.log(xyz.content.forEach((data)=>data.name))})`
Comment: error TS2339: Property 'content' does not exist on type 'DataDto[]
Answer: It's because you are trying to loop through an object instead of array
I think you can try this:
console.log(this.xyz.content.forEach((data)=>data.name) })

Comment: error TS2339: Property 'content' does not exist on type 'DataDto[]


Unable to pass an argument to a python script invoked by a Tkinter Function

Question: I am not able to invoke another python script in a function defined for a button created in Tkinter.
Here the code:
import subprocess
from Tkinter import *

def select (hf):
   subprocess.Popen("<MyScript.py> hf")

root = Tk()

var_hf = StringVar(root)
var_hf.set('Default')

option_hf = OptionMenu(root, var_hf, *["A", "B", "C"])
option_hf.pack()

button = Button (root, text = "Select", command= lambda: select(var_hf.get())
button.pack()

root.mainloop()

When I press the Button "Select", I get an error stating that "hf" is not recognized as a valid variable (the "hf" is called as an argument of MyScript.py).
Do you know why the function associated to the Button is not able to assign to "hf" the value taken by var_hf.get()?
Thank you in advance,
G.
Answer: You are literally passing the string "hf" to <MyScript.py>. I'm guessing that's not what you intend to do. A simple solution is to do this:
subprocess.Popen("<MyScript.py> %s" % hf)


Ever Ascending Melody

Question: I once heard of a melody that, when played, sounds like it is always ascending. Is that a thing? Please explain.
Comment: You are probably thinking about the "Shepard tone" https://en.wikipedia.org/wiki/Shepard_tone
Comment: *Shepard tone* should be the answer.
Comment: It's not that tune about a lark, is it...
Answer: Shepard tones (as noted before) are an example.

https://en.wikipedia.org/wiki/Shepard_tone
Basically, one plays 12 tones (fundamental and 11 overtones) for each note. Eleven of the tones move up a semitone and the other one moves down 11 semitones.

Ever Ascending Melody


Basic Multiple Image Upload to replace standard image uploader

Question: First question on Drupal Answers, hi everyone.
Starting off with a very basic question actually:
While the standard single image at a time uploader is swell and all, I've got the Galleria module installed, and we have hundreds of photos to upload across multiple albums, and a ton more to come along in The near future. Quite simply is there an existing package/mod that can transform that single image uploader into a multiple image uploader, One where you can select multiple images in the browse window?
Answer: The best multiple image uploader that I have found is http://drupal.org/project/plupload (example widget is on their website)
Also if you are working with images and are using drupal 7, you may also wish to check out http://drupal.org/project/media - this modules is looking more and more promising, and now has views integration as well. It also works with the above recommended plupload module)
Comment: Try using this module as well http://drupal.org/sandbox/vingborg/1138512 - according to the README http://drupalcode.org/project/plupload.git/blob/refs/heads/master:/README.txt - plupload only provides a form element
Comment: I seem to have issues getting plupload configured. Its installed and enabled, but i cant find any clear cut english documentation about getting it to run on my D7 installation, especially to replace the Image field :\ Its the only module ive installed that i honestly have no clue what to do with lol
Answer: Plupload does not work on its own. I suggest using a combination of Multiupload Filefield Widget and Multiupload Imagefield Widget. This is as close to the core as possible. It will allow you to hold Ctrl + select files, to upload multiple files.
Once the modules are installed, simply change the Widget Type of the image field to Multiupload.
Comment: Been over a year, but do you know how to make it so that the multiupload images show a preview of the image like the standard image upload does?
Answer: You may try File Resumable Upload:
File Resumable Upload aka file_resup adds large files multiple and resumable upload to the File and Image field widgets.


How to manage the incomplete features in Azure repos

Question: I'm new to DevOps and want to know how to manage the project in Azure Git repos.
I have chosen the Trunk based branching strategy for the development, where we will have the main branch, feature branches, release branches, and bugfix branches (to fix bugs in the releases).

1. Feature management:
As Continuation integration says we need to commit our changes to the main branch at least once a day so how to manage incomplete feature branches and what are the best practices?
I'm aware of the feature toggle/flag concept, but Is there any other option than the feature toggle?
2. Release management:
How to create Release branches only with the complete feature if the main branch also contains incomplete features?
Thanks.
Comment: Why does your CI say you need to "commit once a day".
Comment: I don't know where you got this image from but **never** merge incomplete features in the master branch.
Comment: You can see this link: https://cloud.google.com/architecture/devops/devops-tech-trunk-based-development#how_to_implement_trunk-based_development
Comment: To best honest I disagree with the point "Merge branches to trunk at least once a day.". You should commit and merge often and fast, but after the small feature/fix is finished. Commiting half-finished work is not good at all. (I think they mean this, but phrased this sentence a little wrong)
Answer: You are correct that CI is about merging your branches to your mainline branch at least once a day. Jez Humble created a slightly jokey certification process for CI. You just need to be able to answer yes to 3 questions.

Do all developers merge their code to the mainline branch at least once a day?
Do you have a process for validating that the merge hasn't broken anything? (build and test)
If the merge has broken something, is it fixed or reverted within 10 minutes?

If you can answer yes to all 3 questions then you are doing CI. If you can't answer yes to all 3 then you're doing something, but it isn't CI. Unfortunately tooling vendors have muddied the waters by calling build tools "CI Tools" so a lot of folks think that if they have an automated build then they are doing CI. But that's only relevant to question 2
In addition CD says that your mainline branch should always be releasable. So you should be able to push the code in the mainline to prod at any time, and not worry about it.

This philosophy of keeping the mainline in an always-releasable state is the central tenet of Continuous Delivery.
https://martinfowler.com/articles/branching-patterns.html#release-ready-mainline

Which leads us to your question.
The short answer is, you don't use branches to manage feature availability or release management. You use feature toggles! It's a big subject but there are 2 obvious things to focus on.

Do you have sufficient test automation to answer question 2 above. I.e if your build passes, are you confident that the code "works"
Feature flags / toggles.

There are different types of Feature Toggle and you're need seems to be release toggles. This is a technique where you hide features behind a toggle so that they can be active or dormant depending on the environment.
That way you can have code paths that are only available in development / test environments but that functionality is hidden from the users in production. Once the development of the feature is complete then you can flip the toggle in production and users can now see the new feature.
Essentially what you're trying to do is decouple Deployments and Releases. Where a Deployment is "installing and configuring software" and a Release is "Making new functionality available to customers, including potentially spending a bunch of money of Marketing"
In very very basic terms you're sticking your new feature behind an "if" statement and pulling in a value of true or false from an external datastore of some kind which can be updated without the need for a deployment. For release toggles, these if statements tend to be transitory, so once the feature is released you need to go and clean up the code.
Other types of toggle might be longer lived. you might have a toggle thats based on "is the customer paying me extra money" in which case that toggle will exist until the feature is retired or becomes part of the base product.
There are some tools which can help with Feature toggles. Launch Darkly is quite popular for example.
AS I said, it's quite a broad topic, but most teams I've worked with have found that it's worth the investment as it can simplify the branching strategy significantly and give them a safety net when experimenting with new functionality.
Comment: Thanks, James. Is there any other option to handle incomplete features instead of the Feature flags?
Comment: There are 2, I think. 1. Break your features down in to very small "stories" that can be delivered incrementally so that stuff can be considered "done" in a smaler time frame, you should do this anyway but Toggles will still help here. 2. Abandon CI and have long lived branches with painful mega merges once the feature is delivered. Not recommended but it will solve the problem. It will give you other problems though, merge pain and integration testing pain being the main ones
Comment: Thanks, James. We will go with Feature flags.


node aliased path as views contextual filter

Question: I want to have a view which would output a node title and use a contextual filter the aliased path of a node
/nodefilter?url=/category/path-to-article

I see there no php contextual filters in drupal 8 anymore do I have to write a custom contextual filter or is there another solution ? Any help will be greatly appreciated
Answer: First I have created a view that uses contextual filter content ID to filter the results by "node id" and can be called like this
/nodefilter/[NID]

After I made sure the view was working I modified the content ID contextual filter adding default query paramenter named url under WHEN THE FILTER VALUE IS NOT AVAILABLE > Provide default value

then in a custom module used the views api hook_views_pre_view as follows
use Drupal\views\ViewExecutable;
function MODULENAME_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if($view->id() == 'view_machine_name'){
    $url = \Drupal::request()->query->get('url');
    $path = \Drupal::service('path.alias_manager')->getPathByAlias($url);
    if(preg_match('/node\/(\d+)/', $path, $matches)) {
      //$node = \Drupal\node\Entity\Node::load($matches[1]);
      //$nid = $matches[1];
      $args[0] = $matches[1];
    }
  }
}

Now the view works with NID or the url parameter
/nodefilter/[NID]
/nodefilter/?url=/category/path-to-article


Creating a tip for responsive background image

Question: At start, it's a very generic question, so all replies will be welcome.
So, I have some design, full page background, and some text, which will be html text. And this text is connected, using white line, and this white line points to red dot. I think, red dot will be positioned absolute, but then some questions arrive:
It's responsive view, so when resizing, background image will change width, so red dot should follow this pointed area (is this possible ?)
Also, I'm looking for a way to connect this red dot with html exmplanation box.
I have searched, but could't find anything, that suits my needs.
Also, I'm not expecting that anybody will write full code for me--but I need some clues, how to start this ...
Comment: Have you tried anything yet? What kind of Google terms did you enter? I can image 'responsive tooltip plugin' could give quite a lot of results which could inspire you? In any case, it doesn't seem to be very difficult: with some jQuery code and perhaps a plugin you should be able to get this working without a huge effort.
Comment: Here's something I was playing with a while ago, it's close to what you need, I think http://jsfiddle.net/link2twenty/yuo8s0xz/
Comment: I dint know, how to title this correctly, and your rwd tooltip pluign sounds great. Ill check, thanks.
Comment: @MarekBrzeziński Did you see this: http://www.inabrains.com/tooltip/examples/image-hotspot.html
Comment: Yes, nice, but i need something which works not using hower, but all times visible...
Comment: This one is closer, 'ill try to personalise this and i tell you, if this works, because in my opinion, its worth to know this technique.
http://www.jqueryscript.net/demo/jQuery-Plugin-To-Connect-HTML-Elements-with-Lines-HTML-SVG-Connect/
Answer: You can design it for a large screen (for example 1440 wide pixels) and then scale with CSS depending on the percentage you need. You can make a js function to this purpose:
(Note that's only an example)

function resizeMe() {
  var initialHeight = 1440;

  var displayHeight = $(window).height();
  var percentage = displayHeight / initialHeight;
  $(".your-element").css("transform", "scale("+percentage+")");
}
$(function() {
  $(window).bind('resize', function() {
    resizeMe();
  }).trigger('resize');
});
.your-element {
  background: url(http://dummyimage.com/1440x768/000/fff&text=Big+Image) top left no-repeat;
  background-size: cover;
  width: 100%;
  height: 100%;
}
body,html { height: 100%;margin:0; }
.text {
  position: absolute;
  top: 230px;
  right: 20px;
  height: 100px;
  background: white;
  border:1px solid black;
  color: black;
  padding:10px;
}

Lorem ipsum dolor sit amet

Comment: This method allows you to scale all the content inside. If you achieve the white line to connect the box with the dot all your content will be resized. I don't know how to achieve it without canvas.
Comment: Il will use / test this for red dot item. And now, i will need to archive conencting line effect....


jQuery switch class to change css background

Question: I'm building a web page that shows photos full screen and want to offer users to the ability to switch the background color between black and white using a simple set of links:

White

Black

body.white { background: #f0f0f0 url('white.png'); }
body.black { background: #222222 url('black.png'); }

The plan is to show which one is currently selected using a class of current and when clicked will fade in and out the different color scheme. can anyone help?
EDIT: Just to confirm I want to switch the class on the body and not just change the CSS of background color.
Thanks
Comment: you want an *animated* background color change, or just change the background color?
Answer: You can do like this:
$('#switch li').click(function(){
  $('body').css('background', this.id);
  $('#switch li').removeClass('current');
  $(this).addClass('current');
});

Above code applies background color to body (you can replace if element is some other one) when an li is clicked (you can use links instead). Also the current class is removed from all lis and then applied to clicked one.
Comment: How would I change the class of the body though?
Comment: More elegant solution here. Why do you need to change the class of the body? What would that accomplish?
Comment: because I have a background texture as well
Comment: @Cameron: Notice the line in my answer: `$('body').css('background', this.id);` Also make sure to wrap your code in jquery ready handler.
Answer: If you would like to use classes instead of just changing css...
$('#switch li').click(function(){
  $('body').removeClass('white black').addClass(this.id);
  $('#switch li').removeClass('current');
  $(this).addClass('current');
});

Answer: $("#white").click(function() {
    $("body").css("background", "white")
});

$("#black").click(function() {
    $("body").css("background", "black")
});

Comment: Your elegant solution does not take care of current class. Also no need to assign two click handlers, one can be used.
Answer: There's actually an easier way than having two different lis.
For whatever your background element (#back) is, on clicking something with an id of "switch":
$('#switch').click(function() {
  a = $('#back').css('background');
  if (a == 'black') {
  $('#back').css('background','white');
  }
  else {
  $('#back').css('background','black');
  }
});


Type does not name a type or error: field has incomplete type

Question: Im not sure why I am getting this error..."error: field 'config' has incomplete type". I have tried to do forward declaration and including the headers using #include...Im just trying to include fConfig in fInstance...
#ifndef FINSTANCE_H
#define FINSTANCE_H

//#include "fConfig.h"
#include <vector>
#include <sys/types.h>
#include <string>

using namespace std;

class fConfig;

class fInstance
{
public:
    pid_t pid;
    fConfig config;
    vector<string> notes;
    vector<time_t> times;

    fInstance();
    virtual ~fInstance();
};

#endif // FINSTANCE_H

#ifndef FCONFIG_H
#define FCONFIG_H

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <fcntl.h>
#include "JWDSFork.h"
#include "fInstance.h"

using namespace std;

class fConfig
{
    private:
        pid_t pid, w;

    public:
        pid_t cPid;
        string name;

        int group;
        int instanceId;
        int numInstance;
        int tries;

        bool reply;
        bool debug;
        bool service;
        bool currentlyRunning;

        time_t startTime;
        time_t endTime;

        string path;

        fConfig();
        virtual ~fConfig();

        void start();
        string intToString(int);
        char* stringToChar(string);
};

#endif // FCONFIG_H

EDIT: Added changes
#ifndef FINSTANCE_H
#define FINSTANCE_H

#include "fConfig.h"
#include <vector>
#include <sys/types.h>
#include <string>
using namespace std;

//class fConfig;

class fInstance
{
public:
    pid_t pid;
    fConfig* config;
    vector<string> notes;
    vector<time_t> times;

    fInstance();
    virtual ~fInstance();
};

#endif // FINSTANCE_H

#ifndef FCONFIG_H
#define FCONFIG_H

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <sstream>
#include <string>
#include <cstring>
#include <sys/types.h>
#include <fcntl.h>
#include "JWDSFork.h"
//#include "fInstance.h"

using namespace std;

class fConfig
{
    private:
        pid_t pid, w;

    public:
        pid_t cPid;
        string name;

        int group;
        int instanceId;
        int numInstance;
        int tries;

        bool reply;
        bool debug;
        bool service;
        bool currentlyRunning;

        time_t startTime;
        time_t endTime;

        string path;

        fConfig();
        virtual ~fConfig();

        void start();
        string intToString(int);
        char* stringToChar(string);
};

#endif // FCONFIG_H

Answer: You need to add #include "fConfig.h" in fInstance.h and you don't need to include fInstance.h in fConfig.h because it appears that you are not using the type fInstance in fConfig.h.
When you forward declare a type compiler doesn't know the memory layout of that type and so it treats the type as an Incomplete type & the compiler cannot do any operations for which it needs to know the memory layout of that type.
You create an instance of fConfig after forward declaring it, to do that compiler needs to know the memory layout of fConfig but since you just forward declared it, it doesn't know that and hence complains.
Comment: @JonH: Did you try the solution in the first para of the above answer?
Comment: @Als yes then it tells me that 'fConfig' does not name a type
Comment: @JonH: I don't think you did what is said, Please check again.Only `fInstance` needs to include `fConfig`, `fConfig` does not need to include `fInstance`.
Comment: @Als I took out the `#include "finstance.h"` declaration in fConfig and uncommented `#include "fConfig.h"` in finstance...
Comment: @Als so if I include fInstance.h in another header and need to access its members - how would I do that?
Comment: @op: Forwarding declarations are useful when you are only using references or pointers to that datatype. Since you are using complete instances, you need the complete definition.
Comment: @Als so creating the instance is using new? i thought that calling fConfig config declared an instance?
Comment: @Spidey how do I fully declare this instance?
Comment: @JonH: It declares an member to the class, but the compiler needs to estimate the amount of memory that will be needed to store an object of type `fConfig` inside `fInstance`.How does the compiler know how much memory `fInstance` object will need? By summing up memory needed for all members of `fInstance`, so..
Comment: @Als so am i supposed to do something  `fConfig * config;`???? and if so how do I access the members of that class in cpp?
Answer: You need to put the full definition of fConfig before that of fInstance. The forward declaration won't do because your fInstance has an fConfig data member, so the full type is necessary:
in fConfig.h:
#ifndef FCONFIG_H
#define FCONFIG_H

class fConfig {
  // as in original
};

#endif

in fInstance.h:
#ifndef FINSTANCE_H
#define FINSTANCE_H

#include "fConfig.h" // need to include to get full type

class fInstance {
  // as in original
};

#endif

Comment: ok what does the full definition mean...do i need to use new?
Comment: @JonH no, not at all. Just put all the `fConfig` stuff before `fInstance`, and remove the `fInstance.h` include from `fConfig.h`.
Comment: am i declaring it outside the scope of the class?
Comment: when i do that it says that fConfig does not name a type
Comment: @JonH you must be doing something else wrong. What I suggested compiles, see http://ideone.com/0ndpx
Comment: how does this work when there is no declaration of fConfig in fInstance? did you comment out `#include "fConfig.h"` for use with ideone?
Comment: @JonH I commented it out because in the ideone sample the `fConfig.h` code is already pasted in. If I hade separate header files, I would have left that include uncommented.


Calcular o fatorial por passagem de referência

Question: Estou estudando ponteiros estou tentando fazer o cálculo de um fatorial de um numero, só que o resultado sai um valor totalmente diferente do esperado.
Aqui está o meu código
#include<stdio.h>
#include<stdlib.h>

void calulcafatorial(int num, int *fatorial);

int main(void)

{
     int num, *fatorial;
     scanf("%d", &num);
     calulcafatorial(num, &fatorial;
     return 0;
}

void calulcafatorial(int num, int *fatorial)
{
   int fat;
   for(fat = 1; *fatorial > 1; *fatorial--)
   {
      fat *= *fatorial;
   }
   printf("%d\n", fat);

}

Answer: Vou responder o que importa já que o problema só existe por causa de outro problema.
Estude ponteiros do jeito certo. Este caso não é para usar ponteiros e por isso tudo fica confuso. Até dá para fazer funcionar assim, mas não será o certo.
Funcionar e certo são coisas distintas.

Assim funciona:
#include<stdio.h>

int calculafatorial(int num) {
    int fat = 1;
    while (num > 1) fat *= num--;
    return fat;
}

int main(void) {
    int num;
    scanf("%d", &num);
    printf("%d", calculafatorial(num));
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Mantive o erro de sintaxe que permitia compilar, mas consertei o que impedia a compilação. Tirei a impressão da função porque ela calcula o fatorial e não calcula e imprime o fatorial.
É, eu sei, tirei o ponteiro que era a dúvida central, mas neste código o uso do ponteiro só serve para atrapalhar. Agora procure algo que precise de ponteiro para aprender certo. Ponteiro é difícil, só use quando realmente não tem solução melhor.
Answer: Cálculos Fatoriais envolvem Números Muito Grandes, e isso deve ser levado em consideração pois na prática, a memória disponível é sempre finita.
Códigos mais robustos são capazes de filtrar as entradas que produzam saídas "incalculáveis" devido as limitações da memória da máquina.
Levando o seu raciocínio em consideração, podemos implementar uma função para cálculo fatorial capaz de retornar um erro caso a entrada seja inválida ou incalculável, por exemplo: n < 0 ou n > 20.
O maior número capaz de ser armazenado em uma variável do tipo unsigned long long é 18.446.744.073.709.551.615.
O fatorial de 20 pode ser perfeitamente armazenado em um unsigned long long pois:
20! =  2.432.902.008.176.640.000 < 18.446.744.073.709.551.615
Já o fatorial de 21 extrapola a capacidade de armazenamento de um unsigned long long pois:
21! = 51.090.942.171.709.440.000 > 18.446.744.073.709.551.615
Levando seu raciocínio em consideração, segue um exemplo:
#include <stdio.h>
#include <stdlib.h>

int fatorial( int n, unsigned long long * f )
{
    /* Verifica se o calculo eh possivel*/
    if( n < 0 || n > 20 )
    {
        return -1;     /* retorna -1 em caso de erro */
    }

    *f = 1;

    while( n > 0 )
    {
        (*f) *= n;
        n--;
    }

    return 0; /* retorna 0 em caso de sucesso */
}

int main( int argc, char ** argv )
{
    int num = atoi(argv[1]);
    int ret = 0;
    unsigned long long fat = 0;

    ret = fatorial( num, &fat );

    if( ret < 0 )
    {
        printf( "Erro!\n" );
        return 1;
    }

    printf("%d! = %llu\n", num, fat );
    return 0;
}

Saídas:
$ ./fatorial 5
5! = 120

$ ./fatorial 10
10! = 3628800

$ ./fatorial 15
15! = 1307674368000

$ ./fatorial 20
20! = 2432902008176640000

$ ./fatorial 21
Erro!

$ ./fatorial -1
Erro!


Is it possible for this function to have a negative value?

Question: I have a function $f(x)=(b-1)x+1$ where $b\geq0 $ and $0<x<1$. I want to know is it possible for this function to have a negative value?
Answer: No, it is not, because $$f(x)=bx+(1-x)\geq0.$$
Answer: No, because it is a linear function, thus:
$$f(0)=1>0 \ \ \text{and} \ \  f(1)=b\ge0$$
Answer: $b\ge 0$ and $x>0$ so $bx\ge 0$
$0 <x <1$ so $-x +1>0$
So $(b-1)x+1=bx -x +1> bx \ge 0$.


AngularJs, replace text pattern with DOM-object

Question:

 initial text

 initial text

    <button ng-click="actionme()">generate</button>
    <button ng-click="copyme()">copy</button>

Content of div'txt_select' need to be generated by some "document template string": Apple is %%red|green|not an orange%%.
User have to see in place of %%red|green|not an orange%% combobox with this three options in dropdownlist. And as result in 'txt_output' there need to be simple text with user selected item: "Apple is not an orange".
How i can do textreplace-magic with angular? Generated combobox must be able to can use all (or most) angular features.
//yes, i'm noob)
//edit reason: replaced <textarea> with

Comment: Please post the code you have tried so far.
Comment: first you don't declare a controller so this will be a problem. second you should use ng-model in the textarea to  bind the value of the textarea with a variable in the scope
Comment: if i only know what i can and should do then i will just write code and not bother anyone))
Answer: Since there are more than two options I would suggest you to set it in the controller. But if you want to do a replace in the html itself, then
you can use the following if it is in "if else" format:
{{ ifOrangeOrNot ? Orange : Green }}

Let the default text be "This is not an orange".
Hope this helps.
Comment: i think your answer if totaly wrong. ng-class add a class according to a bool expression, he want to put text inside the text-area. use ng-model for this
Comment: i don't want simple text manipulation. I need create objects and somehow bind them to angular.
Answer:
first you don't declare a controller so this will be a problem.
second you should use ng-model in the textarea to bind the value of
the textarea with a variable in the scope

a little example her http://plnkr.co/edit/Zea3zZqaagDdO4s8pZRC?p=preview
in the html:
     <textarea ng-model="text"></textarea>

in the controller :
     $scope.text = 'param01 : value01\nparam02 : value02\nparam03 : value03\nparam04 : value04\nparam05 : value05\nparam06 : value06\n';

Comment: Well, i discovered that textbox even not able use ,. So combobox insertion also impossible. Edited question with `contenteditable=true`


How can I determine the last user who logged on to each PC on our domain?

Question: We have a network of primarily Windows 7 (and Windows 8.1) PCs, and we'd like to be able to report on who is the most recent person to have logged on to the various hosts.
We've got SCCM in place; however, that seems to give reasonable "last logged on" times, but we know that the "last logged on user" is a comparative work of fiction.
Is this a known problem with SCCM, or is there something we need to tweak to improve its accuracy? Better still, is this something we can query via LDAP (for example, using OPENQUERY from SQL Server)?
Answer: There's no central store of user logins in Active Directory, so you can't just slap together an LDAP query for this information.
Regarding SCCM, you might be running into this issue - check the query being run by your last logged on user report - but if not, the easiest solution is probably going to be some variant of a logon script that records the user name, time/date and machine name somewhere.

The query in question was accessing the User_Name0 field in the v_R_System view.
In case you are not aware v_R_System.User_Name0 is only updated during the last Network Discovery or Heartbeat Discovery.
So I always recommend using v_GS_COMPUTER_SYSTEM.UserName0 as this is updated when hardware inventory runs.
Now most places run their hardware inventory more frequently than their Network or Heartbeat discovery, hence my recommendation.

The SCCM tweak, of course, would be to run a query on the most up-to-date user name field, as well as possibly adjusting your SCCM settings so that the user name field you do use is updated more frequently.


Staccato quarter note versus an eighth note

Question: Well on my piano piece, my right hand needs to play a staccato quarter note and at the same time my left hand plays an eighth note...  so which one would you play longer?
right hand is playing 4 quarter notes staccato in the measure while the left hand is playing 8 eighth notes.
I am late elementary...  if I sort of just tap the staccatos, making them even shorter than the eighth notes...  should I try to time the tap of the stacatto into the center of the sound of eighth note...  or else start them both at the same time?
Comment: A good question to pose to the composer - who must have had  a particular feel in mind to write it as such. Is he still alive? What piece is it? Can you post a copy?
Answer: The one certain part of this question is that both notes START at the same time.
Then we get into a less black-and-white area.   If the composer had wanted both hands to play notes the same length he could have written the RH as eighth notes and rests. A staccato quarter is generally rather longer than an eighth. It could help to think of the LENGTH of the quarters, not their shortness.
Answer: The eighth note can have at most 50% of the duration of the quarters, while a staccato quarter should be played like an eighth note or longer.
Now, as a notation, staccato quarter = an eighth note doesn't make sense, so you'd probably shorten them to 60-70% of their actual legato duration.
Attack simultaneously with the eighths, release after the second quaver.
Ex.
Imagine you play l.h. the boogie bass line GBDE FEDB  legato quavers and r.h. G7 repeated block chords staccato quarters.  Because of the repetition of playing the same keys the quarters could be possibly played portato (ca. 80%). But the staccato will be shorter than portato and similar or longer than the quavers: In a notation program you can choose the duration of staccato values. A duration between 50-80% seems to be appropriate.
Comment: I disagree, and further the note lengths are highly dependent on the genre of music in question and the mood of the section in particular.
Comment: All information I could find are teaching the reduction of the note lenth is not more than 50%.  But I'd agree with the deleted answer by Alan: *The staccato "feel" is a very brief bounce on the note with a sharp decay after the attack. "Staccato" is better defined by the "feel" of the articulation, rather than strict note durations.*
Answer: The quarter-notes all start on the beat, so the starts will be | both, 8th, both, 8th etc.
The length you should hold the staccato quarter-notes isn't absolutely fixed. I suggest you try playing the right hand on its own and see what sounds best, then combine that with the left hand. By the way you did not specify that the left hand is playing legato (smoothly). If the left hand is staccato I would consider ending the notes in both hands together. ie |Both down, both up, Ldown, L up, etc
Answer: Best way to do this, practice separate hands.
Make the eighth notes EXACT eighth notes. With the staccato quarter notes, play them the way you feel they should be, they way that sounds to you like a staccato quarter note.
After much practice of separate hands, practice putting the hands together. And make sure that it sounds as it sounded when they are separate.
Answer: Start at the same time.
Ask yourself: how would you play the right hand line if it were the only one? You'd play each quarter note on the beat. So, why should that change because of what the left hand plays?
Comment: So which one is longer duration?
Comment: The duration of a staccato is to some extent a matter of personal style, but it doesn't depend very much on the tempo. It's "hit and go", so at a medium tempo a staccato quarter note will be shorter than an eight note.
Comment: Yes you most certainly adjust each staff's timing to merge with the other staff.


Calls to system() do not behave the same way as in command prompt (cmd)

Question: I need to cut&paste a folder into another folder through code in C++. But some directory names are problematic, such as the ones which have japanese symbols. However, the same commands introduced through cmd all work fine.
system("move dirName dirName2");      //work
system("move ディレクトリ dirName2");     //does not work (system cannot find the specified file)
system("move ディレクトリ.txt dirName2"); //work

Funny enough, if the item which has the japanese symbols is a file and not a folder, the operation works fine even using calls to system().
I have no idea why the second call to system() does not work or how to solve it.
PS: I'm working with Windows7.
Answer: "move dirName dirName2", it is a const char* type, while the Japanese chars are not ASII chars, you should use the unicode API here, try:
_wsystem(L"move ディレクトリ dirName2")

Answer: It is likely that you need to use _wsystem instead to accomodate the wide characters.  See the relevant MSDN pagefor details, but the syntax of the call is the same.


Add custom attribute to an external JS script

Question: It's not really clear how to add custom attributes when adding an external JS script to the page.
Currently I have this code:
drupal_add_js('https://code.jquery.com/jquery-3.4.1.js', array('type' => 'external'));

How can I add an integrity attribute to the rendered script tag?
The rendered script should look like this:

I know this post exists, but I'm not able to use that solution since the source is loaded externally and I will not be able to check on the source.
Answer: I solved the problem using drupal_add_html like this,
$data = array(
  '#tag' => 'script',
  '#value' => '',
  '#attributes' => array(
    'src' => 'https://code.jquery.com/jquery-3.4.1.js',
    'integrity' => 'sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=',
  ),
);
drupal_add_html_head($data, 'unique_key');

Comment: How to even use drupal_add_html ? is this a module which needs to be installed or what ???


Conditions on distributions which guarantees smaller average distance

Question: Suppose there are two CDF's $F$ and $G$ whose common support is $[0,1]$, and pdf $f$ and $g$, respectively. If distances are measured in squared differences. What kind of condition would guarantee the following inequality?
$$\int^1_0(x-y)^2f(x)dx\leq\int^1_0(x-y)^2g(x)dx,~\forall y\in[0,1].$$
Answer: I don't think that there can be a general solution to this question, because it is much to brought. Nevertheless, let us consider which distribution would maximize the integral:

For $y\lt 0.5$ the $\delta$-distribution $\delta(1)$ maximizes the integral.
For $y= 0.5$ both $\delta$-distributions $\delta(0)$ and $\delta(1)$ maximize the integral.
For $y \gt 0.5$ the $\delta$-distribution $\delta(0)$ maximizes the integral.

This arguments shows, that skewed distribution will "in principle" yield larger integrals then symmetric distribution (not a mathematical statement). However, this is only true for "half" of the $y$-intervall. Hence, we should demand, that both functions $f(x)$ and $g(x)$ be symmetric with respect to $x=0.5$.
The above argument shows as well, that $g(x)$ should have two maxima, which lie at $x=0$ and $x=1$, while $f(x)$ should have only one maximum at $x=0.5$. Furthermore,

I would expect that if $f(x)$ and $g(x)$ have the same "functional form", than the statement is true. By "functional form" I mean if $f(x) = Norm(0.5, \sigma^2)$ then $$g(x) = \big\{\big.
\begin{matrix}
 Norm(0,\sigma^2) \; \textrm{, if $x\le 0.5$} \\
 Norm(1,\sigma^2)\; \textrm{, if $x\gt 0.5$}
\end{matrix}
$$
Of course the normal distribution does not integrate to one on $x\in [0,1]$, so we would need to include a normalization factor.
Furthermore, I would expect that $g(x)$ "likes" to have a small variance. Hence, we obtain $\delta$-distributions in the limit $\sigma^2 \to 0$.

If have not performed any calculation to verify this intuition.


One amplifier, two different instruments

Question: I have a keyboard and a Tagima Dallas guitar. I want to buy an amplifier, but just one. I have been advised that an amplifier for a guitar is not good for a keyboard, and the same about a keyboard one for a guitar.
My question is why. I know amplifiers have a lot of resources, but I'm not a professional and amplifiers aren't cheap. Do I really need to buy two of them?
Comment: What style of music?
Comment: Keyboard amps sometimes have piezoelectric horns, you will blow these out with heavy guitar distortion if that's an issue.
Comment: Rock, Pop and romantic songs
Answer: For Acoustic Guitar
You probably can do a reasonable job using a keyboard amp with an acoustic guitar.  You may need a pre-amp pedal (or similar) to boost the signal from your guitar in order to use it with a keyboard amp, and you may want to adjust the equalization when switching between guitar and keys, but other than that, acoustic guitars often sound good through keyboard amps.
Going the other way, some dedicated acoustic amps will have a less flat response, and thus might affect how the extremes of the keys sound.  In addition, there is some risk that lower bass sounds may overextend the speaker, damaging the amplifier.  For this reason, I'd avoid using a guitar amp for keys (or bass guitar for that matter), unless you can confirm that a given guitar amp will be robust against bass notes from your keys.
For Electric Guitar
Optimally, yes, you want separate amp setups for the keys and guitars.
user20352's answer correctly indicates that guitar amps (for electric guitars) typically significantly color (modify) the guitar's sound.  Without this coloration, electric guitars sound thin.  Since keyboard amps don't provide this functionality, you need to add external effects into the signal chain to provide the color, prior to (effectively uncolored) amplification by a keyboard amp.
One option where you would not need to by two separate amps is to get a full-range high fidelity keyboard amp, and use an external effect that includes amp simulation in the input chain for the electric guitar sound.  Thus you'll still need extra equipment in order to get full guitar tones.
Many multi-effects units, Line-6 pods, Vox tone lab, Axe-FX etc. have these kinds of amp simulation capabilities, and can be used only with a power amp (which is what most keyboard amps behave like).  In addition there is at least one manufacturer of dedicated pedals for this purpose, Tech21 (Sansamp and related pedals).  Finally, one may find that an appropriate combination of guitar pedals, possibly including overdrives/distortion, may provide the sounds you want, even without any any additional coloration from the amp itself.
All in all though, this is a compromise solution, and with it, you may not be able to achieve your desired guitar tones, esp. if amplifier distortion is an essential ingredient.
Running keys through electric guitar amp
I'm pretty sure that going the other way, running keys through a guitar amp, has been done -- mostly back in the 60s, but the coloration imposed by the guitar amp limits how well you can use the full range of the keys.  This might be a feasible approach if you were only going for a limited range of vintage sounds with your synthesizer.  Again, running keys through a guitar amp, esp. loud bass notes, can overdrive the speaker and cause permanent damage.
Comment: Jon Lord of Deep Purple was one of those who ran his Hammond organ through a Marshall guitar amp - specifically because he wanted a distorted sound that the Hammond did not provide. Modern keyboards may have such sounds built in.
Answer: Basically, yes.
An amp is an essential part of a guitar's sound, tends to be overdriven somewhat (or has circuitry simulating the kind of overdrive a tube amp would show), has a single speaker with rather stiff fastenings and specific sound color covering a range up to something like 8kHz, no tweeters which would give overdrive a rather unpleasant color as long as they survive.
A keyboard amp, in contrast, is comparatively faithful in its reproduction, offers a larger frequency range (something like 25-18kHz or more) and will consequently be similar to a PA: it is not supposed to make significant changes to its input signal unless we are talking about a Leslie-like rotating speaker.  You can also feed a keyboard straight into a PA without much of a problem, so player/singers will more likely get away with a single amp when playing keyboard rather than guitar.
Answer: Guitar amplifiers reproduce sound very well in the range of notes (frequencies) that a guitar plays, but the sound quality is relatively poor outside that range. A keyboard can play a much wider range of notes, so a keyboard amplifier needs to be good at producing a wider range of frequencies.
What this means is that a good keyboard amplifier will work well for a guitar, but an amplifier designed for guitar will sound poorly with a keyboard. So your best bet is buying a keyboard amp, and using it for both instruments.
EDIT:
This is more true for an acoustic than an electric. user20352's answer addresses a little of what happens to produce the traditional electric guitar sound through a guitar amp. The keyboard amp will give a more lifelike acoustic sound.


Non-separability of an $\ell_1$-like normed space

Question: Consider the normed vector space that consists of all functions $x(t):[0,1] \rightarrow \mathbb{R}$ such that $x(t)$ vanishes everywhere but a countable set of $t_k$ and
$$||x|| = \sum_{k=1}^{\infty} |x(t_k)| <\infty$$
I would like to prove that this is not separable.
The normed space in question appears very similar to $\ell_1$. I am aware of the proof that $\ell_1$ is separable and it is not apparent to me why the same arguments do not hold for this space. Is there a counter-example function that can be constructed that shows that a countable dense set does not exist or does this proof require something more in depth? Hints would be appreciated.
Answer: Let $x^{s} (t)=1$ if $t=s$ and $0$ if $t \neq s$. Then $x^{s}$ belongs to this space for every $s \in [0,1]$ and $\|x^{s}-x^{s'}\|=2$ for $s \neq s'$. Do you know how to use this to show that the space is not separable? [Hint: Consider open balls of radius $1$ around the points $x^{s}$].
Comment: Agreed except that $\|x^{s}-x^{s'}\|=2$. Also, I would like to add that this space is sometimes denoted $\ell_1([0,1])$, so the similarity to $\ell_1$ is not coincidental.
Comment: This makes sense but I guess I am confused by "countable set of points t_k", how can we have s in [0,1]?
Comment: For each $s$ $x^{s}(t)$ vanishes except on a  countable set, in fact it vanishes for all $t$ except $t=s$. So each $x^{s}$  is an element of the space. @xSkid
Comment: So does countable here refer to the cardinality of the set of non-zero outputs for a given function and not the countability of the input value of t?
Comment: @xSkid For each element of the space there is a countable set set outside which the function is $0$. The countable set is not fixed. It varies from element to element.
Comment: @KaviRamaMurthy thanks!


Why does is_a? fail to match type, and results in split throwing an exception?

Question: While running RSpec and FactoryGirl, it automatically converts any :id param into a fixnum, whereas, in real life, it gets passed as a string. Code I have that processes that :id as a composite primary key tries to call split on params[:id]. That results in an exception, like so:
NoMethodError:
    undefined method 'split' for 234:Fixnum

When trying to call something like this:
  @myinstance = MyClass.find(params[:id].split("-").map{|x| x.to_i})

In an attempt to get around this issue, I have added a simple type check:
if params[:id].is_a? Fixnum
  @myinstance = MyClass.find(params[:id])
else
  @myinstance = MyClass.find(params[:id].split("-").map{|x| x.to_i})
end

Yet, this does not work as I expect it to. The if statement evaluates to false, and the split is still attempted, resulting in the same error. How is it possible that Ruby recognizes params[:id] as a Fixnum in the "else" logic, yet fails to evaluate to true in the if statement?
Answer: It's sheer logic: params[:id] is a String or nil.
Oh... I must edit my answer:
When you do controller specs, the params you send are sent as-is and not stringified...
That's a pain but it should be fixed sooner or later.
So in your specs, stringify your params to be closer to reality.
That's a really important point: don't adapt your code to your specs, do the opposite.
Comment: If, as you say, params[:id] is a string, then how come the error states that it can't find the "split" method on fixnum?
Comment: @muistooshort: hell yes, unfortunately, I learnt it the hard way: my specs were passing but my prod was crashing...
Comment: @muistooshort: that's sooooooo true ;)
Comment: oh correct, I didn't see everything... are you sure it breaks on this line? Does `params[:id].split("-")` breaks in your debugger?
Comment: It for sure breaks there. I'm in the middle of a dev env switch, so I don't have debugging capability at the moment (errors are coming from our CI server). However, I wrapped the call in a begin-rescue clause, and the behavior confirms it's this line.


Erro ao criar SQL parametrizado

Question: Preciso de ajuda com uma mensagem de erro.

Nome de coluna 'nome@' invalido.

Essa mensagem aparece como erro no final da execução do programa
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Cadastro
{
    public partial class FrmMenu : Form
    {
        public FrmMenu()
        {
            InitializeComponent();
            txtPesquisa.Enabled = false;
            txtNome.Enabled = false;
            txtTelefone.Enabled = false;
            txtCelular.Enabled = false;
            txtEmail.Enabled = false;
            txtEndereco.Enabled = false;
            txtNumero.Enabled = false;
            txtCidade.Enabled = false;
            txtSexo.Enabled = false;
        }

        SqlConnection sqlCon = null;
        private string strCon = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Genesis;Data Source=DESKTOP-U3IG6CV\SQLEXPRESS";
        private string strSql = string.Empty;

        private void addFuncionarioToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Adicionar add = new Adicionar();
            add.ShowDialog();
        }

        private void sAIRToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnAdicionar_Click(object sender, EventArgs e)
        {
            txtPesquisa.Enabled = false;
            txtNome.Enabled = true;
            txtTelefone.Enabled = true;
            txtCelular.Enabled = true;
            txtEmail.Enabled = true;
            txtEndereco.Enabled = true;
            txtNumero.Enabled = true;
            txtCidade.Enabled = true;
            txtSexo.Enabled = true;
        }

        private void btnSalvar_Click(object sender, EventArgs e)
        {
            strSql = "insert into ClientesAuE (nome, telefone, celular,email,endereco,numero,cidade,sexo) values (nome@, telefone@, celular@,email@,endereco@,numero@,cidade@,sexo@)";
            //Criar a conexão com o banco de dados
            sqlCon = new SqlConnection(strCon);99
            //Criar o comando que executa a instrução sql
            SqlCommand comando = new SqlCommand(strSql, sqlCon);

            comando.Parameters.Add("@nome", SqlDbType.VarChar).Value = txtNome.Text;
            comando.Parameters.Add("@telefone", SqlDbType.VarChar).Value = txtTelefone.Text;
            comando.Parameters.Add("@celular", SqlDbType.VarChar).Value = txtCelular.Text;
            comando.Parameters.Add("@email", SqlDbType.VarChar).Value = txtEmail.Text;
            comando.Parameters.Add("@endereco", SqlDbType.VarChar).Value = txtEndereco.Text;
            comando.Parameters.Add("@numero", SqlDbType.VarChar).Value = txtNumero.Text;
            comando.Parameters.Add("@cidade", SqlDbType.VarChar).Value = txtCidade.Text;
            comando.Parameters.Add("@sexo", SqlDbType.VarChar).Value = txtSexo.Text;

            try
            {
                sqlCon.Open();
                comando.ExecuteNonQuery();

                MessageBox.Show("CADASTRO REALIZADO COM SUCESSO.");
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                sqlCon.Close();
            }

            txtPesquisa.Enabled = true;
            txtNome.Clear();
            txtTelefone.Clear();
            txtCelular.Clear();
            txtEmail.Clear();
            txtEndereco.Clear();
            txtNumero.Clear();
            txtCidade.Clear();
            txtSexo.Clear();
        }
    }
}

Comment: No insert não deveria ser `VALUES (@nome, @telefone, @etc...)`?
Answer: Cara acredito que o erro está na lina
strSql = "insert into ClientesAuE (nome, telefone, celular,email,endereco,numero,cidade,sexo) values (nome@, telefone@, celular@,email@,endereco@,numero@,cidade@,sexo@)";

acredito que você deveria colocar no values da seguinte forma @nome, @telefone...
com o @ antes do nome

Erro ao criar SQL parametrizado


How to add headers on a 302 redirect in asp.net mvc

Question: Basically I'm writing some code which does an internal webclient request, gets all the headers and then I want to add those headers to a Redirect() call via a controller.
Is there any way to do that?
Comment: Then you are busted. Forget about it. The only thing you can hope is to add custom headers after the POST which is sending the 302 status code. You will have to change your architecture so that you perform the remote call in the target GET action.
Comment: Did you find out if this is possible?
Comment: Unfortunately it's not for security reasons. :(
Comment: Redirect means 302 status code. Do you mean that you want to add some custom headers to this response? It is on the target action that you are redirecting to that you probably want to add the headers, isn't it?
Comment: @DarinDimitrov - in my scenario I am doing a POST-REDIRECT-GET. The information I want to add as a custom header is known only to the POSTed action, but not the GET one.
Answer: Unfortunately it's not possible for security reasons as specified above.
Comment: What kind of security reasons are you talking about? Could you improve your answer a little bit so you have real arguments to say so?


Python module can't be imported when triggered by launchctl script in macos

Question: The python program(apple.py) which wanted to be triggered by launchctl script,written under python2.7 in anaconda
The launchctl plist script(com.tushare.refreshall.plist) which was used to trigger the python program
I try to use a plist script to launch my python program but in vain,in the program,i import a package tushare,but "ImportError: No module named tushare" returned in log file "stderr",this package can be successfully imported in python program written in anaconda.
Results:
Traceback (most recent call last):

  File "/Users/jacksonshawn/PythonCodes/apple.py", line 8, in <module>
import tushare as ts

ImportError: No module named tushare

Guess maybe it's due to "EnvironmentVariables" parameter missing in plist script,but i don't know how to amend the plist script to fix the problem.Every time,i do the following to execute the script.Syntax checked with the Plist script,it can be executed.
"launchctl unload -w com.tushare.refreshall.plist"

"launchctl load -w com.tushare.refreshall.plist"

"launchctl start com.tushare.refreshall.plist"

Comment: Anyone can help?really appreciate it.This module tushare works well in python 2.7 within anaconda,i just didn't know why it can't be imported in program which needed to be triggered by launchctl script.Maybe some parameter like "EnvironmentVariables" missing in my plist script.
Comment: Add some debug to your code that prints the value of sys.path. Make sure that the module you are importing is on the sys.path.
Comment: Try to create a virtual environment on python2 and do the project. And try installing tushare in that environment.
Answer: The service you are starting with launchctl likely does not share the environment you are in when you login into the terminal including the anaconda configuration.
You can fix this by adjusting the plist's ProgramArguments key and run whatever you intent through bash first and include the conda activation before the intended program. Here is an example where the emacs daemon is run in a conda environment named py36:
  <key>ProgramArguments</key>
  <array>
    <string>bash</string>
    <string>-c</string>
    <string>source /Users/username/anaconda3/etc/profile.d/conda.sh; conda activate py36; /usr/local/opt/emacs/bin/emacs --fg-daemon</string>
  </array>

This assumes that you are username, with anaconda installed in /Users/username/anaconda3. Adjust as per your specifics including the conda environment name.
Comment: thank you very much, i will give a shot as what you told.


Como alterar a cor do DropDownList da Kendo UI conforme a variável de Status?

Question: Alguém sabe me dizer se tem como mudar a cor da DropDownList da Kendo conforme uma variável de Status?
Por exemplo:
Caso o usuário esteja Ativo -> Assume a cor Verde
Caso o usuário esteja Inativo -> Assume a cor Vermelho
Caso não seja possível alterar a cor, pode ser um modo de colocar um ícone diferente, ou algum tipo de identificador por registro.
Answer: Bom pessoal... procurei em diversos locais e não consegui trocar a cor da dropdownlist, mas consegui montar com ícones.... Segue o código para montar a DropDownList:
 var cliente = $("#cboCliente").kendoDropDownList({
    autoBind: true,
    filter: "contains",
    dataTextField: "Nome",
    dataValueField: "Id",
    dataSource: {
        serverFiltering: true,
        transport: {
          read: { url: urlBase + "/principal.php?ACAO=ComboClientes", dataType: "json", type: "POST", data: { MODULO: "Seguranca", TELA:"ClonarUsuario"} },
        },requestStart: function (e) {
           $(".clCarregando").show();
        },
        requestEnd: function (e) {
          $(".clCarregando").hide();
        }
    },
    valueTemplate: '   #:Nome#',
    template: kendo.template('    #:Nome#'), });

O "Ativo" e que eu chamo no valueTemplate e no template vem do meu banco de dados, assim ele podem ser preenchidos com 0 ou 1, visto que o campo é bit. Criei duas imagens para ativo e inativo e dei a elas o nome de 0 e 1. Assim quando chamado ele vai carregar a imagem correspondente.


Autoheight of vertical column header in C# using DevXpress

Question: I used this http://www.devexpress.com/Support/Center/p/Q233111.aspx (the code is in VB so I converted it to C#) to get vertical column headers. I get the vertical headers but my problem is some of them doesn't fit, so they are not fully visible.
Is it possible to autoheight the column headers ? (all height set to max height)
Answer: As shown in Devexpress support center i think this will be the solution to your problem
First add an helper class to your solution
public class AutoHeightHelper
{
    GridView view;
    public AutoHeightHelper(GridView view)
    {
        this.view = view;
        EnableColumnPanelAutoHeight();
    }

    public void EnableColumnPanelAutoHeight()
    {
        SetColumnPanelHeight();
        SubscribeToEvents();
    }

    private void SubscribeToEvents()
    {
        view.ColumnWidthChanged += OnColumnWidthChanged;
        view.GridControl.Resize += OnGridControlResize;
        view.EndSorting += OnGridColumnEndSorting;
    }

    void OnGridColumnEndSorting(object sender, EventArgs e)
    {
        view.GridControl.BeginInvoke(new MethodInvoker(SetColumnPanelHeight));
    }

    void OnGridControlResize(object sender, EventArgs e)
    {
        SetColumnPanelHeight();
    }

    void OnColumnWidthChanged(object sender, DevExpress.XtraGrid.Views.Base.ColumnEventArgs e)
    {
        SetColumnPanelHeight();
    }

    private void SetColumnPanelHeight()
    {
        GridViewInfo viewInfo = view.GetViewInfo() as GridViewInfo;
        int height = 0;
        for (int i = 0; i < view.VisibleColumns.Count; i++)
            height = Math.Max(GetColumnBestHeight(viewInfo, view.VisibleColumns[i]), height);
        view.ColumnPanelRowHeight = height;
    }

    private int GetColumnBestHeight(GridViewInfo viewInfo, GridColumn column)
    {
        GridColumnInfoArgs ex = viewInfo.ColumnsInfo[column];
        GraphicsInfo grInfo = new GraphicsInfo();
        grInfo.AddGraphics(null);
        ex.Cache = grInfo.Cache;
        bool canDrawMore = true;
        Size captionSize = CalcCaptionTextSize(grInfo.Cache, ex as HeaderObjectInfoArgs, column.GetCaption());
        Size res = ex.InnerElements.CalcMinSize(grInfo.Graphics, ref canDrawMore);
        res.Height = Math.Max(res.Height, captionSize.Height);
        res.Width += captionSize.Width;
        res = viewInfo.Painter.ElementsPainter.Column.CalcBoundsByClientRectangle(ex, new Rectangle(Point.Empty, res)).Size;
        grInfo.ReleaseGraphics();
        return res.Height;
    }

    Size CalcCaptionTextSize(GraphicsCache cache, HeaderObjectInfoArgs ee, string caption)
    {
        Size captionSize = ee.Appearance.CalcTextSize(cache, caption, ee.CaptionRect.Width).ToSize();
        captionSize.Height++; captionSize.Width++;
        return captionSize;
    }

    public void DisableColumnPanelAutoHeight()
    {
        UnsubscribeFromEvents();
    }

    private void UnsubscribeFromEvents()
    {
        view.ColumnWidthChanged -= OnColumnWidthChanged;
        view.GridControl.Resize -= OnGridControlResize;
        view.EndSorting -= OnGridColumnEndSorting;
    }
}

Then on your form you should make the helper class to Handle GridView's columns resize events by adding the following lines of code
AutoHeightHelper helper;
private void OnFormLoad(object sender, EventArgs e)
{
    helper = new AutoHeightHelper(gridView1);
    helper.EnableColumnPanelAutoHeight();
}

private void OnFormClosing(object sender, FormClosingEventArgs e)
{
    helper.DisableColumnPanelAutoHeight();
}

Hope this helps...
Comment: I attempted to use this solution and I added a context menu item for when I right click a column header to toggle whether I'm using the `AutoHeightHelper` or not.  When I turn the `AutoHeightHelper` off, it calls `UsubscribeFromEvents()`, and the line `_view.GridControl.Resize -= OnGridControlResize;` is executed.  But when I resize the `GridControl`, this event still fires and is handled by my handler.  Do you know why this could be happening?


ESXi Network Issue

Question: I have 2 VMs running on a ESXI 6.0 Host with W2012R2 and VMXNET3. With iperf I get around 982Mbits/sec. Also tried to a outside VM (HyperV) running on another server and I get 300Mbits/sec. Download from that same outside VM to my laptop directly connected to the Procurve 2824 I get max link speed copying a file trough SMB.
Already set all Jumbo Frames (9000) on both VMs and also on the configuration of the vSwitch. What else can be wrong?
NIC Teaming is based on virtual port ID with 2 NICs.
Thank you
Answer: Does that outside VM have the legacy adapter or the "network adapter" attached?  You need integration tools installed for the one called network adapter and not for the legacy adapter. The legacy adapter is slow.
It is the EXACT same problem with VMXNET3 vs the E1000.  We had a client that had nothing but problems in their environment with connectivity issues with the RDS Farm.  Changed all VMs to VMXNET 3.  Flawless.  Same with Hyper-V.  We've had throughput issues with the Legacy Adapter.
Comment: If you're trying to get the 10Gbps speed of the VMXNET3, that only works going between VMs on the same host if your Host box's physical connections are only gigabit.  It will fail over the connection to another NIC if one physical host NIC connection goes down.  But the only way to get the full 10Gbps (though not clear in the question exactly) is to have a 10Gbps daughter card in the host.
Comment: So if I got it I can only achieve 10Gbps if my host NIC is 10Gb also? Even if it's inside VMs on that same physical host? If my host card is 1Gbit I will only get 1Gbit beetween VMs?
Comment: If you have more than one vSwitch for a host where you have them on separate ethernet ports, you'll be limited to 1 Gbps between vSwitches.  If you make it so everything is on one vSwitch and just use the NICs in failover fashion, they will communicate with each other directly through the vSwitch at the full 10Gbps.  What you DON'T want to do is tie a VM directly to a single physical NIC.  It would still create a vSwitch as it converts the interface to virtual, will show that it's a 10Gbps connection, but will only be at a rate of 1Gbps max.
Comment: Can also get all your hosts NICs on 10Gbps for not a huge ton of money.  A lot.. but the speed.... omg the speed...
https://amzn.com/B00B46AEE6 - 8-port 10Gbps Switch &
https://amzn.com/B015HDT6AY - Dual 10Gbps NIC compatible with VMware

ESXi Network Issue


Setting up a mysql "search" page

Question: I need some help on how to set up this page. Let's say I have a mysql table of 5 or so fields of data (i.e. id, firstname, lastname, favorite color, favorite number). I would like to give the user the ability to search the table, so I create a "Search" page.
On the page, I'll have text fields for ID, lastname and firstname.  From here the user would insert data to search by. I guess what I'm confused about is how I can write a script that takes in different search criteria from the text fields and ignore the fields that are left blank. For example, if a user only puts in a first or last name, then all the entries with that same first/last name will be shown. If they only insert the id (would be unique), then all the content for that user will be shown. If they put in both a last name and a last name, then all the data for entries having that first and last name will appear.
I suppose this is basic but I'm new to this so any help on how to set this up would be greatly appreciated.
Code Update:
<?php
//Connect and select database

//if user wants to search
if(isset($_POST['submit']))
{

$sqlConditions = array();

if(isset($_POST['id'])){
$id = filter_var($_POST['id'], FILTER_VALIDATE_INT);
$sqlConditions[] = 'id = ' . $id;
} else {
$id = 0;
}

if(isset($_POST['firstname'])){
$firstName = filter_var($_POST['firstname'], FILTER_SANITIZE_STRING);
$sqlConditions[] = 'firstname = ' . $firstName;
} else {
$firstName = '';
}

if(isset($_POST['lastname'])){
$lastName = filter_var($_POST['lastname'], FILTER_SANITIZE_STRING);
$sqlConditions[] = 'lastname = ' . $lastName;
} else {
$lastName = '';
}

$query = 'SELECT * FROM students WHERE ' . join (' AND ', $sqlConditions);

//print query
while ($row = $query->fetch_row())
{
  print "LastName = " . $row[0] . " FirstName = " . $row[1].
"Favorite Color = " . $row[2] . " Favorite Number = " . $row[3] . "

\n";
}

}
?>

<form method = "POST" action = "<?php echo $_SERVER['PHP_SELF']; ?>">

ID:<input type = "id" id="id" name="id" size="20" maxlength="40" />

First Name:<input type = "firstname" id="firstname" name="firstname" size="20" maxlength="40" />

Last Name:<input type = "lastname" id="lastname" name="lastname" size="20"    maxlength="40" />

<input type="submit" id="submit" name ="submit" value="Search" />

</form>

Answer: I am writing this to people who are just starting out PHP.  I apologize to the OP if they are a PHP pro, but this site is for everyone!
So, Here is what I suggest you do:

Write a simple script that is able to connect and select/display information from your populated table.
After you understand how that works, learn how to use prepared statements. This will protect you from things like SQL injections *
Once you understand how these two things work.  All you have to do is make an HTML form (this is easy to find help on with Sir Google) and then use your $_GET or $_POST to access the input from the user and get your information. (if you don't understand the difference between GET and POST, please look that up too!)

If you can learn these things, you'll be well on your way.  Also, knowing how LIKE works will do you good too:
SELECT stuff FROM myTable WHERE someCondition LIKE '%Me%'
*(IF YOU LEARN ONE THING FROM THIS ANSWER PLEASE REMEMBER THIS)
Answer: In what language is your "search" page?
In general you just need to find out first which of the elements the user completed i.e. are not empty.If you are talking about a web page you can use javascript to determine if a field is empty or not.
Then you should have different queries depending on the fields combination written for example in php to execute the query and get the results.
if (lastnameStr!=null)
 {
  <?php
  $result = mysql_query('SELECT lastname FROM tableName );
  if (!$result) {
  die('Invalid query: ' . mysql_error());
  ?>
 }
else
 {
....
 }
}

Answer: You may try the following approach:
Step 1: get data from POST, validate it and compose the future sql conditions
$sqlConditions = array();

if(isset($_POST['Id'])){
  $id = filter_var($_POST['Id'], FILTER_VALIDATE_INT);
  $sqlConditions[] = 'Id = ' . $id;
} else {
  $id = 0;
}

if(isset($_POST['FirstName'])){
  $firstName = filter_var($_POST['FirstName'], FILTER_SANITIZE_STRING);
  $sqlConditions[] = 'FirstName = ' . $firstName;
} else {
  $firstName = '';
}

if(isset($_POST['LastName'])){
  $lastName = filter_var($_POST['LastName'], FILTER_SANITIZE_STRING);
  $sqlConditions[] = 'LastName = ' . $lastName;
} else {
  $lastName = '';
}

Step 2: Compose the query
$query = 'SELECT * FROM your_table WHERE ' . join (' AND ', $sqlConditions);

Of course you will need to use mysql_real_escape_string or some modern approach as PDO to make sure you avoid SQL injection.
Comment: This is great!  I tried this method (see my updated code above), however I can't seem to get the results to print on the page.  Is there something I'm doing wrong?  Thanks :)
Comment: $query is just a string. You need to execute the query and after that you may fetch the results. Please read: http://php.net/PDO
Comment: Thanks for your help.  I began reading and although confusing, I came up with this:$result = $connection->query($query);
$row = $result->fetch(PDO::FETCH_ASSOC);
print_r($row);...is this what I need?  I tried this, but I was forwarded to a blank page.
Comment: Yes, that's the approach but most probably you have now a fatal error.  Set the display_errors to 1 and user error_reporting(E_ALL) to debug the script.

Setting up a mysql "search" page


How do I get Magento 2 data to use in the template?

Question: I am starting in the Magento development world, and I'm creating a new theme.
On my theme, I have a block which displays business contact info, but I don't know how to get the data from the store.
I have to make a custom menu as well, but stop in the same problem: getting category data from the store.
I also wanted to know if there is any place where you can find more references on this data return issue, such as what available methods and classes are available, for example.
Answer: Where do you want to display the custom data ? In a product page or your custom module's separate page ?
If you want to use custom block in sidebar you can follow steps given here
https://aureatelabs.com/magento-2/how-to-add-a-static-block-in-a-sidebar-column-magento-2/.
Here are some ref you can use:

https://itectec.com/magento/magento-magento-2-get-custom-module-data-in-theme-phtml/
https://code.vky.co.in/display-custom-module-collection-data-frontend-magento-2/


Detecting keypress inside a function not working

Question: I'm trying to make a calculator that calculates slope from two points. I couldn't figure out how to clear text from one text input box, so I have four text input boxes but just one showing at a time. After pressing enter,the y1 function is called. Once you press enter again, the y1 function should call the x2 function, but it doesn't. I used console.log to figure out that the y1 function isn't detecting the keypress. I copy-pasted the detect keypress code from Stack Overflow and I don't really understand it that well, so that might be part of it.
I tried getting rid of the function and moving the y1 code directly inside the if statement of the x1 part, but that didn't work either.
Here is the HTML:

Loading...
 <input type="text" id="input"> <input type="text" id="input2"> <input type="text" id="input3"> <input type="text" id="input4">

and here is the Javascript:
var x4 = document.getElementById('input4');
  x4.style.display = "none";
  var x3 = document.getElementById('input3');
  x3.style.display = "none";
  var x2 = document.getElementById('input2');
  x2.style.display = "none";
  var x = document.getElementById('input');
  x.style.display = "inline";

   document.getElementById("prompt").innerHTML = ("Please Enter x1");

   const x1 = document.getElementById('input');
   x1.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
    y1()
     }
   });

   function y1() {
   document.getElementById('prompt').innerHTML = ("Please Enter y1");
    x.style.display = "none";
    x2.style.display = "inline";
      const y1 = document.getElementById('input2');
   x1.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
    x2()
     }
   });
   }
      function x2() {
   document.getElementById('prompt').innerHTML = ("Please Enter x2");
    x2.style.display = "none";
    x3.style.display = "inline";
    const x2 = document.getElementById('input3');
    x2.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
    y2()
     }
   });
   }
      function y2() {
   document.getElementById('prompt').innerHTML = ("Please Enter y1");
    x3.style.display = "none";
    x4.style.display = "inline";
      const y2 = document.getElementById('input4');
   y2.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
    x3.style.display = "none"
    document.getElementById('prompt').innerHTML = ("Loading");
     }
   });

   }

I keep finding things that say I should use jquery but I don't know much about it and would prefer not to.
Comment: Do you really want only one input box to show up?

If you want the user to insert 4 values in total, why not making all 4 boxes visible with appropriate titles (something like `x1`,`x2`,`y1`,`y2`)?
Comment: I hadn't thought about that. Thanks!
Comment: I posted an answer with the 4 boxes example
Answer: Avoid naming your variables and functions the same.
In the future, post the error messages you encountered
const x1 = document.getElementById('input'); // already store under variable "x"
   x1.addEventListener('keydown', (e) => {
    if (e.key === 'Enter') {
    y1()
     }
   });

const x1 = document.getElementById('input'); - no need to store it again, just use x.addEventListener('keydown'....
    function y1() {
        document.getElementById("prompt").innerHTML = "Please Enter y1";
        x.style.display = "none";
        x2.style.display = "inline";
        const y1 = document.getElementById("input2");
        x1.addEventListener("keydown", (e) => { // you didn't add event listener to y1, but to x1 that's it doesn't call it after you press enter
            if (e.key === "Enter") {
                x2();
            }
        });
    }

On function y1
x1.addEventListener("keydown", (e) => {  -  you didn't add event listener to y1, but to x1 that's it doesn't call it after you press enter
Answer: If you are ok with having 4 different boxes, you could implement something like this (it is only an idea):
DEMO:

//JS
calcSlope();
function setInputFilter(textbox, inputFilter, errMsg) {
  ["input", "keydown", "keyup", "mousedown", "mouseup", "select", "contextmenu", "drop", "focusout"].forEach(function(event) {
    textbox.addEventListener(event, function(e) {
      if (inputFilter(this.value)) {
        // Accepted value
        if (["keydown","mousedown","focusout"].indexOf(e.type) >= 0){
          this.classList.remove("input-error");
          this.setCustomValidity("");
        }
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        // Rejected value - restore the previous one
        this.classList.add("input-error");
        this.setCustomValidity(errMsg);
        this.reportValidity();
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        // Rejected value - nothing to restore
        this.value = "";
      }
    });
  });
}

function calcSlope() {
  x1=document.getElementById("x1").value
  x2=document.getElementById("x2").value
  y1=document.getElementById("y1").value
  y2=document.getElementById("y2").value
  if ([x1,x2,y1,y2].some(p => p === '')) {
    slope = "NaN"
  } else {
    slope = (y2 - y1)/(x2 - x1)
  }
  document.getElementById("slope").innerHTML = slope
}

document.querySelectorAll("input").forEach(inp => {
  setInputFilter(inp, value => {
    return /^-?\d*\.?\d*$/.test(value);
  },
  "Must be a floating (real) number (floating points added with '.')"
  )
})
/*CSS*/
input {
  margin: 1em 0.5em 1em 0;
}

SLOPE CALCULATOR

Please insert points P1(x1,y1) and P2(x2,y2):

P1

  x1:
  <input type="text" id="x1" onkeyup="calcSlope()">
  y1:
  <input type="text" id="y1" onkeyup="calcSlope()">

P2

  x2:
  <input type="text" id="x2" onkeyup="calcSlope()">
  y2:
  <input type="text" id="y2" onkeyup="calcSlope()">

SLOPE:

The JavaScript function to check for input and allow only float numbers (which I believe is what you want) is extrapolated from this answer: https://stackoverflow.com/a/469362/21024780


If $E_k$ is a decreasing sequence of closed nonempty sets of a complete metric space whose diameter converges to zero

Question: then the intersection consists of exactly one point. I can show that the intersection is nonempty, but I couldn't proves it's just one point. Any help?
Answer: Because if $x,y\in\bigcap_{k\in\mathbb N}E_k$ with $x\neq y$, then, for each $k\in\mathbb N$, $x,y\in E_k$ and therefore $\operatorname{diam}E_k\geqslant d(x,y)>0$.
Answer: Hint: Let two points $x$ and $y$ be in the intersection. Since they are different, their distance $d(x,y)$ is larger than some $\varepsilon >0$.
Can you continue?


Template Specialization over derived class

Question: I don't know if it is possible, I checked on StackOverflow, I found a lot of stuff but nothing that really fit my problem (or I don't see the relation).
What I'd like to do is something like that:
class Bean
{
    public:
    Bean(){}
virtual ~Bean(){}
    template <class T>
    bool set_(T){return false;}
    template <class T>
    bool get_(T&){return false;}
};
template <class T>
class GenericBean: public Bean
{
    protected:
    T type;
};
class Prova :  public GenericBean<int>
{
    public:
      Prova(){type = 0;}

   template<int> bool set_(int value){ type=value;}
   template<int> bool get_(int& value){value = type;}

};

I'd like to have on object like Prova, cast to Bean and get the specialized function,
What I want to do is something like this:
#include <vector>
#include "Bean.h"

using namespace std;
class VirtualMessage
{
public:
    VirtualMessage(void){}
    virtual ~VirtualMessage(void){}

    template <class ReturnValue, class Item>
    bool Get(ReturnValue & val)
    {
            for(size_t i = 0; i < m_vData.size(); i++)
            {
                if(m_vData[i].get_<ReturnValue>(val))
                  return true;
            }
    }
    template <class Item, class Value>
    bool Set(Value val)
    {
         Item bean;
         if(bean.set_<Value>(val))
         {
           m_vData.push_back(bean);
           return true;
         }
         return false;
     }
protected:
     vector<Bean> m_vData;
};

Main:
#include "VirtualMessage.h"
#include "Bean.h"
int main()
{
    VirtualMessage msg;
    if(msg.Set<Prova ,int>(4))
        printf("Test 1 passed");
}

this code doesn't compile
Maybe nobody will use it, but I wrote something that fits my need. It's not perfect, I have to work on it but is a begin:
#define UNIQUE(T)   unsigned int GetID(){return UniqueType<T>::id();}

struct UniqueTypeBase
{
   static unsigned int _ids;
};

unsigned int UniqueTypeBase::_ids = 0;
template <class T>
struct UniqueType : public UniqueTypeBase
{
   static const unsigned int id()
   {
      static unsigned int typeId = 0;
      if (typeId == 0)
         typeId = ++_ids;
      return typeId;
    }
 };

template <class T>
class TemplateBean
{
  public:
     T m_tValue;
     template<class T> set_(T){return false;}
     template<class T> get_(T&){return false;}

     bool set_(T value){    m_tValue    =   value;      return true;}
     bool get_(T& value)    {   value       =   m_tValue;return true;}
};

class Prova :  public TemplateBean<int>
{
public:
    UNIQUE(Prova)
    Prova(){m_tValue = 0;}
};
class Prova2 :  public TemplateBean<float>
{
   public:
     UNIQUE(Prova2)
     Prova2(){m_tValue = 0;}
};

class VirtualMessage
{
  public:
    VirtualMessage(void){}
    virtual ~VirtualMessage(void){}
    template <class Item, class ReturnValue>
      bool Get(ReturnValue & val)
    {
         Item a;
         map<unsigned int, void*>::iterator it;
         it = m_TagMap.find(a.GetID());
         if(it != m_TagMap.end())
         {
             Item*  pItem = reinterpret_cast<Item*>(it->second);
             if(pItem->get_(val))
                return true;
          }
          return false;
     }
    template <class Item, class Value>
     bool Set(Value val)
    {
      Item* pBean = new Item();
      if(pBean->set_(val))
      {
           m_TagMap[pBean->GetID()] = (void*)pBean;
           return true;
      }
      return false;
  }
  protected:
    map<unsigned int, void*> m_TagMap;
 };

Test Main:
 int main()
 {
    VirtualMessage msg;
    if(msg.Set<Prova ,int>(4))
        printf("Test 1 passed\n");
    if(!msg.Set<Prova,float>(4.00))
        printf("Test 2 succed\n");
    if(msg.Set<Prova2,float>(4.00))
        printf("Test 3 succed\n");
    int a=0;
    if(msg.Get<Prova>(a))
         printf("%d = 4...if 4=4 test passed\n",a);
     float b=0;
    if(msg.Get<Prova2>(b))
        printf("%f = 4...if 4=4 test passed\n",b);
    getchar();
  }

Comment: Remark: using `protected` attributes makes maintaining invariants impossible and thus debugging harder.
Answer: I think you misunderstood the use of templates.
Templates are blueprints to build classes or methods, that the compiler use to produce real classes and methods (which is called instantiation).
As such, they are purely a compile-time facility. Therefore, they cannot be virtual, and thus overloading a template method in a derived class does not mean what you expect. It hides the base class method when used from derived (statically) but you still call the base class method if you use a reference or pointer to the base class.
What you are trying to achieve is, unfortunately, impossible with templates: it requires a runtime check.
Furthermore, you are using a std::vector<Bean> which will not work as intended. Polymorphic types shall not be manipulated by values in C++, you need a std::vector< std::unique_ptr<Bean> > or boost::ptr_vector<Bean>...
I would recommend reading a good C++ primer before attempting the kind of task you have set yourself upon. You need a basic introduction to C++ paradigms... and gotchas. And there are a lot of gotchas.
Comment: Well I want a help to do something like that. Your comment didnt' help me, I resolve by myself without introduction to C++
Comment: @perusopersonale: you should definitely read a (good) introduction to C++ (follow the white rabbit: http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list), incidentally, you are reinventing (somewhat) Introspection and Reflection in C++. You may wish to read on the Visitor pattern, for example. And you might `Boost.Any` helpful... (it is MUCH nicer than `void*`, and notably... type safe)


MVC Core : Default Index action not triggered when surfing to "Assets" without specifying "Index"

Question: I have two URLs, both should resolve to the same page. One doesn't and returns 404
http://localhost:xxx/Assets = 404 not found
http://localhost:xxx/Assets/Index = works as intended
Here's my index action:
[HttpGet]
public IActionResult Index()
{

    var vm = new AssetsIndexModel()
        {
          /* snipped, not important */
        };

    return View(vm);
}

and this is my only route in Startup.cs:
app.UseMvc(routes =>
{
    routes.MapRoute("default", "{Controller}/{Action}/{id?}", defaults: new { Controller = "Home", Action = "Index" });
});

This is the only action with this problem. All other actions in the same controller resolve properly. Also, my Home/Index route DOES work if I just surf to "/Home". I can omit "/Index" there, but not in my Assets controller.
Does anyone have any ideas what I may be overlooking?
EDIT:
Also, I create the link to the Index action using the following code
Manage Assets

This produces "/Assets", so MVC seems to understand that it can omit "Index", but then that link just doesn't work and returns 404.
Comment: I found the answer by accident about an half hour later after figuring out some other problem. I posted the answer below.
Answer: I have found the answer after finding another problem (that at first seemed unrelated).
In my HomeController, an action was added like this:
[HttpGet("{assetId}")]
    public IActionResult AssetDetail(Guid assetId)
    {
        return View();
    }

This was the problem. I suppose any action anywhere was resolving to this action. Changing the route above to this solved it:
[HttpGet("Detail/{assetId}")]


Expected Service Times for truncated exponential

Question: I'm trying to solve a problem where all arriving items (arrival exponential $\lambda = 1/5$) are divided into into groups, those who are served within 5 units of time and those who have their service time $>5$. The service of items is also exponential $\mu = 1/5$
So if I want to calculate the mean service time for each group:
$$E[S_1] = \int_0^{5}{s (1/5) e^{-(1/5) s} ds}=(5e-10)/e = 1.32$$
$$E[S_2] = \int_5^{\infty}{s (1/5) e^{-(1/5) s} ds}=10/e = 3.6$$
So before going further, I don't understand why my mean service time for the second group of items is 3.6 when only items with service time $>5$ are considered. Do I have an incorrect approach? Do I need to condition it somehow?
Answer: Your $\mu$ = $\frac{1}{5}$ tells you that the mean service time is 5 minutes from 0 to $\infty$.
If you add $E(s_1)$ and $E(s_2)$, it is 5.  One in the interval $ 0-5$ and the other in the interval (5 - $\infty$).
So I am not surprised that the $E(s_2)$ $= \frac{10}{e}$
For truncated exponential, read the above article,
http://en.wikipedia.org/wiki/Truncated_distribution#Expectation_of_truncated_random_variable
Accordingly, $E(S/S>5) = \dfrac{\int_5^{\infty} sf(s)ds}{1-F(5)}$
The top part you already calculated it to be $\frac{10}{e}$
$F(5) = 1-\frac{1}{e}$
$1-F(5) = \frac{1}{e}$
Now $E(S/S>5) = \dfrac{\frac{10}{e}}{\frac{1}{e}} = 10$ which now makes sense
Comment: thank you for your reply, I really appreciate it. I'm still left wondering if the truncated exponential is the correct mean service time for each group based on the definition of the problem. The formulas I need to use use "mean service time", so is it 10/e or (10/e)/(1/e)?
Comment: It is the latter, (10/e)/(1/e).  I do not know what the underlying problem is, So I do not know what is appropriate. It seems like you have multiple servers and you are trying to channel the arrivals to one of these servers and are analysed separately. If that were to be the case, the above truncated exponential could be of use. If you find the answer useful, you could choose to accept it.
Comment: it's m/g/1 nonpreemtive queue with two groups of customers. So, I need to calculate $E[S]$ and $E[S^2]$ for each group


Get the current element type

Question: How can I find the el tag name below (eg. div, p or span) ?
$('div, p, span').each(function(){
  var el = $(this);

});

Answer: Use the tagName property:
$('div, p, span').each(function(){
  var tag = this.tagName;
});

Note: tagName is a property of the element, not a jQuery method.
Answer: Using nodeName is better than tagName if you consider consistency between browsers.
This has good explanation: Difference between .tagName and .nodeName
$('div, p, span').each(function(){
  var el = this.nodeName;
});

Comment: There won't be any other type of nodes than tags in a collection created from that selector. Actually, there will never be any other type of nodes in a jQuery collection created from *any* selector.
Answer:

p

div

....
more info (example) here
Comment: That doesn't work, there is no tagName property in the jQuery object. (I even tried it, to be 100% sure.)
Comment: yes, sorry. It will work now. working demo: http://sandbox.phpcode.eu/g/e26a7.php
Answer: You can use
$(this).prop('tagName')

or
$(e.target).prop('tagName')

to get the selected tag name.

Get the current element type


verify NSURL which is getting from UIImagePickerController

Question: <code>- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    NSURL *imageURL = [info valueForKey:UIImagePickerControllerReferenceURL];
}
</code>
I am getting this image url then i save this in NSUserDefaults and close my app. then i delete picture with this URL from iPhone album now when next time app runs i get imageUrl from user deafults. now i need to decide that whether this image exist or not. how i can find this.
Answer: <code>NSString *path = [imageURL path];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])     //Does file exist?
{
  //Do something if the file exists or handle the case where it doesn't
}
</code>
Hope this helps
Tams


I am trying to make a jQuery modal popup dialogue

Question: I am trying to make a jQuery hover modal popup window for my new project (not tooltip.) Unfortunately it is not working.
Please check this Codepen link https://codepen.io/coderco/pen/MWGgqop. I am looking for same working as this with jQuery.
https://mdbootstrap.com/snippets/jquery/bartek-malanowski/226737
Here is my codes:
$(document).ready(function(){
    $( ".test" ).hover(function() { //Hover Function
           $('.modal').modal({ // Modal
        show: true
    });
  });
});

HTML
<button class="test">Jquery Hover Modal Popup</button>

Jquery Hover Modal Popup

Comment: Have you included jquery-ui?   Please create a full snippet that demonstrates the issue.
Comment: You've tagged this [tag:jquery-ui] but the [jquery-ui dialog](https://jqueryui.com/dialog/) code is `$( "#dialog" ).dialog();`.   You've used `$(".modal").modal(...` and the classname `bs-example-modal-sm` also indicates that you're trying to create a [tag:bootstrap-modal].  Please clarify.
Comment: Please refrain from making hostile rollbacks - the new version is much more readable, and contains far less fluff.
Answer: Here in html firstly I removed the extra script tag I added a new attribute hidden="true" to hide the model and in jquery used built in function.
The popup will get hidden when someone will hoverout.

$(".test").hover(function() {
  $('.modal').show();
}, function() {
  $('.modal').hide();
});
.modal { margin:0.5em 0; padding: 0.5em; border:1px solid rebeccapurple; }

<button class="test">Jquery Hover Modal Popup</button>

      Jquery Hover Modal Popup

Comment: Hi.. you made it as tooltip  .. I am looking for Modal Popup. Not tooltip.
Comment: You probably mean a modal *dialog*.
Comment: Yes. Modal dialogue when hover
Comment: You asked for popup. I thought you are lacking the logic my bad.
Comment: I am looking for same as this https://mdbootstrap.com/snippets/jquery/bartek-malanowski/226737 with Jquery.