Q: C++ Can't figure out arrays and functions
Possible Duplicate:
Stuck on C++ functions and arrays

Stuck on this problem: I can't get it to run and i am stuck on getting the array functions to return to main. Thanks for any help.
Requires the utilization of a 2 dimensional array to store the pounds of food eaten by 3 monkeys each of the seven days of the week.
Create a function to obtain the pounds eaten for each monkey, each day of the week.
Create a second function to determine pass through the array to calculate the total all of the moneys ate, and then the average eaten on one day.
Create a third function to determine which monkey ate the least amount of food and on what day.  Also output the amount the monkey ate on that day.
Create a fourth function to determine which monkey ate the most amount of food on a single day. Output the monkey number, the pounds eaten, and the weekday.
#include <iostream>
using namespace std;

const int monkeys = 3;
const int weekdays = 7;
double monkeyWeek[monkeys][weekdays];
double largest;
double least;
double average;
int index;
int dayCount;
double amount;

double amountEaten(double[] [weekdays], int);
double mostEaten (double[] [weekdays],int);
double leastEaten (double[][weekdays], int);

int main(){
    double mostBananas (double[] [weekdays],int);
    double leastBananas (double[][weekdays],int);
    //double bananaAverage (double[][weekdays], int);
}

double amountEaten(double array[] [weekdays], int) {
    cout << "Please enter the amount of food eaten per monkey per day." << endl;
    double amount = array[0][0];
    for (index = 0; index < monkeys; index++)
    {
        for (dayCount = 0; dayCount < weekdays; dayCount++)
        {
            cout << endl << "Please enter the amount of pounds eaten by monkey"
                         << (index +1)
                         << endl << "for day " << (dayCount +1) << ": ";
            cin >> monkeyWeek[monkeys] [weekdays] ;
            if (monkeyWeek[monkeys] [weekdays] < 1)
                cout << endl <<"Must feed positive amount" << endl;
        }
    }
}

double mostEaten( double array[] [weekdays], int size)
{
    double largest = array[0][0];
    for (int count = 0; count < size; count++)
    {
        for (int col = 0; col < count; col++)
        {
            if (array[count][weekdays] > largest)
            largest = array[count][weekdays];
        }
    }
    return largest;
}

double leastEaten(double array[] [weekdays], int size)
{
    double least = array[0][0];

    for (int count = 0; count < size; count++)
    {
        for (int col = 0; col < size; col++);
        {
            if (array[count][weekdays] < least)
            least = array[count][weekdays];
        }
    }
    return least;
}

A: You are  just  declaring the functions, you haven't made a call to any functions at all. Use the sample below and change your program accordingly.
Example:
int main()
{
    int i_array={0,1,2,3,4,5};
    function(i_array);           //  Call a function
    printf("%d",i_array[0]);    // will print 100 not 0
}

void function(int []  i_array)
{
    i_array[0]=100;
}


Q: How do I run several linear regressions at once in R? If I have a dataset with variable A, X, Y, and Z and I want to run two linear regressions - both have A as the dependent variable but one has X as the independent variable and the other has Y (note - NOT multiple regression), what can I do?
lm(A ~ X, Y, df = df)  doesn't seem to work, and obviously lm(A ~ X + Y, df = df) becomes a multiple regression. I can use lm(A ~ ., - Z, df = df) but I'm looking for a way that I could pick and choose multiple variables to use as the independent variable. Thanks.

A: lmList in nlme can run multiple regressions at once:
library(nlme)

DF <- data.frame(A = 1:10, X = 1:5, Y = 11:15, Z = 1:10)

DF2 <- cbind(A = DF$A, stack(DF[c("X", "Y")]))
lmList(A ~ values | ind, DF2)

A: Here is an alternative using formulas() from package modelr :
df <- data.frame(A = 1:10, X = 1:5, Y = 11:15, Z = 1:10)

library(modelr)

ll <- formulas(~ A,
              m1 = ~ X,
              m2 = ~ Y
)

results_list <- lapply(ll, lm, data = df)


Q: Implement search box for  dropdown in angular I want to implement search box without any third party libraries,
i want search to be inside the dropdown.
how to do this
<select class="form-control" [(ngModel)]="selected5" [ngModelOptions]="{standalone: true}"
              formControlName="manpower_requirement">
              <option selected *ngFor="let person of newArray" [ngValue]="person">{{ person.positions }} </option>
</select>

A: filter your newArray. Add an input for the search and bind it to searchValue with [(ngModel)]="searchValue" then in the setter, filter newArray.
so:
private _searchValue:string
set searchValue(value:string)
{
    this._searchValue = value;
    this.newArray = this.newArray.filter(v=>v.contains(value));
}

Note - this is unchecked, there may be typos. But this is the idea of a way to do it


Q: getting HTTP Status 500 when location href or when forwarding from Servlet? I get this error:
HTTP Status 500 -

type Exception report
message
descriptionThe server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: java.lang.NullPointerException
root cause
java.lang.NullPointerException
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 3.1-b24 logs.
GlassFish Server Open Source Edition 3.1-b24
when I try to forward from a jsp to another jsp or when I forward in a servlet... The thing is that Y modify some datils from my page and I want to go back to the login-page and log in again to see if the update was successful !... Any ideas on this error ?... Thankx

A: A NullPointerException is a rather trivial exception and has actually nothing to do with JSP/Servlets, but with basic Java in general (look, it's an exception of java.lang package, not of javax.servlet package). It just means that some object is null while your code is trying to access/invoke it using the period . operator.
Something like:
SomeObject someObject = null;
someObject.doSomething(); // NullPointerException!

The 1st line of the stacktrace tells you in detail all about the class name, method name and line number where it occurred.
Fixing it is relatively easy. Just make sure that it's not null or bypass the access altogether. You should rather concentrate on why it is null and/or why your code is trying to deal with null.


Q: Why is execstack required to execute code on the heap? I wrote the code below to test shellcode (for unlinking /tmp/passwd) for an assignment in a security class.
When I compile with gcc -o test -g test.c, I get a segfault on the jump into the shellcode.
When I postprocess the binary with execstack -s test, I no longer get a segfault and the shellcode executes correctly, removing /tmp/passwd.
I am running gcc 4.7.2. It seems like it is bad idea to require the stack to be executable in order to make the heap executable, since there are many more legitimate use cases of the latter than the former.
Is this expected behavior? If so, what is the rationale?
#include <stdio.h>
#include <stdlib.h>

char* shellcode;

int main(){
    shellcode = malloc(67);
    FILE* code = fopen("shellcode.bin", "rb");
    fread(shellcode, 1, 67, code);

    int (*fp)(void) = (int (*) (void)) shellcode;
    fp();
}

Here is the output of xxd shellcode.bin:
0000000: eb28 5e89 760c 31c0 8846 0bfe c0fe c0fe  .(^.v.1..F......
0000010: c0fe c0fe c0fe c0fe c0fe c0fe c0fe c089  ................
0000020: f3cd 8031 db89 d840 cd80 e8d3 ffff ff2f  ...1...@......./
0000030: 746d 702f 7061 7373 7764                 tmp/passwd

A: The real "unexpected" behavior is that setting the flag makes the heap executable as well as the stack.  The flag is intended for use with executables that generate stack-based thunks (such as gcc when you take the address of a nested function) and shouldn't really affect the heap.  But Linux implements this by globally making ALL readable pages executable.
If you want finer-grained control, you could instead use the mprotect system call to control executable permissions on a per-page basis -- Add code like:
uintptr_t pagesize = sysconf(_SC_PAGE_SIZE);
#define PAGE_START(P) ((uintptr_t)(P) & ~(pagesize-1))
#define PAGE_END(P)   (((uintptr_t)(P) + pagesize - 1) & ~(pagesize-1))
mprotect((void *)PAGE_START(shellcode), PAGE_END(shellcode+67) - PAGE_START(shellcode),
         PROT_READ|PROT_WRITE|PROT_EXEC);

A:
Is this expected behavior?

Looking at the Linux kernel code, I think that the kernel-internal name for this flag is "read implies exec". So yes, I think that it's expected.

It seems like it is bad idea to require the stack to be executable in order to make the heap executable, since there are many more legitimate use cases of the latter than the former.

Why would you need the complete heap to be executable? If you really need to dynamically generate machine code and run it or so, you can explicitly allocate executable memory using the mmap syscall.

what is the rationale?

I think that the idea is that this flag can be used for legacy programs that expect that everything that's readable is also executable. Those programs might try to run stuff on the stack and they might try to run stuff on the heap, so it's all permitted.


Q: Meteor JS: Organizing Code for Sharing Code Between Template Helpers Inside my Meteor JS Project's client/templates/pages folder I have these files:
1.) admin_add_product.html and admin_add_product.js
2.) admin_edit_product.html and admin_edit_product.js
Inside both admin_add_product.js and admin_edit_product.js I have the same exact code that I use for both files:
var ucwords = function(str)
{
  return str.split(" ").map(function(i){return i[0].toUpperCase() + i.substring(1)}).join(" ");
};

