text:
Q: Can you explain this dart json parsing code please? So i have this code that works somehow, however i can't really explain why.
To get this code i used an automatic json to code application called quicktype using as input a json that my company provides. The goal of the code is obtaining a Map containing polygons in this format : {(Random ID of polygon)} ==> [Lat,Lon]
class Poligoni {
  Map<String, List<String>> poligoni;
  Poligoni({
    this.poligoni,
  });
  factory Poligoni.fromRawJson(String str) {
    return Poligoni.fromJson(json.decode(str));
  }

  factory Poligoni.fromJson(Map<String, dynamic> json) {
    return Poligoni(
      poligoni: Map.from(json["Poligoni"]).map((k, v) {
        return MapEntry<String, List<String>>(
            k, List<String>.from(v.map((x) => x)));
      }),
    );
  }
}

So the code either accepts a raw json from the (.fromRawJson) function or a decoded one from (.fromJson)  function. No problems here. The part that confuses me is this one :
factory Poligoni.fromJson(Map<String, dynamic> json) {
    return Poligoni(
      poligoni: Map.from(json["Poligoni"]).map((k, v) {
        return MapEntry<String, List<String>>(
            k, List<String>.from(v.map((x) => x)));
      }),
    );
  }

The problems i have understanding this are(.fromJson function):

*

*Why i return a Class? example: return Poligoni(.....various code)

*The use of the redirecting constructor in not very clear in this case to me poligoni:

*A lot of difficulty undestanding the function after poligoni: : i know that the function parses the json key 'Poligoni' and transform this in another map of type <String>,List<String>
that contains for every key a list of points which form a polygon however i am not sure how, if you can write a step-by-step walk through it will be greatly appreciated or in alternative if you can reformat this code to make it clearer.

I tried looking through dart and flutter docs but i didn't unterstand most of it because of the nested functions that my code uses and a little bit of language barrier.
Any help is greatly aprreciated,
Best Regards.

A:
Why i return a Class? example: return Poligoni(.....various code)

Because you are using a factory constructor. A factory constructor is like a static method but your are required to return an instance of an object that are compatible with the class it is part of.
One advantage of this pattern is that when using a normal constructor, you are not allowed to set any final variables inside the constructor body but needs to set them as part of the initializing phase.
In you case, this is really not a problem since the variable Map<String, List<String>> poligoni is not final but it can still be a nice pattern.
Read more about factory constructors here:
https://dart.dev/guides/language/language-tour#factory-constructors

The use of the redirecting constructor in not very clear in this case to me poligoni:

See my previous answer.

A lot of difficulty undestanding the function after poligoni: : i know that the function parses the json key 'Poligoni' and transform this in another map of type ,List that contains for every key a list of points which form a polygon however i am not sure how, if you can write a step-by-step walk through it will be greatly appreciated or in alternative if you can reformat this code to make it clearer.

factory Poligoni.fromJson(Map<String, dynamic> json) {
    return Poligoni(
      poligoni: Map.from(json["Poligoni"]).map((k, v) {
        return MapEntry<String, List<String>>(
            k, List<String>.from(v.map((x) => x)));
      }),
    );
  }

As previous stated we have defined a factory constructor which must return an object which are compatible with the class it is part of. In this case we therefore creates a new Poligoni object by calling the constructor of Poligoni which takes a named argument poligoni. This is why we have poligoni:.
We are setting the named argument poligoni to the value of the following statement:
Map.from(json["Poligoni"]).map((k, v) {
        return MapEntry<String, List<String>>(
            k, List<String>.from(v.map((x) => x)));
      })

I am not really sure why we are using Map.from but the purpose of this constructor is to create a new map based on the key-values from another map:
https://api.dart.dev/stable/2.10.4/dart-core/Map/Map.from.html
(personally, I would have used a typecast from json["Poligoni"] since this must be a Map instance)
We are then calling .map on this new Map to create another new Map but where each key-value pair is mapped to new key-value pairs by the following method:
(k, v) {
        return MapEntry<String, List<String>>(
            k, List<String>.from(v.map((x) => x)));
      }

We can see here we are keeping the original key k but are converting the value v with:
List<String>.from(v.map((x) => x))

My guess here is that v is List<dynamic> and we want to create a new list of the type List<String> by taking each element of List v and inserting it into a new List which has been defined as List<String> from the start.
The result of this is then used as value in our new Map which are then used as value for the poligoni argument.
In short, all of this operations are really used for making your code more type safe by converting dynamic types into statically determined types.


text:
Q: Twitter bootstrap: do I need both bootstrap-sass and twitter-bootstrap-rails gems? I have the following entries my (Rails 3.2.13) Gemfile:
gem 'twitter-bootstrap-rails'
gem 'bootstrap-sass'

and in app/assets/javascripts/application.js:
//= require twitter/bootstrap

and at the top of app/assets/stylesheets/custom.css.scss:
@import 'bootstrap'

Is this "correct"?  Do I need both 'twitter-bootstrap-rails' and 'bootstrap-sass' (or maybe 'bootstrap-sass-rails'), or are they redundant and possibly conflicting?  Do the 'bootstrap-sass' gems include the javascript for the framework, or only the CSS?

A: No you do not need both.
Just simply put this in your gemfile:
gem 'sass-rails'
gem 'bootstrap-sass'

This in application.css.scss:
@import 'bootstrap';
@import 'bootstrap-responsive';

This in application.js
//= require bootstrap

If you're still having problems you may need to look at the ordering of things in your manifest files..

A: If you want to use SASS you should use boostrap-sass or bootstrap-sass-rails. Twitter-bootstrap-rails uses LESS source. If you were to include both there would probably be conflicts. All of them include javascript for bootstrap already and integrate into the asset pipeline.
I personally use LESS version as it is what bootstrap is originally written in. (might get faster releases when bootstrap updates)
It's generally good to check the gems out on github to evaluate your exact needs and which version of Rails they support.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Entity Framework Include with two foreign Keys I have a Team table and a Matches table.
Team table:
Id Name
------------
1  TeamA
2  TeamB

If TeamA desires to play TeamB we will add a row in the Matches table
Matches table:
Id HomeTeamId RivalTeamId
-------------------------
1       1          2

If TeamB desires to challenge TeamA we will go about do the following
Matches table:
Id   HomeTeamId   RivalTeamId
-----------------------------
 1       1             2
 2       2             1

My Team and Match POCO (only relevant code) look like this:
public class Team : BaseEntity
{
        public int Id { get; set; }
        public string Name { get; set; }

        public ICollection<Match> HomeMatches { get; set; }
        public ICollection<Match> RivalMatches { get; set; }
}

public class Match : BaseEntity
{
        public int Id { get; set; }
        public string Description { get; set; }

        //navs
        public Team HomeTeam { get; set; }
        public int HomeTeamId { get; set; }

        public Team RivalTeam { get; set; }
        public int RivalTeamId { get; set; }
}

Problem: I guess the experts can already notice a possibility of a cycle up there that I'll come across during query. My problem is that I would like to query TeamA's matches. I would do the following for that
 Team team= dbContext.Team.
                Include("HomeMatches").

In the above team object I notice that BOTH the properties HomeMatches and RivalMatches appear filled.
I would just want the HomeMatches properties filled. I am only interested in those matches which TeamA has chosen to play, not in those where TeamA is a rival.
My question is that when I am clearly mentioned Include("HomeMatches"), why is the RivalMatches property also filled?

A: You can try using Explicit loading as in here


text:
Q: Is the "Constant Rank Theorem" the same as the "Domain Straightening Theorem"? Which theorem is which? Wikipedia says that the inverse function theorem is a special case of the "constant rank theorem".
I'm pretty sure this is supposed to be the same theorem as the "Rank Theorem" on p. 47 of Boothby (especially because the wikipedia article also footnotes to Boothby...), and then in Boothby, he says in a footnote that it is also known as the "Straightening Out Theorem."
Wikipedia also has an article on a "Domain Straightening Theorem".
Which seems vaguely related but does not explicitly discuss anything about rank.
Could someone please help me sort out which theorem is which? My main goal is to find a more in-depth discussion of the "Constant Rank Theorem" (or whatever the true general case of the IFT is) (reading suggestions welcome!), but I would also like to know which of these names refers to the same theorem, and which doesn't.

A: I think they are both standard theorems in differential manifolds, and they actually occur without the name given now. For example, in other books the constant rank theorem was referred to as the normal form of a submersion/immersion map.
As others said, the two theorems are different and both can be proved using inverse function theorem carefully. The first one tells you locally a differentiable map between two manifolds near a regular point can be viewed as a linear map in appropriate local coordinates. The second tells you that locally a vector field at a regular point can be viewed as given by the coordinate vector field $\{ \partial_{x_i}\}$, where $x_{i}$ are the coordinate functions. Since a vector field is a section of the tangent bundle, and a tangent vector is defined (partly) as maps $C^{\infty}(M)_{p}\rightarrow F$, I do not think the two theorems are the same or can be "translated".


text:
Q: Map marker moves when zooming in and out with google-map-react I am adding a map with a marker marking a fixed location in my React app, all works fine, but if I zoom out, the marker moves around and goes further to the right of where it should do.

import GoogleMapReact from 'google-map-react';
import { Icon } from '@iconify/react'
import locationIcon from '@iconify/icons-mdi/map-marker'
import './map.css'

interface Props {
  location: {
    address: string,
    lng: number,
    lat: number
  }
}

  const LocationPin = ({ address }: Props["location"]) => (

      <Icon icon={locationIcon} className="pin-icon" style={{ fontSize: '60px' }} />

{address}

  )

export default function SimpleMap(){
  const defaultProps = {
    center: {
      lat: 53.5050,
      lng: -2.0300
    },
    zoom: 12
  };

  return (
    // Important! Always set the container height explicitly

      <GoogleMapReact
        bootstrapURLKeys={{ key: `${process.env.REACT_APP_GOOGLE_API_KEY}`
              }}
        defaultCenter={defaultProps.center}
        defaultZoom={defaultProps.zoom}

      >
      <LocationPin
        lat={defaultProps.center.lat}
        lng={defaultProps.center.lng}
        address='Stamford golf club'
      />
      </GoogleMapReact>

  );
}

The css class on the pin is just setting it's size. I have tried removing the css file to see if this made a difference but it doesnt.


text:
Q: Why is linear regression considered an ill-posed problem? Could someone please explain to me why exactly linear regression is considered ill-posed?

A: According to Wikipedia, a problem is well-posed if:

*

*a solution exists,

*the solution is unique,

*the solution's behaviour changes continuously with the initial conditions.

Now suppose that you have a dataset $(X, y)$ consisting of samples $(x_i, y_i)_{i = 1}^m$, with $x_i \in \mathbb{R}^n$, $y_i \in \mathbb{R}$. I suppose that you think of linear regression as of the following problem for weights $w$ of the regression: $X w = y$ (or something similar depending on how do you stack samples in the matrix).
This problem is ill-posed because of the following reasons:

*

*the solution is not unique if you have too few samples, namely $m < n$ (for example, there are infinitely many straight lines going through a given point in $\mathbb{R}^2$);

