text:
Q: Opencv : Solve PNP error, EPNP and P3P failed I'm trying to compare precision and time consuming between every SolvePnP possibility : CV_ITERATIVE, CV_EPNP, and CV_P3P
I also compared my result with Matlab EPNP.
And it's look like EPNP and P3P failed :
std::vector<cv::Point2f> imgPoints;
imgPoints.push_back(cv::Point2f(400,188));
imgPoints.push_back(cv::Point2f(400,300));
imgPoints.push_back(cv::Point2f(512,300));
imgPoints.push_back(cv::Point2f(512,188));

double size = 80.0;
std::vector<cv::Point3f> objPoints;
objPoints.push_back(cv::Point3f(0,0,0));
objPoints.push_back(cv::Point3f(0,size,0));
objPoints.push_back(cv::Point3f(size,size,0));
objPoints.push_back(cv::Point3f(size,0,0));

cv::Mat rvec0 = cv::Mat::zeros(3, 1, CV_64FC1);
cv::Mat tvec0 = cv::Mat::zeros(3, 1, CV_64FC1);

cv::Mat rvec1 = cv::Mat::zeros(3, 1, CV_64FC1);
cv::Mat tvec1 = cv::Mat::zeros(3, 1, CV_64FC1);

cv::Mat rvec2 = cv::Mat::zeros(3, 1, CV_64FC1);
cv::Mat tvec2 = cv::Mat::zeros(3, 1, CV_64FC1);

cv::Mat cam, coeff;
cam = (cv::Mat_<double>(3,3) << 700,0,300,0,700,400,0,0,1);
cv::solvePnP(objPoints,imgPoints,cam,coeff,rvec0,tvec0,CV_ITERATIVE);
cv::solvePnP(objPoints,imgPoints,cam,coeff,rvec1,tvec1,CV_P3P);
cv::solvePnP(objPoints,imgPoints,cam,coeff,rvec2,tvec2,CV_EPNP);

cv::Mat rmat0,rmat1,rmat2;
cv::Rodrigues(rvec0,rmat0);
cv::Rodrigues(rvec1,rmat1);
cv::Rodrigues(rvec2,rmat2);

std::cout << "ITERATIVE : Rotation matrix : " << std::endl << rmat0 << std::endl;
std::cout << "ITERATIVE : Tranlation vector : " << std::endl << tvec0 << std::endl << std::endl;

std::cout << "P3P : Rotation matrix : " << std::endl << rmat1 << std::endl;
std::cout << "P3P : Tranlation vector : " << std::endl << tvec1 << std::endl << std::endl;

std::cout << "EPNP : Rotation matrix : " << std::endl << rmat2 << std::endl;
std::cout << "EPNP : Tranlation vector : " << std::endl << tvec2  << std::endl << std::endl;

Give me :
ITERATIVE : Rotation matrix : [1, -2.196885546074445e-016, 9.692430825310778e-016; 2.196885546074445e-016, 1, 1.012059558506939e-015; -9.692430825310778e-016, -1.012059558506939e-015, 1]
ITERATIVE : Tranlation vector : [71.42857142857143; -151.4285714285714; 500]
P3P : Rotation matrix : [1, 0, 0; 0, 1, 0; 0, 0, 1]
P3P : Tranlation vector : [-3.97771428571427e-015; -4.022285714285698e-015; 9.989999999999962e-017]
EPNP : Rotation matrix : [1, 0, 0; 0, 1, 0; 0, 0, 1]
EPNP : Tranlation vector : [-3.97771428571427e-015; -4.022285714285698e-015; 9.989999999999962e-017]
Any suggestion ?
Alexandre Kornmann

A: I have hints for you, some things sounds strange for me :

*

*You give (300,400) for center point in the cam matrix, so your image is 600*800 (vertical) ?

*For the projection position of your 2D points, be sure you put them in the OpenCV way : the (0,0) point in an image is the top left corner.

*Your points are coplanar (plane z=0) and maybe solvePnP is sensitive to this.

A: P3P is'not a good method,it's precision is very poor.EPNP seems like a best choice in precision.But you shouldn't use EPNP only,with Ransac algorithm will be better.


text:
Q: Extending ssl sharepoint site with extranet So I have this project I took over from another guy - whom I can't consult with unfortunately. And I have no experience in SSL.
Basically there's this sharepoint web-app which has been setup to use SSL - and everything's working great. I see in the central admin page, that there are two zones to the web-app (standard and internet). In IIS there are 2 web sites containing to this sharepoint site.
One has the port value TCP 0 and SSL port 443, the other a TCP 80 with a redirect to the SSL website. So far so good.
Now I need to extend this website with a forms-authenticated extranet. How do I go about this?
I did, what I would do with a normal sharepoint website, and first extended the web-app from central admin, remembered to set the zone to extranet, and checked "use SSL". (port 1580)
I went into the web-config file in the virtual directory, and set up the forms-stuff (connection string, providers, etc.).
But then I was stumped as to how to actually access this extranet. I couldn't access it by doing:
http://site.com:1580
or
https://site.com:1580

And I tried just changing the existing redirect to the virtual directory of the extranet - no dice. I know this is simple, so there must be someone who can explain it to me, as if I was a child :D

A: My guess is that IIS does not know about your 1580 port.
Go into IIS manager, into the new extended web site, and check that the 1580 port has been mapped to it. Check that the SSL port has been mapped too. And don't forget to add the certificate.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to create a surface chart with Apache POI? Does anyone know how to create a surface chart with Apache POI?
Unfortunately I could not find an example anywhere.
I tried to use other chart examples but without success.

A: Since XDDF was introduced with apache poi 4, this should be used. And XDDFChartData has a subclass XDDFSurface3DChartData.
What one needs to know when using:
A surface 3D chart needs an additional series axis. And this series axis needs to be defined for the XDDFSurface3DChartData.
Minimal example which creates a Excel sheet having a surface 3D chart. This is tested and works using the current apache poi 5.2.2.
import java.io.FileOutputStream;

import org.apache.poi.ss.util.CellRangeAddress;

import org.apache.poi.xddf.usermodel.*;
import org.apache.poi.xddf.usermodel.chart.*;
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
import org.apache.poi.xssf.usermodel.XSSFDrawing;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class CreateExcelXDDFSurface3DChart {

 public static void main(String[] args) throws Exception {
  try (XSSFWorkbook document = new XSSFWorkbook()) {
   XSSFSheet sheet = document.createSheet("SurfaceChart");

   // create the data
   String[] categories = new String[] { "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9" };
   Double[] values1 = new Double[] { 10d, 20d, 10d, 15d, 12d, 20d, 10d, 18d, 19d };
   Double[] values2 = new Double[] { 20d, 10d, 15d, 20d, 11d, 17d, 18d, 20d, 10d };
   Double[] values3 = new Double[] { 14.5d, 14d, 13.5d, 13d, 12.5d, 12d, 11.5d, 11d, 10.5d };
   int r = 0;
   for (String cat : categories) {
    sheet.createRow(r).createCell(0).setCellValue(cat);
    sheet.getRow(r).createCell(1).setCellValue(values1[r]);
    sheet.getRow(r).createCell(2).setCellValue(values2[r]);
    sheet.getRow(r).createCell(3).setCellValue(values3[r]);
    r++;
   }

   // create the chart
   XSSFDrawing drawing = sheet.createDrawingPatriarch();
   XSSFClientAnchor anchor = drawing.createAnchor(0, 0, 0, 0, 5, 0, 20, 30);
   XDDFChart chart = drawing.createChart(anchor);

   // create data sources
   int numOfPoints = categories.length;
   XDDFDataSource<String> categoriesData = XDDFDataSourcesFactory.fromStringCellRange(sheet, new CellRangeAddress(0, numOfPoints-1, 0, 0));
   XDDFNumericalDataSource<Double> valuesData1 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, numOfPoints-1, 1, 1));
   XDDFNumericalDataSource<Double> valuesData2 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, numOfPoints-1, 2, 2));
   XDDFNumericalDataSource<Double> valuesData3 = XDDFDataSourcesFactory.fromNumericCellRange(sheet, new CellRangeAddress(0, numOfPoints-1, 3, 3));

   // surface 3D chart
   XDDFCategoryAxis categoryAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
   XDDFValueAxis valueAxis = chart.createValueAxis(AxisPosition.LEFT);
   valueAxis.setCrosses(AxisCrosses.AUTO_ZERO);
   // surface 3D chart needs a series axis
   XDDFSeriesAxis seriesAxis = chart.createSeriesAxis(AxisPosition.BOTTOM);
   seriesAxis.setCrosses(AxisCrosses.AUTO_ZERO);
   seriesAxis.crossAxis(valueAxis);

   XDDFChartData data = chart.createData(ChartTypes.SURFACE3D, categoryAxis, valueAxis);
   // surface 3D chart needs the series axis applied to the XDDFSurface3DChartData
   ((XDDFSurface3DChartData)data).defineSeriesAxis(seriesAxis);

   XDDFChartData.Series series = data.addSeries(categoriesData, valuesData1);
   series.setTitle("Series 1", null);
   series = data.addSeries(categoriesData, valuesData2);
   series.setTitle("Series 2", null);
   series = data.addSeries(categoriesData, valuesData3);
   series.setTitle("Series 3", null);

   chart.plot(data);

   // set legend
   XDDFChartLegend legend = chart.getOrAddLegend();
   legend.setPosition(LegendPosition.BOTTOM);

   // Write the output to a file
   try (FileOutputStream fileOut = new FileOutputStream("./CreateExcelXDDFSurface3DChart.xlsx")) {
    document.write(fileOut);
   }
  }
 }
}

Btw.: I have never understood where a surface chart will be helpful for data presentation.


text:
Q: Cleaning soot out of a server Cleaning dusty servers is one thing - but I have a slightly different problem: Soot in the servers!
During some warm summer months, we needed to open the windows at our server room.
Unfortunately, the windows are located directly above the exhaust vent from a diesel heater, and we soon discovered that all our servers were (internally and externally) covered with a fine layer of soot. The soot sorts of "stick" to the surfaces, making cleaning a difficult task to say the least.
I wonder if anyone has any experiences in removing soot when vacuuming / compressed air doesn't work. Some surfaces can easily be cleaned with paper towels / water, but not the circuit boards, fans and power supplies.
I would guess this could also be appliccable to servers salvaged from fires etc.

A: I'm not sure what the best solution to your problem is but using a vacuum cleaner on a server or pc is not a good idea, due to the amount of static they generate. You may not see the effects immediately, but many of the components on the motherboard are easily damaged by ESD.

A: I would recommend dilute isopropyl alcohol (cut with distilled water about 60/40) and a natural-bristle paint brush. Don't use paper towels/napkins as they will shed fibers.  When done, make sure you let it dry completely.
Before you start on a particularly nasty machine, where you might need to remove the motherboard:

*

*Reboot to the CMOS settings screen

*Write down EVERYTHING

*Remove the motherboard

*Take out the CMOS battery

*Clean completely

*Let dry

*Reinstall the CMOS battery

*Reinstall the motherboard

*Use those settings you wrote down.

If it is really bad, you can use the dishwasher trick, but please:

*

*No soap

*Air dry (turn off the heat-dry feature)

