Drupal Internationalization / Translation

Question: When you translate a website using the i8ln module it doesn't automatically translate all the words in fields correct?
Also, what do you need to do to efficiently translate all the words ?
Is it a process that requires manually translating all the text with the i8ln module?
I reviewed some drupal documentation about this but it seems to only be germane to contributing local translations to the server: http://drupal.org/node/11130
I'm looking to have the localization server automatically translate it for me.
Answer: I don't know if I completely understand your question correctly, but I think there's some confusion. The Drupal translations from localize.drupal.org and the locale core module, will only help you translate the interface. If there's something missing or you want some custom translations you can always use: http://drupal.org/project/l10n_client - and to keep it up-to date: http://drupal.org/project/l10n_update
The i18n module allows users to translate the content into different languages, but it does not auto-translate. There are some modules that uses Google's APIs to auto translate but one violates Google's TOS and the other one will stop working when google pulls there translation API

http://drupal.org/project/gtrans
http://drupal.org/project/i18n_auto
Comment: Ah thanks. That clears up the confusion. Are there any other methods to auto translate?
Comment: Nevermind. I found this module that looks even better: http://drupal.org/project/gtranslate
Comment: Good find, that module seems to be more maintained than gtrans and has a D7 version unlike i18n_auto. I wonder if the following will affect the gtranslate module too: http://code.google.com/apis/language/translate/overview.html.

If I had a D6 site I would use i18n_auto the developer is a well known on the Drupal community.
Comment: Sorry I think that gtranslate module is worse than useless. Translations produced by google are much worse than translations written by a human translator, and if non-english readers want to use google translate I think they generally know how to find it. As a website operator I would only want to offer a high quality translation.
Comment: I agree but then again that's not the question I was answering, the question author specifically mentions auto translations.
Answer: I found this:
https://drupal.org/project/translation_management
https://drupal.org/project/i18n
More explanations available in this post:
http://www.icanlocalize.com/site/tutorials/howto-translate-drupal-sites/


Generating expecting ) expected { and EOF found } Unity Javascript

Question: Syntax error on line 12 and 22 there doesn't seem to be any missing/extra brackets so it bewilders me what is causing these errors in my update function. Ideally I want the program to be able to Fire four times before having to reload for 8 seconds.