*the solution may not exist if you have too many samples, namely $m > n$ (for example, there are not straight lines going through three given points in $\mathbb{R}^2$);

*finally, there is multicollinearity issue which contradicts the last necessary condition of weight estimates being continuous in observations.

However, the problem can be adapted to fix these properties. Modifying the problem to $\|Xw - y\|_2^2 \to \min$ allows obtaining a pseudo-solution when there is no exact solution (the problem is still ill-posed because there may be many solutions).
You can also add Tikhonov regularization (a.k.a. ridge in the setting of regression) to get $\|Xw-y\|_2^2 + \lambda \|w\|_2^2 \to \min$ which allows selecting one solution if there are many solutions of the original problem.


text:
Q: What's the PHP $_SERVER variable for the directory above DOCUMENT_ROOT? I have a server where the public root is located at: /var/www/example.com/html/.
Using $_SERVER['DOCUMENT_ROOT']); I get the following result:
/var/www/example.com/html/

What $_SERVER array key would I use to get the path directly above the public root? That is, the one here:
/var/www/example.com/

This will have to work on multiple environments, such as local and live. Not sure if there's some way of doing ./ document_root sort of thing.

A: dirname() returns the parent directory of a directory and is platform independent.
dirname($_SERVER['DOCUMENT_ROOT']);

Should return:
/var/www/example.com

If you need the trailing slash then you can append DIRECTORY_SEPARATOR:
dirname($_SERVER['DOCUMENT_ROOT']) . DIRECTORY_SEPARATOR;

A: ../ is the unixey way to say the folder above so, for example, in a terminal these are the same thing:
/home/user/
/home/user/heavymark/../
If OTOH you need support for Windows directory naming you will have to do the work of removing the last bit of the path. Normally you might do this by using a regular expression to capture all but the last filepathbit/ but to support Windows naming you have to fancy it up to handle both filepathbit/ and filepathbit.


text:
Q: Union-find: largest component size by common factor algorithm gives different results on every run I was practicing data structure algorithm and made a Union - Find solution for the question.
The problem is, I think the code seems ok, but when I run it on Xcode playground, it shows different answers for the same input.
For example, I put an array [4, 6, 15, 35] in the function largestComponentSize, then it shows 2, 3, or 4 as the answer. I don't understand what's happening behind.
class Solution {
    var uf = UnionFind()

    func largestComponentSize(_ nums: [Int]) -> Int {
        var maxNum:Int = 0
        var numFactorMap = [Int:Int]()
        var factorAdded = Set<Int>()
        for num in nums {
            var pFactors = getPrimeFactors(num)
            numFactorMap[num] = pFactors[0]
            for (i, val) in pFactors.enumerated() {
                if !factorAdded.contains(val) {
                    uf.addSet(val)
                    factorAdded.insert(val)
                }
                if i > 0 {
                    uf.union(pFactors[i-1], val)
                }
            }
        }

        var groupCountMap = [Int:Int]()

        for num in nums {
            var groupId = uf.find(numFactorMap[num]!)!
            if groupCountMap.keys.contains(groupId) {
                groupCountMap[groupId]! += 1
            } else {
                groupCountMap[groupId] = 1
            }
            maxNum = max(maxNum, groupCountMap[groupId]!)
        }

        return maxNum
    }

    func getPrimeFactors(_ num: Int) -> [Int] {
        var ans:Set<Int> = []

        if num == 1 {
            return []
        }

        var crrNum = num
        var deno = 2
        while crrNum >= deno {
            if crrNum % deno == 0 {
                ans.insert(deno)
                crrNum = crrNum / deno
            } else {
                deno = deno + 1
            }
        }

        return Array(ans)
    }

    class UnionFind {
        var index = [Int: Int]()
        var parent: [Int]
        var size: [Int]

        init() {
            parent = []
            size = []
        }

        func addSet(_ ele: Int) {
            index[ele] = parent.count
            parent.append(parent.count)
            size.append(1)
        }

        func getSetSize(_ ele: Int) -> Int {
            if let found = find(ele) {
                return size[found]
            }
            return 0
        }

        func find(_ ele: Int) -> Int? {
            if let indexOfEle = index[ele] {
                if parent[indexOfEle] == indexOfEle {
                    return indexOfEle
                } else {
                    if let found = find(parent[indexOfEle]) {
                        parent[indexOfEle] = found
                    }
                    return parent[indexOfEle]
                }
            } else {
                return nil //never come here
            }
        }

        func union(_ first: Int, _ second: Int) {
            guard let indexOfFirst = index[first], let indexOfSecond = index[second] else {
                return
            }

            if parent[indexOfFirst] == parent[indexOfSecond] {
                return
            }

            var indexOfLarger = indexOfFirst
            var indexOfSmaller = indexOfSecond
            if size[indexOfFirst] < size[indexOfSecond] {
                indexOfLarger = indexOfSecond
                indexOfSmaller = indexOfFirst
            }

            parent[indexOfSmaller] = indexOfLarger
            size[indexOfLarger] += size[indexOfSmaller]

            return
        }
    }
}

var sol = Solution()
var nums = [4, 6, 15, 35]
var ans = sol.largestComponentSize(nums)

Thank you for your help in advance!
I just tried it on Xcode playground.


text:
Q: Why this way to detect machine storage methods is incorrect? (Using C language) I missed a problem when I doing my homework.
Computer memory in the storage of data where there are big-endian storage and small-endian storage two methods, in order to detect a machine storage method, a student wrote the following procedure:
union NUM {
    int a;
    char b;
} num;

int main(){
    num.b = 0xff;
    if (num.a! = 0xff)
        printf ("bigend");
    else
        printf ("smallend");
    return 0;
}

But he found the program running on the x86 machine, print out is actually 'bigend', which is clearly wrong. Do you know where the problem is?
How should this program be modified?
I have asked my teacher, the topic is correct. I have found some information in some websites, but it makes me more confused. Why this question is not incorrect? And where the problem actually is?

A: Assuming an int (and therefore the union as a whole) is 4 bytes, writing to num.b only writes to one of those 4 bytes, leaving the rest uninitialized.  Subsequently reading num.a reads those uninitialized bytes, invoking undefined behavior.
The bytes in the union must be set to all 0s so that the content is well defined.
#include <stdio.h>
#include <string.h>

union NUM {
    int a;
    char b;
} num;

int main(){
    // set all bytes of num to 0 first
    memset(&num, 0, sizeof(num));
    num.b = 0xff;
    if (num.a! = 0xff)
        printf ("bigend");
    else
        printf ("smallend");
    return 0;
}

A: Type-punning is undefined behavior in C. When you read num.a you are violating the strict aliasing rules, so the compiler is allowed to generate code that may give back anything. Which it does.
To avoid this, you need to use memcpy():
int a = 0x00010203;
char bytes[sizeof(a)];
memcpy(bytes, &a, sizeof(a));
if(bytes[0] == 03) {
    printf("small endian\n");
} else ...


text:
Q: How to call a component from 2 diiferent routes in angular? I have a userDetails component that can be accessed from two different pages in my application.
It can be accessed from searchUser component and I have a "my account" menu in the header that is available across the application and it is in MenuComponent. I should take the user to the user details page from search page as well as my account menu. I'm using router.navigate to navigate to the details page. It's working fine from the search results page.
However, when I click the "My account" link it is hitting the userDetails component and when it hits the function that calls the service to fetch the data it is not calling the API and comes out of the function and takes me to the homepage. The URL is same from both the places.
I used console.log to log the activatedroute.routeconfig.path, it is /users/:userId when I call from search results and /home when I call from MyAccount link.
Where am I going wrong?


text:
Q: ¿Como esperar en un servicio que un procedimiento en termine? les cuento que estoy trabajando en una Aplicación en Angular, .Net Core y SQL Server, tengo un procedimiento que hace un gran calculo por lo tanto se puede demorar hasta 30 minutos, lo que quiero hacer es que el usuario pueda ejecutar esa acción de manera asíncrona en el front, es decir que el usuario de desentienda y pueda seguir haciendo otras cosas, entonces el servicio invoque el SP y espere a que este se ejecute completamente, estuve tratando de ejecutar  el SP en el servicio pero me genera un error de timeout, vi que se puede aumentar este tiempo pero quisiera otra solución u otra forma de hacer esto. Básicamente quiero que la ejecución en base de datos se mantenga viva.

A: Te recomiendo leer sobre los procesos sincronos y asincronos en tu caso necesitas uno sincrono.

A: Podrias utilizar HangFire para encolar el proceso y que se ejecute en segundo plano


text:
Q: Можно ли в VS Code сделать автоматическое удаление exe-файла после того, как отработала программа на C++? Я занимаюсь олимпиадным программированием на C++ и на каждую задачу создаю отдельный файл, например, 1.cpp для первой задачи, 2.cpp для второй и т. д.
Когда я запускаю файл с помощью Code Runner, автоматически создается файл 1.exe (или 2.exe, в зависимости от имени файла cpp) в той же папке. После того, как программа отработала, этот exeшник остается.
В итоге, если я решаю олимпиаду, где 20 задач, у меня в итоге в папке получается 20 файлов *.cpp и 20 файлов *.exe.
Можно ли сделать так, чтобы exeшник автоматически удалялся сразу, как только программа отработает?
Или, например, сделать так, чтобы при запуске Code Runner, создавался не exeшник в текущей папке с таким же именем, как *.cpp, а файл a.exe (который бы создавался в корневой папке), который автоматически создается при отладке любого файла, который находится в любой папке.


text:
Q: Hide div when clicking outside div and siblings I want to hide the div "auto" ONLY when you click outside of that div.
At the minute if you click on "more-stuff" it will hide the div because you are not clicking on "auto". So i guess my question is how to include the siblings in the IF statement (there could be many divs inside by the way but "more-stuff" is just an example).

      HIDE ALSO WHEN YOU CLICK IN HERE!

 jQuery(document).click(function(e) {
     if( e.target.id != 'auto') { // Hide when click outside of layer
         jQuery("#auto").hide();
     }
 });

I expect clicking on sibling elements to NOT close the div also

A: You can use .closest() to check if the event target have parent with id #auto or not.
Demo:

$(document).click(function(e) {
    if (!$(e.target).closest("#auto").length) {
      $('#auto').hide();
    }
 });
#auto {
  background-color: red;
}

      HIDE ALSO WHEN YOU CLICK IN HERE!

A:

   Will Not Hide here

      NOT HIDE ALSO WHEN YOU CLICK IN HERE!


text:
Q: java math calculation for coordinates of circle given radius of 1.00 In one of my assignments, I am asked to write a program to calculate the (x, y) coordinates of points on a circle of radius 1.0. Display the output of y values for all x values ranging from 1.00 to negative 1.00 by increments of 0.1 and display the output neatly using printf, where all the x values are aligned vertically and to the right of all the x values, the y values are aligned vertically like:
 x1    y1
1.00  0.00
0.90  0.44