*No "extra heat" (some dishwashers will double-heat the water you don't want that)

*Let it dry a WHILE.

A: I actually have salvaged computers from a fire. Isopropyl alcohol and cotton swabs will help you tremendously.
Edit:
Now that I have a second to post, here's some backstory. About 14 years ago a friend's apartment building caught fire while I was visiting. He lived on the second story and his hallway was blocked by a large pile of flaming debris. He and I jumped out a second-story window onto a mattress that the downstairs neighbors were nice enough to drag out onto the sidewalk. My friend was unhurt. I broke both bones in my lower left leg.
It was a small town, and people knew that I was "into computers", so I did a short but steady business of cleaning up machines that were in the various units around my friend's apartment. (I didn't have much else to do-- I was on break from college and unable to walk effectively.)
The worst machine was probably the computer hosting a dial-up bulletin board system that was in the adjacent unit to the fire and running during the fire. It inhaled quite a bit of smoke and was a sooty, tarry mess inside when I got started on it.

I always warn Customers about fires, and I often cite my own fire experience as reasons for off-site backup. A little over a year ago I received an email from a server computer that I'd installed as part of a subcontract job for a small local IT service provider. I'd configured my email address as a test recipient for hardware notifications and the provider or the Customer never bothered to put in their own addresses. I forwarded the fan failure message to the IT support firm with a note that they should remove my address from the hardware notification service.
The next day I learned that the Customer's building caught fire the prior night and that the email I received came, undoubtably, from a server computer that was inhaling smoke and experiencing fan failures-- running on its UPS (which was keeping the router at the end of the T1 line up) while the building burned up around it. They weren't really big enough to have an EPO attached to their fire suppression system-- we're talking two (2) server computers in a small rack in a closet kinda sized.
I won't make this post any longer, but here are some Cisco switches (and one no-name something-or-other at the top of the picture) post fire. (Click for a larger image)

(source: wellbury.com)

A: I salvaged some smoke damaged network equipment after a fire (2 rack mount HP switches), I took them apart, then used a cotton swab and engineering wipes, meths and soap+water on the case and isopryl alcohol on the boards where the build up was particularly bad, I vacuumed the fans.
Came up all ok afterwards, no sign of the fire except a slight smoky odour...


text:
Q: Cache NSData(with UIImages) Currently, I'm working on the client for the website. I have tonne of images that I need to load to my TableView. Here is what I'm currectly doing:
NSDictionary *propertyItems = [self.items objectAtIndex:indexPath.row];
    cell.fio.font = [UIFont boldSystemFontOfSize:17.0f];

    if([propertyItems objectForKey:@"online"] == [NSNumber numberWithInt:1])
        cell.fio.textColor = [UIColor colorWithRed:0.3 green:0.6 blue:0.3 alpha:1.0];

    dispatch_queue_t downloadPhotosQueue = dispatch_queue_create("downloadPhotosQeue", NULL);
    dispatch_async(downloadPhotosQueue, ^{
        NSData *photosData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.example.com/%@", [propertyItems objectForKey:@"photo_trumb"]]]];
        dispatch_async(dispatch_get_main_queue(), ^{
            cell.pic.image = [UIImage imageWithData:photosData];
        });

    });

    cell.fio.text = [propertyItems objectForKey:@"fio"];

I'm doing this in cellForRowAtIndexPath: method.
Everything is loading fast. But the problem is, when I'm scrolling my table down, and after again up, the images are reloading over and over again.
Question: Is there any way to easily cache my UIImages that I'm getting from the server? So if they are loaded once, they wouldn't reload over and over again, while I'm running the app. Maybe I'm doing something wrong?
Thanks in advance!

A: To load image from a website I use AFNetworking. It provides a class to load an image from an URL:

Start by adding #import "UIImageView+AFNetworking" to the top of a
  controller or a view implementation file. This category adds methods
  to UIImageView, like:
[imageView setImageWithURL:[NSURL URLWithString:@"…"]];

A: I strongly recommend AsyncImageView. I use it and it works like a charm. Just set the image url and it handles everything itself.
AsyncImageView *imageView = [[AsyncImageView alloc]init];
imageView.imageURL = [NSURL URLWithString:@"https://www.google.es/logos/classicplus.png"];

It caches the image in memory so it won't retrieve it from the server again. It will also release them when receiving a memory warning.

A: i recommend this library to accomplish what you want.
in cellForRowAtIndexPath:
    [cell.imageView setImageWithURL:
    [NSURL URLWithString:[NSString stringWithString:@"www.yourimagepath.path"]]
      placeholderImage:[UIImage imageNamed:@"no_image.jpg"]];

the library will cache the image for you. you can also set the setHolder of the image, so it wont look like a blank image while the images are downloading.

A: The problem is here :
NSData *photosData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.example.com/%@", [propertyItems objectForKey:@"photo_trumb"]]]];

dataWithContentsOfURL
It launch a request to the Url everytime the function is called (everytime you scrolled).
You need to load all the picture before cellForRowAtIndexPath.
Like in ViewDidLoad.
You can just store them in an array and display your picture's array in cellForRowAtIndexPath.
If it's really fast to load like you say : jsut load picture Once in CellForRowAtIndexPath. Store them in a mutableArray. And check if the picture already exist .


text:
Q: CSS3 HTML5 scrolling issue i'm making an interactive website for my local youth organisation! When i launch the website on my samsung galaxy S1 everything looks normal and it shows me the mobile website. But when i try to launch it on my Ipod 3G i cant scroll down(normal view, scroll down view). The website is: www.ksamerkem.be
i would like to avoid anything but css3 or html5. I'm also using mediaqueries.

A: Do you need to create the page using an iframe?
Your iPod cannot scroll down because your iFrame height is set to 100% which means there is no page scrolling required (all the scrolling is inside the iframe).
Cheers,
Mike


text:
Q: Fly way sbt not working when sbt.version in project/build.properties is 1.2.8 Fly way sbt not working when sbt.version in project/build.properties is 1.2.8, but works fine when sbt.version in project/build.properties is 0.13.17.
Please find below github link of simplified project to demonstrate the issue.
https://github.com/moglideveloper/FlyWaySbtCheck
Thanks.

A: That happens because the (old) flyway-sbt plugin you are using is build for SBT 0.13.x only.
Have a look at the new flyway-sbt site: https://github.com/flyway/flyway-sbt
Use addSbtPlugin("io.github.davidmweber" % "flyway-sbt" % "6.2.0") in your plugin.sbt if you want to use flyway with SBT 1.x.


text:
Q: Contradiction on jump conditions. Just a picture of my configuration.

The assumption here is $\epsilon_a,\epsilon_b,\epsilon_c$ are different from one another. Really the interest of this problem is to find the scalar potential $\phi$, such that $\nabla^2 \phi = 0$.
So now my question, about jump conditions,
Surface at $y=0$ has tangent $\vec{E}$ continous, thus
$\begin{align}
-\hat{x} \cdot \nabla \phi_a =  -\hat{x} \cdot \nabla \phi_b \\
-\hat{x} \cdot \nabla \phi_a =  -\hat{x} \cdot \nabla \phi_c \\
\end{align}$
However if we look at $x=0$ then normal $\vec{D}$ is continous thus
$\begin{align}
-\epsilon_b \hat{x} \cdot \nabla \phi_b =  - \epsilon_c \hat{x} \cdot \nabla \phi_c \\
\end{align}$
From our relation above this implies that $\epsilon_b=\epsilon_c$, which we made no such assumption. So this looks like a contradiction to me.
Can someone tell me where I have gone wrong?
Thank you!


text:
Q: Print array data 1 by 1 sleeping between each iteration? I am trying to make a small Python function that I want to simulate a loading piece. I have an array containing ['|', '\','--','/'] to use the slashes as the loading characters. I strive to re-create the msfconsole's loading page from Metasploit as shown in this image:

Here is the current code that I have:
def loadingSlash(time):
    import time
    chars = [
        '|',
        time.sleep(time),
        '/',
        time.sleep(time),
        '--',
        time.sleep(time),
        '\\'
    ]

    chars_clean = ''.join(chars)

pass

loadingSlash(.5)

Sorry if the code is way off, I don't usually have to deal with arrays :P


text:
Q: Is there any way to get a property's type in Objective-C?
Possible Duplicate:
How to detect a property return type in Objective-C

Is there any way to get a property's type in Objective-C?  I can access the property like this:
objc_property_t* properties = class_copyPropertyList(cl, &count);

And get the name like this:
property_getName(properties[i]);

What I need to do though is get the type.  Also, the value will be nil in most cases so I can't just get the value calling object_getClass().

A: Not in the sense that you seem to be asking — in Objective-C classes are typeless; when dealing with non-C types beyond 'it's a class' the type of properties isn't known at runtime. That's why if you do something silly like the following in a view controller:
[self setValue:@3 forKey:@"view"];

You'll see an exception raised when the controller attempts to send a view message to the NSNumber rather than by the key-value coding mechanisms because you tried to put something that isn't a view into in an inappropriate property.
Parsing property_getAttributes will allow you to go no further than distinguishing the various C literal types from an Objective-C object type.


text:
Q: How to return an array of nested items from every item of a parent object using AppSync? I am currently using Amplify with AppSync, and I want to grab Bs from every A item created, and populate them as an array of "items" as a result.
I searched up pipeline resolvers to deal with those, but got no luck since they are mostly based on "Grabbing all the Bs with A's ID=something", but what about ID=any.
I just want to follow the single-table architecture for DynamoDB.  In this sense, how am I able to grab all the Bs?
schema.graphql:
type A @model {
  id: String!
  theBs: [B]
}

type B {
  id: ID!
  A: String!
  name: String
}

type BConnection {
  items: [B]
  nextToken: String
}

type Query {
  getBs: BConnection
}

A: Assuming you are using the generated queries, it should be something like the following. You'll need to use the nextTokens to get everything.
That being said, this will perform a scan operation in DDB, which is slow and expensive.  I would recommend you read through this article about access patterns and see if there is a better way to organize your data.
query q {
      listA {
        nextToken
        items {
          theBs {
            nextToken
            items {
              id name
            }
          }
        }
      }
    }


text:
Q: Access the properties window for a particular network connection Given the name of a network connection, is there any way to bring up the properties page of only that network? The user should not be required to access ncpa.cpl, or navigate to the other network connections...
I can get a mini list of specific connection properties using netsh command, but a GUI and no shell access / batch file would be better.
If there is a single netsh command which gives me all the properties / value details for a specific connection, that might also come in handy.

A: Maybe WMI or powershell can help.
Have a look at this link


text:
Q: Can I get Windows to automatically save my screenshots? Various tips sites indicate that screenshots taken by pressing, for example, WIN-SHIFT-S or PrintScreen are supposed to show up in a Screenshots subdirectory of the Pictures directory in my home folder.  However, on my quite new installation of Windows 10, they don't get saved there and are just kept in the clipboard, so I have to paste them into e.g. Paint in order to save them somewhere.
Is there a way to tell Windows to automatically save them?  I'm used to MacOS behaviour where it saves screenshots using names containing timestamps.


text:
Q: Windows prompts "activex component can't create object" in vb6 I wrote an activex with name "monitor.exe" and another program named "main.exe" .Compiling the main.exe reference the monitor.exe,
the main exe could run on only computer in where it was implemented ,on other computers,the windows prompts an error message
"activex component can't create object".

The environment is win7 64bit , the language for development is vb6.

A: Monitor /registerserver
and
Monitor /unregisterserver
Or
Just Double Click the Monitor.exe in explorer.
Either way this should do it.


text:
Q: GL_INVALID_ENUM right after context initialization I am getting GL_INVALID_ENUM code when calling glGetError right after glew init has finished and before any other gl command was called.I am setting OpenGL 4.2 CORE ,forward compatible.Using GLFW for window/input and GLEW for gl context all this running on Windows 7 64bit.My graphic card is GeForce 550GT which has the latest drivers with OpenGL 4.2.Another strange thing is that I was using glDrawElements() which worked fine.But then I tried glDrawArrays(), which I needed for some specific task, and it didn't work at all.I double rechecked all the gl syntax ,buffer creations shaders etc.Nothing.I do get GL_INVALID_OPERATION when calling glDrawArrays() and I have no Idea why.All this work is a mini render engine but currently the pipeline is really simple so I can't understand what can be the problem.Here is how I initialize the context and window:
 void Engine::InitWithGLFW(){

    if(!glfwInit()){
        exit(EXIT_FAILURE);
    }
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 4);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
    glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT,GL_TRUE);
    glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwOpenWindowHint(GLFW_FSAA_SAMPLES,0);
    glfwDisable( GLFW_AUTO_POLL_EVENTS );

 #ifdef DEBUG
    glfwOpenWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
 #endif

    if(!glfwOpenWindow(_width,_height,8, 8, 8, 8, 24, 8,GLFW_WINDOW)){
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetWindowTitle("XDEngine V-1.0");
    InitGlew();

}