#pragma strict

 var Bullet : Transform;
 var Spawn : Transform;
 var amountOfShots = 4;

 function Update() {
  if (Input.GetKeyDown("r") {
        Reload(); //Calls the reload function
    }

    if (Input.GetButtonDown("Fire1")) {
        //Fires on left click
        Shoot();
        amountOfShots --;
        //Calls shoot function and removes one shot from amountOfShots
    }
}

function Shoot() {
    var pel = Instantiate(Bullet, Spawn.position, Spawn.rotation);
    pel.rigidbody.AddForce(transform.forward * 6000);
    //instantiates bullet at spawn point and adds a force to propel the bullet forward

    if (amountOfShots <= 0) {
        Debug.Log("No ammo left in magazine");
        //Tells player if there is not enough ammo to fire
    }
}

function OnReload()
   "setTimeout(8000, 3000)"
//Waits 8 seconds while reloading

function Reload()
{
    amountOfShots = 4;
    //resets amount of shots to 4
}

Comment: Thankyou guys for fixing the issues. The code seems to work fine (no syntax errors) but the shoot function doesn't seem to be instantiating an actual bullet object. In the unity engine it just spawns a invisible Bullet(clone). Anyone have any idea why that may be? I have an actual bullet prefab in the project
Answer: There is a missing closing bracket in your first if-statement:
if(Input.GetKeyDown("r")

should be
if(Input.GetKeyDown("r"))

Answer: You forgot a closing bracket on line 12 and hence the errors.
if(Input.GetKeyDown("r"))

Try using an IDE that notifies the user about syntax errors. Webstorm and Brackets are good ones.
Thanks
Answer: Functions do not follow the same procedure regarding how many instructions there are inside them as if, else, for and while.
A function must always have braces ({ and }) around their bodies (even if they contain one instruction). So this:
function OnReload()
   "setTimeout(8000, 3000)"

should be this:
function OnReload() {
   "setTimeout(8000, 3000)"; // a ; is optional here (in this case) but it's not a good habbit to ignore them.
}


PHP Parse issue

Question: I am trying to setup my PHP site in my hosting server which is made from Codeigniter 2.2.0. Everything is fine only $end_date = $end_date ?: $start_date; this line of code generate a parse error -saying Parse error:
syntax error, unexpected ':' .

My hosting server php version is 5.2. How can I avoid this error?
Answer: In PHP, shorthand ternary operator is only available since version 5.3.
Quote:

Since PHP 5.3, it is possible to leave out the middle part of the
  ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1
  evaluates to TRUE, and expr3 otherwise.
Answer: Try this
$end_date = (!empty($end_date)) ? $end_date : $start_date;

Comment: thanks. Would you please tell me what is difference between of two lines.
Comment: There is no need to use [`empty()`](http://php.net/manual/en/function.empty.php). Evaluating `$end_date` in boolean context (as it happens when it is the first operand of the [ternary conditional operator](http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary)) is [the same as `! empty($end_date)`](http://php.net/manual/en/types.comparisons.php).
Comment: @Treadstone there is [no difference between `$end_date` and `! empty($end_date)` in this context](http://php.net/manual/en/types.comparisons.php).
Comment: @axiac if, for example, `$end_date = ' ';`the `!empty()` check is useful
Comment: `empty(' ') === FALSE`. Compare the columns `empty()` and `boolean: if($x)` from the first table displayed in the ["Comparisons of $x with PHP functions" page](http://php.net/manual/en/types.comparisons.php). `if ($x)` (or `$x ? ... : ...`) is the same as `if (! empty($x))` for any value of `$x`.
Answer: local and host PHP versions were differents.
This code solved in booth.
$end_date = (!empty($end_date)) ? $end_date : $start_date;

Comment: There is no need to use [`empty()`](http://php.net/manual/en/function.empty.php). Evaluating `$end_date` in boolean context (as it happens when it is the first operand of the [ternary conditional operator](http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary)) is [the same as `! empty($end_date)`](http://php.net/manual/en/types.comparisons.php).

PHP Parse issue


Where do I set the HTML that wraps a module's config $form inputs?

Question: I am transferring a module from one site to another. All is well except the modules form (where I set settings, upload images, etc). On the original site this is nicely wrapped in a table with each section being a row, but on my new site the form elements are just placed in one after the other, appearing vertically. This is despite me copying the modules .inc, .tpl and .module files almost verbatim.
I'm new to Drupal in general so am struggling with this a bit. Would anyone know where this is set (what file, what function)?
function gallery_grid_theme($existing, $type, $theme, $path) {
  $items = array();

  $items['gallery_grid'] = array(
    'render element' => 'element',
    'path' => drupal_get_path('module', 'gallery_grid') . '/plugins/content_types/gallery_grid/templates',
    'template' => 'gallery-grid',
    'variables' => [],
  );

  // Draggable table for gallery-grid admin form.
  $items['gallery_grid_draggable_form'] = array(
    'render element' => 'fieldset',
    'file' => drupal_get_path('module', 'gallery_grid') . '/plugins/content_types/gallery_grid/gallery_grid.theme.inc',
  );

  return $items;
}

Contents of gallery_grid.theme.inc:
function theme_gallery_grid_draggable_form($variables) {
  $fieldset = $variables['fieldset'];
  $rows = array();

  // Table for the items.
  foreach (element_children($fieldset) as $key) {
    $fieldset[$key]['weight']['#attributes']['class'] = array('item-weight');
    $rows[] = array(
      'data' => array(
        render($fieldset[$key]['image_file']),
        render($fieldset[$key]['image_url']) . render($fieldset[$key]['image_title']),
        render($fieldset[$key]['delete_row']),
        render($fieldset[$key]['weight']),
      ),
      'class' => array('draggable'),
    );
  }

  // Header and render.
  $header = array(t('Image *'), t('Image Settings'), t('Actions'), t('Weight'));
  $table_id = 'items-table';
  $output = theme('table', array(
    'header' => $header,
    'rows' => $rows,
    'attributes' => array('id' => $table_id),
    'sticky' => FALSE,
  ));

  // Add tabledrag.
  drupal_add_tabledrag($table_id, 'order', 'sibling', 'item-weight');
  return $output;
}

Comment: Look in the module for hook_theme(), and add it to your original post. That can likely give us an indication of what's missing.
Comment: @Jaypan Hi Jaypan, have added it above. The 'Draggable table' is what's been copied from the original module
Comment: Did you also copy this file: `drupal_get_path('module', 'gallery_grid') . 'plugins/content_types/gallery_grid/gallery_grid.theme.inc'`?
Comment: @Jaypan yes I did. I've added the contents of that file above. Note I thought it was strange that the fucntion started with `theme_` so tried removing it to no affect.
Comment: What file did you add the contents to? And the function name should be prefixed with `theme_`, so you shouldn't remove that.
Comment: The admin theme may have also implemented form templates and preprocess functions to customize the theme hook above.
Comment: Is that file at the path `drupal_get_path('module', 'gallery_grid') . 'plugins/content_types/gallery_grid/gallery_grid.theme.inc`?
Comment: @Jaypan, yes that's file
Answer: Did you look at form templates? The steps change a little if you are using a starter theme, but the basics are the same.
http://themery.com/dgd7/advanced-theming/forms/with-templates


How do I convert String array into Json Array

Question: I have a string array like string[] sentences which consist of sentences one in each index like This is the first message in sentences[0] and This is the second message in sentences[1] and so on. My java code to send the information to the server for sentiment analysis is like this:
OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
        out.write(
                "[ " +
                "\"Can't wait for the movie\"," +
                "\"Countdown! Only ten days remaining!\" " +
                "]");
        out.flush();
        out.close();

How do I replace the texts above in the code by the string array for it's length say n?
Comment: _How do I add an array of string into the following JSON?_, where is the JSON? this question has nothing to do with JSON.
Comment: Got it, sorry. Anyway, how do I convert this array of string into JSON array?
Answer: Use Gson library, which convert Java object to Json String
    String[] sentences=new String[3];
    sentences[0]="Hi";
    sentences[1]="Hello";
    sentences[2]="How r u?";

    Gson gson=new GsonBuilder().create();
    String jsonArray=gson.toJson(sentences);

    //["Hi","Hello","How r u?"]

    out.write(jsonArray);
    out.flush();
    out.close();

Comment: Hey, I tried that but then I got 200: bad JSON format error as the response. I tried this but I'm not sure whether it's right. It responds with neutral to all.
 `OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
out.write( "[ " + "\"+tweets[0]+\"," + "\"+tweets[1]+\" " + "]");
out.flush();
out.close();` What could be the issue?
Answer: The easiest solution is a loop:
StringBuilder sb = new StringBuilder("[");
for(int i = 0; i < array.length; i++) {
    sb.append(array[i]);
    if(i < array.length-1) {
        sb.append(",");
    }
}
out.write(sb.append("]").toString());

But this has the problem of producing potentially invalid JSON (unescaped). Hence:
The best solution, however, would be to use a proper JSON/Java binding library such as Jackson, Gson, etc.
Comment: Hey, I tried that but then I got 200: bad JSON format error as the response. I tried this but I'm not sure whether it's right. It responds with neutral to all. `OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
    out.write(
            "[ " +
            "\"+tweets[0]+\"," +
            "\"+tweets[1]+\" " +
            "]");
    out.flush();
    out.close();`   What could be the issue?
Comment: As I pointed out, this can produce invalid json. That's why you're highly encouraged to use Jackson or Gson.
Comment: `StringBuilder sb=new StringBuilder();
   sb.append("[ \"");
   for(int x=0;x<val;x++)
   {
    String a=xyz[x].replaceAll("[^A-Za-z0-9]"," ");
    sb.append("+");
    sb.append(a);
    if(x < val-1)
    {
     sb.append("+\",\"");
    }
   }
    sb.append("+\" ]");
    System.out.println(sb.toString());
    out.write(sb.toString());`
This worked perfectly for me. Thanks a lot!


Computing the $\lim_{h\rightarrow0}\frac{2^{2+h}-2^2}{(2+h)-2}$

Question: I'm trying to use this function to compute the derivative.
$$\lim_{h\rightarrow0}\frac{f(x+h)-f(x)}{(x+h)-x}$$
But I'm stuck when I attempt to find the derivative of $f(2)$ for $f(x) =x^2$
The power rule suggests that I should obtain $nx^{n-1}$ as the result but I have no idea how to compute this limit:
$$\lim_{h\rightarrow0}\frac{2^{2+h}-2^2}{(2+h)-2}$$

[updates]
Comment: It should be $(2+h)^2$ not $2^{2+h}$
Comment: @Ethan Aha! Thank you! But I still want to know how should that limit be computed.
Answer: Hint: $f(2+h) = (2+h)^2 = 4+4h+h^2$ rather than $2^{2+h}$.
Note that $\displaystyle\lim_{h\to 0}\frac{2^{h+2}-2^2}{(2+h)-2} = \left.\frac{\mathrm{d}}{\mathrm{d}x}\right|_{x=2} 2^x = \left.\frac{\mathrm{d}}{\mathrm{d}x}\right|_{x=2} e^{x\ln(2)} = \ln(2)2^x|_{x=2} = 4\ln(2)$.
Proving this limit from the definition would probably be very messy.
Comment: Thanks for pointing my careless mistake out! But I still want to know how to compute this limit: $$\lim_{h\rightarrow0}\frac{2^{2+h}-2^2}{(2+h)-2}$$
Comment: So you actually want $g^\prime(2)$ for $g\colon x\mapsto 2^x$?
Comment: Nope, I know how solve that already. But now I still want compute this limit: $$\lim_{h\rightarrow0}\frac{2^{2+h}-2^2}{(2+h)-2}$$
Comment: Yes, that is the definition of $\left.\frac{\mathrm{d}}{\mathrm{d}x}\right|_{x=2}(2^x)$.
Answer: So what you have is precisely $$\lim_{h \to 0 } 4 \cdot\frac{ 2^{h} -1}{h}$$ and this is nothing but the derivative of $f(x) = 2^{x}$ evaluated at $0$.


How to show last login time and user email to all authenticated users?

Question: I have created a view for user profile page. I also want to show the user's current email address and last login time. It is working fine for admin but email and last login time is not visible to authenticated user on front end.
I have granted the View User Information permission to authenticated users but no success after that too.
Is it a permission issue or something else ?
What I am missing ?
Comment: I have the same behavior, very strange, maybe a bug?
Answer: EDIT:
I set up a test View myself and confirmed the issue you reported. Upon some search, I see this is intended behaviour.
There is a thread discussing it here: https://www.drupal.org/project/drupal/issues/2799049
The thread has a very simply Core patch to resolve the issue that could be applied. Or, there's also information on using hook_entity_field_access() to grant field-level access to User fields.
https://www.drupal.org/project/drupal/issues/2773645
************************ORIGINAL INFO***************************
From what you've said, it seems like it should work as you'd expect.
One thing you can try is checking the "Disable SQL rewriting" checkbox in your View. This will bypass ALL permission checking for the View. It is located in the Query Options setting in the Advanced section of your View config.
If checking this works then you'll know that,at least, the issue is permissions related.
Comment: Your solution don't solve the problem.
Comment: See new comment edit above.
Comment: I don't think that the patch will solve the problem, I made the view and I can't see my own information, and to see my own information I don't need this permission because I can see my email from my user page.
Comment: The core patch is just to make it *simpler* to then alter the default access rules and make that information visible. You still need some custom code in hook_entity_field_access() or use a contrib module that allows that. I believe there is one mentioned in the issue. Have a look at what the test module in that issue is doing.
Answer: You have to give "Administer users" permission to view the email and last login details of any user.
Note: This permission needs to be given for trusted user.


What is the difference between MeshPhongMaterial and ShaderMaterial in THREEJS

Question: What is the difference between using MeshPhongMaterial and ShaderMaterial with THREE.ShaderLib.phong.

Will Three js internally use the shaders for all materials ?
Will using ShaderMaterial improve performance ?
I have a piece of code which uses MeshPhongMaterial and how do i convert to ShaderMaterial with THREE.ShaderLib.phong.

Here is the code
var material = new THREE.MeshPhongMaterial({ color: 0xffffff, shininess: 35,
            shading: THREE.SmoothShading, combine: THREE.MultiplyOperation, specular: 0x030303, reflectivity: 1 });
How do I specify combine, reflectivity and other properties in ShaderMaterial
Answer: I clear you doubts line by line might be helpful:
What is the difference between using MeshPhongMaterial and ShaderMaterial with THREE.ShaderLib.phong.
MeshPhongMaterial is the Namespace provided you end user by library to make the development faster more easy for those who are from graphics ( dev/designer background )
So Internally if you check library src/renderers/shaders/ShaderLib.js
THREE.ShaderLib['phong'] is mapped to shaderIDs line 29574 three 75 version.
So they are same.
Will Three js internally use the shaders for all materials ?
Answer: OpenGLES 2.0 and above all are shader based technology compare to fixed pipeline to draw stuff on the surface created using EGL.
Will using ShaderMaterial improve performance ?
Answer: Depends what you are looking into three.js shaders are mature enough you could get a peanut if you don't want light vector calculation into fragment shader ( by providing direct vec3 instead of uniform) but this might not be first point to shoot for performance they are many like LOD, Object Pooling etc etc. ( different people might have different opinion about same )
I have a piece of code which uses MeshPhongMaterial and how do i convert to ShaderMaterial with THREE.ShaderLib.phong.
Answer: You can manually Called
var phongShader = THREE.ShaderLib[ 'phong' ]
var shaderMaterial = new THREE.ShaderMaterial( {
 uniform: phongShader.uniform,
 vertexShader: phongShader.vertexShader,
 fragmentShader: phongShader.fragmentShader
});

But you can use extend shader by calling your custom glsl file using the THREE.ShaderChunk too.
How do I specify combine, reflectivity and other properties in ShaderMaterial
Answer: Create your own uniform (the one one which you mention are already supported in material) and then call
THREE.UniformsUtils.merge( [
phongShader.uniform,
{
//to do custom uniform
}
vertexShader:vertexShader,
fragmentShader:fragmentShader
)]
var vertexShader = [

//so on add the shaderChunk Required
].join( '\n' )

var fragmentShader = [
THREE.ShaderChunk[ "common" ],
//so on add the shaderChunk Required
//call your custom uniform which you have supplied into the final gl_FragColor
].join( '\n' )

Seeing your problem IMHO you won't need to change in the vertexShader you can edit the fragmentShader directly using your custom paramters.
Answer: You can probably think of a MeshPhongMaterial as a ShaderMaterial but with all the hard work done for you (variables, fragment and vertex shader).

Yes, all materials are a shader (send shader code to the gpu).
Depends on your shader.
Why would you want to recreate it? You could though. You should probably understand how the materials work before attempting it.

I have a page of my own experiments with ShaderMaterial you could take a look at.
I also took a look at the built in materials/shaders for my own reference here.
Note though, the three.js materials and how they are made up has changed a bit since I posted these. But my shader experiments might be a bit of a help.
I also have a fiddle here which extends the ShaderMaterial class, effectively making my own material class (though this was just an experiment and I'm not sure if it's the best, or even the correct way to do it.)
...

Answer: They are not really the same, because the renderer has built-in updating of special uniforms for the MeshPhongMaterial, whereas some ShaderMaterial uniforms have to be updated manually. That being said, I don't have the complete overview, which at least requires inspecting details the source code of THREE.WebGLRenderer.
What I can tell for sure, is that
let mat = new THREE.MeshPhongMaterial();

works, and that
let mat = new THREE.ShaderMaterial(THREE.ShaderLib.phong);

fails with error messages about uniforms. This can, at least in part, also be caused by missing default values.
EDIT: I was wrong.
It works if you add
mat.lights = true;

You may also want to use mat.fog = true to enable fog. If you specify the shader object parts (uniforms, vertexShader, fragmentShader) individually, you can also add "lights: true" and "fog: true"  to the parameters to the ShaderMaterial constructor.


How to create a dropdown list with node ids?

Question: I need to create a dropdown list box which contains the list of node ids of a specific content type. Then after selecting the node id in the dropdown i need the content of the node to be displayed below the dropdown.
Iam new to drupal. Is there any way to create the dropdown list box with the features...?
Answer: To get all the nodes ID's for a content-type, you can use EntityFieldQuery and node_load_multiple:
<code>$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'mycontenttype')
  ->execute();
$nodes = node_load_multiple(array_keys($result['node']));
</code>
If you are using FAPI (form API), you can populate your dropdown list with these values easily.
Unfortunately, I can't help with the last part (displaying the node under the form).
Answer: Get a list of nodes of a specific type, assuming $type contains your content type, use node_load_multiple:
<code>$nodes = node_load_multiple(array(), array('type' => $type));
</code>
Create a select using the Form API in a custom module.


Deny node access based on custom field value (Using Code)

Question: I'm new in Drupal so please bare with me. I am looking to restrict access to the article node based on a custom field value. So if the custom field value is set to 1 then allow access for all user expected anonymous user. I have a custom field of 'special article' and this has a Boolean values of 1 (true) and 0 (false). I have tried numerous ways of doing this and I can deny access to every article node, but I only want to do it on the articles where the 'special_article' field is set to 1. This is what I have so far and it restricts all articles from displaying to the anonymous user.
<code>    function mymodule_node_access_records($node) {

  $grants = array();
  if ($node->type === 'article' && $node->status) {
    $grants[] = array(
        'realm' => 'mymodule_myrealm',
        'gid' => 1,
        'grant_view' => 1,
        'grant_update' => 0,
        'grant_delete' => 0,
        'priority' => 0,
    );
  }

  return $grants;
}

/**
 * Implements hook_node_grants().
 */
function mymodule_node_grants($account, $op) {
  $grants = array();

  if (user_access('can view member articles', $account)) {
    $grants['mymodule_myrealm'][] = array(1);
  }

  return $grants;
}
</code>
I tried to add the following to the above ccode but that didn't work.
<code>function mymodule_node_access_records($node) {

      $grants = array();
      if ($node->type === 'article' && $node->field_special_article['und'][0]['value'] == 1 && $node->status) {
        $grants[] = array(
            'realm' => 'mymodule_myrealm',
            'gid' => 1,
            'grant_view' => 1,
            'grant_update' => 0,
            'grant_delete' => 0,
            'priority' => 0,
        );
      }

      return $grants;
    }
</code>
If anyone can help me out with this I would be really grateful. Thanks
Edit: Just to clarify, I would like to achieve this using code in a custom module to understand Drupal development better. Thanks
Answer: Have a look at Nodeaccess.

The upshot is, this module allows you to do things like 'node 123 can be viewed by authenticated users and edited by admin users and joeuser'. As an added bonus, update and delete permissions are separated, so you can make sure users with edit permissions cannot accidentally delete pages.
Comment: Thanks for your answer. I'm trying to do this in my own custom module and not use a Drupal contrib module. Basically I want to understand the code behind this for developing Drupal themes. Thanks again though
Answer: Ok, so after changing my code a bit and republishing the content in Drupal (republishing the content was key!) this is what worked. I hope it helps someone at some point.
<code>/**
 * Implements hook_node_access_records().
 */
       function mymodule_node_access_records($node) {
      $grants = array();
      if (array_key_exists('field_special_article', $node)) {
      if (array_key_exists('und', $node->field_special_article)) {
      if ($node->field_special_article['und'][0]['value'] == 1) {

            if ($node->type === 'article' && $node->status) {
              $grants[] = array(
                'realm' => 'mymodule_myrealm',
                'gid' => 1,
                'grant_view' => 1,
                'grant_update' => 0,
                'grant_delete' => 0,
                'priority' => 0,
              );
            }
          }
        }
      }

      return $grants;
    }

    /**
     * Implements hook_node_grants().
     */
    function mymodule_node_grants($account, $op) {
      $grants = array();

      if (user_access('can view special articles', $account)) {
        $grants['mymodule_myrealm'][] = array(1);
      }

      return $grants;
    }
</code>


How do I add path exception in Redirect and Fast 404 modules?

Question: I have a module which has dynamic paths (e.g. /mymodule/one/file1/a.png, /mymodule/one/two/three, /mymodule/one/two/three/four/b.js), where the number of path parameters are resolved by a class implementing the InboundPathprocessor interface. mymodule is present in all the paths.
I want the Redirect and the Fast 404 module to ignore paths with "mymodule" in it.
Answer: Using an OutBoundPathProcessor and reversing the path logic in it worked for me


Is there any way to create one image(Instead of 4 with different resolutions ldpi,mdpi,hdpi and xhdpi) and use for all the android device resolutions?

Question: Is there any way to create one image(Instead of 4 with different resolutions ldpi,mdpi,hdpi and xhdpi) and use it for all the android device resolutions?
Comment: You may also find drawables-nodpi useful.  Often overlooked...
Comment: Sorry, I'm just a bit curious. Why would you want or need that? Are you constricted in any way by app size?
Comment: Not restricted by app size, but wanted to view the image based on device resolution.
Answer: You can use one image for all, the larger one would be better for quality, android will automatically resize them, however the reason you give the different sizes is to save time and memory. You don't want to be doing this every single time the application loads, because it will slow things down, it might not be noticeable to you, but to slower devices it might be.
Since mdpi, or medium density is the basis for all the others I would create one of them and use it for all, but it might not look to good on all devices.
In short your application would be better if you created all the sizes.
You could also look at 9 patches if you want.
Comment: Thank you both for the suggestions. I have tried using mdpi for all the densities but it's disturbing the layout. Anyways, need to try with 9 patch images.
Answer: Just create one (e.g. medium density/mdpi) and ommit the others. Android will use the closest that fits and scale it if required.
If you want a quote from the documentation:

By default, Android scales your bitmap drawables (.png, .jpg, and .gif files) and Nine-Patch drawables (.9.png files) so that they render at the appropriate physical size on each device. For example, if your application provides bitmap drawables only for the baseline, medium screen density (mdpi), then the system scales them up when on a high-density screen, and scales them down when on a low-density screen. This scaling can cause artifacts in the bitmaps. To ensure your bitmaps look their best, you should include alternative versions at different resolutions for different screen densities.
The configuration qualifiers you can use for density-specific resources are ldpi (low), mdpi (medium), hdpi (high), and xhdpi (extra high). For example, bitmaps for high-density screens should go in drawable-hdpi/.
Comment: Thank you both for the suggestions. I have tried using mdpi for all the densities but it's disturbing the layout. Anyways, need to try with 9 patch images.
Comment: Sounds like you might have to define the dimensions of the control a different way. Are you using px or dp for example?
Comment: I'm using dp's. But, not interested to specify 30dp and 40dp for example. Wanted to wrap content an imageview to look good in all the screens.
Comment: Would be helpful for you to provide some image of the actual issue/layout if possible. Even if you replace your images/texts with some dummy stuff to not break any NDA or whatever.


How to prove that Reed Solomon codes are cyclic

Question: Suppose $C$ is the $[n,k]_q$ Reed-Solomon code with $n = q-1$ and evaluation points defined as $\alpha_i = \beta^{i-1}$ (for $ i = 1, \dots, n$) where $\beta$ is a generator of multiplicative group $F^{\star}_{q}$. How to prove that $C$ is a cyclic code?
Answer: Hint: If evaluating the polynomial $f(x)$ at the points $\alpha_i$ gives the codeword $(\gamma_1,\gamma_2,\ldots,\gamma_n)$, what do you get when you evaluate the polynomial $f(\beta x)$? Observe that $f(x)$ and $f(\beta x)$ have the same degree and that $\beta^n=\beta^0$.
Comment: Alternatively you can try evaluating $f(\beta^{-1}x)$. Depends on which direction you are shifting cyclically.


I need a JavaScript array to hold links to an image to work and be used in a image source

Question: I'm trying to make these images change. I need to store their links in an array but when I press the button to change the image, it doesn't recognise that the array variable links to an image. Can someone help please? Here is my current code:
<!DOCTYPE html>

  <button id="red" onclick="setTimeout(changeyellow, 3000),setTimeout(changered, 6000),setTimeout(changegreen, 12000)">automatic</button>
  <button id="red" onclick="changered();">red</button>
  <button id="yellow" onclick="changeyellow();">yellow</button>
  <button id="green" onclick="changegreen();">green</button>

Comment: you're setting the src attribute to a string, you need to use just the array.
Comment: In other words `lights=[red,yellow,green]` and `img.src=lights[0];` etc.
Answer: In this case, you're setting the src attribute to the string "lights[0]" and not the value in the array at position 0.
Instead of this:
var img = document.getElementById("light");
        //vvvvvvvvv
img.src="lights[0]";
return false;

You need to reference the values in your array. So it would become:
img.src = lights[0];

You'll need to do this in each of your function calls. Also you need to do the same thing with your array when you initialize it.
var lights = ["red","yellow","green"]

needs to become:
var lights = [red, yellow, green]

Comment: Thanks you where a massive help
Answer: Your main problem here is that you are using the wrong variables, for example in the array, if you write:
lights = ["red","yellow","green"];

Your array values will be just static strings with the respective values "red", "yellow" and "green".
You need to change it to :
lights = [red,yellow,green];

So your array will hold the urls.
The same thing goes with the src as well, in your actual code:
img.src="lights[0]";

You are just setting a static string to the src. Change it to:
img.src= lights[0];

Answer: Please remove "" from array element and lights[0].
Here is the modified code:
var lights=[red,yellow,green];

function changered()
{
    var img = document.getElementById("light");
    img.src=lights[0];
    return false;
}

function changeyellow()
{
    var img = document.getElementById("light");
    img.src=lights[1];
    return false;
}

function changegreen()
{
    var img = document.getElementById("light");
    img.src=lights[2];
    return false;
}


PL/SQL : Need to compare data for every field in a table in plsql

Question: I need to create a procedure which will take collection as an input and compare the data with staging table data row by row for every field (approx 50 columns).
Business logic :

whenever a staging table column value will mismatch with the corresponding collection variable value then i need to update 'FAIL' into staging table STATUS column and reason into REASON column for that row.
If matched then need to update 'SUCCESS' in STATUS column.

Payload will be approx 500 rows in each call.
I have created below sample script:
PKG Specification :
CREATE OR REPLACE
PACKAGE process_data
IS
TYPE pass_data_rec
IS
  record
  (
    p_eid employee.eid%type,
    p_ename employee.ename%type,
    p_salary employee.salary%type,
    p_dept employee.dept%type
  );

type p_data_tab IS TABLE OF pass_data_rec INDEX BY binary_integer;
PROCEDURE comp_data(inpt_data IN p_data_tab);
END;

PKG Body:
  CREATE OR REPLACE
    PACKAGE body process_data
    IS
    PROCEDURE comp_data (inpt_data IN p_data_tab)
    IS
      status VARCHAR2(10);
      reason VARCHAR2(1000);
      cnt1   NUMBER;
      v_eid employee_copy.eid%type;
      v_ename employee_copy.ename%type;
    BEGIN
      FOR i IN 1..inpt_data.count
      LOOP
        SELECT ec1.eid,ec1.ename,COUNT(*) over () INTO v_eid,v_ename,cnt1
        FROM employee_copy ec1
        WHERE ec1.eid = inpt_data(i).p_eid;
        IF cnt1 > 0 THEN
          IF (v_eid=inpt_data(i).p_eid AND v_ename = inpt_data(i).p_ename) THEN
            UPDATE employee_copy SET status = 'SUCCESS' WHERE eid = inpt_data(i).p_eid;
          ELSE
            UPDATE employee_copy SET status = 'FAIL' WHERE eid = inpt_data(i).p_eid;
          END IF;
        ELSE
          NULL;
        END IF;
      END LOOP;
      COMMIT;
      status :='success';
    EXCEPTION
    WHEN OTHERS THEN
      status:= 'fail';
      --reason:=sqlerrm;
    END;
    END;

But in this approach i have below mentioned issues.

Need to declare all local variables for each column value.
Need to compare all variable data using 'and' operator. Not sure whether it is correct way or not because if there are 50 columns then if condition will become very heavy.
IF (v_eid=inpt_data(i).p_eid AND v_ename = inpt_data(i).p_ename) THEN
Need to update REASON column when any column data mismatched (first mismatched column name) for that row, in this approach i am not able to achieve.

Please suggest any other good way to achieve this requirement.
Edit :
There is only one table at my end i.e target table. Input will come from any other source as collection object.
Comment: How big are the fields?  I would concatenate all the field values along with the column name into one big string per row, then compare that.
Comment: ¿Why input is a collection?¿source table is on the same data base?
Comment: @alvalongo No. there is no source table. Input will come from ICS end. They will call this procedure by passing multiple rows in the form of collection.
Answer: REVISED Answer
You could load the the records into t temp table, but unless you want additional processing it's not necessary. AFAIK there is no way to identify the offending column (first one only) without slugging through column-by-column. However, your other concern having to declare a variable is not necessary. You can declare a single variable defined as %rowtype which gives you access to each column by name.

Looping through an array of data to find the occasional error is just bad (imho) with SQL available to eliminate the good ones in one fell swoop. And it's available here.  Even though your input is a array we can use as a table by using the TABLE operator, which allows an array (collection) as though it were a database table. So the MINUS operator can till be employed. The following routine will set the appropriate status and  identify the first miss matched column for each entry in the input array. It reverts to your original definition in package spec, but replaces the comp_data procedure.
create or replace package body process_data
is
    procedure comp_data (inpt_data in p_data_tab)
    is
      -- define local array to hold status and reason for ecah.
      type status_reason_r is record
           ( eid    employee_copy.eid%type
           , status employee_copy.status%type
           , reason employee_copy.reason%type
           );
      type status_reason_t is
           table of status_reason_r
           index by pls_integer;
      status_reason status_reason_t := status_reason_t();

      -- define error array to contain the eid for each that have a mismatched column
      type error_eids_t is table of employee_copy.eid%type ;
      error_eids error_eids_t;
      current_matched_indx pls_integer;

      /*
        Helper function to identify 1st mismatched column in error row.
        Here is where we slug our way through each column to find the first column
        value mismatch. Note: There is actually validate the column sequence, but
        for purpose here we'll proceed in the input data type definition.
      */
      function identify_mismatch_column(matched_indx_in pls_integer)
        return varchar2
      is
          employee_copy_row employee_copy%rowtype;
          mismatched_column employee_copy.reason%type;
      begin
          select *
            into employee_copy_row
            from employee_copy
           where employee_copy.eid = inpt_data(matched_indx_in).p_eid;

          -- now begins the task of finding the mismatched column.
          if employee_copy_row.ename !=  inpt_data(matched_indx_in).p_ename
          then
             mismatched_column := 'employee_copy.ename';
          elsif employee_copy_row.salary !=  inpt_data(matched_indx_in).p_salary
          then
             mismatched_column := 'employee_copy.salary';
          elsif employee_copy_row.dept !=  inpt_data(matched_indx_in).p_dept
          then
             mismatched_column := 'employee_copy.dept';
         -- elsif continue until ALL columns tested
          end if;

          return  mismatched_column;

      exception
          -- NO_DATA_FOUND is the one error that cannot actually be reported in the customer_copy table.
          -- It occurs when an eid exista in the input data but does not exist in customer_copy.
          when NO_DATA_FOUND
          then
              dbms_output.put_line( 'Employee (eid)='
                                  || inpt_data(matched_indx_in).p_eid
                                  || ' does not exist in employee_copy table.'
                                  );
              return 'employee_copy.eid ID is NOT in table';
      end identify_mismatch_column;

      /*
        Helper function to find specified eid in the initial inpt_data array
        Since the resulting array of mismatching eid derive from a select without sort
        there is no guarantee the index values actually match. Nor can we sort to build
        the error array, as there is no way to know the order of eid in the initial array.
        The following helper identifies the index value in the input array for the specified
        eid in error.
      */
      function match_indx(eid_in employee_copy.eid%type)
        return pls_integer
      is
          l_at        pls_integer := 1;
          l_searching boolean     := true;
      begin
          while l_at <= inpt_data.count
          loop
             exit when eid_in = inpt_data(l_at).p_eid;
             l_at := l_at + 1;
          end loop;
          if l_at > inpt_data.count
          then
             raise_application_error( -20199, 'Internal error: Find index for ' || eid_in ||' not found');
          end if;
          return l_at;
      end match_indx;

    -- Main
    begin
      -- initialize status table for each input enter
      -- additionally this results is a status_reason table in a 1:1 with the input array.
      for i in 1..inpt_data.count
      loop
        status_reason(i).eid    := inpt_data(i).p_eid;
        status_reason(i).status :='SUCCESS';
      end loop;

      /*
         We can assume the majority of data in the input array is valid meaning the columns match.
         We'll eliminate all value rows by selecting each and then MINUSing those that do match on
         each column. To accomplish this cast the input with TABLE function allowing it's use in SQL.
         Following produces an array of eids that have at least 1 column mismatch.
      */
      select p_eid
        bulk collect into error_eids
        from (select p_eid, p_ename, p_salary, p_dept from TABLE(inpt_data)
              minus
              select eid, ename, salary, dept from employee_copy
             )  exs;

      /*
         The error_eids array now contains the eid for each miss matched data item.
         Mark the status as failed, then begin the long hard process of identifying
         the first column causing the mismatch.
         The following loop used the nested functions to slug the way through.
         This keeps the main line logic clear.
      */
      for i in 1 .. error_eids.count  -- if all inpt_data rows match then count is 0, we bypass the enttire loop
      loop
         current_matched_indx                       := match_indx(error_eids(i));
         status_reason(current_matched_indx).status := 'FAIL';
         status_reason(current_matched_indx).reason := identify_mismatch_column(current_matched_indx);
      end loop;

      -- update employee_copy with appropriate status for each row in the input data.
      -- Except for any cid that is in the error eid table but doesn't exist in the customer_copy table.
      forall i in inpt_data.first .. inpt_data.last
          update employee_copy
             set status = status_reason(i).status
               , reason = status_reason(i).reason
           where eid = inpt_data(i).p_eid;

    end comp_data;
end process_data;

There are a couple other techniques used you may want to look into if you are not familiar with them:

Nested Functions. There are 2 functions defined and used in the procedure.
Bulk Processing. That is Bulk Collect and Forall.

Good Luck.

ORIGINAL Answer
It is NOT necessary to compare each column nor build a string by concatenating. As you indicated comparing 50 columns becomes pretty heavy. So let the DBMS do most of the lifting. Using the MINUS operator does exactly what you need.

... the MINUS operator, which returns only unique rows returned by the
  first query but not by the second.

Using that this task needs only 2 Updates: 1 to mark "fail", and 1 to mark "success". So try:
create table e( e_id integer
              , col1 varchar2(20)
              , col2 varchar2(20)
              );
create table stage ( e_id integer
                   , col1 varchar2(20)
                   , col2 varchar2(20)
                   , status varchar2(20)
                   , reason varchar2(20)
                   );

-- create package spec and body
create or replace package process_data
is
    procedure comp_data;
end process_data;

create or replace package body process_data
is
    package body process_data
    procedure comp_data
    is
    begin
        update stage
           set status='failed'
             , reason='No matching e row'
         where e_id in ( select e_id
                          from (select e_id, col1, col2 from stage
                                except
                                select e_id, col1, col2 from e
                               )  exs
                       );
        update stage
           set status='success'
         where status is null;
    end comp_data;
end process_data;

-- test
-- populate tables
insert into e(e_id, col1, col2)
   select (1,'ABC','def')       from dual union all
   select (2,'No','Not any')    from dual union all
   select (3,'ok', 'best ever') from dual union all
   select (4,'xx','zzzzzz')     from dual;

insert into stage(e_id, col1, col2)
   select (1,'ABC','def')         from dual union all
   select (2,'No','Not any more') from dual union all
   select (4,'yy', 'zzzzzz')      from dual union all
   select (5,'no e','nnnnn')      from dual;

-- run procedure

begin
    process_data.comp_date;
end;

-- check results
select * from stage;

Don't ask. Yes, you to must list every column you wish compared in each of the queries involved in the MINUS operation.
I know the documentation link is old (10gR2), but actually finding Oracle documentation is a royal pain. But the MINUS operator still functions the same in 19c;
Comment: Sorry I missed to mention that the input will come from ICS api as collection.So at my end there is only one table i.e. In your example 'STAGE' table. So basically here comparison is needed between input collection records with STAGE table records. And also it should be identified which column value is mismatched. if in case multiple column value are mismatched then need to update first mismatched column name in REASON.
Comment: Will it be good if i store the collection records into a temp table then compare using minus? But still we can't identify which column value is not matched.
Comment: I've revised the answer. It uses your input array but does so as a table with the MINUS statement.


How to use $ http.get () of angularjs 1.6 with url with parameters

Question: I'm using nodejs and angularjs but I do not understand how to get the data from nodejs to angular, I'll leave my code here
App.js angular
Var myApp = angular.module ('angularTodo', ['angularUtils.directives.dirPagination']);

MyApp.controller ('mainController', ['$ scope', '$ http', function ($ scope, $ http) {

   $ Http.get ('/ api / all'). Then (function (res) {
       $ Scope.pacientes = res.data;

       $ Scope.sort = function (keyname) {
               $ Scope.sortKey = keyname; // set the sortKey to the param passed
               $ Scope.reverse =! $ Scope.reverse; // if true make it false and vice versa
           }
   }). Finally (function () {
       $ Scope.example7 + = "(Finally called)";
   });

}]);

MyApp.controller ('patient', ['$ scope', '$ http', function ($ scope, $ http)

   $ Http.get ('/ patient /: id') .then (function (res) {
       $ Scope.new = res.data.pk;
       $ Scope.test = "test11";
   }). Finally (function () {
       $ Scope.example7 + = "(Finally called)";
   });

}]);

Routes.js
App.get ('/ patient /: id', function (req, res) {

Var id = req.params.id;

Connection.query ('SELECT * FROM patient WHERE pat_id =?', [Id], function (err, data)
        {

            If (err)
                Console.log ("Error Selecting:% s", err);

            Res.json (data [0]);
            Console.log (id);
            Console.log (data);

         });

});

App.get ('/ newinf /: id', isLoggedIn, function (req, res) {

     Res.render ('informe.ejs', {user: req.user});

});

The problem is that $ http.get ('/ patient /: id') is not receiving the id? How do I get the id of the url in angularjs?
Comment: Please fix your code, there are a lot of unwanted spaces in variable names, functions...
Answer: In a factory you can define a function that makes an http request .
MyApp.factory('test_factory',function($http,{
    factory = {};
    factory.get_request = function(params){
        return $http({
            method: 'GET',
            url: 'some_url',
            params: params
        })
    };
    return factory
});

In your controller you can make the http request defined in your factory (make sure to DI your factory).  Notice how I'm passing an object to the get_request function within the factory.
MyApp.controller('some_ctrl',function($scope,test_factory){
    test_factory.get_request({id:12345}).then(function(data){
        console.log(data)
    })
});

Of course you can make a http request directly from your controller using basically the same syntax.  But it is usually much better practice to separate the request logic into a factory.
Also, since you are making a GET request, the query params will be added to the url string when the request is made.  You can confirm this by checking the network tab in most browsers developer tools.
Answer: You need to send the id yourself as part of the url in your request. In angular, you are currently sending a request to /patient/:id. Try replacing the :id in your angular code with a valid id of a patient in your database. For example:
$http.get('/patient/12')
    .then(function (res) {...})

12 should then show up as your req.param.id in your server side code.
I'd also recommend that you follow user2263572's advice and encapsulate this logic into a factory as well.


Loading HTML page into container with java from a page within the container

Question: I'm new to coding and this is my first time here so go easy :)
also please feel free to tell me this is a stupid way of achieving the desired effect.
I'm developing the company intranet page and have started loading pages into a container within the index.php page. which works fine!
The problem I have is this same method isn't working for buttons I create within the pages getting loaded into the container.
Example:
index.html

 HR

 FAQ

 Info

 Directory

$( document ).ready(function() {
    $("#load_HR").on("click", function() {
    $("#content").load("HR.html");
});
    $("#load_FAQ").on("click", function() {
    $("#content").load("FAQ.php");
});
    $("#load_Info").on("click", function() {
    $("#content").load("info.html");
});
    $("#load_directory").on("click", function() {
    $("#content").load("directory.php");
});
});

This is how my Navbar buttons load pages into the Container, this works fine.
Now I want to load a page within say the HR.html page into the container that's currently occupied by the HR.html page.
looks easy, sounds complicated and I'm going round in circles.
Please help! :)
Answer: Looks like the JQuery .load() functions tries to do a XMLHttpRequest
which results in the following error
cannot load Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.
Try using plain JS it worked for me.
$( document ).ready(function() {
    $("#load_HR").on("click", function() {
    document.getElementById("content").innerHTML='<object type="text/html" data="HR.html" ></object>';
});
So your code should look something like this

 HR

 FAQ

 Info

 Directory

$( document ).ready(function() {
    $("#load_HR").on("click", function() {
    document.getElementById("content").innerHTML='<object type="text/html" data="HR.html" ></object>';
});
    $("#load_FAQ").on("click", function() {
    document.getElementById("content").innerHTML='<object type="text/html" data="FAQ.php" ></object>';
});
    $("#load_Info").on("click", function() {
    document.getElementById("content").innerHTML='<object type="text/html" data="info.html" ></object>';
});
    $("#load_directory").on("click", function() {
    document.getElementById("content").innerHTML='<object type="text/html" data="directory.php" ></object>';
});
});

Comment: Thanks for your Help DevKimo!

I eventually worked out that I could get around my problem by adding a function to the page that loaded into the container.
Answer: I found my jQuery Answer:
by adding this function to the page that loaded into the content container
for example when I loaded the HR.html page:
function loadbenefits() {
    $('#hrContent').load('CompanyBenefits.html');
}

then make a button that loaded the new page into the container with the onClick(="loadbenefits()" like so:
<button onClick="loadbenefits()" class="btn" type="button" value="Go"> Some Text </button>


Propriedades do css nao fazem efeito bootstrap

Question: galera estou tentando fazer uma coisa simples no css que e mudar a cor da fonte do meu link e as cores estao sendo anuladas por algum motiv que eu nao sei qual e
 .navbar-inverse .navbar-nav>li>a {
    color: #9d9d9d;
}

galera consegi resolver o problema, o erro foi pq carreguei o bootstrap primeiro que a minha folha de estilo
Comment: Poderia também colocar o trecho em HTML?
Comment: Certifica-te que os teus css são importados no html depois dos do bootstrap
Answer: Como mencionado pelo @JoãoLuiz, evite usar !important, porqu no futuro você pode querer sobrescrever seus próprios estilos, e, além disso, os desenvolvedores que tiverem legado o seu código terão dificuldades para mudá-lo. De acordo com Stephanie Sullivan [Rewis], designer, isso é um ato muito egoísta.
Cada seletor no CSS tem um score, pontuação ou peso. Quanto mais específico for o seletor, maior será sua prioridade, porquanto maior será sua pontuação.
O !important só é recomendado quando alguma classe deve ser hard-code, praticamente imutável, só perde para as declarações inline.
Dessa forma, a melhor forma de sobrescrever o CSS do Twitter Boostrap é declarando suas próprias classes e pondo-as depois da inclusão dos estilos do framework em questão.
A melhor forma de fazer isso é do seguinte modo:
Incluir seus estilos

    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/seu_css.css">

Usar os mesmos nomes das classes do Twitter Bootstrap
.container{
    max-width: 50%;
}

Comment: +1 (se interessar, deixei uma referencia aqui no site de como calcular prioridades de seletor http://pt.stackoverflow.com/a/143893/70 - tem a explicação de como funciona, e link para uma ferramenta de cálculo)
Comment: obrigado por responder acho que o problema causado era pq eu carreguei a bootstrap primeiro que a minha folha de estilo css
Comment: @FernandoAlcantara Ms é exatamente isso que você tem que fazer. Primeiro o Bootstrap e depois seus estilos customizados.
Answer: Verifique se no o seu CSS foi inserido depois do bootstrap. As regras são executadas sequencialmente.
Answer: Talvez a forma que você colocou o <link href="css/bootstrap.css" rel="stylesheet">
ou você pode alterá direto da biblioteca do bootstrap mas a forma que o Guilherme Alvez mencionou pondo o !important
Answer: Seu CSS deve ser declarado posterior ao bootstrap.
Tente evitar !importants.
Answer: Tente:
.navbar-inverse .navbar-nav>li>a {
    color: #9d9d9d !important;
}

Tente adicionar !important na propriedade CSS para forçar o CSS a usar a propriedade descrita nessa linha.


Views contextual filters taxonomy name 2 fields using same vocabulary

Question: I have a content where two fields using the same vocabulary.
I want to show nodes related content filtered by the these fields.
I try with relation
Relationships

content:field_1
(term from field_field_1) Taxonomy term: Content using field1 (Relationship term from field_field_1 ;  Require this relationship )

Contextual filters
<code>   (field_field_1) Content: field_2

   Provide default value : Taxonomy term id from url
   Load default filter from node page
   Limit terms by vocabulary ( country)

   Specify validation criteria ( taxonomy term )

    Vocabularies : Country
    Filter value type : Term name converted to Term ID
    Transform dashes in URL to spaces in term name filter values
</code>
This query returns nothing.
I don't want to use Views PHP code fields because of security concerns.
Comment: Using php filter will be the easiest way. Whilst I fully agree that php filter is generally a bad thing, I think using in this specific instance is fine.
Answer: If I understand your question correctly, out of the box the easiest way is to add a Contextual Filter Content: Has Taxonomy Term Id. This one does not care whether you have 1 field or 20 that reference taxonomy terms.  Further details within are whether you want to match from URL on term id or term name, etc.
I came across your question whilst seeking an answer to mine How to filter on taxonomy term but only match one field on the node, where two fields (primary and secondary) both use the same vocabulary which I think is different.


With Windows XP, how would I download and burn a 4Gig file?

Question: I am trying to use my PC to download CentOS 6.4 64bit, for the purpose of burning it to CD, so that I can install that CD on a new Linux server.  I am required to use the 64bit version of CentOS.
Using my Windows XP PC, I browse to a CentOS download mirror site
http://mirrors.usc.edu/pub/linux/distributions/centos/6.4/isos/x86_64/
I think the files I want are
<code>CentOS-6.4-x86_64-bin-DVD1.iso  4.1G
CentOS-6.4-x86_64-bin-DVD2.iso  1.4G
</code>
I downloaded these files successfully, but when I try to burn the first iso file to a CD, my PC crashes with the blue screen of death.  Im guessing the reason it crashes is that my Windows XP, which is 32 bit, cannot handle a 4.1G file.
How do I make this CD?
Comment: CD's only hold ~800MB, so you're going to need a DVD±R(W) if you want to burn that ISO. I'd recommend using [ISO Recorder](http://alexfeinman.com/isorecorder.htm) to burn the DVD. This has nothing to do with 32bit or 64bit.
Answer: no, this is not related to your operating system bit(32 or 64 it doesnt matter), you're on wanting to burn this image to a CD
i think i didnt need to re-instruct the procedure again you can see this link for Burning your centos image to a CD
here: http://www.centos.org/docs/5/html/CD_burning_howto.html


Keep text in div

Question: If I do:

    Hello 1

    Hello 2

    Hello 3

    Hello 4

    Hello 5

    Hello 6

    Hello 7<be>

The text bleeds out of the DIV.  I want it to either cut the display of the text off or put scrollbars.  Anything but have the text just exit the DIV!  I understand that this is basically what the <textarea> does, but I'm trying not to use that tag for other reasons.
Sure appreciate any help!
Thanks!
Answer: You can leverage overflow-y to force a scrollbar on the y-axis.
Which produces:

        Hello 1

        Hello 2

        Hello 3

        Hello 4

        Hello 5

        Hello 6

        Hello 7<be>

If you want to cut out the redundant text, you can use overflow:hidden which hides text that exceeds the width and height.

        Hello 1

        Hello 2

        Hello 3

        Hello 4

        Hello 5

        Hello 6

        Hello 7<be>

Comment: @BlakeMcBride Glad to help :p
Answer: You're looking for the overflow property
overflow: hidden will hide the text that is outside of the container with no scroll bar
overflow: scroll will always show a scrollbar
overflow: auto will automatically show a scrollbar if the text starts to go beyond the edge of the container

div {
  width: 200px;
  height: 200px;
  background-color: yellow;
  font-size: xx-large;
  overflow: auto;
}

  Hello 1

  Hello 2

  Hello 3

  Hello 4

  Hello 5

  Hello 6

  Hello 7

Answer: Remove width: 200px; height: 200px; from style if you want to keep the field as big as the given text

Keep text in div


Erro - Select com SUM

Question: Caros;
Tenho uma tabela com diversas informações, dentre elas um campo com valor_boleto e outro com vencimento.
Precisava que primeiro fosse ordenado o compo vencimento com o mes atual (corrente) e depois que ordenado, somasse os valores de valor_boleto.
Tentei a query abaixo, porem sem sucesso:
SELECT * FROM boleto WHERE extract(year_month from vencimento) = 201805, (SUM(-valor_boleto)+5000) AS valor_boleto FROM boleto";

O erro gerado é de sintaxe a partir do SUM.
Se eu executo apenas a ordenação do mes corrente, funciona corretamente:
SELECT * FROM boleto WHERE extract(year_month from vencimento) = 201805;

Onde estou errando, ou melhor tem uma frma mais simples de efetuar esta consulta?
Comment: Amigo, apesar de alguns erros no seu sql, acho que entendi o que você está querendo. Mas vamos definir algumas coisas antes. Você precisa selecionar todas as colunas de sua tabela ou queres apenas a soma dos valores agrupados pelo período?
Answer: Amigo, se entendi bem o que deseja, creio que agrupando pelo periodo você consiga a somatória dos valores dos boletos como deseja, segue o código:
SELECT (SUM(valor_boleto)+5000) as soma, extract(year_month from vencimento) as periodo FROM boleto
GROUP BY extract(year_month from vencimento);

segue o exemplo: SqlFiddle
Comment: Boa noite @inacio. Quase isso meu amigo, retornou a soma de todos os meses. Como faço para setar o mês atual. Tentei setar na mão   extract(year_month from vencimento) = '201805' e o vencimento veio todo vazio, apenas a soma retornou resultado.
Comment: Amigo, resolvi. Tinha que setar no final do codigo o mes que eu quero. Vou dar como resposta aceita. Abraços.

Erro - Select com SUM


PHP MVC for XML/ XSL

Question: I have to develop a website in which the content is stored on an external database and is distributed via xml
Can anyone recommend a lightweight framework that can be use to consume this xml and display html using xsl transformation?
I want to use xsl because apart from the data being xml i want to be able to template the pages using xml/ xslt markup
Comment: PHP supports XML and XSLT via its extensions, so you don't need a dedicated framework for that if that is what you're asking for. http://php.net/refs.xml
Answer: XSLT is a very powerful tool on itself, so I doubt that adding a framework into the workflow will have an improving effect if you just want to read XML and transform it into HTML. That is just the kind of job XSLT was invented for.
Maybe the not exactly matching Question XML Outputting - PHP vs JS vs Anything Else? gives an idea how XSLT works.
Edit @hakre comment: PHP supports XML/XSLT, no framework needed is what I say. If you follow the link I suggested you'll see that a transformation needs only 3 lines of PHP-code (beside XML data and XSLT script, of course). PHP uses the very fast and stable xmllib2/xsltlib library in the standard installation, no lib adding is necessary.
Edit @Kendall comment: XSLT is a w3c standard templating language. Why use another one which probably will be not as wide used, documented and supported? To hit the nail on your question: For the task you describe I can't recommend any framework over XSLT which is already built in PHP to use XML and display HTML using XSL transformation. Why putting an framework above instead talking directly XSLT? It's a language, not an API. Even versatility will be better.
Comment: @Kendall: Maybe http://stackoverflow.com/questions/4528272/is-mvc-now-the-only-way-to-write-php/4528577#4528577 ist interesting for you. The accepted answer is partly kind of ranting about MVC but goes along with categorizing XSLT as templating library
Comment: Yeah I have been doing it however, I need a bit more versatility with aspects to page templating...and since I would be using XML then it would be easy to build pages as well using XML. A frame work would then make this a bit more streamlined.
Answer: I would recommend CodeIgniter It is lightweight, dynamically loaded, and supports XSL.

PHP MVC for XML/ XSL


SQL 2012 Schema/Data Compare In VS2010

Question: I've been searching everywhere to find out if there is a current way to do a schema and data compare for SQL 2012 database using the existing Schema/Data compares currently included in VS 2010 Ultimate.
The best I have been able to come up with is a silly add-on tool (SSDT Power Tools) that is not nearly on the same level of usability for schema compares and does not do data compares.
Unfortunately we went ahead and setup a new server with SQL 2012 and were prepared to migrate our current production to it when I learned all the good tool we used to use would not work and that there is no backwards compatibility for compares from 2012 to any previous database version with the SSDT.
I'm looking for any help resolving my issue as my alternative is to have to throw away the 2012 server and deploy everything to a 2008 R2 as our work requires us to constantly be able to do data compares.
Comment: Aaron - To answer your question it perhaps may stem from many not having the need for the red-gate tools because what comes out of the box in Ultimate is sufficient.  Companies who have spent the cost of Premier/Ultimate do not want to pay the cost for Red-Gate when they never have had to up until now.
Comment: If this is a serious need, why not buy an established tool that does this better than Microsoft could (even if it satisfied all of your requirements)? e.g. http://www.red-gate.com/products/sql-development/sql-compare/ other tools here http://bertrandaaron.wordpress.com/2012/04/20/re-blog-the-cost-of-reinventing-the-wheel/
Comment: I'll also add that SSDT cannot compare with the standard db project for VS. This means that if you install it, not only you'll have to convert the projects, but also everyone using the code will have to install SSDT. Same observation for VS2012. Also, apparently, there will be updates to VS2012 in order to include schema and data compare in the near future.
Answer: A couple points of clarification.  As mentioned for schema / data compares, best is to use a commercial tool, such as Red-Gate's SQL-Compare.  For completeness though, I'll add a couple of other points:

SSDT does do schema compares across versions and editions of SQL Server.  At this time it does not do data compares.  For more about SSDT, check out my blog posts on that topic.
You may be able to mitigate the version problem by setting the database compatibility level to something less that SQL Server 2012 as shown in the picture below from SSMS.
Comment: Just an FYI. I am having the same problem, and the answer for #2 didn't work for me. My environment is ... Source = SQL2008R2.SQL2008(100) and Target = SQL2012.SQL2008(100). Same error.
Comment: For the record, this option doesn't work in any way. Microsoft's been very clear about this, it doesn't work. http://social.msdn.microsoft.com/Forums/sqlserver/en-US/355d535f-4a09-4a02-84fb-679b053eb829/vs2010-data-compare-sql-2012
Answer: You can also use Master Data visual studio addin to compare sql server databases .. It's lightweight(1mb) and also includes some advance feature over SSDT ..

SQL 2012 Schema/Data Compare In VS2010


How to create connection between AWS VPC and my PC/LAN?

Question: May be it's little bit odd, but yes i want to make connection between AWS VPC and my PC/LAN, so i can ping any EC2 instance using their Private IP.
More Details:
I'm using AWS Directory Service(DS) and trying to add my PC under AWS DS. But AWS DS is VPC specific. We can't access DS DNS address outside the VPC. Hence I think if i able to connect my PC under VPC network then it can be possible to ping AWS DS DNS.
Comment: The only way that I can think of is using AWS Direct Connect (https://aws.amazon.com/directconnect/), which is to connect your on-premises infrastructure and AWS infrastructure.
Comment: just adding fyi: direct connect is a particular solution, and quite expensive
Answer: This is not odd at all and very common. One easy way to do that is to use an vpn solution, e.g by deploying an openvpn VM from an openvpn AMI (almost everything is configured by default), or by installing another vpn solution on one of your instance.
Then, you will only have to log to this vpn and you will be able to resolve your instances with their private IP addresses
However, if you do want your instances to be routed between your LAN/VPC, this is slightly more complicated. you may have to consider using a more complex architecture, still based on VPN but with "Virtual Private Gateway / customer gateway" configuration
Comment: Thanks, @Tom. **OpenVPN** is awesome. It took 10-15 minutes to setup **VPN Tunnel** and some more time for adding my PC under DS.  One suggestion from my side, instead of doing manual setup you can use AWS Marketplace AMI [OpenVPN AMI](https://aws.amazon.com/marketplace/pp/B00MI40CAE?ref=cns_srchrow) It is easy to setup.
Comment: happy to help @Nitin Patil :) I agree with you, that 's what I mean by "from an openvpn AMI", but maybe it is not clear. Thanks for sharing the link!
Answer: Best self-explanatory YouTube Video for installing OpenVPN
for this you need to use AWS Marketplace AMI - OpenVPN
Answer: In addition to running OpenVPN on AWS you could also use a VPC Virtual Private Gateway.
http://docs.aws.amazon.com/AmazonVPC/latest/UserGuide/VPC_VPN.html
You would set up a deice on your side (usually the router or firewall) and connect it to the VPC via a VPN tunnel to an Amazon VPN endpoint. This solution would make it easy to add multiple hosts on your LAN to the DS without having to connect them all via individual VPN connections.
Edit: This popped up again so I thought I'd add I did a writeup on using Pritunl for something like this a couple months after posting this answer. I've been managing Pritunl Enterprise since then and with ~150 users daily or so it's been performing wonderfully even with just t2.medium hosts and another for the Mongo database.
https://www.nathanv.com/2015/11/09/pritunl-for-aws-vpc/
Answer: A pretty standard site to site type VPN should do the trick. IPSEC or OpenVPN from a gateway on your premises to an instance on AWS that is bridged / routed onto your private AWS network.


What inverted chord is this?

Question: What chord is this? I thought maybe E(add2)/B?

The top line is treble and the bottom is bass
Comment: Does this music have a key signature?
Comment: Yes, the music is in D major
Comment: What made you think it's inverted?
Answer: In the key of D, as suggested by comments, this chord is a Bsus4, with B-B-B-E-F♯, where the minor 3rd of the vi chord (D of Bm) has been replaced by the 4th (E).
With so many Bs in the spelling, I would be inclined to call this chord a Bsus4, but it may also be an inversion of an Esus2, where the minor 3rd of the ii chord (G of Em) has been replaced by the 2nd (F♯).
Comment: Did you mean 'the minor 3rd of the vi chord '? And while it probably would be Bm rather than B, but without the 3rd, it's better calling it Bsus4. Bmsus4 can't exist, I'd have thought. +1
Comment: And there's always the possibility of xsus4 being (dom)xsus2, although with all those Bs, it's unlikely here.
Comment: Yes, I did mean vi; corrected. I didn't mean to suggest Bmsus4, just connecting the chord to its likely diatonic counterpart.
Comment: I understand, although Aric has more than hinted at that.
Answer: (I assume there is no key signature.)
First of all, we can safely assume that the root note is B, since it is played in three different octaves. The other notes are E and F.
The dominant note in B is F#, meaning that this must be a diminished chord. The E is the subdominant note in B minor, so this chord would be a suspension of the fourth.
There is, of course, another less likely possibility
It is most likely that this is a diminished chord with a suspension, however it's also possible that this is E with a suspension (Esus2).
In second inversion, this has the correct notes to be a suspended second chord on E (B E G F), however the G is missing.
In resonse to the OP's comment
This is actually in the key of D major / B minor:

The notes of this chord are B, E, and F#. This is a B minor chord with a suspension on the fourth (some might call it Bsus4).
Comment: @NeilMeyer the bold text in the question says what the clefs are.
Comment: Without an indication of clefs, you cannot actually assume those notes are B's
Comment: Oops. Forgot to put that this is in D major.

What inverted chord is this?


Saving Files to MongoDB GridFS with Node.JS

Question: How do you put the close() in the writeBuffer callback?
This question relates to:
Problem with MongoDB GridFS Saving Files with Node.JS
Comment: and then I read the last comment at the bottom of this one [link]http://stackoverflow.com/questions/8135718/how-to-use-gridfs-to-store-images-using-node-js-and-mongoose ... looks like the writeBuffer has since been deprecated. So how now?
Comment: Why don't you rewrite your question with your attempt, and updated question (instead of the comment).
Comment: oh don't just tease with a response like that... if you know the answer then please do share.
ps. the answer I am looking for will come from a respondent recognizing the following: node.js, callback, close, mongodb, gridfs,
Answer: A simple example is
https://github.com/mongodb/node-mongodb-native/blob/master/test/gridstore/grid_store_test.js#L97
Also check the docs for changes in behavior, writeBuffer was removed so just use write.
http://mongodb.github.com/node-mongodb-native/
Comment: Thanks. I guess that's why I still haven't figured out how to put the close() in the writeBuffer callback, however I was able to get the desired result using a "return file.writeFile(path, fn);" as per an example I found here: https://github.com/jamescarr/nodejs-mongodb-streaming


Como inserir dados e uma tabela com Foreign Key no PHP/MYSQL

Question: eu tenho 2 tabelas Cliente e Endereço com relacionamento 1,1
Na tabela endereço tem a FK.
Qual seria o jeito certo de fazer o insert nessas tabelas, relacionando cliente com endereço?
Imagino que LastInsertId não seria viável em um sistema muito grande com vários registros sendo relizados ao mesmo tempo.
Comment: Wellington edite sua pergunta  e coloque junto o seu código
Comment: Não era para ser ao contrário? O Cliente ter a chave estrangeira do endereco?
Comment: O ideal aqui no fórum é que você coloque seu código para que possamos te ajudar melhor. Pergunta respondida com as informações que colocou, se colocar mais informações e ela não for compatível com a situação eu edito/removo.
Answer: O ideal é que o cliente receba a chave estrangeira do endereço e não o contrário.
Você pode usar o mysqli_insert_id() ou PDO::lastInsertId(), pois mesmo que tenham várias pessoas criando cadastro ao mesmo tempo, o SGBD vai cuidar desse problema para você.
Cada cliente cria uma conexão ao banco. Pelo manual do próprio MySQL: O ID que é gerado ao usar esse comando no servidor é gerado com base na conexão. Isso quer dizer que o valor retornado pela função por um cliente específico é o primeiro valor AUTO_INCREMENT gerado  pelo mais recente comando daquele cliente
 que afete uma coluna AUTO_INCREMENT e esse valor não pode ser afetador por outros clientes, mesmo que eles gerem outros valores de AUTO_INCREMENT.
Comment: Coloquei a chave estrangeira do lado errado realmente, mas a questão era realmente saber se o ideal era usar o mysqli_insert_id() ou PDO::lastInsertId(). Será que se um cliente inserir registros ao mesmo tempo de outro isso não pode dar problema? Porque? Gostaria de saber o motivo
Comment: @wellington adicionei essa informação nos comentários. Espero que agora esclareça melhor :D


Alternatives to multinomial logistic regression

Question: I have been using a multinomial logistic regression to examine the correlates of school choice. There are three possibilities for the dependent variable: government school, private school, and NGO (non-government organization, i.e. non-profit) school. However, I'm pretty sure the problem violates the independence of irrelevant alternatives (IIA) assumption - both on intuitive grounds (e.g. removing the NGO option would increase the probability of going to government vis-a-vis private school) and using the suest command in Stata to conduct a Hausman test (not 100% sure I did this correctly, but that's another issue).
Anyway the question is, if multinomial logit isn't the best model to use then what else can I try? Since there are only three options, can I simply use two separate logits (e.g. NGO vs. other and private vs. other) or is that not appropriate? As I understand it, other multinomial methods bring their own problems, such as the Invariant Proportion of Substitution property (as explained here (pdf)). For what it's worth, multinomial probit produces similar results to mlogit.
Is it possible to argue that the mlogit results are reasonably accurate (perhaps, to argue that it is imperfect but the best available model) despite violating IIA, and if so what evidence would support or refute that claim? (These two papers argue that multinomial logit is at least as accurate as multinomial probit, in the field of voter choice).
Comment: do you have many discreet design variables with small #of modality smaller than, say, 6?
Comment: @user603 sorry, I have no idea what you mean by discreet design variables. There are 5-10 explanatory variables (I try a few different models), 1 or 2 are continuous and the others binary.
Comment: ok, that answers my question.
Comment: I've just checked one of the 2 papers you mention. It happens to be a political sciences master thesis, I'll be rather sceptical in regards of their conclusions as numerical issues with MNP model may explain them.
Comment: @JDav Thanks, I was a bit confused about whether those papers had widespread application or depended on particular data sets or types of data. I came across them while trying to figure out whether violating IIA is always a problem. (I think you edited out an earlier comment which seemed to say something useful about how the data sets examined in both those papers probably have particular characteristics explaining why MNP and MNL give similar results?)
Comment: At the beginning I thought It was a particular data set issue but then I noticed that they were using simulated data so It became an akward result ! I guess they are facing numerical problems and are not aware of this. Moreover, these models (qualitative response,Item response ,etc) are main developments in stats and econometrics where top academics were/are involved, actually there are far more complicated issues/extensions than the IIA to discuss. The master thesis author & supervisor did their best but it's just a master thesis in political sciences, not even stats or maths...
Answer: If your IIA test refuses the IIA , then  you should estimate an alternative model like a nested probit or a mixed multinomial logit. As you mention, you may split you problem in two nested dichotomies: private or not, and Ngo or government. The nested approach is already available in stata whereas the mixed multinomial one can be found here:
http://ideas.repec.org/a/tsj/stataj/v6y2006i2p229-245.html
THe mixed mlogit approach introduces a random parameter that is common to your three categories, this way dependence across categories can be accounted for.
Comment: Thanks, this is helpful, I'm looking into using a mixed multinomial model and `gllamm' as mentioned in your link. (Computational time is probably not an issue here.)

(Incidentally, redoing the tests properly suggests that the model _doesn't_ violate IIA. However, I don't find this plausible given my strong priors about school types, so want to try different models anyway.)
Comment: The IIA assumption refers to the correlation between unobservables across categories or conditional correlation. Your priors about school types might be already taken into account within your explanatory variables (observables) i.e. It's possible that IIA holds if your covariates are capturing the correlation between non private schools, this would explain your test result. You can try to estimate the model without covariates and rerun the tests to check for this.


How can I convert auto generated id to uid in Firestore?

Question:   User? user = FirebaseAuth.instance.currentUser;

 onPressed: () {
                final games = Games(
                    id: user!.uid,
                    pc: pcController.text.trim(),
                    board: boardController.text.trim(),
                    real: realController.text.trim());
                createGame(games);

            },

    Future createGame(Games games) async {
    final json = games.toJson();
    await docUser.set(json);
  }

Here are my codes where the user enters the data into several text fields and saves them in a file called 'games' to the Firestore.
 class Games {
  String id;
  final String pc;
  final String board;
  final String real;

  Games(
      {required this.pc,
      required this.board,
      required this.real,
      this.id = ''});

  Map<String, dynamic> toJson() => {
        'pc': pc,
        'id': id,
        'board': board,
        'real': real,
      };

  static Games fromJson(Map<String, dynamic> json) => Games(
        pc: json['pc'],
        board: json['board'],
        real: json['real'],
        id: json['id'],
      );
}

Games class I created
  List<String> docGameIDs = [];
  User? user = FirebaseAuth.instance.currentUser;

     getGamesId() async {
    await FirebaseFirestore.instance
        .collection('games')
        .where('id', isEqualTo: user?.uid)
        .get()
        .then((snapshot) {
      docGameIDs = [];
      for (var element in snapshot.docs) {
        docGameIDs.add(element.reference.id);
      }
    });
  }
 FutureBuilder(
                        future: getGamesId(),
                        builder: (context, snapshot) {
                          return ListView.builder(
                            itemCount: docGameIDs.length,
                            itemBuilder: (context, index) {
                              return Container(
                                child:
                                    GetGames(documentId: docGameIDs[index]),
                              );
                            },
                          );
                        },
                      ),

Finally, the code where I get the data from Firestore.
class GetGames extends StatelessWidget {
  final String documentId;
  const GetGames({super.key, required this.documentId});

  @override
  Widget build(BuildContext context) {
    CollectionReference users = FirebaseFirestore.instance.collection('games');
    return FutureBuilder<DocumentSnapshot>(
      future: users.doc(documentId).get(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.done) {
          Map<String, dynamic> data =
              snapshot.data!.data() as Map<String, dynamic>;
          return Center(
            child: Text(
              '${data['pc']}',
            ),
          );
        }
        return const Text('');
      },
    );
  }
}

GetGames widget

As seen in the image, the id value created in the file that I defined in the Games class is not the same as the id that the file automatically assigns. However, I used the definition of id = user!.uid in the first code so that those ids are the same. In this way, the id created in the file will no longer be the same as the id of the file but will be the UID of the user and it happened.
But for the .where('id', isEqualTo: user?.uid) code in the 3rd code to work, the id and uid must be the same as seen in the image. In short, how can I print that automatically assigned short id as the uid (XyyjAZ7FZ8PtWw0vfL7YWXIJAGg2) defined in the file?
Comment: So what do you exactly need, to have the `XyyjAZ7FZ8PtWw0vfL7YWXIJAGg2` as an ID of the document rather than `t7iq...DNzU` which randomly generated?
Comment: Yes that's right
Answer: If you need to have a document ID of your choice rather than the one that is randomly generated (t7iq...DNzU), then you have to create a reference that contains that ID. So in code, it will be:
CollectionReference gamesRef = FirebaseFirestore.instance.collection('games');
gamesRef.document(user!.uid).set(yourObject);
//

Comment: You have to use this code when you add documents to Firestore. When you're using `FirebaseFirestore.instance.collection('games').doc()` you're always generating a new random ID. You have to pass the UID of the user to the document() function. And `yourObject` represents the object that you want to add to Firestore. Is it clear now?
Comment: Yes thank you. You explained very clearly and I understood. But I think I saw my job in a simpler way. I wrote 'user!.uid' against the 'id' definition under the toJson() method in the Games class. I also defined the user in the Games class as the top one in the first code. In this way, it started to create files with a uid, not a random id.
Comment: I couldn't understand where I should place this code and what should I write instead of 'yourobject'. final docUser = FirebaseFirestore.instance.collection('games').doc(); I tried to write this code instead of the code, but I did not understand how to pull my json file instead of yourobject.


sshd wont start at boot

Question: I just installed Debian 6, after reboot sshd stopped responding.
I put the default config file but it not help.
In the logs (/var/log/auth,syslog) no errors.
I think the problem is that sshd not start. How can I try to run it? maybe do something in the startup scripts?
Unfortunately I do not have physical access to my virtual machine, and can only reload it and view/edit the files in the filesystem.
[ added  ]
Oh, thanks all. I found the problem.
Added /usr/sbin/sshd -e 2>/tmp/sshd_error to crontab
And get: /bin/sh: /usr/sbin/sshd: No such file or directory
Vaguely I could not understand where to lost a binary file on a freshly installed machine and I could work without it.
But now another question: how can I restore it?
Answer: You can run sshd in debug mode using the -d switch. This causes sshd to stay in the foreground and print messages to the console. You can increase the volume of log messages by adding more -d's
/usr/sbin/sshd -d

for normal logging
/usr/sbin/sshd -ddd

for lots of logging.
Comment: Unfortunately I have no shell access to the server. Can only reload server and view/edit the files.
Answer: Set the log level to DEBUG in sshd configuration.
LogLevel DEBUG

Comment: What kinds of debug messages will get printed, and where?
Answer: You can start sshd by hand with exec /usr/sbin/sshd -D to see if sshd works in general. If it does, a update-rc.d ssh defaults should create the init.d symlinks as required.
Comment: I have no shell access to the server. Can only reload server and view/edit the files. Maybe I can write something in the startup scripts?
Comment: no shell access? oh oh... does the `/etc/init.d/ssh` script exist? If it does (and if it contains the `exec /usr/sbin/sshd` call), take a look into the `/etc/rc[0-6].d` directories if there's a symlink. if there's no symlink, you could try to copy the script into /etc/rc3.d/, rename it to `S16ssh` (for example) and see if it's executed after a reboot.
Comment: @vlad: IMHO the best solution would be to **re-install debian from scratch**. If `sshd` is missing completely, most likely its dependencies are missing, too. Maybe other vital components are also missing, so i think it doesn't make much sense trying to repair that system manually.
Comment: Thanks. It turned out that it was a problem hosting company, they use a common packages (like sshd and etc) for all virtual machines and they have something broken.
Answer: Maybe ssh isn't activated at boot? See if there are pointers in /etc/rc.d to /etc/init.d/ssh.
Alternatively, it may not start if the ssh main key is missing. Check if /etc/ssh/ssh_host*key are present.

sshd wont start at boot


BroadCasting

Question: Ok in order to broadcast, I have created a socket:
<code> notifySock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
</code>
And to send the hostname of my computer to all other computers connected to the same lan, I am using the send(Byte[] buffer) method:
<code> notifySock.Send(hostBuffer);
</code>
hostBuffer contains the hostname of my computer.
However because I am using a 'datagram' socket-type do I need to format the data I need to send.
If possible please provide the code that I must put in between the two lines of code I have entered to create a socket and send the data.
Answer: For broadcast from a user application, UDP is typically used. You need to design a suitable protocol, i.e. a way to format the information you want to send into the UDP packet.
Comment: ok I got that. Am using a datagram socketType for which UDP works fine.
I have a small doubt now.
Between creating the socket of type datagram and sending the data, what is the code I need to write to broadcast the message.
Creating an IPEndPoint of type broadcast is fine but how do I use it??
Answer: In your example you haven't specified who you are sending to. You need something like:
<code>UdpClient notifySock = new UdpClient(endPoint);
notifySock.Send(buffer, buffer.Length, new IPEndPoint(IPAddress.Broadcast, 1234));
</code>
For the other hosts on your LAN to receive that they have to be listening on UDP port 1234.
Comment: Got that.. The new problem here is that there is a receive method within the UDPClient class.. However one of its parameters is a reference variable of type IPEndPoint..But if I need to hear a broadcast message, I do not need that..What is the method I must call to receive a broadcasted message.

BroadCasting


How can I output this JSON file as a HTML table?

Question: I have a JSON file which I would like to output as a HTML table using pure Javascript. What should the JS code look like? The JSON file looks like this:
<code>[
  {
"FIELD1":"A ",
"FIELD2":" B ",
"FIELD3":" C ",
"FIELD4":" D"
},
{
"FIELD1":"E ",
"FIELD2":" F ",
"FIELD3":" G ",
"FIELD4":" H"
},
{
"FIELD1":"I ",
"FIELD2":" J ",
"FIELD3":" K ",
"FIELD4":" L"
  }
]
</code>
Here is a jsbin for your convenience:
http://jsbin.com/nulol/1/edit
Comment: so, what have you tried?
Comment: Ok, a for loop, wait I think I have one here somewhere
Comment: First you start out with a for loop..
Comment: no, that's a hoola hoop. that's for going in horizontal circles. you need a for loop, which goes in vertical circles
Comment: Sure, I am a beginner : D Anyways, I found a loop and put it in the JS file (http://jsbin.com/nulol/1/edit) and I also put a window.addEventListener in that file to start it off.
Comment: Here's a nice example of using the Handlebars templating libary: http://jsfiddle.net/gazraa/xfWKF/ It might be overkill for smaller projects, but it's a nice way to render HTML tables from json.
Answer: Try using JSON.stringify for that:
<code>    var data = [
  {
    "FIELD1":"A ",
    "FIELD2":" B ",
    "FIELD3":" C ",
    "FIELD4":" D"
  },
  {
    "FIELD1":"E ",
    "FIELD2":" F ",
    "FIELD3":" G ",
    "FIELD4":" H"
  },
  {
    "FIELD1":"I ",
    "FIELD2":" J ",
    "FIELD3":" K ",
    "FIELD4":" L"
  }
]

document.getElementById('codeTarget').innerHTML = JSON.stringify(data, undefined, 2);
</code>
or you could use jQuery to target the element and then use its .html() method:
<code>var JSONoutput = JSON.stringify(data, undefined, 2);
$('pre#codeTarget').html(JSONoutput);
</code>
Just be sure to put it in a pre tag so it will format nicely.
Here's a JSFiddle.
Comment: The JSON.stringify() method converts a value to JSON. In your example, the output is not a HTML table. Could you please exemplify so that the result actually is a HTML table? It would make it easier to understand and reverse engineer your code.
Comment: Ah, you want the data to be tabular when output. In that case, you should use a templating system like [Handlebars]http://handlebarsjs.com/). It's pretty straightforward. Here's an article to get you started, and it even puts data into a table: [dhtmlexamples.com/2011/04/15/getting-started-with-handlebars-js-templating-language-in-javascript/](http://dhtmlexamples.com/2011/04/15/getting-started-with-handlebars-js-templating-language-in-javascript/)


Joi require at least one of a group of keys when a specific key exists

Question: Given the example:
Joi.object({
  a: Joi.string(),
  b: Joi.string(),
  c: Joi.string(),
})

I want that when key A is filled, keys B and C are required at least one of them:
{ a: 'foo', b: 'bar' } //success

{ a: 'foo', c: 'bar' } //success

{ a: 'foo' } #error

Comment: And if key A is not filled? Which keys are then required?
Answer: You can require a minimum count of keys on the object.
Joi.object({
  a: Joi.string(),
  b: Joi.string(),
  c: Joi.string(),
}).min(1)


Reconstructing face from randomised embedding

Question: It is fairly agreed in literature that from a given face-embedding (that is a vector of features values) it is possible, with a good amount of effort, to reconstruct the original face, (See here for instance) assuming to have access to the embedding extractor.
Now, for concreteness, let's say that I've a 2000 long embedding of floats. I randomly rearrange the 2000 entries of the vector in one the $2000!$ permutations. The random rearrangement is specific to the owner of the face.
Is it still possible to recover the original face?
(A brute force attack is clearly excluded, as $2000!  \approx 10^{5735}$)
Answer: if you will permute input you would have to also permute coeficients in first layer of network and if these permutations "will agree" then yes, otherwise you will just generate face on random input vector
Comment: I would first generate the embeddings and then randomise them. Knowing the randomisation pattern, it's always possible to recover the original embedding.


What context Should be Use in setUserVisibleHint Method

Question: Because All fragment loaded with together In Pager Sliding tab , I need to use setUserVisibleHint() for laoding that fragment selected .
I have Problem with Context in the setUserVisibleHint() method :
It raised NPE Exception when I use getActivity for my Context. Thanks
Answer: Because getActivity will return null before fragment attached to Activity you need check this value will null or check fragment attached to activity or after onActivityActtached function.
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (getActivity() != null) {
       //do something
    }
}

//or
 boolean isAttached = false;
 @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        isAttached = true;
    }

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isAttached) {
       //do something
    }
}

Comment: and if getActivity returned null what should i work for preventing that ?
Comment: you should waiting or anything that not use actvity because fragment don't have a activity
Answer: Its better to use newInstance Method and put your String over there. And then in fragment use
getArguments().getString("KEY")


Express.js App no Response on localhost:3000

Question: I created an express.js app by typing the following the commands in (OSX):
$ express mytestapp

$ cd mytestapp

$ npm install

Then when I type code below
$ node app.js

and I navigate to http://localhost:3000  I get this webpage is not available.
Answer: An express4 app that's generated using the generator is no longer started using node app.js but instead using;
npm start

The relevant section of the docs.