Q: sql server status change time THENUMBER       NUMBER      SYSMODTIME              TYPE
ACTIM2816332    IM0540202   2014-11-18 09:17:53.000 Closed
ACTIM2806050    IM0540202   2014-11-13 15:11:29.000 Update
ACTIM2806051    IM0540202   2014-11-13 15:11:29.000 External Vendor Assignment
ACTIM2806049    IM0540202   2014-11-13 15:11:29.000 Status Change
ACTIM2806046    IM0540202   2014-11-13 15:10:34.000 Assignment
ACTIM2804167    IM0540202   2014-11-13 09:31:12.000 Status Change
ACTIM2804166    IM0540202   2014-11-13 09:31:12.000 Assignment
ACTIM2802130    IM0540202   2014-11-12 17:09:57.000 Open

Could You please help me to create a select to calculate time difference between type change from open to close ?
I need to be a universal for different NUMBER.

A: Minutes
SELECT NUMBER, MAX([SYSMODTIME]) AS Closed, MIN([SYSMODTIME]) AS Open,
(DATEDIFF (mi, MAX([LoginDateTime]), MIN([SYSMODTIME]))) AS [datediff]
FROM table
GROUP BY NUMBER

Hours
SELECT NUMBER, MAX([SYSMODTIME]) AS Closed, MIN([SYSMODTIME]) AS Open,
(DATEDIFF (hh, MAX([LoginDateTime]), MIN([SYSMODTIME]))) AS [datediff]
FROM table
GROUP BY NUMBER


Q: How to make hover effect only on hamburger button, not on close button? I have a problem with the following code :
.btn-menu:hover .btn-menu__bars::before{
  transform: translateY(-0.5875rem);
}
.btn-menu:hover .btn-menu__bars::after{
  transform: translateY(0.5875rem);
}

How to make this hover code only work in the state of the hamburger button, not on the close button?

$('.btn-menu').on('click', function() {
  $('body').toggleClass('menu-open');
});
.btn-menu {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 38px;
  padding-left: 0;
  padding-right: 0;
  border: none;
  background-color: transparent;
  color: inherit;
  cursor: pointer;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars {
  position: relative;
  width: 40px;
  height: 2px;
}
.btn-menu__bars:before, .btn-menu__bars:after {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars:before {
  transform: translate(0, -5px);
}
.btn-menu__bars:after {
  transform: translate(0, 5px);
}
.menu-open .btn-menu .btn-menu__bars:before {
  transform: rotate(45deg);
}
.menu-open .btn-menu .btn-menu__bars:after {
  transform: rotate(-45deg);
}

/* How to make this only on burger, not on close */
.btn-menu:hover .btn-menu__bars::before{
  transform: translateY(-0.5875rem);
}
.btn-menu:hover .btn-menu__bars::after{
  transform: translateY(0.5875rem);
}

<button class="btn-menu" type="button" style="background-color: red;">

</button>

A: Because you add .menu-open to the body, you need to apply the hover effect when the body doesn't have the class with :not.
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
  transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
  transform: translateY(0.5875rem);
}

$('.btn-menu').on('click', function() {
  $('body').toggleClass('menu-open');
});
.btn-menu {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 38px;
  padding-left: 0;
  padding-right: 0;
  border: none;
  background-color: transparent;
  color: inherit;
  cursor: pointer;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars {
  position: relative;
  width: 40px;
  height: 2px;
}
.btn-menu__bars:before, .btn-menu__bars:after {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars:before {
  transform: translate(0, -5px);
}
.btn-menu__bars:after {
  transform: translate(0, 5px);
}
.menu-open .btn-menu .btn-menu__bars:before {
  transform: rotate(45deg);
}
.menu-open .btn-menu .btn-menu__bars:after {
  transform: rotate(-45deg);
}

body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
  transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
  transform: translateY(0.5875rem);
}

<button class="btn-menu" type="button" style="background-color: red;">

</button>

Also your script without JQuery :
document.querySelector(".btn-menu").addEventListener("click", () => {
  document.querySelector("body").classList.toggle("menu-open")
})

document.querySelector(".btn-menu").addEventListener("click", () => {
  document.querySelector("body").classList.toggle("menu-open")
})
.btn-menu {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 38px;
  padding-left: 0;
  padding-right: 0;
  border: none;
  background-color: transparent;
  color: inherit;
  cursor: pointer;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars {
  position: relative;
  width: 40px;
  height: 2px;
}
.btn-menu__bars:before, .btn-menu__bars:after {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: #000;
  transition: transform 0.6s cubic-bezier(0.075, 0.82, 0.165, 1);
}
.btn-menu__bars:before {
  transform: translate(0, -5px);
}
.btn-menu__bars:after {
  transform: translate(0, 5px);
}
.menu-open .btn-menu .btn-menu__bars:before {
  transform: rotate(45deg);
}
.menu-open .btn-menu .btn-menu__bars:after {
  transform: rotate(-45deg);
}

body:not(.menu-open) .btn-menu:hover .btn-menu__bars::before{
  transform: translateY(-0.5875rem);
}
body:not(.menu-open) .btn-menu:hover .btn-menu__bars::after{
  transform: translateY(0.5875rem);
}
<button class="btn-menu" type="button" style="background-color: red;">

</button>

Note that if you only have 1 element with a class, you can use an id (and then use getElementById() instead).


Q: Support for ',' in input type="number" in IE 11 using Angular + material I need to accept 10,12 as a valid number in IE 11 because the users only have a German number pad as an input device which only has a comma as a decimal separator.
The current behavior is (userinput -> value used)
10,12 -> 10

The desired behavior is
10,12 -> 10.12
10.12 -> 10.12

As it is currently in Chrome.
My current idea is to implement a ControlValueAccessor for an input type="text" which parses the value into a number, but my attempts for that failed.
The input has to work with reactiveForms and has to be a numeric value

A: I encountered the same problem and was not able to get a comma as the decimal separator with <input type="number"> even when setting the language to a different locale and using a step smaller than 1:
<input type="number" step="0.01" lang="en-US">

So I opted for a custom solution based on <input type="text"> with a custom filtering  mechanism to only allow numbers in.
See this stackblitz for a complete demo.

The most important part is filtering what the user inputs in the field. I suggest you write a directive that listens to input/keydown/paste events and that uses a regex to only allow float/integer numbers.
The following regex (/^-?\d*(,|\.)?\d*$/) allows a number to begin with an optional - followed by digits, then a comma or dot and more digits.
If the new value (current value + key pressed) does not match the regex, simply prevent the event from happening with event.preventDefault(). Otherwise, do nothing and let the value go to the input.
Note that you also have to take care of the copy/cut/paste/undo/redo special keys. And also take into account the cursor position and the selection if any.
Once the filtering is done, you can implement the ControlValueAccessor interface and bind it to your input via its change/input events. Do the string to number conversions in these handlers and do the number to string conversion in a getter or a pipe that you bind to the value attribute.
Here is an example of such a directive, you could generalize it by giving the regex as an input parameter.
import { Directive, Input, HostListener, forwardRef } from '@angular/core';

@Directive({
  selector: '[appNumberOnly]'
})
export class NumberOnlyDirective {
  @HostListener('keydown', ['$event'])
  public onKeydown(event: KeyboardEvent): void {
    const { key } = event;
    if (this.isSpecialOperation(event) || !this.isKeyPrintable(event)) {
      return;
    }
    const newValue = this.getNewValue(event.target as HTMLInputElement, key);
    if (!this.valueIsValid(newValue)) {
      event.preventDefault();
    }
  }

  @HostListener('paste', ['$event'])
  public onPaste(event: ClipboardEvent): void {
    const pastedText = event.clipboardData.getData('text');
    const newValue = this.getNewValue(event.target as HTMLInputElement, pastedText);
    if (!this.valueIsValid(newValue)) {
      event.preventDefault();
    }
  }

  private getNewValue(target: HTMLInputElement, str: string): string {
    const { value = '', selectionStart, selectionEnd } = target;
    return [
        ...value.split('').splice(0, selectionStart),
        str,
        ...value.split('').splice(selectionEnd)].join('');
  }

  private valueIsValid(value: string): boolean {
    return /^-?\d*(,|\.)?\d*$/.test(value);
  }

  private isSpecialOperation(event: KeyboardEvent): boolean {
    const { keyCode, ctrlKey, metaKey } = event;
    // allow ctr-A/C/V/X/Y/Z
    const keysACVXYZ = [65, 67, 86, 88, 89, 90];
    if ((ctrlKey || metaKey) && keysACVXYZ.indexOf(keyCode) >= 0) {
      return true;
    }
    return false;
  }

  private isKeyPrintable(event: KeyboardEvent): boolean {
    const { keyCode } = event;
    return (
      (keyCode > 47 && keyCode < 58)      || // number keys
      keyCode === 32 || keyCode === 13    || // spacebar & return key(s)
      (keyCode > 64 && keyCode < 91)      || // letter keys
      (keyCode > 95 && keyCode < 112)     || // numpad keys
      (keyCode > 185 && keyCode < 193)    || // ;=,-./` (in order)
      (keyCode > 218 && keyCode < 223));      // [\]' (in order)
  }
}

And a custom input-number component implementing ControlValueAccessor:
import { Component, ViewChild, forwardRef, ElementRef, Input, Output, EventEmitter } from '@angular/core';
import { NG_VALUE_ACCESSOR, ControlValueAccessor } from '@angular/forms';

@Component({
  selector: 'app-input-number',
  template: `
    <input
      type="text"
      #input
      appNumberOnly
      [placeholder]="placeholder"
      [value]="_stringifiedValue"
      (input)="_onInput($event.target.value)"
      (change)="_onChange($event.target.value)"
      (blur)="input.value = _stringifiedValue">
  `,
  styles: [`
    :host { width: 100%; display: block; }
    input { width: 100%; }
  `],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InputNumberComponent),
      multi: true
    }
  ]
})
export class InputNumberComponent implements ControlValueAccessor {
  private onChange = [(_: number) => {}];
  private onTouch = [() => {}];

  @Input() placeholder;

  @ViewChild('input') _input: ElementRef;

  @Input()
  get value(): number {
    return this._value;
  }
  set value(value: number) {
    const safeValue = this.safeValue(value);
    if (safeValue !== this._value) {
      this._value = safeValue;
      this.onChange.forEach(fn => fn(safeValue));
    }
  }
  private _value: number = undefined;

  @Output() valueChange = new EventEmitter<number>();

  get _stringifiedValue(): string {
    const val = (this._input.nativeElement.value || '').replace('.', ',');
    if (val === '-' || val === ',') return val;
    const safeValue = this.safeValue(this.value);
    return this.stringify(safeValue).replace('.', ',');
  }