void  Engine::InitGlew(){
    glewExperimental=GL_TRUE;
    GLenum err = glewInit();

    if (GLEW_OK != err)
    {
        /* Problem: glewInit failed, something is seriously wrong. */
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));

    }

    fprintf(stdout, "Status: Using GLEW %s\n", glewGetString(GLEW_VERSION));

    glEnable(GL_MULTISAMPLE);
    glEnable (GL_BLEND);
    glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    glEnable(GL_DEPTH_TEST);
    glDepthMask(true);
    glDepthFunc(GL_LEQUAL);
    glDepthRange(0.0f, 1.0f);
    glEnable(GL_DEPTH_CLAMP);
    glEnable(GL_CULL_FACE);
    glCullFace(GL_BACK);

    glfwSetWindowSizeCallback(Reshape);
}

And this is the render loop for glDrawArrays():
     void Draw(){
            _material->Draw();///activate shader program
            glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 4, GL_FLOAT, GL_FALSE, 0, 0);

    glDrawArrays(GL_TRIANGLES, 0, 3);

    glDisableVertexAttribArray(0);

    glBindBuffer(GL_ARRAY_BUFFER, 0);
            _material->PostDraw();  //deactivate shader program

   }

As I said , all the buffers and shader programs are initialized ok.
UPDATE:
Ok , I found the answer for the first issue :
Seems like GL_INVALID_ENUM  may happen after GlewInit and it is not supposed to screw the rendering.So I am left with the second problem...
UPDATE1:
I found the workaround for GL_INVALID_ENUM  when calling glDrawArrays() with VBO.If I pack the VBO into VAO The error disappears and I get the rendering working.Does it mean that in forward compatible core profile we can't draw using VBO directly?Never seen anything related to it in the official docs.

A: Vertex array objects are not optional in the core profile. The GL_INVALID_ENUM error is probably coming from somewhere else; you should be getting GL_INVALID_OPERATION. Remember: OpenGL errors are buffered, so you have to keep fetching GL errors until you come back with GL_NO_ERROR.

glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT,GL_TRUE);

Please stop doing this. Forward compatibility is virtually meaningless in a core profile.


text:
Q: How to deserialize complex json strings? 1.My json string is like this following:
{
  "TagOptions": {
    "AResouceGroupId": "rg-aekzsbuw5climmq",
    "BResouceGroupId": "rg-aekztehix5f6eei",
    "CResouceGroupId": "rg-aek2t7m7dcjqvhq",
    "AClusterGroups": [ 0 ],
    "BClusterGroups": [ 0 ],
    "CClusterGroups": [ 46 ],
    "DClusterGroups": [ 153, 98, 23, 3, 4, 5, 8, 9, 10, 18, 28, 99, 101, 102, 104, 105, 201 ],
    "DataDeleiveryTeamProject": [
      {
        "GroupId": 14,
        "ProjectName": "XXX-A"
      },
      {
        "GroupId": 15,
        "ProjectName": "XXX-B"
      },
      {
        "GroupId": 46,
        "ProjectName": "XXX-C"
      },
      {
        "GroupId": 101,
        "ProjectName": "XXX-D"
      }
    ],
    "DataCenterTeamProject": [
      {
        "GroupId": 0,
        "ProjectName": "Empty"
      }
    ],
    "BazhuayuTeamProject": [
      {
        "GroupId": 153,
        "ProjectName": "XXX-OP1"
      },
      {
        "GroupId": 98,
        "ProjectName": "XXX-OP2"
      },
      {
        "GroupId": 23,
        "ProjectName": "XXX-OP3"
      },
      {
        "GroupId": 201,
        "ProjectName": "XXX-OP4"
      },
      {
        "GroupId": 3,
        "ProjectName": "XXX-OP5"
      },
      {
        "GroupId": 4,
        "ProjectName": "XXX-OP6"
      },
      {
        "GroupId": 8,
        "ProjectName": "XXX-OP7"
      },
      {
        "GroupId": 9,
        "ProjectName": "XXX-OP8"
      },
      {
        "GroupId": 10,
        "ProjectName": "XXX-OP9"
      },
      {
        "GroupId": 28,
        "ProjectName": "XXX-OP10"
      },
      {
        "GroupId": 102,
        "ProjectName": "XXX-OP11"
      },
      {
        "GroupId": 103,
        "ProjectName": "XXX-OP12"
      },
      {
        "GroupId": 104,
        "ProjectName": "XXX-OP13"
      },
      {
        "GroupId": 105,
        "ProjectName": "XXX-OP14"
      },
      {
        "GroupId": 18,
        "ProjectName": "XXX-OP15"
      },
      {
        "GroupId": 99,
        "ProjectName": "XXX-OP16"
      }
    ]
  }
}

2.Then,I try to deserialize the json string to a targete class, the target class is following:
using System.Collections.Generic;

namespace Tag
{
    public class TagOptions
    {
        public string AResouceGroupId { get; set; }

        public string BResouceGroupId { get; set; }

        public string CResouceGroupId { get; set; }

        public int[] AClusterGroups { get; set; }

        public int[] BClusterGroups { get; set; }

        public int[] CClusterGroups { get; set; }

        public int[] OctoparseClusterGroups { get; set; }

        public List<Project> ATeamProject { get; set; }

        public List<Project> BTeamProject { get; set; }

        public List<Project> CTeamProject { get; set; }
    }

    public class Project
    {
        public int GroupId { get; set; }

        public string ProjectName { get; set; }
    }
}

the method is like this, I use .netframework4.5 and Newtonsoft.Json
var s = jsonSerializer.Deserialize<CloudNodeTagOptions>(jsonStr);

but the result is null. Is there are some solution to solve the problem?

A: Your model is not in compliance with the JSON that you are trying to work with. Change your model to the sample shown below, then the Deserialize would work.

public class MyModel
{
    public Tagoptions TagOptions { get; set; }
}

public class Tagoptions
{
    public string AResouceGroupId { get; set; }
    public string BResouceGroupId { get; set; }
    public string CResouceGroupId { get; set; }
    public int[] AClusterGroups { get; set; }
    public int[] BClusterGroups { get; set; }
    public int[] CClusterGroups { get; set; }
    public int[] DClusterGroups { get; set; }
    public Project[] DataDeleiveryTeamProject { get; set; }
    public Project[] DataCenterTeamProject { get; set; }
    public Project[] BazhuayuTeamProject { get; set; }
}

public class Project
{
    public int GroupId { get; set; }
    public string ProjectName { get; set; }
}

Deserialize as below,
   var s = jsonSerializer.Deserialize<MyModel>(jsonStr);

A: There's
target object definition is not correct, JSON properties must match class properties and types.
Use the following classes:
public class TargetClass
{
    public TagOptions TagOptions { get; set; }
}

public class TagOptions
{
    public string AResouceGroupId { get; set; }

    public string BResouceGroupId { get; set; }

    public string CResouceGroupId { get; set; }

    public int[] AClusterGroups { get; set; }

    public int[] BClusterGroups { get; set; }

    [JsonProperty("DClusterGroups")]
    public int[] OctoparseClusterGroups { get; set; }

    [JsonProperty("DataDeleiveryTeamProject")]
    public List<Project> ATeamProject { get; set; }

    [JsonProperty("DataCenterTeamProject")]
    public List<Project> BTeamProject { get; set; }

    [JsonProperty("BazhuayuTeamProject")]
    public List<Project> CTeamProject { get; set; }
}

public class Project
{
    public int GroupId { get; set; }

    public string ProjectName { get; set; }
}

Note that I've added JsonProperty attribute to tell deserializer the correct property name.
Then you can use the following code to deserialize specifying the target class:
var jsonObj = JsonConvert.DeserializeObject<TargetClass>(jsonStr);


text:
Q: null value not detected. Bypass if condition java
As seen in the image, expiryTime is printed out as null as shown in the console. However, it bypass my if condition and i even printed out (expiryTime == null) and (expiryTime == "null"). However, it is giving me as false. Why is this possible?

A: Try this:
 if(expiryTime == null || expiryTime.isEmpty() || expiryTime.equals("null")) { /* do your stuffs here */ }


text:
Q: d3.js undefined in Meteor I am an experienced Meteor developer, as well as experienced with d3...but I cant get them to work together!
I have tried:
meteor add d3js:d3, which crashes and produces:

d3 is not defined

<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script> crashes and produces:

d3 is not defined

<script src="d3.min.js" charset="utf-8"></script>, with the source in the top level of my project directory, which crashes and produces:

TypeError: Cannot call method 'querySelector' of undefined

(the previous two both in the header of my index.html file)
all the while, d3 is still undefined in my browser.
Ive updated all of my packages and Meteor, as well as disabled every Meteor package, other than d3js:d3.
Looking for a solution (to my potential idiocy) or a work around.
EDIT
Adding:
pete:jsdom produces new error message:

