Overlay smaller image in a larger image in OpenCV

Question: I would like to replace a part of the image with my image in Opencv
I used
cvGetPerspectiveMatrix() with a warpmatrix and using cvAnd() and cvOr()

but could not get it to work
This is the code that is currently displaying the image and a white polygon for the replacement image. I would like to replace the white polygon for a pic with any dimension to be scaled and replaced with the region pointed.
While the code is in javacv I could convert it to java even if c code is posted
grabber.start();
while(isDisp() && (image=grabber.grab())!=null){
  if (dst_corners !=  null) {// corners of the image to be replaced
  CvPoint points = new CvPoint((byte) 0,dst_corners,0,dst_corners.length);
  cvFillConvexPoly(image,points, 4, CvScalar.WHITE, 1, 0);//white polygon covering the replacement image
  }
correspondFrame.showImage(image);
}

Any pointers to this will be very helpful.
Update:
I used  warpmatrix with this code and I get a black spot for the overlay image
cvSetImageROI(image, cvRect(x1,y1, overlay.width(), overlay.height()));
CvPoint2D32f p = new CvPoint2D32f(4);
CvPoint2D32f q = new CvPoint2D32f(4);

q.position(0).x(0);
q.position(0).y(0);
q.position(1).x((float) overlay.width());
q.position(1).y(0);
q.position(2).x((float) overlay.width());
q.position(2).y((float) overlay.height());
q.position(3).x(0);
q.position(3).y((float) overlay.height());

p.position(0).x((int)Math.round(dst_corners[0]);
p.position(0).y((int)Math.round(dst_corners[1]));
p.position(1).x((int)Math.round(dst_corners[2]));
p.position(1).y((int)Math.round(dst_corners[3]));
p.position(3).x((int)Math.round(dst_corners[4]));
p.position(3).y((int)Math.round(dst_corners[5]));
p.position(2).x((int)Math.round(dst_corners[6]));
p.position(2).y((int)Math.round(dst_corners[7]));

cvGetPerspectiveTransform(q, p, warp_matrix);

cvWarpPerspective(overlay, image, warp_matrix);

I get a black spot for the overlay image and even though the original image is a polygon with 4 vertices the overlay image is set as a rectangle. I believe this is because of the ROI. Could anyone please tell me how to fit the image as is and also why I am getting a black spot instead of the overlay image.
Comment: Is your polygon axis aligned (more specifically, rectangle)?
Comment: It is not a rectangle and it is not axis aligned, but it has only 4 vertices.
Answer: One way to do it is to scale the pic to the white polygon size and then copy it to the grabbed image setting its Region of Interest (here is a link explaining the ROI).
Your code should look like this:
resize(pic, resizedImage, resizedImage.size(), 0, 0, interpolation); //resizedImage should have the points size
cvSetImageROI(image, cvRect(the points coordinates));
cvCopy(resizedImage,image);
cvResetImageROI(image);

I hope that helps.
Best regards,
Daniel
Answer: I think cvWarpPerspective(link) is what you are looking for.
So instead of doing
CvPoint points = new CvPoint((byte) 0,dst_corners,0,dst_corners.length);
cvFillConvexPoly(image,points, 4, CvScalar.WHITE, 1, 0);//white polygon covering the replacement image

Try
cvWarpPerspective(yourimage, image, M, image.size(), INTER_CUBIC, BORDER_TRANSPARENT);

Where M is the matrix you get from cvGetPerspectiveMatrix
Comment: Hi I am using cvGetPerspectiveTransform(q,p,warp_matrix); where p has the image corners and q has the overlay image corners. I am then using this warp_matrix for warpperspective but it still fails to replace the image. Am I missing something?
Comment: Could you paste your code? And what do you mean by "fails to replace"?
Comment: I added an update please check the code there :) As I said I want to fit an overlay image in a polygon with 4 vertices, not necessarily a rectangle. thanks for helping me
Comment: @PavanK I don't think you need to set ROI for image. And make sure the order of dst_corners is correct. You can print out warp_matrix to see if `cvGetPerspectiveTransform` gives you something reasonable.
Comment: If I dont set the ROI then whole image gets garbled. dst_corners have the correct corners as when I use convexpolyfill it fills perfectly. I'll print the warp_matrix to see if there are any problems there. I am really stuck here and I don't know whats going wrong.


How do I migrate file entities into media entities?

Question: I am using the Migrate module for a D7 to D8 migration and I am writing the whole migration manually in code (rather than use the built in D7 migrate module, as I wanted more granual control on the migration.)
I have the following structure: the D7 site has a image field where images are stored as File entities. On the D8 site, the image field is an entity reference to a Media entity (and the Media entity in turn has a Image field.)
Originally, I had the following for my Images migration:
id: image_files

source:
  plugin: legacy_images
  constants:
    source_base_path: http://example.com/

destination:
  plugin: 'entity:file'

process:
  fid: fid
  filename: filename
  source_full_path:
    -
      plugin: concat
      delimiter: /
      source:
    -     constants/source_base_path
    -     uri
    -
      plugin: urlencode
  uri:
    plugin: file_copy
    source:
      - '@source_full_path'
      - uri
  filemime: filemime
  status: status

Inside my article node migration file, I had the following:
'field_article_image/target_id':
plugin: migration
migration: image_files
source: field_article_image

but I realized that this would not work. The target_id coming from the image_files migration were really File Entity ID's, not media entity ID's.
In the ideal world, I'd like to find a way to create a third migration, which would create this middle step, and migrate file entities into Media Entities and then map that migration to the Articles migration. However, I can't figure out a good way of doing this.
Plan B will simply be to create a process plugin for the images migration, which will manually create file entities, attach them to media entities, and pass that migration over to Articles (this removes the middle step). This would mean, though, that while Media entities can be rolled back, File Entities could not.
Answer: I ended up chosing to do it slightly different - I create a regular file import, set that migration as the source for my media entity reference field, and then applied a second process plugin 'MediaGenerate' to translate the FID to the new media target_id
<?php

namespace Drupal\my_migration\Plugin\migrate\process;

use Drupal\media_entity\Entity\Media;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Row;
use Drupal\migrate_plus\Plugin\migrate\process\EntityGenerate;

/**
 * Generate a media entity with specified metadata.
 *
 * This plugin is to be used by migrations which have media entity reference
 * fields.
 *
 * Available configuration keys:
 * - destinationField: the name of the file field on the media entity.
 *
 * @code
 * process:
 *   'field_files/target_id':
 *     -
 *       plugin: migration
 *       source: files
 *     -
 *       plugin: media_generate
 *       destinationField: image
 *
 * @endcode
 *
 * @MigrateProcessPlugin(
 *   id = "media_generate"
 * )
 */
class MediaGenerate extends EntityGenerate {

/**
* {@inheritdoc}
*/
public function transform($value, MigrateExecutableInterface $migrateExecutable, Row $row, $destinationProperty) {
if (!isset($this->configuration['destinationField'])) {
  throw new MigrateException('Destination field must be set.');
}
// First load the target_id of the file referenced via the migration.
/* @var /Drupal/file/entity/File $file */
$file = $this->entityManager->getStorage('file')->load($value);

if (empty($file)) {
  throw new MigrateException('Referenced file does not exist');
}

// Creates a media entity if the lookup determines it doesn't exist.
$fileName = $file->label();
if (!($entityId = parent::transform($fileName, $migrateExecutable, $row, $destinationProperty))) {
  return NULL;
}
$entity = Media::load($entityId);

$fileId = $file->id();
$entity->{$this->configuration['destinationField']}->setValue($fileId);
$entity->save();

return $entityId;
}

}

Comment: What is the destinationField configuration?
Comment: Ok i figured it out by myself, it's the field for the asset in the media type, for image this is `field_media_image`.
Comment: How do you handle file alt/title attributes?
Comment: Tested and it works nicely, however you will likely need to use "migration_lookup" plugin because "migration" plugin is deprecated and didn't work on my latest versions already. Following worked for me to import user pictures:

      plugin: migration_lookup
      migration: my_file_migration
      source: picture

Also, if you migrate entities without bundles (like user pictures), you will probably need the patch from here: https://www.drupal.org/project/migrate_plus/issues/2787219 , otherwise you get an error "The entity_lookup plugin requires a value_key, none located." on migration.
Comment: Could anyone please explain how $entityId is found in this?
Answer: As Media is an entity type you should create its own migration.
You can generate a new source from the file table. Here is an example
https://gist.github.com/jibran/8e7cd2319e873858dd49a272227a4fd2
Then with migration_lookup you can map the fields like this.
field_d8_media_image/0/target_id:
  plugin: migration_lookup
  migration: my_media_image
  source: field_d7_image/0/fid

Answer: I appreciated the accepted answer a lot, however it already had some deprecated definitions and did not support posting alt and title image properties. Thus, I enhanced it a bit to support that and to work smoothly with latest Drupal 8.6.x. Here is the code of MediaGenerate.php (the appropriate Yaml syntax is inside the doc comment):
<?php

namespace Drupal\my_migration\Plugin\migrate\process;

use Drupal\media\Entity\Media;
use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\MigrateException;
use Drupal\migrate\Row;
use Drupal\migrate_plus\Plugin\migrate\process\EntityGenerate;

/**
 * Generate a media entity with specified metadata.
 *
 * This plugin is to be used by migrations which have media entity reference
 * fields.
 *
 * Available configuration keys:
 * - destinationField: the name of the file field on the media entity.
 *
 * @code
 * process:
 *   'field_files/target_id':
 *     -
 *       plugin: migration_lookup
 *       migration: my_file_migration
 *       source: field_image/0/fid
 *     -
 *       plugin: media_generate
 *       destinationField: image
 *       imageAltSource: field_image/0/alt
 *       imageTitleSource: field_image/0/title
 *
 * @endcode
 *
 * If image_alt_source and/or image_title_source configuration parameters
 * are provided, alt and/or title image properties will be fetched from provided
 * source fields (if available) and pushed into media entity
 *
 * @MigrateProcessPlugin(
 *   id = "media_generate"
 * )
 */
class MediaGenerate extends EntityGenerate {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrateExecutable, Row $row, $destinationProperty) {
    if (!isset($this->configuration['destinationField'])) {
      throw new MigrateException('Destination field must be set.');
    }

    // First load the target_id of the file referenced via the migration.
    /* @var /Drupal/file/entity/File $file */
    $file = $this->entityManager->getStorage('file')->load($value);

    if (empty($file)) {
      throw new MigrateException('Referenced file does not exist');
    }

    // Creates a media entity if the lookup determines it doesn't exist.
    $fileName = $file->label();
    if (!($entityId = parent::transform($fileName, $migrateExecutable, $row, $destinationProperty))) {
      return NULL;
    }

    $entity = Media::load($entityId);

    $fileId = $file->id();

    $destinationFieldValues = $entity->{$this->configuration['destinationField']}->getValue();
    $destinationFieldValues[0]['target_id'] = $fileId;

    $this->insertPropertyIntoDestinationField($destinationFieldValues, $row, 'alt', 'imageAltSource');
    $this->insertPropertyIntoDestinationField($destinationFieldValues, $row, 'title', 'imageTitleSource');

    $entity->{$this->configuration['destinationField']}->setValue($destinationFieldValues);
    $entity->save();

    return $entityId;
  }

  protected function insertPropertyIntoDestinationField(array &$destinationFieldValues, Row $row, $propertyKey, $configurationKey) {
    // Set alt and title into media entity if not empty
    if (isset($this->configuration[$configurationKey])) {
      $propertyValue = $row->getSourceProperty($this->configuration[$configurationKey]);
      if (!empty($propertyValue)) {
        $destinationFieldValues[0][$propertyKey] = $propertyValue;
      }
    }
  }
}