I know how to calculate the y values by using the Pythagorean theorem, but I don't know how to display every x and y values neatly by using a loop and formatting it with printf Below is my code that I have so far, any help will be greatly appreciated:
public class PointsOnACircleV1 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    // TODO code application logic here

    // // create menu

    // create title
    System.out.println("Points on a circle of Radius 1.0");

    // create x1 and y1
    System.out.println("          x1                         y1");

    // create line
    System.out.println("_________________________________________________");

    // // display x values

    // loop?

    // // perform calculation

    // radius
    double radius = 1.00;

    // x value
    double x = 1.00;

    // calculate y value
    double y = Math.pow(radius, 2) - Math.pow(x, 2);
}

}

A: public static void main(String[] args) {

    double radius =  1.00;
    double x  , y ;

    for ( x=-1.0 ; x<=1.0; x+=0.2 ) {
        y = Math.sqrt(radius - Math.pow(x,2)) ;
        System.out.printf("\n" + x +"     "+ y);
    }
}

The code within loop you can adjust them according to your need.

A:  public class PointsOnACircleV1
 {
  public static void main (String [] args)
{
    double r = 1; //radius initialized to one

    double x = 1; // x coordinate initialized to one, could be anything
    double y = 0.0; // y coordinate is dependent so left at 0.

    //output
    System.out.println("\tPoints on a Circle of Radius 1.0");
    System.out.printf("\t%6s%6s%12s%7s\n", "x1", "y1", "x1", "y2");
    System.out.println("--------------------------------------------");

    //for loop to decrement values from the initialized x coordinate to the
    //end of the diameter, radius is 1 so diameter is 2 so 1 to -1.
    for(x = 1; x >= -1; x -= .1)
    {
        y = Math.sqrt(Math.pow(r,2) - Math.pow(x,2)); //pythagorean theorem to achieve y value.
        System.out.printf("\t%6.2f%7.2f%12.2f%8.2f\n", x, y, x, -y); //output, -y to get values
        //for the other 1/2 of the circle
    }
}

}

A: for(int i=100; i>=-100; i-=10) {
    x = i/100.0;
    //do stuff
    System.out.print("\t%.2f\t%.2f", x, y);
}

That should get you started.  If you don't understand the part within the parenthesis of the System.out.print statement, I suggest you look up what System.out.print does, look up format specifiers, and look up escape characters.  Then you should be all set.


text:
Q: windows 7 64 bits didn't found win32comm i wanted to list the serial port available on my pc so i used javax.comm library,and i got a problem with win32com.dll it doesn't work on my windows 7 64 bits is that version is for windo 32 bits or also for 64 bit too ? because i didn't find a link of win32com.dll for windows 7 64 bit , please can you help me to find that link ? and that's why i get when i run my program .
and thank you.


text: Q: How does R2-D2 not remember Yoda or Dagobah R2-D2 joined Yoda on a trip to Dagobah in the episode "Voices" from season 6.  R2-D2 did not have his memory wiped.  Why did R2 not tell Luke that he's been there before with Yoda?  I know it was a long while after, probably around 22 years, but I feel like I must be missing something...


text:
Q: Shopify Checkout/update webhook not firing We are developing an app that utilises a bunch of shopify webhooks.
We can get most of the webhooks to trigger except a few, would anyone be able to suggest what store action(s) I would need to take in order to trigger the following webhooks
checkouts/create, checkouts/update
product_listings/add, product_listings/update


text:
Q: How to plot Clebsch surface with those 27 lines? I can get its Algebraic Equation by this code:
Entity["Surface", "ClebschDiagonalCubic"][EntityProperty["Surface", "AlgebraicEquation"]]

Then get its graphics:
ContourPlot3D[81 (x^3 + y^3 + z^3) - 9 (x^2 + y^2 + z^2) -
   189 (x^2 y + x^2 z + x y^2 + x z^2 + y^2 z + y z^2) + 54 x y z -
   9 (x + y + z) + 126 (x y + x z + y z) - 1 == 0, {x, -1, 1}, {y, -1,
   1}, {z, -1, 1}, Boxed -> False, BoxRatios -> {1, 1, 1},
 AxesOrigin -> {0, 0, 0}, AxesStyle -> {Red, Green, Blue}, Mesh -> None]

As we know, there are 27 lines in its surface:

But I don't know how to draw these lines onto the surface

