text:
Q: structure of np.zeros with multi dimensional shape I have seen in a program on github which contains
img_out = np.zeros(((4,)+(512,1024,3)+(3,)))

I am trying to understand the structure of the numpy array formed from this. The documentation doesn't give any details of such complex shapes. Can someone explain me how should I interpret the structure of this array.

A: A mention by @Sree.
It's a 5D image where.
import numpy as np
a = np.zeros(((4,)+(512,1024,3)+(3,)))
a.shape

(4, 512, 1024, 3, 3) #output

512 is width of the image
1024 is the height
3 is channel in the image like rbg
so look closly on the code you will know what first and last element represent.

A: you can try to understand a more simple 5 dimensions example:
print(np.zeros( (1, 2, 1, 2, 2)))

output:
[[[[[0. 0.]
    [0. 0.]]]

  [[[0. 0.]
    [0. 0.]]]]]

in this example, you can see that you have 1 element of 5th dimension, which contains 2 elements of 4th dimension which each of them contains a 1 element of  3rd dimension which contains 2  elements of  2nd dimension which each of them contains 2 elements of 1st dimension:
[<== your array
    5th.1[<=== your 5th dimention, only 1 element of 5th dimention

        5th.1.4th.1[<=== your 4th dimention, 1st element of 4th dimention

            5th.1.4th.1.3th.1[<=== your 3rd dimention, only 1 element of  3rd dimention

                5th.1.4th.1.3th.1.2ed.1[<=== your 2ed dimention, 1st element of 2ed dimention,
                                             inside of this element are those elements of 1st dimention,
                                             there are 2 elements of 1st dimention:
                                                0.0, 0.0],

                 5th.1.4th.1.3th.1.2ed.2[<=== your 2ed dimention, 2end element of 2ed dimention,
                                              inside of this element are those elements of 1st dimention,
                                              there are 2 elements of 1st dimention:
                                                 0.0, 0.0]]],

        5th.1.4th.2[<=== your 4th dimention, 2end element of 4th dimention

            5th.1.4th.2.3th.1[<=== your 3rd dimention, only 1 element of 3rd dimention

                5th.1.4th.2.3th.1.2ed.1[<=== your 2ed dimention, 1st element of  2ed dimention,
                                             inside of this element are those elements of 1st dimention,
                                             there are 2 element of 1st dimention:
                                                0.0, 0.0],

                 5th.1.4th.2.3th.1.2ed.2[<=== your 2ed dimention, 2end element of 2ed dimention,
                                              inside of this element are those elements of 1st dimention,
                                              there are 2 elements of 1st dimention:
                                                0.0, 0.0]]]]

for simplicity:
[1 X [2 x [1 x [[0.0, 0.0],
                [0.0., 0.0]]]]]

you have to keep in mind that (4,)+(512,1024,3)+(3,) = (4, 512, 1024, 3, 3), they used 3 tuples to evidentiate:

*

*the number of images (4),

*the hight (512), the width(1024) and depth(3),

*the number of channels(3)

similar in your example for np.zeros(((4,)+(512,1024,3)+(3,))) you can simplify as:
 [4 X [512 X [1024 X [[0.0, 0.0, 0.0],
                      [0.0, 0.0, 0.0],
                      [0.0, 0.0, 0.0]]]]]

A: The code above can be broken down like
shape = ((4,)+(512,1024,3)+(3,))
## above line is similar to joining list using +, and will result tuple (4,512,1024,3,3)

img_out = np.zeros(shape)
## so shape of img_out = (4,512,1024,3,3)


text:
Q: Data storage format for iPad app. Export to excel I am fairly new to Objective C and iOS programming but am constantly trying to learn as much as I can.
I am about to start an iPad project which will involve storing large amounts of data which will need to be exported to one extremely large excel spreadsheet.(it's for a friend....they currently enter massive amounts of data into excel by hand so that they can analyze it).
This database contains over 400 names(this number is constantly growing) and the app will be very functionally similar to to built in contacts app, except that for each name there will be approximately 2,000 attributes. These attributes will be entered across tens, if not over a hundred views.
The excel file will be located on a local server and the database will be synced with it over wifi. If I have to write a server side application to handle this, I happily will.
My question is this:
What data storage method would serve best for my purpose accounting for the sheer size of the database and the need to export to excel? (i.e. CoreData?, SQLLite?, XML?)
I sincerely appreciate any help you might offer.
James

A: A framework for relational data such as Core Data or SQlite would work well for selecting and working with subsets of data. There's no innate export-to-Excel functionality but you could export a csv (comma-separated-value) file that Excel can import.

A: It'll be harder to create a CoreData store on the server end. I'd suggest using and SQLite DB. FMDB is decent frontend for using SQLite on the iPhone, but there are many others.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Contact us form error I am using contact us form using php and i am not well known abt php since im working in java now.
I am facing one problem in contact form that is im using 1 php file and contact form html, but the thing is when click the submit button it downloads the php file but it is not sending any mail from the contact form.
But i've mentioned the to mail in the php content page but no process is done.
Can anyone help to do it or share if any process like sending mail from contact form using php? It can be just sample form also.

A: If it is downloading the PHP file, then the server is not processing the file for PHP statements. You need to install PHP on the server and make sure it is properly configured.


text:
Q: How to sketch a curve given its equation? I am given the equation of a curve which is $y = x(x-2)^2 $ and I am asked to sketch that curve.
What I've already done: I already found the stationary points of the curve by differentiating the equation and I got $(2,0) $ and $(2/3, 32/27) $ and I found the nature of the two stationary points and the result is when $x=2 $, its a minimum and when $x=2/3$ , its a maximum.
What do I do next?

A: You know that $y=x(x-2)^2$ has zeros at $x=0$ and at $x=2$.
Let's look at the important attributes of the graph of $y(x)$ moving from left to right.
When $x <0$ then $y <0$ so the graph starts in the lower left hand quadrant.
At $x=0$ you know that $\frac{\text{d}y}{\text{d}x}=4$ which is positive, so at $(0,0)$ the graph of $y(x)$ crosses the $x$-axis from the lower left hand quadrant into the upper right hand quadrant.
You then have a maximum at $(2/3, 32/27)$ so the graph is horizontal at that point. As you move from left to right the graph stops going upwards at $(2/3, 32/27)$ and heads downwards.
At $(2,0)$ you have a root and a minimum (this is because of the factor of $(x-2)^2$), so here the graph just touches the $x$-axis as it comes down from $(2/3, 32/27)$, but then turns upwards again.
When $x >2$ then $y >0$ so the graph ends in the upper right hand quadrant.

A: given the curve $y=x(x-2)^2$
As you have said the best way to start would be to check for a few things:

*

*asymptotes

*discontinuities

*stationary points

*roots (points at which it crosses the axis)

First of all, for all real $x$, $y$ is also real so this function can be kept in just the real range.
Roots to this equation are easy to find as it has already been factorised, so we can easily see the points $(0,0)$ and $(2,0)$ for where it crosses the $x$ axis. We can already see from our first root that this function passes through the origin, so we already know where it crosses the $y$ axis.
We can clearly see that there are no usable asymptotes as $\lim_{x\to \infty}f(x)=\infty$. We also know that it is a continuous, non-periodic function.
To find the stationary points we just differentiate:
$$y=x(x-2)^2$$
$$\frac{dy}{dx}=(x-2)^2+2x(x-2)$$
let $\frac{dy}{dx}=0$ and solve for $x$
we get:
$$(x-2)(3x-2)=0$$
and so the $x$ values for our stationary points are:
$x=2$ and $x=\frac{2}{3}$
we now input each of these into our function to find the points:
$$f(2)=2(2-2)^2=0$$
$$f\left(\frac{2}{3}\right)=\frac{2}{3}\left(\frac{2}{3}-2\right)^2=\frac{32}{27}$$
so now we have the points $(2,0)$ and $\left(\frac{2}{3},\frac{32}{27}\right)$
we can see that one of our roots is repeated $(x-2)^2$ and it is also a stationary point. This suggests to us that the line 'touches' this point twice and therefore it must not pass the axis here.
When we check we can see that $f(2.1)=0.021$ so the line approaches this point from above. We also know that this curve has two distinct roots and is a cubic where the coefficient of the $x^3$ term is positive so is must form an S shape, coming from negative below $x=0$ and tending to infinity for x>0, so we can plot the points we know and draw this characteristic curve through them.
Hope this helps

A: That's already really good, now try to draw these points inside a coordinate system.
Then it might be helpful to expand the equation into $y = x^3-4x^2+4x$ which tells you two things: First, the curve goes through the origin, and second, it has degree $3$.
Such curves have a very characteristic shape: As the maximum comes first (reading from the left), the  curve will come from $-\infty$, pass through the origin, go up to the maximum, then drop down to the minimum, and then go up into $+\infty$.
Spoiler: This is what it looks like: http://www.wolframalpha.com/input/?i=y+%3D+x(x-2)%5E2


text:
Q: Mostrar usuarios que no tienen un departamento Quiero mostrar los nombres de las personas que no tienen un departamento
Los datos son:
+----+---------+----------------+    +----+--------------------+
| id | Nombre  | idDepartamento |    | id | NombreDepartamento |
+----+---------+----------------+    +----+--------------------+
| 44 | Daniel  |        1       |    | 1  |    Desarrollo      |
+----+---------+----------------+    +----+--------------------+
| 45 | Manuel  |        0       |    | 2  |   Contabilidad     |
+----+---------+----------------+    +----+--------------------+
| 47 |  Juan   |        0       |
+----+---------+----------------+
| 49 | Alfonso |        0       |
+----+---------+----------------+

Los quiero mostrar en un select de html usando razor en asp.net-mvc-5
Tengo el siguiente código:
<select class="form-control" name="UsuarioSelect" multiple>
  @{foreach (var departamento in Model.Departamentos)
  {
    <optgroup label="@departamento.Departamento"></optgroup>
    foreach (var empleado in Model.Empleados)
    {
      if (empleado.IdDepartamento == departamento.id)
      {
        <option value="@empleado.id">@empleado.Nombre</option>
      }
    }
  }}
</select>

Pero no tengo idea de como mostrar los usuarios que no tienen un departamento.
¿Qué necesito agregar en mi código para que se muestren?
Lo que quiero lograr es algo como esto:

$('select').select2({
  width: '50%'
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<select class="Select2" multiple>
  <optgroup label='Desarrollo'></optgroup>
  <option value='44'>Daniel</option>
  <optgroup label='Contabilidad'></optgroup>
  <optgroup label='Sin Departaento'></optgroup>
  <option value='45'>Juan</option>
  <option value='47'>Manuel</option>
  <option value='49'>Alfonso</option>
</select>

A: Intenta lo siguiente usando Linq en tu en tu razor:
<select class="form-control" name="UsuarioSelect" multiple>
  <optgroup label="Sin Departamento"></optgroup>
  @foreach (var empleado in Model.Empleados.Where(i=>i.IdDepartamento == 0))
  {
    <option value="@empleado.id">@empleado.Nombre</option>
  }

  @{foreach (var departamento in Model.Departamentos)
  {
    <optgroup label="@departamento.Departamento"></optgroup>
    foreach (var empleado in Model.Empleados.Where(i=>i.IdDepartamento == departamento.id))
    {
       <option value="@empleado.id">@empleado.Nombre</option>
    }
  }
</select>


text:
Q: Kubeflow Pipelines error on GCP - Run doesn't end After submitting the "run" using Jupyter notebook, when I go to the Kubeflow pipeline dashboard, I can see my "run" submitted & running but it doesn't end even after few hours & doesn't show any logs either.
I have tried running the "DEMO XG-BOOST" but the same issue persists & the "run" doesn't end.
Can someone please help me understand if there is any issue with the account settings or any other issue which I'm missing because I have tried to check documentation & other websites but couldn't understand why this occurs.
Please note that this "run" was working fine (creating the pipeline flow) on coursera using quicklabs (Covertype classifier)
error snapshot
Using below versions:
kfp 1.8.12 ;
kfp-pipeline-spec 0.1.14;
kfp-server-api 1.8.1;
Python 3.7.12
If there is any other information which I have missed to put above, please let me know so I could share that information that could help us solve this issue.

A: The issue mentioned above has been resolved. The part where "DEMO XG-BOOST" run doesn't end has been resolved by selecting "Use emissary executor" option while creating the pipeline.
see the snapshot
When we launch the pipeline with this setting, it solved the issue & we can run complete pipelines now.
More details:
We took support from GCP & they have mentioned that the issue might have been caused by a recent upgrade of the GKE cluster which removes the docker runtime (https://www.kubeflow.org/docs/components/pipelines/installation/choose-executor/#docker-executor). Namely, the Docker executor is the default workflow executor and depends on docker container runtime, which is deprecated on Kubernetes 1.20+. We were using a GKE cluster whose version was 1.21.6. Hence the issue. So, we used the documentation (https://www.kubeflow.org/docs/components/pipelines/installation/choose-executor/#migrate-to-emissary-executor) & migrated to the Emissary executor (instead of Docker) which has solved our issue.


text:
Q: Creating MP4/M4A files with Chapter marks I am trying to join together several audio files into one mp4/m4a file containing chapter metadata.
I am currently using QTKit to do this but unfortunately when QTKit exports to m4a format the metadata is all stripped out (this has been confirmed as a bug by Apple) see sample code. I think this rules QTKit out for this job, but would be happy to be proven wrong as it is a really neat API for it if it worked.
So, I am looking for a way to concatenate audio files (input format does not really matter as I can do conversion) into an m4a file with chapters metadata.
As an alternative to code, I am open to the idea of using an existing command line tool to accomplish this as long as it is redistributable as part of another application.
Any ideas?

A: Audiobook Maker does something like this, and I believe it uses ffmpeg under the hood.  It's open source, so maybe its worth a look?

A: commandline tool mp4chaps does the work. It is from mp4v2-utils package if you use Ubuntu. Remember to specify qt format for quicktime, because Nero format chapter marks seems to be used less nowadays.

A: I discovered these guys: sensoryresearch who license an API for writing chapter/text/link tracks to MP4s (which is what an M4A is).

A: Depending on where the bug is, you could try going straight to the QuickTime C APIs to write the movie file.  You might also try adding the chapters track using the C APIs.
Any word on when Apple will fix the bug?  I am planning to create enhanced podcasts with QTKit, and need this to work.


text:
Q: Vertices and connected vertices I 'd like to load an STL, list all its vertices and get the vertices they are connected to so I can calculate their angles and distance.
Would it be possible to do this with three.js ?
My idea is to load low poly stl and create connectors that I could 3D print and assemble with rods, to recreate a wireframe representation of the stl in real life.
For example, load a cube stl file, and create 8 connectors that would each have 3 branches, something like the image below.

A: The way this question is worded, you really should have applied a bounty. but I was curious about how to do it, because I like your idea. Note though that even a simple stl or obj file could contain thousands of edges. That's a lot of dowels to print. Even a simple, rough sphere can contain hundreds of edges.
This function returns a list of edges and nodes.
The edges list is very simple. Each array position is an ID, and the value is the length of the edge. For example if you need to find the length of edge 15, just find edges[15]. The value will be the length of the line.
The nodes contain a list of their own edges. I believe these are stored counterclockwise, but, you'll want to test that. The winding order of each node will determine if your vertices print correctly and may still need to be resolved. These look like [0,2,4] for example. You can use these values to find their lengths. The nodes also contain an angle object. These angles are kept in a list in the same order as the edges. The property name of each node is it's local position in space delimited by a colon. For example a node's unique name might look like: "19.09830093383789:190.2113037109375:58.778526306152344"
The angles of each are radians in local space, listed in the same order as the edges. This is important: the angles are in radians in local space. If your model has a parent model with a transformation on it, you need to apply a transformation matrix to obtain world space. The model also can't have any flipped faces.
For example, this node connects to edge 0,2,and 4:
Node > "19.09830093383789:190.2113037109375:58.778526306152344"
Node.edges > [0, 2, 4]
Node.angles > [0.31415926112916176, 0.31415926112916176, 0.31415926228226293]
This will work with nodes with N number of edges. However, the model needs to be watertight to work in the real world.
function getEdges(geometry){
    var material = new THREE.LineBasicMaterial({ color: 0xff0000});
    var edges = new THREE.EdgesGeometry( geometry );
    var vertexList = edges.attributes.position.array;
    var nodes = {};
    var edges = [];
    var edgeID = 0;
    for(var i=0; i<vertexList.length;i=i+6){
      var geometry = new THREE.Geometry();
      var node1ID = vertexList[i]+":"+vertexList[i+1] +":"+ vertexList[i+2];
      var node2ID = vertexList[i+3]+":"+vertexList[i+4] +":"+ vertexList[i+5];
      var node1 = nodes[node1ID];
      var node2 = nodes[node2ID];
      if(node1 == undefined){
        node1 = {};
        node1.edges = [];
        node1.angles = [];
        nodes[node1ID] = node1;
      }
        if(node2 == undefined){
        node2 = {};
        node2.edges = [];
        node2.angles = [];
        nodes[node2ID] = node2;
      }
      var vec1 = new THREE.Vector3(vertexList[i], vertexList[i+1], vertexList[i+2]);
      var vec2 = new THREE.Vector3(vertexList[i+3], vertexList[i+4], vertexList[i+5]);
      geometry.vertices.push(vec1);
      geometry.vertices.push(vec2);
      geometry.computeLineDistances();
      var edge = new THREE.Line(geometry, material);

      node1.edges.push(edgeID);
      node1.angles.push(vec1.angleTo(vec2));

      node2.edges.push(edgeID);
      node2.angles.push(vec2.angleTo(vec1));

      edges[edgeID] = geometry.lineDistances[1];

      mesh.add(edge);
      edgeID++;
    }
    return {nodes:nodes, edges:edges};
  }

working fiddle:
https://jsfiddle.net/y1hs9x4v/


text:
Q: "Are fees paid current?" meaning This is an extract from a form applying for mortgage relief from PNC (PDF, 3.9MB):

Section 2C of this application asks about condominium or homeowner association fees. It says "Are fees paid current?"
What does it mean? Does it mean that whether I paid the fees up-to-date? Is it asking for the previous late payment or no? How does the word "current" translate here? Or is "paid current" one word?

A: "Fees paid" should be read as one phrase.  Are fees paid current? means is the account up to date.


text:
Q: Calculate diameter distributions from irregular 3d cylinder I have 3d models (stl-files) of irregular cylinder-like objects that I would like to measure at set intervals along the long axis. The result should be a distribution of diameters (or of the lengths of the long and short axes of the elliptical cross-section).
 Is there a way to do this using built-in functions of one of the standard pieces of 3d software (Geomagic, Meshlab, Solidworks)?

A: Here's Solidworks API approach that I would take :
1 Collect all the edges of your body, convert them to vectors. If it's a curve just take endPoint - startPoint. IPartDoc::GetBodies2 IBody2::GetEdges
2 Using those vectors as potential axes figure out the smallest box that your body fits into using IBody2::GetExtemePoint.
3 Largest dimension of the box will be your long axis.
**If you know orientation of your body beforehand (ie top of the cylinder always looks towards x/-x) you can skip first three steps
4 Take 4 faces of the box that you found that are parallel to the longest dimension. For example if your box is x,y,z axes and x is the longest you must take 2 faces parallel to xy plane and 2 faces parallel to xz plane.
5 For each of those 4 faces generate a grid of points that will evenly cover the face, number of points depends on the accuracy of the result that you want, I'd suggest to start with 100 points per face.
6 Shoot rays from those points though the body with IModelDoc2::RayIntersections.
7 Disregard rays that don't intersect the body, those that do will give you 2 points - an entry and an exit, calculating the distance between them will give you your diameter.
8 Because your rays will be intersecting cylinder across the surface not only in the thickest part use only biggest diameter per row of grid points.
This is the most generic approach that would work for any 'irregular cylinder-like object' given that height of the cylinder is bigger than its diameter.
Let me know if you need clarification on any of the steps, I can draw some sketches.


text:
Q: What's the use of the logOnly option in ngrx DevTools? I've read the minimalistic docs at https://github.com/ngrx/platform/tree/master/docs/store-devtools, and understood that you can add instrumentation as follows:
StoreDevtoolsModule.instrument({
  logOnly: environment.production
})

Supposedly, if the logOnly flag is true, your app will connect to the Redux DevTools extension in a log only mode, it'll have very little overhead as it shouldn't store the state data, but only log the action names that are happening during the runtime.
But in my experiments, I still see the state data in the ngrx DevTools panel, so what're the benefits of using logOnly:true?

A: According to the documentation:

logOnly: boolean - connect to the Devtools Extension in log-only mode. Default is false which enables all extension features.

With a link to the extensions features.
Based on this we can assume that setting logOnly to true will switch the following redux-devtools-extension features off:
const composeEnhancers = composeWithDevTools({
    features: {
        pause: true, // start/pause recording of dispatched actions
        lock: true, // lock/unlock dispatching actions and side effects
        persist: true, // persist states on page reloading
        export: true, // export history of actions in a file
        import: 'custom', // import history of actions from a file
        jump: true, // jump back and forth (time travelling)
        skip: true, // skip (cancel) actions
        reorder: true, // drag and drop actions in the history list
        dispatch: true, // dispatch custom actions or action creators
        test: true // generate tests for the selected actions
    }
})

This is ideal for production environments as you may not need or want these primarily dev-focused features running in your live application.

A: Using logOnly guarantee the integrity of the state.
You can't modify it as e.g action dispatcher is switched off. In log-only mode, you can review the log, but you can't modify it.


text:
Q: Android Studio not detecting Microsoft Android Emulator I installed Microsoft's Android Emulator from here which can now work without disabling Hyper-V on Windows 10. I was following the instructions in this post and everything was working smooth until yesterday. I was successfully able to debug my app in MS android emulator.

Today morning I closed the emulator and started it again. Now, When I start running the app to test it then the MS Android emulator is not showing up in Select Deployment Target window of Android Studio as below. Nexus 5X API 28 emulator visible under Available Virtual Devices is Google's Android emulator which doesn't work with Hyper-V enabled due to reasons mentioned here.

I've already launched the MS Android simulator and it is up and running:

I can see it running in Hyper-V as well as shown below:

Not sure what happened suddenly and it stopped working altogether. Can anyone suggest me the reason behind it or I'm missing something?

A: If it didn't detected by IDE, try to rerun the emulator and check if it is detecting again or not.
Also, you can try this too:

Tools -> Android -> Enable ADB Integration

If it is already enabled, try to disable and re enable it, seems like this works most of the times.

EDIT: You may want to check:
https://stackoverflow.com/a/38788436/4409113
Changing the value Path then running following commands:
adb kill-server
adb start-server

Might help.

A: I happened to resolve it by chance. Sharing my experience in case it helps someone in future.
Initially what I was doing is as below:

*

*Start Visual Studio Emulator for Android application which contains the list all the device profiles.

*Choose an appropriate device profile and install it.

*Run the installed profile and launch the emulator.

*Start Android studio, open the project and launch the app.

I simply reversed the above steps to resolve my issue. First close everything including Android Studio, emulators, device profile window etc.:

*

*At first, start Android studio, open the project and hit Run app button to show Select Deployment Target window.

*Now, start Visual Studio Emulator for Android application which contains the list of all the device profiles.

*Choose an appropriate device profile and install it.

*Run the installed profile and launch the emulator. Wait for the Android operating system to get started fully.

*The Connected Devices section in Select Deployment Target window would refresh on its own to start showing Microsoft's Android Emulator.

A: The adb.exe can be seen as an infected file by antivirius software.  So need to exclude once reinstated.


text:
Q: Function to show/hide menu not working in iOS I have created a menu system where if I click on the top level menu item it will display the submenu, and then if I click off of it anywhere else on the page the submenu will disappear again. This works fine on desktop and android but not iOS.
$("#menu > li").click(function(e) {
    e.stopPropagation();
});
$("#menu > li > ul").click(function(e) {
    e.stopPropagation();
});
$("body").on("click", function(){
    console.log('test');
    $("#menu > li:nth-child(1) > ul").fadeOut("slow");
    $("#menu > li:nth-child(2) > ul").fadeOut("slow");
    $("#menu > li:nth-child(3) > ul").fadeOut("slow");
});

This piece of code is fairly simple. Fadeout if they click anywhere on the page (e.g. the <body> tag). And allow them to click within the menu by stopping the click events within the menu.
I have no idea why this wouldn't work in iOS, any ideas or suggestions would be greatly appreciated.

A: Issue resolved by adding 'touchstart'.
$("#menu > li").on("click touchstart", function(e) {});


text:
Q: Jump/tailcall to another function I have two functions, looking like this in C++:
void f1(...);
void f2(...);

I can change the body of f1, but f2 is defined in another library I cannot change. I absolutely have to (tail) call f2 inside f1, and I must pass all arguments provided to f1 to f2, but as far as I know, this is impossible in pure C or C++. There is no alternative of f2 that accepts a va_list, unfortunately. The call to f2 happens last in the function, so I need some form of tailcall.
I decided to use assembly to pop the stack frame of the current function, then jump to f2 (it is actually received as a function pointer and in a variable, so that's why I first store it in a register):
__asm {
    mov eax, f2
    leave
    jmp eax
}

In MSVC++, in Debug, it appears to work at first, but it somehow messes with the return values of other functions, and sometimes it crashes. In Release, it always crashes.
Is this assembly code incorrect, or do some optimizations of the compiler somehow break this code?

A: The compiler will make no guarantees at the point you are digging around.  A trampoline function might work, but you have to save state between them, and do a lot of digging around.
Here is a skeleton, but you will need to know a lot about calling conventions, class method invocation, etc...
/
* argn, ..., arg0, retaddr */
trampoline:
    push < all volatile regs >
    call <get thread local storage >
    copy < volatile regs and ret addr > to < local storage >
    pop < volatile regs >
    remove ret addr
    call  f2
    call < get thread local storage >
    restore < volatile regs and ret addr>
    jmp f1
    ret

A: You have to write f1 in pure asm for it to be guaranteed-safe.
In all the major x86 calling conventions, the callee "owns" the args, and can modify the stack-space that held them.  (Whether or not the C source changes them and whether or not they're declared const).
e.g.  void foo(int x) { x += 1; bar(x); } might modify the stack space above the return address that holds x, if compiled with optimization disabled.  Making another call with the same args requires storing them again unless you know the callee hasn't stepped on them.  The same argument applies for tailcalling from the end of one function.
I checked on the Godbolt compiler explorer; both MSVC and gcc do in fact modify x on the stack in debug builds.  gcc uses add DWORD PTR [ebp+8], 1 before pushing [ebp+8].

Compilers in practice may not actually take advantage of this for variadic functions, though, so depending on the definitions of your functions, you might get away with it if you can convince them to make a tailcall.
Note that void bar(...); is not a valid prototype in C, though:
# gcc -xc on Godbolt to force compiling as C, not C++
<source>:1:10: error: ISO C requires a named argument before '...'

It is valid in C++, or at least g++ accepts it while gcc doesn't.  MSVC accepts it in C++ mode, but not in C mode.  (Godbolt has a whole separate C mode with a different set of compilers, which you can use to get MSVC to compile code as C instead of C++.  I don't know a command-line option to flip it to C mode the way gcc has -xc and -xc++)

Anyway, It might work (in optimized builds) to write f2(); at the end of f1, but that's nasty and completely lying to the compiler about what args are passed.  And of course only works for a calling convention with no register args.  (But you were showing 32-bit asm, so you might well be using a calling convention with no register args.)
Any decent compiler will use jmp f2 to make an optimized tail-call in this case, because they both return void.  (For non-void, you would return f2();)

BTW, if mov eax, f2 works, then jmp f2 will also work.
Your code can't work in an optimized build, though, because you're assuming that the compiler made a legacy stack-frame, and that the function won't inline anywhere.
It's unsafe even in a debug build because the compiler may have pushed some call-preserved registers that need to be popped before leaving the function (and before running leave to destroy the stack frame).

The trampoline idea that @mevets showed could maybe be simplified: if there's a reasonable fixed upper size limit on the args, you can copy maybe 64 or 128 bytes of potential-args from your incoming args into args for f1.  A few SIMD vectors will do it.  Then you can call f1 normally, then tail-call f2 from your asm wrapper.
If there are potentially register args, save them to stack space before the args you copy, and restore them before tailcalling.


text:
Q: How to bulk replace links that are embed to words in Excel cells I have a huge list of words that have links. All the URLs have text that repeats. I want to mass replace this text with another. Right now, "Replace all" only searches between words, not through the embed hyperlinks behind words.
Please help. Thanks.

A: The only way to do this is with a Macro:
Public Sub ReplaceHyperlinkURL(FindString As String, ReplaceString As String)
Dim LinkURL, PreStr, PostStr, NewURL As String
Dim FindPos, ReplaceLen, URLLen As Integer
Dim MyDoc As Worksheet
Dim MyCell As Range
On Error GoTo ErrHandler

Set MyDoc = ActiveSheet
For Each MyCell In MyDoc.UsedRange
If MyCell.Hyperlinks.Count > 0 Then
 LinkURL = MyCell(1).Hyperlinks(1).Address
 FindPos = InStr(1, LinkURL, FindString)
 If FindPos > 0 Then 'If FindString is found
  ReplaceLen = Len(FindString)
  URLLen = Len(LinkURL)
  PreStr = Mid(LinkURL, 1, FindPos - 1)
  PostStr = Mid(LinkURL, FindPos + ReplaceLen, URLLen)
  NewURL = PreStr & ReplaceString & PostStr
  MyCell(1).Hyperlinks(1).Address = NewURL 'Change the URL
  End If
 End If
Next MyCell
Exit Sub
ErrHandler:
MsgBox ("ReplaceHyperlinkURL error")
End Sub

The ReplaceHyperlinkURL code must be placed in a VBA code module. From a spreadsheet, Press Alt+F11 to open the VBA Editor. Then select Insert - Module from the menu. Copy the code and paste it into the module. Then save the module.
In order to run the procedure, create a macro that contains following line and run the macro in Excel. Be sure to replace the FindText with the portion of the address you want to find and ReplaceText with the text you want to replace it with.

Call ReplaceHyperlinkURL("FindText", "ReplaceText")

Source


text:
Q: Find by array of IDs and get a sorted response I have an array of IDs:
const arrayIds =
    ['5f43e8ad0500ed0017ff9f65',
    '5f46d26c4dec5600173e60fe',
    '5f47f4a1dae1140017f2a409',
    ...]

And I can get all documents using mongoose find:
const documents = await Model.find().where('_id').in(arrayIds).exec();

But the problem is the response is not sorted. I would like to get an array of documents sorted exactly like arrayIds.
Can you help me? Thank you so much.


text:
Q: @gorhom-react-native-bottom-sheet | How to add a clickable custom backdrop to the bottom sheet I am using https://github.com/gorhom/react-native-bottom-sheet to add a bottom sheet.
I need to add a custom backdrop to the bottom-sheet , I am able to add it as below :
const CustomBackdrop = ({animatedIndex, style, onPress}) => {
  // animated variables
  const containerAnimatedStyle = useAnimatedStyle(() => ({
    opacity: interpolate(
      animatedIndex.value,
      [1, 0],
      [0.5, 0],
      Extrapolate.CLAMP,
    ),
  }));

  // styles
  const containerStyle = useMemo(
    () => [
      style,
      {
        backgroundColor: '#000',
      },
      containerAnimatedStyle,
    ],
    [style, containerAnimatedStyle],
  );

  return (
    <AnimatedPressable onPress={() => onPress(0)} style={containerStyle} />
  );
};

   <BottomSheetModal
  backdropComponent={(props) => (
    <CustomBackdrop {...props} onPress={handleSheetChanges} />
  )}
>
  ...
</BottomSheetModal>;

But now the issue is that if above backdrop is added, it does not allow the click events under the sheet as mentioned here
I also tried adding another way of adding backdrop :
 <BottomSheetModalProvider>
      {isExpanded && (
        <TouchableWithoutFeedback onPress={() => handleSheetChanges(0)}>
          <View style={[styles.backDrop]} />
        </TouchableWithoutFeedback>
      )}

      <BottomSheetModal> ...

But with this approach, backdrop is visible only when bottom sheet has snapped to a point ( updating isExpanded on onChange event ) , is there a way where I can get the event as soon as drag of action sheet has started so that backdrop is visible as the bottom sheet is pulled up ?
Many Thanks.


text:
Q: Concatenating string with String Builder? I want to generate a string with a format
'abc','avc',abc','avc',abc','avc','abc','avc',abc','avc',abc','avc','abc','avc'
The value can be anything or it can be empty.This is my code
        string sep = "";
        StringBuilder sb = new StringBuilder();
        foreach(var l in label.Rows)
        {
            sb.Append(sep).Append(l.Text);
            sep = ",''";
        }

this returns me
abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc,''abc
any help will be appreciated.

A: Of course using Linq will be simpler and more readable, but if you want to know what has gone wrong in your code then
// Start with the initial quote
string sep = "'";
StringBuilder sb = new StringBuilder();
foreach(var l in label.Rows)
{
    sb.Append(sep).Append(l.Text);
    // Quote before and after the comma
    sep = "','";
}
// You need an additional quote to close the string if there is any
if(sb.Length > 0)
   sb.Append("'");

Consider also that StringBuilder is not always faster than a simple concatenation. If this code is performance sensitive I would try to measure what happen if you use a single sb.Append(sep + l.Text) instead of calling two times the Append method

A: More simple with LinQ and method Join
string s = string.Join(",", label.Rows.Select(l => $"'{l.Text}'"));


text:
Q: how to compare key to each other in a dictionary using javascript Here is my code, in which I am getting all data from wcf service and storing that data in to a dictionary with key.
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
app.use(bodyParser.urlencoded({extended: true}));
var parseString = require('xml2js').parseString;
var BasicHttpBinding = require('wcf.js').BasicHttpBinding
        , Proxy = require('wcf.js').Proxy
        , binding = new BasicHttpBinding(
                {
                })
        , proxy = new Proxy(binding, "http://localhost:9877/IDBReport/basicHttp")
        , message = "<Envelope xmlns='http://schemas.xmlsoap.org/soap/envelope/'>" +
        "<Header />" +
        "<Body>" +
        "<OrderReport xmlns='http://tempuri.org/'>" +
        "<value></value>" +
        "<value></value>" +
        "<value>+ req.query.start +</value>" +
        "<value>+ req.query.end +</value>" +
        "<value></value>" +
        "<value></value>" +
        "<value></value>" +
        "<value></value>" +
        "<value></value>" +
        "</OrderReport>" +
        "</Body>" +
        "</Envelope>";
proxy.send(message, "http://tempuri.org/IDBReport/OrderReport", function (message, ctx) {
    app.set("view engine", "jade");
    app.get('/', function (req, res) {
        parseString(message, function (err, result) {

            var response = result['s:Envelope']['s:Body'][0].OrderReportResponse[0].obj[0];
            var marketOrder = response['a:MarketOrder'];
            var dict1 = [];
            for (var i = 0; i < marketOrder.length; i++) {
                var keys1 = [];
                var keys = [];
                keys.push({
                    k1: marketOrder[i]['a:SecurityExchange'],
                    k2: marketOrder[i]['a:Symbol'],
                    k3: marketOrder[i]['a:MaturityMonthYear']

                });
                if (keys1.indexOf(keys[0].k1) && keys1.indexOf(keys[0].k2) && keys1.indexOf(keys[0].k3)) {
                    keys1.push(keys[0].k1, keys[0].k2, keys[0].k3);

                }
                for (var k1 in keys1[0]) {
                    var dict = {};
                    dict[keys1] = marketOrder[i];

                    if (dict1.indexOf(dict)) {
                        dict1.push(dict);
                    }
                }
            }
             for (var i = 0; i < dict1.length; i++) {
            for(var t in dict1[i]){
                 console.log(dict1[i]); //In 'dict1' all data is storing
            }}

//            var serialized = JSON.stringify(dict1, null, 4);
//            console.log(serialized);
            res.render('MarketPosition', {mrkt: marketOrder});

        });
    });
});

var server = app.listen(3000, function () {
    console.log('Server is running..http://localhost:3000/');
});

Now I want to compare all keys to each other, and want to print only those record which are not repeating by key(means if the key value is same, it should not print the data) how should I do that.
{ 'CME,ES,201703':
   {
     'a:CustomerOrFirm': [ 'Customer' ],
     'a:MaturityMonthYear': [ '201703' ],
     'a:Modifier': [ '' ],
     'a:MsgSeqNumber': [ '0' ],
     'a:MsgType': [ 'D' ],
     'a:OrdType': [ 'Limit' ],
     'a:SecurityExchange': [ 'CME' ],
     'a:SecurityId': [ [Object] ],
     'a:SecurityType': [ 'FUT' ],
     'a:SenderCompId': [ 'TRDFIRSTDTS' ],
     'a:SendingTime': [ '2016-12-20T11:44:05' ],
     'a:Symbol': [ 'ES' ],
     'a:TTOrderId': [ '' ],
     'a:TargetCompId': [ 'TTDEV25O' ],
     'a:TimeInForce': [ '0' ],
     'a:TmpOrderQty': [ '0' ],
     'a:TransactTime': [ '2016-12-20T11:44:04' ] } }
{ 'CME,ZB,201703':
   { 'a:CustomerOrFirm': [ 'Customer' ],
     'a:MaturityMonthYear': [ '201703' ],
     'a:Modifier': [ '' ],
     'a:MsgSeqNumber': [ '0' ],
     'a:MsgType': [ 'D' ],
     'a:OrdType': [ 'Market' ],
     'a:SecurityExchange': [ 'CME' ],
     'a:SecurityId': [ [Object] ],
     'a:SecurityType': [ 'FUT' ],
     'a:SenderCompId': [ 'TRDFIRSTDTS' ],
     'a:SendingTime': [ '2016-12-20T11:44:52' ],
     'a:Symbol': [ 'ZB' ],
     'a:TTOrderId': [ '' ],
     'a:TargetCompId': [ 'TTDEV25O' ],
     'a:TimeInForce': [ '-' ],
     'a:TmpOrderQty': [ '0' ],
     'a:TransactTime': [ '2016-12-20T11:44:50' ]} }
{ 'CME,ZB,201703':
   { 'a:CustomerOrFirm': [ 'Customer' ],
     'a:MaturityMonthYear': [ '201703' ],
     'a:Modifier': [ '' ],
     'a:MsgSeqNumber': [ '0' ],
     'a:MsgType': [ 'D' ],
     'a:OrdType': [ 'Market' ],
     'a:SecurityExchange': [ 'CME' ],
     'a:SecurityId': [ [Object] ],
     'a:SecurityType': [ 'FUT' ],
     'a:SenderCompId': [ 'TRDFIRSTDTS' ],
     'a:SendingTime': [ '2016-12-20T11:44:52' ],
     'a:Symbol': [ 'ZB' ],
     'a:TTOrderId': [ '' ],
     'a:TargetCompId': [ 'TTDEV25O' ],
     'a:TimeInForce': [ '-' ],
     'a:TmpOrderQty': [ '0' ],
     'a:TransactTime': [ '2016-12-20T11:44:50' ] } }

I am getting output like above.

A: Push the used keys into an array, then as you loop through your dictionary, check if the array contains the key, if so, don't print it.

var dictionary = [{ Key: 'A', Value: 'Key 1'}, { Key: 'A', Value: 'Key 1'}, { Key: 'B', Value: 'Key 2'}, { Key: 'B', Value: 'Key 2'}, { Key: 'C', Value: 'Key 3'}];

var usedKeys = [];

for (var i = 0; i < dictionary.length; i++) {
  if (usedKeys.indexOf(dictionary[i].Key) == -1) {
    console.log(dictionary[i].Value);
  }

  usedKeys.push(dictionary[i].Key);
}


text:
Q: Неправильные аргументы функции fit Здравствуйте!
# ----#
# количество классов для обучения
class_total = 0
# лист классов
class_list = []
# количество файлов в каждой папке для обучения
files_total = 100
# лист файлов
files = []
files2 = []
# файлов загружено в словарь
file_num = 0
# классов загружено в словарь
class_num = 0

#print("Введите количество классов: ")
#class_total = int(input())
class_total = 2

classes_written = 0
# while classes_written < class_total:
#     print("Введите класс номер " + str(classes_written + 1) + ": ")
#     class_list.append(input())
#     classes_written += 1
class_list.append('cpp')
class_list.append('python')

file_num = 0
while file_num < files_total:
    if os.path.isfile('O:/categories/' + class_list[class_num] + '/article_' + str(file_num) + '.htm'):
        current_file = open('O:/categories/' + class_list[class_num] + '/article_' + str(file_num) + '.htm', "r")

        line = current_file.read()
        trantab = line.maketrans(string.punctuation, ' ' * len(string.punctuation))
        r = line
        tokens = r.lower().translate(trantab)
        files.append(tokens)
    file_num += 1

input_files = {f:class_list[class_num] for f in files}

count_vectorizer = CountVectorizer()
counts = count_vectorizer.fit_transform(input_files.values())

classifier = MultinomialNB()
targets = input_files.values()

classifier.fit(counts, targets)

Это моя попытка обучения по загруженным текстам из папки. Сначала они загружаются строками, из них удаляются знаки препинания, после чего векторизуются.
Задача в общем состоит в том, что есть большой список выпарсенных вопросов со stackoverflow по разным языкам программирования, и необходимо классифицировать этот список по ним, распределив по папкам с соответствующими названиями.
При попытке самого обучения (последняя строка) получаю ошибку следующего содержания:
Traceback (most recent call last):
  File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.3.2\helpers\pydev\pydevd.py", line 1596, in <module>
    globals = debugger.run(setup['file'], None, None, is_module)
  File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.3.2\helpers\pydev\pydevd.py", line 974, in run
    pydev_imports.execfile(file, globals, locals)  # execute the script
  File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.3.2\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "C:/Users/Андрей/PycharmProjects/test/test.py", line 91, in <module>
    classifier.fit(counts, targets)
  File "D:\Program Files\WinPython-64bit-3.4.4.5Qt5\python-3.4.4.amd64\lib\site-packages\sklearn\naive_bayes.py", line 562, in fit
    X, y = check_X_y(X, y, 'csr')
  File "D:\Program Files\WinPython-64bit-3.4.4.5Qt5\python-3.4.4.amd64\lib\site-packages\sklearn\utils\validation.py", line 526, in check_X_y
    y = column_or_1d(y, warn=True)
  File "D:\Program Files\WinPython-64bit-3.4.4.5Qt5\python-3.4.4.amd64\lib\site-packages\sklearn\utils\validation.py", line 562, in column_or_1d
    raise ValueError("bad input shape {0}".format(shape))
ValueError: bad input shape ()

У меня есть такие вопросы:

*

*Как правильно пользоваться fit в данном контексте?

*fit должен получать на вход обучающие выборки всех типов сразу (и cpp, и python) или что-то одно?

A: *

*Более Python-way читать файлы следующий (обратите внимание на кодировку):
text = ''
with open('my_text_file.txt', 'rb') as input:
    text = input.read().decode('utf-8')

*Не ясно что у вас в файлах. Предположу что на каждой строчке отдельный вопрос.
Для задач машинного обучения принято создавать 2 матрицы. Точнее матрицу X (признаки) и вектор y (целевой класс - кодируется числом).
На этапе загрузки у вас должно получиться что-то вроде:
X = [
'text 1',
'text 2',
...
]
y = [1, 0, 2, 9, ...]

*После того как вы такие массивы подготовите можете их трансформировать. Текст != признаки (фичи). Фичи должны быть числовыми.

Для этого и нужен CountVectorizer. Он берет Ваш X и преобразует в нечто вроде
[
    [0, 0, 3],
    [0, 1, 2],
    [3, 3, 0],
    ...
]
Строки соответствуют вашим текстам, а в столбцах посчитаны вхождения отдельных слов/n-грамм (зависит от параметров CountVectorizer)

*Вероятнее всего глупый количественный анализ вам ничего хорошего не даст и придется дополнительно трансформировать эту матрицу через TFIDF

*Теперь непосредственно к ошибке. Там на вас ругаются за неправильную форму (размерность) переданных данных.
Поэтому делайте отладочную печать (или в отладчике смотрите) похожи ли передаваемые данные на то что я расписал в пункте 3. Количество срок в X должно быть равно длине y


text:
Q: SQL Server partition by month use persisted column and create clustered column store index at the same time I created a partitioned table in SQL Server as follows:
--Add File Groups
ALTER DATABASE TEST ADD FILEGROUP JAN;
GO
ALTER DATABASE TEST ADD FILEGROUP FEB;
GO
ALTER DATABASE TEST ADD FILEGROUP MAR;
GO
... to DEC

--create files
ALTER DATABASE [Test]
ADD FILE (NAME = N'JAN', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\Part_JAN.ndf' , SIZE = 5120KB , FILEGROWTH = 1024KB ) TO Filegroup [JAN]

ALTER DATABASE [Test]
ADD FILE ( NAME = N'FEB', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\Part_FEB.ndf' , SIZE = 5120KB , FILEGROWTH = 1024KB ) TO Filegroup [FEB]

ALTER DATABASE [Test]
ADD FILE ( NAME = N'MAR', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\Part_MAR.ndf' , SIZE = 5120KB , FILEGROWTH = 1024KB ) TO Filegroup [MAR]
... to DEC

--Create Partition Function & Partition Schema
DROP PARTITION FUNCTION partition_ByMonth

CREATE PARTITION FUNCTION partition_ByMonth (int)
    AS RANGE RIGHT FOR VALUES (2,3,4,5,6,7,8,9,10,11,12) ;
GO

-- Creates a partition scheme called myRangePS1 that applies myRangePF1 to the four filegroups created above
CREATE PARTITION SCHEME Partition_Schema_ByMonth
    AS PARTITION partition_ByMonth
    TO (JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC) ;
GO

--Create Table
CREATE TABLE [TEST].[TEST_PS_MONTH]
(
    [ID] [varchar](4) not null,
    [VALUE] [varchar](30) null,
    [ETL_Date] [datetime] not null,
    [ETL_Month] as MONTH([ETL_Date]) PERSISTED,

    CONSTRAINT(AK_TEST_PS_MONTH) UNIQUE NONCLUSTERED
    ([ID] ASC, [ETL_Month] ASC)
               WITH (PAD_INDEX= OFF) ON Partition_Schema_ByMonth([ETL_Month])
) ON Partition_Schema_ByMonth([ETL_Month])
GO

Then I want to create clustered column stored index
---- create clustered column store index (col compression)
CREATE CLUSTERED COLUMNSTORE INDEX [IDX_TEST_PS_MONTH]
ON TEST.TEST_PS_MONTH
WITH (DROP_EXISTING = OFF, COMPRESSION_DELAY = 0) ON Partition_Schema_ByMonth([ETL_Month])
GO

But I get the following error

Msg 35307, Level 16, State 1, Line 177
The statement failed because column 'ETL_Month' on table 'TEST_PS_MONTH' is a computed column. Columnstore index cannot include a computed column implicitly or explicitly.

Is there a way to compress a table that has been partitioned by computed month?
Thanks!

A: Since your objective is to maintain a 12 month sliding window based on the the ETL_Date month, you can partition on ETL_Date directly without a computed column. Create a partition function with initial monthly date boundaries. Then run monthly maintenance to truncate the oldest month data, remove the old boundary, and create a new boundary for the upcoming month. I suggest you use a single filegroup unless you have a need to do otherwise.
Below is an example of an initial setup for this strategy with 13 month boundaries (2020-01-01 through 2020-01-01).
CREATE PARTITION FUNCTION partition_ByMonth_Function (datetime)
    AS RANGE RIGHT FOR VALUES();
CREATE PARTITION SCHEME partition_ByMonth_Scheme
    AS PARTITION partition_ByMonth_Function
    ALL TO ([PRIMARY]);
GO
DECLARE
     @PartitionDate datetime = '20200101'
    ,@EndDate datetime = '20210101';
WHILE @PartitionDate <= @EndDate
BEGIN
    ALTER PARTITION SCHEME partition_ByMonth_Scheme NEXT USED [PRIMARY];
    ALTER PARTITION FUNCTION partition_ByMonth_Function() SPLIT RANGE(@PartitionDate);
    SET @PartitionDate = DATEADD(month, 1, @PartitionDate);
END;
GO
CREATE TABLE [TEST].[TEST_PS_MONTH]
(
    [ID] [varchar](4) not null,
    [VALUE] [varchar](30) null,
    [ETL_Date] [datetime] not null,
    CONSTRAINT AK_TEST_PS_MONTH UNIQUE NONCLUSTERED
        ([ID] ASC, [ETL_Date] ASC)
        WITH (PAD_INDEX= OFF) ON partition_ByMonth_Scheme([ETL_Date])
) ON partition_ByMonth_Scheme([ETL_Date]);
GO
CREATE CLUSTERED COLUMNSTORE INDEX [IDX_TEST_PS_MONTH]
ON TEST.TEST_PS_MONTH
WITH (DROP_EXISTING = OFF, COMPRESSION_DELAY = 0) ON partition_ByMonth_Scheme([ETL_Date])
GO

Example monthly maintenance script (remove oldest 2020-01-01 month and add new 2021-02-01 month):
DECLARE
      @OldestPartitionDate datetime = '20200101'
    , @NewPartitionDate datetime = '20210201';
BEGIN
    TRUNCATE TABLE [TEST].[TEST_PS_MONTH] WITH(PARTITIONS ( $PARTITION.partition_ByMonth_Function(@OldestPartitionDate) ) );
    ALTER PARTITION FUNCTION partition_ByMonth_Function() MERGE RANGE(@OldestPartitionDate);
    ALTER PARTITION SCHEME partition_ByMonth_Scheme NEXT USED [PRIMARY];
    ALTER PARTITION FUNCTION partition_ByMonth_Function() SPLIT RANGE(@NewPartitionDate);
END;
GO


text:
Q: New Ubuntu installation with Win 10 no dual boot screen I am very new to this and hope someone can help.
I have just installed Ubuntu 20.04.1.I installed it while keeping my win 10. I wanted it as a dual boot laptop. I burned the iso on a disk, I followed the loading sequence. I selected ' along side existing o/s. once completed I got the 'restart laptop'.
Now, should I get a screen after the Acer logo to select which operating system? as I don't get any. The laptop just starts up with windows as usual. Do I have to select something in win 10 to show a dual boot screen. I have tried to reinstall and this went very smoothly..
Thanks

A: Turn on your computer than Keep clicking escape untill it takes you to the menu then go to boot manager there will be windows and ubuntu, select ubuntu hit enter and it will boot ubuntu..

Go to the boot options and change the boot order and put ubuntu at the top, with the f5 and f6 keys..

A: Try what Nmath said and after this check in your BIOS the Boot Order. Seems here is "Windows boot manager" selected. Check if you have other options to boot and use it for test.
If you choose the right boot device, you will get the GRUB Menu every boot where you can choose what you want to boot.


text:
Q: Execute shell script after successful connection with server create a server on port 790. This should be a listening port in continuous mode which runs something which tell you how many files can be found in /root. When you are counting you should ignore hidden files.
Here is I have done

*

*I have created file at /root/script1 file which consists of the counts of the files in root

*Created 'scr.sh'
#!/bin/bash
ls | wc -l > /root/counts

*creating the server
netcat -l 127.0.0.1 -p 790 -e 'cat /root/script1' --continuous

*connecting with the server
netcat 127.0.0.1 790
How do I call scr.sh file while connecting with the server so that after every successful connection the script1 file updated which holds the count of the files at /root directory?


text:
Q: I have lot of lag/slow down when i use a scrollViewer. Can i fix that? I need to create a scrollviewer with X amount of items, i made the code that create a border with an image and sets into a grid, thats the code:
    public partial class MainWindow : Window
    {
        panel panels = new panel();
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            int col = -1;
            int actual_row =0;

            for (int i = 0; i != 20;i++)
            {
                col++;

                Grid g = panels.create_panel();
                scroll.Children.Add(g);

                g.SetValue(Grid.RowProperty, actual_row);
                g.SetValue(Grid.ColumnProperty, col);

                if (col == 3)
                {
                    actual_row++;
                    col = -1;

                    //aad row
                    RowDefinition newrow = new RowDefinition();
                    scroll.RowDefinitions.Add(newrow);
                }

            }
        }
    }

and her is the XAML:
<Window x:Class="pretyListbox.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:pretyListbox"
        mc:Ignorable="d"
        Background="#282828"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style x:Key="item" TargetType="Grid">

        </Style>
    </Window.Resources>
    <Grid>
        <ScrollViewer VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto"
                      VirtualizingStackPanel.IsVirtualizing="True"
                      VirtualizingStackPanel.VirtualizationMode="Standard"
                      >
            <Grid x:Name="scroll">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="*"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                </Grid.RowDefinitions>

            </Grid>

        </ScrollViewer>

        <Button  Height="100" Width="100" Click="Button_Click" Content="gen" Margin="0,0,3,1" HorizontalAlignment="Right" VerticalAlignment="Bottom"/>
    </Grid>
</Window>

I put an image of the app working:
App working
And there is the lag:Lagged app
the lag only appears the first time it get resized or scrolled, but isnt about time bc i wait 1 min and it get lagg equally.
If someone can tell me how to repair that or charge the grid after with an async methot i will be very greatefull. Thnx.

A: Use ItemControl and Bind all items to ItemSource, It will create Vertical scroll bar if required
Please look at below example
<ItemsControl x:Name="CountryCodeFlagControl"
                  ItemsSource="{Binding SourceList}">
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <WrapPanel />
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
        <ItemsControl.Template>
            <ControlTemplate>
                <Border>
                    <ScrollViewer>
                        <ItemsPresenter />
                    </ScrollViewer>
                </Border>
            </ControlTemplate>
        </ItemsControl.Template>
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <Button Content="{Binding Value}">
                </Button>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

A: i resolve my answer, i just put an asynchronous methot and now it works perfectly every time.
The code :

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            int col = -1;
            int actual_row =0;

            for (int i = 0; i != 100; i++)
            {
                Task task = Task.Factory.StartNew(() =>
                {
                    col++;

                    Dispatcher.Invoke(() =>
                    {
                        Grid g = panels.create_panel();
                        scroll.Children.Add(g);

                        g.SetValue(Grid.RowProperty, actual_row);
                        g.SetValue(Grid.ColumnProperty, col);

                        if (col == 3)
                        {
                            actual_row++;
                            col = -1;

                            //aad row
                            RowDefinition newrow = new RowDefinition();
                            scroll.RowDefinitions.Add(newrow);
                        }
                    });
                });
                await Task.Delay(100);
                await task;

            }
        }


text:
Q: Sent mail through Azure Pipeline The current operating system is not capable of running this task. That typically means the task was written for Windows only. For example, written for Windows Desktop PowerShell.
enter image description here
Script code here
enter image description here
I'm sending mail through the azure, when the pipeline is success. but facing the above issue


text:
Q: Postfix catch all for emails which include a unique id I would like to allow email addresses that have an unique id as prefix.
For example U123456_bla@bla.tld and U654321_bla@bla.tld would be accepted and send to one users email box.
Postfix works fine on my box and I tried to add to my main.cf
recipient_canonical_maps = regexp:/etc/postfix/recipient_canonical-regexp

and defined in /etc/postfix/recipient_canonical-regexp
/\wbla@bla.tld$/        myuser

But I had no luck with it. How can this be done?
Any help very very appreciated
Thanks in advance
Jens

A: I would do it using a virtual map, not a recipient_canonical map.  Try that, along with a pattern like:
/.*foo@example.com/    foo

A: I know it's possible to use a suffix after the username with Postfix and an MDA like Procmail - this is how my ticketing system does email-to-ticket. But I don't remember the exact setup.
I'd look around for Address Extensions in the Postfix docs. I have a feeling you can only use a suffix, not a prefix.


text:
Q: How can I open a txt file with vim by using shortcut [By using AutoHotKey] I'm using vim to open file quite frequently in windows.
Normally, open the file by right-click file -> select Edit with Vim. I'd like to open the file more quickly.
I've tried by using this way: right-click file -> press v(because press v would auto select the context-menu Edit with Vim). But, there are two context menu by using &v way (Edit with Vim and Restore previous versions).
Then, I want to using Autohotkey help to do it. But there are something wrong with my scripts:
!e::
  ClipSaved := ClipboardAll
  Clipboard =
  Sendinput ^c
  While(!Clipboard)
  {
    ClipWait,0.1,1
    If A_Index > %MaxTimeWait%
      Break
  }
  Select = %Clipboard%
  IsFile := DllCall("IsClipboardFormatAvailable","int",15)
  Clipboard := ClipSaved
  ClipSaved =
  If IsFile
  {
    Run, "C:\Marslo\MyProgramFiles\Vim\vim74\gvim.exe" "%Select"
  }
Return

Error is:
What should I do can open file by using: Select file -> Alt+E?
Thanks in advanced.

A: Try this code:
!e::
  ClipSaved := ClipboardAll
  Clipboard =
  Sendinput ^c
  While(!Clipboard)
  {
    ClipWait,0.1,1
    If A_Index > %MaxTimeWait%
      Break
  }
  Select := Clipboard
  IsFile := DllCall("IsClipboardFormatAvailable","int",15)
  Clipboard := ClipSaved
  ClipSaved =
  If IsFile
  {
    Run, "C:\Marslo\MyProgramFiles\Vim\vim74\gvim.exe %Select%"
  }
Return

*

*I corrected your Run command. Select variable should be enclosed
with %, like this %Select% as suggested by MCL.

*I replaced Select = %Clipboard% with Select := Clipboard. I
always try to use := instead of =.

Does my code works for you?
Also, always use AutoHotkey and its documenatation from http://ahkscript.org/ (current uptodate version, new official website)! AutoHotkey and its documentation from autohotkey.com is outdated and you may have some problems using them!


text:
Q: I used pow() function in my C program but did not link to -lm it still worked. Why? I was reading a book on GCC. It said only the standard library is linked by default for any C program. Since the pow() is not in the standard library, I will have to link to it using the -lm flag. However, when I compiled, I simply used:
gcc hello.c -o hello

and it still worked..
And there is another similar problem, the book also said that if you have printf("%f\n", 4); in your C program and if you compile WITHOUT -Wall option, no warning will be issued. However, I tried compiling it without the -Wall option but I still got a warning:

hello.c:6:2: warning: format '%f' expects argument of type 'double',
  but argument 2 has type 'int' [-Wformat]

Why is this? The book said I have to supply -lm and -Wall in order to make my program compiled and get the warning but I did not use either of them but I still got my program compiled and got the warning?
Thank you!

A: A bit more information based on some experimentation.
Consider this program:
#include <stdio.h>
#include <math.h>
int main(void) {
#ifdef CONSTANT
    double x = pow(2.0, 10.0);
#else
    double expon = 10.0;
    double x = pow(2.0, expon);
#endif
    printf("x = %f\n", x);
    return 0;
}

On Ubuntu, when I compile it with
$ gcc c.c -o c

it complains about an undefined reference to pow; adding -lm corrects it.
But this:
$ gcc -DCONSTANT c.c -o c

compiles and links without error, replacing the pow() call with a constant 1024.0.  But this:
$ gcc -fno-builtin -DCONSTANT c.c -o c

complains again about the undefined reference to pow.
Conclusion: gcc uses the built-in implementation of pow only when the result can be determined at compile time. Otherwise it generates an explicit call to the pow() function, which requires linking with -lm.
Note also that this depends on the way the C library is organized (the library is provided separately; it's not part of gcc). On Cygwin, which uses newlib rather than the glibc used on Ubuntu, the -lm option is not needed; apparently the math routines are an integral part of the standard library rather than being provided separately. (gcc on Cygwin still accepts the -lm option.)

A: GCC supplies several standard library functions as built-ins:

GCC provides a large number of built-in functions other than the ones mentioned above. Some of these are for internal use in the processing of exceptions or variable-length argument lists and will not be documented here because they may change from time to time; we do not recommend general use of these functions.
The remaining functions are provided for optimization purposes.

If you look at the list of built-ins, you'll see that pow is one of them.
If you add -fno-builtin to your compiler options, you should get the linker error that you're expecting.


text:
Q: Docker: replace file contents with secret in docker-compose I'm trying to setup a database with a schema and some users, using docker and docker-compose. The users are system-users for a web-application, and it needs a password for security.
In order to do so, I thought I could simply replace a template-value in the file with the value from the secret. This does not work, however.
What is the correct way to replace a file's contents with the value from the secret?
Dockerfile
FROM postgres:12.4
EXPOSE 5432
COPY 00_users.sql /docker-entrypoint-initdb.d/
COPY 01_schema.sql /docker-entrypoint-initdb.d/

RUN sed -i "s/__SECRETPASSWORD__/$(cat /run/secrets/postgres-secret)/g" /docker-entrypoint-initdb.d/00_users.sql

docker-compose
version: '3.1'
services:
  my-db:
    build: ./my-db
    container_name: my-postgres
    volumes:
      - ntool-data:/var/lib/postgresql/data
    ports:
      - 5432:5432
    environment:
      - POSTGRES_DB=mydb
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD_FILE=/run/secrets/postgres-passwd
    secrets:
      - postgres-passwd
      - postgres-secret

secrets:
  postgres-passwd:
    file: postgres-passwd.txt
  postgres-secret:
    file: postgres-secret.txt

The output is:
Step 5/5 : RUN sed -i "s/__VCNTOOLPASSWORD__/$(cat /run/secrets/postgres-secret)/g" /docker-entrypoint-initdb.d/00_users.sql
 ---> Running in 012dd81c830b
cat: /run/secrets/postgres-secret: No such file or directory

A: I ended up creating this 00_users.sh script and putting it in the /docker-entrypoint-initdb.d/
Dockerfile
 FROM postgres:12.4
 EXPOSE 5432
 COPY 00_users.sh /docker-entrypoint-initdb.d/

Content:
#!/bin/bash
set -e

MYPASS=$(cat /run/secrets/postgres-secret)

psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
  CREATE USER secretuser SUPERUSER ;
  ALTER USER secretuser WITH PASSWORD '${MYPASS}';

EOSQL


text:
Q: What is the best private cloud storage setup I need to create a private cloud and I'm searching for the best setup.
These are my 2 most important requirements
1. Disk and system redundant
2. Price / GB as low as possible
The system is going to be used as backup setup which will receive data 24/7 over SFTP and rsync. High throughput is not that important.
I'm planning to use glusterfs and consumer grade 4TB hard-drives.
I have worked out 3 possible setups

*

*3 servers with 11 4TB HDD
Setup up a replica 3 glusterfs and setup each hard drive as a separate ext4 brick.
Total capacity: 44TB
HDD / TB ratio of 0.75 (33HDD / 44TB)

*2 servers with 11 4TB HDD
The 11 hard-drives are combined in a RAIDZ3 ZFS storage pool. With a replica 2 gluster setup.
Total capacity: 32TB (+ zfs compression)
HDD / TB ratio of 0.68 (22HDD / 32TB)

*3 servers with 11 4TB consumer hard-drives
Setup up a replica 3 glusterfs and setup each hard-drive as a separate zfs storage pool and export each pool as a brick.
Total capacity: 32TB (+ zfs compression)
HDD / TB ratio of 0.68 (22HDD / 32TB) (Cheapest)
My remarks and concerns:
If a hard drive fails which setup will recover the quickest? In my opinion setup 1 and 3 because there only the contents of 1 hard-drive needs to be copied over the network. Instead of setup 2 were the hard-drive needs te be reconstructed by reading the parity of all the other harddrives in the system.
Will a zfs pool on 1 harddrive give me extra protection against for example bit rot?
With setup 1 and 3 I can loose 2 systems and still be up and running with setup 2 I can only loose 1 system.
When I use ZFS I can enable compression which will give me some extra storage.

A: Disclaimer: I have no experience with glusterfs.
If you plan to use ZFS please make sure you have a lot of RAM. I've got 5 x 2TB HDDs in a RAIDz1 and it uses about 10Gigs of RAM. So a good rule of thumb is to spend at least 1GB RAM per TB HDD.
A ZFS on a single Harddrive won't give you any protection against "bit rot".
I my opinion you should think about smaller RAIDz2 Pools connected to one big RAIDz2 or RAIDz3. This gives you a lot of protection.


text:
Q: R use shinyFiles to get a path name that I can use in a function I'm building an RShiny App and I'd like to have users be able to navigate to a directory and then I want to be able to use this directory name in a function. There are several similar questions out there, but nothing I've been able to work out for my problem. I created a simple reproducible example.
In this example, I'd like to be able to take the path_prefix and pass it to a system command so that I can change to this directory. I'm having the function print the path_prefix in the Shiny window and what is printed is appropriate. However, the functions I'm using turn the path into a list where each folder is in quotes. Does anyone have suggestions for how this could work?
library(shiny)
library(shinyFiles)

# UI
ui <- fluidPage(
  shinyDirButton('path_prefix', 'Select a directory', title='Select a directory'),
  textOutput('path_prefix'),
  actionButton("run", "run test")
)
# Server
server <- function(input, output, session) {
  volumes <- getVolumes()
  shinyDirChoose(input, 'path_prefix', roots=volumes, session=session)
  dirname <- reactive({parseDirPath(volumes, input$path_prefix)})

  # Observe input dir
  observe({
    #fileinfo <- parseSavePath(volumes, input$path_prefix)
    if(!is.null(dirname)){
      print(dirname())
      output$path_prefix <- renderText(dirname())
    }
  })

  observeEvent(input$run, {
    system(paste0("cd ", input$path_prefix))
  })

}
shinyApp(ui = ui, server = server)


text:
Q: Не компилируется Hallo world на Kotlin. Кнопка Run не активна. Пробовал разные варианты написания Не компилируется Hallo world на Kotlin. Кнопка Run не активна. Пробовал разные варианты написания

A: Надо настроить параметры запуска в "Add Configuration" слева от запуска

После этого нажмите на значок Kotlin рядом с первой строкой кода или на название файла и выберите в появившемся меню пункт Run '<название Вашей конфигурации>':

A: Разобрался! Не там создал сам файл. Пересоздал его в папке srs main kotlin


text:
Q: check if webpage comes from another webpage How would i check if someone is redirected to my site. How do i check what site they came from? PHP is preferable here.
What I'm trying to do is code a TOS, and they have to come from that part of my site. Like if they come from the Terms of Service/Agreement page, and accepted (I know how to check that), then the page will function normally, if not it will pop up the TOS and they'll have to accept it then....
Or should i use a $_SESSION variable?
Thanks in advance guys.

A: You could try looking into $_SERVER['HTTP_REFERER']. But yes, using sessions to check if they agreed to your TOS is a better choice (or just client side cookies)


text:
Q: What's the standard way to use a PHP library? Say I downloaded a PHP library (which I suppose usually comes as a bunch of .php files - is this correct?)
The only way I can think of using the library in my project is simply copy the files to my server and include or require them.
Is there a better or more standard way?
Also, how does yum relate to using PHP libraries?

A: The most popular way of installing and using packages in php is using composer.  You can get more information on composer at https://getcomposer.org. Composer will handle the auto loading for you so that you don't need to include every single file into the files.
You may also be interested in having a look at packagist.org where you can find a bunch of packages to use with composer/your projects.

A: According to my experience, all you have to do is import the right files and that's all. There is no "standard" way to use 3rd party libraries I think.
But the library you are using should have documentation. Make sure to read it because maybe you only have to import one file and that file is importing the others.


text:
Q: Special characters issue in PHP I am working on a project where a user enters his info and I save it into database, a user posted a string in the form "I still am…". But the string stored in database as "I still am…".
Now I am wondering why this happened, by looking at the string it is cleared that the suffix used after am is a kind of special characters and is converted into ….

A: You have to set the UTF-8 as the connection to a database too. It is set to Windows 1252 by default. (This encoding is often incorrectly labelled ISO 8859-1.)
The bytes E2 80 A6 are rendered as … in UTF-8 and as … in Windows 1252. The PHP is most of the time unaware of an encoding and pass raw bytes.


text:
Q: discord.py Blacklist words or certain commands I am trying to blacklist words or certain commands in a specific channel. In the channel #verify, I only want commands that start with e?verify to be processed. If the command does not start with e?verify or is just a word (not a command), I want the bot to delete the message and not process the command.
I have tried
@bot.event
async def on_message(message):
    if message.channel.id == 775951693820985404:
        if not message.content.lower().startswith('e?verify'):
            await message.delete()
        else:
            await bot.process_commands(message)

But it does not work. Can anyone help?
Edit: Also, my bot does not respond to commands in any other channels.


text:
Q: Remote update cell content in kendo grid Here I have a code to update a cell contet when pressing a button.
It works fine, but it doesn't set the flag, that indicates, that the cell has been changed.
It should look like this with the litle red triangle:

The code:
Click me

Update:
Here is the update based on @tstancin: Kendo example.
Thank you for the answer - I had thought of it to.
I am wondering if it's possible to do the update in a more clean way with some binding through som MVVM perhaps?
Kind regards from Kenneth

A: If that's all you want then you should expand your button click code with the following:
$('#button').click(function (e) {
    var data = grid.dataItem("tr:eq(1)");

    data.set('category', 'Merchandice');

    $("#grid tr:eq(1) td:eq(1)").addClass("k-dirty-cell");
    $("#grid tr:eq(1) td:eq(0)").prepend("");
});

But if you, for instance, manually change the value of name column from Chai to something else, and then click the click me button, the dirty marker in the name column will disappear.
You should use flags for every cell and set them before data.set(). Then, in the grid's dataBound event you should inspect every cell's value and assign the dirty marker if it's needed. For manual changes you should handle the save event and set flags there.

A: I wrote a script that makes it posible to use a call like this:
SetCellData(id, columnName, value);

So with an id, a columnName and a value, I can update a value in a grid and the flag will be set on the cell.
function SetCellData(id, columnName, value) {
    var dataItem = grid.dataSource.get(id);
    dataItem.set(columnName, value);
    var columnIndex = GetColumnIndex(columnName);
    if (columnIndex > -1) {
        var cell = $('tr[data-uid*="' + dataItem.uid + '"] td:eq(' + columnIndex + ')')

        if (!cell.hasClass("k-dirty-cell")){
            cell.prepend("");
            cell.addClass("k-dirty-cell");
        }
    }

}

function GetColumnIndex(columnName) {
    var columns = grid.columns;
    for (var i = 0; i < columns.length; i++)
        if (columns[i].field == columnName)
            return i;
    return -1;
};

I have the code here : example


text:
Q: How Could Python iterate the directoriy and detect the new files? How can I iterate all files and subdirs in  a Dir,
and can detect new file when put there?
Thank you for your help!

A: Try os.walk. More specifically, try:
top="."
import os
for root, dirs, files in os.walk(top):
    for name in files:
        # do something with each file as 'name' (a)
        pass
    for name in dirs:
        # do something with each subdir as 'name' (b)
        pass
    # do something with root (dir path so far)
    # break at any point if necessary

To answer the question in your comment, at point (b) in the code, you can handle any subdirectory logic (also you can check to test that you have the right subdirectory to do certain custom logic on), via another function or directly/inline.


text:
Q: Can client and service web applications share the same Azure Active Directory Application? I have a ASP.NET Web Forms site where users will login using Azure Active Directory. As a client it calls Asp.Net Core Web Api site, that will return some information depending on customer roles.
The approach is similar to https://github.com/Azure-Samples/active-directory-dotnet-webapp-webapi-openidconnect-aspnetcore sample.
Each application in the sample has it's own Azure Active Directory application.  My application has quite a few application roles and maintain them in both applications can be annoying and error-prone. I want client and service to use the same AAD application  to avoid maintain the same roles in 2 AAD applications.
I haven't seen such architecture in examples, is any problem with such approach?
I tried to implement it and received a "promising" error, that "scenario is supported".

AADSTS90009: Application is requesting a token for itself. This
  scenario is supported only if resource is specified using the GUID
  based App Identifier.

Unfortunately I don't understand how to specify resource "using the GUID based App Identifier". In the request I already using GUID
resource=https%3A%2F%2FMyDomain.onmicrosoft.com%2Fe0a25761-XXXX-XXXX-XXXX-2aefc7e3134d
Advice to change some GUID on MS Forums thread https://social.msdn.microsoft.com/Forums/azure/en-US/3de0c14d-808f-47c3-bdd6-c29758045de9/azure-ad-authentication-issue-aadsts90009?forum=WindowsAzureAD#cf3986f5-3422-44d1-bcb7-3a4201f68fa2(I asked for clarifications there) also is not clear.
So my question is: Can I share the same AAD application between client and Service, and, if yes, how to do it?

A: Based on my test, the normal Azure AD tenant doesn't support to mix the client and server apps well.
Here is my trying for your reference:
1 .Grant the permission to the app itself by modifying the manifest like below:
"requiredResourceAccess": [
{
  "resourceAppId": "{AppID}",
  "resourceAccess": [
    {
      "id": "{customOauth2PermissionsId}",
      "type": "Scope"
    }
  ]
},
{
  "resourceAppId": "00000002-0000-0000-c000-000000000000",
  "resourceAccess": [
    {
      "id": "311a71cc-e848-46a1-bdf8-97ff7156d8e6",
      "type": "Scope"
    }
  ]
}
],

2 .Then we can acquire the token using OAuth2 code grant flow
https://login.microsoftonline.com/common/oauth2/authorize?response_type=code&client_id={appId}&redirect_uri={redirectURL}&resource={appId}
POST:https://login.microsoftonline.com/common/oauth2/token

However, I was not able to find the custom specific permission when pasred the access_token. If you want the Azure AD normal tenant to support this scenario, you can submit the feedback from here.

A: I tried to add a new App ID URI for AAD application (identifierURIs[]) that is supported  according to  https://learn.microsoft.com/en-us/azure/active-directory/develop/active-directory-application-manifest .
Manifest allowed to specify multiple identifierURIs, but portals(both new and classic) show only  the first  of URIs.  New portal highlights App ID URI entry box as changed and prompts to save it(effectively removing the second URI).
However I realized that I don't need both AAD applications to have roles.  I can have 2 separate AAD applications and keep roles only in one of them. Web Site client will authenticate user, but do not check for roles itself. Instead it will call Web API site that should have AAD application with all application roles declared and assigned to users/user groups. Web API can provide roles/permissions to the client according to client's requests.


text:
Q: Howto correctly add compiled class files to jar with package structure I have a prorgam thats generating source code and want to compile this source code during the java-runtime execution like:
generateSource()
compileSource()

I use the JavaCompiler from ToolProvider:
ArrayList<String> optionList = new ArrayList<String>();
System.out.println("Retrieve dependendcy Jars");
ArrayList<File> jarfiles = getJarFiles(this.libdir);
String libpath = System.getProperty("java.class.path") + convertJarFilesToClassPath(jarfiles);
optionList.addAll(Arrays.asList("-d", this.genClassDir ));
optionList.addAll(Arrays.asList("-classpath", libpath));

ArrayList<File> files1 =  getSourceFiles(this.genCodeDir);
Iterable<? extends JavaFileObject> compilationUnits1 = fileManager.getJavaFileObjectsFromFiles(files1);
JavaCompiler.CompilationTask task = compiler.getTask(null ,fileManager , null, optionList, null, compilationUnits1 );
task.call();

Now the important line is where i add the -d classdirectory in the optionlist.
I have this genClassDir /gen/classes where all my .class files  are inside including subdirs.
Now the problme in my jar file is, that the class files are having the genClassDir as prefix before the package structure.
./gen/classes/foo/
./gen/classes/foo/bar/

instead of
/foo
/foo/bar

or without the leading slash.
I am packaging the jar like in the first answer from How to use JarOutputStream to create a JAR file?
Is there a way i get only the package structure of the class files in my jar?

A: You could add a basePath parameter to the add()-method of the solution shown in the other question and the strip the base path from each file name before creating the Jarentry
private void add(File source, String basePath, JarOutputStream target) throws IOException
{
    //...
    name = name.replaceFirst(basePath, "");
    JarEntry entry = new JarEntry(name);
    //...
}

Adjust the replacement as necessary (leading/trailing slashes, backslashes instead of slashes, etc.)
Usage:
add(new File("gen/classes/test.class", "gen/classes", new JarOutputStream(...));


text:
Q: PrimeFaces 4.0 themes I'm in trouble in my primefaces 4.0 setup, I have the following settings in my pom.xml:
But nothing works, I need to improve some more code, taken a look in this forum but did not solve my problems.


text:
Q: Git post-receive Not running I've searched several questions here and haven't been able to get the answer, so I'll ask regarding my specific situation.
Real simple post-receive hook, it just curls to Redmine to force Redmine to update the views of the repo on commit. (For sake of debugging I'm also echo'ing "Post Receive Hook Go" to see
Setup:
Bare Repo /git/repos/test.git
$ cd ~/
$ git clone file:///git/repos/test.git
$ cd test/
$ vim somefile_gets_updated
$ git commit -a -m 'Tackling bug #1, include the bug number so Redmine will pick it up and associate it'
$ git push origin master

This commits and pushes as expected, but the post-receive hook does not fire
If I do
$ curl http://localhost:3000/sys/fetch_changesets?key=cGdcUaRr8u4Rr4zXzXhr and refresh my redmine issue page it works, hooray!
If after the push I do:
$ ./.git/hooks/post-receive

I get:
$ Post Receive Hook Go

It works, hooray!
So I know the curl works, even the post-receive works, Git just doesn't fire it
This is the hooks
 $ cd .git/hooks
 $ ls -l | grep post-receive
 $ -rwxr-xr-x  1 bobbydown  staff   109 Dec 22 03:42 post-receive

I just don't understand why git isn't running the hook...

A: The post-receive hook fires after a repo receives pushed commits.
In your scenario, your hook should be in your bare repo, not the clone.


text:
Q: EGL Group Permissions Add/Manage For those of you that have dealt with EGL (Elite Gaming Ladders) Tournament & Ladders script... I'm having a problem figuring out how to add new group permissions for customized mods I've made. I've created a new type of "General Rules" mod that I would like to store the permission as shown:
case "select_genrules";
    if($group['genrules_manager']=="yes"){
        include("./includes/rules.php");
        select_genrules();
    }else{
        return warning("<b>" . LANG_WARNING_NO_PERMISSIONS_TO_ACCESS_PAGE . " </b>");
    }
    break;

where "genrules_manager" formatted the same as all of the others is added to the group_permissions set. I added it to the groups_permissions table and it actually does show in the list of permissions in the ACP under the category "Misc" but I would like to add "Lang" so that it doesn't just say "genrules_manager" etc... Any help as to how to access/modify those keys in the admincp/includes/addmembergroup.php and admincp/includes/managemembergroup.php would be greatly appreciated!

A: This is actually found in groups.php under the functions addmembergroup and editmembergroup. You will need to add a key that links to the "lang" you have written in admincp/language/english.php like so:
if($key=='genrules_manager'){$descr='' . LANG_GRO_PERMISSIONS_DESCR_GENRULES_MANAGER . ''; $site .= group_radio($key, $value, $descr);}

It has to be done in both functions in order for you to see when adding and editing. Simply place it inline with the keys under whichever category you'd like...


text:
Q: Avoid from loading all fragment in Pager Sliding Tab I have several fragment in the PagerSlidingTab .Because all fragment load in the one time , it doesn't have good performance and quality (some times load correctly and sometimes go to Volley  onResponseError ).
In the fragments i load the json data and populate RecyclerView with Json data .

One of my fragment :

public class Fragment_four extends Fragment {
    private boolean isFragmentLoaded = false;
    private static final String FIRST_URL = "http://myapiservice.com/api/3";
    private ProgressBar loadingProgressBar;
    private ArrayList<ModelDars> darsha = new ArrayList<ModelDars>();
    private RecyclerView reyclerCharDab;
    private AdapterRecyclerDars adapterRecyclerDars;
    private String after_url;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_four, container, false);

        //======================================
        loadingProgressBar = (ProgressBar) view.findViewById(R.id.prg_loading_frg_four);

        //recyclerview init
        reyclerCharDab = (RecyclerView) view.findViewById(R.id.recycler_frg_chaharom_dab);
        reyclerCharDab.setHasFixedSize(true);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        reyclerCharDab.setLayoutManager(gridLayoutManager);
        adapterRecyclerDars = new AdapterRecyclerDars(darsha, getActivity(), FIRST_URL, getActivity());
        reyclerCharDab.setAdapter(adapterRecyclerDars);

        if (helpers.isOnline(getActivity())) {
            //creating volley object request
            JsonObjectRequest request = new JsonObjectRequest(FIRST_URL, new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (response != null || response.length() > 0) {
                        try {
                            JSONArray data = response.getJSONArray("data");
                            for (int i = 0; i < data.length(); i++) {
                                JSONObject currentData = data.getJSONObject(i);
                                ModelDars newModelDars = new ModelDars();

                                newModelDars.setDarsId(currentData.getString("id"));
                                newModelDars.setDarsTitle(currentData.getString("title"));
                                newModelDars.setDarsPoster(currentData.getString("poster"));
                                newModelDars.setDarsVisitCnt(currentData.getString("visitcnt"));
                                newModelDars.setDarsDate(currentData.getString("date"));
                                newModelDars.setDarsCatId(currentData.getString("cat_id"));
                                newModelDars.setDarsCatName(currentData.getString("cat_name"));

                                darsha.add(newModelDars);
                            }
                            after_url = response.getString("pagination");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        //notify adapter about data changed
                        adapterRecyclerDars.notifyDataSetChanged();
                        loadingProgressBar.setVisibility(View.GONE);
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    loadingProgressBar.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), "failed to fetch data from internet ", Toast.LENGTH_SHORT).show();
                }
            });
            AppController.getInstance().addToRequestQueue(request);

            // LOAD MORE FUNCTION =====================================================================

            reyclerCharDab.addOnScrollListener(new EndlessRecyclerViewScrollListener(gridLayoutManager) {
                @Override
                public void onLoadMore(int page, int totalItemsCount) {
                    if (after_url == "null") {

                    } else {

                        JsonObjectRequest request = new JsonObjectRequest(after_url, new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                if (response != null || response.length() > 0) {

                                    try {
                                        JSONArray data = response.getJSONArray("data");
                                        for (int i = 0; i < data.length(); i++) {
                                            JSONObject currentData = data.getJSONObject(i);
                                            ModelDars newModelDars = new ModelDars();

                                            newModelDars.setDarsId(currentData.getString("id"));
                                            newModelDars.setDarsTitle(currentData.getString("title"));
                                            newModelDars.setDarsPoster(currentData.getString("poster"));
                                            newModelDars.setDarsVisitCnt(currentData.getString("visitcnt"));
                                            newModelDars.setDarsDate(currentData.getString("date"));
                                            newModelDars.setDarsCatId(currentData.getString("cat_id"));
                                            newModelDars.setDarsCatName(currentData.getString("cat_name"));

                                            darsha.add(newModelDars);
                                        }
                                        after_url = response.getString("pagination");

                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                    //notify adapter about data changed
                                    adapterRecyclerDars.notifyDataSetChanged();

                                }
                            }
                        }, new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        });
                        AppController.getInstance().addToRequestQueue(request);
                    }
                }
            });
        } else {
            Toast.makeText(getActivity(), "You dont have internet !", Toast.LENGTH_SHORT).show();
            loadingProgressBar.setVisibility(View.GONE);
        }
        return view;
    }
}

And This is the view pager adapter :

public class MainActivityPagerAdapter extends FragmentStatePagerAdapter {
    //============================================ Constructor
    public MainActivityPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    //============================================ GetItem Method ()
    @Override
    public Fragment getItem(int position) {
        Fragment frag = null;
        switch (position) {
            case 0:
                frag = new Fragment_one();
                break;
            case 1:
                frag = new Fragment_two();
                break;
            case 2:
                frag = new Fragment_three();
                break;
            case 3:
                frag = new Fragment_four();
                break;
        }
        return frag;
    }
    //============================================= GetCount Method ()
    @Override
    public int getCount() {
        return 4;
    }
    //============================================= GetPageTitle
    @Override
    public CharSequence getPageTitle(int position) {
        String title = "";
        switch (position) {
            case 0:
                title = "one";
                break;
            case 1:
                title = "two";
                break;
            case 2:
                title = "three";
                break;
            case 3:
                title = "four";
                break;
        }
        return title;
    }
}

A: AS per your comment, here is a snippet of instantiating the fragments only once, and only returning the one to be displayed :
public class MainActivityPagerAdapter extends FragmentStatePagerAdapter {
private Fragment_one fragment_one;
private Fragment_two fragment_two;
private Fragment_three fragment_three;
private Fragment_four fragment_four;

//============================================ Constructor
public MainActivityPagerAdapter(FragmentManager fm) {
    super(fm);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    fragment_one = new Fragment_one();
    fragment_two = new Fragment_two();
    fragment_three = new Fragment_three();
    fragment_four = new Fragment_four();
}

//============================================ GetItem Method ()
@Override
public Fragment getItem(int position) {
    switch (position) {
        case 0:
            return (fragment_one);
        case 1:
            return (fragment_two);
        case 2:
            return (fragment_three);
        case 3:
        default:
            return (fragment_four);
    }
}
}

A: you can load specific fragment by overriding setUserVisibleHint
boolean isVisible;

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
   super.setUserVisibleHint(isVisibleToUser);
   isVisible= isVisibleToUser;

    if (isVisible) {
       //callApi
    } else {
      Log.d(TAG, "this fragment is now invisible");
    }
 }


text:
Q: How to understand "Please be sure to keep me posted as to your graduation date." The hr manager emailed me with this sentence "Please be sure to keep me posted as to your graduation date."
what exactly the manage mean? Thanks.

A: Quite simply, "Let me know the date [of your graduation] and update me if it changes".


text:
Q: On diagonal terms in the Coulomb matrix I have seen many machine learning algorithms for prediction of quantum chemistry properties that use Coulomb matrix as their input. Coulomb matrix is defined as
$$\boldsymbol{M}_{i j}^{\mathrm{Coulomb}}=\left\{\begin{array}{cc}{0.5 Z_{i}^{2.4}} & {\text { for } i=j} \\ {\frac{Z_{i} Z_{j}}{R_{i j}}} & {\text { for } i \neq j}\end{array}\right.$$
where the diagonal terms:

... can be seen as the interaction of an atom with itself and are
  essentially a polynomial fit of the atomic energies to the nuclear
  charge.

I was trying to read more about these diagonal terms and how exactly this equation is fitted. It seems that the model was first utilized by Rupp et al Phys. Rev. Lett.,108(5):058301, 2012, but there is not much more than this one sentence there. Essentially, I'm looking for something that says: ". . . and from there we get $0.5Z^{2.4}$" and if these energies can be extended to bonds as well, as the off-diagonal term in Coulomb matrix represent repulsion forces rather than potentials. Any references would be appreciated as well.

A: I know nothing about machine learning algorithms for quantum chemistry, however it is easy to guess what that $0.5 Z^{2.4}$ term means: it is an approximation to the total energy of atoms.
Consider, for example, the following ground-state energies of neutral atoms computed at the Dirac-Hartree-Fock level:
L. Visscher and K.G. Dyall, Dirac-Fock atomic electronic structure calculations using different nuclear charge distributions, Atom. Data Nucl. Data Tabl., 67, (1997), 207.
Data are available as Table II at
http://dirac.chem.sdu.dk/doc/FiniteNuclei/FiniteNuclei.shtml
A fit of those energies (using the values computed with a point-charge nucleus) to a functional form of the type $E=0.5 Z^\alpha$ for $Z=1$ to $Z=109$ results (my calculations) in $\alpha =2.42$, and the typical fitting error is about 3%. In all probability the constant is fixed to $0.5$ to reproduce exactly the energy of the hydrogen atom.