var editForDB = function(str){

  return ucwords(str.trim());
}

var makeHidden = function(object){
  object.addClass('hidden');
}

var removeHidden = function(object){
  object.removeClass('hidden');
}

var makeDisabled = function(object){
  object.addClass('disabled');
}

var removeDisabled = function(object){
  object.removeClass('disabled');
}

I would like to organise my code so that I don't REPEAT any code unnecessarily.  I wish to put the above snippet of code somewhere where I can share between Template helpers (in this case between admin_add_product.js and admin_edit_product.js) so if ever I do need to edit it I just need to edit it in one place rather than two or more....
I already tried Template.registerHelper but I have found that that only works inside the .html file.........
How do I organise my code in Meteor JS to do this?
Is this even possible in Meteor JS given that each template helper file is supposedly enclosed inside a function(){} closure???

A: Variables declared with var have a file scope, and are indeed inside a closure like you mentioned. However, if you declare new variables without the var keyword, they are accessible throughout your project (given you load files in the right order), as Meteor declares these variables outside the closure.
In your case the solution is to declare your form functions without var, or maybe better declare a new object without var and put them as methods in there:
FormHelpers = {};

FormHelpers.ucwords = function(str)
{
  return str.split(" ").map(function(i){return i[0].toUpperCase() + i.substring(1)}).join(" ");
};

...

You can then use these helpers in both you add and edit tenplates, or anywhere else you need them.
More info on namespacing in the Meteor docs.