A: EDIT:
With help from @cvgmt, both fixing a wrong term in the equation(!) and adding constraints for finding lines:
With[{expr =
   1 + 54 x y z - 9 (x + y + z) + 126 (x y + x z + y z) -
     9 (x^2 + y^2 + z^2) -
     189 (x^2 y + x y^2 + x^2 z + y^2 z + x z^2 + y z^2) +
     81 (x^3 + y^3 + z^3) == 0},
 (* Expression over a parametric infinite line. *)
 expr /. Thread[{x, y, z} -> {a, b, c} + t {u, v, w}] //
    (* Find lines which lie on the surface. *)
    Solve[
      (* Expression must be true for all t,
      that is, it must lie on the surface everywhere. *)
      Resolve[ForAll[t, #]] &&
       (* Constrain solutions:
       line offset and line direction vectors must be at right angle,
       and line direction vector must be unit length. *)
       {a, b, c} . {u, v, w} == 0 && u^2 + v^2 + w^2 == 1 &&
       (* Prevent finding lines with "direction" negated. *)
       ((w > 0) || (w == 0 && v > 0) || (w == 0 && v == 0 && u > 0)),
      {a, b, c, u, v, w}, Reals] & //
   (* Line segments inside the plotted area. *)
   RegionIntersection[
      InfiniteLine[{a, b, c}, {u, v, w}], Ball[]] /. N[#] & //
  (* Create animated graphics. *)
  Animate[
    Show[
     (* Plot the surface. *)
     ContourPlot3D[expr, Element[{x, y, z}, Ball[]],
      PlotPoints -> 100, ContourStyle -> Opacity[9/10], Boxed -> False,
      BoxRatios -> Automatic, Axes -> None, Mesh -> None,
      RegionBoundaryStyle -> None,
      SphericalRegion -> True, ViewAngle -> 10 Degree,
      ViewPoint -> Dynamic[{5 Sin[a], 5 Cos[a], 5/2}]],
     (* Plot line segments. *)
     Graphics3D[{Thick, CapForm["Butt"], #}]],
    {a, 0, 2 Pi}] &]

Original answer:
This is more of an extended comment - but anyway, it would seem that Mathematica has at least some success finding those lines on the surface:
With[{eqn = -1 + 54 x y z - 9 (x + y + z) + 126 (x y + x z + y z) -
    9 (x^2 + y^2 + z^2) -
    189 (x^2 y + x y^2 + x^2 z + y^2 z + x z^2 + y z^2) +
    81 (x^3 + y^3 + z^3)},
 CoefficientList[eqn /. Thread[{x, y, z} -> {a, b, c} + t {u, v, w}],
        t] & // Map[# == 0 &] //
     Solve[
       And @@ # && {a, b, c} . {u, v, w} == 0 &&
        u^2 + v^2 + w^2 == 1, {a, b, c, u, v, w}, Reals] & // N //
   RegionIntersection[InfiniteLine[{a, b, c}, {u, v, w}],
      Cuboid[{-1, -1, -1}, {1, 1, 1}]] /. # & //
  ListAnimate@
    Table[
     Show[ContourPlot3D[eqn == 0, {x, -1, 1}, {y, -1, 1}, {z, -1, 1},
       PlotPoints -> 50, ContourStyle -> Opacity[9/10],
       Boxed -> False, BoxRatios -> Automatic, Axes -> None,
       Mesh -> None, SphericalRegion -> True,
       ViewPoint -> {5 Sin[a], 5 Cos[a], 5/2}],
      Graphics3D[{Thick, #}]],
     {a, 0, 2 Pi - Pi/64, Pi/64}] &]

A: Provide a more concise solution:
expr = 1 + 54 x y z - 9 (x + y + z) + 126 (x y + y z + z x) -
   9 (x^2 + y^2 + z^2) -
   189 (x^2 y + x y^2 + y^2 z + y z^2 + z^2 x + z x^2) +
   81 (x^3 + y^3 + z^3);
sols = Solve[{Resolve[
     ForAll[t, (expr /.
         Thread[{x, y, z} -> {a, b, c} + t {u, v, w}]) == 0]], {a, b,
       c} . {u, v, w} == 0, u^2 + v^2 + w^2 == 1,
    w > 0 || w == 0  && v > 0 || w == 0 && v == 0 && u > 0}, {a, b, c,
     u, v, w}, Reals];
Show[ContourPlot3D[expr == 0, {x, -2, 2}, {y, -2, 2}, {z, -2, 2},
  Mesh -> None, PlotPoints -> 60, MaxRecursion -> 4,
  ContourStyle -> Cyan],
 Graphics3D[{White, InfiniteLine[{a, b, c}, {u, v, w}] /. sols}],
 Boxed -> False, Axes -> False, ViewPoint -> Front]

Explanation

*

*We can get the lines in the surface by the parametric equation of a line to combine the original equation to get eqns.

*Since the original equation is $0$, We can let the equation of the substituted line be constant $0$

*I assumed that the line was translated through the origin to the surface:

So it has to satisfy:{a,b,c}.{u,v,w}==0

*Since {u,v,w} is a vector, we can assume that it's distributed along the circumference of the unit circle. So it meet:u^2+v^2+w^2==1

*Now, one last problem, we solve the equation this way and we get $54$ solutions. Because MMA can't tell the difference between $-vec$ and $vec$ being the same vector. We have to limit it with some conditions:
 ((w > 0)(*At an acute Angle to the w axis*)
   || (w == 0 && v > 0)(*Perpendicular to the w axis but at an acute Angle to the v axis*)
   || (w == 0 && v == 0 && u > 0)(*Perpendicular to both the w and v axes,but at an acute Angle to the u axis*))

But I have an additional puzzle: Why can I only solve three lines on a cubic surface $x^3 + 3 y^3 + z^3-2 x^2 + 5 x y - x + 7=0$? Why can't I get $27$ too as this statement?


text:
Q: Ошибка - "Не удалось отправить некоторые ссылки в Гитлаб" Создал репозиторий на гитлаб, затем инициализировал Гит в своем проекте на компьютере. Столкнулся с ошибкой. " не удалось отправить некоторые ссылки в «https://.........» "
подсказка: Обновления были отклонены, так как внешний репозиторий содержит
подсказка: изменения, которых у вас нет в вашем локальном репозитории.
подсказка: Обычно, это связанно с тем, что кто-то уже отправил изменения в
подсказка: то же место. Перед повторной отправкой ваших изменений, вам нужно
подсказка: забрать и слить изменения из внешнего репозитория себе
подсказка: (например, с помощью «git pull …»).
подсказка: Для дополнительной информации смотрите «Note about fast-forwards»
подсказка: в «git push --help».

Помогите пожалуйста, боюсь ошибиться со своими дальнейшими действиями...
При создании репозитория на гитлабе, автоматически был создан файл readme. При инициализации локального репозитория и создании коммита встает ошибка. Дело в этом файле? Он пошел первым коммитом при создании репозитория на сервисе


text:
Q: hacer un subquery con un where dentro, laravel tenía un query en el cual podía hacer todo en la misma consulta, el query era
return Place::doesntHave('locationGroupPlace')->has('site')->limit($limit)->get();

pero ahora necesito reemplazar esto, ya que necesito hacer otra consulta, la relación 'site', tiene una columna llamada 'state'.
necesito hacer exactamente la misma consulta, pero esta vez "donde un site tenga la columna state con valor 1"
he intentado haciendo esto
    $place = Place::doesntHave('locationGroupPlace')->with(['site' => function ($query) use ($limit) {
        $query->where('state', '=', 1)->take($limit)->get();
     }]);
    return $place;

pero no obtengo ningún resultado, así que me está saliendo mal.
Cómo puedo resolverlo?

A: prueba de esta manera
 $place = Place::doesntHave('locationGroupPlace')->has('site')->with(['site' => function
 ($query) {
        $query->where('state', '=', 1);
 }])
 ->take($limit)
 ->get();

 return $place;

No es necesario que apliques el get(); ya que Laravel solo esta adicionando la Closure a la consulta, debes de colocarlo es fuera de ella


text:
Q: How to set value of a property from iputs of View in auto generated partial class in asp.net MVC I'm working in a ASP.NET MVC(EF6) database first project and I have an auto generated partial class in my Models folder like this:
public partial class StdModel
{
    public string StdName { get; set; }
    public int StdNr { get; set; }
}

Because this is an auto generated class, every time I refresh my Models(for whatever reason) any change made to this class gets deleted, so I have extended this class and I would like to ser some input values that is passed from View to some properties(entities) in this new partial class, for example removing spaces between words.
View:

       @Html.LabelFor(model => model.StdName , htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.StdName , new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.StdName , "", new { @class = "text-danger" })

However because it's an partial class I can't declare the same properties in this new partial class and I have already tried different approach like via constructor and set property with initializer to achieve this and yet no success, is there any way to set the properties and change if needed before it goes to db like this:
public partial class StdModel   <---  PartialClasses.cs
{
    private string stdName;
    public string StdName
    {
      get { return stdName; }
      set { stdName = value.ToUpper(); }
    }
    private int stdNr;
    public int StdNr
    {
      get { return stdNr; }
      set {stdNr = Regex.Replace(value, @"\s+", ""); }
    }
}

Thanks in advance.

A: A possible, potentially acceptable workaround may be to explicitly implement an interface. Example:
using System;
using System.Text.RegularExpressions;

namespace StackOverflow_AutoPartialPropOverriding
{
    class Program
    {
        static void Main(string[] args)
        {
            IStdModel model = new StdModel();
            Console.WriteLine($"StdName: {model.StdName}");
            Console.WriteLine($"StdNr: {model.StdNr}");
            /* StdName: steve
             * StdNr: 1
             */
            Console.ReadKey();
        }
    }

    public partial class StdModel
    {
        public string StdName { get; set; }
        public int StdNr { get; set; }
    }

    public interface IStdModel
    {
        string StdName { get; set; }
        int StdNr { get; set; }
    }

    public partial class StdModel : IStdModel
    {
        private string stdName = "steve";
        string IStdModel.StdName
        {
            get => stdName;
            set => value.ToUpper();
        }

        private int stdNr = 1;
        int IStdModel.StdNr
        {
            get => stdNr;
            set => stdNr = value; //value is already type int--not sure why you used regex
        }
    }
}

Notes:

*

*Code provided is compiled under C#7, .Net 4.6.1

*$"{expression}" is string interpolation, added in C#6

*=> is an expression bodied member, get-C#6; set-C#7

A: It is widely accepted that setting a property should be a very simple operation. Changing values in setters makes properties return unexpected values. You could still do this --aside from the partial class problem-- if you think it's really inevitable, but note that EF will also use the setter when materializing StdModel objects. If there is a deviant value in the database you won't notice!
Taking all this into account I would either create two delegate properties that convert the value to the mapped property, for example ...
public string StdNameSetToUpper
{
  get { return StdName; }
  set { StdName = value.ToUpper(); }
}

... or (preferably) work with a view model that transfers converted values between the UI and the data layer.


text:
Q: CoreData info are not shown in the table cell I have a custom cell and using core data the cell is not updating.
At first i created some entities at the .xcdatamodeId with a Manual/None Codegen option. The project would not build and would give me this error:
'An NSManagedObject of class 'DreamLister.Item' must have a valid NSEntityDescription.'
After i went to the generated class files for my model and deleted all the @objc(Item) lines, the project was build but nothing would come up in the cells of the simulator. The custom cell has an identifier that is used in the code for the cellForRowAt function, also i am generating test data and i access the AppDelegate like this
let ad = UIApplication.shared.delegate as! AppDelegate
let context = ad.persistentContainer.viewContext

edit: after an answer suggested to change the codegen option to Class Definition the build fails with a Swift compile error:
Command: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swiftc failed with exit code 1
here is the code of my controller
import UIKit
import CoreData

class MainVC: UIViewController, UITableViewDelegate, UITableViewDataSource, NSFetchedResultsControllerDelegate {

    @IBOutlet weak var tableView: UITableView!
    @IBOutlet weak var segment: UISegmentedControl!

    var controller: NSFetchedResultsController<Item>!

    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.delegate = self
        tableView.dataSource = self

        generateTestData()
        attemptFetch()

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as! ItemCell

        configureCell(cell: cell, indexPath: indexPath as NSIndexPath)

        return cell

    }

    func configureCell(cell: ItemCell, indexPath: NSIndexPath) {

        let item = controller.object(at: indexPath as IndexPath)
        cell.configureCell(item: item)

    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        if let objs = controller.fetchedObjects , objs.count > 0 {

            let item = objs[indexPath.row]
            performSegue(withIdentifier: "ItemDetailsVC", sender: item)
        }
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "ItemDetailsVC" {
            if let destination = segue.destination as? ItemDetailsVC {
                if let item = sender as? Item {
                    destination.itemToEdit = item
                }
            }
        }

    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if let sections = controller.sections {

            let sectionInfo = sections[section]
            return sectionInfo.numberOfObjects
        }

        return 0
    }

    func numberOfSections(in tableView: UITableView) -> Int {

        return 0
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return 150
    }

    func attemptFetch() {

        let fetchRequest: NSFetchRequest<Item> = Item.fetchRequest()
        let dateSort = NSSortDescriptor(key: "created", ascending: false)

        fetchRequest.sortDescriptors = [dateSort]

        let controller = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)

        controller.delegate = self

        self.controller = controller

        do {

            try controller.performFetch()

        } catch {

            let error = error as NSError
            print("\(error)")

        }

    }

    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.beginUpdates()
    }

    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.endUpdates()
    }

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) {

        switch(type) {

        case.insert:
            if let indexPath = newIndexPath {
                tableView.insertRows(at: [indexPath], with: .fade)
            }
            break
        case.delete:
            if let indexPath = indexPath {
                tableView.deleteRows(at: [indexPath], with: .fade)
            }
            break
        case.update:
            if let indexPath = indexPath {
                let cell = tableView.cellForRow(at: indexPath) as! ItemCell
                configureCell(cell: cell, indexPath: indexPath as NSIndexPath)
            }
            break
        case.move:
            if let indexPath = indexPath {
                tableView.deleteRows(at: [indexPath], with: .fade)
            }
            if let indexPath = newIndexPath {
                tableView.insertRows(at: [indexPath], with: .fade)
            }
            break

        }
    }

    func generateTestData() {

        let item = Item(context: context)
        item.title = "MacBook Pro"
        item.price = 1800
        item.details = "I can't wait until the September event, I hope they release new MPBs"

        let item2 = Item(context: context)
        item2.title = "Bose Headphones"
        item2.price = 300
        item2.details = "But man, its so nice to be able to block out everyone with the noise canceling tech."

        let item3 = Item(context: context)
        item3.title = "Tesla Model S"
        item3.price = 110000
        item3.details = "Oh man this is a beautiful car. And one day, I willl own it"

        ad.saveContext()

    }

}

the code for the ItemCell
import UIKit

class ItemCell: UITableViewCell {

    @IBOutlet weak var thumb: UIImageView!
    @IBOutlet weak var title: UILabel!
    @IBOutlet weak var price: UILabel!
    @IBOutlet weak var details: UILabel!

    func configureCell(item: Item) {

        self.title.text = item.title
        self.price.text = "$\(item.price)"
        self.details.text = item.details

    }

}

and the code of the core data generated files
Item+CoreDataClass.swift
import Foundation
import CoreData

public class Item: NSManagedObject {

    public override func awakeFromInsert() {

        super.awakeFromInsert()

        self.created = NSDate()
    }

}

Item+CoreDataProperties.swift
import Foundation
import CoreData

extension Item {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Item> {
        return NSFetchRequest<Item>(entityName: "Item");
    }

    @NSManaged public var created: NSDate?
    @NSManaged public var details: String?
    @NSManaged public var title: String?
    @NSManaged public var price: Double
    @NSManaged public var toImage: Image?
    @NSManaged public var toItemType: ItemType?
    @NSManaged public var toStore: Store?

}

Any thoughts or ideas?
Thanks in Advance.

A: In core data file Select Entity and  Select  Codegen option to Class defination  and run and see

A: I deleted and created the generated files for the core data again and i also change the return statements of these two functions on the MainVC from returning zero to this.
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let sections = controller.sections {

      let sectionInfo = sections[section]
      return sectionInfo.numberOfObjects

    } else {

     return 0
    }

func numberOfSections(in tableView: UITableView) -> Int {

    return 1
}


text:
Q: asp.net mvc 4 webgrid sorting issue of enum datatype column In MVC4 Web Grid,
  Iam  binding Web Grid from server side for efficient paging and sorting.
Sorting is working fine for all columns except one column i.e the datatype of column is ENUM.
I have tried with grid.bind() samples that are present in this site but not working.
please help me

A: I had the same problem - it would not sort the Enums. So I simply just called the .ToString() on my enums when I added it to a list:
        private void CreateReport(int id, string name,
          ReportType type, Relationshiplevel level, string date, string createdby,
                              string filetype, double filesize)
        {
          var newReport=new Report
            {
                Id = id,
              Name  = name,
              Reporttype = type.ToString(),
              Relationshiplevel = level.ToString(),
              CreatedDate = DateTime.Parse(date),
              CreatedBy = createdby,
              FileType = filetype,
              FileSize = filesize
            };
        _reports.Add(newReport);
       }

Works fine now


text:
Q: Is it possible to mount a directory in a docker image during build? Starting with the Docker tutorial, I modify the Dockerfile to contain just
FROM mcr.microsoft.com/vscode/devcontainers/base:0-jammy
RUN mkdir proc && mount --bind /proc ./foo

From the directory hosting the Dockerfile I issue command
docker build -t getting-started .

I expect this docker image to mount /proc at ./foo during the build, but I actually get:
 > [2/2] RUN mkdir foo && mount --bind /proc ./foo:
#5 0.399 mount: /foo: permission denied.

Is there a way to grant permissions to the build process so it can mount proc inside the Docker image?

A: On windows:
docker buildx create --driver-opt image=moby/buildkit:master ^
    --use --name insecure-builder ^
    --buildkitd-flags "--allow-insecure-entitlement security.insecure"
docker buildx use insecure-builder
docker buildx build --allow security.insecure .
docker buildx rm insecure-builder


text:
Q: Radius of convergence of $\frac{z}{1-z-z^2}$ So I want to find the radius of convergence of $\frac{z}{1-z-z^2}:=\sum_{n=0}^{\infty}F_nz^n$ and also show that $F_n$ are the Fibonacci number.
$\underline{\text{My attempt}}$
To show that $F_n$ are the Fibonacci numbers is it enough to see that
\begin{align*}
\frac{z}{1-z-z^2}&=z(1-(z+z^2))^{-1}\\
&=z+z^2+2z^3+3z^4+5z^5+...
\end{align*}
where the coefficients seems to be the Fibonacci numbers?
To find the radius of convergence it is easy to see that $\alpha = \frac{1+\sqrt{5}}{2}$ and $\beta =\frac{1-\sqrt{5}}{2}$ are simple poles of $\frac{z}{1-z-z^2}$. So we can write $$\frac{z}{1-z-z^2}=\frac{z}{\sqrt{5}}\left( \frac{1}{z+\alpha}-\frac{1}{z+\beta}\right)$$however I'm not quite sure how to continue. Any help would be appreciated!

A: $$1-z-z^2=1+\dfrac14-\left(z+\dfrac12\right)^2=\dfrac54\left(1-\left(\dfrac{2z+1}{\sqrt5}\right)^2\right)$$
So we need $$\left|\dfrac{2z+1}{\sqrt5}\right|<1$$


text:
Q: Remove an item from my CustomArrayAdapter Firstly, sorry for my english, I am french.
So, I have a CustomArrayAdapter (ReservationAdapter), and I would remove an item from this class. I have tried many things, but they didn't work.
public class ReservationAdapter extends ArrayAdapter<Reservation> {
public ReservationAdapter(Context context, ArrayList<Reservation> reservations) {
    super(context, 0, reservations);
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    // Get the data item for this position
    Reservation reservation = getItem(position);

    // Check if an existing view is being reused, otherwise inflate the view
    ReservationHolder holder;
    if (convertView == null) {
        holder = new ReservationHolder();

        LayoutInflater inflater = LayoutInflater.from(getContext());
        convertView = inflater.inflate(R.layout.reservation_fragment, parent, false);

        holder.date = (EditText) convertView.findViewById(R.id.dateReserv);
        holder.imgDelete = (ImageButton) convertView.findViewById(R.id.less);

        convertView.setTag(holder);
    } else {
        holder = (ReservationHolder) convertView.getTag();
    }

    // Populate the data into the template view using the data object
    holder.date.setText(reservation.date);
    holder.imgDelete.setOnClickListener(deleteReservListener);

    // Return the completed view to render on screen
    return convertView;
}

private View.OnClickListener deleteReservListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        //Where I try to remove an item
        notifyDataSetChanged();
    }
};

public static class ReservationHolder {
    private EditText date;
    private ImageButton imgDelete;
}

A: You have to remove the item from reservations and then call notifyDataChanged().
Before of all you have to implement a OnItemClickListener on your ListView (outside of your adapter, of course):
        AdapterView.OnItemClickListener itemCLickListener = new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            reservations.remove(i);
            ((ReservationAdapter)listView.getAdapter()).notifyDataChanged();
        }
    }

e voilà

A: It works, merci !
Meanwhile, I'm still looking for a solution, and have find this :
holder.date.setText(reservation.date);
    holder.imgDelete.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            remove(reservation);
            notifyDataSetChanged();
        }
    });