/Users/Admin/.meteor/packages/pete_jsdom/.0.0.2.1uo6lix++os+web.browser+web.cordova/npm/node_modules/jsdom/lib/jsdom.js:3
  `jsdom 4.x onward only works on io.js or Node.js 4 or newer: https://github.co

A: It seems to me that you have a bug elsewhere. The following works perfectly fine on my machine (osx):
meteor create d3
cd d3
meteor add d3js:d3
meteor

Then, opening the browser I can do in the console:
> typeof(d3)
"object"

> _.keys(d3)
["version", "ascending", "descending", "min", "max", "extent", "sum", "mean", "quantile", "median", "variance", "deviation", "bisectLeft", "bisectRight", "bisect", "bisector", "shuffle", "permute", "pairs", "zip", "transpose", "keys", "values", "entries", "merge", "range", "map", "nest", "set", "behavior", "rebind", "dispatch", "event", "requote", "selection", "ns", "select", "selectAll", "mouse", "touch", "touches", "interpolateZoom", "color", "hsl", "hcl", "lab", "rgb", "functor", "xhr", "dsv", "csv", "tsv", "timer", "round", "formatPrefix", "time", "locale", "format", "geo", "geom", "interpolateRgb", "interpolateObject", "interpolateNumber", "interpolateString", "interpolate", "interpolators", "interpolateArray", "ease", "interpolateHcl", "interpolateHsl", "interpolateLab", "interpolateRound", "transform", "interpolateTransform", "layout", "random", "scale", "svg", "transition", "text", "json", "html", "xml"]

A: Not sure if you already included this, but try adding JSDOM.

As of d3#3.5.4, JSDOM is a development dependency. You will need to include it as a dependency.

A: Make sure you only reference d3 on the client. It is not available serverside, thus using it serverside will crash the application.

A: Use
meteor npm install d3

instead of
meteor add d3js:d3

It works for me


text:
Q: How to specify the include and lib path of pgm library when making PCA-SIFT code I am trying to make the PCA-SIFT code (pcasift-0.91nd.tar.gz) in this webpage: http://www.cs.cmu.edu/~yke/pcasift/. After running ./configure which is OK, the make command report that the C compiler can not find header pgm.h:

image.cc:18:22: fatal error: pgm.h: No such file or directory
        #include
                        ^ compilation terminated.

There is a webpage in internet which discussed this issue: http://ubuntuforums.org/showthread.php?t=1918422. A solution was stated at the end:

Apparently, the header files are in the directory /usr/include/pgm-5.1
  - the preferred way to get this into your include directories when compiling is to use pkgconfig. You will need to add something like
  pkg-config --cflags openpgm-5.1 at the end of your compilation
  command to get the right headers and add pkg-config --libs
  openpgm-5.1 to your linking command.

, but I cannot understand it. Specifically, what does "add pkg-config --cflags openpgm-5.1 at the end of your compilation command" mean? What should I do, to add pkg-config --cflags openpgm-5.1 literally or the results this command returns in terminal? And add to what file? The Makefile is generated by ./configure. Should I add to Makefile or ./configure? I have successfully install libpgm-dev and they are really in /usr/include/pgm-5.1. The command pkg-config --cflags openpgm-5.1 returns -I/usr/include/pgm-5.1 -I/usr/lib/x86_64-linux-gnu/pgm-5.1/include and command pkg-config --libs openpgm-5.1 returns -lpgm -lpthread -lm.
Since that thread was closed, I have to ask here. Hoping someone familiar with Linux compiling process could help me with this issue. Thanks a lot.

A: I solved the problem myself.
Everything in the ubuntuforums.org webpage mentioned in the original question is wrong; that's why I met with so many problems.
Wrong 1: It's wrong to install libpgm-dev using sudo apt-get install libpgm-dev.
We should download Netpbm, and run the following command after uncompression:
./configure      //type none on prompt if you don't have JPEG, TIFF, etc. libraries
make
sudo make package pkgdir=netpbmpkg
sudo ./installnetpbm
sudo rm -f -r /netpbmpkg/

Then Netpbm is installed on Ubuntu.
Wrong 2. The include path returned by pkg-config --cflags is wrong
By default, The include path shold be /usr/local/netpbm/include and the lib path is /usr/local/netpbm/lib.
Wrong 3. The linking option -lpgm returned by pkg-config --libs is wrong
The correct linking option should be -lnetpbm.
Following the right way, I can successfully compile the project in Netbeans (forget about command line make).


text:
Q: Set default JVM parameters to be used for applet launch I am trying to remote debug a Java applet, but I cannot seem to get the -agentlib:jdwp JVM argument to work. I have tried specifying it in the Java control panel for the particular JRE used, and I have tried setting it via the JNLP file used to launch the applet.
What is the correct way to set JVM parameters for applet launch? In particular, to debug remotely.

A: Looking at a similar SO question, I found the following answer...
Sometimes to debug some security related stuff the browser plugin environment is just too different from appletviewer. Here's what you can do to effectively debug applets in the browser:
1) Obtain debugging info for the binaries
Backup the .jar files from JRE_HOME/lib
(Download and) Install a JDK for the same version as your JRE.
Copy the .jar files from JDK_HOME/jre/lib to JRE_HOME/lib
The files inside the JDK were compiled with the debugging information included (source-code line number information, variable names, etc) and the JRE files don't have this information.
Without this you won't be able to meaningfully step into core class code in your debugger.
2) Enable debugging for the Java Plug-in
Go to the Java Control Panel / Java / Java Runtime Settings / View / User / Runtime Parameters
And add the options to enable debugging. Something like this:
-Djava.compiler=NONE -Xnoagent -Xdebug -Xrunjdwp:transport=dt_socket,address=2502,server=y,suspend=n

The interesting options are the port (using 2502 here, you can use pretty much any free port, just write it down for later) and the suspend - if you need to debug the applet startup, classloading, etc, set this to "y". That way when you access an applet page, the browser will appear to freeze as the JVM immediately gets suspended waiting for a debugger to connect.
3) Use your favorite IDE to Remotely debug the Java Plug-in
In Eclipse, for instance, choose Run / Debug Configurations ... / Remote Java Application
Click on the "New" button.
Make sure connection type is "Socket Attach", choose localhost as the host if your browser is local, and the port you chose earlier (2502 in the example).
You might have to inlude the src.zip in your JDK on the sources tab to have the Java core class sources available.
Save the configuration, and once your browser is running the plug-in (with the JVM suspended or not) run the remote debugger to connect to the plug-in JVM, with a project containing your applet sources open.

A: This issue has been fixed for 7_u40 which is available for early access on java.net. Otherwise the Oracle bug says this is fixed for Java 8!
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=8016005
http://jdk7.java.net/download.html

A: Do you absolutely need to run the applet within a browser? Because the normal way to debug applets is with the appletviewer.

According to the JPDA docs (which I'm assuming you've read, based on the things you've already tried), you should be able to specify the agent in the Java Control Panel. I've never tried this, and the doc claims that you can't interrupt the applet launch this way (just attach to a running applet), so all I can do is wish you luck.

A: I have a workaround. It seems like it's JRE7_u21 that doesn't open a port, doesn't suspend, and jconsole VM summary doesn't show the VM parameters configured in the Java control panel.
I downgraded to JRE7_u17 and everything works. My VM arguments string in the Java control panel is:
 -agentlib:jdwp=transport=dt_socket,address=8889,server=y,suspend=y,quiet=n,timeout=10000

it seems to work without
 -Djava.compiler=NONE

Nothing else has worked, not even replacing the lib folder as previously suggested. I even tried some registry hacking (changing paths).

A: You can use JAVA_TOOL_OPTIONS environment variable to pass the default JVM params. It will pass the params to your applet which is running in the browser (and not only to the applet). This approach will work even on java 7u21 and higher.


text:
Q: Approximating integration by samples of a probability distribution Let $f(x)$ be a probability density function (PDF) and $x_i\sim f(x), i=1,\ldots, n$ be $n$ i.i.d samples of $f(x)$. Then we may write:
$$E(X) = \int x f(x) dx\approx\frac{1}{n}\sum_{i=1}^n x_i$$
In the above equation we are approximating an integration using samples of a PDF.

Is it also possible to approximate the following integral using samples of $f(x)$ (i.e. $x_1,\ldots,x_n$)?
$$\int x f'(x) dx\approx \ ?$$
where $f'(x)=\frac{d}{dx}f(x)$.

Edit:
As pointed by Kavi Rama Murthy the above integral equals $-1$ if the integration is over the entire domain of $f(x)$. What happens if we restrict the integration domain?
$$\int_a^b x f(x) dx\approx \frac{1}{n}\sum_{i=1}^n x_i \times \mathbb{I}(a\leq x_i \leq b)$$
where $\mathbb{I}$ is the indicator function.
$$\int_a^b x f'(x)dx =x f(x)|_a^b - \int_a^b f(x) dx\approx \ ?$$

A: For sufficiently nice density functions $f$ we have   $\int x f'(x)dx=-1$: Integrate by parts to get $xf(x)|_{-\infty}^{\infty} -\int f(x)dx=0-1=-1$.


text:
Q: 'Channels first' training accuracy very low compared to 'channels last' My issue:
I am trying to train a semantic segmentation model in tf.keras, in fact it works very well when I am using channels_last (WHC) mode (it reaches 96%+ val acc). I wanted to train it in channels_first (CHW) mode so the weights are compatible with TensorRT. When I do this, the ~80% training accuracy in the first few epochs dips down to around 0.020% and stays there permanently.
It is useful to know that the base of my model is a tf.keras.applications.MobileNet() model with the pre-trained 'imagenet' weights. (Model architecture at the bottom.)
The transformation process:
I used the guidelines provided and I change only a few things here:

*

*Set tf.keras.backend.set_image_data_format() to 'channels_first'.

*I change the channel order in the input tensor from: input_tensor=Input(shape=(376, 672, 3))  to: input_tensor=Input(shape=(3, 376, 672))

*In my image preprocessing (using tf.data.Dataset), i use tf.transpose(img, perm=[2, 0, 1]) on both my input image and one-hot encoded mask to change the channel orders. I checked this with equality assertion to make sure its correct and it seems to be fine.

When I change these the training starts fine but as I said the training accuracy goes down to almost zero. When I revert back everything's fine again.
Possible leads:
What am I doing wrong or what could be the problematic part here? My suspicions are around these questions:

*

*Are the pre-trained imageNet weights changed to the 'channels_first' order also when I set the backend? Is this something I should consider at all?

*Could it be that the tf.transpose() function messes up the mask's one-hot encoding? (I have 3 classes represented by 3 colors: lane, opposing lane, background)
Maybe I am not seeing something obvious. I can provide further code and answers as needed.
EDIT:
08/17: This is still an ongoing issue, I have tried several things:

*

*I checked if the image and the mask is correct after the transpose with numpy assertion, seems correct.

*I suspected that the loss function calculates on the wrong axis, so I customized the loss function for the first axis (where the channels are). Here it is:

def ReverseAxisLoss(y_true, y_pred):
    return K.categorical_crossentropy(y_true, y_pred, from_logits=True, axis=1)

*

*My main suspicion is that the 'channels first' backend setting does nothing to transpose the pretrained 'imagenet' weights for the mobilenet part. Is there an updated way for TF2.x / Keras to transpose the pre-trained weights into CHW format?

Here is the architecture that I use (the skipNet() is the head network and the mobilenet is the base, and it is connected in the create_model() function)
def skipNet(encoder_output, feed1, feed2, classes):
    # random initializer and regularizer
    stddev = 0.01
    init = RandomNormal(stddev=stddev)

    weight_decay = 1e-3
    reg = l2(weight_decay)

    score_feed2 = Conv2D(kernel_size=(1, 1), filters=classes, padding="SAME",
                kernel_initializer=init, kernel_regularizer=reg)(feed2)
    score_feed2_bn = BatchNormalization()(score_feed2)
    score_feed1 = Conv2D(kernel_size=(1, 1), filters=classes, padding="SAME",
                kernel_initializer=init, kernel_regularizer=reg)(feed1)
    score_feed1_bn = BatchNormalization()(score_feed1)

    upscore2 = Conv2DTranspose(kernel_size=(4, 4), filters=classes, strides=(2, 2),
                               padding="SAME", kernel_initializer=init,
                               kernel_regularizer=reg)(encoder_output)
    height_pad1 = ZeroPadding2D(padding=((1,0),(0,0)))(upscore2)
    upscore2_bn = BatchNormalization()(height_pad1)

    fuse_feed1 = add([score_feed1_bn, upscore2_bn])

    upscore4 = Conv2DTranspose(kernel_size=(4, 4), filters=classes, strides=(2, 2),
                               padding="SAME", kernel_initializer=init,
                               kernel_regularizer=reg)(fuse_feed1)
    height_pad2 = ZeroPadding2D(padding=((0,1),(0,0)))(upscore4)
    upscore4_bn = BatchNormalization()(height_pad2)

    fuse_feed2 = add([score_feed2_bn, upscore4_bn])

    upscore8 = Conv2DTranspose(kernel_size=(16, 16), filters=classes, strides=(8, 8),
                               padding="SAME", kernel_initializer=init,
                               kernel_regularizer=reg, activation="softmax")(fuse_feed2)

    return upscore8

def create_model(classes):

    base_model = tf.keras.applications.MobileNet(input_tensor=Input(shape=IMG_SHAPE),
                                                 include_top=False,
                                                 weights='imagenet')

    conv4_2_output = base_model.get_layer(index=43).output
    conv3_2_output = base_model.get_layer(index=30).output
    conv_score_output = base_model.output

    head_model = skipNet(conv_score_output, conv4_2_output, conv3_2_output, classes)

    for layer in base_model.layers:
        layer.trainable = False

    model = Model(inputs=base_model.input, outputs=head_model)

    return model


text:
Q: Having an Object Rotate and Look at the center of the screen (Third person game) So I am trying to get my character to point its cannon to the center of the screen so it can shoot accurately. This game is going to be a third person game so keep that in mind. I'm fairly new to coding so if you can help it would be awesome!
void Update()
{

    //Ray mouseRay = Camera.main.ScreenPointToRay(Input.mousePosition); (not sure if I should use this)
    float midPoint = (transform.position - Camera.main.transform.position).magnitude * 0.5f;

    transform.LookAt(midPoint);
}

A: You can try
Vector3 screenPos = new Vector2(Screen.width /2.0f, Screen.height/2.0f,0);

Vector3 worldPos = ScreenToWorldPoint(screenPos);

will get the center of the screen as a point in the world, however it will be on the veiw plane right next to the camera
you could get something to look at this point with
object.transform.LookAt(worldPos);

however if you want it to point at whatever the camera is looking at,  you can raycast along this line like
Raycast(worldPos, Camera.main.transform.forward);

and then look at whatever that hits


text:
Q: What's a word to refer to "school homework" and "take-home work"? So, we have homework that they give you in high school and university. Then we have take-home work which they give your in an office or any workplace.
Is there a word that you can use to refer to these two types of home assignments?

A: According to the Merriam Webster dictionary seems that you can use just "homework" for both
Definition of homework

*

*piecework done at home for pay

*an assignment given to a student to be completed outside the regular class period

*preparatory reading or research (as for a discussion or a debate)


text:
Q: How to remove padding around Android CheckBox I need to put check to the right hand top corner of my imageview. But when I do this I noticed a default margin around my checkbox. Is there a way to remove this??
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <FrameLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true" >

        <ImageView
            android:id="@+id/thumbImage"
            android:layout_width="100dp"
            android:layout_height="132dp"
            android:layout_gravity="center" />
    </FrameLayout>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:background="#ff0000"
        android:gravity="center" >

        <CheckBox
            android:id="@+id/itemCheckBox"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:layout_gravity="center"
            android:button="@drawable/checkbox_background"
            android:paddingLeft="0dp"
            android:paddingTop="0dp" />

    </LinearLayout>

</RelativeLayout>

A: This works for me in Constraint Layout. I hope it will work for another layout.
<androidx.appcompat.widget.AppCompatCheckBox
                ...
                android:translationX="-5dp"
                 />

A: To remove radio button default margins or padding in android
if you using xml
android:minWidth="0dp"
android:minHeight="0dp"

if using programmatically
 radiobtn.setMinimumHeight(0);
 radiobtn.setMinimumWidth(0);

A: You could use a negative margin.
android:layout_marginTop = "-5dp"
android:layout_marginRight = "-5dp"

A: If you look at the source code for the CompoundButton class that is extended by the Checkbox class at the onDraw() method, the padding depends from the gravity
  @Override
    protected void onDraw(Canvas canvas) {
        ...

            final int top;
            switch (verticalGravity) {
                case Gravity.BOTTOM:
                    top = getHeight() - drawableHeight;
                    break;
                case Gravity.CENTER_VERTICAL:
                    top = (getHeight() - drawableHeight) / 2;
                    break;
                default:
                    top = 0;
            }
       ...
    }

So what you can do is set the xml value for the attribute gravity to
android:gravity="top|start"
But this can be used only if you don't want to use text with your checkbox, since the gravity is used to center the text.

A: There's now a better way of doing this:
android:minWidth="0dp"
android:minHeight="0dp"

A: Thanks to @VladislavShcherbakov comment, it is:
android:paddingLeft="-5dp"
android:layout_marginStart="-5dp"
android:layout_marginLeft="-5dp"
// android:translationX="-5dp"

A: Why to complicate with a negative padding and all. Use the simple and straight way, give padding to the FrameLayout instead tof the top most Relative layout that would do the trick. As you have only the CheckBox in the second layout there is no need to give padding for it.
Please do let me know if you face any problems or have any further doubts


text:
Q: Some approaches to distribute an iPhone application to run in a specific location My boss wants to distribute the application for a specific client, whose number of employees is around 500. The application uses webservices and the UDID of the device to restrict the other users from accessing the software. We are not a big company that can register for the enterprise program, and especially my boss does not want other users to download the software because it may lead to overload to the server, even though we use the udid to restrict the user but the first webservice request is still needed to verify if the iPhone/iPod is granted to use the system.
Putting the software into the appstore with free price leads to many unwanted things: writing comments to blame the software that he can not use it (in fact, other users do not suppose to use it, only the client of the company is the one that has the right to use the software) or even we can think of the software be confidential and should not be exposed to other users.
Putting the software into the appstore with the maximum price is not a good approach because then our client has to pay money to download the program. It's not necessary.
Distributing the software in the ad-hoc mode requires us to reinstall the software every time the provisioning profile is expired, even worse, the installation limit is only 100 devices.
So, what are the approaches to distribute this kind of software? Any thoughts on this topic?

A: Suck it up and pay for the enterprise developer program.  Its only $299/year. Or look into jailbreaking every employee's device and installing your app through alternate means.

A: This is our solution and it works on the appstore:
- Distribute your app as usual on the appstore
- In your app, limit it to a certain devices by letting it query a service on your own managed server.
- Authentication is necessary if you want to differentiate between users.


text:
Q: Converting from parametric equation of cube face to general equation I am trying to convert the vector equation:
$\begin{bmatrix}x\\y\\z\end{bmatrix} =
\begin{bmatrix}0\\0\\0\end{bmatrix} +
s\begin{bmatrix}1\\0\\0\end{bmatrix} +
t\begin{bmatrix}0\\0\\1\end{bmatrix},
s,t \in \mathbb{R}
$
which represents one of the faces of a unit cube in $\mathbb{R}^3$, to general form.
I know that the general form is $x=0$, and parametric equations:
$x = s\\y = 0\\z = t$
But am confused how I might go straight to the general form from the parametric equations.
Thanks.


text:
Q: AFNetworking memory allocation keeps rising I'm making an app which will fetch pictures resources and text from web service. I pick the great AFNetworking's UIImageView+AFNetworking category to deal with the image downloading stuff.
However, I'm facing a memory problem. I used Allocation tool of the Instruments, finding each time I load more images, there will always be a growth of memory allocation, 1-2 MB in size. I tracked down to the source code, it turned out that it lies in AFNetworking's code.
The exact line of code is:
- (void)connectionDidFinishLoading:(NSURLConnection *)__unused connection {
    self.responseData = [self.outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];

    [self.outputStream close];

    [self finish];

    self.connection = nil;
}

This will occupy 99.6% of the memory allocation.
I user ARC in the project, display the UIImageViews in a UITableView and configure the cell like the following code:
[self.imageView setImageWithURLRequest:request
                          placeholderImage:nil
                                   success:successBlock
                                   failure:failBlock];

Can any one offer some idea about the memory issue? It's really a headache cuz once the memory is allocated, they will never be cleared even if I cleared the whole image view. After a little while, my app will occupy more than 100MB from the Real Memory Usage window of Instruments.
Any help will be greatly appreciated!! Thanks in advance!!

A: It is possible to clear the cache of images. There is a discussion about it on github here:
AFNetworking Image Cache
That may or may not solve your problem. I would imagine clearing the cache on a regular basis should keep your memory usage down though.


text:
Q: The fastest way to check if two lists contain the same object I've been dealing with a problem lately where i have to wait for hours to get the right answer.
The problem is this:
I have two different lists that have thousands of elements.
I want to check if both lists contain the same element and if soo i want to add that element in a separate list.
When i try with a small amount of elements in the lists, the program works perfectly fine but when i try with more elements, i have to wait for hours to get the right answer.
        List<Point> res1 = new LinkedList<>();
        for (Point value : w1) {
            System.out.println("Thread 1");
            Point a = value;
            for (Point point : w2) {
                if (a.equals(point)) {
                    System.out.println(Math.abs(a.x) + Math.abs(a.y));
                    res1.add(a);
                }

            }
        }

What is the fastest way to do this kind of comparing?
Thanks in advance

A: If you use HashSet you get a very efficient contains method free of charge:
        HashSet hsw1 = new HashSet(w1); // turn first into a hashset
        List<Point> res1 = new LinkedList<>(w2); // load the second into new list
        res1.retainall(hsw1); // retain only values that are in the first as well


text:
Q: is there any scriptella jruby script sample/example? I am new scriptella user.
Is there any sample or tutorial to use jruby
as scripting language?
Thanks and Regards,
Manish
== updated after ejboy's suggesstions ==

*

*Copied jruby.jar (1.7.4) in lib.

*However scriptella failed with following exception.

Jun 14, 2013 9:31:36 AM  Script /bigdisk/work/cougar/code/leopard-monitor/analytics/kpoint_usage/scriptella/scripts/jruby_sample.xml execution failed.
/etl/script[1] failed: keySet
Location: /etl/script[1]
Jun 14, 2013 9:31:36 AM <SEVERE> Scriptella bug report. Submit to issue tracker.
Scriptella version: 1.1
Exception:
scriptella.execution.EtlExecutorException: /etl/script[1] failed: keySet Location: /etl/script[1]
    at scriptella.execution.EtlExecutor.execute(EtlExecutor.java:190)
    at scriptella.tools.launcher.EtlLauncher.execute(EtlLauncher.java:276)
    at scriptella.tools.launcher.EtlLauncher.launch(EtlLauncher.java:193)
    at scriptella.tools.launcher.EtlLauncher.main(EtlLauncher.java:321)
Caused by: scriptella.core.ExceptionInterceptor$ExecutionException: /etl/script[1] failed: keySet
    at scriptella.core.ExceptionInterceptor.execute(ExceptionInterceptor.java:44)
    at scriptella.core.Session.execute(Session.java:103)
    at scriptella.execution.EtlExecutor.execute(EtlExecutor.java:227)
    at scriptella.execution.EtlExecutor.execute(EtlExecutor.java:183)
    ... 3 more

Following is my xml file.
<!DOCTYPE etl SYSTEM "http://scriptella.javaforge.com/dtd/etl.dtd">
<etl>
  <description>
    use jruby as scripting language.
  </description>
  <connection id="script-jruby" driver="script" url="out/test-out.csv"> <!-- classpath="path/to/jar:path/to/jar2"> -->
     language=jruby
  </connection>
  <script connection-id="script-jruby">
    puts "Hello world - using jruby"
  </script>
</etl>

A: Try setting the language property to jruby and make sure the required jars are available on classpath. You can either copy them to <scriptella_home>/lib directory or include in the connection declaration:
<connection id="script" driver="script" classpath="path/to/jar:path/to/jar2">
   language=jruby
</connection>


text:
Q: Выровнять блок по вертикали + не работает скроллбар Народ нужна помощь.
Снизу ссылка на jsfiddle, там код сайта.
Проблема такая: посередине есть блок с сообщениями. Они уже выровняны по низу родительского блока, но скроллбар не работает. Возможно я где-то ошибся ранее.
Подскажите кто знает, как сделать так, чтобы сообщения были снизу центрального блока(как и есть), но чтобы работал скроллбар, если браузер сузить по вертикали.
https://jsfiddle.net/xmnz3z5c/

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin sed metus felis. Mauris consequat aliquet sollicitudin.

   erat-pellentesque-dignissim.pdf

Victor Briggs
08/08/14 06:15 PM

Suspendisse potenti. Nulla facilisi. Vestibulum libero ligula, vestibulum vel velit sit amet, imperdiet laoreet quam. Fusce blandit, metus quis gravida scelerisque, ante ligula bibendum risus, vitae malesuada dolor quam et diam.

Me
08/08/14 06:15 PM

Duis porttitor, massa eget varius faucibus, nunc libero pulvinar justo, at adipiscing purus arcu eu lectus. Cras neque tortor, varius quis ullamcorper sit amet, congue id erat. Duis tincidunt orci sed fringilla bibendum. Nullam vel consectetur odio, ac posuere erat.


text:
Q: How to get a particular item from Response Object havig 4 Items? I am having Respone object which reurn 4 values.I need to get particular one detail alone.
 ResponseDTO responseDto = new ResponseDTO();

responseDto.ResponseObject = new
{
    ShippingPackageInfoList = shippingPacakgeInfo,
    IsDifferentLotNumber = diffLotNumber,
    IsDifferentLocation = diffLocation,
    IsPartMappedToTote = partTote != null
};

In this, I need to get shippingpackageInfo alone which is List and I need to iterate to access the values.
The ResponseDTO class Contains :
  public class ResponseDTO
{
    public bool IsSuccess { get; set; }

    public string UserMessage { get; set; }

    public string TechMessage { get; set; }

    public string Status { get; set; }

    public object ResponseObject { get; set; }

    public bool RestrictApproveAction { get; set; }

    public bool IsAlreadyExists { get; set; }
}

I tried following method ,it returns null
IList<ShippingPackageInfoDTO> generatedShippingPackageList = generatedData as IList<ShippingPackageInfoDTO>;
IList generatedShippingPackageList = (IList)generatedData;
IEnumerable e = generatedData as IEnumerable;
IEnumerable<ShippingPackageInfoDTO> generatedShippingPackageList = e.OfType<ShippingPackageInfoDTO>();

A: You are setting the ResponseObject property to an anonymous object so this should work provided that shippingPacakgeInfo in your first code snippet is indeed an IList<ShippingPackageInfoDTO>:
dynamic responseObject = generatedData.ResponseObject;
IList<ShippingPackageInfoDTO> generatedShippingPackageList =
    responseObject.ShippingPackageInfoList as IList<ShippingPackageInfoDTO>;


text:
Q: Develop custom admin panel with front user in laravel I want to implement a custom admin panel, which can add merchant and view reports. admin have different URL to login into the admin panel.
the merchant as frontend user has a login to their account and manage payment send an email etc. merchant can using the application on a subdomain.
can anyone help me to implement the solution?

A: If you want to add separate admin panel in to your application, first of all you need to create different routes, views and controllers for admins. Then implement your logic that differentiate merchant from admin. You can start from there.


text:
Q: Combines chmod and running script in one line not working in Bash Having the following Bash sequence that creates a file, changes file permissions (to be executable) and run the script I want to do in one line the last 2 commands:
$ touch dotfiles.sh
$ chmod +x ./dotfiles.sh
$ ./dotfiles

Solution 1
I thought a possible solution is to use the && operator. So ./dotfiles will be executed only if chmod succeeds.
But this solution is not working and bash says the file does not exists. Any idea?.
(not working solution)
Note: chmod returns 0 if success. So the && is done, but fails in the second part when ./dotfiles.sh:
$ chmod +x ./dotfiles.sh && ./dotfiles.sh
-bash: ./dotfiles.sh: No such file or directory
$

Update: Solution 1 is correct. See my answer below to full explanation.

A: Update:
Solution 1 proposed was in fact working. After reading user's comments I figured out that the problem may be with the content of dotfiles.sh and not with the bash command I was asking for.
What problem I had?
In the dotfile.sh file, I included #!/usr/bin/env bash instead of #!/bin/bash. So when executing chmod +x ./dotfiles.sh && ./dotfiles.sh the "No such file or directory" problem, was referring to the ./dotfiles.sh content and not with the "command" itself (that I thought).

A: This should work.
chmod +x dotfiles.sh; [ $? -eq 0 ] && ./dotfiles.sh


text:
Q: Blender Python `bpy` `__init__.py`, apparently importing from a non-existent module `_bpy` I'm using Mac OS X with PyCharm and Python 3.5.1 and Blender 2.77.
I'm using Blender with Python scripts. I understand that in order to run Python scripts that use Blender (i.e. that imports bpy), I need to run it from command line using blender -b -P /path/to/my_python_script.py (although I don't really know why). That's all fine and it works, but I wish I could just run it from inside Python, because I use these scripts with other non-Blender Python code and I like to use PyCharm to debug and to do pretty much everything. I understand that I can't just run the Blender Python script from PyCharm, but I thought I'd try anyway. I took care to ensure that PyCharm can see the bpy module by editing the "Project Structure" settings in "Preferences" to include the parent directory in which the bpy module lives, which on my machine is  /Applications/blender.app/Contents/Resources/2.77/scripts/modules. However, when I try to run the script, it gives ImportError: No module named '_bpy'. I followed the source of the error and the culprit was a line in the __init__.py file in the bpy module (whose location on my machine is /Applications/blender.app/Contents/Resources/2.77/scripts/modules/bpy/__init__.py); the line is:
from _bpy import types, props, app, data, context

So I tried to search for the module _bpy on my machine, and couldn't find it anywhere. So it seems to be importing things from a module that doesn't exist. However, I know that my script works because I've successfully run it in Blender.
So my question is, what witchcraft is going on with the mysterious _bpy module, that neither I nor PyCharm can find, but that the Blender app doesn't have a problem with? I looking to gain a general understanding of what might be going on here, so educated guesses (as well as precise answers obviously) are welcome.

A: Did you happen to notice the line before from _bpy import... it says # internal blender C module which should be the giveaway.
The witchcraft that makes this work is that the blender binary includes _bpy as a binary python module, blender makes this module accessible within the python interpreter included with blender, it does this during the initialization of the python interpreter. The normal blender binary cannot be imported into a python interpreter outside of blender without being built into a Python module (see below).
To figure out how to do it you can start with the Python docs on Python's c-api. You may also want to look through blender's source code within source/blender/python where you will find the C files used to build blender's main C based modules such as bpy, bgl, bmesh, mathutils.
Also see this answer which has a link to info on building blender as a Python module so it can be imported (without the gui) into an external Python interpreter. If you search for pycharm at blender.stackexchange.com you will find several answers about using bpy in pycharm and eclipse, including ways to have blender running as an external interpreter for debugging.


text:
Q: AngularJS: Get attribute value from custom tags i am a newbie of AngularJS don't know what i am doing wrong here is my code. Basically i am trying to get attribute value of post-id from my index.html and print it in console from my controller.
In my index.html:
<post-creator post-id="5" category="1"></post-creator>

post-creator.component.js:
function controller($http) {
        var model = this;

        model.$onInit = function () {
            console.log("id again:" + model.postId);
        }
module.component("postCreator", {
        templateUrl: "components/post-creator/post-creator.template.html",
        bindings: {
            value: "<"
        },
        controllerAs: "model",
        controller: ["$http", controller]
    });

A: Since in the HTML, you are passing post-id="..." category="...", they should be part of bindings of your component and not value. Like this:
bindings: {
    postId: "<",
    category: "<"
}

Here's a sample working example:

var module = angular.module("myApp", [])

function controller($http) {
  var model = this;

  model.$onInit = function() {
    console.log("id again:" + model.postId);
  }
}

module.component("postCreator", {
  template: "
post creator
",
  bindings: {
    postId: "<",
    category: "<"
  },
  controllerAs: "model",
  controller: ["$http", controller]
});

  <post-creator post-id="5" category="1"></post-creator>


text:
Q: Call UserManager From Data Layer I am using identity 1.0 for my application and want to move UserManager to Data layer such as the following code (I've Customized Userstore to AppUserStore):
public class UserRepository
{
    public UserManager<ApplicationUser, string> AppUserManager()
     {
        using (var db=new DataContext())
       {
         var Appstore = new AppUserStore<ApplicationUser>(db);
         var userManager = new UserManager<ApplicationUser, string>(Appstore);
         return userManager;
       }
     }
}

and then in business Layer i want to use this userManager to create a user:
 public bool Create(CreateUserViewModel quser)
    {
     var repository = new UserRepository();
     var userManager = repository.AppUserManager();
     var result = userManager.Create(quser);
     return result.IsCompleted
    {

but it threw an exception that DataContext is disposed.
how can i Move userManager to Data Layer and fix this problem? i always use this pattern for my Apps.


text:
Q: PySpark: hash() ResultIterable differs before and after collect() I'm attempting to implement locality-sensitive hashing in PySpark (based on the spark-hash project, written in Scala). The hashing step is generating some strange behavior.
In a step where I take the hash of the list of minhashes generated for each vector, the output of this appears to depend greatly on whether I'm hashing in parallel (PySpark REPL) or in sequence (after collect). For instance, if I generate the hashes this way (the call to groupByKey should give me elements that hash to the same band):
bands = model.signatures.groupByKey().collect()
hashes = [hash(band[1]) for band in bands]

I get a list that resembles what you would expect; namely, lots of unique numbers:
278023609,
278023657,
278023621,
278023449,
278023593,
278023589,
278023529,
278023637,
278023673,
278023429,
278023441,
...

However, I take that exact same data but hash it using the Spark constructs:
hashes = model.signatures.groupByKey().map(lambda x: hash(x[1])).collect()

Now I get a list that looks like this:
286120785,
286120785,
286120785,
286120785,
286120785,
286120785,
286120785,
286120785,
...

Same hash repeating over and over. If, however, I use the same Spark constructs, but at the last second cast the ResultIterable to a frozenset:
hashes = model.signatures.groupByKey().map(lambda x: hash(frozenset(x[1].data))).collect()

Now I get a list of unique hashes again. Any idea what's going on? Is there something strange about how hashing works on ResultIterable objects during Spark execution?


text:
Q: can somebody show me an example of using pysimplegui not in a loop - maybe as a definition setup that I can update manually I am looking for a way to use a PYSimpleGUI progress bar... without a loop
I have looked for several days on the internet with no luck to find an example.
seems everybody does their example with a loop, or on a timer.
I'd like to do something more like a definition that I Can call to to update
I dont know what to change to make it a manually updated item...
I want to be able to tell it i=0 at teh beginning of my script
and periodically place update marks thru the script(i=i+4)
so that I can update it as each Major Step in my script is done
This is the PySimpleGUI script, plus some lines showing what I want to do
This currently auto iterates...and I do not know how to change it
I'm just trying to learn and cant find any examples online to do what I want to do.
import PySimpleGUI as sg
import time
from time import sleep

import PySimpleGUI as sg

def prog():

    layout = [[sg.Text('Completed Tasks')],
          [sg.ProgressBar(100, orientation='h', size=(50, 20), key='progressbar')],
          [sg.Cancel()]]

    window = sg.Window('Progress').Layout(layout)
    progress_bar = window.FindElement('progressbar')

    for i in range(100):
        event, values = window.Read(timeout=0)
        progress_bar.UpdateBar(i + 4)
    time.sleep(2)
    window.Close()

prog()

time.sleep(2)
#______________________________________________________________

#I'd like to be able to do this

#i=0 at this point
prog()
#do Scripty Stuff

#Update Progress Bar Manually
#i=4 at this point

#do more scriptic writings

#Update Progress bar Manually
#i=8 at this point

#and so forth and so on until I reach 100

A: Figured it out
just leave everything as a single line, not a definition
heres an example to help others
I just did real numbers in the Update bar section
but you can use variables (i=0) and then update it in the script with an i=i+1
and then use i as your number in the update bar function
i=0
progress_bar.UpdateBar(i, 5)
#i returns a value of 0

i=i+1
progress_bar.UpdateBar(i, 5)
#i now returns a vlaue of 1

#repeat until you reach your maximum value

#this Script will create a Progress Bar
#The Progress will be Manually Updated using the format listed below
#progress_bar.UpdateBar(Value of Bar, Maximum Bar Value)
#the Window uses a .Finalize Function to make the window Persistent

#Import the PySimpleGUI Library
import PySimpleGUI as sg
#Import the Time Library for use in this script
import time

#this is for the Layout Design of the Window
layout = [[sg.Text('Custom Text')],
              [sg.ProgressBar(1, orientation='h', size=(20, 20), key='progress')],
          ]
#This Creates the Physical Window
window = sg.Window('Window Title', layout).Finalize()
progress_bar = window.FindElement('progress')

#This Updates the Window
#progress_bar.UpdateBar(Current Value to show, Maximum Value to show)
progress_bar.UpdateBar(0, 5)
#adding time.sleep(length in Seconds) has been used to Simulate adding your script in between Bar Updates
time.sleep(.5)

progress_bar.UpdateBar(1, 5)
time.sleep(.5)

progress_bar.UpdateBar(2, 5)
time.sleep(.5)

progress_bar.UpdateBar(3, 5)
time.sleep(.5)

progress_bar.UpdateBar(4, 5)
time.sleep(.5)

progress_bar.UpdateBar(5, 5)
time.sleep(.5)
#I paused for 3 seconds at the end to give you time to see it has completed before closing the window
time.sleep(3)

#This will Close The Window
window.Close()

A: Just a quick note for everyone that is finding this answer in 2021 or later:
The window.FindElement() is deprecated, one uses window.find_element() nowadays :)
@soundtechscott: Thanks for your answer, I also encountered that issue today and your solution worked out for me.


text:
Q: rad date picker should load start date of current month automatically, when Page loads in asp.net current month
current year
and start date(1 to be constant) in telerik rad date picker
Am working to get date 1= year,6 months back, 1
date2=year, current month, 1
i can get current date as below
    startdatepicker.SelectedDate = DateTime.Now;
//startdatepicker.SelectedDate = new DateTime(DateTime.Now.Year, DateTime.Now.AddMonths(-6), 1);//-->this not working

A: This should work, unless I misunderstand your question...
startdatepicker.SelectedDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

A: I got it by:
DateTime end = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
enddate.SelectedDate = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);

start.SelectedDate = (end.AddMonths(-6));


text:
Q: Any way to create a Object that extends Array? I have created a lexer in javascript, and where im now using an array to describe a range of items, i now see the use of having my own Range object so i can properly distinguish an "array" and a "range array" in such a way that it reads nicely.
So is there any way i can create a hugely cross browser compatible sublcass of the Array object?
Or would a better/simpler approach just using array as is, and for "range arrays" i just tag the array with a property of my own choosing?
something like:
var myRange = [1,2,3];
myrange.isRangeObj = true;

//i would then use if(myRange.isRangeObj) to do specific range operations.
//However i still think myRange instanceof Range reads better

A: Use composition in javascript to create an Object that extends Array:
function Range(arr) {
  this.arr = arr;
}

var myRange = new Range([1, 2, 3]);

if (myRange instanceof Range) {
    doSomethingWithRange(myRange.arr);
}

A: You can use this:
Array.prototype.isRangeObj = false;

So all the arrays created by you will have the property isRangeObj


text:
Q: Why Table Lock Escalation is happening in my scenario I have a table Table1 that is updated in small chunks using below query:
update top (1000) Table1
    set VarcharColumn1 = 'SomeValue'
from Table1
where ID in (select ID from Table2)
      and VarcharColumn1 is NULL

Additional details:
Table2 has 90000 rows, and total number of rows that need to be updated in Table1, is also 90000 (1 to 1 relationship)
Also when Table1 rows are updated, there is a trigger on Table1 that inserts rows as they were before update, to table Table1History
So this means when I update 1000 rows in Table1, 1000 rows inserted into Table1History
Question:
When I update top 100 rows, no Table Lock Escalation happens
I monitor this using Extended Events "lock_escalation" event, and also in Performance Monitor - SQLServer:Access Methods - Table Lock Escalations / sec
When I update top 1000 or 500 rows, Table Lock Escalation IS happening on Table1
So I wonder, what is the mechanism or formula that is used by SQL Server
to escalate locking to table level ?

In google it says 5000 rows is the threshold, but obviously in my case 1000 or 500 rows is enough to cause Table Lock Escalation on Table1

A: Lock escalation is not exactly based on 5k rows, but rather a number of locks pr. level in the locking hierarchy. Once you hit the threshold, locks escalate to the next object level, until you eventually reach table-level which usually has a negative impact on the application. To work around this the easiest, consider how many rows you are affecting in  the DELETE TOP() and how many pages that correlates to. The amount of rows in a page is defined by with width of the row. If you have many columns (requiring lots of byte-storage), your row-width is bigger, then a table with fewer columns. A page can contain roughly 8k-bytes of data.

"Books Online states that the threshold for a lock escalation is reached when the statement has acquired in excess of 5,000 row or page level locks on a single instance of an object. Also some blogs (which I came across in the Internet) just take 5000 value as a threshold point and not consider other parameters. When rows exceed 5000 an attempt is made to convert a higher-level lock on the object (either an IS or an IX lock) to an S lock or an X lock on the table. If this fails, perhaps because the table is being used by someone else, then SQL Server will back off and try again if it acquires another 1,250 locks on the same instance of the object. Remember that all locks attained must originate from the same object within the statement to qualify for exceeding the lock threshold, so 4,000 locks from tableA that is self-joined (i.e., another set of 4,000 locks) would not qualify." [taken from book "Professional SQL Server 2008 Internals and Troubleshooting" by Christian Bolton et al. published by Wrox ]

Good info in the page-object in SQL Server:
https://www.sqlskills.com/blogs/paul/inside-the-storage-engine-anatomy-of-a-page/
There is an option to disable lock escalation as part of your table-definition. Buts it not advisable in most cases. I'd advise to not go this route until you've tried designing with lock escalation in mind. See more here: What is disadvantage of disabling lock escalation in SQL Server 2016

A: Note (select ID from Table2) could return (theorically) 90k rows. Maybe the plan could change with a "exists" or a join between table1 and table2.
Anyway a possible workaourd could be a cursor-loop to avoid large number of rows locked on each iteration.


text:
Q: Function applied in loop on two different dataframes I have two dataframes. The first (games) shows, for each of several games, the year and which player accomplished certain unspecified goals (player1, player2, player3). The second (rankings) show the ranking of each player in a given year.
My goal is to add a column to the games dataframe, indicating the average ranking of all players who accomplished those goals in each game.
A reproducible example:
set.seed(0)
players <- c("Abe", "Bob", "Chris", "John", "Jane", "Linda", "Mason", "Zoe", "NA")
years <- c(2000:2005)
season <- sample(years, 20, replace = TRUE)
player1 <- sample(players, 20, replace = TRUE)
player2 <- sample(players, 20, replace = TRUE)
player3 <- sample(players, 20, replace = TRUE)
games <- data.frame(season, player1, player2, player3, stringsAsFactors = FALSE)
rankings <- data.frame(replicate(6,sample(1:5,8,rep=TRUE)))
colnames(rankings) <- years
ranked_players <- players[-9]
rankings <- cbind(ranked_players, rankings)

The games is the first dataframe, showing the year of the game (season), who was player1, who was player2 and who was player3. There isn't always a player for all categories for all games.
The rankings is the second dataframe, showing the ranking from 1 to 5 of each player in a given year.
I want to calculate what is the ranking of the player who played as player1, player2, and player3 respectively for each game in games, and average those rankings.
To calculate the ranking, I tried this function:
calc_ranking <- function(x, y) {
  z <- select(filter(rankings, ranked_players==x), c(y))
  z <- as.integer(z[1,1])
  z
}

It apparently works. Now I have to apply it for each player who played a game in games and for every year.
I tried this loop:
new_col <- mapply(calc_ranking, games$player1, games$season)

but it doesn't work. It gives me an error
 Error in inds_combine(.vars, ind_list) : Position must be between 0 and n

However, even if it worked, with this solution I should repeat the loop 3 times to create 3 columns, one for each role as player1, player2, and player3, and then create the column I really want (the average of the 3 columns). I suspect there is a more efficient way to do it without repeating the loop (assuming I can fix it)? It would be very useful, because in my real dataset I have 13 "roles" for which I have to calculate the ranking.
Hope this second question is better than my first. Apologize for any mistake, I'm only 1 week into learning R (which is my first experience with coding in general).
Thanks a lot!

A: My understanding is that each row in games is a separate game id. So for:
season    player1    player2   player3
  2001        Joe       Bill      Jane

player    season     ranking
   Joe      2001           1
  Bill      2001           3
  Jane      2001           5

The intended answer is 3 for that one game. To address this, melting the data and then merging the two data.frames on the season and player name would be the simplest route. Edit: added output similar to @heds with the dcast() lines.
library(data.table)

setDT(games)
games[, game_id := seq_len(.N), keyby = season]

molten_games <- melt(games, id.vars = c('season', 'game_id'), variable.name = 'player_number', value.name = 'player')

setDT(rankings)
molten_rankings <- melt(rankings, id.vars = 'ranked_players', variable.name = 'season', value.name = 'ranking', variable.factor = F)[, season:= as.integer(season)]

merged_dt <- molten_rankings[molten_games
                             , on = .(season
                                      , ranked_players = player )
                             , nomatch = 0L
                             ]

merged_dt[, mean(ranking, na.rm = T), by = .(season, game_id)]
    season game_id       V1
 1:   2000       1 2.666667
 2:   2001       2 2.000000
 3:   2001       3 1.333333
 4:   2001       4 4.000000
 5:   2002       1 3.333333
...
#or if you want all the players and rankings
dcast(merged_dt, season + game_id ~ player_number, value.var = c('ranked_players', 'ranking')
      )[, means := rowMeans(.SD), .SDcols = c('ranking_player1', 'ranking_player2', 'ranking_player3')][]

    season game_id ranked_players_player1 ranked_players_player2 ranked_players_player3 ranking_player1 ranking_player2 ranking_player3    means
 1:   2000       1                   John                  Mason                    Zoe               2               2               4 2.666667
 2:   2001       1                   <NA>                    Zoe                   <NA>              NA               4              NA       NA
 3:   2001       2                  Chris                   Jane                  Linda               1               1               4 2.000000
 4:   2001       3                   Jane                   Jane                   John               1               1               2 1.333333
 5:   2001       4                  Linda                    Zoe                    Zoe               4               4               4 4.000000
...

Since it appears you use dplyr, this is a similar approach although I couldn't figure out the way to make it wide at the very end:
library(dplyr)
library(tidyr)

long_rankings <- rankings%>%
  gather(key = 'season', value = 'ranking', - ranked_players)%>%
  mutate(season = as.integer(season))

long_games <- games%>%
  arrange(season)%>%
  group_by(season)%>%
  mutate(game_id = row_number())%>%
  ungroup()%>%
  gather(key = 'player_number', value = 'player', -season, - game_id)

inner_join(long_rankings
           ,long_games
           , by = c('season' = 'season'
                    , 'ranked_players' = 'player'))%>%
  group_by(season, game_id)%>%
  summarize(game_rank_ave = mean(ranking, na.rm = T))

   season game_id game_rank_ave
    <int>   <int>         <dbl>
 1   2000       1          2.67
 2   2001       1          4
 3   2001       2          2
 4   2001       3          1.33
 5   2001       4          4
 6   2002       1          3.33

Regarding generating your data, please be careful about cbind()!! It coerces objects into a matrix and matrices can only have one class such as character or numeric. I addressed the data.frame generation to address the issue.
Data used:
set.seed(0)
players <- c("Abe", "Bob", "Chris", "John", "Jane", "Linda", "Mason", "Zoe", "NA")
years <- c(2000:2005)
season <- sample(years, 20, replace = TRUE)
player1 <- sample(players, 20, replace = TRUE)
player2 <- sample(players, 20, replace = TRUE)
player3 <- sample(players, 20, replace = TRUE)
games <- data.frame(season, player1, player2, player3, stringsAsFactors = FALSE)
rankings <- data.frame(replicate(6,sample(1:5,8,rep=TRUE)))
colnames(rankings) <- years
ranked_players <- players[-9]
#rankings <- cbind(ranked_players, rankings) ##don't cbind unless you're making a matrix!
rankings$ranked_players <- players[-9]

A: I interpreted your desired output a bit differently than @Cole, being that you wanted the column of means of the player ranks per game. My strategy was to extract the players into their own dataframes (while having to change the column names to not be numeric). Then, for each of player1, player2 and player3, look for the player in that "position", and look up their ranking from their individual dataframe. I'm sure there are better ways of doing this but it worked in this case (although I'm not sure it's exactly what you're after.
Output:
> head(games,10)
     season player1 player2 player3 player1_rank player2_rank player3_rank    means
1  year2005   Mason    John    John            3            3            3 3.000000
2  year2001    <NA>     Zoe    <NA>           NA            4           NA       NA
3  year2002     Bob   Linda   Chris            3            4            3 3.333333
4  year2003   Linda     Zoe    Jane            5            5            3 4.333333
5  year2005     Bob    Jane   Chris            5            1            3 3.000000
6  year2001   Chris    Jane   Linda            1            1            4 2.000000
7  year2005    John     Zoe   Chris            3            3            3 3.000000
8  year2005     Abe     Abe    Jane            4            4            1 3.000000
9  year2003    John    Jane   Mason            1            3            3 2.333333
10 year2003     Zoe   Mason     Abe            5            3            5 4.333333

Code:
for (player in players){
    temp_player <- filter(rankings, ranked_players == player)
    colnames(temp_player) <- c("player","year2000","year2001","year2002","year2003","year2004","year2005")
    assign(paste(player), temp_player)
}

games$season <- paste0("year",games$season)
games[games=="NA"] <- NA

i <- 1
for (rows in games$player1){
        if (!is.na(games$player1[i])) {
            season <- games$season[i]
            games$player1_rank[i] <- get(games$player1[i])[,season]
        }
        else
        {
            games$player1_rank[i] <- NA
        }
        i <- i + 1
    }

i <- 1
for (rows in games$player2){
        if (!is.na(games$player2[i])) {
            season <- games$season[i]
            games$player2_rank[i] <- get(games$player2[i])[,season]
        }
        else
        {
            games$player2_rank[i] <- NA
        }
        i <- i + 1
    }

i <- 1
for (rows in games$player3){
        if (!is.na(games$player3[i])) {
            season <- games$season[i]
            games$player3_rank[i] <- get(games$player3[i])[,season]
        }
        else
        {
            games$player3_rank[i] <- NA
        }
        i <- i + 1
    }

games$means <- rowMeans(games[,5:7]

Data:
set.seed(0)
players <- c("Abe", "Bob", "Chris", "John", "Jane", "Linda", "Mason", "Zoe", "NA")
years <- c(2000:2005)
season <- sample(years, 20, replace = TRUE)
player1 <- sample(players, 20, replace = TRUE)
player2 <- sample(players, 20, replace = TRUE)
player3 <- sample(players, 20, replace = TRUE)
games <- data.frame(season, player1, player2, player3, stringsAsFactors = FALSE)
rankings <- data.frame(replicate(6,sample(1:5,8,rep=TRUE)))
colnames(rankings) <- years
ranked_players <- players[-9]
rankings <- cbind(ranked_players, rankings)


text:
Q: Hibernate - One to Many Mapping of Set - Annotations Newbie to Hibernate here. I'm building a simple app to play around with Hibernate and I'm getting the hang of most of the annotations but the mappings are really confusing me.
I have a Person class and I have a Note's class. A person can have many notes associated with them but a single note will only ever correspond to a specific person.
I'm trying to set it up so that the note table has a column called person_id such that I won't need an extra person_note table in the database for the associations.
How would I go about setting up the annotations such that an extra table is not created in the database and I can associate multiple notes to a single person via an extra column in the note's table?
I've tried a few options after searching on Google such as using annotations like this but with no luck:
@JoinColumn(name="id_person", nullable=false)

Person Class
@Entity
@Table(name = "person")
public class Person {

    @OneToMany()
    private Set<Note> notes;

    public Set<Note> getNotes() {
        return notes;
    }

    public void setNotes(Set<Note> notes) {
        this.notes = notes;
    }

    ...

}

Note Class
@Entity
@Table (name = "note")
public class Note {

    @ManyToOne
    private Person person;

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }

   ...

}

Any help would be appreciated. Thank you.

Final Working Solution
For the benefit of anyone looking in the future, I now don't have a separate table for mapping note objects to people objects. The final code (with extra lines removed) now looks like this:
Person Class
@Entity
@Table(name = "person")
public class Person {

    @OneToMany(fetch = FetchType.EAGER, mappedBy = "person", cascade = CascadeType.ALL)
    private Set<Note> notes;

    ...

}

Note Class
@Entity
@Table (name = "note")
public class Note {

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "id_person", nullable = false)
    private Person person;

   ...

}

Misc Points

*

*I had to add cascade = CascadeType.ALL in the Person class to ensure that when I saved a Person object that all the Note objects inside were saved.

*I combined the code from chsdk and Saif. Thank you to both of you.

A: In your mapping annotations you should map the entities with a mappedBy property in the @OneToMany annotation and specify a joinColumn under the @ManyToOne annotation using the @JoinColumn annotation, Change your code like this:
Person class:
@OneToMany(mappedBy = "person") // "person" here refers to the person property in the notes class
private Set<Note> notes;

Notes class:
@ManyToOne
@JoinColumn(name = "id_person", nullable = false)
private Person person;

Take a look at Hibernate Collection mapping for further information.

A: Edit Person
@OneToMany(fetch = FetchType.EAGER , mappedBy = "person")
private Set<Note> notes;

And Note
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "person_id", nullable = false)
private Person person;

A: I agree with you. One can implement what you're asking with only the two tables you already have.
Here is what I would do:
Database wise:
Table Person, with:
 PK column: person_id
Table Note, with:

*

*PK column: note_id

*column: person_id  (nullable)

*column: assigned_person_id (nullable with unique index)

Purpose:

*

*person_id - reference to the PK of the Person table. That will define the [Person : Note] relationship, where 1 person can have multiple notes.

*assigned_person_id - reference to the person assigned to the note. However to guarantee your requirement that only one person can be assigned to a note - add an unique index by that column. That will guarantee that the same person_id was on used for another note record.
Hibernate wise:
Note that the code snippet is not complete! It is just pointing the important moments.
You can look at one of the many complete examples, for instance:
http://www.mkyong.com/hibernate/hibernate-one-to-many-relationship-example-annotation/
public class Person {

   @OneToMany(fetch = FetchType.LAZY, mappedBy = "person")
   public setNotes(Set<Note> notes) {
     this.notes=notes;
   }

...
}

@Table(name = "note", catalog = "schema_name",
uniqueConstraints = @UniqueConstraint(columnNames = "assigned_person_id"))
public class Note {
  private Person person;
  private Person assignedPerson;

  @ManyToOne(fetch = FetchType.LAZY)
  @JoinColumn(name = "person_id", nullable = false)
  public Person getPerson() {
    return person;
  }

  public Person getAssignedPerson() {
    return assignedPerson;
  }

  ...

}