Q: Google Analytics with First Party Cookie I am in the process of setting up Google Analytics (GA) on a Wordpress site. As part of this, I want to include a custom cookie (for users that consent) that allows me to segment the analytics of users based on what settings they have active on the site (via a custom plugin). I have managed to successfully implement this most of the way (the cookie is included in many of the tagged events).
However, I have included the custom cookie in a Gravity Form that is being submitted on the website, and there are a number of instances of a form being submitted successfully, tagged with a cookie ID, but that cookie ID is not showing up in Google Analytics as an option to segment page views, for example. I have a record of the cookie being generated on my Apache server, but it has not made its way through to GA.
Is there a way to see all events with a specific attribute in GA? Or is this only possible with a custom report (which necessarily requires you to filter out events that don't have a specific metric).
(I'm primarily a back-end developer, and have limited experience with GA. Apologies if there is something very obvious that I have not done.)

A: You would need to create a custom dimension in Google Analytics, retrieve the cookie value and pass it to the GA code (how exactly would depend on the version of the GA code that you use, as they have recently shifted from the analytics.js library to gtag.js).


Q: Image resize script I'm searching a javascript that can resize images similar to script thats available as a plugin in vBulletin CMS:

I want the script to be used in blogger blog so that all images i upload into a post are resized to a smaller res and on clicking the image should be displayed in original dimensions
Something of the sort getelementbyID("img").
are there any script providing this feature? Pls help me out
Thanks in advance.

A: Something like a lightbox, perhaps?
I know the specific interaction you're asking about, and personally, I've always found it really obnoxious.

A: If you don't want to use a server side script to automatically create a smaller version of the image that you would link to the larger version, I wouldn't recommend using JavaScript to resize an image either. I'd recommend setting the image's dimensions in CSS and then attaching a click handler with JS that showed the image in some sort of overlay (or just using HTML to link to the larger image file).


Q: How to dynamically load the material-ci-icons icon I use Material-ui@next and  material-ui-next@next
material-ui@next load one icon usage:
import AddIcon from 'material-ui-icons/AddIcon';
function AddIconButton(props) {
    return (
        <AddIcon />
    );
}

But I want dynamically load the material-ci-icons icon
For example, I have variable menus
const menus = [
  {
    Name: 'menu1',
    Icons: 'face',
  },
  {
    Name: 'menu2',
    Icon: 'extension',
  }
].

How to display the icon on the page according to the menus

A: I faced with this problem too. i use this link:
dynamically load an icon.
save my menu icon name at database and use  <Icon>{props.iconName}</Icon> but, it doesn't work for me.
so because i don't have so much time i just save the SVG format of material ui icon in my database and restore it at my JSX.
i got SVG format of icons from inspect element of browser from material ui icon web page


Q: java.lang.AbstractMethodError: org.hibernate.search.elasticsearch.analyzer.impl.ElasticsearchAnalyzerStrategy.initializeAnalyzerReferences I am trying to integrate elastic search with hibernate search.For doing this I am using following maven dependencies.
      <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>5.2.1.Final</version>
    </dependency>

    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-search-orm</artifactId>
        <version>5.7.0.Final</version>
    </dependency>

    <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-search-elasticsearch</artifactId>
      <version>5.6.1.Final</version>
    </dependency>

But while deploying the application I am getting below error.
 java.lang.AbstractMethodError: org.hibernate.search.elasticsearch.analyzer.impl.ElasticsearchAnalyzerStrategy.initializeAnalyzerReferences(Ljava/util/Collection;Ljava/util/Map;)Ljava/util/Map.
I know this question has already been asked but I am not able to find out the root cause of error.Any suggestion..........

A: You're using multiple modules of Hibernate Search, but without different versions (5.7.0.Final and 5.6.1.Final). Use the same version for each Hibernate Search module, in your case 5.7.0.Final:
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.2.1.Final</version>
</dependency>

<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-search-orm</artifactId>
    <version>5.7.0.Final</version>
</dependency>

<dependency>
   <groupId>org.hibernate</groupId>
   <artifactId>hibernate-search-elasticsearch</artifactId>
  <version>5.7.0.Final</version>
</dependency>


Q: Observable in for loop? I would like to call an observable REST service in a for loop. It returns base64 encoded csv file. I would like to decode it and concatenate it into one string and return it. After that I am trying to subsrciibe to that method and click the DOM to download. I get empty string with only "\r\n" in it. Why doesn't it wait for REST to return the file before returning?
downloadFilesAndConcatenate(): Observable<any> {
    let concatenatedFileDecoded: string = '\r\n';
    for (let i = 0; i < this.fileIDs.length; i++) {
      this.restService.getFile(this.fileIDs[i]).subscribe(response => {
        this.fileResultSet = response;
        this.message = response.message;
        this.file = this.fileResultSet.result;
        let fileCSVbase64 = this.file.fileBytes
        let fileCSVDecoded = atob(fileCSVbase64);
        concatenatedFileDecoded += fileCSVDecoded;
      },
      error => {
        this.message = error.error.message;
      });

      return new Observable( observer => {
        observer.next(concatenatedFileDecoded)
        observer.complete();
      });
    }
  }

And then I subscribe to it:
download() {
    if (this.dateEnd !== null && typeof this.dateEnd !== "undefined") {
      debugger;
      this.downloadFilesAndConcatenate()  // Multiple files
        .subscribe(
          (result) => {
            debugger;
            const link = document.createElement( 'a' );
            link.style.display = 'none';
            document.body.appendChild( link );

            const blob = new Blob([result], {type: 'text/csv'});
            const objectURL = URL.createObjectURL(blob);

            link.href = objectURL;
            link.href = URL.createObjectURL(blob);
            link.download =  this.file.name;
            link.click();
          },
          (err) => {
            console.error(err);
          },
          () => console.log("download observable complete")
        );
    } else {
      this.downloadFile();  // Only one file
    }
  }

A: because it is asynchroniuos code. it is expected that sync code will be executed earlier than async.
correct code would be like this
downloadFilesAndConcatenate(): Observable<string> {
    return forkJoin(this.fileIDs.map(id => this.restService.getFile(id))).pipe(
      map(responses => '\r\n'+responses.map(r => atob(r.result.fileBytes)).join(''))
      catchError(e => this.message = e.error.message)
    );
  }


Q: how to set java web application's context root when working with reverse proxy
*

*My old way using mod_jk in apache and configure virtual host in tomcat
In the JSP file, I refer to CSS as below
/<%=request.getContextPath()%>/css/styles.css
while the home link is set to
/<%=request.getContextPath()%>/

so this worked fine when I use mod_jk in apache to work with tomcat using ajp;

*

*When I try to configure reverse proxy as below

ProxyPass / http://localhost:800/mywebapp
ProxyPassReverse / http://localhost:800/mywebapp
the home page can be retrieved fine but the css request becomes
http://mydomain.com/mywebapp/mywebapp/css/style.css
so the css file can not be retrieved correctly;

*

*I think one possible way is to always use relative path like ./style.css or ../style.css
a. since header/footer are shared, and the home page is in a different level with detail page, it's inconvenient to use relative path because they're at a different level
b. still, I think the home link will have to be /<%=request.getContextPath()%>/

so I wonder what's the way to set contextroot fine in java web and also work fine with reverse proxy?
thx a lot

A: As I know your application server (Tomcat) isn't able to be aware of a reverse proxy presence. Generally speaking, it can be contacted through any number of reverse proxies or directly by browsers. A network configuration is usually used to limit this, not HTTP or Java.
So, you must accurately rely on relative URLs to make your application work well.
When I have to deal with reverse proxy presence (almost always due to SSO architectures), I embed a "junction" configuration string item (the portion of the URL used in the proxy to map the application) and use it in the only places where I need to build an absolute URL.


Q: How to vectorize process of spltting vector I have a vector of numbers (here random). I'd like to calculate the consecutive relation of something (here means to clarify example) on the left and right side of each number in a vector.
Here is a procedural example. I'm interested in the vectorized form.
from numpy.random import rand
import numpy as np
numbers = rand(40)

k=np.zeros(numbers.shape)
for i in range(*numbers.shape):
     k[i]=np.mean(numbers[:i])/np.mean(numbers[i:])

This example will return nan in the first iteration but it is not a problem now.

A: Here's a vectorized way -
n = len(numbers)
fwd = numbers.cumsum()/np.arange(1,n+1)
bwd = (numbers[::-1].cumsum()[::-1])/np.arange(n,0,-1)
k_out = np.r_[np.nan,fwd[:-1]]/bwd

Optimizing a bit further with one cumsum, it would be -
n = len(numbers)
r = np.arange(1,n+1)

c = numbers.cumsum()
fwd = c/r
b = c[-1]-c
bwd = np.r_[1,b[:-1]]/r[::-1]
k_out = np.r_[np.nan,fwd[:-1]]/bwd

A: I spent some time and there is a simple and universal solution: numpy.vectorize with excluded parameter, where vector designated to be split must be excluded from vectorisation. The example still uses np.mean but can be replaced with any function:
def split_mean(vect,i):
    return np.mean(vect[:i])/np.mean(vect[i:])

v_split_mean = np.vectorize(split_mean)
v_split_mean.excluded.add(0)

numbers = np.random.rand(30)
indexes = np.arange(*numbers.shape)

v_split_mean(numbers,indexes)


Q: Function that reads and stores values from configuration file I'm relatively new to C++ programming and I am just trying to create a function that opens a configuration file, reads each line and column, then stores the values into some array.
So my config file will look like this which simply just stores values:
12345    10    20
67890    30    40
...
...

What I want to do is open this file, read each line and store the values into an [i][j] array. So for the above, it would be stored as:
[0][0] = 12345
[0][1] = 10
[0][2] = 20
[1][0] = 67890
[1][1] = 30
[1][2] = 40

I have been looking at the fopen function to open the file, but when I research on how to store these values how I want (using functions like fgets), I keep hitting a wall.
My attempt thus far:
#include <iostream>
using namespace std;

int main()
{
    FILE *fp;
    fp = fopen("configFile.conf","r");

    char a[20];
    char b[20];
    char c[20];

    fscanf(fp, "%s\t%s\t%s", a, b, c);
    cout << a << " " << b << " " << c << endl;
}

output:
12345    10    20

Now I want to just modify this loop through until the end of the file and store the values in an array based off the i'th element.

A: This is C code :
#include <stdio.h>

int main()
{
   FILE *fp;
   int i = 0;
   fp = fopen("configFile.conf", "r");

   if(fp == NULL) // To check for errors
   {
      printf("Error \n");
   }

   char a[20][20]; // Declared a 2D array
   char b[20][20];
   char c[20][20];

   while (fscanf(fp, "%s\t%s\t%s", a[i], b[i], c[i]) != EOF) //fscanf returns EOF if end of file (or an input error) occurs
   {
      printf("%s  %s   %s\n", a[i], b[i], c[i]);
      i++;
   }

   return 0;
}

C++ code is :
#include <iostream>
using namespace std;

int main()
{
   FILE *fp;
   int i = 0;
   fp = fopen("configFile.conf", "r");

   if(fp == NULL) // To check for errors
   {
      cout<< "Error" << endl;
   }

   char a[20][20]; // Declared a 2D array
   char b[20][20];
   char c[20][20];

   while (fscanf(fp, "%s\t%s\t%s", a[i], b[i], c[i]) != EOF) //fscanf returns EOF if end of file (or an input error) occurs
   {
      cout << a[i] << " " << b[i] << " " << c[i] << endl;
      i++;
   }

   return 0;
}


Q: Access Parent Element Within href So... this is a simple question with a simple answer, but somehow my RTFMing isn't proving any results.
I have a link within a div, like so:

 Close
I'd like to close that div with that link, and I've been trying the following code:

 Close
However, it still hasn't worked... any suggestions are greatly appreciated.

A: Change it to this:

 Close

The reason is that when using href="javascript:..., this doesn't refer to the element that received the event.
You need to be in an event handler like onclick for that.


Q: How to create this below JSON response using python DRF Since I am new to this DRF I am facing some difficulties creating this JSON. I have created an API endpoint and the output of that API endpoint is like this now as shown below
  "meta": {
    "limit": 1,
    "page_count": 1,
    "total_count": 1
  },
  "results": {
    "id": 1234567,
    "curriculum": {
      "ES Math": [
        {
          "grade_level": "ES",
          "subject": "Math",
          "subject_abbr": "Math",
          "product_id": 438,
          "product_title": "Test1",
          "ratings": [
            {
              "source": "A",
              "report_url": "********",
              "Org1_rating": [
                {
                  "name": "green_alignment_ratings",
                  "value": 12,
                  "label": "Meet Expectations",
                  "label_color": "Green"
                },
                {
                  "name": "green_usability_ratings",
                  "value": 12,
                  "label": "Meet Expectations",
                  "label_color": "Green"
                }
              ],
              "Org2_rating": [
                {
                  "name": "Overall",
                  "value": null,
                  "label": "Tier 1: Exemplifies Quality",
                  "label_color": null
                }
              ]
            }
          ]
        },
        {
          "grade_level": "ES",
          "subject": "Math",
          "subject_abbr": "Math",
          "product_id": 2085,
          "product_title": "Test2",
          "ratings": [
            {
              "source": "A",
              "report_url": "********",
              "Org1_rating": [
                {
                  "name": "green_alignment_ratings",
                  "value": 12,
                  "label": "Meet Expectations",
                  "label_color": "Green"
                },
                {
                  "name": "green_usability_ratings",
                  "value": 12,
                  "label": "Meet Expectations",
                  "label_color": "Green"
                }
              ],
              "Org_rating2": "null"
            }
          ]
        }
      ]
    }
  }
}

But I want the output to be in this format below
{
  "meta": {
    "limit": 1,
    "page_count": 1,
    "total_count": 1
  },
  "results": {
    "id": 1234567,
    "curriculum": {
      "ES Math": [
        {
          "grade_level": "ES",
          "subject": "Math",
          "subject_abbr": "Math",
          "product_id": 438,
          "product_title": "Test1",
          "ratings": [
            {
              "review_org": "Org1",
              "review_url": "url",
              "review_items": [
                {
                  "name": "green_alignment_ratings",
                  "value": 14,
                  "label": "Meets Expectations",
                  "label_color": "Green"
                },
                {
                  "name": "green_usability_ratings",
                  "value": 34,
                  "label": "Green",
                  "label_color": 38
                }
              ]
            },
            {
              "review_org": "Org2",
              "review_url": "url",
              "review_items": [
                {
                  "name": "Overall",
                  "value": null,
                  "Label": "Tier I, Exemplifies quality",
                  "scale": null
                }
              ]
            }
          ]
        },
        {
          "grade_level": "ES",
          "subject": "Math",
          "subject_abbr": "Math",
          "product_id": 2085,
          "product_title": "Test2",
          "ratings": [
            {
              "review_org": "Org1",
              "review_url": "url",
              "review_items": [
                {
                  "name":"green_alignment_ratings",
                  "value": 14,
                  "label": "Meets Expectations",
                  "label_color": "Green"
                },
                {
                  "name":"green_usability_ratings",
                  "value": 34,
                  "label": "Meets Expectations",
                  "label_color": "Green"
                }
              ]
            },
            {
              "review_org": "Org2",
              "review_url": "url",
              "review_items": []
            }
          ]
        }
      ]
    }
  }
}

And I tried something with the serializer below but this is yeilding some different JSON only.

class CurriculumSerializer(ModelSerializer):
    grade_level = serializers.CharField(source='grade_level_dim')
    subject_abbr = serializers.CharField(source='subject_abbr_dim')
    product_id = serializers.IntegerField(source='dim_id')
    product_title = serializers.CharField(source='title_dim')
    ratings = serializers.SerializerMethodField()

    class Meta:
        model = Table2
        fields = [
            'grade_level',
            'subject',
            'subject_abbr',
            'product_id',
            'product_title',
            'ratings'
        ]

    def get_ratings(self,obj):
        queryset = Table2.objects.all()
        c = queryset.filter(id=obj.id, title_dim = obj.title_dim, ratings_source__isnull=False).distinct('id',)
        if c.exists():
            serializer = RatingsSerializer(c, many=True)
            return serializer.data
        else:
            data = 'null'
            return data

class RatingsSerializer(ModelSerializer):
    review_items = serializers.SerializerMethodField()
    Louisiana_rating = serializers.SerializerMethodField()
    class Meta:
        model = Table3
        fields = ['source','report_url','review_items','Louisiana_rating']

    def get_review_items(self, obj):
        queryset = Table3.objects.all()
        c = queryset.filter(source__iexact = 'Org1', title = obj.title_dim, grade_level = obj.grade_level, subject_abbr = obj.subject_abbr_dim)
        # print(c.query)
        if c.exists():
            serializer = reportSerializer(c, many=True)
            return serializer.data
        else:
            data = 'null'
            return data

    def get_Louisiana_rating(self, obj):
        queryset = Table3.objects.all()
        c = queryset.filter(source__iexact = 'Org2', title = obj.title_dim, grade_level = obj.grade_level, subject_abbr = obj.subject_abbr_dim)
        if c.exists():
            serializer = reportSerializer(c, many=True)
            return serializer.data
        else:
            data = 'null'
            return data

class reportSerializer(ModelSerializer):
    class Meta:
        model = Table3
        fields = ['name',
                  'value',
                  'label',
                  'label_color']

class DistrictDetailSerializer(ModelSerializer):
    curriculum = serializers.SerializerMethodField()

    class Meta:
        model = Table1
        exclude = ('finance_total', 'revenue_total')

    def get_curriculum(self, obj):
        queryset_list = Table2.objects.all()
        c = queryset_list.filter(id=obj.id)\
            .distinct('col1','col2')
        if c.exists():
            serializer = CurriculumSerializer(c, many=True)
            curriculum_map = {}
            for d in serializer.data:
                key = f"{d['grade_level']} {d['subject_abbr']}"
                if key in curriculum_map:
                    curriculum_map[key].append(d)
                else:
                    curriculum_map[key] = [d, ]
            return curriculum_map
        else:
            data = 'null'
            return data

The table3 has all details for ratings like source, report_url, name,label,value,label_colour I want this values as show in the JSON below.

A: This error usually occurs if the user account was not given/assigned to the Virtual Machine User Login role on the VMs.
Please check this https://learn.microsoft.com/en-us/azure/active-directory/devices/howto-vm-sign-in-azure-ad-windows#azure-role-not-assigned to assign required roles and try login.


Q: How to empty/flush Windows READ disk cache in C#? If I am trying to determine the read speed of a drive, I can code a routine to write files to a filesystem and then read those files back. Unfortunately, this doesn't give an accurate read speed because Windows does disk read caching.
Is there a way to flush the disk read cache of a drive in C# / .Net (or perhaps with Win32 API calls) so that I can read the files directly from the drive without them being cached?

A: Why DIY?
If you only need to determine drive speed and not really interested in learning how to flush I/O buffers from .NET, you may just use DiskSpd utility from http://research.microsoft.com/barc/Sequential_IO/. It has random/sequential modes with and without buffer flushing.
The page also has some I/O related research reports you might find useful.

A: const int FILE_FLAG_NO_BUFFERING = 0x20000000;
return new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read,64 * 1024,
(FileOptions)FILE_FLAG_NO_BUFFERING | FileOptions.Asynchronous
& FileOptions.SequentialScan);