I just put the OnClickListener into the GetView method.
Thanks again ! :)

A: Add position vatiable in your ReservationHolder, and also construcror as:
public ReservationHolder(int position)
{
    this.position = position;
}

public int getCurrentPosition()
{
    return position;
}

and in getView(): ReservationHolder holder = new ReservationHolder(position);
Change your method:
private View.OnClickListener deleteReservListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
    //Where I try to remove an item
    notifyDataSetChanged();
}
};

to:
private View.OnClickListener deleteReservListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
    //Where I try to remove an item

    ReservationHolder holder = (ReservationHolder)v.getTag();
    reservations.remove(holder.getCurrentPosition());

    notifyDataSetChanged();
}
};


text:
Q: Reference project to WCF best practices For WPF, there's the Microsoft Patterns & Practices's Prism project.

Prism provides guidance designed to
  help you more easily design and build
  rich, flexible, and easy-to-maintain
  Windows Presentation Foundation (WPF)
  desktop applications, Silverlight Rich
  Internet Applications (RIAs), and
  Windows Phone 7 applications

I was wondering whether a similar project (reference implementation) intended for software developers building WCF applications exists.
In our main internal project (a .Net WinForms rich client app), we don't talk directly with the database but instead fetch and update data with ASP.Net web-services that we also control. Our current setup is giving us some bottlenecks.
For a new smallish project, we want to try WCF.
Objective question: Where do I find a not-too-basic WCF reference project?

A: There is nothing like Prism provided by Microsoft. WCF usually makes only thin layer on top of other logic.
You can check this guidance for Visual Studio:

*

*Web Service Software Factory

*Web Service Software Factory Contrib
You can also check different articles about best practices:

*

*WCF Security Guidance Project

*Guidelines and best practices

*Security Guidance and Best practices

A: You can find some targeted examples in the Visual Studio 2010 and .NET Framework 4 Training Kit.
It contains several projects demonstrating key features. It is sometimes more relevant than a big project containing to much information.
http://www.microsoft.com/downloads/en/details.aspx?familyid=752CB725-969B-4732-A383-ED5740F02E93&displaylang=en


text:
Q: Как добавить значения нескольких массивов php в mysql? Здравствуйте.
Необходимо вводить данные целыми массивами и сохранять их в базе mysql.
input.php

<form action="addvmstodb.php" method="post">
  List of VM names: <textarea name="VMNAMES" cols="25" rows="5"></textarea>
  List of VM IP's: <textarea name="VMIPS" cols="20" rows="5"></textarea>
  List of VM PWD's: <textarea name="VMPWDS" cols="20" rows="5"></textarea>
  VMs Group name: <textarea name="GROUPNAME" cols="20" rows="5"></textarea>
  <input type="submit">
</form>

addvmstodb.php
$con=mysqli_connect("host","user","pwd","db");
// Check connection
if (mysqli_connect_errno())
{
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$input_VMNAMES = isset($_POST['VMNAMES'])?$_POST['VMNAMES']:"";
$VMNAMES_array = explode("\n", str_replace("\r", "", $input_VMNAMES));

$input_VMIPS = isset($_POST['VMIPS'])?$_POST['VMIPS']:"";
$VMIPS_array = explode("\n", str_replace("\r", "", $input_VMIPS));

$input_VMPWDS = isset($_POST['VMPWDS'])?$_POST['VMPWDS']:"";
$VMPWDS_array = explode("\n", str_replace("\r", "", $input_VMPWDS));

$VMGROUPNAME=$_POST['GROUPNAME'];

for( $i = 0 ; $i < count( $VMNAMES_array ) ; $i++ ) {
  $INSERTQUERY="insert into vmlist (vm_name,vm_ip,vm_pwd,groupname) values ('".$VMNAMES_array[$i]."', '".$VMIPS_array[$i]."', '".$VMPWDS_array[$i]."', '$VMGROUPNAME')";
  $result=mysqli_query($con,$INSERTQUERY);
}
mysqli_close($con);

Массивы получаю нормально. Например, echo $VMNAMES_array[1]; возвращает верное значение. Но данные в базу не добавляются и в логах висят ошибки вида

PHP Warning:  mysqli_query() expects parameter 1 to be mysqli, string given in /path/to/folder/addvmstodb.php on line 81

Куда копать и как починить?
p.s. В php я полный новичок.
UPD
var_dump($INSERTQUERY);
string(99) "insert into vmlist (vm_name,vm_ip,vm_pwd) values ('host1', '111.111.111.1', 'pwd1')"
string(99) "insert into vmlist (vm_name,vm_ip,vm_pwd) values ('host2', '111.111.111.2', 'pwd2)"
string(99) "insert into vmlist (vm_name,vm_ip,vm_pwd) values ('host3', '111.111.111.3', 'pwd3')"

var_dump ($result);
NULL NULL NULL

var_dump ($con);
(mysqli)#1 (19) { ["affected_rows"]=> int(7) ["client_info"]=> string(14) "5.5.47-MariaDB" ["client_version"]=> int(50547) ["connect_errno"]=> int(0) ["connect_error"]=> NULL ["errno"]=> int(0) ["error"]=> string(0) "" ["error_list"]=> array(0) { } ["field_count"]=> int(5) ["host_info"]=> string(25) "Localhost via UNIX socket" ["info"]=> NULL ["insert_id"]=> int(0) ["server_info"]=> string(14) "5.5.47-MariaDB" ["server_version"]=> int(50547) ["stat"]=> string(133) "Uptime: 12357 Threads: 1 Questions: 173 Slow queries: 0 Opens: 3 Flush tables: 2 Open tables: 27 Queries per second avg: 0.014" ["sqlstate"]=> string(5) "00000" ["protocol_version"]=> int(10) ["thread_id"]=> int(69) ["warning_count"]=> int(0) }

A: Вы создаете коннект при помощи расширения mysqli, а для выполнения запроса вызываете функцию mysql_query из расширения mysql.
Замените ее на функцию mysqli_query и все должно заработать
А если добавите использование prepared statement и обработку ошибок, то вообще будет конфетка
$INSERTQUERY = "insert into vmlist (vm_name, vm_ip, vm_pwd, groupname) values (?, ?, ?, ?)";
$stmt = mysqli_prepare($con, $INSERTQUERY);
if (!$stmt)
  die(mysqli_error($con));
$name = null;
$ip = null;
$pwd = null;
if (!mysqli_stmt_bind_param($stmt, 'ssss', $name, $ip, $pwd, $VMGROUPNAME))
  die(mysqli_stmt_error($stmt));
for ($i = 0; $i < count($VMNAMES_array); $i++ ) {
  $name = $VMNAMES_array[$i];
  $ip = $VMIPS_array[$i];
  $pwd = $VMPWDS_array[$i];
  $result = mysqli_stmt_execute($stmt);
  if (!$result)
    die(mysqli_stmt_error($stmt));
}
$stmt = null;
mysqli_close($con);

A: У вас опечатка в строке
$result=mysql_query($con,$INSERTQUERY);

Забыли i, должно быть
$result=mysqli_query($con,$INSERTQUERY);


text:
Q: How can i find out time when my key is stored in Redis Cache/db? Is there any redis command which tells when key is stored in redis?
I know there is TTL command.
Depending on time, i want to take different action. like if
live since last 1 min then do x,
live since last 2 min then do y,
etc...

A: There's no such command. However, you can achieve your goal with the EXPIRE and TTL commands.
For each key, set its TTL to be 1000000000, i.e. EXPIRE key 1000000000. So that the key will be expired after about 32 years. It's should be long enough.
When you want to find out how long the key has been stored, just get the key's TTL, i.e. TTL key. And the key has been stored since 1000000000  - TTL seconds.


text:
Q: Change marker color in Google Maps V2 I'm trying to change the color of a marker.
I have this:
private void addMarker(GoogleMap map, double lat, double lon,
                         int title, int snippet) {
    map.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
                                     .title(getString(title))
                                     .snippet(getString(snippet)));

and then this to add a marker:
addMarker(map, 40.748963847316034, -73.96807193756104,
                R.string.title, R.string.snippet);

I want to change the color of the marker and I thought it would be easy and just implement it like this:
private void addMarker(GoogleMap map, double lat, double lon,
                         int title, int snippet, int icon) {
    map.addMarker(new MarkerOptions().position(new LatLng(lat, lon))
                                     .title(getString(title))
                                     .snippet(getString(snippet))
                                         .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.(getString(icon)));

and:
addMarker(map, 40.748963847316034, -73.96807193756104,
                R.string.title, R.string.snippet, HUE_AZURE);

But I can't use "getString" together with ".icon" apparently.
How can I do this?
Also, is that method of changing color supported for API 8+? I've had lots of problems supporting API 8+ and it would suck if this broke something...

A: here is a loop where I set markers with different colors on the map and it works great for me:
for (Task tempTask : TasksListAppObj.getInstance().tasksRepository.getTasksRepository())
                {
                    LatLng latlng = new LatLng(tempTask.getLatitude(), tempTask.getLongtitude());
                    if (tempTask.getStatus().contentEquals(TasksListActivity.STATUS_WAITING))
                    {
                        newmarker = map.addMarker(new MarkerOptions().position(latlng).title(tempTask.getTitle()).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_for_map_blue)));
                    }
                    else if (tempTask.getStatus().contentEquals(TasksListActivity.STATUS_IN_PROGRESS))
                    {
                        newmarker = map.addMarker(new MarkerOptions().position(latlng).title(tempTask.getTitle()).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_for_map_bordo)));
                    }
                    else if (tempTask.getStatus().contentEquals(TasksListActivity.STATUS_ON_THE_WAY))
                    {
                        newmarker = map.addMarker(new MarkerOptions().position(latlng).title(tempTask.getTitle()).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_for_map_turkiz)));
                    }
                    else if (tempTask.getStatus().contentEquals(TasksListActivity.STATUS_COMPLETE))
                    {
                        newmarker = map.addMarker(new MarkerOptions().position(latlng).title(tempTask.getTitle()).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_for_map_orange)));
                    }
                    else if (tempTask.getStatus().contentEquals(TasksListActivity.STATUS_FAILED))
                    {
                        newmarker = map.addMarker(new MarkerOptions().position(latlng).title(tempTask.getTitle()).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker_for_map_purpul)));
                    }
}