  _onInput(value: string): void {
    this.value = this.safeValue(value);
  }

  _onChange(value: string): void {
    this.value = this.safeValue(value);
    this.valueChange.emit(this.value);
  }

  private safeValue(val: string | number): number {
    const safeValue = parseFloat(this.stringify(val).replace(',', '.'));
    return isNaN(safeValue) ? undefined : safeValue;
  }

  private stringify(val: string | number): string {
    return val === undefined || val === null ? '' : `${val}`;
  }

  public registerOnChange(fn: any): void {
    this.onChange.push(fn);
  }

  public registerOnTouched(fn: any): void {
    this.onTouch.push(fn);
  }

  public writeValue(inputValue: number): void {
    this.value = this.safeValue(inputValue);
  }
}

The component can then be used with two-way binding with [(ngModel)] or with [(value)]. It will work with reactive-forms too:
<app-input-number [(ngModel)]="value"></app-input-number>
<app-input-number [(value)]="value"></app-input-number>


Q: Remove portion of text using GetElementsByClassName I'm trying to use the following script to remove ".00" from all prices on a page I'm working on. The ".00" is built in automatically by the WP theme I'm working with.
Here's the script I'm using:

The prices are formatted as such:

$24.00

...but it's not working. What am I missing?

A: getElementsByClassName returns a HTMLCollection. You must iterate it:

var elements = document.getElementsByClassName("hungry-menu-item-price");
for(var i=0; i<elements.length; ++i)
  elements[i].textContent = elements[i].textContent.replace(".00", "");

$24.00

A: document.getElementsByClassName() function returns a nodeList, not an element
so it must be :
document.getElementsByClassName('hungry-menu-item-price')[0].innerHTML


Q: Do I need to send the data in $.ajax as json? I have an $.ajax request that's sending the data in a serialize() and gets a json array in return. It works perfectly without any issues on Chrome develop's tools and Firefox's firebug. My question is, do I HAVE to send the data(user inputs) as json? I need json for the response but not for the request.

A: No, you send the data however you like but keep in mind how you send it will affect how you can retrieve it.
Also you aren't sending JSON in your request as .serialize() does not return JSON it returns a text string in standard URL-encoded notation.

A: No, you don't need to send it as JSON.  You can send it in any other format, but your receiver will need to know how to interpret it.  Usually people use JSON or XML since your receiver can easily parse these types of data.
You'll need to set the content-type, then you can tell the receiver how to process this content-type.