A: Constantin: Thanks! That link has a command-line EXE which does the testing I was looking for.
I also found a link off that page to a more interesting article (in Word and PDF) on this page: Sequential File Programming Patterns and Performance with .NET
In this article, it talks about Un-buffered File Performance (iow, no read/write caching -- just raw disk performance.)
Quoted directly from the article:

There is no simple way to disable
  FileStream buffering in the V2 .NET
  framework. One must invoke the Windows
  file system directly to obtain an
  un-buffered file handle and then
  ‘wrap’ the result in a FileStream as
  follows in C#:

    [DllImport("kernel32", SetLastError=true)]
    static extern unsafe SafeFileHandle CreateFile(
        string FileName,           // file name
        uint DesiredAccess,        // access mode
        uint ShareMode,            // share mode
        IntPtr SecurityAttributes, // Security Attr
        uint CreationDisposition,  // how to create
        uint FlagsAndAttributes,   // file attributes
        SafeFileHandle  hTemplate // template file
        );

    SafeFileHandle handle = CreateFile(FileName,
                            FileAccess.Read,
                            FileShare.None,
                            IntPtr.Zero,
                            FileMode.Open,
                             FILE_FLAG_NO_BUFFERING,
                            null);

    FileStream stream = new FileStream(handle,
                    FileAccess.Read,
                    true,
                    4096);

Calling CreateFile() with the
  FILE_FLAG_NO_BUFFERING flag tells the
  file system to bypass all software
  memory caching for the file. The
  ‘true’ value passed as the third
  argument to the FileStream constructor
  indicates that the stream should take
  ownership of the file handle, meaning
  that the file handle will
  automatically be closed when the
  stream is closed.  After this
  hocus-pocus, the un-buffered file
  stream is read and written in the same
  way as any other.

A: Response of Fix was almost right and better than PInvoke.
But it has bugs and doesn't works...
To open up File w/o caching one needs to do following:
const FileOptions FileFlagNoBuffering = (FileOptions)0x20000000;

FileStream file = new FileStream(fileName, fileMode, fileAccess, fileShare, blockSize,
    FileFlagNoBuffering | FileOptions.WriteThrough | fileOptions);

Few rules:

*

*blockSize must be hard drive cluster size aligned (4096 most of the time)

*file position change must be cluster size aligned

*you can't read/write less than blockSize or block not aligned to it's size

And don't forget - there is also HDD Cache (which slower and smaller than OS cache) which you can't turn off by that (but sometimes FileOptions.WriteThrough helps for not caching writes). With those options you have no reason for flushing, but make sure you've properly tested that this approach won't slow things down in case your implementation of cache is slower.

A: I found this article and it seems that this is a complicated program because you also have to flush other caches.


Q: Python - huge memory consumption while parsing folder of CSV files I have several folders, each of them contains many CSV files. I need to parse them to make some plots etc.
The problem is, that memory consumption is huge and after while it skyrockets to cca 3.4GB. I have no idea what's the cause of this behavior, I've never met a memory-related problem with Python before.
I've found memory profiler, which gives me this output:
Filename: /home/martin/PycharmProjects/readex-radar/fooVisualizer.py

Line #    Mem usage    Increment   Line Contents
================================================
   560  293.340 MiB    0.000 MiB   @profile
   561                             def getAllDataClassifiedFromFolder(measuredFuncFolderArg,
   562                                                                yLabelArg,
   563                                                                filenameArgs,
   564                                                                slideshowCreator,
   565                                                                samplesArgs=None):
   566
   567  293.340 MiB    0.000 MiB       sampleSourcesInds = {}
   568  293.340 MiB    0.000 MiB       summarySourcesAvg = {}
   569  293.340 MiB    0.000 MiB       summarySourcesAvgInds = {}
   570  293.340 MiB    0.000 MiB       summarySourcesFull = {}
   571
   572 3342.426 MiB 3049.086 MiB       for dirpath, dirnames, filenames in os.walk(measuredFuncFolderArg, topdown=True):
   573                                     # Ignorovat skryte slozky kvuli GITu atd.
   574                                     # TODO mozna nebude treba
   575  293.340 MiB -3049.086 MiB           filenames = [f for f in filenames if not f[0] == '.']
   576  293.340 MiB    0.000 MiB           dirnames[:] = [d for d in dirnames if not d[0] == '.']
   577
   578                                     ##########################
   579                                     # Parsovani jedne slozky #
   580                                     ##########################
   581
   582                                     # Vsechna data z jedne slozky (funkce na urcitem radku)
   583  293.340 MiB    0.000 MiB           folderData = []
   584
   585                                     # Nacitam parametry dane v nazvu CSV souboru
   586  293.340 MiB    0.000 MiB           funcLabelArg = filenameArgs.getFuncLabel()
   587  293.340 MiB    0.000 MiB           xLabelArg = filenameArgs.getXLabel()
   588  293.340 MiB    0.000 MiB           otherUserArgs = filenameArgs.getConfigLst()
   589
   590                                     # 'Rozlozim' config argument na jednotlive hodnoty
   591  293.340 MiB    0.000 MiB           keyLst = filenameArgs.getLstOfParams()
   592
   593 3382.207 MiB 3088.867 MiB           for filename in filenames:
   594                                         # Nactu data
   595 3382.207 MiB    0.000 MiB               p = LabeledCSVParser('{}/{}'.format(dirpath, filename))
   596 3382.207 MiB    0.000 MiB               p.parse()
   597 3382.207 MiB    0.000 MiB               data = p.getDicData()
   598
   599                                         # Vytvorit a zapsat 'samples', pokud jsou zadany
   600                                         # parametrem 'samplesArgs'