Answer: If you want to migrate files in Drupal 8 to media entities you can use this module:
https://www.drupal.org/project/migrate_file_to_media
It has a drush script, that automatically creates the media reference fields. Additionally it detects duplicate images using a binary hash. And it supports translations.
Comment: That module only solves migration between D8 versions by default. The question is more like about migration from D7 to D8, so that module cannot be easily used (an additional source plugin to MediaEntityGenerator.php that would read data from attached files in D7 would likely need to be created). There is also one fundamental difference: migrate_file_to_media module only converts files attached to certain entity (=entity_type and bundle are required in step1), while the accepted solution doesn't have this requirement and it firstly migrates all the file entities from the (D7) source.


Explaining this particular version of the Implicit Function Theorem

Question: I understand the general 'word' definitions of the Implicit Function Theorem and the simple examples such as the one on wikipedia but the version of the Implicit Function theorem given in our lecture notes seems pretty obscure (or perhaps I am just missing something). Here it is.

Let $D \subset \mathbb{R}^m \times \mathbb{R}^p$ be open and $f:D \to \mathbb{R}^n$ be continuously differentiable. Further assume $$f(\bar{x},\bar{\lambda}) = 0 \, \, \,  \mathrm{and} \, \, \,  \det f_1'(\bar{x},\bar{\lambda})\neq 0.$$ Then there is a neighbourhood $N$ of $\bar{\lambda}$ and a uniquely determined continuously differentiable mapping $$\phi : N \to \mathbb{R}^m \quad N \subset \mathbb{R}^p$$ such that for all $\lambda \in N$ $$f(\phi(\lambda), \lambda) = 0.$$

Can someone please try and explain this particular formulation of the Implicit Function Theorem in a different way? Thanks!
Comment: Could you expand on what you don't understand?
Comment: Perhaps this might help: http://math.stackexchange.com/questions/128269/intuitive-understanding-about-the-implicit-function-theorem/128271#128271
Answer: First of all, I think that in the statement of the theorem $n=m$; in the following I will assume so. $f$ is a function depending on $m+p$ variables: ($x_1,\dots,x_m,\lambda_1,\dots,\lambda_p)$. $f$ is a vector valued function taking values in $\mathbb{R}^m$; let $f_1,\dots,f_m$ be its components. We are given a system of $m$ equations in $m+p$ unknowns:
$$\begin{align*}
f_1(x_1,\dots,x_m,\lambda_1,\dots,\lambda_p)&=0,\\
f_2(x_1,\dots,x_m,\lambda_1,\dots,\lambda_p)&=0,\\
\dots\dots\dots\qquad&=0,\\
f_m(x_1,\dots,x_m,\lambda_1,\dots,\lambda_p)&=0,\\
\end{align*}$$
Our goal is to solve for $x_1,\dots,x_m$ in terms of $\lambda_1,\dots,\lambda_p$. The implicit function theorem gives sufficient conditions for this to be possible. What are these conditions?

There exists at least one solution. In mathematical notation, this is written as: there exists $(\bar x,\bar\lambda)\in D$ such that $f(\bar x,\bar\lambda)=0$.
A certain non-degeneracy condition is satisfied. In this case it is
$$
\frac{\partial(f_1,\dots,f_m)}{\partial(x_1,\dots,x_m)}(\bar x,\bar\lambda)=
\det\,\begin{pmatrix}
\frac{\partial f_1}{\partial x_1}(\bar x,\bar\lambda)&\dots&\frac{\partial f_1}{\partial x_m}(\bar x,\bar\lambda)\\
\dots&\dots&\dots\\
\frac{\partial f_m}{\partial x_1}(\bar x,\bar\lambda)&\dots&\frac{\partial f_m}{\partial x_m}(\bar x,\bar\lambda)\\
\end{pmatrix}\ne0.
$$

If they are satisfied, the theorem guarantees the existence of $C^1$ functions $x_k=\phi_k(\lambda_1,\dots,\lambda_p)$, $1\le k\le m$, solving the equation.
The theorem is called the implicit function theorem because the system of equations defines implicitely $x_1,\dots,x_m$ as functions of $\lambda_1,\dots,\lambda_p$.


Calculate the transformationmatrix $D^B_C(\phi)$ given two Vectorspaces $V$ and $W$

Question:
$V:= \begin{pmatrix} a&b&c&d\\b&a&d&c\\c&d&a&b\\d&c&b&a\\\end{pmatrix}$ $W:= \begin{pmatrix} u&v&w\\x&y&0\\z&0&0\\\end{pmatrix}$
  $\phi: V \rightarrow W, \begin{pmatrix} a&b&c&d\\b&a&d&c\\c&d&a&b\\d&c&b&a\\\end{pmatrix} \mapsto \begin{pmatrix} a-b&a+c&a-d\\b+c&b-d&0\\c+d&0&0\\\end{pmatrix}$

So $D^B_C(\phi)$ is bascially a transformation of the spanvectors of V to W. Now the basis of $V$ are obviously $B: \begin{pmatrix} 1&0&0&0\\0&1&0&0\\0&0&1&0\\0&0&0&1\\\end{pmatrix}, \begin{pmatrix} 0&1&0&0\\1&0&0&0\\0&0&0&1\\0&0&1&0\\\end{pmatrix}, \begin{pmatrix} 0&0&1&0\\0&0&0&1\\1&0&0&0\\0&1&0&0\\\end{pmatrix}, \begin{pmatrix} 0&0&0&1\\0&0&1&0\\0&1&0&0\\1&0&0&0\\\end{pmatrix}$ and the basis of $W$ $C: \begin{pmatrix} 1&0&0\\0&0&0\\0&0&0\\\end{pmatrix}, \begin{pmatrix} 0&1&0\\0&0&0\\0&0&0\\\end{pmatrix}, \begin{pmatrix} 0&0&1\\0&0&0\\0&0&0\\\end{pmatrix}, \begin{pmatrix} 0&0&0\\1&0&0\\0&0&0\\\end{pmatrix}, \begin{pmatrix} 0&0&0\\0&1&0\\0&0&0\\\end{pmatrix}, \begin{pmatrix} 0&0&0\\0&0&0\\1&0&0\\\end{pmatrix}$
Now I have no idea how I get the transformation matrix, help is very appreciated
Answer: $\phi(v_1)=1w_1+1w_2+1w_3$ where $v_i$ is the $i$-th basisvector of $B$ and $w_j$ is the $j$-th basisvector of $C$. Hence the first column of the desired matrix is $\begin{pmatrix}
1\\1\\1\\0\\0\\0
\end{pmatrix}$.
Similarly, find $\phi(v_i)$ and write it with respect to $C$ to get the coefficients that make up the $i$-th column of the desired matrix.
Comment: Thanks a lot for the quick answer!
Answer: We have $$\phi\begin{pmatrix} 1&0&0&0\\0&1&0&0\\0&0&1&0\\0&0&0&1\\\end{pmatrix}=\begin{pmatrix} 1&1&1\\0&0&0\\0&0&0\\\end{pmatrix}$$
$$=1\begin{pmatrix} 1&0&0\\0&0&0\\0&0&0\\\end{pmatrix}+1 \begin{pmatrix} 0&1&0\\0&0&0\\0&0&0\\\end{pmatrix}+1 \begin{pmatrix} 0&0&1\\0&0&0\\0&0&0\\\end{pmatrix}$$
$$ +0\begin{pmatrix} 0&0&0\\1&0&0\\0&0&0\\\end{pmatrix}+0 \begin{pmatrix} 0&0&0\\0&1&0\\0&0&0\\\end{pmatrix}+ 0\begin{pmatrix} 0&0&0\\0&0&0\\1&0&0\\\end{pmatrix}.$$
$$\ldots$$
Transposing,
$$D^B_C(\phi)=\begin{bmatrix}{1}&{*}&{*}&*\\{1}&{*}&{*}&*\\{1}&{*}&{*}&*\\{0}&{*}&{*}&*\\{0}&{*}&{*}&*\\{0}&{*}&{*}&*\end{bmatrix}.$$
Comment: Thanks alot, so you bascially watch what happens to every basis under the transformation
Comment: Yes, that is right.


PHP MYSQL CONCAT with string containing comma in the start

Question: Its a strange problem that I am having. I am trying to update a value in the database table with a new one by concatenating old and new values with a comma in between. So basically my value now is:
 Hello and I am updating it to World and I want the new value to be Hello,world but I am unable to do this. Both the CONCAT and CONCAT_WS functions through an error that you have invalid syntax.
Table name is fields. The column I wish to update is values and the new value to be concatenated is $newval. Here is my query.
$sql="update fields set values=CONCAT_WS(',',values, '$newval') where name='fundType'";

I get this error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'values=CONCAT_WS(',',values, 'Buyout') where name='fundType'' at line 1

Any help will be appreciated.
Ahmar A.
Answer: values is a keyword of mysql. use backticks `` to mark it as a field name:
$sql="update fields set `values`=CONCAT_WS(',',`values`, '$newval') where name='fundType'";


Highly correlated engineered features any helpful?

Question: Take a car price predictor for an example. If you know the model and year of a car, you can extrapolate facts ("engineer features") about the car. For example: city and highway mpg, number of doors, horsepower, engine size, weight, factory recalls, popularity, etc... Of course, this assumes a non-customized car.
So assuming these things stay constant for cars, is there any value in using a dozen or so features that have the same value for all cars of a certain model and year, or would simply using some representation of the model and year of the car provide the same amount of signal to an ml model?
For example: all 2015 Honda Civics will have the same weight, number of doors, mpg, fuel type, etc...
Concrete Example
Original dataset
<code>| price  | make_id | model_id | year | miles  |
|:-------|:--------|:---------|:-----|:-------|
| 1000   | 15      | 4        | 2015 | 250000 |
| 25000  | 16      | 8        | 2016 | 75000  |
| 45000  | 23      | 42       | 2018 | 10000  |
</code>
After feature engineering:
<code>| price  | make_id | model_id | year | miles  | horse_power | city_mpg | hw_mpg | doors | engine_size |
|:-------|:--------|:---------|:-----|:-------|:------------|:---------|:-------|:------|:------------|
| 1000   | 15      | 4        | 2015 | 250000 | 160         | 18       | 23     | 4     | 1.5         |
| 800    | 15      | 4        | 2015 | 720000 | 160         | 18       | 23     | 4     | 1.5         |
| 500    | 15      | 4        | 2015 | 928300 | 160         | 18       | 23     | 4     | 1.5         |
| 3200   | 15      | 4        | 2015 | 268300 | 160         | 18       | 23     | 4     | 1.5         |
| 2600   | 15      | 4        | 2015 | 236200 | 160         | 18       | 23     | 4     | 1.5         |
| 26000  | 15      | 4        | 2015 | 1320   | 160         | 18       | 23     | 4     | 1.5         |
| 40000  | 15      | 4        | 2015 | 3250   | 160         | 18       | 23     | 4     | 1.5         |
</code>
Note that the example with the features expanded, for a given make/model/year, every feature is the same except for the mileage.
Is this redundant?
Answer: Given that car model is a categorical variable, replacing it with some numerical variables such as horsepower or mpg can have advantages depending on the scope of your prediction model.
If you only want to predict prices for car models (and years) for which you have sufficent individual data, then you can just estimate with binary variables for all car models. Adding mpg, horsepower, etc. will probably not help a whole lot.
However, this kind of model breaks down as soon as you try to make predictions for prices of car models you have no (or too few) observations to train on. A model based on horsepower, mpg, etc. on the other side would still work in that scenario.
Answer: Yes, highly correlated values can be very useful.
Have a look at Feature Selection: Correlation and Redundancy
EDIT:
After you added a sample dataset to your question, it becomes clear that you are not actually talking about linear correlation but rather mean mutual information.
The so called engineering features do not add any relevant information to your dataset since their mutual information with the model_id feature is 1.
Yet in real life, for a single model_id there are possible customizations such as an increased horse_power.


Destruir componente React (Unmounting Component)

Question: Gostaria de saber como faço pra destruir um componente com React ao clicar em um botão. Encontrei uma saída, porém na minha concepção é bem "gambiarrosa". Tenho um state chamado show e quando click em fechar modifico o valor do this.state.show para false, no método render() utilizo um if ternário para renderizar o componente ou não dependendo do valor this.state.show.
MyComponent.js
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import FontAwesome from 'react-fontawesome';

