Opengl lighting not working

Question: So far a sky box and cube and ability to move the camera left right forward and back is working. However the cube is not being shaded by the lighting and isn't even appearing as the correct color. From my perspective I've enabled everything I was told to enable and created a light source etc etc so I'm pretty lost.
//  ========================================================================
//
//  ========================================================================

#include <iostream>
#include <GL/freeglut.h>
#include <cmath>
#include "loadTGA.h"
using namespace std;

#define GL_CLAMP_TO_EDGE 0x812F   //To get rid of seams between textures
float theta = 0.0;      //Camera rotation
float cdr=3.14159265/180.0; //Conversion from degrees to radians
float eye_x=0.0, eye_z=0.0;
float look_x=eye_x + 100*sin(cdr*theta);
float look_z=eye_z - 100*cos(cdr*theta);

GLuint texId[6];

void loadGLTextures()               // Load bitmaps And Convert To Textures
{
    glGenTextures(6, texId);        // Create texture ids
    // *** left ***
    glBindTexture(GL_TEXTURE_2D, texId[0]);
    loadTGA("alps_rt.tga");
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    // *** front ***
    glBindTexture(GL_TEXTURE_2D, texId[1]);
    loadTGA("alps_ft.tga");
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    // *** right ***
    glBindTexture(GL_TEXTURE_2D, texId[2]);
    loadTGA("alps_lf.tga");
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    // *** back***
    glBindTexture(GL_TEXTURE_2D, texId[3]);
    loadTGA("alps_bk.tga");
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    // *** top ***
    glBindTexture(GL_TEXTURE_2D, texId[4]);
    loadTGA("alps_up.tga");
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    // *** down ***
    glBindTexture(GL_TEXTURE_2D, texId[5]);
    loadTGA("grass.tga");
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

    glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_REPLACE);
}

//========================================================================================

void temple(){

    glColor3f(0, 0, 0);
    glPushMatrix();
      glTranslatef(20, 10, 0);
      glutSolidCube(1);
    glPopMatrix();

}

void skybox(){
    glEnable(GL_TEXTURE_2D);

    ////////////////////// LEFT WALL ///////////////////////
    glBindTexture(GL_TEXTURE_2D, texId[0]);
    glBegin(GL_QUADS);
    glTexCoord2f(0., 0.);
    glVertex3f(-10000,  0, 10000);
    glTexCoord2f(1., 0.);
    glVertex3f(-10000, 0., -10000);
    glTexCoord2f(1., 1.);
    glVertex3f(-10000, 10000., -10000);
    glTexCoord2f(0., 1.);
    glVertex3f(-10000, 10000, 10000);
    glEnd();

    ////////////////////// FRONT WALL ///////////////////////
    glBindTexture(GL_TEXTURE_2D, texId[1]);
    glBegin(GL_QUADS);
    glTexCoord2f(0., 0.);
    glVertex3f(-10000,  0, -10000);
    glTexCoord2f(1., 0.);
    glVertex3f(10000, 0., -10000);
    glTexCoord2f(1., 1.);
    glVertex3f(10000, 10000, -10000);
    glTexCoord2f(0., 1.);
    glVertex3f(-10000,  10000, -10000);
    glEnd();

    ////////////////////// RIGHT WALL ///////////////////////
    glBindTexture(GL_TEXTURE_2D, texId[2]);
    glBegin(GL_QUADS);
    glTexCoord2f(0., 0.);
    glVertex3f(10000,  0, -10000);
    glTexCoord2f(1., 0.);
    glVertex3f(10000, 0, 10000);
    glTexCoord2f(1., 1.);
    glVertex3f(10000, 10000,  10000);
    glTexCoord2f(0., 1.);
    glVertex3f(10000,  10000,  -10000);
    glEnd();

    ////////////////////// REAR WALL ////////////////////////
    glBindTexture(GL_TEXTURE_2D, texId[3]);
    glBegin(GL_QUADS);
    glTexCoord2f(0., 0.);
    glVertex3f( 10000, 0, 10000);
    glTexCoord2f(1., 0.);
    glVertex3f(-10000, 0,  10000);
    glTexCoord2f(1., 1.);
    glVertex3f(-10000, 10000,  10000);
    glTexCoord2f(0., 1.);
    glVertex3f( 10000, 10000, 10000);
    glEnd();

    /////////////////////// TOP //////////////////////////
    glBindTexture(GL_TEXTURE_2D, texId[4]);
    glBegin(GL_QUADS);
    glTexCoord2f(0., 0.);
    glVertex3f(-10000, 10000, -10000);
    glTexCoord2f(1., 0.);
    glVertex3f(10000, 10000,  -10000);
    glTexCoord2f(1., 1.);
    glVertex3f(10000, 10000,  10000);
    glTexCoord2f(0., 1.);
    glVertex3f(-10000, 10000, 10000);
    glEnd();

    /////////////////////// FLOOR //////////////////////////
    glBindTexture(GL_TEXTURE_2D, texId[5]);
    glBegin(GL_QUADS);
    glTexCoord2f(0., 0.);
    glVertex3f(-10000, 0., 10000);
    glTexCoord2f(100., 0.);
    glVertex3f(10000, 0.,  10000);
    glTexCoord2f(100., 100.);
    glVertex3f(10000, 0., -10000);
    glTexCoord2f(0., 100.);
    glVertex3f(-10000, 0., -10000);
    glEnd();

}

//---------------------------------------------------------------------
void initialise(void)
{
    float grey[4] = {0.2, 0.2, 0.2, 1.0};
    float white[4]  = {1.0, 1.0, 1.0, 1.0};

    loadGLTextures();

    glEnable(GL_LIGHTING);
    glEnable(GL_LIGHT0);

    glLightfv(GL_LIGHT0, GL_AMBIENT, grey);
    glLightfv(GL_LIGHT0, GL_DIFFUSE, white);
    glLightfv(GL_LIGHT0, GL_SPECULAR, white);

    glEnable(GL_COLOR_MATERIAL);
    glColorMaterial(GL_FRONT, GL_AMBIENT_AND_DIFFUSE);

    glEnable(GL_DEPTH_TEST);
    glEnable(GL_TEXTURE_2D);
    glEnable(GL_NORMALIZE);
    glClearColor (0.0, 0.0, 0.0, 0.0);

    glMatrixMode (GL_PROJECTION);
    glLoadIdentity ();
    gluPerspective(90.0, 1.0, 1.0, 20000.0);   //Perspective projection

}

//---------------------------------------------------------------------
void display(void)
{
    float outsidelightpos[4] = {1.0f, 1.0f, 1.0f, 1.0f};

    glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    gluLookAt (eye_x, 10, eye_z, look_x, 10, look_z, 0, 1, 0);  //camera rotation

    glLightfv(GL_LIGHT0, GL_POSITION, outsidelightpos);

    skybox();

    temple();

    glFlush();
}

//--------------------------------------------------------------
 void special(int key, int x, int y)
 {

    if(key==GLUT_KEY_LEFT) theta-=5;         //Turn left
    else if(key==GLUT_KEY_RIGHT) theta+=5;   //Turn right
    else if(key == GLUT_KEY_DOWN)
    {  //Move backward
        eye_x -= 5*sin(cdr*theta);
        eye_z += 5*cos(cdr*theta);
    }
    else if(key == GLUT_KEY_UP)
    { //Move forward
        eye_x += 5*sin(cdr*theta);
        eye_z -= 5*cos(cdr*theta);
    }

    look_x = eye_x + 100*sin(cdr*theta);
    look_z = eye_z - 100*cos(cdr*theta);

    glutPostRedisplay();
    glutSwapBuffers();
}
//-------------------------------------------------------------------

int main(int argc, char** argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode (GLUT_SINGLE | GLUT_DEPTH);
    glutInitWindowSize (1024, 800);
    glutInitWindowPosition (50, 50);

    glutCreateWindow ("Alex Bull's Assignment");
    initialise();
    glutDisplayFunc(display);
    glutSpecialFunc(special);

    glutMainLoop();
    return 0;
}

Answer: So, you draw this "temple" cube

while texturing is still on, with the last texture of your skybox which is still bound. Since glutSloidCube does not provide any texcoords, the same texcoords will be used all over the place. You can use glDisable(GL_TEXTURE_2D) to disable it.
with a color of (0,0,0) while glColorMaterial is set to GL_AMBIENT_AND_DIFFUSE, so you basically will get only specular lighting
with the GL's fixed function, so you only get gouraud shading, and will not get any useful specular highlight because the lighting is just calculated at each corner vertex of your cube

So, in the end, you'll get a crappy specular highlight, modulated by some corner texel color of some of on of your skybox textures, interpolated across your cube faces.
You should note that almost every single GL function you are using is deprecated since a decade now. Your code is totally outdated, the fixed function is long gone from GPUs. If you really want to learn OpenGL nowadays, you shouldn't do it in ways which are 20 years old.
Comment: How does one turn texturing off? And take it up with the university I have to do this stuff for lmao.
Comment: glDisable(GL_TEXTURE_2D); nvm got it already... everything working as expected

Opengl lighting not working


Tension/gauge less prone to buzzing

Question: Is there a type of string (high tension or low tension) that is less prone to generate buzzing on the acoustic guitar ?
I've mainly heard these few arguments so far :

high tension strings are larger, making them more subjected to buzzing
high tension strings have a lower amplitude of vibration when played, making them less subjected to buzzing
the two effects above counterbalance each other making no real difference

Is one actually better than the other when specifically trying to avoid buzzing ?
Comment: Whatever tension or gauge strings are on at the time will have their propensity to buzz affected by the action and the string height - and to a degree the way the player presses them onto the fingerboard. So, for a given set of circumstances, there are still too many variables, I think, if that makes sense.
Comment: @Tim Of course, there are better ways of fixing buzzing than changing strings, but let's put that aside and focus only on this point : High or low tension and its interaction with buzzing. Or are you saying that this interaction behaves differently depending on other parameters, and it's not easily predictable ?
Answer: Let's knock the concepts into shape a bit…

high tension strings are larger, making them more subjected to buzzing

This makes no logical sense whatsoever. Sure, they're thicker, but the thickness still rests on the same fixed points, where the string passes over the nut, bridge & fretted position, meaning the bulk of the string is further from the fretboard not nearer.

high tension strings have a lower amplitude of vibration when played, making them less subjected to buzzing

Yes, to an extent. They won't vibrate quite so much for a given strike velocity.
However, assuming no other adjustment is made to the guitar, there is another reason they will not buzz…

They will pull the neck forward very slightly - giving better clearance to the next un-fretted fret, meaning less buzz.

This, combined with reason 2, would be the simplest explanation.
This assumes you can still correctly hold the string to the fret with the added tension & greater distance to the fretboard.
Comment: Nice, I totally didn't think of 1. when hearing the original arguments in my question. It makes sense though. Thanks :)

Tension/gauge less prone to buzzing


VBScript copy a file from a Network Server to another Network Server

Question: I want to copy a file from
\\Server\SharedFolder\NameOfFile.txt

to
\\Server2\SecondSharedFolder\NameOfFile - 1-10-2012.txt

I can copy and rename the file on the local drive. I am having trouble access the file called NameOfFile.txt
I get the following error
Microsoft VBScript runtime error (50, 9) : File not found

Here is the offending code
fso.CopyFile SourcePath, DestinationPath, True

Comment: I was just going to ask you, what are the values of `SourcePath` and `DestinationPath` when you get the error.
Answer: The SourcePath had a missing "\"


swift create jsonArray from NSMutableArray