We can see, that in lines 572 and 593 memory consumption rises dramatically. Do you have any idea why? I suppose it's something with os.walk...
So, have you ever seen this before? And if you have, could you, please, tell me, how to deal with this?

I've tried to add an explicit destructor to the LabeledCSVParser object, but it has a very little effect on memory. In addition, it appears, that there's no significant memory consumption in parse() function.
So, I'll try to inspect iterating through files a little more.
Edit 1
Filename: /home/martin/PycharmProjects/readex-radar/fooVisualizer.py

Line #    Mem usage    Increment   Line Contents
================================================
   100 3271.395 MiB    0.000 MiB       @profile
   101                                 def parse(self):
   102                                     """
   103                                     Funkce pro parsovani 'ostitkovaneho' CSV.
   104
   105                                     Predpoklada CSV ve tvaru:
   106
   107                                         # Label 1
   108                                         data1, data2
   109                                         data3, data4
   110
   111                                         # Label 2
   112                                         data5, data6
   113                                         data7, data8
   114                                         ...
   115
   116                                     Labely se mohou opakovat, ziskane hodnoty
   117                                     se ulozi do ruznych listu ve slovniku __dicData,
   118                                     kde jejich spolecnym klicem bude label.
   119                                     """
   120
   121 3271.395 MiB    0.000 MiB           currentLabel = self.__parsedFile.readline().split('#')[1].strip()
   122 3271.395 MiB    0.000 MiB           dataBlock = list()
   123 3271.395 MiB    0.000 MiB           self.__dicData[currentLabel] = list()
   124
   125                                     # Ulozim soucasny dataBlock do __dicData pod klic currentLabel
   126                                     # - hodnoty se do tohoto dataBlocku zapisuji pozdeji diky
   127                                     #   referenci
   128 3271.395 MiB    0.000 MiB           self.__dicData[currentLabel].append(dataBlock)
   129
   130 3272.949 MiB    1.555 MiB           for row in self.__parsedFile:
   131                                         # Kontrola, jestli se jedna o label nebo radek s daty
   132 3272.949 MiB    0.000 MiB               if row.__contains__('#'):
   133
   134                                             # Vytvorim novy dataBlock
   135 3271.395 MiB   -1.555 MiB                   dataBlock = list()
   136
   137                                             # Zisk nazvu labelu z radku
   138 3271.395 MiB    0.000 MiB                   tmpLabel = row.split('#')[1].strip()
   139
   140                                             # Label se stane 'aktualnim' -  nasledujici
   141                                             # data se budou zapisovat k nemu
   142 3271.395 MiB    0.000 MiB                   currentLabel = tmpLabel
   143
   144                                             # Pokud neni label 'zaevidovany', pridam
   145                                             # jej do __dicData jako klic
   146 3271.395 MiB    0.000 MiB                   if currentLabel not in self.__dicData.keys():
   147 3271.395 MiB    0.000 MiB                       self.__dicData[currentLabel] = list()
   148
   149 3271.395 MiB    0.000 MiB                   self.__dicData[currentLabel].append(dataBlock)
   150                                         else:
   151                                             # Pridam rozparsovany radek do aktualniho
   152                                             # bloku dat jako n-tici
   153 3272.949 MiB    1.555 MiB                   dataBlock.append(tuple(row.strip().split(',')))

Filename: /home/martin/PycharmProjects/readex-radar/fooVisualizer.py