class MyComponent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      show:true,
    };
  }

  closeComponent(){
      console.log("Destruir componente");
      var x = ReactDOM.findDOMNode(this);
      console.log(x);
      //ReactDOM.unmountComponentAtNode(this.container);
      this.setState({ show: false });
  }

  componentDidMount() {
  }

  componentWillUnmount() {
    clearInterval(this.state);
  }

  render() {
    return (
      this.state.show ?

Mostrar componente

        <FontAwesome name="window-close-o" onClick={this.closeComponent.bind(this)}/>

      : null
    );
  }

}

export default MyComponent;

Essa é realmente a única saída pro que eu preciso fazer?
ComponentFather.js
import React, { Component } from 'react';
import './ComponentFather.css';
import MyComponent from '../MyComponent/MyComponent'

class ComponentFather extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value: "Adicionar Categoria",
      key: 0,
      matchs: [],
    };
  }

  componentDidMount(){

  }

  componentWillUnmount(){
    clearInterval(this.state);
  }

  buttonClicked(){
    var mat = this.state.matchs;
    this.state.key ++;
    mat.push(<Match key={this.state.key}/>);
    console.log(mat);
    this.setState({
      matchs: mat
    });
  }

  render() {
    return (

Events Information

        <MyComponent></MyComponent>
        <MyComponent></MyComponent>
        <MyComponent></MyComponent>

    );
  }
}

export default ComponentFather;

MainComponent
import React, { Component } from 'react';
//import logo from './logo.svg';
import './App.css';
import ComponentFather from '../ComponentFather/ComponentFather';
import Streaming from '../Streaming/Streaming';

//import {Grid, Row, Col, Clearfix} from 'react-bootstrap';

class App extends Component {
  render() {
    return (

        <ComponentFather />
        <Streaming />

    );
  }
}

export default App;

index.js
import React from 'react';
import ReactDOM from 'react-dom';

import App from './components/App/App';

import 'bootstrap/dist/css/bootstrap.css'
import 'bootstrap/dist/css/bootstrap-theme.css'

ReactDOM.render(
  <App />,
  document.getElementById('main-container')
);

Comment: Vi agora o teu edit. Dá-me ideia que o teu código é adaptado e não o código real. Duas perguntas: Esses `MyComponent` são sempre 3 ou isso é dinâmico? Outra pergunta, o `ComponentFather` sabe o estado de cada `MyComponent`?
Comment: Coloquei os 3 amarrados apenas para ter uma representação de como vai ser, mas o correto é ser dinâmico. Quanto a sua outra pergunta eu não sei responder. Iniciei os estudos no React esses dias, to devorando a documentação pra vê se clareia mais as coisas. A ideia é a seguinte, o ComponentFather vai carregar uma lista de objetos do backend e pra cada objeto da lista eu vou criar um MyComponent passando o objeto como parametro, as propriedades do objeto serão todas exibidas no MyComponent e dentro do MyComponent vou ter a opção de destruir aquele componente ao clicar em um determinado botão....
Comment: Ok. Se o `ComponentFather` guardar o estado de cada `MyComponent` ele saberá se deve mostrar ou não um dado `MyComponent`. Essa parece-me a maneira mais correta. Estás a usar flux? Mobx? nenhum deles? Daqui a pouco vou dar um exemplo para ver se é isso que procuras
Comment: Por enquanto ainda estou apenas na parte estática mas pretendo utilizar o flux, pelo que li até agora me aprece o mais viável. Porém tenho que pesquisar um pouco mais fundo porque a comunicação vai ser via socket. Pelo que vi na sua resposta é justamente isso que preciso. Muito obrigado pela força que você ta me dando. Só mais outra coisa... Tem algum material que você recomenda pra turbinar meu aprendizado a cerca do React?
Comment: Dá uma olhada aqui entretanto: https://www.youtube.com/watch?v=Wsg3aSvPCXE
Comment: Mais uma duvida para o exemplo que estou a montar: esses `MyComponent` são uma representação de quê? uma array? uma lista da BD? chaves de um objeto?
Comment: Chaves de um objeto
Comment: Editei a resposta, como estás a fazer funciona bem. Dependendo da lógica do elemento pai podes ter uma array com elementos filhos não fazer render via "pai", mas como tens funciona bem. Dá uma olhada no meu jsFiddle, pode ser util para testes.
Answer: A maneira de desmontar um componente é com ReactDOM.unmountComponentAtNode. Esse método aceita o elemento DOM em que o componente está montado. Se não tens uma referência do elemento podes passar ReactDOM.findDOMNode(this).parentNode como argumento.
Assim o teu método para destruir o componente poderia ser:
closeComponent() {
    console.log("Destruir componente");
    var container = ReactDOM.findDOMNode(this).parentNode;
    ReactDOM.unmountComponentAtNode(container);
}

Se esse componente estiver inserido noutro, o melhor seria esconder o elemento via componente pai. Dependendo da lógica por detrás do state do componente.
No teu caso, como estás a fazer é válido, dessa maneira o componente MyComponent fica responsável de guardar o seu próprio estado. E ficaria assim: https://jsfiddle.net/5gjapobx/
Comment: Agradeço pelo ajuda, resolveu meu problema.
Comment: Não rolou... warning.js:36 Warning: unmountComponentAtNode(): The node you're attempting to unmount was rendered by React and is not a top-level container. Instead, have the parent component update its state and rerender in order to remove this component.
Comment: @LuKsSys pensava que era um componente isolado, assim preciso que mostres o componente onde esse está inserido para ajudar...
Comment: Vou editar o código acima e mostrar o código onde ele está inserido


WordPress h1 border insert after not working

Question: Having trouble inserting a gold border after every first child under #content in wordpress..
#content .spacer h1:first-child:after{

display:block;
content:'';
width:45px;
border-bottom:3px solid rgb(229,164,20);
margin:40px 0;
padding:5px 0;
}

either or doesn't work
#content .spacer h1:first-child:after{

display:block;
content:'';
width:45px;
border-bottom:3px solid rgb(229,164,20);
margin:40px 0;
padding:5px 0;
}

Comment: This is useless without markup to go along with it. The rules are probably fine, its your selector string that has to match the markup.
Comment: @Bosworth99 here's a link http://tudorice.com/ (check the following pages, not the home page).
Answer: I am making an assumption for your HTML markup and you wanting to add a empty block with gold border after each H1 element in DIV #content.spacer.
It would be proper to use h1:nth-child(1):after
HTML
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>JS Bin</title>

First-child

Children

Children

Children

CSS
#content.spacer h1:nth-child(1):after{
  display:block;
  content:'';
  width:45px;
  border-bottom:3px solid rgb(229,164,20);
  margin:40px 0;
  padding:5px 0;
}

JSBIN sample here: http://jsbin.com/wejefixajiro/1/edit
Comment: I would like to be only after the title, the first h1 element.
Comment: @user2984926
Comment: @user2984926 please post your entire HTML on JSbin
Comment: @user2984926 I figured it out.. Had to change the number in parenthesis to (2).. Thanks so much for your dedication.. What's your twitter user name?


Trouble finding the integral curves of a PDE

Question: I have to verify that $ C1=x/(x+y+z) $ and $ C2=y^2-z^2 $ are the integral curves of the PDE
$ x∂z/∂x + z∂z/∂y = y $
I already verified that C2 is (using method of characteristic curves) by solving
$ ∂y/z=∂z/y $
but when i try solving
$ ∂x/x=∂z/sqrt(C2+z^2) $
the result is something that has nothing to do with C1, the result is
$ C1=ln(x)-(arctan(z/(y^2-z^2))/sqrt(y^2-z^2) $
How can i get C1? I also tried solving $ ∂x/x=∂y/sqrt(y^2-C2) $ but the result is something with exponentials
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Answer: $$x\frac{\partial z}{\partial x}+z\frac{\partial z}{\partial y}=y$$
System of characteristic ODEs (Charpit-Lagrange) :
$$\frac{dx}{x}=\frac{dy}{z}=\frac{dz}{y}$$
A first characteristic equation comes from
$$\frac{dx}{x}=\frac{dy}{z}=\frac{dz}{y}=\frac{dx+dy+dz}{x+y+z}=\frac{d(x+y+z)}{(x+y+z)} \tag {Note below}$$
Solving $\frac{dx}{x}=\frac{d(x+y+z)}{(x+y+z)}$leads to $\ln|x|=\ln|x+y+z|+$constant.
$$\frac{x}{x+y+z}=C_1$$
A second characteristic equation comes from solving $\frac{dy}{z}=\frac{dz}{y}$ :
$$y^2-z^2=C_2$$
NOTE : Remember a wellknown property of fractions :
$$\frac{A}{B}=\frac{C}{D}=\frac{E}{F}\quad\implies\quad \frac{A}{B}=\frac{C}{D}=\frac{E}{F}=\frac{c_1A+c_2C+c_3E}{c_1B+c_2D+c_3F}$$
for arbitrary constants $c_1,c_2,c_3$ not all nul.
Another (but equivalent method) :
$$\frac{dx}{x}=\frac{dy}{z}=\frac{dz}{y}=dt \quad\implies\quad
\begin{cases}
dx=x\:dt\\ dy=z\:dt\\ dz=y\:dt
\end{cases}  \quad\implies\quad dx+dy+dz=xdt+zdt+ydt$$
$$d(x+y+z)=(x+y+z)dt=(x+y+z)\frac{dx}{x}  \quad\implies\quad \frac{d(x+y+z)}{(x+y+z)}=\frac{dx}{x}$$


Significance of the value of the `current_compiler` variable

Question: Vim's compiler plugins are supposed to set the value of the variable current_compiler to something.  They should also, unless they are intended to augment an existing compiler plugin, exit early if that variable is already defined.  Is the value of the variable intended to be used?  Should it be set to the basename of the compiler plugin file?  (e.g. $VIMRUNTIME/compiler/foo.vim -> foo)
The documentation has this to say:
To support older Vim versions, the plugins always use "current_compiler" and
not "b:current_compiler".  What the command actually does is the following:

- Delete the "current_compiler" and "b:current_compiler" variables.
- Define the "CompilerSet" user command.  With "!" it does ":set", without "!"
  it does ":setlocal".
- Execute ":runtime! compiler/{name}.vim".  The plugins are expected to set
  options with "CompilerSet" and set the "current_compiler" variable to the
  name of the compiler.
- Delete the "CompilerSet" user command.
- Set "b:current_compiler" to the value of "current_compiler".
- Without "!" the old value of "current_compiler" is restored.

The command referred to is :compiler.  Its argument becomes the {name} used above.
The entry on writing compiler plugins doesn't provide additional information, and the above-mentioned entries cover all the instances of the string current_compiler in the vim help database (as per :lhelpgrep current_compiler).
Answer: You can pre-select a particular compiler for a filetype in ~.vim/after/ftplugin/<filetype>.vim.
Because this is re-sourced whenever the buffer is loaded (e.g. when moving through :args), it is recommended to only set the compiler if it hasn't yet been set (i.e. only on the first load). Otherwise, switching buffers may override any changed compiler, and messages from when the compiler was set may be printed (and need to be acknowledged) all the time.


Finding $\frac{d}{dx}\left[ y'(x) \cdot \left(1+y'(x) \right)^{-\frac{1}{2}} \right]$. How do I know what rule to apply?

Question:
$\dfrac{d}{dx}\left( \dfrac{y'(x)}{\sqrt{1+y'(x)}} \right)$