See if it's helps you.
The if statements are for changing the marker icon.

A: The following snippet does the trick for me without dependencies:
BitmapDescriptor bitmapDescriptor = BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE);

myMap.addMarker(new MarkerOptions()
    .position(point)
    .icon(bitmapDescriptor)
    .title(point.toString()));

Found it here: http://android-er.blogspot.de/2013/01/change-marker-color-of-googlemaps-v2.html


text:
Q: Visual Studio 2022 - Helper View in App_code not being found when referenced inside Partial View I have an ASP.NET MVC (5.2.7) Partial View inside a project within a Visual Studio solution:
/Views/[MyEntity]/Partial/MyPartial.cshtml
@model My.Models.ViewModels.Booking.BookingDefaultsViewModel

@BookingDefaultsHelper.View(this,Model)

/App_Code/BookingDefaultsHelper.cshtml
@using System.Web.Mvc
@using System.Web.Mvc.Html
@using My.Models.ViewModels.Booking
@helper View(WebViewPage page, BookingDefaultsViewModel model)
{
    var myList = new List<System.Web.Mvc.SelectListItem>
    {
        new System.Web.Mvc.SelectListItem {Text = @"Days", Value = "1"},
        new System.Web.Mvc.SelectListItem {Text = @"Hours", Value = "2"},
        new System.Web.Mvc.SelectListItem {Text = @"Minutes", Value = "3"}
    };

.. etc

my.csproj
...
<Content Include="App_Code\BookingDefaultsHelper.cshtml" />
... etc

In the partial view, BookingDefaultsHelper I get The name BookingDefaultsHelper does not exist in the current context. Why isn't it found?
It's a similar issue to the following one in Rider, but I'm seeing this in Visual Studio (and the question below doesn't provide any clues or answer):
Global helpers inside razor views in App_Code are not recognized


text:
Q: Передача ссылки на список в функцию Собственно проблема не в самой передаче а в дальнейшей работе со списком:
template < typename T > void minmaxList( const list< T > &listRef ) {
    int min=0,max=0,i=0;
    list<int>::iterator it;
    for( it=listRef.begin(); it != listRef.end(); ++it ) {
       if (*it==1){
          min=*it;
          max=*it;
       }
       if (*it<=min) min=*it;
       if (*it>=max) max=*it;
    }
    cout<<"\tMIN: "<<min<<"\tMAX"<<max<<endl;
}

Соответственно заголовок функции
template < typename T > void minmaxList( const std::list< T > &listRef );

список объявляем list<int> L;
Возникает ошибка при компиляции:
[Error] no match for 'operator=' in 'it = (& listRef)->std::list<_Tp, _Alloc>::begin [with _Tp = int, _Alloc = std::allocator<int>, std::list<_Tp, _Alloc>::const_iterator = std::_List_const_iterator<int>]()'

на строке где я получаю итератор:
    list<int>::iterator it;
Собственно что не так?
Полный код программы http://govnokod.com/6728 ошибка на строке 38
Сделал вот так: http://govnokod.com/6734
A: Вы передаёте список как конст ссылку на список, по идее и итератор должен быть константным.
std::list<T>::const_iterator it;


text:
Q: Существует ли краткий справочник, годный для распечатки со всеми методами STL? Существует ли краткий справочник, годный для распечатки со всеми методами STL классов и их кратким описанием?
Не смог найти в интернете.
A: Вот здесь этот вопрос был освещен


text:
Q: loading Spinner - always keep in the middle of the screen even while scrolling the page

It is the code for showing a loading graphic while page is getting loading. It shows above a grid view. When the grid consist of large number of rows, when I scroll down the page, I can't see the loading graphic . But when I go to the top of the screen I can see the loading graphic. How I keep it always in the middle of the screen even while scrolling the page?
Please help me.

A: I went through my old answers to see if I could add something that is more modern. In my newer solution you do not need to specify the height or the width. Its a more generic solution.
.center {
   position: fixed;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%);
}

Try this:
.centered {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px; //Half of the height of the loading graphic
  margin-left: -50px; //Half of the width of the loading graphic
}

A: Here's my solution...

<!DOCTYPE html>

  <meta charset="utf-8">
  <title>Untitled</title>

  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.2.616/styles/kendo.common.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.2.616/styles/kendo.rtl.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.2.616/styles/kendo.default.min.css">
  <link rel="stylesheet" href="https://kendo.cdn.telerik.com/2021.2.616/styles/kendo.mobile.all.min.css">

This is a long DIV...


text:
Q: Exception in thread "main" java.lang.Error: Unresolved compilation problems: This is the error I'm getting
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    Scanner cannot be resolved to a type
    Scanner cannot be resolved to a type

    at hello.main(hello.java:11)

This is my code.
public class hello {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        double area;
        double radius;

        Scanner input = new Scanner(System.in);
        System.out.print("반지름을 입력하시오: ");
        radius = input.nextDouble();
        area = 3.14 * radius * radius;

        System.out.println(area);
    }
}

A: Have you imported Scanner class like import java.util.Scanner;

A: You need:
import java.util.Scanner;

at the top of your file.  You've got to import it.


text:
Q: In-App Purchase, how to get products which are have "Waiting for review" status I have published app, and I added new products for In-App Purchase. Status is "Waiting for review"  now. How can I programmatically get status of my products?
I know that when if you will try to buy this product, you get error code 0. But I need to check all my products id before user starts buy them.
Thank you!

A: If you are using Xcode or Application Loader, you already have Transporter (Apple's command-line tool) installed.
You can find it in :
/Applications/Xcode.app/Contents/Applications/Application Loader.app/Contents/MacOS/itms/bin
Transporter have a Lookup Mode allow you to retrieve your app's current metadata and will create an
App Store package at the set destination.
Type following command in the Terminal app (navigate to directory where Transporter is installed):
$ iTMSTransporter -m lookupMetadata -u [iTunes Connect user name] -p [iTunes Connect password] -vendor_id [App SKU] -destination [destination path for App Store Package] -subitemtype InAppPurchase -subitemids [requested_purchase_ID]
if you have several products to check. Set purchase_IDs comma-separated list in subitemids.


text:
Q: How to detect if a browser can play multiple sounds at the same time Mobile Safari on iOS won't play more than one HTML5 audio file at the same time. I've been using the following to check if multiple sounds can be played:
var isIos = /iPhone|iPad|iPod/i.test( navigator.userAgent );

I would prefer checking for feature support directly instead of testing for individual platforms. There's always a (small) chance that the feature will be added to Safari later, and there might be other browsers that have the same limitation and won't be detected with this code.
Is there a more reliable way to check or test whether multiple concurrent sounds are supported?


text:
Q: ES6 is not recognized - NodeJS and WebStorm I've been googling and searching everywhere and couldn't find an answer.
I'm just a little familiar with Typescript. Started working on my GraphQL NodeJS server and wanted to use Typescript for safer and easier coding.
The first thing needed to be done is set the current JS version to ES6 and so I did.
In addition I set my tsconfig that way:
{
"compilerOptions": {
    "module": "es6",
    "target": "es6",
    "noImplicitAny": false,
    "outDir": "./build",
    "sourceMap": true
},
"exclude": [
    "node_modules"
]

}
my index.js
import * as express from 'express';
import * as graphqlHTTP from 'express-graphql';
import {Schema} from './src/schema/Schema';

const PORT = 3000;

const app = express();

const graphqlOption: graphqlHTTP.OptionsObj = {
  schema: new Schema().getSchema(),
  pretty: true,
  graphiql: true
};

app.use('/graphql', graphqlHTTP(graphqlOption));

app.listen(PORT, ()=> {
  console.log("listening on PORT 3000");
});

When running this I'm getting

SyntaxError: unexpected token import

also, when hovering the const graphqlOption: graphqlHTTP.OptionsObj I get

Types are not supported by the current JavaScript version

Please help, what am i doing wrong?
Thanks in advance.
EDIT:
Wanted it to be clear that when I'm using a simple var express = require('express') I do not get this unexpected token and it moves to the next line
SCREENSHOTS:

A: Go to:
File -> Settings -> Languages -> JavaScript

And enable ES6.

A: The problem is not with WebStorm or NodeJS, it is that you are not transpiling the ES6 module declarations into their ES5 CommonJS equivalent, so when you run the output you are getting an error as no version of Node implements ES6 modules.
Update your tsconfig.json:
"compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    ...
}

A: Thanks for all the help, eventually I've found the problem.
If you'll look carefully enough you'll notice i do not have an index.ts and what I was trying to do by mistake is to run the index.js with Typescript syntax in it.
I've renamed it to index.ts, used tsc to create the build directory again and then ran the index.js created there, everything works.
Thanks for all the comments.