Line #    Mem usage    Increment   Line Contents
================================================
   558  293.543 MiB    0.000 MiB   @profile
   559                             def getAllDataClassifiedFromFolder(measuredFuncFolderArg,
   560                                                                yLabelArg,
   561                                                                filenameArgs,
   562                                                                slideshowCreator,
   563                                                                samplesArgs=None):
   564
   565  293.543 MiB    0.000 MiB       sampleSourcesInds = {}
   566  293.543 MiB    0.000 MiB       summarySourcesAvg = {}
   567  293.543 MiB    0.000 MiB       summarySourcesAvgInds = {}
   568  293.543 MiB    0.000 MiB       summarySourcesFull = {}
   569
   570 2746.160 MiB 2452.617 MiB       for dirpath, dirnames, filenames in os.walk(measuredFuncFolderArg, topdown=True):
   571                                     # Ignorovat skryte slozky kvuli GITu atd.
   572                                     # TODO mozna nebude treba
   573                                     #filenames = [f for f in filenames if not f[0] == '.']
   574                                     #dirnames[:] = [d for d in dirnames if not d[0] == '.']
   575
   576                                     ##########################
   577                                     # Parsovani jedne slozky #
   578                                     ##########################
   579
   580                                     # Vsechna data z jedne slozky (funkce na urcitem radku)
   581  293.543 MiB -2452.617 MiB           folderData = []
   582
   583                                     # Nacitam parametry dane v nazvu CSV souboru
   584  293.543 MiB    0.000 MiB           funcLabelArg = filenameArgs.getFuncLabel()
   585  293.543 MiB    0.000 MiB           xLabelArg = filenameArgs.getXLabel()
   586  293.543 MiB    0.000 MiB           otherUserArgs = filenameArgs.getConfigLst()
   587
   588                                     # 'Rozlozim' config argument na jednotlive hodnoty
   589  293.543 MiB    0.000 MiB           keyLst = filenameArgs.getLstOfParams()
   590
   591  293.543 MiB    0.000 MiB           print('nacitam data')
   592 3271.395 MiB 2977.852 MiB           for filename in filenames:
   593                                         # Nactu data
   594 3271.395 MiB    0.000 MiB               p = LabeledCSVParser('{}/{}'.format(dirpath, filename))
   595 3271.395 MiB    0.000 MiB               p.parse()
   596 3271.395 MiB    0.000 MiB               data = p.getDicData()
   597
   598 3271.395 MiB    0.000 MiB               print('zapisuji samples')
   599                                         # Vytvorit a zapsat 'samples', pokud jsou zadany
   600                                         # parametrem 'samplesArgs'
   601 3271.395 MiB    0.000 MiB               if samplesArgs:
   602                                             sampleSourcesInds[filename] = {}
   603                                             for sampleArg in samplesArgs:
   604                                                 prevNumOfSources = slideshowCreator.getNumOfDataSources()
   605                                                 slideshowCreator.createAndAddDataSource(data[sampleArg], 100, True, 0, 2)
   606                                                 sampleSourcesInds[filename][sampleArg] = list(range(prevNumOfSources,
   607                                                                                slideshowCreator.getNumOfDataSources()))
   608
   609                                         # Ziskam nazvy parametru z nazvu souboru
   610 3271.395 MiB    0.000 MiB               args = filename[0:filename.rfind('.')].split('_')
   611
   612 3271.395 MiB    0.000 MiB               print('tvorim slovnik')
   613                                         # Priradim konkretni hodnoty z nazvu CSV souboru
   614                                         # k zadanym parametrum filenameArgs
   615 3271.395 MiB    0.000 MiB               d = {key: (args[i] if i < len(args) else '') for i, key in enumerate(keyLst)}
   616
   617                                         # Pridam do slovniku nactena data ze souboru
   618 3271.395 MiB    0.000 MiB               d['Data'] = data
   619
   620 3271.395 MiB    0.000 MiB               print('pridavam slovnik do folderData')
   621 3271.395 MiB    0.000 MiB               folderData.append(d)
   622
   623                                     ###############################################################
   624                                     # Rozdelim nactena data ze slozky do skupin podle volitelnych #
   625                                     # argumentu (preconditioner, schur complement...)             #
   626                                     ###############################################################
   627 2742.480 MiB -528.914 MiB           print('rozdeluji data do kategorii')
   628                                     # Ulozene prumerne hodnoty yLabel za vsechna
   629                                     # volani funkce
   630 2742.480 MiB    0.000 MiB           folderDataGroupsAvg = {}
   631
   632                                     # Ulozene hodnoty yLabel ze vsech volani fce
   633                                     #
   634                                     # TODO mozna bude treba zapsat jako zdroj pro
   635                                     # graf jednotlivych iteraci solveru
   636 2742.480 MiB    0.000 MiB           folderDataGroupsFull = {}
   637
   638 2745.746 MiB    3.266 MiB           for i, val in enumerate(folderData):
   639                                         # Ziskam hodnoty konfiguracnich argumentu
   640                                         # a ulozim je jako n-tici
   641 2745.746 MiB    0.000 MiB               optArgsTup = tuple([str(val[arg]) for arg in otherUserArgs])
   642
   643                                         # Pokud jeste neni, pridam n-tici s konfiguracnimi
   644                                         # parametry jako klic pro slovnik s prumernymi
   645                                         # hodnotami spotreby
   646 2745.746 MiB    0.000 MiB               if optArgsTup not in folderDataGroupsAvg:
   647 2743.320 MiB   -2.426 MiB                   folderDataGroupsAvg[optArgsTup] = {}
   648 2743.320 MiB    0.000 MiB                   folderDataGroupsFull[optArgsTup] = {}
   649
   650 2745.746 MiB    2.426 MiB               if folderData[i][funcLabelArg] not in folderDataGroupsAvg[optArgsTup]:
   651 2744.539 MiB   -1.207 MiB                   folderDataGroupsAvg[optArgsTup][folderData[i][funcLabelArg]] = []
   652 2744.539 MiB    0.000 MiB                   folderDataGroupsFull[optArgsTup][folderData[i][funcLabelArg]] = []
   653
   654                                         # Fce pro ziskani hodnot z Blade summary,
   655                                         # ktere slouzi jako yLabelArg.
   656                                         # Nepsano jako lambda kvuli fyz. delce kodu funkce.
   657 2745.746 MiB    1.207 MiB               def getYLabelVals(ind):
   658 2745.746 MiB    0.000 MiB                   retLst = []
   659 2745.746 MiB    0.000 MiB                   for subLst in folderData[ind]['Data']['Blade summary']:
   660 2745.746 MiB    0.000 MiB                       for item in subLst:
   661 2745.746 MiB    0.000 MiB                           if item[0] == yLabelArg:
   662 2745.746 MiB    0.000 MiB                               retLst.append(float(item[1]))
   663 2745.746 MiB    0.000 MiB                   return retLst
   664
   665                                         # Zapisu hodnoty ze vsech volani fce pro jedno nastaveni
   666                                         # do folderDataGroupsFull
   667 2745.746 MiB    0.000 MiB               folderDataGroupsFull[optArgsTup][folderData[i][funcLabelArg]] \
   668 2745.746 MiB    0.000 MiB                   .append((folderData[i][xLabelArg], getYLabelVals(i)))
   669
   670                                         # Ziskam prumernou spotrebu ze vsech volani fce pro jedno
   671                                         # nastaveni (Prec, Schur) a jeden popisek funkce
   672                                         # (pocet jader...).
   673                                         #
   674                                         # TYTO UDAJE PRIDAM do folderDataGroupsAvg.
   675 2745.746 MiB    0.000 MiB               folderDataGroupsAvg[optArgsTup][folderData[i][funcLabelArg]] \
   676 2745.746 MiB    0.000 MiB                   .append((folderData[i][xLabelArg], numpy.mean(getYLabelVals(i))))
   677
   678 2745.746 MiB    0.000 MiB           print('zapidu folderDataGroupsAvg jako zdroj')
   679                                     # Ziskani dat z folderDataGroupsAvg a jejich zapis jako zdroje
   680 2746.160 MiB    0.414 MiB           for key, vals in sorted(folderDataGroupsAvg.items()):
   681 2746.160 MiB    0.000 MiB               summarySourcesAvg[key] = {}
   682
   683                                         # TODO promyslet, jestli nebude lepsi sloucit summarySourcesAvg a summarySourcesAvgInds
   684                                         # do jednoho slovniku
   685 2746.160 MiB    0.000 MiB               summarySourcesAvgInds[key] = {}
   686
   687 2746.160 MiB    0.000 MiB               for subKey, val in sorted(vals.items()):
   688                                             # Zapisu do listu zdroje pro danou konfiguraci - pro vypocty procent atd.
   689 2746.160 MiB    0.000 MiB                   summarySourcesAvg[key][subKey] = val
   690
   691                                             # Zapisu data do zdroju pro vykreslovani grafu
   692 2746.160 MiB    0.000 MiB                   summarySourcesAvgInds[key][subKey] = slideshowCreator.getNumOfDataSources()
   693 2746.160 MiB    0.000 MiB                   slideshowCreator.createAndAddDataSourcesTexCode([sorted(val)], 0, False, 0, 1)
   694
   695 2746.160 MiB    0.000 MiB           print('ziskam data z folderDataGroupsFull')
   696                                     # Ziskani dat z folderDataGroupsFull
   697                                     #
   698                                     # TODO mozna bude potreba i zapis zdroju pro
   699                                     # grafy jednotlivych iteraci
   700 2746.160 MiB    0.000 MiB           for key, vals in sorted(folderDataGroupsFull.items()):
   701 2746.160 MiB    0.000 MiB               summarySourcesFull[key] = {}
   702
   703 2746.160 MiB    0.000 MiB               for subKey, val in sorted(vals.items()):
   704                                             # Zapisu do listu zdroje pro danou konfiguraci - pro vypocty procent atd.
   705 2746.160 MiB    0.000 MiB                   summarySourcesFull[key][subKey] = val
   706
   707 2746.160 MiB    0.000 MiB       return summarySourcesAvg, sampleSourcesInds, summarySourcesAvgInds, summarySourcesFull


Q: How to get clean website url with php? I'm using $wsurl as my websites clean url $wsurl = 'http://'. $_SERVER['HTTP_HOST'] . '/'; But recently when I want to echo it from websites admin panel it gave me result:
http://localhost/admin/>http://localhost/?page=166
instead of
http://localhost/?page=166
More Detailed
What i use: <?=$wsurl?>?page=<?=$new_id?>">Link
What i get as html output localhost/?page=170">Link
But when i click it from admin panel, it opens page localhost/admin>http://localhost/?page=170 (instead of http://localhost/?page=170) which doesn't exist at all
How to deal with that problem?
I want to get websites main url from everywhere within ws.
For ex, if i'm in admin panel http://localhost/admin/index.php the $wsurl will be http://localhost/
If my admin panels url looks like http://mydomain.com/admin/index.php the $wsurl will be http://mydomain.com/

A: If you are facing issues like that then you can try this :
$url = "http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
echo 'http://'.parse_url($url, PHP_URL_HOST) . '/';


Q: CreateChooser is not working in Android v5.1 I am using intent to share pdf files. I am restricting apps when share file. I want to share the file to Good document, Kindle and drop box alone. I am using the below code to achieve this.But the below code is not working in android v5.1. The device have the required app to share. But it is showing "No apps can perform this action" when share. Can you anyone suggest your ideas to resolve this?
var pathFile = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
            var m_documentMobiNames = shortName + "." + fileType;
            var mobileFileName = Path.Combine(pathFile, m_documentMobiNames);
            var shareIntentsLists = new List<Intent>();
            Intent sendIntent = new Intent();
            sendIntent.SetAction(Intent.ActionSend);
            sendIntent.SetType("application/pdf");
            var resInfos = context.PackageManager.QueryIntentActivities(sendIntent, 0);
            if (resInfos.Count > 0)
            {
                foreach (var resInfo in resInfos)
                {
                    string packageName = resInfo.ActivityInfo.PackageName;
                    if (packageName.Contains("com.google.android.apps.docs") || packageName.Contains("com.dropbox.android") || packageName.Contains("com.amazon.kindle"))
                    {
                        Intent intent = new Intent();
                        intent.SetComponent(new ComponentName(packageName, resInfo.ActivityInfo.Name));
                        intent.SetAction(Intent.ActionSend);
                        intent.SetType("application/pdf");
                        intent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse("file://" + mobileFileName));
                        intent.SetPackage(packageName);
                        shareIntentsLists.Add(intent);
                    }
                }
            }

            if (shareIntentsLists.Count > 0)
            {

                chooserIntent = Intent.CreateChooser(new Intent(), "Share with");
                chooserIntent.PutExtra(Intent.ExtraStream, Android.Net.Uri.Parse(mobileFileName));
                chooserIntent.PutExtra(Intent.ExtraInitialIntents, shareIntentsLists.ToArray());
                chooserIntent.SetFlags(ActivityFlags.ClearTop);
                chooserIntent.SetFlags(ActivityFlags.NewTask);
                context.StartActivity(chooserIntent);
                await Task.FromResult(true);

            }