I thought of using the normale rules that we have for finding the derivative.
What I obtained is:
$$\dfrac{d}{dx}\left(\dfrac{y'(x)}{\sqrt{1+y'(x)}} \right) = \frac{y''(x)}{\sqrt{1+y'(x)}}   - \frac{y'(x)\left(y''(x)\right)^2}{2\sqrt{\left(1+y'(x)^2\right)^3}}$$
Is my working correct? Are there any rules for finding the derivatives in these cases? I too have problems with other similar derivatives, however I do not know which rules to proceed with.
Comment: Why taged partial-differential-equations ? I see no PDE in the question. -1.
Answer: Your first term is correct.
Let's break this down:
$$\left(\frac{a}{b^{\alpha}}\right)'=\frac{a'-\alpha b^{-1}b'a}{b^{\alpha}}=\frac{a'}{b^{\alpha}}-\alpha\frac{b'a}{b^{\alpha+1}}$$ Now $a = y', b=1+y',\alpha=1/2;$ so we have
$$\frac{y''-\frac{1}{2}\frac{y''y'}{1+y'}}{(1+y')^{\frac{1}{2}}}=\frac{y''}{\sqrt{1+y'}}-\frac{1}{2}\frac{y'y''}{\sqrt{(1+y')^3}}.$$


Integrate Apache storm with zookeeper in windows

Question: Can anyone help me how to integrate storm with zookeeper in windows.
I try to find the find a good installation steps for production in windows but I can't.
Write now I have installed stand  alone zookeeper and I am trying to configure it in the storm.yaml.
sample code I tried :
 storm.zookeeper.servers:
   - "127.0.0.1"
    - "server2"

storm.zookeeper.port: 2180
nimbus.host: "localhost"

If any body knows please help me.
Comment: Next time on words, to highlight code use `ctrl+k` , not `#`
Answer: Please follow the below steps for complete installation of storm with zookeeper in windows
1. create a zoo.cfg file under /conf directory of zookeeper.
here are the configuration entries
# The number of milliseconds of each tick
tickTime=2000
# The number of ticks that the initial
# synchronization phase can take
initLimit=10
# The number of ticks that can pass between
# sending a request and getting an acknowledgement
syncLimit=5
# the directory where the snapshot is stored.
dataDir=D:\\workspace\\zk-data
# the port at which the clients will connect
clientPort=2181

2.run the zookeeper by executing the zkServer.bat in /bin directory
3.create the storm.yaml file in /conf directory of the apache-storm
here are the configuration entries
########### These MUST be filled in for a storm configuration
storm.zookeeper.servers:
    - "localhost"

#supervisor.slots.ports:
#    - 6700
#    - 6701
#    - 6702
#   - 6703
storm.local.dir: D:\\workspace\\storm-data
nimbus.host: "localhost"
#
#

4.run  the below commands from the command prompt
 a. bin\storm nimbus
 b. bin\storm supervisor
 c. bin\storm ui

hit the browser with localhost:8080 to see the nimbus ui

6.make sure your JAVA_HOME path does not have any space. otherwise storm command
will not run.


"Attempted to read or write protected memory" when filling a DataTable

Question: I am developing some reports using ReportViewer and at certain point I have to connect to an Oracle database to retrieve some data and store it in a DataTable.
When the DataAdapter executes the Fill method I get this error:
"Attempted to read or write protected memory. This is often an indication that other memory is corrupt."
Here's the code(unfortunatelly I can't put that sql code inside a procedure or something):
OleDbConnection objConn = new OleDbConnection(ConfigurationManager.ConnectionStrings["Premio"].ConnectionString);
        OleDbCommand objCmd = new OleDbCommand();
        DataTable objDt = new DataTable();
int vTipoTerr = LoadTipoTerritorio(ReportParameter.ReportData.Parameters.Item("pTerritorio").Value.ToString());
            string vDataParametroDataFinal = ReportParameter.ReportData.Parameters.Item("pMesAnoCompetencia").Value.ToString();
            int vDataInicial = int.Parse(vDataParametroDataFinal.Substring(0, 4));
            vDataInicial = vDataInicial - 1;
            vDataInicial = int.Parse(vDataInicial.ToString() + vDataParametroDataFinal.Substring(4, 2));

objCmd.CommandText = "SELECT   T.Nome, " +
                                 "          T.Prontuario, " +
                                 "          C.Cobertura, " +
                                 "          Cn.Mesano_competencia, " +
                                 "        G.Grupo, " +
                                 "        T.Territorio, " +
                                 "        N.Negocio " +
                                 "     FROM Calculo C " +
                                 "    Inner Join Territorio T " +
                                 "       ON C.Id_Territorio = T.Id_Territorio " +
                                 "    Inner Join Grupo G " +
                                 "       ON C.Id_Grupo = G.Id_Grupo " +
                                 "    Inner Join Cenario Cn " +
                                 "       On Cn.Id_cenario = C.Id_cenario " +
                                 "    Inner Join Negocio N " +
                                 "       On Cn.Id_negocio = N.Id_negocio " +
                                 "    Where Cn.Mesano_competencia Between :p1 And :p2 --datas " +
                                 "      And G.Grupo = :p3 " +
                                 "      And Sub_terr(T.Territorio, Decode(:p4, 1, 'SETOR', 2, 'DISTRITO', 3, 'REGIONAL')) = :p5 " +
                                 "      And (Cn.Flag_cenario_disp = 1 Or Cn.Flag_cenario_disp_rec = 1) " +
                                 "      And N.Negocio = :p6 " +
                                 "      And Cn.Flag_recuperacao = 0 " +
                                 "      Order By Cn.Mesano_competencia; " +
                                 "union all " +
                                 "SELECT T.Nome, " +
                                 "        T.Prontuario, " +
                                 "        C.Cobertura, " +
                                 "        Cn.Mesano_competencia, " +
                                 "        G.Grupo, " +
                                 "        T.Territorio, " +
                                 "        N.Negocio " +
                                 "     FROM Calculo_Rec C " +
                                 "    Inner Join Territorio T " +
                                 "       ON C.Id_Territorio = T.Id_Territorio " +
                                 "    Inner Join Grupo G " +
                                 "       ON C.Id_Grupo = G.Id_Grupo " +
                                 "    Inner Join Cenario Cn " +
                                 "       On Cn.Id_cenario = C.Id_cenario " +
                                 "    Inner Join Negocio N " +
                                 "       On Cn.Id_negocio = N.Id_negocio " +
                                 "    Where Cn.Mesano_competencia Between :p1 And :p2  " +
                                 "      And G.Grupo = :p3 " +
                                 "      And Sub_terr(T.Territorio, Decode(:p4, 1, 'SETOR', 2, 'DISTRITO', 3, 'REGIONAL')) = :p5 " +
                                 "      And (Cn.Flag_cenario_disp = 1 Or Cn.Flag_cenario_disp_rec = 1) " +
                                 "      And N.Negocio = :p6 " +
                                 "      And Cn.Flag_recuperacao = 1 " +
                                 "      Order By Cn.Mesano_competencia ";
objCmd.Parameters.Add(new OleDbParameter("p1", OleDbType.Integer)).Value = vDataInicial;
            objCmd.Parameters.Add(new OleDbParameter("p2", OleDbType.Integer)).Value = int.Parse(vDataParametroDataFinal);
            objCmd.Parameters.Add(new OleDbParameter("p3", OleDbType.VarChar, 30)).Value = ReportParameter.ReportData.Parameters.Item("pGrupo").Value.ToString();
            objCmd.Parameters.Add(new OleDbParameter("p4", OleDbType.Integer)).Value = vTipoTerr;
            objCmd.Parameters.Add(new OleDbParameter("p5", OleDbType.VarChar, 30)).Value = ReportParameter.ReportData.Parameters.Item("pTerritorio").Value.ToString();
            objCmd.Parameters.Add(new OleDbParameter("p6", OleDbType.VarChar, 30)).Value = ReportParameter.ReportData.Parameters.Item("pNegocio").Value.ToString();

            OleDbDataAdapter objAdapter = new OleDbDataAdapter(objCmd);

            objConn.Open();

            objAdapter.Fill(objDt);

            objConn.Close();

Thank you very much (:
Answer: Try using OracleCommand and OracleConnection objects instead:
OracleConnection objConn = new OracleConnection (ConfigurationManager.ConnectionStrings["Premio"].ConnectionString);
    OracleCommand objCmd = new OracleCommand ();

Comment: What just solve is that I splitted the Select with union in 2 different commands and filled the DataTable twice. Not sure about what was wrong but its ok now. Thanks again.


Dropdown menu hides behind other elements in IE

Question: I have installed the Boldy theme from site5 on one of my projects and have run into one major problem.
When browsing in internet explorer (8 or lower), the top dropdown menu gets displayed behind some other elements (main content slider, H1's etc.). I've tried everything from changing all the z-index's to fixed positions, with no luck.
You can view the problem by visiting site5's Boldy demo page http://wordpress.site5.net/boldy/ and hovering over the top menu's blog tab in IE.
I have asked site5 to look into it, they are aware of the problem, but have failed to find any solutions.
Answer: Ok originale solution here - Swiss credit website. This works but uses a complicated z-index solution.
Here is very simple and improved solution here - Jeyjoo stock image gallery
This works in IE6+, firefox, opera, safari and chrome
Solution
The HTML

    NAV BAR GOES HERE

    ...body text...

The CSS
#container_page #container_header {position:relative;z-index:2;}
#container_page #container_body {position:relative;}

why it works
You have to tell IE how the two divs relate to one another.
Comment: i would just like to tell people that i hate ie 8, thank you though , i really needed that, i had no idea what was going on
Answer: (not my script) Pretty sure i may have found the answer to this on here, but i cant find it. Either way, this worked great for me...
$(function() {
var zIndexNumber = 1000;
$('ul').each(function() {
    $(this).css('zIndex', zIndexNumber);
    zIndexNumber -= 10;
});
});

just make sure your css includes position and z-index so the script can access the values.
kudos to whomever came up with this - saved me a whole lot of trouble.
Answer: If I'm not mistaken, IE is not properly inheriting the z-index from the top-nav for the children li items in the menu. That is why the Photos with a z-index of 60 are covering it up. You can do two things here.

Eliminate the photo z-index.
Directly specify a z-index of 100 for the sub list, not just the top-nav list.
Answer: I see you still havent solved this on.
I found a solution here on a submenu - Chkredit - swiss credit website
Works in all versions of IE and is light and 100% CSS (no javascript).
Basically the problem was that IE does not use z-index correctly.
Check the z-index's in the CSS code. Yo will need to put a z-index -1 on the items your menu is hiding behind.
I working on exactly the same problem for my own image gallery right now (go to "top image" page) - jeyjoo image gallery


Como transformar um Array de Objetos em um Array Simples? Javascript

Question: eu queria saber como eu faço pra transformar um Array de Objeto para um Array Simples somente com um determinado vaor..
Eu tenho isto:
const names = [
  {id:0, name:"Jean"},
  {id:2, name:"Ricardo"},
  {id:4, name:"Letiiicia"},
  {id:5, name:"Dai"},
  {id:7, name:"Tamy"},
  {id:10, name:"Abeu"},

Eu queria retornar isto para:
const names /*ou um novo array, não sei*/ = ['Jean','Ricardo','Leticia','Dai','Tamy','Abeu']

Um novo array somente com os names. Alguem poderia me ajudar ?
Answer: O mais simples é utilizar a função map de Array, que foi precisamente para esse tipo de situações que foi criada. Esta permite-lhe obter um novo array com base numa transformação do array corrente.
No seu caso seria algo como:
names = persons.map(function(person){
    return person.name;
});

Em que persons seria o array de objetos que tinha inicialmente. O map irá chamar a função passada para cada elemento do array, e construir um novo com os retornos obtidos para cada elemento.
Com Arrow Functions fica ainda mais direto, simples e fácil de ler:
names = persons.map(person => person.name);

Que podemos ler da seguinte forma: persons é mapeado sendo que cada person passa a ser person.name.
Veja a funcionar:

const persons = [
  {id:0, name:"Jean"},
  {id:2, name:"Ricardo"},
  {id:4, name:"Letiiicia"},
  {id:5, name:"Dai"},
  {id:7, name:"Tamy"},
  {id:10, name:"Abeu"}
];

const names = persons.map(person => person.name);
console.log(names);
Comment: Muitissimo obrigado, Isac <3
Answer: Uma forma de fazer é a seguinte:
var novoArray = []

for (i = 0; i < names.length; i++) {
   novoArray.push(names[i].name);
}

Comment: Obrigado Paulo
Consegui!!
Answer: Você pode fazer isso:
function myFunction(){

const obj = [
  {id:0, name:"Jean"},
  {id:2, name:"Ricardo"},
  {id:4, name:"Letiiicia"},
  {id:5, name:"Dai"},
  {id:7, name:"Tamy"},
  {id:10, name:"Abeu"}]

const names = obj.map(function(item) {
  return item['name'];
});

alert(names);
}

Comment: Obrigado Fernando!!
Answer:

const persons = [
  {id:0, name:"Jean"},
  {id:2, name:"Ricardo"},
  {id:4, name:"Letiiicia"},
  {id:5, name:"Dai"},
  {id:7, name:"Tamy"},
  {id:10, name:"Abeu"}
];
let result = []

for(const r of persons) {
  result.push(r.name)
}
  console.log(result)
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: outra forma com (for of)


Strategy for analysing stock history data from multiple files with SPSS

Question: I have a folder with a hundred comma separated files (CSVs) of which the filename equals a company stock exchange followed by it's symbol, delimited with a "_", eg: NASDAQ_MSFT.csv
Each file contains historical daily stock information, eg. a csv file looks like:
Date,Open,High,Low,Close,Volume
29-Dec-00,21.97,22.91,21.31,21.69,93999000
28-Dec-00,22.56,23.12,21.94,22.28,75565800
27-Dec-00,23.06,23.41,22.50,23.22,66881000
...
5-Jan-00,55.56,58.19,54.69,56.91,62712600
4-Jan-00,56.78,58.56,55.94,56.31,52866600
3-Jan-00,58.69,59.31,56.00,58.34,51680600

Now, I want to analyse this information (analyse the companies as if the company name is a column field rather than a new list of fields). But there are a couple of issues:

Each company has it's own file with the symbol and exchange as filename
Some companies start at different dates than others. Eg. some might have a range of 30 days while others have a range of 30 months (every step is still 1 day difference though).

I am using SPSS as my analysis tool. My question is, how can I import these files to perform senseful analystical operations on them?
For example, I wish to see the average slope of the open price of all companies together, etc.
Answer: Getting the data into SPSS
Typically when you organize your data, the rows in the data matrix correspond to the units of analysis, and the columns correspond to attributes of those units. Given the description of your data, you have basically three possible units of analysis, companies, days, and companydays. Given the format of your CSV files it will be easiest to either import the data as "days" or "companydays". I'm going to suggest you import it as "company*days" as it is easier to transform the data to the other units of analysis later on if needed in that format.
So to import the data, you can use this syntax (just replace with the right variable names and formats). I just generated this example through the GUI.
GET DATA
  /TYPE=TXT
  /FILE='H:\NASDAQ_MSFT.csv'
  /DELCASE=LINE
  /DELIMITERS=","
  /ARRANGEMENT=DELIMITED
  /FIRSTCASE=2
  /IMPORTCASE=ALL
  /VARIABLES=
  time F3.0
  panel F1.0
  price F16.15.
EXECUTE.
Dataset Name NASDAQ_MSFT.

I would then make a variable that identifies what company the dataset correponds to.
string company (A100).
compute company = "NASDAQ_MSFT".
execute.

After you have loaded the csv files into SPSS datasets, you can then concatenate them together with the add files command. Note this adds new rows to the dataset, not columns, hence the need to make a variable that identifies each company.
ADD FILES file = 'NASDAQ_MSFT'
/FILE = 'OTHER_DATASET'
/FILE = 'OTHER_DATASET'.

This will obviously be tedious, but if it only needs to be done once I would just write a macro to semi automate the job. If this needs to be done periodically I would suggest posting the question to one of the other SPSS forums (links provided in the SPSS tag wiki), I wouldn't be surprised in someone has already made a tool via Python to accomplish this (i.e. getting all the files in one directory and doing whatever you want with them).

Analyzing the data
To be able to give useful advice you need to be able to formulate more specific questions. Different hypotheses would require different answers to your second question. Below I have posted a simulated example getting the average slope against time for all companies (via the split file command) and two plotting examples I cooked up with the GUI. If they are not clear enough just say so in a comment and I will add further explanation. For documentation on SPSS's graph language and other syntax see this page.
*SIMULATING DATA.
input program.
loop #company = 1 to 10.
loop time = 1 to 100.
compute company = #company.
compute price = RV.NORMAL(#company,.10).
variable level company (NOMINAL).
end case.
end loop.
end loop.
end file.
end input program.
execute.

*USING split file to get the average slope against time for every company.
sort cases by company.
split file by company.
REGRESSION
  /MISSING LISTWISE
  /STATISTICS COEFF OUTS R ANOVA
  /CRITERIA=PIN(.05) POUT(.10)
  /NOORIGIN
  /DEPENDENT price
  /METHOD=ENTER time.
split file off.

*Multiple lines on one chart via Chart Builder GUI, note the panel variable needs to be coded as nominal.
GGRAPH
  /GRAPHDATASET NAME="graphdataset" VARIABLES=time price company MISSING=LISTWISE REPORTMISSING=NO
  /GRAPHSPEC SOURCE=INLINE.
BEGIN GPL
  SOURCE: s=userSource(id("graphdataset"))
  DATA: time=col(source(s), name("time"))
  DATA: price=col(source(s), name("price"))
  DATA: panel=col(source(s), name("company"), unit.category())
  GUIDE: axis(dim(1), label("time"))
  GUIDE: axis(dim(2), label("price"))
  GUIDE: legend(aesthetic(aesthetic.color.interior), label("company"))
  ELEMENT: line(position(time*price), color.interior(panel), missing.wings())
END GPL.

*Small multiples via the IGRAPH GUI.
IGRAPH
  /VIEWNAME='Line Chart'
  /X1=VAR(time) TYPE=SCALE
  /Y=VAR(price) TYPE=SCALE
  /PANEL=VAR(company)
  /COORDINATE=VERTICAL
  /YLENGTH=5.2
  /X1LENGTH=6.5
  /CHARTLOOK='NONE'
  /CATORDER VAR(company) (ASCENDING VALUES OMITEMPTY)
  /LINE(MEAN) KEY=ON STYLE=LINE DROPLINE=OFF INTERPOLATE=STRAIGHT BREAK=MISSING.

Comment: This is very helpful, thanks. Your answer will help me get further. I understand the need for more specific questions, which I shall do in the future. Now that I have a starting point, I can get into more specific areas. Thanks again.


iphone image library

Question: I need to work on an image library for iphone/ipad devices. I once saw a sample code in which we could arrange multiple images in landscape format with three images on every screen and image in the center was larger and in front. We could easily scroll through it. I am not able to find this sample code on the net now when I need it.:-(
There was another one where images were arranged in like a file in a drawer. If any one could provide me this code, it will again be a great help
Does someone have these sample code?
Thanks
Pankaj
Answer: Could it have been Coverflow in the Tapku library?
Comment: Thanks Jakob this what I wanted but while searching I found another library which does similar task but with different ways. https://github.com/nicklockwood/iCarousel
Comment: just check this one it is awsome

iphone image library


Why is "drush cc all" failing with "undefined function user_load()"

Question: After updating my Drupal test server to have a fresh copy of the database and code from the production system, "drush cc all" would fail with a message saying

PHP Fatal error:  Call to undefined function user_load() in /usr/share/pear/drush/includes/drupal.inc on line 138

I'm running drush version 6.2.0 with a drupal 7.25 system. I'm using memcache as cache_default_class.
Comment: Can you clear caches via the Performance screen? Does the site work otherwise?
Comment: The site was completely dead, white screen and a fatal PHP error in the apache error log: "PHP Fatal error:  Call to undefined function system_run_automated_cron() in /srv/www/www.imsa.edu/drupal1/includes/common.inc on line 2706"
Comment: Sounds like you're missing some files. Are you sure you copied everything from production?
Comment: jmking, that's what I thought too, but I diffed the files between test and production and they matched exactly (except for settings.php, of course).
Answer: The problem went away after I restarted memcached.
I discovered that by running drush with -d and seeing a PHP error about a $theme value not being a valid index. Tracing the code showed that access to cache_bootstrap was getting empty arrays for the module and theme data.
From now on I plan to restart memcached or flush its cache on my test server after rebuilding its database. (I've done this kind of rebuilding dozens of times before with no issues.)


Javascript variable as function name

Question: const self = {
        element: document.querySelector(selector),
        html: () => self.element,
        on: (event, callback) => {
            self.element.addEventListener(event, callback);
        },
        style: {
            alignContent: (property) => {
                return (property === null) ? self.element.style.alignContent : self.element.style.alignContent = property;
            }
     }
}

I am trying to make it so I have quick access to all CSS style properties with jQuery like selectors it should work as: select('h1').style.alignContent('center'), but the problem is that I would have to make a seperate function for each style property in order for this method to work, is there a way to solve this problem without duplicating a lot of code?
//Duplication example
color: (property) => {
  return (property === null) ? self.element.style.color : self.element.style.color = property;
}

Answer: One way to do this is with a Proxy (mdn):

let elemWrapper = selector => {
  let element = document.querySelector(selector);
  return {
    element,
    html: () => element,
    on: (event, callback) => {
      element.addEventListener(event, callback);
    },
    style: new Proxy({}, {
      get: (obj, prop) => {
        // The user called a function named "prop"
        // We need to return a function that sets the style property named "prop"
        return cssValue => element.style[prop] = cssValue;
      }
    })
  };
};

let bodyElem = elemWrapper('body');
bodyElem.style.backgroundColor('cyan');

Here to prove the concept I've set the body element's background colour using a dynamically named function.
The big downside to this approach is the poor performance of Proxies (an excellent read on Proxy performance is available here).
This means it may be quicker to simply compile a list of all css property names, and define a function for each (never using Proxies). The following code compiles all css property names, to serve as a starting point:

console.log(Object.keys(document.body.style));
Comment: Why does returning a function cssValue give me the argument?
Comment: To clarify - are you asking about the return value of `bodyElem.style.backgroundColor('...')`?
Comment: ```return cssValue => element.style[prop] = cssValue;``` this bit
Comment: That function takes only a css value, and sets it under a given css property name.
Answer: You can use a Proxy to intercept all attempts to get a property.

let selector = '#test';
const self = {
    element: document.querySelector(selector),
    html: () => self.element,
    on: (event, callback) => {
        self.element.addEventListener(event, callback);
    },
    style: new Proxy(Object.create(null), {
        get(target, prop, receiver) {
            if (self.element.style.hasOwnProperty(prop)) {
                return val => {
                    if (val != null) {
                        self.element.style[prop] = val;
                    } else {
                        return self.element.style[prop];
                    }
                }
            }
            throw Error("No such property exists: " + prop);
        }
    })
};
self.style.color('red')
console.log("Color:", self.style.color());

This is a test

You can also wrap this into a general function like so:

const getEnhancedElement = arg => {
  const element = /Element/.test(Object.prototype.toString.call(arg)) ? arg
     : document.querySelector(arg);//accept a HTMLElement or a selector
  return {
    element,
    html: () => element,
    on: (event, callback) => {
      element.addEventListener(event, callback);
    },
    style: new Proxy(Object.create(null), {
      get(target, prop) {
        if (element.style.hasOwnProperty(prop)) {
          return val => {
            if (val != null) {//set value
              element.style[prop] = val;
            } else {//get value
              return element.style[prop];
            }
          }
        }
        throw Error("No such property exists: " + prop);
      }
    })
  };
};
let test = getEnhancedElement("#test");
test.style.color('red')
console.log("Color:", test.style.color());
test.style.textAlign('center');

  This is a test

Answer: I would have something like this:
style: {
    chnageStyle: (propertyName, propertyVal) => {
        return (propertyName === null) ? self.element.style[propertyName] : self.element.style[propertyName] = propertyVal;
    }
}

Then you can call this:
style.changeStyle('alignContent','center');
style.changeStyle('color','orange');

Javascript variable as function name


Euler product of $\sum (2^k n + 1)^{-s}$

Question: do we know for a given $k > 2$ the Euler product of $\ \displaystyle\sum_{n=0}^\infty (2^k n + 1)^{\textstyle-s} \ $ ?
I saw that every prime numbers will appear in it, as well as some non-prime generators of $2^k \mathbb{N} + 1$ (the set $A_k$) :
$$F_k(s) =\sum (2^k n + 1)^{\textstyle-s} = \left(\prod_{\textstyle  p \in \mathcal{P}} \frac{1}{\textstyle 1-p^{\textstyle- e(k,p) s}}\right) \left( \prod_{\textstyle  r \in A_k} \frac{1}{1 - r^{\textstyle  -s}} \right)$$
of course my problem is to describe precisely how looks that set $A_k$,  which is a subset of $2^k \mathbb{N} + 1$, and probably is tightly related to the other generators $p^{\textstyle e(k,p)}$ ?
another way to ask the question would be : how can we predict in some sort the result of the sieve of Eratosthene on the set of integers $\equiv 1 \text{ mod } 2^k $ ?
(some precisions)
given $p$ an odd prime number : $e(k,p)$  is the smallest integer $ \ge 1$ such that $p^{d} \equiv 1 \text{ mod } 2^k$ and there always exists such a $d$, because $p^m \equiv 1 \text{ mod } 2^n \implies$   $p^{2m} \equiv 1 \text{ mod } 2^{n+1}$. this means that every prime  appears as a power of itself in the set $2^k \mathbb{N} +1$ and thus it must appear in the Euler product.
Now the set $A_k$ : it is the set of the  generators of  $2^k \mathbb{N} +1$ which are not prime powers. Indeed, the Euler product is not only onto the primes numbers : for example $21$ is $ \equiv 1 \text{ mod } 4$ but nor $3$ nor $7$ are $ \equiv 1 \text{ mod } 4$ ($3^2$ and $7^2$ are $ \equiv 1 \text{ mod } 4$  but they don't divide $21$) and so $21$ must appear in the Euler product of $\sum_{n=0}^\infty (4n+1)^{-s}$ : $21$ is one of the generators of the set $2^2 \mathbb{N} +1$ . Notice the uniqueness of  the generators of $2^k \mathbb{N} + 1$ and thus the uniqueness of the exponents $e(k,p)$ and the set $A_k$: they can be obtained from the sieve of Eratosthene on $2^k \mathbb{N} + 1$.
After all this, the idea would be that having a sieve of Eratosthene (*) and furthermore having every odd prime appearing as a power of itself as generator, the "topology" of $2^k \mathbb{N} +1$ is very similar to the "topology" of $\mathbb{N}^*$, and maybe it would be possible to derive some recurrences formulas for $A_k$, for $e(k,p)$, for the zeros and poles of $\sum (2^k n +1)^{-s}$, the growth of it's Mertens function ... Of course the fact that $2 F_{k+1}(s) = F_k(s) + \sum (2^k n + 1)^{-s} (-1)^n$ is very useful to link the properties of $F_k(s)$ to $\zeta(s)$.
(*) but no simple functional relation as $\zeta(s)$, even if with some recurrences formulas on $k$, one could maybe define a functional relation different from the usual functionnal relation for Hurwitz zeta functions..
Comment: What are $e(p)$ and $A_k$ ?
Comment: @Lucian : Hi, I added some precisions above.
Answer: I found that $e(k,p) = 2^{k-m}$ where $m$ is the integer such that $p = (2a+1) 2^m +1$
(proof)
consider an odd prime $p \equiv 2^{m}+1 \text{ mod } 2^{m+1}$ :
$p = a 2^m + 1 $ where $a$ is odd $ \implies p^2 = 2^{m+1} \left( a^2 2^{m-1} + a\right)+ 1 \implies p^{\textstyle 2^d}$ is at least $\equiv 1 \text{ mod } 2^{m+d}$.
now if $p^c = a2^l+1$ and $p^d=b2^n+1$ where $a,b$ are odds $\implies p^{c+d} = ab 2^{l+n} + a2^l+b2^n+1$ $ \implies p^{c+d} \equiv 1 \text{ mod } 2^{n+1}$ if and only if $l = n$, so that $p^{\textstyle 2^d}$ is at most $\equiv 1 \text{ mod } 2^{m+d}$.


How do I restore my mongodump backups to my newly sharded architecture? (Mongodb)

Question: I have a directory of bson files (Results from my mongodump).
OK, so I just set up a new architecture for sharding MongoDB.  (2 replica sets--3 servers each, and also 1 config server and 1 mongos server).
I followed the tutorial. It was simple. Basic.
How do I load my database backup into this shard?
Answer: use mongorestore and point it to the mongos server


NextJS having links in the _document

Question: Working on a application which uses NextJS. Having the following problem. When I have a _document file like this:
import Document, { Head, Main, NextScript } from 'next/document';
import Header from '../components/header/header';

export default class MyDocument extends Document {
  render() {
    return (

             // Header is custom component

          <NextScript />

    )
  }
}

And my Header component is as follows:
import React, { Component } from 'react';
import { withRouter } from 'next/router';
import Link from 'next/link';

class navigationMobile extends Component {

    render() {
        return (

                <Link href="/auth">Auth</Link>

        );
    }

}

export default withRouter(navigationMobile);

Because this link is placed outside of the file it will reload the page for some reason. This will lose the application state and ruin UX and kind off defeats the purpose of implementing something with a SPA.
When I place the Header component in a page itself the routing works fine. The problem however is that I would have to put this component in every page.
Question:
Is there a way to not reload the page and still have the header component only in one place of the application?
Comment: Why not import `` in pages like in [docs](https://github.com/zeit/next.js/blob/canary/examples/using-router/pages/index.js)? `` with `` w/o href inside, `withRouter` IMHO to many things mixed. Shouldn't it be `` OR `withRouter` with `` using props from HOC?
Answer: You can use a custom _app.js. This is the correct place where to put a custom layout.
https://github.com/zeit/next.js/tree/master#custom-app
Answer: The entry point in Next.js is the _app.js, every page in the pages folder is rendered from here. Since we want our Header to appear on all pages, this is the best place to get it done. But for readability, let's create a new component, say Layout and import it into _app.js. We render it as shown below. And so, <Component /> gets passed as children prop, we can use in the Layout component later:
_app.js
import Layout from 'components/Layout'

function MyApp({ Component, pageProps }) {
  return (
      <Layout>
          <Component {...pageProps} />
      </Layout>
  );
}

export default MyApp

components/Layout.js
import Header from './Header' // Make sure to import from the right location

const Layout = ({children}) => {
    return (
        <>

            {children} // This is the page meant to be rendered (passed from _app.js)
        </>
    )
}

export default Layout

This way, we can have our Header (or footer or any other shared component) on every page without the page reloading.
Extra:
In our Layout.js we could check which page is being rendered by doing {children.type.name}. Using this, we can render the shared component (Header in this case) conditionally if we don't want it to appear on all pages.

NextJS having links in the _document


Erro ao acessar indices do array pelo nome( foreach-php )

Question: Não estou conseguindo acessar os índices de um array, que é resultado de uma consulta, através do nome das colunas, somente pelos números correspondentes.
<?php

$conexao = mysqli_connect("localhost", "root", "", "bdteste");

function verificaVencidos($conexao){

$query = "select * from tbl_atividades where  atualizado <> 'S'";

$resultado = mysqli_query($conexao, $query);
$lista_resultado = array();

while($pre_lista = mysqli_fetch_array($resultado)){
    array_push($lista_resultado, $pre_lista);
}
    return $lista_resultado;
}

$resultados = verificaVencidos($conexao);

foreach($resultados as $print){

    echo $print[1] . "
";
    echo $print[2] . "
";
    echo $print[3] . "
";
    echo $print[4] . "
";
    echo $print[5] . "
";
    echo $print[6] . "
";
    echo $print[7] . "
";
    echo $print[8] . "
";
    echo $print[9] . "
";
    echo $print[10] . "
";
    echo $print[11] . "
";
    echo $print[12] . "
";
}

desejo acessar dessa forma:
<?php

$conexao = mysqli_connect("localhost", "root", "", "bdteste");

function verificaVencidos($conexao){

$query = "select * from tbl_atividades where  atualizado <> 'S'";

$resultado = mysqli_query($conexao, $query);
$lista_resultado = array();

while($pre_lista = mysqli_fetch_array($resultado)){
    array_push($lista_resultado, $pre_lista);
}
    return $lista_resultado;
}

$resultados = verificaVencidos($conexao);

foreach($resultados as $print){

    echo $print['tipo_atividade'] . "
";

}

porém quando coloco dessa forma retorna o seguinte erro:
Notice: Undefined index: tipo_atividade in
C:\xampp\htdocs\atualizador\atualizador-beta.php on line 23

já acessei outros tópicos com o assunto parecido, porém nenhum deu solução.
resultado do print_r:

Array ( [0] => 93233 [c�digo] => 93233 [1] => 696 [COD] => 696 [2] => 3 FG ADMINISTRA��O (CORDEIRO) [EMPRESAS] => 3 FG ADMINISTRA��O (CORDEIRO) [3] => PRESUMIDO [TRIBUTACAO] => PRESUMIDO [4] => PEDRO [RESPONSAVEL] => PEDRO [5] => GLEISI.R [DESIGNADOR] => GLEISI.R [6] => DCTF [TIPO_ATIVIDADE] => DCTF [7] => [DT_INICIO] => [8] => 2019-09-24 00:00:00 [DT_VENCIMENTO] => 2019-09-24 00:00:00 [9] => [DT_FIM] => [10] => PENDENTE [STATUS] => PENDENTE [11] => [DETALHES] => [12] => [FEEDBACK] => [13] => CONTABIL [DEPARTAMENTO] => CONTABIL [14] => MATRIZ [EMPRESA_ORIGEM] => MATRIZ [15] => [DATA_VISUALIZADO] => [16] => [DATA_FEEDBACK] => [17] => S [ARQUIVO] => S [18] => [DIRETORIO] => [19] => C [EXTRA_URGENTE_COMUM] => C [20] => N [VISUALIZADO] => N [21] => N [ATUALIZADO] => N [22] => [DATA_DETALHES] => [23] => A CONFERIR [CONFERENCIA] => A CONFERIR [24] => [CONFERENTE] => [25] => 1 [QNTD_PROCESSOS] => 1 [26] => [EXTRA_VISUALIZADO] => [27] => [FEEDBACK_VISUALIZADO] => [28] => [URGENTE_VISUALIZADO] => [29] => [OBSERVACOES_PRIVADAS] => [30] => N [DETALHE_VISUALIZADO] => N [31] => [OBSERVACOES_PRIVADAS_VISUALIZADAS] => )
Comment: @AndersonCarlosWoss existe sim, eu consigo acessar ela assim se no select eu ao invés de colocar "select * from" colocar select tipo_atividade from".  O resultado do print_r são todos os dados da consulta: Array ( [0] => 93233 [c�digo] => 93233 [1] => 696 [COD] => 696 [2] => 3 FG ADMINISTRA��O (CORDEIRO) [EMPRESAS] => 3....
Comment: @NicolasPereira mesmo com aspas duplas não vai. Só vai, como falei, se eu colocar "select tipo_atividade from" ao invés de "select * from", porém eu preciso pegar todos os campos na consulta.
Comment: @NicolasPereira você diz dessa forma?  echo $print[1]  ? se sim, assim vai.
Comment: Tem certeza que o nome da coluna é tudo minúsculo mesmo? Não seria `TIPO_ATIVIDADE`?
Comment: Acredito que a solução do @AndersonCarlosWoss vá funcionar, acredito que o campo no banco de dados seja `TIPO_ATIVIDADE`
Comment: @AndersonCarlosWoss cara, foi isso mesmo. Estou familiarizado com o VBA que a consulta não é case sensitive, e também acesso pelo index do array.  Muito obrigado pelas respostas!
Comment: E existe a coluna `tipo_atividade` no banco de dados? Qual o resultado de `print_r($print)`?
Comment: Olá! Acredito que você tenha que utilizar `aspas duplas`, verifiquei na documentação oficial do PHP para a função mysqli_fetch_array e lá apresenta o uso de `aspas dupla`. Segue link da documentação [PHP Doc](https://www.php.net/manual/pt_BR/mysqli-result.fetch-array.php)
Comment: Sim @AndersonCarlosWoss acabei de verificar este meu erro, não olhei o código a undo! já exclui meu comentário.
Comment: @Denied Consegue colocar esta saída do `print_r` na pergunta?
Comment: @Denied você executando o `SELECT * FROM` e na hora de imprimir a variavel você colocar o index dela, da certo? exemplo, execute o `SELECT * FROM` e no  `echo` deixe da seguinte forma: `echo $print[indexDoCampo]."";`
Answer: Lembre-se que PHP é case sensitive; se você cria no banco de dados a coluna TIPO_ATIVIDADE então o PHP irá gerar a chave no array também com o texto em maiúsculas. Faz diferença acessar as posições TIPO_ATIVIDADE, tipo_atividade, Tipo_Atividade, etc. Muito cuidado com isso.
Outra coisa, seu laço para gerar um array a partir dos resultados é completamente desnecessário:
$resultado = mysqli_query($conexao, $query);
$lista_resultado = array();

while($pre_lista = mysqli_fetch_array($resultado)){
    array_push($lista_resultado, $pre_lista);
}

return $lista_resultado;

Ao invés disso use mysqli_fetch_all que já retornará todos os registros em um array:
$resultado = mysqli_query($conexao, $query);

return mysqli_fetch_all($resultado);

E, ainda, se precisa apenas a forma associativa do resultado, você pode informar à função para não gerar os índices numéricos:
return mysqli_fetch_all($resultado, MYSQLI_ASSOC);


Como pegar o id da view caso tenha asp.net mvc?

Question: Tenho a seguinte situação, no meu _Layout eu estou verificando:
@{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    var view = HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString();
 }

Eu envio esta informação para o controller para que após trocar o idioma da página eu possa voltar para a mesma.

    -

Quero saber como eu posso pegar o  "Id" caso tenha.
Comment: Não seria mais fácil pegar a url completa?
Comment: pode tentar utilizar viewBag
Comment: @EduardoSampaio, eu precisava de um exemplo, agradeço
Answer: A solução:
Seguindo como referência RoutConfig
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

Ficou desta forma na view:
@{
    var controller = HttpContext.Current.Request.RequestContext.RouteData.Values["Controller"].ToString();
    var view = HttpContext.Current.Request.RequestContext.RouteData.Values["action"].ToString();
    var id = HttpContext.Current.Request.RequestContext.RouteData.Values["id"];
 }

Estou enviando os dados para o controller assim:

    -

Recebo os dados:
public ActionResult AlteraIdioma(string LinguagemAbreviada, string NomeControler, string NomeView, string IdPagina)

Redirecionar para a mesma página:
return RedirectToAction(NomeView, NomeControler, new { id=IdPagina});


javascript createObjectURL corrupt file

Question: im using the following javascript to create an object url, the only problem is when loading the url blob:http:///mysite.com/randomhash the file is corrupt.
var audioFile = null;
var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
         if (this.readyState == 4 && this.status == 200) {
              audioFile = new Blob([xhttp.response], {type: 'audio/mp3'});
          }
        };
        xhttp.open("GET", "myMp3File.mp3", false);
        xhttp.send();

var file = new File([audioFile], "myMp3File.mp3", {type: "audio/mp3", lastModified: Date.now()});

any ideas as to why this would create a blob url with a corrupt mp3 ?
Answer: Multiple problems here.
First, you are dealing with asynchronous code. You will need to use a callback in order to use the response of your XHR request.
Then, even if you did so, there are good chances that it will still not work.
This is because the response you get is plain text UTF16 and that some bytes will get mangled by encoding.
The real solution in your case is to directly request the response as a Blob.
You can do so with the XMLHttpRequest.responseType parameter.
var xhttp = new XMLHttpRequest();
xhttp.responseType = 'blob';
xhttp.onload = function(e) {
  var blob = xhttp.response;
  callback(blob);
};
xhttp.open...

And now in your callback you will be able to create a blobURI directly from this blob.
function callback(blob) {
  var url = URL.createObjectURL(blob);
  ...

Also, if all you want is to display this file, there is no point in creating a File from it, the only web API it would make a difference if it was a File and not just a Blob is Formdata.append method, and even there, it's not that useful.

javascript createObjectURL corrupt file


Why is my hashset so memory-consuming?

Question: I found out the memory my program is increasing is because of the code below, currently I am reading a file that is about 7GB big, and I believe the one that would be stored in the hashset is lesson than 10M, but the memory my program keeps increasing to 300MB and then crashes because of OutofMemoryError. If it is the Hashset problem, which data structure shall I choose?
    if(tagsStr!=null) {
        if(tagsStr.contains("a")||tagsStr.contains("b")||tagsStr.contains("c")) {
            maTable.add(postId);
        }
    } else {
        if(maTable.contains(parentId)) {
            //do sth else, no memories added here
        }
    }

Comment: I think it is unlikely a HashSet problem unless you are putting a lot of data in it. What is the size of the strings you are storing? Are you reading the entire file into memory or one line at a time? The data you have provided here does not really give enough information to help.
Comment: And what is the average length / size of the elements?
Comment: How many items does your table contain before crashing?
Comment: look at http://www.javaspecialists.eu/archive/Issue193.html
Comment: I just followed the size of the HashSet, when it cracks, it has 86,000 elements of String in it, are they the reason to the memory failure?
Answer: You haven't really told us what you're doing, but:

If your file is currently in something like ASCII, each character you read will be one byte in the file or two bytes in memory.
Each string will have an object overhead - this can be significant if you're storing lots of small strings
If you're reading lines with BufferedReader (or taking substrings from large strings), each one may have a large backing buffer - you may want to use maTable.add(new String(postId)) to avoid this
Each entry in the hash set needs a separate object to keep the key/hashcode/value/next-entry values. Again, with a lot of entries this can add up

In short, it's quite possible that you're doing nothing wrong, but a combination of memory-increasing factors are working against you. Most of these are unavoidable, but the third one may be relevant.
Comment: Are you sure about your third point - "reading lines with BufferedReader"?  I thought BufferedReader took care to use new String(...) itself. I agree with the bit about substrings.
Comment: @PaulCager: It certainly didn't last time I looked. Last I checked, it read into a buffer char array (defaulting to 80 chars IIRC), and then created a new `String` which is a view onto that char array. If the array was much bigger than the "usable string" then you can waste a lot of memory. This was a while ago, so it may have changed.
Comment: It looks to have changed - it will now either return a String built via a StringBuffer (if overflows cb), or do a "str = new String(cb, startChar, i - startChar);" where cb is the buffer.
Comment: @PaulCager: Right - but in both cases that could end up with a larger backing buffer than the logical string.
Answer: You've either got a memory leak or your understanding of the amount of string data that you are storing is incorrect.  We can't tell which without seeing more of your code.
The scientific solution is to run your application using a memory profiler, and analyze the output to see which of your data structures is using an unexpectedly large amount of memory.

If I was to guess, it would be that your application (at some level) is doing something like this:
String line;
while ((line = br.readLine()) != null) {
    // search for tag in line
    String tagStr = line.substring(pos1, pos2);
    // code as per your example
}

This uses a lot more memory than you'd expect.  The substring(...) call creates a tagStr object that refers to the backing array of the original line string.  Your tag strings that you expect to be short actually refer to a char[] object that holds all characters in the original line.
The fix is to do this:
    String tagStr = new String(line.substring(pos1, pos2));

This creates a String object that does not share the backing array of the argument String.
UPDATE - this or something similar is an increasingly likely explanation ... given your latest data.

To expand on another of Jon Skeet's point, the overheads of a small String are surprisingly high.  For instance, on a typical 32 bit JVM, the memory usage of a one character String is:

String object header for String object: 2 words
String object fields: 3 words
Padding: 1 word (I think)
Backing array object header: 3 words
Backing array data: 1 word

Total: 10 words - 40 bytes - to hold one char of data ... or one byte of data if your input is in an 8-bit character set.
(This is not sufficient to explain your problem, but you should be aware of it anyway.)
Comment: I'd like to add that in general it is also possible that sharing of backing arrays of Strings leads to a reduced memory consumption. This depends on how many strings share a backing array, and which part of the backing array isn't used by any of the Strings.
Comment: It is theoretically possible, but it seems unlikely in the OP's case.
Answer: Couldn't be it possible that the data read into memory (from the 7G file) is somehow not freed? Something ike Jon puts... ie. since strings are immutable every string read requires a new String object creation which might lead to out of memory if GC is not quick enough...
If the above is the case than you might insert some 'breakpoints' into your code/iteration, ie. at some defined points, issue gc and wait till it terminates.
Comment: You will not get an OOM if GC isn't quick enough. If necessary GC will pause the whole VM and do a stop-the-world collection before throwing OOM.
Comment: Thank you for your response. In fact I was unaware of the fact that GC is triggered automatically in a blocking mode if necessarry:) However it seems that even with this method an OOM might still occur. See the related question: http://stackoverflow.com/questions/1393486/what-does-the-error-message-java-lang-outofmemoryerror-gc-overhead-limit-excee and specifically the official article it references: http://www.oracle.com/technetwork/java/javase/gc-tuning-6-140523.html#par_gc.oom
Comment: "The parallel collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown." That is if GC has too much to work (too much object too free) an OOM might be thrown. Hence in such cases application-driven GC might help, might not?
Answer: Run your program with -XX:+HeapDumpOnOutOfMemoryError. You'll then be able to use a memory analyser like MAT to see what is using up all of the memory - it may be something completely unexpected.
Comment: It sounds like you have run  out of disk space.
Comment: Thanks, I tried using MAT, but it kept failing like this:           Dumping heap to java_pid4080.hprof ...
Dump file is incomplete: Not enough space                                                               Is there any way to solve this?

Why is my hashset so memory-consuming?


Drupal Multisite Creation using the same code base with multiple content databases

Question: I am trying to create a multisite Drupal install which uses the same code base and a unique database for each site. I'm attempting to use the multisite wizard module to do this.

After completing the above steps, when I select site 1 as 'From site' and site 2 as 'To site', the site 1 database is empty and its tables are inside the database for site 2. How can i have separate databases for my sites?
Comment: FYI: I've downvoted this because of the poor grammar, intentional spelling errors, and pseudo-language you've got going on. It's clear you've made no effort to ask a good quality question for our repository. Please treat this site with the respect that it deserves, and ask a proper, well-structured and formatted question.
Comment: sorry i modified it can you help in this now
Comment: Hello. I cleaned your question as much as I was able to. You can see the point where I gave up. I honestly don't understand what you are asking here. Bad language is despised on this site not because we are language purists. The main, maybe only reason is that bad language prevents good understanding. @Clive it seems OP tried. Do you understand him better than I do? If so, could you help? Because I reached limits of my abilities here.
Answer: Looks like your using the drupal module Multisite wizard
This module doesn't seem to support one core multiple databases, only one core one database with multiple table prefixes. So all your data will be in the same Database in different prefixed tables.


How can I change the value of an objects property IF and only IF that value meets a certain condition? (Javascript)

Question: I have the following code for a dynamic Polybius square:
/*
  1 2 3 4 5
1 A B C D E
2 F G H I K
3 L M N O P
4 Q R S T U
5 V W X Y Z
*/
alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZ';
tiles = {
A : {letter: alphabet.charAt(0), x: 1, y: 1},
B : {letter: alphabet.charAt(1), x: 2, y: 1},
C : {letter: alphabet.charAt(2), x: 3, y: 1},
D : {letter: alphabet.charAt(3), x: 4, y: 1},
E : {letter: alphabet.charAt(4), x: 5, y: 1},
F : {letter: alphabet.charAt(5), x: 1, y: 2},
G : {letter: alphabet.charAt(6), x: 2, y: 2},
H : {letter: alphabet.charAt(7), x: 3, y: 2},
I : {letter: alphabet.charAt(8), x: 4, y: 2},
K : {letter: alphabet.charAt(9), x: 5, y: 2},
L : {letter: alphabet.charAt(10), x: 1, y: 3},
M : {letter: alphabet.charAt(11), x: 2, y: 3},
N : {letter: alphabet.charAt(12), x: 3, y: 3},
O : {letter: alphabet.charAt(13), x: 4, y: 3},
P : {letter: alphabet.charAt(14), x: 5, y: 3},
Q : {letter: alphabet.charAt(15), x: 1, y: 4},
R : {letter: alphabet.charAt(16), x: 2, y: 4},
S : {letter: alphabet.charAt(17), x: 3, y: 4},
T : {letter: alphabet.charAt(18), x: 4, y: 4},
U : {letter: alphabet.charAt(19), x: 5, y: 4},
V : {letter: alphabet.charAt(20), x: 1, y: 5},
W : {letter: alphabet.charAt(21), x: 2, y: 5},
X : {letter: alphabet.charAt(22), x: 3, y: 5},
Y : {letter: alphabet.charAt(23), x: 4, y: 5},
Z : {letter: alphabet.charAt(24), x: 5, y: 5},
};

At a certain point I will want to swap rows and columns.  For example, if I want row 1 and row 2 to swap, I will change the x value of every tile whose x == 1 to 2, and vice versa.
How could I do that?
EDIT:
With the first answer's code I'm getting "cannot read property x of undefined" error:
    function getLetterCoords(letter)
    {
    coords = [];
    Object.values(tiles).map(tile =>
        {
            if(tile.letter === letter)
                {
                coords['x'] = tile.x;
                coords['y'] = tile.y;
                }
        return coords;
        })
    }

function getLetterFromCoords(coords)
    {
    Object.values(tiles).map(tile =>
        {
            if ((tile.x === coords['x']) && (tile.y === coords['y']))
                {
                return tile.letter;
                }
        })
    }

function encrypt()
    {
    plaintext = document.getElementById('plaintext').value;
    key = document.getElementById('key').value;
    ciphertext = '';

    for (var i = 0; i < plaintext.length; i++)
        {
        plaintextCoords = getLetterCoords(plaintext.charAt(i));
        keyCoords = getLetterCoords(key.charAt(i));
        ciphertext += getLetterFromCoords(keyCoords);
        }

    document.getElementById('ciphertext').value = ciphertext;
    }

Comment: Any luck with the answers provided?
Comment: Yeah! I just accepted an answer.  I'm sure the others work also but I'm trying to work with the first one at the moment.
Answer: Use a simple loop that checks the tile X or Y and changes it:
function swapRows(tiles, y1, y2) {
  const newTiles = {};

  for (const [key, tile] of Object.entries(tiles)) {
    // If the tile is from the first row, change its row to the second
    if (tile.y === y1) {
      newTiles[key] = {...tile, y: y2};
      continue;
    }

    // If the tile is from the second row, change its row to the first
    if (tile.y === y2) {
      newTiles[key] = {...tile, y: y1};
      continue;
    }

    // Otherwise don't change
    newTiles[key] = tile;
  }

  return newTiles;
}

const swappedTiles = swapRows(tiles, 1, 2);

Object.entries returns an array containing all the object keys (a.k.a. attributes, properties) and their values.
My example is a pure function which is the #1 trend in JavaScript today. It can be a little simpler without a purity.
Answer:         // Convert to array, then go through each
        Object.values(tiles).forEach(tile => {
                // do what ever check you want in here
                if(tile.letter === 'W') {
                        tile.x = 0;
                        tile.y = 0;
                }
        })

        console.log(tiles); // Will now show the change

Answer: Convert to array and use map and get return of changes

var alphabet = 'ABCDEFGHIKLMNOPQRSTUVWXYZ';
var tiles = {
A : {letter: alphabet.charAt(0), x: 1, y: 1},
B : {letter: alphabet.charAt(1), x: 2, y: 1},
C : {letter: alphabet.charAt(2), x: 3, y: 1},
D : {letter: alphabet.charAt(3), x: 4, y: 1},
E : {letter: alphabet.charAt(4), x: 5, y: 1},
F : {letter: alphabet.charAt(5), x: 1, y: 2},
G : {letter: alphabet.charAt(6), x: 2, y: 2},
H : {letter: alphabet.charAt(7), x: 3, y: 2},
I : {letter: alphabet.charAt(8), x: 4, y: 2},
K : {letter: alphabet.charAt(9), x: 5, y: 2},
L : {letter: alphabet.charAt(10), x: 1, y: 3},
M : {letter: alphabet.charAt(11), x: 2, y: 3},
N : {letter: alphabet.charAt(12), x: 3, y: 3},
O : {letter: alphabet.charAt(13), x: 4, y: 3},
P : {letter: alphabet.charAt(14), x: 5, y: 3},
Q : {letter: alphabet.charAt(15), x: 1, y: 4},
R : {letter: alphabet.charAt(16), x: 2, y: 4},
S : {letter: alphabet.charAt(17), x: 3, y: 4},
T : {letter: alphabet.charAt(18), x: 4, y: 4},
U : {letter: alphabet.charAt(19), x: 5, y: 4},
V : {letter: alphabet.charAt(20), x: 1, y: 5},
W : {letter: alphabet.charAt(21), x: 2, y: 5},
X : {letter: alphabet.charAt(22), x: 3, y: 5},
Y : {letter: alphabet.charAt(23), x: 4, y: 5},
Z : {letter: alphabet.charAt(24), x: 5, y: 5},
};

Object.values(tiles).map(tile => {
  if(tile.letter === 'A') {
    tile.x -= 1;
    tile.y += 1;
  }
  return tile;
})

console.log(tiles);


Do these results also hold for automorphisms?

Question: Let $G, G_1, G_2,..., G_n$ be groups.
I know the following results:
a) If $G$ is abelian, then $\operatorname{Hom}(G_1 \times G_2 \times \dots \times G_n, G)\cong \operatorname{Hom}(G_1,G)\times \operatorname{Hom}(G_2,G)\times \dots \times \operatorname{Hom}(G_n,G)$
(you may find a proof here: https://ysharifi.wordpress.com/2019/09/26/group-homomorphism-direct-product-1/ )
b) If $G_1, G_2,..., G_n$ are all abelian, then $\operatorname{Hom}(G, G_1 \times G_2 \times \dots \times G_n)\cong \operatorname{Hom}(G, G_1)\times \operatorname{Hom}(G, G_2) \times \dots \times \operatorname{Hom}(G, G_n)$
(you may find a proof here: https://ysharifi.wordpress.com/2019/09/26/group-homomorphism-direct-product-2/)
I was wondering if these results also hold if we replace $\operatorname{Hom}$ by $\operatorname{Aut}$. I believe that they should, since automorphisms are homomorphism, so the proofs from the links above should still work). If they do not, I would be interested if something similar exists for $\operatorname{Aut}$.
EDIT: As pointed out, these results do not hold for $\operatorname{Aut}$. I would like to know if there is something similar for $\operatorname{Aut}$, though.
A little bit more info: when dealing with the number of endomorphisms of an abelian group these results are pretty useful because I can use the structure theorem and then apply them. Now I am interested if something similar can be done for automorphisms.
Comment: For (a), the map from the product is surjective but not usually injective. For (b), it is the opposite: the map to the product is injective but not usually surjective.
Comment: If you take $C_2 \times C_2 \times C_2$ you see that its automorphism group is simple ant thus not decomposable into any non-trivial direct products: https://groupprops.subwiki.org/wiki/GL(3,2)
Answer: This is not true for $Aut$ since $Aut(\mathbb{Z}/2\times\mathbb{Z}/2)$ is distint of $Aut(\mathbb{Z}/2)\times Aut(\mathbb{Z}/2)$, the second group is embedded in the first group and does not contain the map $(x,y)\rightarrow (y,x)$ since the groups are finite they dont have the same cardinal.
Remark that if $f$ is an automorphism of $\mathbb{Z}/2$, $f(\bar 0)=\bar 0$ since $\bar 0$ is the neutral, $f(\bar 1)=\bar 1$ since $f$ is bijective, $f$ is the identity. We deduce that $Aut(\mathbb{Z}/2)\times Aut(\mathbb{Z}/2)$ contains only one element, but  $Aut(\mathbb{Z}/2\times\mathbb{Z}/2)$ contains the identity and $f(x,y)=(y,x)$ its cardinality is at least $2$.
Comment: The cardinality of $Aut(C_2 \times C_2)$ is not only $\geq 2$ , it is even equal to $6$. That is because any permutation of the three non-identity elements of $C_2 \times C_2$ induces a unique automorphism (one can check the manually). Thus we have $Aut(C_2 \times C_2) \cong S_3$.


A matrix commuting with a diagonal matrix

Question: Let $A(z)=[a_{ij}(z)]$ be an invertible  $n\times n$ matrix where $a_{ij}(z)$ is entire function (i.e., analytic on all of the complex plane $\mathbb{C}$) for all $i,j=1,2,\dots, n$.
Let $D(z)$ be an $n\times n$ diagonal matrix with non distict (entire) entries $d_{ii}(z)$ $i=1,2,\dots, n$,  such that
$$A(z)D(z)=D(z)A(z)$$
What can we say about the matrix $A(z)$? Is there any characterization of such matrix in terms of $D$?
I know that if $D(z)$ is diagonal with distinct entries then $A(z)$ must be diagonal, but if it's not with "distinct entries" then $A(z)$ is not necessary diagonal.
I appreciate any help!
Comment: Probably looking at spezial cases gives some insight. Try, for example, the case $n=3$, $d_1=d_2=1, d_3=0$.
Answer: Suppose $d_{ii}$ and $d_{jj}$ are two different functions, i.e. $d_{ii}(z)\ne d_{jj}(z)$ for some complex number $z$. By the identity theorem, the zero set $Z$ of $d_{ii}-d_{jj}$ must be isolated. Hence $S=\mathbb C\setminus Z$ has an accumulation point in $S$.
Since $A$ commutes with $D$ but $d_{ii}(z)\ne d_{jj}(z)$ on $S$, we must have $a_{ij}(z)=a_{ji}(z)=0$ on $S$. As $S$ has an accumulation point in itself, we must have $a_{ij}=a_{ji}=0$ on $\mathbb C$ by the identity theorem.
So, if we permute the rows and columns of $D$ so that $D=d_1I_{m_1}\oplus d_2I_{m_2}\oplus\cdots\oplus d_kI_{m_k}$ for some $k$ distinct entire functions $d_1,d_2,\ldots,d_k$, then $A=A_1\oplus A_2\oplus\cdots\oplus A_k$ where each $A_i$ is an $m_i\times m_i$ matrix whose entries are entire functions. In other words, this block-diagonal structure and the block sizes must remain unchanged on $\mathbb C$.
Since $A$ is invertible, each $A_i$s is invertible. However, I don't know how to characterize invertible matrices whose entries are entire functions.
Comment: OK. So the $A_{i}$'s are not in general diagonal, wright!
Comment: @MathGuest They aren't in general diagonal even when $D$ and $A$ are constant matrices.


Display page created using panel programatically

Question: I am using Drupal 7 and Panel module.
I have created custom page using panel module. page-welcome
I want to render this page on the following url user/%user/my-profile
Is there any way to print page programatically..
Answer: You should be able to set the path to /user/%user/my-profile within Panels.  For an example of this, look at the "User edit template" override provided with Panels, which, if enabled, overrides /user/%user/edit.
To set the path in Panels, go to /admin/structure/pages, choose the page you wish to edit, click Basic under Settings, and set the Path.
The help text there states the following:

The URL path to get to this page. You may create named placeholders
  for variable parts of the path by using %name for required elements
  and !name for optional elements. For example: "node/%node/foo",
  "forum/%forum" or "dashboard/!input". These named placeholders can be
  turned into contexts on the arguments form.