text:
Q: Is it possible to change the path of a css file that is registered through wp_enqueue_style()? The theme I am using already calls the wp_enqueue_style function to enqueue a css file.
I want to whether it is possible to change the css file path before it is actually outputted on the page.
Why I want to do this?
Basically, I want to check if it is a dev or prod environment. Based on that I want to include either the uncompressed or compressed file.

A: I wonder if you are looking for the style_loader_src filter?
For example:
add_filter( 'style_loader_src',
    function ( $src ){

        // ... your stuff ...

        return $src;
    }
);

Similarly there exists the script_loader_src filter.
There's also the base_url property of the global $wp_scripts and $wp_styles objects, but I think that's only used for enqueued native styles and scripts.


text:
Q: Soluions over ring of integers from an non archimedean field This is Proposition 1.9.  I am confused with the forward direction:
If $K$ is alg. closed narc field with $x$ a nonzero element with posiive norm. Then:

*

*$K$ is not discrete.

*Every polynomial over $O_K/(x)$ has a root in $O_K/(x)$.

where $O_K$ is ring of inegers of $K$.

My problems/ thoughts. Suppose I have a polynomial over $O_K/(x)$ of form
$\sum a_i t^i$ when lifted to $K$. It has root $y \in K$. But I don't see how we can scale $y$ so as to obtain new root in $O_K/(x)$.
any hints would be appreciated.

A: The valuation/norm on $K$ is not discrete because $v(x^{n/m}) = v(x) n/m$.
Every monic polynomial $\in O_K[t]$ has a root in $O_K$.
$pt-1\in O_{\overline{Q}_p}/(p^2)[t]$ doesn't have a root in $O_{\overline{Q}_p}/(p^2)$.


text:
Q: EXC_BAD_ACCESS with GCM 3.0 I'm trying to integrate GCM v3 into a cocos2d-x v3.6 project, and after a few days of getting things working with CocoaPods and Xcode, I finally was able to build the app. However, when deployed on device for testing, it crashes on calling [[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID scope:kGGLInstanceIDScopeGCM options:_registrationOptions handler:_registrationHandler] with the error EXC_BAD_ACCESS. What gives?
Screenshot: http://i.imgur.com/s0HnxTp.png
My configuration is as follows:

daffodilistic$ pod --version
  0.39.0.beta.4
  daffodilistic$ cat Podfile
  platform :ios, '8.1'
  source 'https://github.com/CocoaPods/Specs.git'
  target 'project-redacted iOS' do
      pod 'Google/CloudMessaging'
  end
  target 'project-redacted Mac' do
  end

A: I managed to debug and resolve the exception successfully - apparently, it's caused by a NULL or 0x00000000 value being pointed to by the @property(nonatomic, retain) void (^registrationHandler) block property declared earlier on as per Google's sample GCM v3 code for iOS. As to whether it was Xcode, iOS or cocos2d-x causing the block declaration to be dereferenced/deallocated, I'm not sure.
The solution was to move the (^registrationHandler) block declaration from
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

to
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken

Related SO link which was useful, but not really crucial: unable to register (com.google.iid error 1005.)


text:
Q: Web service and transactional guarantees How do you integrate applications via web services and deal with technical errors like connectivity errors for web service calls which change state?
E.g. when the network connection gets interrupted during a web service call, how does the client know whether the web services has processed its action or not?
Can this issue be solved at the business layer only (e.g. to query a previous call state) or are you aware of some nice frameworks/best practices which can help wrapping transactional guarantees around a web service?

A: Implementing it all by yourself with some kind of transactional context tracked in the business layer is always an option. You can use some compensation mechanisms to ensure transactions are rolled back if needed, but you'll need to:

*

*have the information on transactions persisted somewhere

*use transaction correlation IDs, so you can query when the response has
been lost (having correlation IDs is good idea anyway)

*implement the operations needed to read/write/rollback, etc, so it might make your services a bit more complex

Another option I can think of is If you're using SOAP you can go for asynchronous communication and look for some stack implementing WS-Coordination, WS-AtomicTransaction and WS-BusinessActivity specifications, then decide for yourself if it is a good idea in your context or not. For example, I think Axis2 supports these, but of course eventually it depends on technologies and stack you use.
From the article above:

WS-AtomicTransaction defines a coordination type that is most useful
  for handling system-generated exceptions, such as an incomplete write
  operation or a process terminating abnormally.

Below are the types of 2-Phase Commit that it implements.

Hope this helps!


text:
Q: Postgres aggregate with case I have a some query that returns a table "code_1"(id - distinct).
|---------------------|------------------|
|         id          |       status     |
|---------------------|------------------|
|          1          |         true     |
|---------------------|------------------|
|          2          |         true     |
|---------------------|------------------|
|          3          |         false    |
|---------------------|------------------|
|          3          |         true     |
|---------------------|------------------|
|          4          |         false    |
|---------------------|------------------|

Based on the data .. I want to get the following table ("code_2")
|---------------------|------------------|
|     id              |     status       |
|---------------------|------------------|
|          1          |      include     |
|---------------------|------------------|
|          2          |      include     |
|---------------------|------------------|
|          3          |      partial     |
|---------------------|------------------|
|          4          |      exclude     |
|---------------------|------------------|

if the id is repeated status is partial, else status = status from code_1 table

A: If I understand correctly, use aggregation:
select id,
       (case when min(status) = max(status) and min(status) then 'Include'
             when min(status) = max(status) and not min(status) then 'Exclude'
             else 'Partial'
        end) as status
from t
group by id;

Or, using boolean aggregation functions:
select id,
       (case when bool_and(status) then 'Include'
             when bool_or(status) then 'Partial'
             else 'Exclude'
        end) as status
from t
group by id;


text:
Q: Lost the information in the menu bar/panel in Intellij IDEA on Ubuntu 16.10 Previously I had information about the path to my project and which project I currently had opened in Intellij, but that information seems to have vanished. How can I get it back?
Excuse my Gimp skills, but here I where I mean:

A: I have the same version of Ubuntu and I can see correctly the project information in IntelliJ. The only case that this info is hidden is when lost the windows focus, behavior that is normal I thing.
You can try to see in IntelliJ logs to find a problem related with this. The logs are saved in /home/${username}/.${idea_version}/system/log


text:
Q: How to understand question about text document similarity My teacher rarely answers emails so forgive me for asking here. I'm having trouble understanding what he means about the highlighted part:
"Create a python program that will compute the text document similarity between different documents. Your implementation will take a list of documents as an input text corpus and it will compute a dictionary of words for the given corpus."
So is the input a list of strings like so: e = ["a", "a", "b", "f"]
Or is it just a list with a single string where I pull the individual words?
Full question:
Create a python program that will compute the text document similarity between different documents. Your implementation will take a list of documents as an input text corpus and it will compute a dictionary of words for the given corpus. Later, when a new document (i.e search document) is provided, your implementation should provide a list of documents that are similar to the given search document, in descending order of their similarity with the search document. For computing similarity between any two documents in our question, you can use the following distance measures (optionally you can also use any other measure as well).
1.dot product between the two vectors
2.distance norm (or Euclidean distance) between two vectors .e.g.||u−v||
Hint A text document can be represented as a word vector against a given dictionary of words. So first compute the dictionary of words for a given text corpus, containing the unique words from the documents of given corpus. Then transform every text document of the given corpus into vector form i.e. creating a word vector where 0 indicates the word is not in the document and 1 indicates that the word is present in the given document. In our question, a text document is just represented as a string, so the text corpus is nothing but a list of strings

A: The way I understand it you are given a list of documents and you will match a new document to them, for instance:
my_docs = ["this is the first doc", "this is the second doc", "and this is yet another doc"]
inpd = input('please enter a document: ')
my_vocab, v_dim = build_vocab(my_docs + [inpd]) # build vocabulary from doclist and new doc
my_vdocs = [build_dvec(doc, v_dim, my_vocab) for doc in my_docs] # vectorize documents
inpdv = build_dvec(inpd, v_dim, my_vocab) # vectorize input document

print('docs and score: ', [str(my_docs[itm[0]])+': '+str(itm[1]) for itm in dmtch(inpdv, my_vdocs)])

this would produce
please enter a document: yet another doc
docs and score:  ['and this is yet another doc: 3.0', 'this is the first doc: 1.0', 'this is the second doc: 1.0']

The best match is the last document in your list as it contains the most words from the input document.  I have omitted the code for constructing the vocabulary, transforming the documents to vectors and matching them (=assignment).


text:
Q: How to evaluate user policy via API for a given set of users I want to evaluate user policies for a particular user or list of users, is there any API available to perform the same in OIM 11gR2PS3?

A: you can use oracle.iam.accesspolicy.api.AccessPolicyService.evalutePoliciesForUser() OIM API which can be used for the same. Here is the code snippet for the same.


text:
Q: Open Source Alternatives to 123D Catch 123D Catch is an app for Windows, OSX and Android that lets a user turn a series of photographs into a 3D model (a process known as photogrammetry).
Is there an alternative, preferably with a GUI, available for Linux/Ubuntu?

A: Enjoy the open source realm, you can find many such apps:

*

*Agisoft Photoscan: Here's a tutorial. (not open source, thanks for @Yomismo's comment)

*VisualSFM: Here's a tutorial.(not open source,thanks for @Yomismo & @hellocatfood comments)

*Python Photogrammetry Toolbox: Here's a tutorial.

*openMVG: Here's a tutorial.

Moreover you can use a GNU/Linux distribution called ArcheOS.

ArcheOS is the acronym of Archeological Operating System. It is a
  GNU/Linux live distribution built for archaeological aims. At the
  moment a new version (5.0 codename "Theodoric") based on Debian
  "Wheezy" is under development.

You can use the 3D applications that suit your needs.


text:
Q: How to plot stacked bar chart according to the custom Y axis in D3 I have a stacked bar chart where I have to show data% within 0 to 100.
for example - if a, b have value 3, 7 out of 10 then I have to show it as 30% and 70%. But sometimes the data comes under 1%, so I modified the Y-axis as below which is equally distributed but not able to put the chart according to the custom Y-axis.
custom Yaxis chart
This is how I modified the Y-axis using D3
var y_data = [0,1,2,3,4,5,6,7,8,9,10,30,50,70,100];

var y = d3.scaleLinear()
  .domain([0, 100])
  .range([height, 0])
  svg.append("g").attr('class', 'y-stack')
  .call(d3.axisLeft(y).tickValues(y_data).tickSize(10).tickPadding(10));

d3.select('.y-stack').selectAll('.tick').each(function(i, val) {
  const temp_height = height + margin.top + margin.bottom - margin.left;
  const diff = temp_height / (y_data.length - 1);
  $(<any>this).attr('transform', 'translate(0, ' + (temp_height - (diff * val ) + 0.5 + ')'));
});

Now how do I plot the chart or is there any easy way to do it instead of making a custom calc function for it.

A: You can do that by providing arrays of n domain values (the y_ticks you gave) and n range values (the number of pixels from 0 along the axis). Then it will also automatically interpolate for example 15 to be on 25% between 10 and 30.
I got the base code from here:

var data = [{
    "State": "AL",
    "Under 5 Years": 52,
    "5 to 13 Years": 29,
    "14 to 17 Years": 10
  },
  {
    "State": "AK",
    "Under 5 Years": 56,
    "5 to 13 Years": 21,
    "14 to 17 Years": 20
  },
  {
    "State": "AZ",
    "Under 5 Years": 28,
    "5 to 13 Years": 62,
    "14 to 17 Years": 15
  },
  {
    "State": "AR",
    "Under 5 Years": 43,
    "5 to 13 Years": 17,
    "14 to 17 Years": 20
  },
  {
    "State": "CA",
    "Under 5 Years": 49,
    "5 to 13 Years": 15,
    "14 to 17 Years": 30
  },
  {
    "State": "CO",
    "Under 5 Years": 87,
    "5 to 13 Years": 1,
    "14 to 17 Years": 11
  }
];

var keys = Object.keys(data[0]).slice(2);
var states = [...new Set(data.map(d => d.State))]
var yTicks = [0,1,2,3,4,5,6,7,8,9,10,30,50,70,100];

function getRange(from, to) {
  const interpolator = d3.interpolate(from, to);
  return new Array(yTicks.length)
    .fill(undefined)
    .map((_, i) => interpolator(i / yTicks.length));
}

var svg = d3.select("#chart"),
  margin = {
    top: 35,
    left: 35,
    bottom: 0,
    right: 0
  },
  width = +svg.attr("width") - margin.left - margin.right,
  height = +svg.attr("height") - margin.top - margin.bottom;

var x = d3.scaleBand()
  .range([margin.left, width - margin.right])
  .padding(0.1)

var y = d3.scaleLinear()
  .range(getRange(height - margin.bottom, margin.top))
  .domain(yTicks)

var xAxis = svg.append("g")
  .attr("transform", `translate(0,${height - margin.bottom})`)
  .attr("class", "x-axis")

var yAxis = svg.append("g")
  .attr("transform", `translate(${margin.left},0)`)
  .attr("class", "y-axis")

var z = d3.scaleOrdinal()
  .range(["steelblue", "darkorange", "lightblue"])
  .domain(keys);

data.forEach(function(d) {
  d.total = d3.sum(keys, k => +d[k])
  return d
});

svg.selectAll(".y-axis")
  .call(d3.axisLeft(y).tickValues(yTicks))

data.sort((a, b) => states.indexOf(a.State) - states.indexOf(b.State))

x.domain(data.map(d => d.State));

svg.selectAll(".x-axis")
  .call(d3.axisBottom(x).tickSizeOuter(0))

var group = svg.selectAll("g.layer")
  .data(d3.stack().keys(keys)(data), d => d.key)

group.exit().remove()

group.enter().append("g")
  .classed("layer", true)
  .attr("fill", d => z(d.key));

var bars = svg.selectAll("g.layer").selectAll("rect")
  .data(d => d, e => e.data.State);

bars.exit().remove()

bars.enter().append("rect")
  .attr("width", x.bandwidth())
  .merge(bars)
  .attr("x", d => x(d.data.State))
  .attr("y", d => y(d[1]))
  .attr("height", d => y(d[0]) - y(d[1]))

var text = svg.selectAll(".text")
  .data(data, d => d.State);

text.exit().remove()

text.enter().append("text")
  .attr("class", "text")
  .attr("text-anchor", "middle")
  .merge(text)
  .attr("x", d => x(d.State) + x.bandwidth() / 2)
  .attr("y", d => y(d.total) - 5)
  .text(d => d.total)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.js"></script>
<svg id="chart" width="650" height="400"></svg>


text:
Q: C# bitwise shift on ushort (UInt16) I need to perform a bitwise left shift on a 16-bit integer (ushort / UInt16), but the bitwise operators in C# seem to apply to int (32-bit) only. How can I use << on an ushort, or at least get to the same result with a simple workaround?

A: Cast the resulting value back into ushort after shifting:
ushort value = 1;
ushort shifted = (ushort)(value << 2);


text:
Q: Circular, dependency in makefile. How can I solve it? I have a fairly simple makefile, but it crashes on linking all .o to build myprogram executable.
This is the error message:
make: Circular myprogram <- myprogram dependency dropped.
g++        -o .cpp
g++: no input files
make: *** [.cpp] Error 1

This is the makefile:
CODE = myprogram

OBJS = /home/Documents/Obj/object1.o /home/Documents/Obj/object2.o /home/Documents/Obj/object3.o /home/Documents/Obj/object4.o

default: $(CODE)

C = g++ $(CXXFLAGS) -fopenmp -g

INCLUDE = -I/home/Documents/Include/

LIBS = -lfftw3 -lm $(LIB)

%.o: %.cpp
        $(C) $(INCLUDE)  -c -o $@ $<

$(CODE): $(OBJS) $(CODE).cpp
        $(C) $(INCLUDE) -o $(CODE) $(CODE).cpp $(OBJS) $(LIBS)

clean:
        - $(RM) $(CLEAN) $(CODE) $(OBJS)


text:
Q: auto_prepend_file PHP Core Directives not Loading I have 4 web servers running Apache. These servers utilize two core php.ini directives to parse and insert content on every site.
e.g.
auto_prepend_file = /home/stats/scriptty.php
auto_append_file = /home/stats/scripttrry.php
Docs
auto_prepend_file
http://php.net/manual/en/ini.core.php#ini.auto-prepend-file
auto_append_file
http://php.net/manual/en/ini.core.php#ini.auto-append-file
On Three of the servers, the directives are in working order. The server which is failing to include the
files has PHP 5.4 and the others PHP 5.3.
When doing I grep the loaded config for PHP, the correct value is there and path to file, same with auto_append_file.
php -r "phpinfo();" | grep auto_prepend_file

I have compared other 3 server php configuration files to the failing server, they look similar. I've checked "httpd.conf" for "AllowOverrideAll" and / it's set to All.
I don't see any error on logs. I've tried loading it directly on htaccess instead, but it generates a system error.
php_value auto_prepend_file "/dir/path/utilities.php"

Not sure where to go from here. Would you have any ideas what could be wrong?


text:
Q: Operational amplifier bandwidth - why does manufacturer tell it's DC when it is not I've been working with op amp datasheets lately and i noticed strange thing with RF amplifiers specifications.
I will provide one example, but there quit more of them with this manufacturer.
HMC625BLP5E
http://www.analog.com/media/en/technical-documentation/data-sheets/HMC625B.pdf
So the description says it's "VARIABLE GAIN AMPLIFIER, DC - 5 GHz"
But application schematic's show that DC blocking capacitor is required at the input of the amplifier

So my questions are:
1) Why would they say it's DC when it's effectively not.
2) What would happen if i would not put that capacitor on the input?

A: This isn't an opamp (operational amplifier). It isn't even a differential amplifier. This is a radio frequency attenuator and amplifier on a chip.

*

*
Why would they say it's DC when it's effectively not.

Because the inputs of the amplifier and attenuator are DC coupled to the respective outputs.

It could theoretically be used for amplifying a signal with a DC component, although in most (probably all) applications you wouldn't want to. The schematic you posted is just a hint, showing a typical application of the chip, it's not the only way to use it.

*
What would happen if i would not put that capacitor on the input?

It depends wholly on what you connect to the inputs and outputs. To pass the DC component in the first place you'd have to DC couple AMPOUT too (as well as ATTIN and ATTOUT if you wish to use the attenuator at DC, probably those decoupling pins of the attenuator too). Good luck doing that without messing up all the internal biasing of the amplifier, however. I doubt that it could be done, nor that this is the right tool for the job.
I agree that the manufacturers are misleading here. It can't really do actual DC under practical terms, but even 1 MHz is functionally DC when compared to 6 GHz.

A: This is more or less a marketing thing.
As you've noticed, the amplifier (and many many others) need DC-blocks. They are also biased over an inductor at the output. Any DC-signal would just be absorbed into the supply voltage.
The "DC-capable" feature only tells you, that the amplifier itself is not the limiting factor for low frequencies. Many of these RF-amplifiers are basically just a 50 Ohm matched transistor in a common source/emitter circuit. Therefore, the amp is DC capable. Just its standard circuit is not.
Theoretically you could achieve amplification at a very low frequency. You just have to use a very large inductor and huge capacitors for AC coupling.
Unfortunately, values become unrealistic at some point. Imagine an inductor that blocks 2 Hz...

A: They say it is DC if the DC is within a narrow range. For RF only a simple blocking capacitor solves this issue. As an op-amp though with a wide-band response some manufactures use them for Timer/Counter front ends usually with a 10:1 divider.
A servo-loop keeps track of the DC offset by integration so the input always has an average DC value that is correct. Note that not all RF op-amps perform well at DC or even low band AM radio. But they give the spec anyways as a selling point to those who know how to get wide-bandwidth and keep it stable.
Think about oscilloscopes with real-time GHZ inputs that MUST use special RF op-amps that are DC stable-if you use an active servo loop to keep it stable.


text:
Q: How to make npx work with my custom npm pakage? I've published a new package which aims to generate a very small boilerplate for a node open source project via cli. For now, it's just a combination of few npx commands and requires other npm packages like gitignore, license to work. I want to execute the build script in package.json with the following command.
npx get-set-node-oss build youremailaddress@xyz.com

Link to the npm package: get-set-node-oss. I know the name is a bit too long.
{
  "name": "get-set-node-oss",
  "version": "1.0.1",
  "description": "One command setup for your Node OSS project",
  "scripts": {
    "build": "npx license mit > LICENSE && npx gitignore node && npx covgen"
  },
  "author": "Harshit Juneja",
  "license": "MIT",
  "repository": {
    "type": "git",
    "url": "git+https://github.com/harshitjuneja/get-set-node-oss.git"
  },
  "keywords": [
    "node",
    "boilerplate","gitignore","MIT","OSS"
  ],
  "bugs": {
    "url": "https://github.com/harshitjuneja/get-set-node-oss/issues"
  },
  "homepage": "https://github.com/harshitjuneja/get-set-node-oss#readme"
}

I expect the user to make a new folder and cd into the folder and do
npx get-set-node-oss build emailstring

and get the resulting boilerplate files.

A: For npx to work you need to specify what the get-set-node-oss command means. Thankfully, this can be accomplished by using the bin field in your package.json file. More information from NPM documentation for your reference:

To use this, supply a bin field in your package.json which is a map of command name to local file name. On install, npm will symlink that file into prefix/bin for global installs, or ./node_modules/.bin/ for local installs.

An example of it below.
"bin": {
    "get-set-node-oss": //script you like to run
},

Hope it works out for you. I have understood bin as scripts in package.json. Where we can either do npm run foo or npx foo both yielding the same results. If you want an example, here you go https://github.com/vipulgupta2048/balenaclone


text:
Q: Value with the highest frequency in a particular field I am trying to figure out a way to get the value with the highest frequency in a particular field.
Is there a built-in MongoDB command that can help me do that?

A: you can use something like
db.getCollection('tweetsprocessed').aggregate([
    {"$group" : {
        _id:"$principal_topic",
        count:{$sum:1}
        }
     },
     { $sort : { count : -1 } }

])

it's similar to use GROUP BY and ORDER BY on SQL