Q: Axios delete is ignoring the second argument This is my createAsyncThunk
export const removePlayer = createAsyncThunk(
    'player/removePlayer',
    async (playerId: any, thunkAPI) => {
        try {
            await axios.delete(URL, playerId)
        } catch (error) {
            return thunkAPI.rejectWithValue(error)
        }
    }
)

And this is the function that dispatches the action
<Button variant='outlined' onClick={() => {
     dispatch(removePlayer(player._id))
}}><DeleteIcon /></Button>

I have used createAsyncThunk for other CRUD operations like Read, Create and Update and they all work just fine. Am I using axios.delete wrong? This is what I feel. As you can see, all I want to do is pass in the player ID, then delete it, simple as that. I used very similar logic for axios.put, axios.get and axios.post and they all work fine
EDIT I can solve this by adding a id parameter to the route like so
router.delete('/:id', deletePlayer)

But im just curious if there is another alternative, because with axios post get and put, I can do it without using any params

A:
But im just curious if there is another alternative

Typically DELETE requests do not have a request body though that doesn't mean you cannot use one.
From the client side, something like this...
axios.delete("/url/for/delete", {
  data: { playerId }
});

will send an application/json request with body {"playerId":"some-id-value"}.
On the server side, with Express you would use this
router.delete("/url/for/delete", async (req, res, next) => {
  const { playerId } = req.body;

  try {
    // do something with the ID...

    res.sendStatus(204);
  } catch (err) {
    next(err.toJSON());
  }
});

To handle JSON payloads you should have registered the appropriate middleware
app.use(express.json());


Q: Is there a simple way to use OpenSSL BIO objects in Java or are there any alternatives? Could anyone tell me is there any way to use OpenSSL's BIO objects from Java?
I'm working on a project, which is intended to provide support for handling of PEAP (https://en.wikipedia.org/wiki/Protected_Extensible_Authentication_Protocol) packets by TinyRadius.
I have tried to search any existing PEAP implementations in Java, but, it seems, there is no one.
Successfully, I have found an implementation, written in Python, which uses pyOpenSSL to decrypt and encrypt data within PEAP sessions. But the problem is that the code uses several OpenSSL features, which are not provided by javax.net.ssl like reading and writing into BIO objects of a SSL session or getting a master key and secure random, generated by the client from a session.
Here is an example of code, which I'm trying to port:
def get_keys(self):
    self.master_key = self.ssl_connection.master_key()
    self.server_sec_random = self.ssl_connection.server_random()
    self.client_sec_random = self.ssl_connection.client_random()
...
def write(self, data):
    self.ssl_connection.bio_write(data)
...
def read(self):
    return self.ssl_connection.bio_read(4096)

I have studied pyOpenSSL and found that all these calls are just wrappers for OpenSSL library functions through libffi (http://sourceware.org/libffi), but I have no idea of how implement the same functionality in Java.
As far as I understand the only way for me is use JNI (or JNA) to call OpenSSL functions. Also, I need to implement the code for managing lifetime of objects, created during OpenSSL access but I do not know how to do that, because I do not have any prior experience with native code from Java.
If anyone knows other ways to utilize OpenSSL from Java or maybe some ready-to-use implementations or ports of OpenSSL, please tell me - all answers are highly appreciated.
Thanks!

A: After numerous searches for ways to utilize OpenSSL from Java I have ended up with JNA wrapper implementation, which, suprisingly, appeared to be pretty simple.
Fortunately, OpenSSL is designed in such way that in vast majority of use-cases we do not need to exactly know the type of the value, returned from the call to OpenSSL function (e.g. OpenSSL does not require to call any methods from structures or work with structure fields directly) so there is no need in huge and complex wrappings for OpenSSL's data types.
Most of OpenSSL's functions operate with pointers, which may be wrapped into an instance of com.sun.jna.Pointer class, which is equivalent to casting to void* in terms of C, and the callee will determine the correct type and de-reference the given pointer correctly.
Here is a small code example of how to load ssleay32.dll, initialize the library and create a context:
1) Define the interface to ssleay32.dll library (functions list may be obtained from OpenSSL GitHub repo or by studying the export section of the dll):
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;

public interface OpenSSLLib extends Library {
  public OpenSSLLib INSTANCE = (OpenSSLLib) Native.loadLibrary("ssleay32",
                               OpenSSLLib.class);
  // Non-re-enterable! Should be called once per a thread (process).
  public void SSL_library_init();
  public void SSL_load_error_strings();

  // Supported context methods.
  public Pointer TLSv1_method();

  ...

  // Context-related methods.
  public Pointer SSL_CTX_new(Pointer method);
  public void SSL_CTX_free(Pointer context);
  public int SSL_CTX_use_PrivateKey_file(Pointer context, String filePath, int type);
  public int SSL_CTX_use_certificate_file(Pointer context, String filePath, int type);
  public int SSL_CTX_check_private_key(Pointer context);
  public int SSL_CTX_ctrl(Pointer context, int cmd, int larg, Pointer arg);
  public void SSL_CTX_set_verify(Pointer context, int mode, Pointer verifyCallback);
  public int SSL_CTX_set_cipher_list(Pointer context, String cipherList);

  public Pointer SSL_new(Pointer context);
  public void SSL_free(Pointer ssl);

  ...
}

2) Initialize the library:
...
public static OpenSSLLib libSSL;
public static LibEayLib  libEay;
...

static {
    libSSL = OpenSSLLib.INSTANCE;
    libEay = LibEayLib.INSTANCE;
    libSSL.SSL_library_init();
    libEay.OPENSSL_add_all_algorithms_conf(); // This function is called from
                                              // libeay32.dll via another JNA interface.
    libSSL.SSL_load_error_strings();
}

...
3) Create and initialize SSL_CTX and SSL objects:
public class SSLEndpoint {
  public Pointer context; // SSL_CTX*
  public Pointer ssl;     // SSL*
  ...
}

...

SSLEndpoint endpoint = new SSLEndpoint();

...

// Use one of supported SSL/TLS methods; here is the example for TLSv1 Method
endpoint.context = libSSL.SSL_CTX_new(libSSL.TLSv1_method());

if(endpoint.context.equals(Pointer.NULL)) {
  throw new SSLGeneralException("Failed to create SSL Context!");
}

int res = libSSL.SSL_CTX_set_cipher_list(endpoint.context, OpenSSLLib.DEFAULT_CIPHER_LIST);
if(res != 1) {
  throw new SSLGeneralException("Failed to set the default cipher list!");
}

libSSL.SSL_CTX_set_verify(endpoint.context, OpenSSLLib.SSL_VERIFY_NONE, Pointer.NULL);

// pathToCert is a String object, which defines a path to a cerificate
// in PEM format.
res = libSSL.SSL_CTX_use_certificate_file(endpoint.context, pathToCert, certKeyTypeToX509Const(certType));
if(res != 1) {
  throw new SSLGeneralException("Failed to load the cert file " + pathToCert);
}

// pathToKey is a String object, which defines a path to a priv. key
// in PEM format.
res = libSSL.SSL_CTX_use_PrivateKey_file(endpoint.context, pathToKey, certKeyTypeToX509Const(keyType));
if(res != 1) {
  throw new SSLGeneralException("Failed to load the private key file " + pathToKey);
}

res = libSSL.SSL_CTX_check_private_key(endpoint.context);
if(res != 1) {
  throw new SSLGeneralException("Given key " + pathToKey + " seems to be not valid.");
}

SSLGeneralException is the custom exception, simply inherited from RuntimeException.
...
// Create and init SSL object with given SSL_CTX
endpoint.ssl = libSSL.SSL_new(endpoint.context);
...

Next steps may be creating of BIO objects and linking them to the SSL object.
Regarding to the original question, client/server secure randoms and the master key may be obtained via such methods:
public int SSL_get_client_random(Pointer ssl, byte[] out, int outLen);
public int SSL_get_server_random(Pointer ssl, byte[] out, int outLen);
public int SSL_SESSION_get_master_key(Pointer session, byte[] out, int outLen);