Question: i tried like that. but i did not get jsonArray and i do not know how can i do. I want to jsonArray as String. Can you help me?
public static func createInkitchenJson(additionId : Int64, orderId : Int64)
{
    let dicArray : NSMutableDictionary = NSMutableDictionary();
    let nsArray : NSMutableArray = NSMutableArray();

    for basket in BasketStatic.baskets
    {
        let dicObject : NSMutableDictionary = NSMutableDictionary();
        let model = basket.Product;
        dicObject.setValue(String(additionId), forKey: JsonHeader.ADDITION_ID);
        dicObject.setValue(String(orderId), forKey: JsonHeader.ORDER_ID);
        dicObject.setValue(BasketStatic.table?.getTableName(), forKey: JsonHeader.TABLE_NAME);
        dicObject.setValue(model.Id, forKey: JsonHeader.REQUEST_ID);
        dicObject.setValue(String(basket.RowCount), forKey: JsonHeader.ITEM_COUNT);
        dicObject.setValue(model.Name, forKey: JsonHeader.REQUEST_NAME);
        dicObject.setValue(model.getExtraToString(), forKey: JsonHeader.EXTRAS);
        dicObject.setValue(basket.getType(), forKey: JsonHeader.REQUEST_TYPE);
        dicObject.setValue(EMPTY_FIELD, forKey: JsonHeader.MENU_UNIQUE);
        dicObject.setValue(EMPTY_FIELD, forKey: JsonHeader.MENU_NAME);
        dicObject.setValue(EMPTY_FIELD, forKey: JsonHeader.MENU_ID);
        dicObject.setValue(String(basket.RowPrice), forKey: JsonHeader.PRICE);
        dicObject.setValue(WaiterModel.WAITER_ID, forKey: JsonHeader.CREATED_BY);
        nsArray.add(dicObject);
    }

    // here i want to convert NsMutableArray to jsonArray
    // jsonArray convert to string

}

Comment: refer https://stackoverflow.com/questions/6368867/generate-json-string-from-nsdictionary-in-ios
Answer: It's better to
let arr = [Item(/////),,,,,]
let data  = try? JSONEncoder().encode(arr)
let str = String(data: data, encoding: .utf8)

struct Item:Decodable {

 // add properties

}

OR
let data = try? JSONSerialization.data(withJSONObject: dic, options: [])

let str = String(data: data, encoding: .utf8)


how to get a list of all nodes that haven been created and are not in use on the system

Question: as the title says..
i need to get a all published nodes of type A that have been created and not used (at the moment) by other nodes.
in other words a list of all node of type A that are on the Database except for those that are NOT been referenced in an entity reference field.
the easy approach will be to load all nodes that uses node of type A, and that load all type A nodes and check for each if it's has a reference for it.
but then if i add another node that will use node of type A as an entity reference i'll have to go back check it as well.
is there an easy way to do it ?
Comment: What does _in use on other nodes_ mean?
Comment: Don't explain in comments, edit your question to clarify :)
Comment: How do I in your case define that a node has been used by another? Is it that they are referenced in a entity reference field? That they are linked to from the text in the body field? Etc.
Comment: sorry, i meant referenced in a entity reference field.
Comment: When you say "Never been used", does that mean if a reference has existed, and then been removed, should that count as "Have been before and thus should not show up in the list"?
Does it have to be dynamic enough to search through _all_ possible entity references, or would one specific field suffice?
Comment: @Letharion i edited the question, i'm looking at the present state of the entity reference, but yes i do need it to be dynamic, because i can always add a new content type that will have an entity reference to this "type A" content type.
Comment: FWIW, dynamically finding fields of a certain type across all entities (or one particular entity type) is not trivial. Hopefully someone will know, but I wouldn't count on getting an answer to that question.
Answer: You could set up a view showing title of content type A,  title of content type B (using relations), hide both and create a custom PHP field that just returns title of ct A if ct A does not have ct B referencing to it. Maybe


PHP preg_replace: to save all the transformed parts into an array

Question: I have a large text containing many dates formatted like this:
 10 april 2012, monday

I need to transform all of them into this format:
 \r\nmonday, 10 april 2012

So, I wrote a regex and it works perfectly OK.
 $matches1= preg_replace(
 '#(\d{,2} [a-z]+) \d{4}, (sunday|monday|tuesday|wednesday|thursday|friday|saturday)#u',
 "\r\n$2$3$4$5$6$7$8, $1",
 $txt);

The problem is that I also need to save all the transformed parts of the text matching the replacement pattern - "\r\n$2$3$4$5$6$7$8, $1" (like \r\nmonday, 10 april 2012) - into an array. So that I have something like this:
 Array('\r\nmonday, 10 april 2012', '\r\ntuesday, 11 april 2012', '\r\nfriday, 14 april 2012' etc.)

Is that possible?
Replacement pattern ("\r\n$2$3$4$5$6$7$8, $1") comes from a html form and may vary.
Update
I've tried to write a callback function but I couldn't get the result I needed.
So I've come up with the following:
 $text = ...;//some text
 $search = ...;//search pattern
 $replacement = ...;//replacement pattern

 preg_match_all('#' . $search. '#u', $text, $matches, PREG_SET_ORDER);

 foreach ($matches as $match)
 {
     $replacements[] = preg_replace('#' . $search. '#u', $replacement, $match[0]);
 }

 $newtext = preg_replace('#' . $search. '#u', $replacement, $text);

So $newtext contains the transformed text and $replacenemts contains all the replacements.
Comment: Do you have to use regex? It can be done using string functions which is easier.
Comment: Yes, I have to use regex. That's just an example, the real regexes may be much more complex.
Answer: Use preg_replace_callback instead (or exemplary in the following code-example additionally) and keep track of all replacements:
$search =  '#(\d{,2} [a-z]+) \d{4}, (sunday|monday|tuesday|wednesday|thursday|friday|saturday)#u';
$replace = "\r\n$2$3$4$5$6$7$8, $1";
$captured = array();

preg_replace_callback($search, function($matches) use (&$captured)  {
    $captured[] = $matches;
}, $txt);

$matches1= preg_replace($search, $replace, $txt);

Answer: Use preg_replace_callback and a custom function which stores the matches into an array and returns the replacement string.
Answer: You could have also split the string at the comma and space in the middle using $txtArr = explode(', ', $txt, 1); and then concatenated them back together at the same time as pushing them into an array using array_push($matches, $txtArr[1].', '.$txtArr[0]);1. Don't forget define your array you will be adding the dates to (e.g. $matches = array();).
If they are in a large string of text, you could locate them using a RegEx function and make use of this to put the "cleaned up" matches into an array.


Help me about continuity of graph

Question:
For the function:
  $$f(x) =
\begin{cases}0 & ~~\text {if}~~ x=-1;\\ -x & ~~\text{if}~~ -1 \lt x \lt 0;\\ x & ~~\text{if } 0 \le x\le 1 \end{cases}$$
  $$f(x+2) = f(x) + 1$$
  make this graph, and watch the graph.

I'm sure that $y=f(x)$ is discontinuous at $x=1$, but about $x \in [0,1]$, $x$ is continuous at $x=1$ ?
Comment: Do you mean that $f(x)$ is discontinuous at $x=-1$. So, what's the question.
Comment: I tend to believe this kind of questions are spam.
Comment: @Kannappan, I'd guess the question is, "Is $f(x)$ continuous at $x=1$?"
Comment: @RahulNarain Isn't that a kind of obvious, if you know that continuity at end points is determined by one sided limits?
Comment: Have you drawn the graph? It is a rising sequence of disconnected V shapes.
Answer: Let's sketch the graph of this function first over $[-1,1]$.
It looks messy:
$f(x)= \cases{\color{darkgreen}{0}, & $\color{darkgreen}{x=-1}$ \cr\color{maroon}{ -x }& $\color{maroon}{-1\lt x\lt 0} $\cr  \color{darkblue}{x}, & $\color{darkblue}{ {0\le x\lt 1} }$ \cr}$
$f$ s a piecewise defined function. To sketch the graph of $f$, look at each "piece" separately:
When $\color{darkgreen}{x=-1}$, the function has the value $0$; so the point $(-1,0)$ is on the graph. We plot this point in the graph below.
For the range of $x$-values in $\color{maroon}{-1<x<0}$, the rule for $f$ is $\color{maroon}{f(x)=-x}$.  Over the interval $(-1,0)$ sketch the graph of $\color{maroon}{y=-x}$.  Note that the value of $f$ at $-1$ is 0 and is not given by the rule $f(x)=-x$.
The "closed" and "open" dots on the graph below indicate what value $f$ takes at the point $x=0$.
For the range of $x$-values in $\color{darkblue}{0\le x\le1}$, the rule for $f$ is
$\color{darkblue}{f(x)= x}$.  Over the interval $(0,1)$ sketch the graph of $\color{darkblue}{y=-x}$.  Note that the value of $f$ at $ 1$ is 1.

So, that's the graph of $f$ over $[-1,1]$.
What about the rest of the graph? Well, that's obtained from the rule
$$
f(x+2)=f(x)+1.
$$
So, for example: $f(3)=f(1+2)=f(2)+1$ and $f(3.5)=f(1.5+2)=f(1.5)+1$.
To evaluate $f$ at $f(x+2)$, you just take the value of $f$ at $x$, and add 1.
So, to obtain the graph of $f$ over $[1,3]$, you just draw the same shape as the graph over $[1-2, 3-2]=[-1,1]$ but raise it vertically by 1 unit.
To obtain the graph of $f$ over $[3,5]$, you just draw the same shape as the graph over $[3-2, 5-2]=[1,3]$ but raise it by 1 unit. etc...
Below, is the graph of $f$ over three of its "periods":

Now, looking at the graph, you can see that $f$  discontinuous at every odd integer $x\ge -1$ and that $f$ is continuous for any $x>-1$ that is not an odd integer.
Answer: By the definition , the formula for the function in a right neighborhood of X=1
is : y= -X+3. The  lateral limits at X=1 are not equal . Then the function is not continuous at X=1.(is left continuous).

Help me about continuity of graph


Inserting multiple records with unique key per insert

Question: I have a table offices. On the insert page of the app, I have two textboxes for the office name and the type of office, and a button that says Add Office. I use jQuery to duplicate the two textboxes, so the user can insert more than one office at a time. A user may put in an office name and a type, hit Add Office, insert a couple of more offices on the same page, and hit Submit.
I'd like to use a group_by query to group together offices that were created at the same time. I found a way for each insert row to have a unique key. I want the rows for a group of offices to share the same unique key. Is this possible?
Comment: I really don't understand who's going about downrating questions all the time! There is nothing wrong with this question! I'm going to uprate it.
Answer: In the controller under the action, you can create a random number and have a third field on your table that accepts the unique key. This unique key value would be the random number.
@unique_key = rand[99999999999]
However, this approach does allow a small 1/99999999999 chance that you would create the same unique_key value as another office. Instead, you may want to create a random hash instead to reduce the possibility of creating the duplicate.
@unique_key = SecureRandom.hex
To make this even less likely, you could do
@unique_key = "#{SecureRandom.hex}#{SecureRandom.hex}"
which would still technically be possible, but extremely unlikely.
This example is if you're using simple_form. You would want to modify to your own specifics
<%= f.input :unique_key, :as => :hidden, :input_html => {:value => @unique_key} %>
Comment: Oh, don't forget to `add_index` in your migration to ensure that the `unique_key` is index which will better optimized on your database.
Answer: You don't really have group_by in ActiveRecord queries. You do have group, but that's if you want to make sums and counts on groups of rows, which I don't think is the case here.
Instead you can use group_by on the returned results. To clarify, it won't be part of the query generated, but it will "group" your results "by" certain criteria, like a unique key, resulting in a Hash, where each entry in the Hash will have an array of offices with the same unique key:
Office.where(...some condition...).group_by(&:my_unique_key_field_name)
Or just:
Office.all.group_by(&:my_unique_key_field_name)
Please take note of kobaltz answer for generating the unique key and consider uprating it if you found it useful.
Blessings.


What kind of regular polygons should placed in this area?

Question: A regular polygon has to be filled in at the vertex with angle marked $ (z \, 150^{\circ}) $ to form a 3D tessellation.
What kind of regular polygon should be placed in this area to complete the tesselation?
Comment: Which "area" are you referring to?  Are there any limitations on size of the polygons in relation to the picture?  Unless if you clarify the question it would appear as though the obvious answer is *every* kind of regular polygon provided it is made with small enough sides.
Comment: Do you maybe want to ask for which $n$ it is possible to place a regular $n$-gon in the plane such that $X$ is one of its vertices and it does not overlap the blue square or the green hexagon? Or maybe even, for which $n$ is there a perfect fit?
Answer: A regular $n$-gon has interior angle $\pi-2\pi/n$.
Here, to fit exactly, you want to get an angle of 150°, or $5\pi/6$.
Solve $\dfrac{n-2}{n}\pi=\dfrac56\pi$, and you get $n=12$.
Comment: does it have another way to find that?
Answer: An interior angle of $150°$ implies an exterior angle of $180-150 = 30°$, so the regular polygon that would fill the $z$ angle on its own would have $360 / 30 = 12$ sides, since the exterior angles of every convex polygon sum to $360°$.
(If you are allowed two regular polygons to fill that angle, they would be a square and an equilateral triangle.)

Diagram for clarity - the exterior angle measures the change in direction at a corner for something traversing the perimeter of the polygon


overloading << in class template with ifsteam

Question: For some reason I can't find the right template function sign to overload my class template Arr with ifstream...(ofstream worked)
I'm having a really hard time figuring this out...
Here is my code:
#include <iostream>
using namespace std;
#include <fstream>

template<typename T, int N = 1>
class Arr {
    T m_data[N];
public:
    Arr(const T& initializer = 0) {   //only for context
        for (int i = 0; i < N; i++)
            m_data[i] = initializer;
    };
    Arr(initializer_list<T> values) {   //only for context
        copy(values.begin(), values.end(), m_data);
    };
    ~Arr() {};                        //only for context

    T operator[](unsigned index) const {   //only for context
        return m_data[index];
    }
    T& operator[](int index) {   //only for context
        return m_data[index];
    };
};

template <typename T, int N>        //OK
ostream& operator<<(ostream &os, const Arr<T, N>& v)
{
    for (int i = 0; i < N; i++)
        os << v[i] << ' ';
    return os;
}

template<typename T, int N>       //OK
ofstream& operator<<(ofstream &os, const Arr<T, N>& v)
{
    int i;
    for (i = 0; i < N - 1; i++)
        os << v[i] << ',';
    os << v[i];
    return os;
}

template<typename T, int N>     // NEVER REACHING HERE
T operator>>(ifstream &os, T v)
{
     //not reading
}

template<typename T, int N>     //OK
ifstream& operator>>(ifstream &os, const Arr<T, N>& v)
{
    for (int i = 0; i < N; i++)
        os >> v[i];     //C2679 binary '>>': no operator found which takes a right-hand operand of type 'T' (or there is no acceptable conversion)
    return os;
}

int main()
{
    Arr<float, 9> numbers({ 1,2,3,4,5,6,7,8,9 });
    cout << numbers;             // ok
    ofstream outf;
    outf.open("myStat.csv");
    outf << numbers;             // OK(save numbers to file)
    outf.close();
    Arr<float, 9> numbers_load;
    ifstream inf;
    inf.open("myStat.csv");

    inf >> numbers_load;      // the problem here(explanation below)

}

Note: numbers_load is  Arr<T, N>  so  inf >> loaded_players  will call to
ifstream& operator>>ifstream &os, const Arr<T, N>& v)  but then a error will occur because the compiler can't find  T operator>>(ifstream &os, T v)  . Why?
Any help will be very appreciated.
Comment: You know, you don't need to write separate functions for `std::ostream` and `std::ofstream`. The latter inherits from the former, so you can use polymorphism.
Comment: good to know, but why does it matters for the overloading purposes? what is the right sign to overload this operator?
Answer: In your function
template<typename T, int N>
T operator>>(ifstream &os, T v);

there's no way to deduce a value for template parameter N.  (It works for the other functions taking a const Arr<T,N>& parameter, because the compiler can compare that parameter type to an argument type like Arr<float, 9> and deduce that T is float and N is 9.)
So you could maybe remove the int N template parameter ... but it's a Really Bad idea to define a template function that says how to get any object type at all from an ifstream.  Many built-in types, Standard library types, and user-defined types define their own versions of operator>> saying how to get them from either a std::istream or more generally from a std::basic_istream<CharT, CharTraits>.  And adding in that overload, there would be some non-obvious results about whether any particular >> token uses the existing definitions or your new one.  And existing code which assumes it's using the ordinary operator>> might suddenly switch to using yours instead.
If you just want a place to define what to do with each element while inputting to an Arr<T,N>, define a function with an ordinary name for that, not an operator>>.
(Less broken, but still a shaky design decision, is the part where os << some_arr; does different things depending on whether the static type of os is a std::ifstream or not.  This is at least unusual.  And note that it might lead to situations where someone passes a std::ofstream to a function taking std::ostream&, so that inside that function, << means the non-file version, even though the stream object actually is an ifstream.)


How do I setup a Python script to run multiple hours each day using Google Cloud job cloud scheduler / cron jobs using AppEngine?

Question: I am trying to have a Python script run each day, triggered in the morning at 9am and killed around 5pm (i.e. during trading hours). I have seen multiple posts about using Google Cron jobs but have not found a clear explanation on how to set this up. I uploaded my script into a Google Bucket in and ran using a Google VM successfully, so it's just a matter of automating.
I thought of potentially creating a function and running that but Google cloud functions timeout after 9 minutes apparently. I believe what I need to do is setup the script in an AppEngine but I have not found great resources on how to do this for a simple setup. Can someone point me in the right direction?
Comment: You want it to run continuously for 8 hours? What is it doing? If you can give us some more details we can help point you in the right direction.
Comment: Thanks Dustin, it's a day trading algorithm that uses an async handler to track several stock indices, with realtime trading data via the Polygon API. Here's the base code I used: https://github.com/alpacahq/Momentum-Trading-Example.git
Answer: If you run it with a Google VM, you could use the VM cron to activate the job.
Adding something like this with crontab -e
09 00 * * 1-5 /usr/bin/python script.py
And you could schedule the instance to start a few minutes before 9 using and shutdown at 5. See here.
If you want to go full serverless, you could put the algorithm in a container and use Cloud Run, triggering with Pub/Sub.


Convert $\frac1b\sum_{n=1}^\infty\frac{(b e^a)^n}{n!}B_{n-1}(an)$ to integral using $B_n(x)=\frac{n!}{2\pi i}\oint\frac{e^{x(e^t-1)}}{t^{n+1}}dt$

Question: $\def\B{\operatorname B}$
In

How to solve $x^{y^z}=z$

A solution uses Bell polynomials $\B_n(x)$
$$e^{ae^{bz}}=z=1+\frac1b\sum_{n=1}^\infty \frac{(ae^b)^n}{nn!}\B_n(b n)=\frac1b\sum_{n=1}^\infty\frac{(b e^a)^n}{n!}\B_{n-1}(an)\tag1$$
A contour integral representation is:

$$\B_n(x)=\frac{n!}{2\pi i}\oint\frac{e^{x(e^t-1)}}{t^{n+1}}dt\tag2$$

interchanging sum and integral gives:
$$e^{ae^{bz}}=z\mathop=^?1+\frac i{2\pi b}\oint\ln\left(1-\frac{ae^{be^t}}t\right)dt\mathop=^?\frac i{2\pi b}\oint\ln\left(1-\frac{be^{ae^t}}t\right)dt$$
I have little experience with contour integration, but trying $a=b=-\frac12$ and $\oint\leftrightarrow\int_{\frac12-i\infty}^{\frac12+i\infty}$ gives a different result than the sum. Likely, the contour used is wrong or one cannot switch the sum and integral without converting to an ordinary integral.
How can $(2)$ be used in $(1)$ to find a similar contour integral solution to $e^{ae^{bz}}=z$?
Comment: The contour is indeed wrong: $\oint$ implies a closed path. This typically means integrating from $\tau=0\to1$ and that $C:z=w_0+Re^{2\pi i \tau}.$
Answer: (WIP) Interchange the sum and the integral, and integrate on the path $z=r_0e^{2\pi i \tau}$ from $0$ to $1$. Take the limit as $r_0\to 0$ like so
$$b^{-1}\sum \frac{b^ne^{an}}{2\pi in}\oint \frac{e^{an(e^{t}-1)}}{t^n}dt\\=b^{-1}\oint \sum \frac{b^ne^{an}}{2\pi in} \frac{e^{an(e^{t}-1)}}{t^n}dt\\=\frac{b^{-1}}{2\pi i}\oint \sum \frac{1}{n}\left(\frac{be^{ae^t}}{t}\right)^ndt\\ =-\frac{b^{-1}}{2\pi i}\oint \ln\left(1-\frac{be^{ae^t}}{t}\right)dt\\ = -b^{-1}\lim_{r_0\to0}\int_0^1r_0e^{2\pi i\tau}\ln\left(1-\frac{be^{ae^{r_0e^{2\pi i\tau}}}}{r_0e^{2\pi i\tau}}\right)d\tau$$ Now, I know what you're thinking, and I'm also very overwhelmed... however with a bit of faith, I think we can proceed with the limit using asymptotics and L'Hopital's rule.

However, if you want an inverse function for $e^{ae^{bz}}-z,$ you can use the Cauchy Integral Theorem to get
$$f^{-1}(w)=\frac{1}{2\pi i}\oint_{f^{-1}\gamma} \frac{zf'(z)}{f(z)-w}dz$$
Comment: [Trying](https://www.wolframalpha.com/input?i=lim%5Bh+e%5E%282+pi+i+catalan%29+ln%281-+baxter+e%5E%28glaisher+e%5E%28h+e%5E%282+pi+i+catalan%29%29%29%2F%28h+e%5E%282+pi+i+catalan%29%29%29%2Ch-%3E0%5D) various positive, negative, and complex $a,b$ makes the limit $0$, unless the limit and integral cannot be switched.
Comment: Maybe you can try another contour?
Comment: @TymaGaidash Normally I would want to be right about my choice of contour, but since the integral looks worse I'll say "*hopefully* I got the contour wrong".
Comment: @TymaGaidash I'll attempt. I don't think I deserve the 50+ you gave, (at least not yet), but I'll get back to you with something. Can you reference where you found the contour definition of the Bell functions?
Comment: It is in the [Bell polynomial representation](https://en.m.wikipedia.org/wiki/Touchard_polynomials#Properties) link of the question. It is under "basic properties" in the source
Answer: Using @Gary's Bell polynomial integral representation, we get:
$$\frac1b\sum_{n=1}^\infty\frac{(b e^a)^n}{n!}\text B_{n-1}(an)=\int_{-\pi}^\pi \sum_{n=1}^\infty\frac{e^{\left(ae^{e^{it}}-a-i t\right)n+it}(b e^a)^n}{2\pi b n}dt$$
with something similar for the second sum in the question. Now apply the series expansion of $\ln(x)$:
$$\bbox[2px,border: 2.5px ridge green]{e^{ae^{bx}}=x=-\frac1{2\pi b}\int_{-\pi}^\pi e^{it}\ln\left(1-be^{ae^{e^{it}}-it}\right)dt,1-\frac1{2\pi b}\int_{-\pi}^\pi\ln\left(1-ae^{be^{e^{it}}-it}\right)dt}$$
shown here. Software gives a restriction when summing over $n$, but it is not clear how to apply it to the integral representation. Taking $a=b$ gives another integral representation of the Lambert W function solving $e^{ax}=x$. Additionally, one can remove the logarithm with integration by parts to get a slightly longer integral expression. It also may be interesting to take the real part of the integrand.


Nulo no corpo da requisição

Question: Utilizo em um projeto DTOs para entrada e saídas de dados.
Na requisição estou enviando um objeto do tipo ProductModel com todas as propriedades, mas o objeto retornado do controlador contém todas as propriedades nulas.
A assinatura do método está correta:
<code>@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public ProductModel adicionarPorSku(@RequestBody ProductModel productModel)
</code>
O corpo que estou enviando:
<code>{
"sku": 43264,
"name": "L'Oréal Professionnel Expert Absolut Repair Cortex Lipidium - Máscara de Reconstrução 500g",
"inventory": {
    "quantity": 15,
    "warehouses": [
        {
            "locality": "SP",
            "quantity": 12,
            "type": "ECOMMERCE"
        },
        {
            "locality": "MOEMA",
            "quantity": 3,
            "type": "PHYSICAL_STORE"
        }
    ]}}
</code>
E assim estão as classes do meu Representation Model:
<code>
    public class ProductModel {

    @NotNull
    private Long sku;

    @NotBlank
    private String name;

    @Valid
    @NotNull
    private InventoryModel inventory;

    @JsonProperty(access = Access.READ_ONLY)
    private Boolean isMarkeatable;
}

@Getter
@Setter
public class InventoryModel {

    @PositiveOrZero
    private Long quantity;

    @Valid
    @NotNull
    private List<WarehouseModel> warehouses;

}

@Getter
@Setter
public class WarehouseModel {

    @NotBlank
    private String locality;

    @NotNull
    private Long quantity;

    @NotBlank
    private String type;

}

Já tentei enviar objetos de outros tipos, e tudo funcionou normalmente, mas como esse tipo (ProductModel) foi instanciado tudo com valor null.
</code>
Answer: A sua classe ProductModel está sem os Getters e Setter, assim o objeto não consegue criar os campos do objeto. Tente colocar um @Data em cima da classe.

Nulo no corpo da requisição


Vanishing Printer Ports

Question: I have a Microsoft Windows Server 2003 SP2 print server. This is serving about 15 print queues the problem is just one of these queues is randomly losing its printer ports.
What do i mean by losing the ports?
A printer is setup with custom ports, printing works perfect until randomly printing stops and errors. Then under the printer properties on the ports tab, the custom created ports are no longer showing. If i jump into the registry and look under the key:
<code>HKLM\SYSTEM\CurrentControlSet\Control\Print\Monitors\SafeCom Pull Port\Ports
</code>
all of the ports are visible even the ones which no longer show! - a little more information would be all other queues are setup with HP Drivers, but this one is a Xerox 7755 using the correct driver. If I create new ports printing resumes as normal.
Has anyone else come across behaviour like this?
Why are you using custom ports?
This is because printing is being monitored by a print auditing software package which has its own ports.
Only this one print queue has this issue, all others work as they should do.
Many thanks for looking at this question.
Cheers
Update
Event logs show nothing related or worth while mentioning. The server has been powered off and then backup. The time between the last occurance of the ports disapearing has been about 2 months.
All ideas are welcomed!
Comment: Anything in the Event logs, do the ports come back if the print spooler service is restarted?
Comment: @Ed - Nothing visable in the logs, the spooler service has been stopped and started whilst doing my intial troubleshooting. The server has also been restarted. - Not that it makes any difference but I will throw it out there! - the server is virtual running under vSphere.
Comment: Going to be hard to t-shoot, since the occurrence is very sporadic we really won't know if a change has any effect for possibly months.  If restarting the spooler service restores the ports then scheduling a nightly service restart may eliminate the symptom although w/out finding the root cause.  Beyond that I would look for updates from Xerox, the print audit app and get in touch w/ both org's tech support for further ideas.
Comment: I had similar issue. I removed all printers and ports. Run windows update...added the printers and all is well...wierd.
Comment: Thanks for your feedback. The restart of the spooler really didnt help, only method to get the device working is to create some new ports. I was thinking about going to Xerox but I cant see how the driver would cause ports to be hidden/vanish. I will indeed speak with the print audit application developers to see if they have any ideas.
Comment: @Saif - Ideally I would do the same, my problem is this is a production print server, serving about 1000users. To distrupt all of the users is not really an option. Thanks for your experience of the issue though.
Answer: This might not help, but I wanted to add it in case it does. We ran into this same issue on Server 2008 after using Windows Printer Migrator from a Server 2003 box. All printers on custom ports would disappear after the server or print spooler service restarted.
We opened a support ticket with Microsoft, with it being closed months later saying they were working on a bug fix for it.
With some additional testing, we found after repairing/reinstalling the OS over top of itself and manually installing the printers (not using any migration tools), the issue was fixed.
Comment: Hi Thanks for your answer. I dont think the issue is quite the same but it's something to keep in mind.
Answer: Specially if you don't see any meaningful OS logs, you might be looking at a particular issue with your print auditing software (version) and the xerox print driver (since others aren't showing this behavior).   See if there is a way to get application-specific logs for this software, instead of looking at windows logs for anomalies.  If all fails, check the support website for the vendor, or call for support... this could be a known bug where they can provide a quick hot-fix/update (I did a quick check for this type of issue on a print auditing software we used to use [PCounter], and found this being a bug in one of their versions--maybe not what you're using, but it might support the claim of it being a software bug).
...at least it's only affecting one printer and not all :)
Comment: Hi first off thanks for replying. - PCounter is one of the many solutions which I support, the strange issue is that of the setups I look after I havent seen any issues like this before. (This setup is using Safecom) I'm leaning now more towards either the port driver version (Pull Printing) or the Driver assigned to this printer queue. I've gone through all the verbose logging which the solution can output but nothing obvious shows up. - I think your answer has the best response and will give you the bounty. Thank You.

Vanishing Printer Ports


Idea behind derivation in logic

Question: Lets say you have the following premises.
$$\{ (C \lor E) \rightarrow \neg M, R \rightarrow M, C \}$$
which is equivalent to
$$\{ ((C \lor E) \rightarrow \neg M) \land (R \rightarrow M) \land C \}$$
Addition means that $\{P\} \vdash P \lor Q$.
Why does $$\{ ((C \lor E) \rightarrow \neg M) \land (R \rightarrow M) \land C \} \vdash C \lor E$$
without truth tables with using addition?
I could see how you form the following implication
$$\{ (C \lor E) \rightarrow \neg M, R \rightarrow M, \mathbf{ C \vdash C \lor E} \}$$
I do not get the idea behind the derivation. I know the question is broad but I feel like I have always been missing something.
I am relatively new to logic.
Comment: $\models$ and $\vdash$ are not the same symbol. I think you have them confused. The first means "models" and the second means "proves"
Comment: I don't know what you mean by addition. Addition means that the statement $A \lor B$ is true if and only if either $A$ or $B$ is true or both.
Comment: Addition here I am referring to P->PVQ is a tautology for the if then operator.
Comment: Why did you write $P \models P \lor Q$?
Comment: Let P=1, 1, 0, 0 and Q=1, 0, 1, 0. Then PVQ= 1, 1, 1, 0. Thus, P->Q= 1, 1, 1, 1 which is a tautology. Then, P⊨(PVQ).
Comment: Okay. I will switch all of the symbols to ⊢.
Answer: EDIT  (Before the OP changed the $\vDash$ into $\vdash$ the comments directly below were aplicable. But now, scroll down to Answer below)
As several commentators already pointed out: you seem to be confusing $\vDash$ and $\vdash$
It is certainly true that $P$ logically implies $P \lor Q$ (you can verify this with a truth-table). We write this fact as $P \vDash P \lor Q$.  That is: $\vDash$ stands for 'logically implies'.
Derivations are something different though. In a derivation we have specified certain rules that tell us what kind of statements can be written down during a derivation on the basis of other statements. And the key to these rules is that they are syntactic or formal. They say "If you have something that looks like bla-bla, then you can write down that looks like such-and-such".
So, to give a crazy example, I could define an inference rule that says: "whenever you have a statement of the form $\phi \lor \psi$. then you can write down ('infer') $\phi$ by itself. And suppose I call this rule Modus Bogus. Then Modus Bogus can be specified as (or: the fact that I have Modus Bogus available to me for a derivation means that) $\phi \lor \psi \vdash \phi$. That is, the $\vdash$ stands for 'allows me to derive'
Now, of course this Modus Bogus inference rule is of course bogus, because it allows me to derive $P$ from $P \lor Q$, which does not at all follow. That is: $P \lor Q \not \vDash P$ ... even though with Modus Bogus I have $P \lor Q \vdash P$!  Do you see the difference?
Now, when you are talking about Addition, it is most likely an inference rule (because many proof systems have Addition as an inference rule and call it as such).  So what you have to work with for a derivation is $P \vdash P \lor Q$. And yes, it is also true that $P \vDash P \lor Q$, but by 'Addition' we typically mean $P \vdash P \lor Q$.
Likewise, when you ask

Why does $$\{ ((C \lor E) \rightarrow \neg M) \land (R \rightarrow M) \land C \} \models C \lor E$$

you probably should have asked:

Why does $$\{ ((C \lor E) \rightarrow \neg M) , (R \rightarrow M) , C \} \vdash C \lor E$$

because you are asking for a derivation, rather than a truth-table demonstration of logical consequence.
Answer
If you start a derivation with
$$((C \lor E) \rightarrow \neg M) , (R \rightarrow M) , C $$
as your 3 premises, then you can immediately apply the Addition inference rule on $C$ to derive
$$C \lor E$$
and that will complete your derivation. And therefore:
$$\{ ((C \lor E) \rightarrow \neg M) , (R \rightarrow M) , C \} \vdash C \lor E$$
Comment: I hate not being able to give the answer to you too. It is so irritating that I can not, because I was misinterpreting the use of those symbols which you figured out. I know I would not have been able to figure it out with both of these answers. I truly appreciate your help.
Comment: @W.G. No problem, and I'm glad I could help!! :)
Answer: Perhaps, this will help you understand the problem more clearly. If you are given the following premises,
$$(C \lor E) \rightarrow \neg M\\ R \rightarrow M\\ C$$
You can instantly verify that $C \lor E$ is true because we are given $C$ is true as our third premises. Therefore, since $C$ is true, $C \lor E$ is also true.
Perhaps, you are wondering what we can deduce from the remaining premises.
Well, since we know $C$ is true because it is the third premises, we know $C \lor E$ is also true, so $\neg M$ must be true because of the first premises.
Since $\neg M$ is true, then $M$ is false, so $R$ must also be false for the second premises to be true.
We cannot determine anything useful about $E$. The premises holds if either $E$ is true or false since $C$ is true.
Edit: The statements above can be easily written out as expressions, but I feel that it is easier to understand in words rather than symbols.
Comment: I have looked for this answer for so long, and I finally get it. I had no idea that premises were assumed true. I thought the letters would be all the combinations of true and false. I finally get it.
Comment: Great! I am glad you are able to understand. Yes. The premises are always assumed to be true.

Idea behind derivation in logic


Probability of Difference of Two independent normal random variables

Question: Can $P(Z_{1}>0,Z_{2}>0)$ be written as $P(X_{1}>0,X_{2}>0)$, if $Z_{1}=X_{1}-Y_{1}$, where $X_{1} \sim N(0,1)$ & is independent of $Y_{1}\sim N(0,1)$, $Z_{2}$ is defined in same way as $Z_{1}$ i.e. $Z_{2}=X_{2}-Y_{2}$?
Answer: Let $\rho:=\operatorname{Cov}(X_1,X_2)$. If $\operatorname{Cov}(Y_1,Y_2)=\rho$ as well, that is, $(Y_1,Y_2)$ is an independent copy of $(X_1,X_2)$, then
$$
\frac{1}{\sqrt 2}\begin{bmatrix}
X_1-Y_1 \\
X_2-Y_2
\end{bmatrix}\sim N\!\left(0, \begin{bmatrix}
1 & \rho \\
\rho & 1
\end{bmatrix}\right),
$$
and the probabilities are equal.


How to explain model?

Question: I am building model in R. Can you help me how to interpret this results. For example what is Pr(>|t|) and others...Thanks!
<code> Call:
lm(formula = Cn ~ B10_75mean + b5_75mean + ui75mean + tvi75mean)

**Residuals:**
    Min      1Q  Median      3Q     Max
-6.3655 -3.7021 -0.3621  2.9530 12.5155
**Coefficients:**
             Estimate Std. Error t value Pr(>|t|)
(Intercept)  24.08902  228.38548   0.105    0.917
B10_75mean   -0.04073    0.75413  -0.054    0.957
b5_75mean   -39.98091   42.28717  -0.945    0.355
ui75mean     20.71277   20.59630   1.006    0.326
tvi75mean    32.69517   42.33715   0.772    0.448
Residual standard error: 4.826 on 22 degrees of freedom
Multiple R-squared:  0.2408,    Adjusted R-squared:  0.1027
F-statistic: 1.744 on 4 and 22 DF,  p-value: 0.1763
</code>
Answer: Pr (>|t|) is the p value. It's actually a better representation than "p-value" because it tries to make you a little more aware of what the p value is (that is, the probability of getting a t that is farther from 0 than the one you got, given a sample the size of the one you have, if the null hypothesis is true).
The rest is really standard output from any regression. Explaining all of the output is too broad a question for this forum and would really require a course in regression.  But if you have other specific questions about the output, feel free to ask them.
Comment: Thanks, and is this result saying something bout how close will the predicted and measured values be.
Comment: R^2 says something about that, but if that is what you want to find out, you could make a scatterplot of the predicted vs. actual values.

How to explain model?


OOP inheritance and objects instaces

Question: I working out the inheritance and OOPS in JavaScript. I created 'A' object and 'B' object and inherited all the properties of 'B' to 'A'.
While I check the newly created object instance by using 'instanceof', I am getting both objects are true.
But I have created the object using 'B' constructor only.
function A(){
    this.a = "test1",
    this.b = "test2"
}

function B(){
    this.c = "test3",
    this.d = "test4"
}

B.prototype = new A();

var userObj = new B();

console.log(userObj instanceof B); // true
console.log(userObj instanceof A); // true, How this can be true?

Answer: In JavaScript, the inheritance is prototype-based. That means that there are no classes. Instead, an object inherits from another object.
What you have done here is, object B inherits from object A because of this:
B.prototype = new A();

So ,now,  userObj (instance of object B) of-course becomes instance of object A, (thats what inheritance is all about, right?)
So thats the reason
console.log(userObj instanceof B); // true
console.log(userObj instanceof A); //  Also true?

Answer: Prototype object has a built in property called constructor.First see this image from chorme console than i will discuss

In your code B.prototype = new A(); =>this statement sets B's prototype to a instance of A.So B's prototype object has it's constructor property assigned to A();
console.log(userObj.constructor // it will show A.But it is not true

Remember it is not userObj's constructor.The constructor you get is from prototype obj.

console.log(userObj instanceof A); // true, How this can be true?

As userObj is a instance of B.And B inherits from A.So userObj is also a instance of A.But you can manipulate the constructor property set to B using
B.prototype.constructor=B;

Answer: console.log(userObj instanceof A); you will surely get true. This is as per the JavaScript standard.
When you are creating a object of B which inherits all the properties of A , the object contains a link __proto__ which points to A's Prototype.
So instanceof will find the A's constructor in the prototypical chaining of the Object B.
That's why it returns true.

OOP inheritance and objects instaces


Bulk Update in Oracle PL/SQL

Question: I have a table like this:
table_name     SQL_statement               id_value      result

employee       select ... where ..= :1    101
customer       select ....where ..= :1    903

there will be about 6-8 different tables
the ID_VALUE is supplied as parameter to SQL_Statement
the SQL statement will always return a single row.
the result of "c" above should be stored in result column

I know I can use EXECUTE IMMEDIATE, but that will create hard parsing in SGA.
What kind of BULK technique can be used here ?
Comment: `execute immediate` does not necessarily cause a hard parse if used with parameters
Comment: a straightforward update statement for each table being updated would do the trick. How are the ids passed in? 1 at a time, or as the result of a select statement?
Comment: The objective is to pass ID_VALUE to SQL_STATEMENT using some kind of BULK operation.
Comment: Right, but how are you getting the id_values in the first place? Are they generated from within the database (eg. `select id_value from table_with_id_values where `), or passed in an id at a time via a front end program, or something else?
Comment: Agree with a_horse_with_no_name on hard parsing. It should be avoided to prevent SQL engine to pl-sql engine swap multiple times though.
Comment: Is `sql_statement` always the same for all rows where `table_name = 'employee'` ? If yes then one of the columns is redundant.
Answer: If you can assume that the statement always extracts a single value with a fixed alias, you can try the following.
setup:
create table yourTable(table_name varchar2(30), SQL_statement varchar2(100), id_value number, result number);
insert into yourTable
(
select 'employee', 'select :1 *2 as result from dual', 1,  null from dual union all
select 'customer', 'select :1    as result from dual', 10, null from dual
);

Given the alias result, you can use a single update statement.
update:
update yourTable
set result = extractvalue(xmltype(dbms_xmlgen.getxml(replace (SQL_statement, ':1', id_value))),'/ROWSET/ROW/RESULT')

result:
SQL> select *
2  from yourTable;

TABLE_NAME SQL_STATEMENT                              ID_VALUE     RESULT
---------- ---------------------------------------- ---------- ----------
employee   select :1 *2 as result from dual                  1          2
customer   select :1    as result from dual                 10         10

Comment: @Boneist - the table is populated by another backend procedure. When a record in customer,employee etc is updated, a trigger populates this table with ID_VALUE which is the PK of the record being updated. So in above - 101 is PK of employee table and 903 is PK of customer table. Imagine this table having few million records.

Bulk Update in Oracle PL/SQL


Como fazer Parse de uma response XML de Web Service

Question: Olá, gostaria de saber como eu faço parse de uma resposta em xml que eu recebo do meu web service..
No caso, estou fazendo em Android, e queria transformar os valores e os nomes que exibem no xml, em variáveis para ser aplicado um gráfico com os mesmos..
A resposta do WS seria esta:
<NewDataSet>
<xs:schema id="NewDataSet" xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="GWDataTable" msdata:UseCurrentLocale="true">
<xs:complexType>
<xs:choice minOccurs="0" maxOccurs="unbounded">
<xs:element name="GWDataTable">
<xs:complexType>
<xs:sequence>
<xs:element name="CODFORMAPG" type="xs:string" minOccurs="0" />
<xs:element name="DESCRICAO" type="xs:string" minOccurs="0" />
<xs:element name="VALOR" type="xs:decimal" minOccurs="0" />
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:choice>
</xs:complexType>
</xs:element>
</xs:schema>
<GWDataTable>
<VALOR>462.73</VALOR>
</GWDataTable> <GWDataTable>
<CODFORMAPG>1 </CODFORMAPG>
<DESCRICAO>DINHEIRO</DESCRICAO>
<VALOR>38502.39</VALOR>
</GWDataTable> <GWDataTable>
<CODFORMAPG>2 </CODFORMAPG>
<DESCRICAO>CHEQUE</DESCRICAO>
<VALOR>3765.63</VALOR>
</GWDataTable> <GWDataTable>
<CODFORMAPG>3 </CODFORMAPG>
<DESCRICAO>CARTOES</DESCRICAO>
<VALOR>13043.70</VALOR>
</GWDataTable> <GWDataTable>
<CODFORMAPG>5 </CODFORMAPG>
<DESCRICAO>TICKETS</DESCRICAO>
<VALOR>6.50</VALOR>
</GWDataTable> <GWDataTable>
<CODFORMAPG>6 </CODFORMAPG>
<DESCRICAO>NOTA PROMISSORIA</DESCRICAO>
<VALOR>56.24</VALOR>
</GWDataTable> <GWDataTable>
<CODFORMAPG>9 </CODFORMAPG>
<DESCRICAO>TEF</DESCRICAO>
<VALOR>27.47</VALOR>
</GWDataTable>
</NewDataSet>

Gostaria de Filtrar todas as descrições e seus respectivos valores e armazena-los em variáveis para serem reusadas..
Comment: tenta isso aqui https://github.com/stanfy/gson-xml
Comment: não entendi como ele funciona.. Você saberia me explicar?
Comment: @RicardoGiaviti saberia me dizer?
Answer: Já utilizei parte de uma resposta de outro post que eu não havia encontrado:
Fazendo o parse do XML
O código editado por mim se encontra assim e funcionando 100%:
package com.getway.infovendas.Parsers;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.StringReader;
import org.w3c.dom.Document;
import com.getway.infovendas.FormasDePagamento;

public class pFormasDePagamento {

public static void parseXML(String xml) throws ParserConfigurationException, SAXException, IOException {
    InputSource is = new InputSource(new StringReader(xml));
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(is);

    doc.getDocumentElement().normalize();

    String valFormaOutros = doc.getElementsByTagName("VALOR").item(0).getTextContent();

    String descForma = doc.getElementsByTagName("DESCRICAO").item(0).getTextContent();
    String valForma = doc.getElementsByTagName("VALOR").item(1).getTextContent();
    String descForma1 = doc.getElementsByTagName("DESCRICAO").item(1).getTextContent();
    String valForma1 = doc.getElementsByTagName("VALOR").item(2).getTextContent();
    String descForma2 = doc.getElementsByTagName("DESCRICAO").item(2).getTextContent();
    String valForma2 = doc.getElementsByTagName("VALOR").item(3).getTextContent();
    String descForma3 = doc.getElementsByTagName("DESCRICAO").item(3).getTextContent();
    String valForma3 = doc.getElementsByTagName("VALOR").item(4).getTextContent();
    String descForma4 = doc.getElementsByTagName("DESCRICAO").item(4).getTextContent();
    String valForma4 = doc.getElementsByTagName("VALOR").item(5).getTextContent();
    String descForma5 = doc.getElementsByTagName("DESCRICAO").item(5).getTextContent();
    String valForma5 = doc.getElementsByTagName("VALOR").item(6).getTextContent();

    FormasDePagamento.tvFormas.setText("Outros: "+ valFormaOutros+ "\n"+ descForma + ": " + valForma + "\n" + descForma1 + ": " + valForma1 + "\n" + descForma2 + ": " + valForma2 + "\n" + descForma3 + ": " + valForma3 + "\n" + descForma4 + ": " + valForma4 + "\n" + descForma5 + ": " + valForma5);
}

}


In a MLE what are the rules for getting things out of the product symbol $\prod$ in our $f(x_1,...,x_n | \theta )$?

Question: In a MLE what are the rules for getting things out of the product symbol in our $f(x_1,...,x_n | \theta )$?
What I mean is once we have the density function of our distribution we write $f(x_1,...,x_n | \theta ) = \prod_{i=1}^n$ (We have the distribution formula here).
I want to know what are the rules for getting things out i.e does
$\prod_{i=1}^n 2x_i\theta = 2\theta n \prod_{i=1}^n x_i$ ?
This is a very simple example. What happens when you have an exponent?
does $\prod_{i=1}^n 2^{x_i}\theta = 2^{\sum x_i}\theta $ ?
What happens when the exponent does not contain the random variable X how do we get it out? i.e does $\prod_{i=1}^n 2^{\theta + x_i} = 2^{\theta n + \sum x_i}$ ?
It all boils down to when do I know when to multiply by $n$ or not when getting the expressions out of the product symbol? This is what I want answered.
Comment: Just take $n=2,3$ and see what you get. Then for general $n$ it should be obvious. This has nothing to do with MLE or distributions.
Answer: When in doubt, write it out.
\begin{align}
\prod_{i=1}^n 2x_i\theta &= (2x_1 \theta)(2x_2 \theta)(2x_3 \theta) \cdots (2x_n \theta) \\
&= (2\theta)x_1 (2\theta)x_2(2\theta)x_3 \cdots (2\theta) x_n \\
&= (2\theta)^n x_1 x_2 x_3 \cdots x_n = (2\theta)^n \prod_{i = 1}^n x_i.
\end{align}

It all boils down to when do I know when to multiply by n or not when getting the expressions out of the product symbol?

You multiply by $n$ when you are pulling a constant out of each summand:
$$ \sum_{i = 1}^n (f(i) + c) = f(1) + c + f(2) + c + \dots + f(n) + c = nc + \sum_{i = 1}^n f(i). $$
The corresponding rule for products is
$$ \prod_{i = 1}^n f(i) \cdot c = c^n \cdot \prod_{i=1}^n f(i). $$
Another rule that is sometimes helpful is
$$ \prod_{i = 1}^n c^{f(i)} = c^{f(1)} c^{f(2)} \cdots c^{f(n)} = c^{f(1) + f(2) + \dots + f(n)} = c^{\sum_{i = 1}^n f(i)}$$
Comment: thank you very much!
Comment: $\prod_{i=1}^n 2^{\theta + x_i} = 2^{\theta n + \sum x_i}$ was it correct it seems to involve both what you would do for products with what you would for sums?
Comment: Yes, that's exactly right @Nassims


Como criar um @Html.ActionLink dinamico com JQuery?

Question: Estou tentando criar um @Html.ActionLink dinamico com JQuery mas não estou conseguindo, como fazer isso ?
$('#tableView > tbody').empty();
    if (data["CategoriaProduto"].length > 0) {
        $.each(data["CategoriaProduto"], function (i, cp) {
            var editLink = $('@Html.ActionLink("Edit", "edit", "CategoriaProduto"), new {id = ' + cp.id + '}');

            $('#tableView > tbody:last-child').append('
'
                                                    + '' + cp.descricao + '	'
                                                    + '' + editLink + '	'
                                                    + '
');
        });
    }

Comment: Este código está dentro de um arquivo JS ou está na view?
Comment: @goenning dentro de um arquivo JS, eu consigo preencher a table com `cp.descricao`, mas nao estou conseguindo criar o `@Html.ActionLink`
Answer: As instruções que começam com @ são processadas no lado do servidor. O seu arquivo sendo um JavaScript, será enviado para o cliente sem qualquer pré-processamento. Isto significa que o @ não será processado pelo servidor e o JavaScript também não sabe como interpretar isto.
Uma possível solução é dentro da sua View colocar um script assim:

Isto vai criar uma variável de escopo global dentro do JavaScript. Esta variável poderá então ser acessada pelo seu arquivo. Ficaria assim:
$('#tableView > tbody').empty();
    if (data["CategoriaProduto"].length > 0) {
        $.each(data["CategoriaProduto"], function (i, cp) {
            var fullUrl = editUrl + cp.id;

            $('#tableView > tbody:last-child').append('
'
                                                    + '' + cp.descricao + '	'
                                                    + '' + fullUrl + '	'
                                                    + '
');
        });
    }

Neste exemplo vai ser impresso o endereço HTTP, faltando apenas transformar em um link usando a tag a.


Windows PE autorun scripts

Question: I've set up a Windows Preinstallation Environment on a USB Thumb Drive (version from the latest iteration of the Windows Automated Install Kit/WAIK), and I'm working on getting a deployment environment set up.
However, we'd like to make it so our Level 1 technicians can use the deployment system, and because of this, I've written several batch files to minimize the amount of command line work the technicians have to do.
Is there a way I can get these scripts to autorun after the PE environment has finished initializing?
Answer: Under the "sources" folder on the PE key is the "boot.wim" file.

Mount Boot WIM:
dism /Mount-Wim /wimfile:C:[WPE PATH]\sources\boot.wim /index:1 /MountDir:C:\Mounted_images\boot

Then the file can be found at:
C:\Mounted_images\boot\Windows\System32\startnet.cmd

Commit changes and Unmount WIM:
dism /Unmount-Wim /MountDir:C:\Mounted_images\boot /commit

If you want to discard changes instead:
dism /Unmount-Wim /MountDir:C:\Mounted_images\boot /discard
Answer: Generally I don't do autorun scripts for fear that someone would accidentally wipe their machine.  The solution I found worked well was to provide a single batch file with a simple name, and tell them to type that at the command-prompt and press return.  If you have multiple images for different makes/models you could call it a name based on the made model, e.g. type "dellgx280" to re-image a Dell GX280.
You can however modify the startnet.cmd file (WinPE's equivalent of autoexec.bat) to do it if you really want.  That just a case of mounting the PE image r/w, locating the file (at %systemroot%\system32), editing it, then commiting and unmounting.
Comment: This doesn't mess with the disks, it just sets up the network configuration and launches the installer.  Preferably the partitioning will be taken care of manually for both the reason you describe and differentiating systems.
Answer: In addition to the great answer by @nick-phipps, I recommend the Dism++ tool for easy handling (i.e. mounting) of the WIM image in order to edit the "autoexec.bat" file at C:\Mounted_images\boot\Windows\System32\startnet.cmd
Answer: Use the Windows Automated Installation Kit to create a custom WinPE image with a Winpeshl.ini answer file (see http://technet.microsoft.com/en-us/library/cc766156(WS.10).aspx)

Windows PE autorun scripts


Plugin Bxslider não mostra miniatura

Question: Estou usando o plugin Bxslider para fazer um carrosel com miniaturas, só que já tentei de tudo e as miniaturas não aparecem de mandeira nenhuma. As imagens vem do banco, mas mesmo trocado as imagens por um simples texto não aparece. O codigo html * php é esse:

    <?php
    while ($img = mysql_fetch_array($query_fotos)) {
        ?>
        <a data-slide-index="<?php echo $i; ?>" href=""><img src="album/thumb/<?php echo $img['foto'] ?>" />
        <?php
        $i++;
    }
    ?>

E o js está assim:
    $('.bxslider').bxSlider({
    adaptiveHeight: false,
    controls : true,
    pagerCustom: '#bx-pager',
    mode: 'fade'
});

Alguém pode me dar uma ajuda?
Comment: A melhor dica que posso te dar é pra procurar outro plugin, o bx slider da muito problema, ele é muito instável, usar ele significa ir dormir com a animação funcionando e acordar com ela toda errada inexplicavelmente
Comment: Isso acontece porque você não colocou os "items", que seriam os elementos de dentro do elemento com a classe `bx-pager`. Tente algo como `<?php`.
Answer: O problema é que pagerCustom não é para uso com carrosséis dinâmicos:

[...] Not for use with dynamic carousels.

E também que o Pager não corresponde ao número de slides, mas ao número de páginas. Uma opção é usar o callback buildPager:
buildPager: function ( slideIndex ) {
    var img_pager = 'http://dummyimage.com/50x50/aaa/fff&text=' + (slideIndex + 1);
    return '';
}

$('.bxslider').bxSlider({
    slideWidth: 300,
    minSlides: 3,
    maxSlides: 3,
    moveSlides: 3,
    slideMargin: 10,
    pager: true,
    pagerType: 'full',
    buildPager: function (slideIndex) {
        var img_pager = 'http://dummyimage.com/25x25/aaa/fff&text=' + (slideIndex + 1);
        return '';
    }
});
.bx-pager-item {
    margin: 0 5px;
}
.bx-wrapper .bx-pager, .bx-wrapper .bx-controls-auto {
    bottom: -40px !important; /* só aqui no stacksnippet */
}
<link href="https://cdn.rawgit.com/stevenwanderski/bxslider-4/master/jquery.bxslider.css" rel="stylesheet"/>

Já que está puxando imagens do BD via, uma opção é criar um objeto JS no loop while (não testado):

E no buildPager:
var img_pager = pager_images[slideIndex];

Answer: Já tentou estruturar com
 e
? E eu usaria a classe bxslider na

Comment: Já tentei, também não vai
Comment: Ao invés de ` ` tente `` só para ver se puxa as imagens. Já usei esse plugin e nunca tive problemas

Plugin Bxslider não mostra miniatura


Change xml selector values from java code

Question: I am trying to create a universal image selector for multiple buttons.
Is there an option to change the xml's "android:drawable" resource from java code?
Comment: for which control you want to set drawable resource. e.g. Button or textview
Answer: use StateListDrawable for seeting selector by code as:
<code>StateListDrawable states = new StateListDrawable();
states.addState(new int[] {android.R.attr.state_pressed},
    getResources().getDrawable(R.drawable.pressed));
states.addState(new int[] {android.R.attr.state_focused},
    getResources().getDrawable(R.drawable.focused));
states.addState(new int[] { },
    getResources().getDrawable(R.drawable.normal));

imageView.setImageDrawable(states);  //YOUR IMAGE HERE
//AND FOR BUTTON
 button.setBackgroundDrawable(states);//FOR BUTTON
</code>
Comment: imageView? do i need to set up one within my layout?
Comment: yes as your need create dynamically or add an Imageview to Xml layout
Comment: @user1185841 : you can try to search on google how we create a dynamic ImageView in android.if this answer help u in solving your problem then mark it as answer.Thanks friend!!! :)
Comment: needed to add the negative value for each state to make it work. Thanks!!
Answer: You can set button drawable from java like
<code>    btnSettings.setBackgroundResource(R.drawable.ic_launcher);
</code>


How to use owl carousel options in React Owl Carousel?

Question: I am new to React JS. I have tried to use owl carousel in React.
The package link I installed from npm is
https://www.npmjs.com/package/react-owl-carousel
As instructed I have imported Owl Carousel component on specific page. Here is the code:
import React, { Component } from 'react';
import {Grid, Row, Col , ProgressBar } from 'react-bootstrap';
import UserAvtar from '../common/UserAvtar.js';
import SectionHeaderOfCards  from '../common/SectionHeaderOfCards.js';
import OwlCarousel from 'react-owl-carousel';

const options = {
    items: 4,
};

class DashboardPage extends Component {
  render() {
    return (

              <UserAvtar />

              <Grid>
                  <SectionHeaderOfCards title="Recommended Matches" />
                  <OwlCarousel margin={10} >

1

2

3

4

5

6

                  </OwlCarousel>
              </Grid>

    );
  }
}

export default DashboardPage;

As default This code outputs 3 items at a time (As 3 is the default value in owl carousel) . I thought of I may initialised the value with 4 , hence tried ,
const options = {
    items: 4,
};

But it's not working. There is nothing mentioned in its node package either. Anyone knows how to use owl carousel options in React Owl carousel ?
Apart I want to show 3 items for devices between 768px to 1200px , 2 items between 500px to 767px and 1 item for the devices below 499px.
Here is how normal owl carousel use the option to add responsiveness. https://owlcarousel2.github.io/OwlCarousel2/demos/responsive.html
How to achieve the same in React owl carousel ?
Comment: `` or ``
Comment: you are not adding the option object to OwlCarousel Component.
Comment: Anu suggestions to How to add it ?
Comment: Check the docs for [responsiveClass](https://github.com/seal789ie/react-owl-carousel#owlcarousel-class-props)
Comment: responsiveClass is not much help. I would rather like to use Owl Carousel option "responsive" .
Comment: You can use [responsive](https://github.com/seal789ie/react-owl-carousel#owlcarousel-options) too. Its same as the official docs.
Answer: You need to add options object to OwlCarousel component.
Example:
<OwlCarousel margin={10} items={4} >
    //...
</OwlCarouse>

OR
<OwlCarousel margin={10} {...options} >
    //...
</OwlCarouse>

Comment: A small help further please : Want to add responsive option for different break point ? Any suggestions ? or want me to create a separate question ?
Comment: you can create a state object with the default values for the `options` and then update the state with the desired way of yours. this way you can set the options like this ``. If you explain it a little bit more I can update my answer.
Comment: Edited question.
Answer: Best you can use:
render() {
    const options = {
      items: 1,
      nav: true,
      navText:["

","

"],
      rewind: true,
      autoplay: true,
      slideBy: 1,
      dots: true,
      dotsEach: true,
      dotData: true
    };

    return (
<OwlCarousel ref="gallery" options={options}>
          ...
        </OwlCarousel>
)


Changing Windows Network Profile from "DomainAuthenticated" to Public

Question: I have a domain joined Windows Server 2012 R2 box that has the OpenVPN 2.3.13 client software installed on it. When the VPN connection is active the "Ethernet 2" (TAP interface) connection is placed into the Domain Network category alongside the main LAN NIC by NLA. Ideally I want to be able to assign the VPN interface to the Public category. I've tried via PowerShell, but get this error constantly:

Unable to set the NetworkCategory due to one of the following possible
  reasons: not running PowerShell elevated; the NetworkCategory cannot
  be changed from 'DomainAuthenticated'; user initiated changes to
  NetworkCategory are being prevented due to the Group Policy setting
  'Network List Manager Policies'. At line:1 char:1
  + Set-NetConnectionProfile -InterfaceIndex 15 -NetworkCategory Public
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : PermissionDenied: (MSFT_NetConnect...72AADA665483}"):root/StandardCi...nnectionProfile)
  [Set-NetConnectionProfile], CimException
      + FullyQualifiedErrorId : MI RESULT 2,Set-NetConnectionProfile

15 is the interface number of "Ethernet 2"
Its worth noting, I am running this command in an elevated PowerShell session and have I tried all the available GPO policies but the error is constantly thrown. Most information about NLA suggest switching between Private and Public should work, but DomainAuthenicated seems a little bit different.
The registry method doesn't have an actual profile for Ethernet 2, so it can't be changed that way either.
Is there anyway to force the TAP adapter to be Public? The OpenVPN connection itself does not override the default gateway of the main NIC and uses the 10.0.0.0/8 subnet. The fact I use route-nopull and override the routes might be part of the problem with the way NLA detects the networks.
Ethernet adapter Ethernet 2:

Connection-specific DNS Suffix  . :
Link-local IPv6 Address . . . . . : fe80::xxxx:xxxx:xxxx:xxxx%xx
IPv4 Address. . . . . . . . . . . : 10.xx.xx.xx
Subnet Mask . . . . . . . . . . . : 255.255.255.252
Default Gateway . . . . . . . . . :

The main reason for needing to assign the Public profile is for firewall rules, I am having trouble preventing certain applications from only using the VPN interface, being able to write network profile based firewall rules seems to work best in this case, I've tried writing rules based on the local IP address but this didn't work.
Comment: `user initiated changes to NetworkCategory are being prevented due to the Group Policy setting 'Network List Manager Policies` - This would seem to imply that user initiated changes are prevented via Group Policy. In order to allow user initiated changes then the GPO needs to be configured to allow that. Have you located the domain GP where this is configured?
Comment: @joeqwerty I've looked into the GPO locally and via domain at Computer Configuration / Windows Settings / Security Settings / Network List Manager Policies, none of settings allow the change.
Comment: It sounds like your elevated account is missing the right to change the NetworkCategory.  You may need to add this, or remove/relax a restriction on it.  https://technet.microsoft.com/en-us/library/jj966256(v=ws.11).aspx.  But it sounds like you can only set the user permission objects for 'unidentified' networks.
Comment: Also, `When the VPN connection is active the "Ethernet 2" (TAP interface) connection is placed into the Domain Network category alongside the main LAN NIC by NLA.`  Isn't this the whole point of VPN?  If you wish to increase the security for VPN users, set their settings higher in the `DomainAuthenticated` category, and even higher in `Public`.
Comment: I've tried modifying that GPO it doesn't allow the change still, both locally and via domain policy and running `gpupdate /force` I can't get round that error no matter what settings I change.
Comment: Why don't you just add executable-based firewall rules?
Comment: @Lenniey I can but I wanted to use Network Profiles in addition to using scope and program based rules. I.e. domain and public, its easier to control that way. Using IP scope alone won't work currently based on the subnets, I need one NLA profile to be different. Its interesting because I had the OpenVPN client setup on another domain connected machine before and it assigned it as Public straight away.
Comment: @Pandorica Try not setting a default gateway on your OpenVPN adapter. It should become public. After that set a gateway and see what happens.
Comment: @Lenniey, by default the VPN interface does not get a default gateway value set. I've updated the original post.
Comment: Could you please try using get-ciminstance and see if that sticks?
Code to get is here:
Comment: get-ciminstance -Namespace root/StandardCimv2 -ClassName MSFT_NetConnectionProfile -Filter "interfacealias='Ethernet 2'"
Comment: You may need to leave -Filter off to see what your actual 'interfacealias' name is. From there, you should be able to | to set-ciminstance -property @{NetworkCategory="Public"}
Comment: In the information above the Connection-specific DNS Suffix is empty, is it really empty or have you removed it to hide it?
Comment: @Drifter104 Not obfuscated by myself, it is empty.
Comment: Add a random, non-existent one in via the dns tab on the connection properties. This should leave it in a private/public state.
Comment: @Drifter104 Tried that and disabled and enabled the connection, hasn't changed the profile.
Comment: Strange, basically domain authenticated is determined using a registry key. If the value in the registry matches the value in the connection and an ad server is found for the same name you get that profile. Changing the registry key would do it but it is a single key, not per connection. So I thought changing the connection suffix would suffice. Did you also restart the NLA service after chaning the suffix?
Comment: @Drifter104 I did, no change sadly.
Answer: The below will use WMI/CIM.
get-ciminstance -Namespace root/StandardCimv2 -ClassName MSFT_NetConnectionProfile -Filter "interfacealias='Ethernet 2'" | set-ciminstance -property @{NetworkCategory="1"}

Comment: I've come across that article in my searches also. In most cases however, it seems to be the reverse of what I'm trying to achieve, switching from rather than to DomainAuthenicated. I may just have to accept its probably not possible.
Comment: Sorry, got the same error. This is the error if you try and set it to DomainAuthenticated.
Comment: Set-CimInstance : Unable to set NetworkCategory to 'DomainAuthenticated'.  This NetworkCategory type
will be set automatically when authenticated to a domain network.
At line:1 char:124
+ ... lias='Ethernet 2'" | Set-CimInstance -Property @{NetworkCategory='2'}
+                          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (MSFT_NetConnect...5A09504828DA}"):CimInstance) [Set-C
   imInstance], CimException
    + FullyQualifiedErrorId : MI RESULT 4,Microsoft.Management.Infrastructure.CimCmdlets.SetCimInstan
   ceCommand
Comment: Unfortunately, I still get the same error in regards to domain policies blocking the change, as I'm running as PowerShell Admin as before. In this case I am trying to move Ethernet 2 away from being set to DomainAuthenicated, but it looks like in my case this is forced and cannot be changed.
Comment: @Pandorica as you mentioned, it appears that once you join a domain, NetworkCategory is locked into DomainAuthenticated.
Comment: @Pandorica are both your NICs set to DomainAuthenticated? In some of the web examples (http://windowsitpro.com/powershell/how-force-network-type-windows-using-powershell) with two NICs, one is set to public, the other to DomainAuthenticated. Can you change one and not the other?
Comment: Both are set to DomainAuthenticated, neither can seemingly be overridden.
Comment: @Pandorica is your second NIC registering in DNS? I'm wondering if that registration is causing it to be DomainAuthenticated? This blogpost also has some interesting information which might be relevant.
Comment: I have already disabled this option as I thought it might be related. I can't see the blog post link you are referring to.
Comment: Sorry @Pandorica Ctrl+V didn't work for me at midnight.... http://evansblog.thebarrs.info/2013/02/windows-server-force-your-network.html Thanks, Tim.
Answer: Removing the adresses of the 'public' adapter from the list of listening addresses of your DNS server would do the trick.
Answer: Review the third option "Using the Firewall" on this page: https://evansblog.thebarrs.info/2013/02/windows-server-force-your-network.html
You can prevent DomainAuthenticated network profile by using the Windows Firewall to create an Outbound rule to block the Windows service "Network Location Awareness".  Make sure to specify the Local IP of the VPN adapter in the rule so it doesn't affect other adapters.  The VPN adapter should now be classified as "Public" network profile.


Temp files disappears when CarrierWave processing

Question: I created an ActiveJob to process my carrier waves uploads.  However, when I upload more than one image, I get the following error for the second file:
Errno::ENOENT (No such file or directory @ rb_sysopen - C:/Users/tdavi/AppData/Local/Temp/RackMultipart20180830-392-z2s2i.jpg)

Here's the code in my controller:
if @post.save
  files = params[:post_attachments].map { |p|
    {image: p['photo'][:image].tempfile.path, description: p['photo'][:decription]}
  }
  ProcessPhotosJob.perform_later(@post.id, files.to_json)
  format.html { render :waiting }
end

And my ActiveJob
require 'json'

class ProcessPhotosJob < ApplicationJob
  queue_as :default

  def perform(post_id, photos_json)
    post = Post.friendly.find(post_id)
    photos = JSON.parse photos_json

    photos.each do |p|
        src_file = File.new(p['image'])
        post.post_attachments.create!(:photo => src_file, :description => p[:description])
    end

    post.processed = true
    post.save
  end
end

When I upload only one file to upload, it works okay.
Answer: You should not pass Tempfile to the queued jobs.
First of all - TempFiles can be deleted automatically by Ruby (docs, explanation)
If you would like to upload file(s) and process them later (in a background), then I would suggest you check this question.


windows 7 firewall logging PID

Question: i enabled my windows 7 firewall to by default block all outbound connections by default. i configure each and every program that needs network access in the 'Windows Firewall with Advanced Security' mmc. problem is sometimes i cant find the program that needs network access. i enabled firewall logging but that log file does not contain the PID of the process that was blocked.
<code>2010-08-26 17:57:33 DROP TCP 192.168.1.200 188.8.131.52 64883 80 0 - 0 0 0 - - - SEND
2010-08-26 17:57:33 DROP TCP 192.168.1.200 22.214.171.124 64884 80 0 - 0 0 0 - - - SEND
2010-08-26 17:58:10 DROP TCP 192.168.1.200 184.108.40.206 64885 80 0 - 0 0 0 - - - SEND
</code>
i know that this connection is triggered by the Games for Windows Live process, but allowing that specific executeable to go through the firewall does not prevent these connections from being dropped. how do i find out what actual program (or service) is trying to open up these connections, so i can make a firewall rule to allow it?
Answer: Three years late, but still, if anyone needs to know, my solution would be one of the following:

program that installs its own firewall driver with notification functionality (NetLimiter, Comodo Firewall)
program that enables audit logging of blocked connections into security log (WFNotifier, WFControl)
auditpol /set /subcategory:{0CCE9226-69AE-11D9-BED3-505054503030} /failure:enable

windows 7 firewall logging PID


dc.js: How to change the data distribution in pie chart using different input threshold?

Question: I would like to use the score from input field to change the data distribution in pie chart.
For example, the distribution "71% High/ 28% Low" with scoreThreshold 0.5 will be changed to "42% High/ 57% Low" with scoreThreshold 0.7.
I made this example here, but the result was not satisfactory: when typing 0.5 in the input field and clicking "check!", the pie chart distribution does not change.
This decides the distribution:
//##  pie chart
var coreCount = ndx.dimension(function (d) {
    var maxNumber=80;
    if (typeof scoreThreshold!='number') {scoreThreshold=0.5}
    //console.log(scoreThreshold)
    if (d.scores >maxNumber*scoreThreshold)
        {return 'High';}
    else {return 'Low';}
    });

I would like to renew the  coreCount function to reassign the distribution using input score threshold. But it does not work:
$('#scoreThresholdBt').click(function () {
            scoreThreshold=document.getElementById('scoreThreshold').value
            scoreThreshold=parseFloat(scoreThreshold);
            console.log(scoreThreshold,typeof scoreThreshold);
            function redo_coreCount () {
                var coreCount = ndx.dimension(function (d) {
                    var maxNumber=80;
                    console.log(scoreThreshold);
                    if (d.count >maxNumber*scoreThreshold)
                        {return 'High';}
                    else {return 'Low';}
                    });
            }; redo_coreCount();
            coreCount.group();/**/
            dc.renderAll();
            dc.redrawAll();
        });

How can I realize this function?
I really appreciate any help.
Answer: You are essentially putting the new dimension in a temporary variable which gets thrown away immediately. coreCount in the click function is unrelated to the variable with the same name at the global level.
Likewise, coreCount.group() is not an action; it's constructing a group object which will also get lost if you don't use it.
You need to assign the new dimension and group to your chart, since it doesn't track the value of the global or the local coreCount.
So let's change the function to return a new dimension based on reading the score threshold from the input:
function coreCount_from_threshold() {
  var scoreThreshold=document.getElementById('scoreThreshold').value;
  scoreThreshold=parseFloat(scoreThreshold);
  console.log(scoreThreshold,typeof scoreThreshold);
  if (isNaN(scoreThreshold)) {scoreThreshold=0.5}
  return ndx.dimension(function (d) {
    var maxNumber=80;
    if (d.scores >maxNumber*scoreThreshold)
        {return 'High';}
    else {return 'Low';}
    });
}

Note that we need to use isNaN here, because typeof NaN === 'number'
We can use this both at initialization time:
var coreCount = coreCount_from_threshold();

and on click:
$('#scoreThresholdBt').click(function () {
    coreCount.dispose();
    coreCount = coreCount_from_threshold();
    coreCountGroup = coreCount.group();
    coreYesNoPieChart
      .dimension(coreCount)
      .group(coreCountGroup);
    dc.redrawAll();
});

Note that we are assigning to the same global variables coreCount and coreCountGroup (because we don't use var here). We first dispose the old dimension, because otherwise it would continue to filter and take up resources. Then we assign the new dimension and group to the chart (because otherwise it won't know about them).
We only need to do a redraw (not a render) here, because dc.js charts can just update when they get new data.
Here is a working fork of your fiddle.
Comment: I tried this in your fiddle and noticed a few other problems, like having to dispose of the old dimension. I'll give it another shot on Monday.
Comment: Thank you very much,  Gordon, I tried your suggestion,  but there were still problems.  I am looking forward reading your feedback on Monday.
Comment: Okay, I've updated my answer with a few more necessary details. Would you consider contributing this example to dc.js? It would be nice to have an example of replacing the dimension & group.
Comment: Sure, Gordon. I have also another big project using dc.js, may I send the link to you via mail?
Comment: @Woodran, thanks for the PR. I will merge it soon. If anyone is looking for a complete example, it's here: https://github.com/dc-js/dc.js/pull/1166


replacing the column between 2 columns that have different column name using sql

Question: How can I replace the content of home_team_api_id and away_team_id to real name
I have 2 tables using sql. first one is the home and away id and the 2nd one is the description of the home and away id from table 1
Table 1
home_team_api_id    away_team_api_id
================    ================
8600                8540
9882                8636
8524                8551
8529                8543
8530                10233

Table 2
team_api_id       team_long_name     team_short_name
===========       ==============     ===============
8600                Udinese          UDI
9882                Sampdoria        SAM
8524                Atalanta         ATA
8529                Cagliari         CAG
8530                Catania          CAT
8540                Palermo          PAL
8636                Inter            INT
8551                Siena            SIE
8543                Lazio            LAZ
10233               Genoa            GEN

desired result
home_team_api_id    away_team_api_id
================    ================
Udinese              Palermo
Sampdoria            Inter
Atalanta             Siena
Cagliari             Lazio
Catania              Genoa

Comment: Tag the DBMS (i.e. `MySQL`, `SQL Server`, etc..) that you are using.
Answer: Join table2 twice with different alias names
select home.team_long_name as home_team_api_id,
       away.team_long_name as away_team_api_id
from table1
join table2 as home on home.team_api_id = table1.home_team_api_id
join table2 as away on away.team_api_id = table1.away_team_api_id


Bootstrap interferindo ImageAreaSelect (Primefaces)

Question: Estou utilizando o componente, do primefaces Extesions, chamado ImageAreaSelect.
Primefaces Extesion - ImageAreaSelect
Porem esta TAG do Bootstrap está fazendo com que o background do ImageAreaSelect está ficando desproporcional.
<code>* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box
}
:after,
:before {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box
}
</code>
Esta imagem é o background com problema

Como faço para solucionar este problema? se eu tirar o CSS o template fica bugado.
Eu estava pensando em solucionar o problema tirando o background do ImageAreaSelect porem não faço ideia de qual TAG ele usa.
Tambem não achei na documentação do primefaces
Comment: Use a opção Inspect/Inspecionar do Google Chrome sobre o componente que você encontra o CSS que ele usa.
Answer: Consegui fazendo o seguinte
<code>.pe-imgageareaselect-outer {
    display: none !important;
}

.pe-imgageareaselect-selection {
    background: black !important;
}
</code>


JSONObject toString sometimes throw a ConcurrentModificationError

Question: At the outset, sorry about not being able to provide my code. I created a JSONObject and I am converting to string and my Android app crashes sometimes with the following error.
E/AndroidRuntime( 6162): java.util.ConcurrentModificationException
E/AndroidRuntime( 6162):    at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)
E/AndroidRuntime( 6162):    at org.json.JSONArray.writeTo(JSONArray.java:612)
E/AndroidRuntime( 6162):    at org.json.JSONStringer.value(JSONStringer.java:233)
E/AndroidRuntime( 6162):    at org.json.JSONObject.writeTo(JSONObject.java:720)
E/AndroidRuntime( 6162):    at org.json.JSONObject.toString(JSONObject.java:689)

From my research, I am not able to tell why there's a ConcurrentModificationException. I have only one thread accessing the information. I don't think the toString() does any removal. Can someone explain if they have seen any such issue in Android and how they might have gone about sorting it?
EDITED
Added a slightly modified code per @domi's suggestion. The problem is consistently seen in the line

message.put("message", tempObject.toString());

private void message() {
    if (this.jsonObject == null)
        this.jsonObject = new JSONObject();
    try {
        TimeZone tz = TimeZone.getTimeZone("UTC");
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'", Locale.US);
        df.setTimeZone(tz);
        Date date = new Date();
        String dateString = df.format(date);
        System.out.println(dateString);
        jsonObject.put("Date", dateString);

        JSONObject jsObj = new JSONObject();
        jsObj.put("Cat", Cat.getInfo());
        jsonObject.put("Cat", jsObj);

        JSONArray tempInfo = getJsonArray(Dog.getInfo());

        jsonObject.put("Dog", tempInfo);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    TimeZone tz = TimeZone.getTimeZone("UTC");
    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSS'Z'", Locale.US);
    df.setTimeZone(tz);
    Date date = new Date();
    String dateString = df.format(date);

    if (this.message == null)
        this.message = new JSONObject();

    try {

        message.put("topic", topic);
        JSONObject tempObject = new JSONObject();

        synchronized(this.jsonObject) {
            System.out.println("In lock" + dateString);
            tempObject = this.jsonObject;
            this.jsonObject = null;
        }

        message.put("message", tempObject.toString());
        tempObject = null;

        synchronized (this.message) {
            doSomething(message);
        }
        System.out.println("Out lock");
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        System.out.println(message);
    }
}

Comment: http://stackoverflow.com/questions/10690903/arraylist-concurrent-modification
Comment: Thanks @domi. I am not iterating thru the JSONObject though I think toString has to. It is crashing inside the toString method. toString shouldn't be removing any elements.
Comment: you should really post some code, a little snippet is okay :)
Answer: I was able to resolve this. The problem was
message.put("message", tempObject.toString());

The method call tempObject.toString() leads to an iteration through the list (presumption) and the message.put(...) leads to accessing the resultant string. Sometimes this leads to ConcurrentModificationException. I was able to resolve it by doing it in two lines and having some locks in place.


MongoDB How to compare fields in associative array

Question: I'm looking for the right query in MongoDB to compare two values inside associative arrays, I have documents like this:
{
    "_id" : ObjectId("5502cc4280ee2cd549dee9e8"),
    "formats" : [
        {
            "name" : "first",
            "prices" : [
                {
                    "futurePrice" : 5.49,
                    "price" : 5.49
                }
            ]
        },
        {
            "name" : "second",
            "prices" : [
                {
                    "futurePrice" : 5.49,
                    "price" : 5.49
                }
            ]
        }
    ]
}

I need to compare the futurePrice and price fields to find document that have at least one format with a futurePrice > price
I tried something like this:
Collection.find({'formats.prices': { $elemMatch: 'this.futurePrice > this.price' }}, ...

But it doesn't seem to work, any idea?
Answer: You can do this with the aggregation framework using $cond operator:
db.Testing.aggregate([
    {
        '$unwind': '$formats'
    },
    {
        '$unwind': '$formats.prices'
    },
    {
        '$project':
        {
            formats :1,
            eq : {
                $cond: [ { $gt: [ '$formats.prices.futurePrice', '$formats.prices.price' ] }, 1, 0 ]
            }
        }
    },
    {
        $match: { eq: 1 }
    },
    {
        '$group':
        {
            '_id' : '$_id',
            'formats':
                {
                    '$push': '$formats'
                }
            }
        }
])

EDIT:
As @pepkin88 mentioned in the comment you can use $where operator to get the same result. Although it doesn't take advantage of indexes and may impact performance.
db.Testing.find(function() {
    for (i = 0; i < this.formats.length; i++) {
        for (j = 0; j < this.formats[i].prices.length; j++)
            return this.formats[i].prices[j].futurePrice > this.formats[i].prices[j].price
    }
})

Comment: Yes you can, with `$where` operator. It isn't optimized and doesn't use indices, but works.
Comment: @pepkin88 you are right. Thank you for pointing it out. I will modify my answer accordingly.