Q: Activity crashes when paused I have an activity that keeps crashing onPause. Theres a looped thread that draws on a canvas. And When I paused the application or try to move to another activity it crashes.
I have it so it closes out onPause, because I don't want it to post a force close. But I want to be able to go back to the activity
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
    // TODO Auto-generated method stub
    boolean retry = true;
    _canDraw = false;
    while(retry) {
        try {
            DrawThread.join();
            retry = false;
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
    android.os.Process.killProcess(android.os.Process.myPid());
}

@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    android.os.Process.killProcess(android.os.Process.myPid());
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
    case R.id.face_button:
        _canDraw = false;
        try {
            DrawThread.join();
            whack.this.startActivity(selectFace);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

A: @Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    android.os.Process.killProcess(android.os.Process.myPid());
}

You're wondering why it crashes onPause? You're crashing it.


Q: Histogram computational efficiency I am trying to plot a 2 GB matrix using MATLAB hist on a computer with 4 GB RAM. The operation is taking hours. Are there ways to increase the performance of the computation, by pre-sorting the data, pre-determining bin sizes, breaking the data into smaller groups, deleting the raw data as the data is added to bins, etc?
Also, after the data is plotted, I need to adjust the binning to ensure the curve is smooth. This requires starting over and re-binning the raw data. I assume the strategy involving the least computation would be to first bin the data using very small bins and then manipulate the bin size of the output, rather than re-binning the raw data. What is the best way to adjust bin sizes post-binning (assuming the bin sizes can only grow and not shrink)?

A: I don't like answers to StackOverflow Questions of the form "well even though you asked how to do X, you don't really want to do X, you really want to do Y, so here's a solution to Y"
But that's what i am going to do here. I think such an answer is justified in this rare instance becuase the answer below is in accord with sound practices in statistical analysis and because it avoids the current problem in front of you which is crunching 4 GB of datda.
If you want to represent the distribution of a population using a non-parametric density estimator, and you wwish to avoid  poor computational performance, a kernel density estimator (KDE) will do the job far better than a histogram.
To begin with, there's a clear preference for KDEs versus histograms among the majority of academic and practicing statisticians. Among the numerous texts on this topic, ne that i think is particularly good is An introduction to kernel density estimation )
Reasons why KDE is preferred to histogram

*

*the shape of a histogram is strongly influenced by the choice of
total number of bins; yet there is no authoritative technique for
calculating or even estimating a suitable value. (Any doubts about this, just plot a histogram from some data, then watch the entire shape of the histogram change as you adjust the number of bins.)

*the shape of the histogram is strongly influenced by the choice of
location of the bin edges.

*a histogram gives a density estimate that is not smooth.
KDE eliminates completely histogram properties 2 and 3. Although KDE doesn't produce a density estimate with discrete bins, an analogous parameter, "bandwidth" must still be supplied.
To calculate and plot a KDE, you need to pass in two parameter values along with your data:
kernel function: the most common options (all available in the MATLAB kde function) are: uniform, triangular, biweight, triweight, Epanechnikov, and normal. Among these, gaussian (normal) is probably most often used.
bandwith: the choice of value for bandwith will almost certainly have a huge effect on the quality of your KDE. Therefore, sophisticated computation platforms like MATLAB, R, etc. include utility functions (e.g., rusk function or MISE) to estimate bandwith given oother parameters.

KDE in MATLAB
kde.m is the function in MATLAB that implementes KDE:
[h, fhat, xgrid] = kde(x, 401);

Notice that bandwith and kernel are not supplied when calling kde.m. For bandwitdh: kde.m wraps a function for bandwidth selection; and for the kernel function, gaussian is used.

But will using KDE in place of a histogram solve or substantially eliminate the very slow performance given your 2 GB dataset?
It certainly should.
In your Question, you stated that the lagging performance occurred during plotting. A KDE does not require mapping of thousands (missions?) of data points a symbol, color, and specific location on a canvas--instead it plots a single smooth line. And because the entire data set doesn't need to be rendered one point at a time on the canvas, they don't need to be stored (in memory!) while the plot is created and rendered.


Q: Collapse pandas DataFrame based on daily column value I have a pandas DataFrame with multiple measurements per day (for example hourly measurements, but that is not necessarily the case), but I want to keep only the hour for which a certain column is the daily minimum.
My one day in my data frame looks somewhat like this
    DATE                Value               Distance
17  1979-1-2T00:00:00.0 15.5669870447436    34.87
18  1979-1-2T01:00:00.0 81.6306803714536    31.342
19  1979-1-2T02:00:00.0 83.1854759740486    33.264
20  1979-1-2T03:00:00.0 23.8659679630303    32.34
21  1979-1-2T04:00:00.0 63.2755504429306    31.973
22  1979-1-2T05:00:00.0 91.2129044773733    34.091
23  1979-1-2T06:00:00.0 76.493130052689     36.837
24  1979-1-2T07:00:00.0 63.5443183375785    34.383
25  1979-1-2T08:00:00.0 40.9255407683688    35.275
26  1979-1-2T09:00:00.0 54.5583051827551    32.152
27  1979-1-2T10:00:00.0 26.2690011881422    35.104
28  1979-1-2T11:00:00.0 71.3059740399097    37.28
29  1979-1-2T12:00:00.0 54.0111262724049    38.963
30  1979-1-2T13:00:00.0 91.3518048568241    36.696
31  1979-1-2T14:00:00.0 81.7651763485069    34.832
32  1979-1-2T15:00:00.0 90.5695814525067    35.473
33  1979-1-2T16:00:00.0 88.4550315358515    30.998
34  1979-1-2T17:00:00.0 41.6276969038137    32.353
35  1979-1-2T18:00:00.0 79.3818377264749    30.15
36  1979-1-2T19:00:00.0 79.1672568582629    37.07
37  1979-1-2T20:00:00.0 1.48337999844262    28.525
38  1979-1-2T21:00:00.0 87.9110385474789    38.323
39  1979-1-2T22:00:00.0 38.6646421460678    23.251
40  1979-1-2T23:00:00.0 88.4920153764757    31.236

I would like to keep all rows that have the minimum "distance" per day, so for the one day shown above, one would have only one row left (the one with index value 39). I know how to collapse the data frame so that I only have the Distance column left. I can do that - if I first set the DATE as index - with
df_short = df.groupby(df.index.floor('D'))["Distance"].min()

But I also want the Value column in my final result. How do I keep all columns?
It doesn't seem to work if I do
df_short = df.groupby(df.index.floor('D')).min(["Distance"])

This does keep all the columns in the final result, but it seems like the outcome is wrong, so I'm not sure what this does.
Maybe this is already posted somewhere, but I have trouble finding it.

A: You can use aggregate
df_short = df.groupby(df.index.floor('D')).agg({'Distance': min, 'Value': max})

If you want the kept Value column is the same with minimum of Distance column:
df_short = df.loc[df.groupby(df.index.floor('D'))['Distance'].idxmin(), :]

A: Make a datetime Index:
df.DATE = pd.to_datetime(df.DATE) # If not already datetime.
df.set_index('DATE', inplace=True)

Resample and find the min Distance's location:
df.loc[df.resample('D')['Distance'].idxmin()]

Output:
                         Value  Distance
DATE
1979-01-02 22:00:00  38.664642    23.251


Q: flutter web alternates/reduce size of canvaskit.wasm My flutter web initial page load is slow(10-15 secs),
Found that large amount of time is spent in downloading "https://unpkg.com/canvaskit-wasm@0.24.0/bin/canvaskit.wasm" which is around 2.5 MB as per browser logs.
Is there a way to reduce this time/alternate file path/ minification which can be done?
(package is built using flutter build web)

A: Changed web renderer to html renderer
flutter build web --web-renderer html

which resulted in significant reduction in initial load time

A: For the moment there is no solution for this, anyways the Flutter team is working on that and there should be a solution as soon as possible.
You can check the status of this in this link:
Flutter github issue

A: There is a possibility to integrate the canvaskit at build process and host it with your web app for offline support.
Therefore you need to define the url like:
flutter build web --dart-define=FLUTTER_WEB_CANVASKIT_URL=/canvaskit/
This may could also reduce loading time. (direct network connection, no dns lookup...)


Q: Python Script Erroring with argparse.ArgumentError I am running a python selenium script but it's getting an error of
https://i.stack.imgur.com/oQdvx.png
argparse.ArgumentError: argument --screenshot/--save_screenshot/--save-screenshot/--ss: conflicting option string: --screenshot
From reading, there seems to be a pytest-argument being defined in multiple locations.  My install dependency step looks like this:
https://i.stack.imgur.com/XmXoe.png
Any recommendations on how to get rid of this to then execute the test?


Q: Chrome screen keyboard blocking content at bottom of page on mobile Here, I recorded video about problem.
https://www.youtube.com/watch?v=WZbKix3XGTE
Problem is when keyboard on screen. The content is behind of keyboard not reachable. If there is input end of page user can't see what is typing in it.
I have this issue only with chrome, other browsers work normal.
All solutions in my mind about this contains javascript. But I am not sure javascript handle this perfectly. I wanted to ask you knowledge before start. Is there any other option for this only with CSS or something else?
Code in example
<!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=1" />
    <title></title>

Top

        <input type="text" />

Codepen Link
https://codepen.io/hllktlhndd/pen/yZKzyZ

A: Did you get answer for this ?
This worked before okay, but now the android-chrome comes on top of the page and does not push it up anymore.
I'm using webview, maybe they have some option for it?
Quick fix is to add padding at the bottom of the screen, maybe 200 - 300px


Q: MongoDB StitchClient cannot be accessed inside a js function I have already called stClient.login function inside  "addUser()" and "loginUser()" and they worked pretty well. I am able to add the user to my MongoDB database and find the user when login clicked. (dont bother with delete one) After finding a logged user in DB, i am loading a new HTML page where i pass the name of the logged user and profil photo retrieved from MongoDB. Besides, i also want to display the comments of the logged user along with the name and profil photo. Here the issue comes: in showComments method, i am not able to access the stitch Client. Any help is so much appreciated.
Below is the code:
Html 1:
<!DOCTYPE html>

    <title>myFb</title>
     <link rel="stylesheet" type="text/css" href="style1.css">

Hello My App

    <button name="adding" onclick="addUser()">Add User</button>

    <button name="deleting" onclick="deleteUser()">Delete User</button>

    <button name="logging" onclick="loginUser()">Login</button>

Common JS for 2 HTMLs:
let db;
    let itemsCollection;
    let stClient;
    let globalName;
    let temp;

     let clientPromise = stitch.StitchClientFactory.create('facebookclone-tlwvi');

    function onLoadConnectDB(){
        clientPromise.then(stitchClient=>{
            stClient=stitchClient;
            db = stClient.service('mongodb', 'mongodb-atlas').db('FbUsers');
            itemsCollection=db.collection("ClonedFbUsers");
        });

    }

function addUser(){
    var n= prompt("Your username: ")
    const userId = stClient.authedId();
    stClient.login().then(()=>
        itemsCollection.insertOne({ owner_id: stClient.authedId(), userName : n , profilePhoto: "https://avatarfiles.alphacoders.com/115/115265.png", photos: ["NULL"],comments: [{msg:"NULL",time:"NULL",like:0}] })
        ).then(() => itemsCollection.find({}).execute())
    .then(docs =>
      docs.forEach((doc, index) =>
        console.log(`${index}: ${JSON.stringify(doc)}`)
        )
      );
 // });
    alert("added");
}

function deleteUser(){

    var d= prompt("Username to delete: ");
    const userId = stClient.authedId();
    stClient.login().then(()=>
        itemsCollection.deleteOne({ userName: "Messi" })
        ).then(() => itemsCollection.find({}).execute())
    .then(docs =>
      docs.forEach((doc, index) =>
        console.log(`${index}: ${JSON.stringify(doc)}`)
        )
      );
    alert("User "+d+ " deleted.");

}

function loginUser(){
var n= prompt("Your username: ");
globalName=n;
    const userId = stClient.authedId();
    try{
    stClient.login().then(()=>

         itemsCollection.find({ userName : n }).execute()
        ).then(docs=>

        loadUser(n,docs.map(c=>c.userName),docs.map(c=>c.profilePhoto)) //found result in db, send userName and pp link while loading a new user
        );

}catch(err){
    alert("not found a user");
}

 // });
}
function loadUser(name,usName,pp){
if(usName!=""||usName!=null){
//sending name and profile photo link retrieved form db to 2nd HTML
    document.location = "user.html?name="+encodeURIComponent(usName)+"&prof="+encodeURIComponent(pp);
    //document.getElementById("name").value=name;
}else{
    //no user in db
    alert(name+ " is not found");
}

}
 function onLoad () {
    //onLoadConnectDB();

    var pic;
    var url = document.location.href,
        params = url.split('?')[1].split('&'),
        data = {}, tmp;
    for (var i = 0, l = params.length; i < l; i++) {
         tmp = params[i].split('=');
         data[tmp[0]] = tmp[1];
    }
    document.getElementById('name').value = data.name;
    document.getElementById('pp').src=decodeURIComponent(data.prof);
    showComments(data.name);

   // document.getElementById('pp').value=data.pp;
}

 function showComments(globalName){

//ISSUE IS HERE!!

        stClient.login().then(()=>

         itemsCollection.find({ userName : globalName }).execute()
        ).then(docs=>

        document.getElementById("comments").innerHTML = docs.map(c => "
" + c.comments + "
").join("")
        );
        };

HTML2
<!DOCTYPE html>

    <title>MyProfile</title>
     <link rel="stylesheet" type="text/css" href="style2.css">

         &nbsp &nbsp Home  &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp&nbsp &nbsp &nbsp   &nbsp &nbsp &nbsp &nbsp

 <input style="border: none; font-size: 20px; width: 100%" id="name" type="text" readonly>

<button type="submit" onclick="addPhoto()">Add Photo</button>

<button type="submit">Choose Profile Photo</button>

Show comments

A: The issue is relating to async/sync communication. After separating js for html2, i was calling onLoad2() function inside onLoad() function after assuming the connection is established, but no. Should 'wait' till the connection is established and then call another function. js2:
    let db;
    let itemsCollection;
    let stClient;
    let globalName;
    let temp;

    let clientPromise = stitch.StitchClientFactory.create('facebookclone-tlwvi');

function onLoad(){

        clientPromise.then(stitchClient=>{
            stClient=stitchClient;
            db = stClient.service('mongodb', 'mongodb-atlas').db('FbUsers');
            itemsCollection=db.collection("ClonedFbUsers");
            onLoad2(); //if you call outside then, wont work. onLoad2() will be interpreted before establishing connection to db

        });
    }

     function onLoad2 () {
    var pic;
    var url = window.location.href,
        params = url.split('?')[1].split('&'),
        data = {}, tmp;
    for (var i = 0, l = params.length; i < l; i++) {
         tmp = params[i].split('=');
         data[tmp[0]] = tmp[1];
    }
    document.getElementById('name').value = data.name;
    document.getElementById('pp').src=decodeURIComponent(data.prof);
    showComments(data.name);

}

 function showComments(globalName){
    console.log("i am here");
    const userId = stClient.authedId();

        stClient.login().then(()=>

         itemsCollection.find({ userName : globalName }).execute()
        ).then(docs=>

        document.getElementById("comments").innerHTML = docs.map(c => "
" + c.comments.msg + "
").join(" ")
        );
        }

   function addComment(){

    var n=document.getElementById("name").value;

    var com= document.getElementById("comment").value
   stClient.login().then(()=>
        itemsCollection.updateOne({userName : n}, {$push:{comments:{msg:com,time:"22:30",like:4}}})
        ).then(() => itemsCollection.find({}).execute())
    .then(docs =>
      docs.forEach((doc, index) =>
        console.log(`${index}: ${JSON.stringify(doc)}`)
        )
      );

   }

HTML for the js2:
    <!DOCTYPE html>

    <title>MyProfile</title>
     <link rel="stylesheet" type="text/css" href="style2.css">

         &nbsp &nbsp Home  &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp &nbsp &nbsp &nbsp &nbsp &nbsp&nbsp &nbsp &nbsp&nbsp&nbsp &nbsp &nbsp   &nbsp &nbsp &nbsp &nbsp

 <input style="border: none; font-size: 20px; width: 100%" id="name" type="text" readonly>

<button type="submit" onclick="addPhoto()">Add Photo</button>

<button type="submit">Choose Profile Photo</button>

    <input type="text" name="comment" id="comment" placeholder="Type comment">
    <button onclick="addComment()">Send</button>


Q: I cant import the ucf 101 dataset (torchvision), 'list index out of range' error dataset = torchvision.datasets.UCF101(r'my_directory', annotation_path=r'my_directory2', frames_per_clip=16, step_between_clips=1, frame_rate=None, fold=1, train=True, transform=transforms.Compose([transforms.ToTensor()]), _precomputed_metadata=None, num_workers=1, _video_width=64, _video_height=64, _video_min_dimension=0, _audio_samples=0)

This line works, the problem is when I try to do any kind of operation using 'dataset', in particular this one:
data = torch.utils.data.DataLoader(dataset, batch_size=512, shuffle=True)

I get the error, so i can't work on the video data because I can't use the dataLoader, the error is:
IndexError: list index out of range

Complete error message:

    ---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-16-dc3631481cb3> in <module>
----> 1 data = torch.utils.data.DataLoader(dataset, batch_size=512, shuffle=True)

~\anaconda3\lib\site-packages\torch\utils\data\dataloader.py in __init__(self, dataset, batch_size, shuffle, sampler, batch_sampler, num_workers, collate_fn, pin_memory, drop_last, timeout, worker_init_fn, multiprocessing_context)
    211             else:  # map-style
    212                 if shuffle:
--> 213                     sampler = RandomSampler(dataset)
    214                 else:
    215                     sampler = SequentialSampler(dataset)

~\anaconda3\lib\site-packages\torch\utils\data\sampler.py in __init__(self, data_source, replacement, num_samples)
     90                              "since a random permute will be performed.")
     91
---> 92         if not isinstance(self.num_samples, int) or self.num_samples <= 0:
     93             raise ValueError("num_samples should be a positive integer "
     94                              "value, but got num_samples={}".format(self.num_samples))

~\anaconda3\lib\site-packages\torch\utils\data\sampler.py in num_samples(self)
     98         # dataset size might change at runtime
     99         if self._num_samples is None:
--> 100             return len(self.data_source)
    101         return self._num_samples
    102

~\anaconda3\lib\site-packages\torchvision\datasets\ucf101.py in __len__(self)
     96
     97     def __len__(self):
---> 98         return self.video_clips.num_clips()
     99
    100     def __getitem__(self, idx):

~\anaconda3\lib\site-packages\torchvision\datasets\video_utils.py in num_clips(self)
    241         Number of subclips that are available in the video list.
    242         """
--> 243         return self.cumulative_sizes[-1]
    244
    245     def get_clip_location(self, idx):

IndexError: list index out of range

A: Problem:
This problem occurs when you run your code on windows because windows paths use backslash ("\") instead of forward slash ("/").
As you see in the code:
https://github.com/pytorch/vision/blob/7b9d30eb7c4d92490d9ac038a140398e0a690db6/torchvision/datasets/ucf101.py#L94
So, this line of code reads the file path from label file as “action\video_name” and merge it with “root” path using backslash therefore full path becomes like “root\action/video_name”. Such paths doesn’t match with the video lists at line#97 and returns empty list for indices variable.
Solution:
Two of possible solutions can be:

*

*Replace the forwardslashes “/” in the label files with backslashes “\”.

*Override the _select_fold(…) function of class UCF101 and fix the backslashes inside the function


Q: How to get devise custom User columns to save? I am reading that the application controller needs to have a before filter: before_filter :configure_permitted_parameters, if: :devise_controller?
however, I am receiving this error:

undefined method `before_filter' for ApplicationController:Class Did
  you mean? before_action

How can I get the new User fields added with a migration to save with devise?

A: Add new column in to your database
after In your ApplicationController.rb Add
before_action :configure_permitted_parameters, if: :devise_controller?
private
def configure_permitted_parameters
 devise_parameter_sanitizer.permit(:sign_up, keys:[:profile_pic,:fname,:mobile,:gender])
end

Here use keys  => your added fields


Q: Why need to decrease clientHeight from windowHeight while calculating scrollPercent? I am trying to show how much a user has scrolled through the page a with progress bar and I have done it.  But I have a little confusion here.
Here is the code that I found to calculate  scrollPercent which works well

windowHeight = Math.max(
html.clientHeight,
html.scrollHeight,
html.offsetHeight,
body.scrollHeight,
body.offsetHeight
);

const  scrolledPercent =
((html.scrollTop || body.scrollTop) / (windowHeight - html.clientHeight)) *
100;

Initially, I thought, to get the scrollPercent , I need to get the current scrollPosition and divide that number with the total height of the page and multiply by 100% . which is like normally how we get % of something.
const  scrolledPercent =
((html.scrollTop || body.scrollTop) / windowHeight) * 100;

but this line doesnot worked as I expected . If I do this the progress bar wont reach 100% even if I scroll to end of the page. I don't understand why am I wrong here !
So, my question is why do we need to decrease the html.clientHeight  from  windowHeight ?
Thank you.
Demo here:

// --------------------------------------------
// variables
// --------------------------------------------

const html = document.documentElement,
  body = document.body,
  countryList = document.querySelector(".country__list");
scrollNavigated = document.querySelector(".scroll__navigated");
let windowHeight;

// --------------------------------------------
// function
// --------------------------------------------

async function prepareListOfCountries() {
  let list = await fetch("https://restcountries.eu/rest/v2/all");
  list = Array.from(await list.json());
  let markup = list
    .map((country, index) => {
      return `

              ${country.name}${country.capital}

`;
    })
    .slice(0, 30)
    .join(" ");
  countryList.innerHTML = markup;
}

function updateScrolledStatus(e) {
  windowHeight = Math.max(
    html.clientHeight,
    html.scrollHeight,
    html.offsetHeight,
    body.scrollHeight,
    body.offsetHeight
  );

  const scrolledPercent =
    ((html.scrollTop || body.scrollTop) / (windowHeight - html.clientHeight)) *
    100;
  // const scrolledPercent =
  //   ((html.scrollTop || body.scrollTop) / windowHeight) * 100; // this line doesnot work
  scrollNavigated.style.width = scrolledPercent + "%";
}

prepareListOfCountries();

// --------------------------------------------
// event-handler
// --------------------------------------------

window.addEventListener("scroll", updateScrolledStatus);
*::after,
*::before,
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: #fff;
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
 Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}

.container {
  max-width: 980px;
  margin: 0 auto;
}

.justify-between {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.items-center {
  display: flex;
  align-items: center;
}

.card {
  background-color: #fff;
  box-shadow: 0 0 12px 12px rgba(0, 0, 0, 0.054);
  border-radius: 4px;
  padding: 16px;
}

.country__flag img {
  height: 100%;
  width: 100%;
}

.header {
  padding: 24px 0;
  background-color: #333;
  color: #f1f1f1;
  position: -webkit-sticky;
  position: sticky;
}

.content {
  padding: 50px 0;
}

.content__form {
  margin: 0 auto;
  margin-bottom: 32px;
}

.content__search {
  width: 50%;
  padding: 12px 16px;
  border-radius: 20px;
  border: 1px solid #ddd;
  transition: 0.2s;
}

.content__search:hover {
  box-shadow: 0 1px 6px 0 rgba(32, 33, 36, 0.28);
}

.content__search:focus {
  outline: none;
}

.country__list {
  margin-top: 50px;
  margin: 10px auto;
}

.country__item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}

.country__name, .country__capital, .country__flag {
  width: 33.33%;
}

.country__flag {
  width: 32px;
  height: 24px;
}

.scroll__navigator {
  height: 2px;
  margin: 0 auto 32px;
  background-color: #333;
  position: -webkit-sticky;
  position: sticky;
  top: 0;
}

.scroll__navigated {
  display: block;
  height: 100%;
  width: 0;
  background: orangered;
  transition: 0.3s linear;
}

        All countries list

        <form class="content__form">
          <input class="content__search" />
        </form>

              NepalKathmandu

A: As an example, say that the height of your client is 100px and the height of your whole page is 500px.
When the scroll position is 0px, you're able to see the first 100px of your site, so from 0px to 100px.
At scroll position 100px, you can see the range 100px to 200px, because you've moved the page, and therefore the visible range, on by 100px.
At scroll position 400px, you can therefore see the range 400px to 500px – in other words, you've scrolled to the bottom.
This demonstrates that the scrollable height of the page (400px) is less than the actual height of the page (500px), namely by the height of the client.
To get the percentage scrolled, you need to use the scrollable height, so it is necessary to subtract the height of the client from the height of the page to get a correct value, or you'll never be able to scroll to the bottom. It's not possible to scroll by 500px on a site that is only 500px long!


Q: makefile fails - implicit rule compiles one object file but doesn't compile the rest Makefile isn't using implicit rules correctly. I am following this guide here.
Here's my makefile:
objects = main.o hello.o
hello : $(objects)
    cc -o hello $(objects)

hello.o : defs.h
main.o : defs.h hello.h

.PHONY : clean
clean :
    -rm hello $(objects)

I get the following error:
cc: error: main.o: No such file or directory

It creates the object code hello.o, but does not do it for main.c. If I swap lines and main is above, it'll create main.o but not hello.o.
Here's my main.c file:
#include "defs.h"
#include "hello.h"

int main(int argc, char** argv) {
   display_hello();
   return (EXIT_SUCCESS);
}

Here's my hello.c file:
#include "defs.h"

void display_hello()
{
    printf("Hello!\n");
}

My hello.h file:
#ifndef HELLO_H
#define HELLO_H

#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
}
#endif

#endif /* HELLO_H */

void display_hello();

Here's my defs.h file:
#ifndef DEFS_H
#define DEFS_H

#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
}
#endif

#endif /* DEFS_H */

#include <stdio.h>
#include <stdlib.h>

A: Works fine for me, I created the files as https://gist.github.com/boyvinall/f23420215707fa3e73e21c3f9a5ff22b
$ make
cc    -c -o main.o main.c
cc    -c -o hello.o hello.c
cc -o hello main.o hello.o

Might be the version of make like @Beta said, but even an old version of GNU make should work just fine for this.
Otherwise, ensure you're using tabs to indent in the makefile, not spaces.


Q: GridControl Navigation In VFP9 I have a grid control ,witch  show the records from a database table. And also I have a command button wherewith I want to navigate from a row to another. I tried with thisform.grid1.ActiveRow = thisform.grid1.ActiveRow +1 ,but this doesn't work. Thanks in advance.

A: Per the VFP documentation, the ActiveRow Property "Specifies the row that contains the active cell in a Grid control. Not available at design time; read-only at run time".
I would do something like this.
IF EOF("TableAlias) = .F.
    SKIP 1 IN "TableAlias"
ENDIF


Q: Will JS be aligned with the ECMAScript specs regarding the "typeof null"? In the ECMAScript specs, it is clearly stated that Null is a type whose one and only value is null:
4.3.12 null value
primitive value that represents the intentional absence of any object value

4.3.13 Null type
type whose sole value is the null value

My question is very simple: why on earth we've got the below:
typeof null
>"object"

Is there any intent to correct/amend this? (either the specs or the JS language)

A: JS does align with the ECMAScript spec. null values may have a Null type, but that does not mean that typeof is supposed to return "null". You can see the spec behavior in section 12.5.5.1, which defines the runtime behavior of typeof, that Null-type objects return "object" from typeof.


Q: What's the result of an integer list plus an integer in C? I should post the complete code.
int f(int x, int *y) {
   static int a =0;
   int b =0;
   while(b<x) {
       a =a +y[b];
       b =b +1;
   }
   return a;
 }
 int main(int argc, char **argv){
     int z[5] ={1,2,3,4,5};
     int r1, r2;
     r1 =f(3, z);
     r2 =f(1, z+1);
 }

The value of r2 is 8. What is z+1 here?

A: The expression z+1 is an example of pointer arithmetic.
The array z decays to a pointer to the first element of the array, i.e. &z[0].  z+1 means "take the address contained at z and add 1 array element to that address".  This is the same as &z[1].
So this function call:
r1 =f(3, z);

Passes in the address of the first element of z, resulting in the array z being visible in the function.
In this function call:
r2 =f(1, z+1);

It passes in the address of the second element of z.  So the function is able to see the array starting from the second element.


Q: How to apply alternating background color to divs which are not siblings I'd like aaaa and bbbb to have red background. How can I do this , the usual answers dont seem to work since the target divs are not siblings
Here is my CSS/HTML:

div.rules-container>div.ng-star-inserted>div.rules-form:nth-of-type(odd) {
  background: red;
}

      aaaaaaaaaaaa

      bbbbbbbbbb

      ccccccccccccc

A: Use :nth-child(odd).
Answer 1:
If you want all the odd numbers, then do this:

.rules-container .ng-star-inserted:nth-child(odd) {
  background-color: red;
  }

      aaaaaaaaaaaa

      bbbbbbbbbb

      ccccccccccccc

      dddddddddddddd

      eeeeeeeeeeeeee

Answer 2:
If you only want 1 & 3, not 5 , then change the css to:

.rules-container .ng-star-inserted:nth-child(1), .rules-container .ng-star-inserted:nth-child(3) {
  background-color: red;
}

      aaaaaaaaaaaa

      bbbbbbbbbb

      ccccccccccccc

      dddddddddddddd

      eeeeeeeeeeeeee


Q: Give every question in a Google-Form an unique id I want to make a Google Form using Google Apps Scripts. The questions in the form comes from a Google Sheet which includes the id and text of a question. When the form is submitted and I export the questions to a sheet the column names are the questions as text. I would rather replace them using an unique ID based on a column from my own Google Sheet where the questions are also stored as text.
How can I solve this?

A: Build a Question Text to ID hash table
function hashtable() {
  const ss = SpreadsheetApp.getActive();
  const sh = ss.getSheetByName('Sheet0');
  let texttoid = {};
  sh.getDataRange().getDisplayValues().forEach(r => texttoid[r[1]]=r[0]);
  Logger.log(JSON.stringify(texttoid));
}

Execution log
11:58:17 AM Notice  Execution started
11:58:18 AM Info    {"text1":"id0","text2":"id1","text3":"id2","text4":"id3","text5":"id4","text6":"id5","text7":"id6","text8":"id7","text9":"id8","text10":"id9","text11":"id10"}
11:58:18 AM Notice  Execution completed

Sheet0:

id0
text1

id1
text2

id2
text3

id3
text4

id4
text5

id5
text6

id6
text7

id7
text8

id8
text9

id9
text10

id10
text11

You can goto to Google Apps Script Reference and using the search box find any function that you don't understand. If it's a pure JavaScript function the go here
You could store the hash table in cache if wish to use it repeatedly to save the time of building it each time from a spreadsheet.


Q: Oracle PL/SQL set column names using other table I'm struggling with naming columns in one table, using a reference table containing these names. I'm sure it should be possible, but I can't seem to find the right solution or think of the correct logic to achieve it...
Situation: I got 2 tables, one with data, columns having descriptive names, and one with a translation of these column names to meaningful names (reference table, or 'codebook').
I'm looking for a way to return the data of the first table, with the names of the columns given in the second column of the second table.
Tables look like:
dataTable:
q1,q2,q3
1,2,3
4,5,6

and
translationTable:
descName, meanName
q1, meaning1
q2, meaning2
q3, meaning3

Result should be:
meaning1,meaning2,meaning3
1,2,3
4,5,6

Help would be highly appreciated!

A: You can not directly do it, because you need a query whose columns are variable, based on some value.
Slightly different, what you can do is build a dynamic SQL to have your query created by Oracle:
SETUP:
SQL> create table dataTable(q1,q2,q3) as
  2  select 1,2,3 from dual union all
  3  select 4,5,6 from dual
  4  ;

Table created.

SQL> create table translationTable(descName, meanName) as
  2  select 'q1', 'meaning1' from dual union all
  3  select 'q2', 'meaning2' from dual union all
  4  select 'q3', 'meaning3' from dual ;

Table created.

This will create and print your query:
SQL> declare
  2      vSQL varchar2(1000);
  3  begin
  4      select listagg (column_name || ' AS "' || meanName || '"', ', ') within group (order by column_name)
  5      into vSQL
  6      from user_tab_columns col
  7        inner join translationTable    tr
  8          on (upper(tr.descName) = col.column_name)
  9      where table_name = upper('dataTable');
 10      --
 11      vSQL := 'select ' || vSQL || ' from dataTable';
 12      dbms_output.put_line(vSQL);
 13  end;
 14  /
select Q1 AS "meaning1", Q2 AS "meaning2", Q3 AS "meaning3" from dataTable

PL/SQL procedure successfully completed.

If you copy the statement and run it:
SQL> select Q1 AS "meaning1", Q2 AS "meaning2", Q3 AS "meaning3" from dataTable;

  meaning1   meaning2   meaning3
---------- ---------- ----------
         1          2          3
         4          5          6

SQL>

This way you have your query, but you can not fetch it, because it still has variable columns.
You can easily edit this code to make it build a query that returns strings, composed by concatenating the felds; this way you will always have a single field, but it's different from what you asked:
SQL> select 'meaning1, meaning2, meaning3' from dual
  2  union all
  3  select Q1 || ',' || Q2 || ',' ||  Q3 from dataTable;

'MEANING1,MEANING2,MEANING3'
--------------------------------------------------------------------------------
meaning1, meaning2, meaning3
1,2,3
4,5,6


Q: SQL Server query to Postgres Please help me to convert this SQL Server Query to a Postgres query. I am using Postgresql 9.3.I am not able to get the desired output in postgres
If object_ID(N'tempdb.dbo.#tmp') is not NULL
    Drop table #tmp;

create table #tmp
(
variable_int_col int,
timestamp_int_col int,
value_col int
)

insert into #tmp values
(8,1449486435,25),
(8,1449486436,26),
(9,1449486435,40),
(9,1449486436,44),
(9,1449486440,52)

select * from #tmp

Declare @sql varchar(max);
Declare @sql2 varchar(max);

set @sql= STUFF((select distinct ','+ QUOTENAME(variable_int_col) from #tmp FOR XML PATH('')) ,1,1,'');
set @sql2= STUFF((select distinct ','+ 'ISNULL(' + QUOTENAME(variable_int_col) + ',0)' + ' AS ' + QUOTENAME('variable_' + cast(variable_int_col as varchar) + '_value') from #tmp FOR XML PATH('')) ,1,1,'');

set @sql='select timestamp_int_col,' + @sql2 + ' from #tmp t
               PIVOT (SUM(value_col) FOR variable_int_col IN ('+@sql+')) p';
-- print @sql

If object_ID(N'dbo.newTable') is not NULL
    Drop table newTable;

set @sql='select * into newTable from (' + @sql + ') s';

exec(@sql);

select * from newTable;

I have tried But failed to convert this line
set @sql='select timestamp_int_col,' + @sql2 + ' from #tmp t
                   PIVOT (SUM(value_col) FOR variable_int_col IN ('+@sql+')) p';

Please Help


Q: How to get confusion matrix and ROC curve when using flow_from_directory? I've trained a model using:
    train_datagen = ImageDataGenerator(rescale = 1/255,
                                       zoom_range=0.3,
                                       shear_range=0.3,
                                       horizontal_flip=True,
                                       rotation_range=30,
                                       fill_mode="nearest",
                                       validation_split = 0.2)

    test_datagen  = ImageDataGenerator(rescale = 1./255
                                      )

    train_dataset  = train_datagen.flow_from_directory(directory = './train',
                                                       target_size = tsize,
                                                       class_mode = 'categorical',
                                                       subset = 'training',
                                                       batch_size = BS)

    valid_dataset = train_datagen.flow_from_directory(directory = './train',
                                                      target_size = tsize,
                                                      class_mode = 'categorical',
                                                      subset = 'validation',
                                                      batch_size = BS)

    test_dataset = test_datagen.flow_from_directory(directory = './test',
                                                      target_size = tsize,
                                                      class_mode = 'categorical',
                                                      batch_size = BS)

and also:
    hist = model.fit(train_dataset,validation_data=valid_dataset,epochs=30,callbacks=[vgg_step_1])

How can i plot confusion matrix?, im confused, i only have the validation vs train plot.

A: To get a confusion matrix you need to make predictions on the test set. Then you need to provide the predicted values and the associated true values to the confusion matrix. Note -- in your code for the test_dataset you MUST set shuffle=False in flow_from_directory!!
Code below should generate an adaptable confusion matrix plot and classification report. model is your trained model.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import imshow
import seaborn as sns
sns.set_style('darkgrid')
def cm_cr(test_gen, model):
    preds=model.predict(test_gen)
    labels=test_gen.labels
    classes=list(test_gen.class_indices.keys()) # ordered lst of class names
    pred_list=[ ] # will store the predicted classes here
    true_list=[]
    for i, p in enumerate (preds):
        index=np.argmax(p)
        pred_list.append(classes[index])
        true_list.append(classes[labels[i]])
    y_pred=np.array(pred_list)
    y_true=np.array(true_list)
    clr = classification_report(y_true, y_pred, target_names=classes)
    print("Classification Report:\n----------------------\n", clr)
    cm = confusion_matrix(y_true, y_pred )
    length=len(classes)
    if length<8:
        fig_width=8
        fig_height=8
    else:
        fig_width= int(length * .5)
        fig_height= int(length * .5)
    plt.figure(figsize=(fig_width, fig_height))
    sns.heatmap(cm, annot=True, vmin=0, fmt='g', cmap='Blues', cbar=False)
    plt.xticks(np.arange(length)+.5, classes, rotation= 90, fontsize=16)
    plt.yticks(np.arange(length)+.5, classes, rotation=0, fontsize=16)
    plt.xlabel("Predicted")
    plt.ylabel("Actual")
    plt.title("Confusion Matrix")
    plt.show()

cm_cr(test_dataset, model)

I did not do the ROC curve but there is a good tutorial here for that activity.


Q: How to make the calendar using the TimeGridWeek view show me only the name of the day I am making a generic weekly calendar so i want to only show the name of the day no the number but a i didn't find how to do it.
I am using fullcalendar v6
https://fullcalendar.io/
How it look

How it should be


Q: element onChange javascript not working <select name='cmg_select'  onChange="javascript:window.location.href='index.php?'+this.value">
    <option value='pening'> pening </option>
    <option value='complete'> complete </option>
    <option value='pening'> pening </option>
</select>

The concatenation is not working.

A: *

*Remove the javascript: portion

*Remove the href portion

The result :

     < select name='cmg_select' onchange="window.location='index.php?'+this.value" >

A: Try this instead
<select name='cmg_select' onChange="window.location.href='index.php?'+this.options[this.selectedIndex].value">
<option value='pening' > pening </option>
<option value='complete' > complete </option>
<option value='pening' > pening </option>
</select>

A: Remove the javascript: from the onchange attribute.


Q: How do I click on a drop down menu that is hidden using Selenium? I'm trying to click on a drop down menu, but since it is hidden, I'm getting the error:
could not be scrolled into view

I've done some digging and I see that using some JavaScript could help, but I'm not sure how to implement that into my Python script.

<input name="idTeam1Desktop" type="hidden" id="idTeam1Desktop" value="">

This is what I have so far:
driver = webdriver.Firefox(profile, options=options)
driver.get("https://tradenba.com/trade-machine")
element = driver.find_element_by_xpath("//*[@id='idTeam1Desktop']")
element.click()

A: To click on the drop down menu and select the menu item with text as MIL you need to induce WebDriverWait for the element_to_be_clickable() and you can use the following xpath based Locator Strategies:

*

*Using XPATH:
driver.get('https://tradenba.com/trade-machine')
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@id='select-idTeam1Desktop']"))).click()
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='MuiListItemText-root MuiListItemText-inset']/span/div/p[text()='MIL']"))).click()

*Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

*Browser Snapshot:


Q: Display a Popup Goal:
When you rightclick one of the row in the table, a popup with links should display, close to the row and cursor. A similiar concept is gmail's functionality.
Problem:
I cannot find a demo version in order to use it.
Information:
I'm using Bootstrap and jQuery..


Q: What is the best practice to use Oauth2, React, Node.js and Passport.js to authenticate user with Google sign on button? I want to have a login button in my website so when a user clicks on it, the user can use their Google credentials. I'd like to ideally perform the authentication server side using Express.js and Passport.js.
I implemented authentication server-side but the problem is that I can't make an AJAX request from the website to the server to start authentication because Google or Oauth don't support CORS. So I need to use a href element in my website which would call the server authentication endpoint. However, I can't catch server response in this way.
If I perform the authentication client-side (I'm using React) I could store login state in Redux and allow the user to access the website's resources. However, when the user logs out I need to make sure that server endpoints stop serving the same user which feels like implementing authentication twice: client-side and server-side.
In addition when authenticating client-side, Google opens a popup for the user to authenticate which I think is worse user experience then just a redirect when authenticating server-side.
I'm wondering what the best practice in terms of authenticating using Oauth2/Google. For example, stackoverflow.com also has Google button but just makes a redirect, without any popup, so I guess they figured out a way to perform server-side authentication and to bypass CORS issue.

A: I faced the same issue. This article is Gold link
1.In auth route File I had following code
 const CLIENT_HOME_PAGE_URL = "http://localhost:3000";

  // GET  /auth/google
  // called to authenticate using Google-oauth2.0
  router.get('/google', passport.authenticate('google',{scope : ['email','profile']}));

  // GET  /auth/google/callback
  // Callback route (same as from google console)
   router.get(
    '/google/callback',
    passport.authenticate("google", {
    successRedirect: CLIENT_HOME_PAGE_URL,
    failureRedirect: "/auth/login/failed"
   }));

   // GET  /auth/google/callback
  // Rest Point for React to call for user object From google APi
   router.get('/login/success', (req,res)=>{
     if (req.user) {
         res.json({
          message : "User Authenticated",
         user : req.user
        })
     }
     else res.status(400).json({
       message : "User Not Authenticated",
      user : null
    })
  });

2.On React Side After when user click on button which call the above /auth/google api
  loginWithGoogle = (ev) => {
    ev.preventDefault();
    window.open("http://localhost:5000/auth/google", "_self");
  }

3.This will redirect to Google authentication screen and redirect to /auth/google/callback which again redirect to react app home page CLIENT_HOME_PAGE_URL
4.On home page call rest end point for user object
(async () => {
  const request = await fetch("http://localhost:5000/auth/login/success", {
   method: "GET",
   credentials: "include",
   headers: {
    Accept: "application/json",
     "Content-Type": "application/json",
    "Access-Control-Allow-Credentials": true,
  },
});

const res = await request.json();
   //In my case I stored user object in redux store
   if(request.status == 200){
     //Set User in Store
    store.dispatch({
      type: LOGIN_USER,
      payload : {
        user : res.user
     }
    });
  }

})();

5.last thing add cors package and following code in server.js/index.js in node module
// Cors
app.use(
  cors({
    origin: "http://localhost:3000", // allow to server to accept request from different origin
    methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
    credentials: true // allow session cookie from browser to pass through
   })
);

A: Your authentication should be done server side. Here is how it works.

*

*You make a fetch or axios call to your authentication route.

*Your authentication route sends a request to Google's Authentication servers. This is important to have on the backend because you will need to provide your clientSecret. If you were to store this on the frontend, it would make it really easy for someone to find that value and compromise your website.

*Google authenticates the user and then sends you a set of tokens to your callback url to use for that user (refresh, auth, etc...). Then you would use the auth token for any additional authorization until it expires.

*Once that expires, you would use the refresh token to get a new authorization token for that client. That is a whole other process though.

Here is an example of what that looks like with Passport.js: https://github.com/jaredhanson/passport-google-oauth2
EDIT #1:
Here is an example with comments of the process in use with Facebook, which is the same OAuth codebase:
https://github.com/passport/express-4.x-facebook-example/blob/master/server.js

A: Redux can really help with achieving this and this follows the same logic as Nick B already explained...

*

*You set up oauth on the server side and provide an endpoint that makes that call

*You set up the button on you react frontend and wire that through an action to the endpoint you already setup

*The endpoint supplies a token back which you can dispatch via a reducer to the central redux store.

*That token can now be used to set a user to authenticated

There you have it.


Q: Set VisualState of combobox when a item is selected in Xaml (Silverlight) When my combobox expands and I select an item, I want the combobox to change visual state(it is highlighted). This will signify something is selected. I tried various VisualStates but none of them would trigger in this scenario. How can I achieve this? Thanks.

A: The standard ComboBox simply doesn't have states to distinguish between having something selected and having nothing selected.
There are a number of ways to go about solving the underlying problem, and it depends mostly on the answer to the following question:
Do you really need to change the visual appearance of the ComboBox itself or does it suffice to style the selected item more prominently?
If it's the latter, you're best served with the rather easy way of using a custom control template for the ComboBoxItems.
If you really want to style the ComboBox itself that way, there are two options I can think of:
A) Add custom states to a ComboBox with a custom template.
Copy your ComboBox's control template and add another state group to the already present states. Both of this is typically done in Expression Blend.
After that you can update the new states in code with
VisualStateManager.GoToState(this, "Selected", true);

for example. You will have to set those states yourself when the first item is chosen. This could be done on the SelectionChanged event.
B) Derive from ComboBox
If you want to use the control in this way often, it might be worthwhile to derive from ComboBox to make your own custom control.
It would look somthing like this:
[TemplateVisualState(Name = "SelectedStates", GroupName = "Unselected")]
[TemplateVisualState(Name = "SelectedStates", GroupName = "Selected")]
// ... (more attributes copied from the ComboBox ones)
public class MyComboBox : ComboBox
{
    public MyComboBox()
    {
        SelectionChanged += HandleSelectionChanged;

        DefaultStyleKey = typeof(MyComboBox);
    }

    void HandleSelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        VisualStateManager.GoToState(this, SelectedItem != null ? "Selected" : "Unselected", true);
    }
}

And you would then need a default style based on the default ComboBox style (or whatever you usually use).
Note that I didn't test this in any way.


Q: PHP array_key_exists and is not empty Following on from a previous question, I am now using the following function to check if a key exists in a multi-dimensional array...
function array_key_exists_r($needle, $haystack) {
        $result = array_key_exists($needle, $haystack);
        if ($result)
            return $result;

        foreach ($haystack as $v) {
            if (is_array($v) || is_object($v))
            $result = array_key_exists_r($needle, $v);
            if ($result)
            return $result;
        }

        return $result;
    }

I am checking like this...
if (array_key_exists_r("image",$myarray)) {
echo 'Array Key Image Exists';
}

But now I am trying to modify it or the result to check that key is not empty, can I do this inside the function or should I do something with the output of the function?
Or should I be using isset instead?

A: Whether you do this inside the function or not it's fully up to you. Personally if I did it inside the function I would change its name to something clearer since it doesn't only check if a key exists. Anyhow I found a solution within the same function:
function array_key_exists_r($needle, $haystack){

    $result = array_key_exists($needle, $haystack);

    if ($result && $haystack[$needle]){
        return $result;
    }

    foreach ($haystack as $v)
    {
        if (is_array($v) || is_object($v)){
            $result = array_key_exists_r($needle, $v);

            if ($result) {
                return $result;
            }
        }
    }

    return false;
}

So basically I added a validation on your ifs and that did it also change the default return value to false just in case. I think it can still be enhanced but this does the job.

A: Try this approach instead. Easier!
function array_key_exists_r($needle, $haystack) {
   $found = [];
   array_walk_recursive($haystack, function ($key, $value) use (&$found) {
      # Collect your data here in $found
   });
   return $found;
}


Q: Multiple Uploads Rails Paperclip not Saving I have a rails model 'Guitar' and a rails model 'Photo.' I wanted to be able to attach multiple photos so I watched the railscasts for Paperclip, read the docs, etc. I've used Paperclip in the past to attach a single photo, but I wanted to do multiples this time. I don't have a problem updating the model, and it doesn't error out when I attach sample photos, but when I rails console to Photos.all, nothing comes back. My ultimate goal is to a polymorphic association with an 'Amps' model, but I really just wanted to get 'Guitars' working first.
I have paperclip added to the Gemfile and I've bundle installed, restarted the server, etc. I think I'm missing something stupid and I'm new to rails so please be gentle...
guitar.rb
class Guitar < ActiveRecord::Base
  belongs_to :user
  has_many :photos

  accepts_nested_attributes_for :photos
end

photo.rb
class Photo < ActiveRecord::Base
  belongs_to :guitars

  has_attached_file :photo, styles: {
        thumb: '100x100>',
        square: '200x200#',
        medium: '300x300>',
        large: '600x600#' }
end

guitars_controller.rb
class GuitarsController < ApplicationController
  before_action :set_guitar, only: [:show, :edit, :update, :destroy]

  # GET /guitars
  # GET /guitars.json
  def index
    @guitars = Guitar.all
  end

  # GET /guitars/1
  # GET /guitars/1.json
  def show
  end

  # GET /guitars/new
  def new
    @guitar = Guitar.new
    3.times { @guitar.photos.build }
  end

  # GET /guitars/1/edit
  def edit
    @guitar = Guitar.find(params[:id])
    3.times { @guitar.photos.build }
  end

  # POST /guitars
  # POST /guitars.json
  def create
    @guitar = Guitar.new(guitar_params)
    @guitar.user_id = current_user.id if current_user

    respond_to do |format|
      if @guitar.save
    format.html { redirect_to @guitar, notice: 'Guitar was successfully created.' }
    format.json { render action: 'show', status: :created, location: @guitar }
      else
    format.html { render action: 'new' }
    format.json { render json: @guitar.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /guitars/1
  # PATCH/PUT /guitars/1.json
  def update
    respond_to do |format|
      if @guitar.update(guitar_params)
    format.html { redirect_to @guitar, notice: 'Guitar was successfully updated.' }
    format.json { head :no_content }
      else
    format.html { render action: 'edit' }
    format.json { render json: @guitar.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /guitars/1
  # DELETE /guitars/1.json
  def destroy
    @guitar.destroy
    respond_to do |format|
      format.html { redirect_to guitars_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_guitar
      @guitar = Guitar.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def guitar_params
      params.require(:guitar).permit(:make, :model, :year, :color, :serial, :price, :condition, :kind, :bodykind, :frets, :one_owner, :user_id)
    end
end

guitars show.html.erb

  Make:
  <%= @guitar.make %>

  Model:
  <%= @guitar.model %>

  Year:
  <%= @guitar.year %>

  Color:
  <%= @guitar.color %>

  Serial:
  <%= @guitar.serial %>

  Price:
  <%= @guitar.price %>

  Condition:
  <%= @guitar.condition %>

  Kind:
  <%= @guitar.kind %>

  Bodykind:
  <%= @guitar.bodykind %>

  Frets:
  <%= @guitar.frets %>

  One owner:
  <%= @guitar.one_owner %>

  User:
  <%= @guitar.user_id %>

    <% for asset in @guitar.photos %>
      <%= link_to image_tag(photo.photos.url(:thumb)), photo.photo.url(:original) %>
    <% end %>

<%= link_to 'Edit', edit_guitar_path(@guitar) %> |
<%= link_to 'Back', guitars_path %>

guitars _form.html.erb
<%= simple_form_for(@guitar, html: { class: 'form-horizontal', :multipart => true}) do |f| %>
  <% if @guitar.errors.any? %>

<%= pluralize(@guitar.errors.count, "error") %> prohibited this guitar from being saved:

      <% @guitar.errors.full_messages.each do |msg| %>

<%= msg %>

      <% end %>

  <% end %>

  <%= f.input :make, label: 'Make of the Guitar', placeholder: 'Gibson' %>
  <%= f.input :model, label: 'Model of the Guitar', placeholder: 'Les Paul' %>
  <%= f.input :year, label: 'Year Made', placeholder: '1957' %>
  <%= f.input :color, label: 'Color', placeholder: 'GoldTop' %>
  <%= f.input :serial, label: 'Serial', placeholder: '#7-8789' %>
  <%= f.input :price, label: 'Price' %>
  <%= f.input :condition, label: 'Condition, 1-10' %>
  <%= f.input :kind, label: 'Kind of Guitar', placeholder: '6-String-Electric' %>
  <%= f.input :bodykind, label: 'Body Type', placeholder: 'Solid String Electric' %>
  <%= f.input :frets, label: 'Number of Frets', placeholder: '22' %>
  <%= f.input :one_owner, label: 'Original Owner' %>

  <%= f.fields_for :photos do |photo| %>
    <% if photo.object.new_record? %>
      <%= photo.file_field :photo %>
    <% end %>
  <% end %>

    <%= f.submit %>

<% end %>

A:  def guitar_params
  params.require(:guitar).permit(:make, :model, :year, :color, :serial, :price, :condition, :kind, :bodykind, :frets, :one_owner, :user_id, photos_attributes: [:photo])
end

A: You're running into mass assignment protection which is preventing the photos from being saved.  Add this line to your Guitar model:
attr_accessible :photos_attributes

A: in my case I need create a document.
# config/initializer/paperclip.rb
require 'paperclip/media_type_spoof_detector'
module Paperclip
  class MediaTypeSpoofDetector
    def spoofed?
      false
    end
  end
end

This document is necessary create in config > initializers. If your SO is windows, you need add this line in config/environments/development.rb:

Paperclip.options[:comand_path] = "/ImageMagick-6.8.9-Q16/"


Q: Android service fails after onRebind() with a DeadObjectException I am having a problem with my Android service and client apps who rebind to it. Everything works fine when a client app initially binds to my service, after which messages can be sent from service to client. However, if the client app is killed and then binds agains, onRebind() is correctly called in the service, but my messenger in the intent is invalid, causing a DeadObjectException, as noted in the code below. Any ideas?
Here is my code for the service:
@Override
public IBinder onBind(Intent intent)
{
    getMessenger(intent);

    return _inputMessenger.getBinder();
}

@Override
public void onRebind(Intent intent)
{
    getMessenger(intent);
}

@Override
public boolean onUnbind(Intent intent)
{
    return true;
}

private void getMessenger(Intent intent)
{
    Bundle extras = intent.getExtras();

    if (extras != null)
    {
        // Get the messenger sent from the app.
        // This is handled correctly after onBind() and onRebind().
        _outputMessenger = (Messenger) extras.get("MESSENGER");
        Log.i(TAG, "Got messenger from app: " + _outputMessenger);
    }
}

private void sendMessageToClient(String key, String value)
{
    Message message = Message.obtain();
    Bundle bundle = new Bundle();
    bundle.putString(key, value);
    message.setData(bundle);

    try
    {
        _outputMessenger.send(message); // EXCEPTION OCCURS HERE AFTER onRebind()
    }
    catch (Exception ex)
    {
        Log.e(TAG, "_outputMessenger.send() failed: " + ex);
    }
}

And here is the code for the application:
     Intent intent = new Intent("com.foobar.service");

    // Create a new messenger for the communication from service to app.
    _messenger = new Messenger(new ServiceToActivityHandler());
    intent.putExtra("MESSENGER", _messenger);

    _serviceConnection = new MyServiceConnection();

    _isBoundToService = _context.bindService(intent,
                                           _serviceConnection,
                                           Context.BIND_AUTO_CREATE);

A: There is a note on bound services... The part under additional notes should be useful. I think trapping the exception is probably what you should do...
try {
    // Do stuff
} catch(DeadObjectException e){
    // Dead object
}

I read that object lifetimes should be reference counted by android across processes, so you should be OK, when the client dies I wonder if
 _outputMessenger // needs to be unassigned in your service...?

I assume what is happening is that your binding to the service, it's pumping some data back to your client, your client goes away, the service continues running but then needs to pump some data to the client which has gone by this point?
Also this link


Q: postman only showing "This field is required" to ManyToMany field in django I have 2 models - Module and Room. A module can have zero or multiple rooms and a room can be added into multiple modules. So, there is a simple many-to-many relationship between them.
When I use post request, raw-data works, but not form-data.
module/models.py -
class Module(models.Model):
    module_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100)
    desc = models.TextField()
    room_list = models.CharField(max_length = 100, blank=True)
    rooms = models.ManyToManyField(Rooms, blank=True)

rooms/models.py -
class Rooms(models.Model):
    room_id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=100)
    level = models.CharField(max_length=100)
    desc = models.TextField()

module/serializers.py -
class ModuleSerializer(serializers.ModelSerializer):
    rooms = RoomSerializer(many=True)

    class Meta:
        model = Module
        fields = '__all__'

    def create(self, validated_data):
        rooms_data = validated_data.pop('rooms')
        module = Module.objects.create(**validated_data)
        for data in rooms_data:
            room = Rooms.objects.get(**data)
            module.rooms.add(room)
        return module

    def update(self, instance, validated_data):

        # Updating rooms
        rooms_data = validated_data.get('rooms')
        instance.rooms.clear()

        for room_data in rooms_data:
            room = Rooms.objects.get(**room_data)
            instance.rooms.add(room)

        # Updating other fields
        fields = [
            'title',
            'desc',
            'thumbnail',
            'is_deleted',
        ]
        for field in fields:
            setattr(instance, field, validated_data[field])
        instance.save()
        return instance

rooms/serialier.py -
class RoomSerialize(serializers.ModelSerializer):
    room_id = serializers.IntegerField()
    class Meta:
        model = Rooms
        fields = "__all__"

module/views.py -
class add_module(APIView):
    def post(self, request, format=None):

        # Adding the rooms to module from room_list
        new_request = request.data.copy()
        room_list=[]
        if 'room_list' in new_request:
            room_list_data = list(new_request['room_list'].split(" "))
            for room in room_list_data:
                room_object = Rooms.objects.get(room_id=room)
                room_serializer = RoomSerializer(room_object)
                room_list.append(room_serializer.data)
        new_request.update({'rooms':room_list})

        # creating the module
        module_serializer = ModuleSerializer(data=new_request)
        if module_serializer.is_valid():
            module_serializer.save()
            return Response(module_serializer.data['module_id'])
        return Response(module_serializer.errors)

POST request body for updating a module in POSTMAN -
{
    "module_id": 2,
    "room_list": "1 2",
    "title": "4",
    "desc": "22",
}

Pls notice that while taking input of ManyToMany field - "rooms", I'm taking a string "room_list" as input that contains all the room_ids to be included. This works perfectly fine when I take input as raw-data in postman, but when I use form-data, it shows
{
    "rooms": [
        "This field is required."
    ]
}

What to do?

A: First of all, serializer fields with (many=True) create nested objects.
If you input data with Rooms as already serialized, then it means that you create other Rooms instances. It will be shown with if module_serializer.is_valid(): part. Therefore, if you intended to implement as just link already instantiated Rooms to Module, it's better to make it as primary key list.
Here are my example codes.
class ModuleSerializer(serializers.ModelSerializer):
    rooms = RoomSerializer(many=True, read_only=True)

    def create(self, validated_data):
        rooms_data = validated_data['room_list']
        module = Module.objects.create(**validated_data)
        for data in rooms_data.split(' '):
            room = Rooms.objects.get(room_id=data)
            module.rooms.add(room)
        return module

    def update(self, instance, validated_data):

        # Updating rooms
        rooms_data = validated_data.get('rooms')
        instance.rooms.clear()

        for room_data in rooms_data:
            room = Rooms.objects.get(**room_data)
            instance.rooms.add(room)

        # Updating other fields
        fields = [
            'title',
            'desc',
            'thumbnail',
            'is_deleted',
        ]
        for field in fields:
            setattr(instance, field, validated_data[field])
        instance.save()
        return instance

    class Meta:
        model = Module
        fields = '__all__'

class AddModule(APIView):
    def post(self, request, format=None):
        # creating the module
        module_serializer = ModuleSerializer(data=request.data)
        if module_serializer.is_valid():
            module_serializer.save()
            return Response(module_serializer.data['module_id'])
        return Response(module_serializer.errors)

Any other parts are same as yours. Regardless of whether data are sent by form-data or json raw data, results are same as below.


Q: Chrome Devs tools - where's size and content? According to Chrome Dev Tools - "Size" vs "Content", I should be able to see Size (bytes on the wire) and Content (uncompressed size).
I remember seeing this at one time.
But now (Chrome 38), I only see one measurement, and I'm not sure which one it is.

Can I see the compressed and uncompressed sizes with the Chrome Dev Tools?

A: You should press "Use large resource rows." to see more data.

A: If you are using the latest version of Chrome (like 78+), you can check "Use large request rows" under the settings icon.
Doc: https://developer.chrome.com/docs/devtools/network/reference/#uncompressed

A: I was stuck because only the name of the file was showing up (no other columns), but I realized that you must close the "details" view that shows on the right side when you click a row to see any other columns. Posting the answer here since search brought me here, though it wasn't the OP's actual issue.


Q: format of returned result for .objects.filter(name__containe=data) without quotes sign I have written a code by django in which a user can search for a word in a table of database. My problem here is when I print the returned results, they contain quotations. How can I omit them?
def My_data_filed(request):
    form = data_filed_Form(request.POST or None)
    data = None
    download_form = None

    if request.method == 'POST':
        if form.is_valid():
            data_g = form.cleaned_data.get('g')
            data = list(data_filed.objects.filter(g__contains=data_g).values())
            print(data_filed.objects.all().values())
            download_form = data_filed_DownloadForm(initial={
                'g': data_g,
            })

    return render(request, 'search_report.html',
                  {
                      'form': form,
                      'data': data,
                      'download_form': download_form
                  })

The output of this code is like:
 'Creator': 'Davide'

But I just want to have:
Davide

Whats wrong in my effort?

My code for writing the fetched result into a csv file: (Since from the comments I understood this part is related too)
def resultDownload(request):
    try:
        assert request.method == 'POST'
        form = data_DownloadForm(request.POST)
        assert form.is_valid()
        data_g = form.cleaned_data.get('g')
        data = list(data_filed.objects.filter(data__contains=g).values_list())
    except AssertionError:
        error = 'Your request has some problems.'
        data = error

    attachment = 'SearchedReport.csv'
    response = HttpResponse(content_type='text/csv')

    response['Content-Disposition'] = 'attachment;filename="{}"'.format(attachment)
    response.write(data)
    return response

A: Whenever you run a queryset like data_filed.objects.filter(g__contains=data_g).values() it always returns a dictionary kind of output with keys and values. And when you passed that result to your template file using:
return render(request, 'search_report.html',
                  {
                      'form': form,
                      'data': data,
                      'download_form': download_form
                  })

It is still in that format. If you want to output only the value, you need to output it as such
{{ data.Creator }}

That will give you the output "Davide" without the quotes


Q: I'm trying to set up a new SharePoint production server and getting an error creating an Open XML 2.5 document I have a SharePoint application written in Visual Basic that works fine and creates Word Documents using Open XML 2.5 on my development machine. We recently set up a new Production server and I published the .wsp file and deployed it on the new server. The application all works fine except the code that generates reports in Word format. It fails on the following line of code.
Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)
This is what the code looks like in the function that is failing.
''' \<summary\>
'''
''' \</summary\>
''' \<param name="MemStream"\>\</param\>
''' \<returns\>\</returns\>
Public Function WPDCreateFromStream(MemStream As MemoryStream) As WordprocessingDocument
   Try
      Dim wpd As WordprocessingDocument = WordprocessingDocument.Create(MemStream, WordprocessingDocumentType.Document, True)
      Dim MainPart As MainDocumentPart = wpd.AddMainDocumentPart()
      MainPart.Document = New Document()
      Dim DocBody As New Body()
      Return wpd
   Catch ex As Exception
      WriteErrorToEventLog("OpenXML", "WPDCreateFromStream", "", ex)
      Return Nothing
   End Try
End Function

Here is the exception detail I get when trying to make the WordProcessingDocument.Create call above.
ERROR: Source: OpenXML Routine: WPDCreateFromStream User:
Message: The type initializer for 'MS.Utility.EventTrace' threw an exception.
StackTrace:    at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)
Source: WindowsBase
Data: System.Collections.ListDictionaryInternal
InnerException: System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
The Zone of the assembly that failed was:
MyComputer
ToString: System.TypeInitializationException: The type initializer for 'MS.Utility.EventTrace' threw an exception. ---> System.Security.SecurityException: Requested registry access is not allowed.
at System.ThrowHelper.ThrowSecurityException(ExceptionResource resource)
at Microsoft.Win32.RegistryKey.OpenSubKey(String name, Boolean writable)
at Microsoft.Win32.Registry.GetValue(String keyName, String valueName, Object defaultValue)
at MS.Utility.EventTrace.IsClassicETWRegistryEnabled()
at MS.Utility.EventTrace..cctor()
--- End of inner exception stack trace ---
at MS.Utility.EventTrace.EasyTraceEvent(Keyword keywords, Event eventID)
at System.IO.Packaging.Package.Open(Stream stream, FileMode packageMode, FileAccess packageAccess, Boolean streaming)
at DocumentFormat.OpenXml.Packaging.OpenXmlPackage.CreateCore(Stream stream)
at DocumentFormat.OpenXml.Packaging.WordprocessingDocument.Create(Stream stream, WordprocessingDocumentType type, Boolean autoSave)
at FIS.SP.PSTARProjectTracker.PSTAR.Core.BusinessLogic.OpenXML.WPDCreateFromStream(MemoryStream MemStream)
TargetSite: Void EasyTraceEvent(Keyword, Event)
I know this is not an issue with the code as the same code works in development. I assume it has to do with  permissions, or getting the DocumentFormat.OpenXML.dll installed / registered correctly on the new server, but I've had no luck searching for a solution.
I tried installing OpenXML and the Productivity tool on the server. The productivity tool works and can open a word document, but the Application has the same issue.
If anyone has run into this and can point me to a solution, I would appreciate it.

The MemoryStream is created and passed in to be used by this function. The WordProcessingDocument is returned to the calling function. I could explicitly call ByVal, but in this case it would not change anything.
I am creating a new document, that is why it is coded using WordProcessingDocument.Create
Remember, this code all functions perfectly on the development SharePoint server. It has been used heavily for about a year. I'm just trying to get this to work on a new production server we recently stood up. I have to believe this is related to some permission issue, or a component that is not installed or registered correctly. For Open XML, I believe there is just the one DLL (DocumentFormat.OpenXML.DLL) and it does not register. It is on the server from installing the .wsp package. I also tried installing Open XML 2.5 on the server along with the productivity tool and they all work fine.
The more I think about it, it just feels like a permission issue.


Q: Reporting Services: How To Fit PDF Export On One Page? I've built a report in Reporting Services and when we browse to the report in Internet Explorer we want to be able to export the report in PDF format.  It works, but it was cutting off the columns to the right and displaying them on the next page (in PDF) because the page was too wide.  I changed the orientation to landscape and it still cut off the columns on the right.  Then I changed the page size to legal paper and it fits on one page, but we want the report on letter size paper.  Is there a way to compress the report to fit on letter size landscape?

A: Here is how to get a report to fit on a letter page:

*

*Click on the blank space outside of your report

*Look at the properties and find interactive size. Set it to 11,8.5in.  Set your Margins to 0.5in, 0.5in, 0.5in, 0.5in

*Click on the body and select properties.  Set the width to 10in and something less than 7.5 for the height.

A: I was having this issue too. I set my margins to zero, which allowed me to print on 1 pdf page instead of 2.

A: When you develop report from SpagoBI Studio
change setting of Master Page (next to Layout).
No need to change orientation but you need to
increase the width of report according to your number of columns and column with.
make sure it is greater than sum of all column's width (table width)
This will solve the issues


Q: Because the plugin below does not work when used in the response of a getJSON (function ($) {
    $.fn.reverse = function(fn) {
       var i = this.length;
       while(i--) {
           fn.call(this[i], i, this[i])
       }
    };
}(jQuery));

Below the use of jquery code with alphabetical data
$.fn.reverse ($response, function (k, v) {
    $("#selector").append('
' + v.name + '
');
});

A: You need to apply the plugin to any jQuery object, so you need to do something like this to use the plugin.
$($response).reverse(function (k, v) { /*.. code here ...*/ });
//-^^^- wrap using jQuery if it's not a jQuery object

Refer : How to Create a Basic Plugin


Q: Remove layers and objects in FabricJS My question is, how to remove object and layer in same time using fabricJS delete function?
Here is my jQuery for deleting objects:
$('#remove').on('click', function () {
    deleteObjects();
    $(".deleteBtn").remove();
});

Here is my FabricJS example with layer control https://jsfiddle.net/peLcju2h/15/
Thank you :)

A: If you take a look through the Fabric JS documentation you'll notice that every object extends the Fabric.Object.
The Fabric.Object has a remove() method that you can call to remove any Fabric.Object or class that extends Fabric.Object, which is just about every class that can be rendered onto a canvas, with the exception of a handful of less commonly used classes.
Take a look at the documentation of the remove() function here:
http://fabricjs.com/docs/fabric.Object.html#remove
Also there is a hierarchy of classes on the main page of their documentation which can be found here:
http://fabricjs.com/docs/


Q: Refresh UltraCombo Content I have to do some maintenance on an old VB.NET application (Visual Studio 2003) that uses Infragistics NetAdvantage 2006. I have a UltraCombo control binded to a DataView.
How can I refresh the content displayed after a change in the database?

A: It sounds like you'll need to repopulate the DataView from the database and refresh your databinding on the UltraCombo; probably pretty close to the same code you use to initially populate the DataView and set the UltraCombo databinding.
You may get a more complete answer if you post some code.


Q: LINQ-to-SQL not submitting changes to local database I have a local, SQL Server Compact database in an application I am creating. I generated a .dbml file I can use for LINQ-to-SQL purposes using the SqlMetal.exe tool, which worked fine - I now have the table objects for use in my application.
I have a strange issue though. Even after calling SubmitChanges() on my DataContext, the data never commits. But strangely, after adding the rows, these rows do appear in the table object on the datacontext, but not in the table. What shocked me is even after stopping and starting my application, these rows still existed in the DataContext - but after a few minutes they seem to disappear.
Have I configured this correctly? Are there any more steps I need to do after using SqlMetal to allow the LINQ to commit changes?

A: I am assuming that you linked to the dbml file using the default properties.  This means that, each time you start a debug session, the file will be copied into your output directory and changes made to it will only be seen for that session (i.e., "Copy -> Always").
If you want the changes to persist then right click the file -> properties -> Copy Never.  By default the IDE assumes that you don't want to modify the original database, only a copy for debugging purposes.


Q: Not getting Form value, in java I have a form and bean. From bean I am retreiving values and setting in DTO. That is also setting in FORM. But getter property value is null. I don't know what is the problem here. Can anybody suggest on this?
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;

public class LoginForm extends XFormBase {
    private String title;

    public void setTitle(String title) {
       this.titleValue = title;
       System.out.println(" Form set"+titleValue);
    }

    public String getTitle() {
       this.title = titleValue;
       System.out.println(" Form get"+titleValue);
       return title;
   }
}

A: It looks like there is an bug:
the setTitle method, does not set the title but the titleValue!
I would guess the correct implementation is:
public void setTitle(String title) {
   this.title = title;
   System.out.println(" Form set"+title);
}

A: Try using this. I suspect a mistake in your getter and setter implementation
public class LoginForm extends XFormBase {
    private String title;

    public void setTitle(String titleValue ) {
       this.title= titleValue;
       System.out.println(" Form set"+this.title);
    }

    public String getTitle() {
       System.out.println(" Form get"+this.title);
       return this.title;
   }
}