Please, note, that JNA will search dlls to load looking into jna.library.path parameter. So, if the dlls are located, for example in directory D:\dlls, you must specify such VM option:
-Djna.library.path="D:/dll"
Also, JNA requires 32-bit JRE for 32-bit dlls (probably, libffi constraint?). If you try to load a 32-bit dll using 64-bit JRE, you'll get an exception.


Q: downgrade laravel project 5.5 to 5.0.* First of all sorry about my English! I'm in situation where I need to downgrade my Laravel project because some history about php version running on installation server (php 5.4). After I set my composer.json and run update,
I get this error

composer update --no-interaction --ansi
 C:\composer\composer.bat update --no-interaction --ansi
 Loading composer repositories with package information
 Updating dependencies (including require-dev)
 Package operations: 46 installs, 0 updates, 0 removals
   - Installing psy/psysh (v0.4.4): Downloading (connecting...)
 Downloading (failed)
 Downloading (connecting...)
 Downloading (failed)
 Downloading (connecting...)
 Downloading (failed)    Failed to download psy/psysh from dist: The "https://api.github.com/repos/bobthecow/psysh/zipball/489816db71649bd95b416e3ed9062d40528ab0ac" file could not be downloaded: SSL operation failed with code 1. OpenSSL Error messages:
 error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert protocol version
 Failed to enable crypto
 failed to open stream: operation failed
     Now trying to download from source
   - Installing psy/psysh (v0.4.4): Cloning 489816db71 from cache
     489816db71649bd95b416e3ed9062d40528ab0ac is gone (history was rewritten?)

   [RuntimeException]
   Failed to execute git checkout "489816db71649bd95b416e3ed9062d40528ab0ac" -
   - && git reset --hard "489816db71649bd95b416e3ed9062d40528ab0ac" --

   fatal: reference is not a tree: 489816db71649bd95b416e3ed9062d40528ab0ac

 update [--prefer-source] [--prefer-dist] [--dry-run] [--dev] [--no-dev] [--lock] [--no-custom-installers] [--no-autoloader] [--no-scripts] [--no-progress] [--no-suggest] [--with-dependencies] [--with-all-dependencies] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [-i|--interactive] [--root-reqs] [--] [<packages>]...

 Failed to update packages for  ./composer.json.

could someone help me to fix this error?!


Q: Issue with ComboBox - DropDownStyles + Disable Text Edit So i've looked at a few stackoverflow posts and nothing seems to be solving my issue.
Tried:
How to show text in combobox when no item selected?
And some others, can't find link now.
Application:
http://puu.sh/5mQtX.png
So for the drop down menu at the bottom, I was trying to make the text display "Select Email Use" but whenever adding the text using the DropDownList in the DropDownStyle menu, the text disappears. But I want to make it so the user cannot just edit the text.
Don't have any code exactly for the program right now.
From the SOF post I linked above, I tried everything in that post to fix the issue but nothing exactly helps.
i am using Visual C# 2010 Windows Form Application

A: You can use Text Property of ComboBox Control to show Default Text
Try:
ComboBox1.Text="Select Email Use";

It will be shown ByDefault

A: I think you have to draw the string yourself, here is the working code for you, there is a small issue with the flicker, the string is a little flickering when the mouse is hovered on the combobox, even enabling the DoubleBuffered doesn't help, however it's acceptable I think:
public partial class Form1 : Form {
   public Form1(){
      InitializeComponent();
      comboBox1.HandleCreated += (s,e) => {
         new NativeComboBox{StaticText = "Select Email Use"}
                           .AssignHandle(comboBox1.Handle);
      };
   }
   public class NativeComboBox : NativeWindow {
        public string StaticText { get; set; }

        protected override void WndProc(ref Message m)
        {
            base.WndProc(ref m);
            if (m.Msg == 0xf)//WM_PAINT = 0xf
            {
                var combo = Control.FromHandle(Handle) as ComboBox;
                if (combo != null && combo.SelectedIndex == -1)
                {
                    using (Graphics g = combo.CreateGraphics())
                    using (StringFormat sf = new StringFormat { LineAlignment = StringAlignment.Center })
                    using (Brush brush = new SolidBrush(combo.ForeColor))
                    {
                        g.DrawString(StaticText, combo.Font, brush, combo.ClientRectangle, sf);
                    }
                }
            }
        }
    }
}


Q: Is it possible to integrate Google Play Games Services Realtime Multiplayer into LibGDX for both Android and iOS? I have integrated real-time multiplayer in LibGDX for Android. Now I am wondering how to implement it also for iOS. I have a few questions:
Is this possible?
Can Android and iOS players play together?
What are the possible ways to implement?

A: It is possible, of course. Have a look at interfacing. For the iOS app I would use the Multi-OS engine. Use the normal gdx-setup jar file to create moe module.


Q: Retrieve the formated URL from open_id form I just added OpenID to my website using the PHP janrain libraries, and I got everything working but I have a question about how to do something.
After receiving the openid_url from the user, I pass it to the openid lib, which then processes the url and gets it ready to send to the OP.  How can I retrieve that URL?
Why I ask is because my script currently sees http://mysite.com and mysite.com as different URLs.  I know the library normalizes the URL, I just don't know how to extract it.
I hope I made sense, and thank you for helping.

A: You get the final URL you want to use for tracking purposes back with a Auth_OpenID_SuccessResponse object, in the claimed_id attribute.  (The getDisplayIdentifier() method outputs a version more intended for human consumption, which may or may not be different.)


Q: how to fix 'shopify.api_version.VersionNotFoundError' I am building a simple “Hello World” using Python, Flask and the Shopify Embedded SDK. Following this tutorial----> https://medium.com/@dernis/shopify-embedded-sdk-with-python-flask-6af197e88c63.
After doing all the work when I go to the link ' https://localhost:5000/shopify/install?shop=khawaja-kaleem-com.myshopify.com '   to install the application to test store it gives me this error. Need to fix it.
shopify.api_version.VersionNotFoundError.

TRACEBACK (MOST RECENT CALL LAST)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 2309, in __call__
return self.wsgi_app(environ, start_response)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 2295, in wsgi_app
response = self.handle_exception(e)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1741, in handle_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 2292, in wsgi_app
response = self.full_dispatch_request()
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1815, in full_dispatch_request
rv = self.handle_user_exception(e)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1718, in handle_user_exception
reraise(exc_type, exc_value, tb)
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\_compat.py", line 35, in reraise
raise value
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1813, in full_dispatch_request
rv = self.dispatch_request()
File "C:\Users\92344\Anaconda3\lib\site-packages\flask\app.py", line 1799, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "C:\Users\92344\Downloads\HelloShopify-master\helloshopify\shopify_bp\views.py", line 36, in install
session = shopify.Session(shop_url)
File "C:\Users\92344\Anaconda3\lib\site-packages\shopify\session.py", line 47, in __init__
self.version = ApiVersion.coerce_to_version(version)
File "C:\Users\92344\Anaconda3\lib\site-packages\shopify\api_version.py", line 18, in coerce_to_version
raise VersionNotFoundError
shopify.api_version.VersionNotFoundError

A: You need to specify the API version you wish to use. Set the version before you make any calls. 2020-10 is the default for now.
See the documentation, it explains everything to you.
https://help.shopify.com/en/api/versioning

A: The ShopifyAPI package specifies the allowed versions in the 'shopify/api_version.py' file. In my case the Shopify platform latest API version is '2022-10' but the latest version allowed by the ShopifyAPI package is '2022-07'.
It seems that the ShopifyAPI package is not always updated quickly after the release of a new API version on the Shopify platform. Try aligning the API version to one of the versions allowed to work around this error.


Q: Where can i see the log written by uisng Gauge.writemessage()? Just now i am started switching from testNg to Gauge framework for many reasons, now my question is where i can find the log which was written by using Gauge.writemessage inbuilt method. Or else is there any way to customize the location for the sam.?

A: That message will be in the Gauge report under the step it was executed in.
I personally look at the html reports, but I would assume it is in the xml option as well.
If you want something instantaneous you can write to the console where real time messages are output.  This also helps if some sort of bug in the code prevents the reports from being written (like an infinite loop that keeps the report from being written at the end of the full execution).
Here is what it would look like. The gray box is the GaugeMessage.

A: Gauge.writeMessage api allows you to push messages to the reports at logical points.
For example, the step implementation below
    @Step("Vowels in English language are <vowelString>.")
    public void setLanguageVowels(String vowelString) {
    Gauge.writeMessage("Setting vowels to " + vowelString);
        vowels = new HashSet<>();
        for (char ch : vowelString.toCharArray()) {
            vowels.add(ch);
        }
    }

yields this html report: