text:
Q: How to redirect to an Angular custom made Login page if the user is not logged in In my current case I have an Angular application with Azure AD and MSAL v2 implementation. What I want to achieve is when the user is not logged in redirecting them to the custom made Login page with a simple Login (click)="login()" button. I've followed this project to get where I am now but unfortunately after navigating to ' / ' path of localhost:4200 I am getting redirected straight to the Microsoft login page instead of ' /login '. Am I missing something here? Here is my routing module:
const routes: Routes = [
  {
    path: '',
    component: HomeLayoutComponent,
    canActivate: [MsalGuard],
    children: [
      { path: '', component: WelcomeComponent, pathMatch: 'full'},
      { path: 'map-requests', component: MapRequestsComponent},
      { path: 'map-requests/map-request/details', component: MaprequestDetailComponent }
    ]
  },
  {
    path: '',
    component: LoginLayoutComponent,
    children: [
      {
        path: 'login',
        component: LoginComponent
      }
    ]
  },
  { path: '**', redirectTo: '' }
];

Found similar question on stack: this

A: Thanks to this post I found the solution, the solution is to add a second guard which will check if a user is logged in or not, this is how the auth guard looks like.
import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { MsalBroadcastService, MsalService } from '@azure/msal-angular';
import { InteractionStatus } from '@azure/msal-browser';
import { Observable, of } from 'rxjs';
import { filter, switchMap } from 'rxjs/operators';

@Injectable({ providedIn: 'root' })
export class CanActivateGuard implements CanActivate {
    constructor(private msalService: MsalService,
        private router: Router,
        private msalBroadcastService: MsalBroadcastService) { }

    canActivate(route: ActivatedRouteSnapshot,
        state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
        return this.msalBroadcastService.inProgress$
            .pipe(
                filter((status: InteractionStatus) => status === InteractionStatus.None),
                switchMap(() => {
                    if (this.msalService.instance.getAllAccounts().length > 0) {
                        return of(true);
                    }

                    this.router.navigate( ['/auth/login'] );
                    return of(false);
                }),
            );
        }
}

Note: Depending on your rxjs version, you may need to import operators from rxjs library like this
import { Observable, of, filter, switchMap } from 'rxjs';


text:
Q: how to replace .csv containg two tables data into 2-tables of mysql How to import .csv containing two tables data into two tables of Mysql?
Here is the query-
REPLACE INTO TABLE EmployeeTable WHEN EmployeeID,EmployeeDetailTable FIELDS TERMINATED BY ',' IGNORE 1 LINES ";

A: As the LOAD DATA statement doesn't allow for individual columns to be included, I would suggest:

*

*create a temporary Table which contains all columns.

*import the whole file using LOAD DATA, see MySQL LOAD DATA

*do two individual INSERT ... SELECT statements with the columns you want in either one of the tables, see MySQL INSERT...SELECT

redpajama_set_name: RedPajamaStackExchange


text:
Q: height not showing 100 percentof the page how can i make the height so it covers the entire page, do i need to  make the position fixed and how do i hide the slide and show back in if i have to
this is the code i am using
http://jsfiddle.net/tyuth1sr/16/
html code

Taectur sinti consed magnimp oreptatem que est essi cuptus doluptate pratis rero omni con fugitatius venienimus. Xim fuga. Iliqui omnim comnimus estiorrum cum et accus et liquia nos.

this is the jscode
$("#slideshow").click(function() {
          $( ".flex-caption" ).toggle( "slide" , { direction: "right" }, 1000 );
        });

and the css code
.slides {
    overflow: hidden !important;
}

.right {
    right: 0;
    margin-bottom: 0px;
}

.flex-caption {
    position: absolute;
    text-align: left;
    background:rgba(255, 255, 255, 0.7);
    z-index: 1;
    padding: 20px;
    width: 295px;
    padding-top: 100%;
    bottom: 0px;
}


text:
Q: Throwing error intermittently I am getting a weird error, and that too sometimes while executing my script. The error is:
Method invocation failed because [System.Object[]] does not contain a method named 'op_Subtraction'.

The line in which I get this error is:
 $LineNr = $dbsnap_file | Select-String -Pattern $check | Select-Object -ExpandProperty LineNumber
 $del = $dbsnap_file[$LineNr-13] -split ':' | Select-Object -Last 1

$dbsnap_file is gc (some_file). That file contents are like:
AllocatedStorage     : 5
AvailabilityZone     : us-west-1a
DBInstanceIdentifier : test-multisite
DBSnapshotIdentifier : test-multisite-2015-09-03-04-15
Encrypted            : False
Engine               : mysql
EngineVersion        : 5.6.19a
InstanceCreateTime   : 12/19/2014 5:19:26 AM
Iops                 : 0
KmsKeyId             :
LicenseModel         : general-public-license
MasterUsername       : root
OptionGroupName      : default:mysql-5-6
PercentProgress      : 100
Port                 : 3306
SnapshotCreateTime   : 9/2/2015 11:15:36 PM
SnapshotType         : automated

$check has value like test-multisite-2015-09-03-04-15. So, what I get as $del is the SnapshotCreateTime.
Iam recieving this error intermittently, sometimes its working, sometimes not. Can someone please guide me through what will be the issue.?

A: Like CB was saying Select-String will return all matches. You were expecting only one and the code was built around that assumption. The error you are getting is fairly explicit.
[System.Object[]] does not contain a method named 'op_Subtraction'

You were trying to subtract 13 from an object instead of an integer. As discussed in chat it turned out the issue was your source file had a double of data.
The solution in this case was to clean your source. If you are comfortable with assumptions you can also address this issue by updating the select
$LineNr = $dbsnap_file | Select-String -Pattern $check | Select-Object -First 1 -ExpandProperty LineNumber

That will ensure only one is returned. Caveat being you are ignoring real data. So verify the source and the contents of the $LineNr are the solutions I would recommend here.


text:
Q: Why would a photon of light still strike mirror A at the same point that it left it? If two mirrors were fixed normal to each other in a vacuumed cubicle travelling at some velocity V (see image below) and a single photon of light was emitted from point A at time t1. At time t2 would an observer (or some measurement device) see the photon returning back to point A or point C?
I am assuming that there is no horizontal component of velocity V that can be added to the photon of light emitted normally from mirror A, otherwise that would contravene the universal constant speed of light.

A: The return point of the photon depends upon the direction in which it was travelling. If the photon was travelling normally to the mirrors in the frame of the mirrors, then it will return to point A. If it was travelling normal to the mirrors in the frame of the stationary observer, it will return to point C.
You must remember that directions of motion, as well as speeds of motion, are frame dependent. If you drop a ball on a moving train it will fall vertically. However to an observer on the platform, the ball will follow a sloping path. Likewise if the observer drops a ball vertically on the platform, it will drop at an angle in the frame of the train. So if you want to talk unambiguously about a ball dropping vertically, you have to say whether you mean in the frame of the train or the platform. The same applies to your thought experiment- you have to say whether the light is moving vertically down from the upper mirror in the frame of the mirror or the stationary observer.
Finally, as other answers have pointed out, it is simply wrong to say that 'there is no horizontal component that can be added to the photon'. Adding the horizontal component changes the direction of the photon, but not its speed, owing to the rule for the relativistic addition of velocities.

A:
I am assuming that there is no horizontal component of velocity V that can be added to the photon of light emitted normally from mirror A, otherwise that would contravene the universal constant speed of light.

Then you are failing to understand and really grapple with special relativity.
So you are saying, "I am assuming that you can't X because that would contradict Y" but we would like to say, "No, X and Y are both true, and your argument is actually 'if X (and W, obviously), then not Y', and the problem is that W that you think is obvious."
In this case, your W is the belief that if you add some horizontal component to the velocity, for instance by using a different reference frame, then the vertical component of the velocity of the light stays constant. And it actually does, to first order in $v_x/c$, which is why you can essentially ignore this effect. But then to second order you have
$$v_y = \sqrt{c^2-v_x^2}\approx c -\frac12 {v_x^2\over c}$$
and the vertical component has been very slightly attenuated.

A: That depends on how you aim it.  I presume you are thinking of a case where the beam is oriented to produce photons normal to the mirror, and where with the mirrors at rest the photon returns to point A.  Is that correct?

I am assuming that there is no horizontal component of velocity V that can be added to the photon of light emitted normally from mirror A, otherwise that would contravene the universal constant speed of light.

But the emitter in your scenario already has a horizontal component.  In fact, we can calculate the total momentum of this object in the horizontal direction.
When the photon leaves, the mass of the mirror must be reduced.  Therefore either the speed is the same as before and the momentum is less or the momentum is the same and the speed has increased.  The second is not possible  on energy conservation.  So the first is true.
The total momentum of the system must be constant, and the momentum of the mirror has reduced.  Therefore the photon must be carrying some of the horizontal momentum of the system.  To an observer where the mirrors are stationary and to one where the mirrors are moving, the photon returns to point A.

A: First, I am calling $T1$ frame $T$ and $T2$ is now $T'$, because: tradition makes SR problems clearer.
It's unclear how the light is being transmitted. Suppose it's a laser with its phase fronts parallel to the mirror in frame $T$ (that is, the laser is stationary w.r.t. to the mirrors, and emits parallel to their normal).
Then the bounce is perpendicular and it returns to the laser. (If this were not true, then the internal mirrors in the laser would only work in the Universe's absolute rest frame, which doesn't exist, ergo: there is no absolute rest frame ....so much easier than the Michelson-Morley experiment...but I digress).
In the moving frame, the hyperplane of simultaneity is tilted w.r.t to the direction of motion, hence the phase fronts are tilted. Note: phase is a Lorentz scalar, everyone agrees what it is at an event in spacetime:
$$ \phi(x, t) = kx-\omega t = k_{\mu}x^{\mu} = k'_{\mu}x'^{\mu} = k'x'-\omega' t' = \phi(x', t') $$
But the laser aperture spans many events.
For instance, at $t=0$ lets say $\phi(x, 0)=0$. But:
$$t' = \gamma\big(t-\frac{vx}{c^2}\big) = -\gamma\frac{vx}{c^2}\ne 0$$
The phase front is tilted in $T'$ so the laser is not perpendicular to the mirror.
If you want to calculate the angle, then just start with:
$$ k_{\mu} = (\omega/c, k_x, k_y, k_z) = (k,0,0,-k) $$
and boost along $-x$.


text:
Q: How can I move a Grapviz node to the left? I'm making an application on Sreamlit, which should visualize Gradient Descent. I have this code:
graph= graphviz.Digraph(graph_attr={'rankdir':'LR'})

#black arrows

graph.edge(f'3', '12 ', label='3*4')
graph.edge(f'4', '12 ', label='4*3')
graph.edge('12 ', '12', label='max(0,12)')
graph.edge('12', '60', label='12*5')
graph.edge('5', '60', label='5*12')
graph.edge('60', '1600', label='(100 - 60)**2')

#red arrows

graph.edge('1600', '60', label='2*(100 - 60)=80', color='red')
graph.edge('60', '12', label='5*80=400', color='red',)
graph.edge('60', '5', label='12*80=960', color='red')
graph.edge('12', '12 ', label='1*400=400', color='red')
graph.edge('12 ', '3', label='400*4=1600', color='red')
graph.edge('12 ', '4', label='400*3=1200', color='red')

st.graphviz_chart(graph)

Which produces this graph:
I want all the black arrows to point to the right and all the red arrows to point to the left. For that I would need to move node 12to4 and 60to5 to the left.
I tried graph.edge(... pos="-1,0")  but that did not help.
Does anyone have any suggestions? Would really appriciate it.

A: [This answer is at the Graphviz-level, not specific to Streamlit.]
I don't remember a generic way to force edges to be directional, however there are several ways to "strongly encourage" directionality.

*

*rank=same (https://graphviz.org/docs/attrs/rank/) to force nodes to the same rank

*TBbalance=min (https://graphviz.org/docs/attrs/TBbalance/) to force nodes that could be positioned to multiple ranks toward min or max rank

*setting minlen for some of the edges to establish "openings" for other nodes

I suggest setting nodes 3 & 4 on the same rank and 5 & 12 on the same rank.
In the Graphviz language this would be:
{rank=same 3 4}
{rank=same 5 12}


text:
Q: How to pass a dymamic array of strings pointers from C++ to a C function
Possible Duplicate:
std::vector<std::string> to char* array

I have to call a c function that accepts an array of string pointers. Example
void cFunction(char* cities[], int count)
 {
   for(int i = 0; i < count; ++i )
   {
    printf("%s\n", cities[i]);
   }
 }

Assume that function is in some third party libabry; it cannot be changed
I can declare a static array and call the function like this
char* placesA[] = {"Teakettle Junction", "Assawoman Bay", "Land O' Lakes", "Ion", "Rabbit Hask" };
cFunction(placesA, 5);

That works. But my data is dynamic i.e. the size of the array changes many times at runtime
So I tried this
std::vector<std::string> placesB(placesA, placesA + 5);
cFunction(&placesB[0], 5); // this won't work because std::string != char*[]

Tried this
std::vector<char*> placesC;
cFunction(&placesC[0], 5);

I find placesC awkward to populate at the sametime avoid memory leaks I am looking for a solution that is both efficient ( as little string copying as possible and preferably uses STL and or Boost )

A: You can write a function that populates a vector<char*> from a vector<string> using .c_str() on each string.

A: There's going to be some awkwardness no matter how you slice it.  If the C API truly requires modifiable arrays, then that's what you'll need to provide -- you'll have to copy your strings into.  If it doesn't modify the strings, then you can use a std::vector of const char*, where the string data is still owned by the underlying std::string objects; you just have to be careful that the C API doesn't hold onto references to those strings and tries to access them after the strings have been modified or deallocated.
For example, here's one way to do it:
// Unary functor which calls c_str() on a std::string object
struct StdStringCStrFunctor
{
    const char *operator() (const std::string& str) { return str.c_str(); }
};
...

std::vector<std::string> places;
... // populate places

// Convert to array of C strings
std::vector<const char *> placesCStr(places.size());
std::transform(places.begin(), places.end(), placesCStr.begin(), StdStringCStrFunctor());
cFunction(const_cast<char**>(&placesCStr[0]), placesCStr.size());


text:
Q: Convert D3 to Angular component I have this done now. How I can have it as Angular Component?? Here is a repo for that https://github.com/bastiankhalil/line-chart-D3
The problem in the function tick() which is should be called recursively.

<!DOCTYPE html>
<meta charset="utf-8">
<style>
.line {
  fill: none;
  stroke: #000;
  stroke-width: 1.5px;
}
</style>
<svg width="960" height="500"></svg>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.js"></script>
<script>
var n = 40,
    random = d3.randomNormal(0, .2),
    data = d3.range(n).map(random);

var svg = d3.select("svg"),
    margin = {top: 20, right: 20, bottom: 20, left: 40},
    width = +svg.attr("width") - margin.left - margin.right,
    height = +svg.attr("height") - margin.top - margin.bottom,

    g = svg.append("g").attr("transform", "translate(" + margin.left + "," + margin.top + ")");

var x = d3.scaleLinear()
    .domain([0, n - 1])
    .range([0, width]);
var y = d3.scaleLinear()
    .domain([-1, 1])
    .range([height, 0]);

var line = d3.line()
    .x(function(d, i) { return x(i); })
    .y(function(d, i) { return y(d); });

g.append("defs").append("clipPath")
    .attr("id", "clip")
  .append("rect")
    .attr("width", width)
    .attr("height", height);

g.append("g")
    .attr("class", "axis axis--y")
    .call(d3.axisLeft(y));
g.append("g")
    .attr("clip-path", "url(#clip)")
  .append("path")
    .datum(data)
    .attr("class", "line")
  .transition()
    .duration(500)
    .ease(d3.easeLinear)
    .on("start", tick);

function tick() {

  data.push(random());
  // Redraw the line.
  d3.select(this)
      .attr("d", line)
      .attr("transform", null);
  // Slide it to the left.
  d3.active(this)
      .attr("transform", "translate(" + x(-1) + ",0)")
    .transition()
      .on("start", tick);
  data.shift();
}
</script>

A: Got it to work, full code available here.
To get the code working, I had to do different things.
Package
Install the full d3 package and import it. For some reason, Webpack does not catch that transition needs to be bundled
this and tick function context
For the tick function to work, I had to jump though a few hoops.
First, the tick function has to be rebound in the component constructor to get the correct context:
constructor() {
   this.tick = this.tick.bind(this);
}

Then, in the update/transition phase, I had to capture the actual component before handling the on callback:
const self = this;
g.append('g')
  .attr('clip-path', 'url(#clip)')
  .append('path')
  .datum(this.data)
  .attr('class', 'line')
  .attr('d', this.theLine)
  .transition()
  .duration(500)
  .ease(d3.easeLinear)
  .on('start', function (d, i) {
    self.tick(this);
  });

Notice how I introduced the self variable before the callback, and use it to call the tick function with this as argument, and how I use an actual function and not a lambda/arrow function. In this case, this refers to the current selection (i.e. the path element).
Finally, I modified the tick function to accept the selected/transitioned element as an argument and apply the same trickery as the example you provided. Here again, I manually capture this in a self variable, use a function callback,and call self.tick(this).
tick(sel: any) {
  const self = this;
  this.data.push(this.random());
  // Redraw the line.
  d3.select(sel)
    .attr('d', this.theLine)
    .attr('transform', null);
  // Slide it to the left.
  d3.active(sel)
    // .select('.line')
    .attr('transform', 'translate(' + this.x(-1) + ',0)')
    .transition()
    .on('start', function () { self.tick(this) });
  this.data.shift();
}

In the hope that this helps you :-). If something is unclear, let me know.


text:
Q: Airflow - got an unexpected keyword argument 'dag' I know there is already an airflow function that passes file from Cloud Storage to Big Query, as I did, I made the connection inside the script with the GCP the same way I would without the airflow, I called the PythonOperator to call the function that I configured in the script to read the Cloud Storage and insert the data from the file to Big Query, however I get the error message: "got an unexpected keyword argument 'dag'"
It seems to be a pretty simple thing to solve but I really do not know what that means since I put the DAG attributes inside the PythonOperator
import json
import decimal
import airflow
from airflow import DAG
from airflow.contrib.operators.mysql_to_gcs import MySqlToGoogleCloudStorageOperator
from airflow.contrib.operators.gcs_to_bq import GoogleCloudStorageToBigQueryOperator
from airflow.contrib.operators.bigquery_operator import BigQueryOperator
from datetime import datetime, timedelta
from airflow.operators.bash_operator import BashOperator
from airflow.models import BaseOperator
from airflow.utils.decorators import apply_defaults
from airflow.contrib.hooks.gcs_hook import GoogleCloudStorageHook
from airflow.hooks.mssql_hook import MsSqlHook
from tempfile import NamedTemporaryFile
import pymssql
import logging
import os
# import cloudstorage as gcs
from google.cloud import bigquery
from oauth2client.client import GoogleCredentials
from airflow.operators.python_operator import PythonOperator

default_args = {
    'owner': 'airflow',
    'start_date': airflow.utils.dates.days_ago(2),
    'depends_on_past': False,
    'email': ['airflow@airflow.com'],
    'email_on_failure': False,
    'email_on_retry': False,
    'depends_on_past': False,
    # If a task fails, retry it once after waiting
    # at least 5 minutes
    'retries': 1,
    'retry_delay': timedelta(minutes=5),
}

dag = DAG(
    dag_id='test_tab1',
    default_args=default_args,
    schedule_interval=timedelta(days=1),
    dagrun_timeout=timedelta(minutes=60)
)

try:
    script_path = os.path.dirname(os.path.abspath(__file__)) + "/"
except:
    script_path = "/usr/local/airflow/key/key.json"

#Bigquery Credentials and settings
os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = script_path

def insert_bigquery(self):
    bigquery_client = bigquery.Client(project="project-name")
    dataset_ref = bigquery_client.dataset('bucket-name')
    job_config = bigquery.LoadJobConfig()
    job_config.autodetect = True
    job_config.skip_leading_rows = 1
    job_config.source_format = bigquery.SourceFormat.CSV
    time_partitioning = bigquery.table.TimePartitioning()
    job_config.time_partitioning = time_partitioning
    job_config.clustering_fields = ["id"]
    #job_config.field_delimiter = ";"
    uri = "gs://bucket-name/"+filename
    load_job = bigquery_client.load_table_from_uri(
        uri,
        dataset_ref.table('tab1'),
        job_config=job_config
        )
    print('Starting job {}'.format(load_job.job_id))
    load_job.result()
    print('Job finished.')

json_gcs_to_bq = PythonOperator(
    task_id='json_gcs_to_bq',
    python_callable=insert_bigquery,
    provide_context=True,
    dag=dag)

Error Message:
[2019-06-21 15:45:40,732] {{models.py:1760}} ERROR - insert_bigquery() got an unexpected keyword argument 'dag'
Traceback (most recent call last):
  File "/usr/local/lib/python3.6/site-packages/airflow/models.py", line 1659, in _run_raw_task
    result = task_copy.execute(context=context)
  File "/usr/local/lib/python3.6/site-packages/airflow/operators/python_operator.py", line 95, in execute
    return_value = self.execute_callable()
  File "/usr/local/lib/python3.6/site-packages/airflow/operators/python_operator.py", line 100, in execute_callable
    return self.python_callable(*self.op_args, **self.op_kwargs)
TypeError: insert_bigquery() got an unexpected keyword argument 'dag'

A: You do not need to parse in self into yor python_callable. Modify your insert_bigquery function's parameter as def insert_bigquery(ds, **kwargs) instead of def insert_bigquery(self).
Reference: https://airflow.apache.org/howto/operator/python.html


text:
Q: Use AJAX to update page when new row is added to table I am in the process of learning AJAX, as I need it for a current project. I have a feed which I want to update live when a new row is added to a MYSQL table. I've actually done this with node.js, but unfortunately my clients server can't use NODE, so I am trying to see if it's possible with AJAX.
Thank you for your help!

A: You'll need to have the client either contact the server constantly via polling, or use a push technique such as comet or websockets. Otherwise your client has no way to know when new data has arrived.
Comet and websockets allow for the most real-time feel to the process since they actually send the data to the user client (your connected browser) as soon as it is available whereas with polling it's just your browser querying the server on an interval.
Disadvantage is that push techniques and certainly comet which requires a HTTP Keep Alive can be quite heavy on your server, especially for process based servers such as apache, their maximum connections get filled quickly and then held up until disconnect. There are tuning options and modern settings for it but it's not optimal: the problem even has an official name c10k and is one of the reasons you see event based servers gain popularity these days.

A: There isn't any way that i know about where MYSQL or PHP can push updates to a page when it is updated.
The best option would probably be running timer with javascript and check the database periodically to see if there have been any updates,
var refreshId = setInterval(function() { checkforUpdates(lastIndex) }, 10000);

Pass in the last row of your table index to the javascript function and the function makes an ajax call to a PHP that queries the database for any new rows, if any updates returned, add them to the table with javascript.
If you are also looking to check for updated rows, that gets a bit trickier!

A: its easier to do ajax stuff with jquery
$("#update_charges").live("click",function() {
     $.ajax(
         {
            type: "POST",
            url: "phpfile_toadd_updaterecord.php",
            data: "passvalue="+$('input_field_name').val(),
            success: function(msg)
           {
                            $('#result_div').html(msg); //msg contains any test echoed  from  //phpfile_toadd_updaterecord.php file
           }
     });//end $.ajax
 }

below can be your html code
<form>

<input type="button" name="update_charges" id="update_charges" />
<input type="hidden" name="input_field_name" id="input_field_name" value="anyvalue_to be passed to php file"/>
</form>

Jquery ajax help page


text:
Q: Tricky problem about time and work today my 'Introduction to Mathematics' proposed the following problem.
Two painters spend 18 hours to paint a wall, how many hours will 4 painters spend in the same wall ?
She told us that they will spend 36 hours, I know how to get it but, it doesn't makes any sense to double the labor and spend more time. Is it right ?

A: You're right. More workers means less time. Use the equation $Work=rate*time$. The amount of work to paint one wall, according to the first equation, is $2*18=36$ person-hours. Thus, for four workers, we have $36=4T$, which we solve to obtain $T=9$.

A: The ratio is
$$2:18$$
This is inverse proportionality, so the proportion is
$$2:18::x:4$$
Where $x$ is the number of hours the 4 painters take to paint the wall.
One thus has
$$8=18x\\
\implies x=\frac{4}{9}\mbox{hours.}$$


text:
Q: How to use establish a secure connection in code behind application page SharePoint 2010 I need to solve the double hop issue for SharePoint 2010 application page. The ASP (C# code behind) page must connect securely to SQL server instance on another host.  The secure store service appears to me to only work for a webpart. This can not be accomplished for the application page. Is there a secure alternative?
Current connection string is similar to:

private const string CONNECT_STR = @"Data Source=10.X.X.X,1433
  ;Initial Catalog=TestCatalogName ; Integrated Security=false;User
  ID=testID;Password=********";
  SqlConnection con = new SqlConnection(CONNECT_STR)

This seems like a common problem in SharePoint so I hope there is a corresponding common solution.

A: Only A webpart can use the secure store service in SharePoint 2010. The solution in place uses a SharePoint application page. I am connecting SQL Server and a viable alternative is to use a certificate for the encrypted connection.
See Enabling Encryption section in Using Encryption Without Validation in the client as in my case and concerned only with encryption over the connection. Both the client and server hosts are trusted.
See Selectively using secure connection to SQL Server. The table provides a good explanation of how to achieve the result of a my client using encrypted connection without impacting the SQL server and other connections to it.
The updated connection string is:

private const string CONNECT_STR = @"Data Source=10.X.X.X,1433 ;Initial Catalog=CM_ReleaseManagement ; Integrated Security=false; TrustServerCertificate=true; Encrypt=true; User ID=testID;Password=********";

See "Encrypting Connections to SQL Server" (insufficient reputation to post link) for instructions on configuring SQL Server per Microsoft when you need to encrypt all communications and higher level of security is required. No PII/PHI data involved.


text:
Q: How can I "compress" my tree into aggregate data on up the hierarchy in Oracle? I have to get a list of limits for a the sub-parts of a level 1part.  Limits for some parts are null, and for those null parts, I have to query the level 2 parts that are on that part and give the MIN of the limits of those level 2 parts.  For some of the level 2 parts, I have to get the MIN of their sub-parts (the level 3 parts on that level 2 part) and roll that up to the level 2 aggregate.
What would be your approach?
In writing this, I realized that I could filter the nulled level 1 parts out and UNION it with a query that does the aggregation for nulled level 1 parts, but I want to make sure there's not a better solution.  I think I felt a little pigeon holed by the query that I was given originally, which gave the entire tree (lower level parts parts were joined to higher level parts using START WITH and CONNECT BY), and I was trying to compress it via clever SQL, but I could not.  Also, I'd like the query to work with n levels of aggregation, not a finite number based on how many times I want to copy-paste my UNIONs and subqueries.
This has to be done in SQL.  I can't use PL/SQL.
For simplicity's sake, think of the schema like this:
Assembly table
level1_serial | level2_serial
-----------------------------
1234          | null
123           | 1
123           | 2
123           | 3

Limit table
part_serial | limit
-------------------
1234        | 1000
123         | null
1           | 500
2           | 400
3           | 600

In this case, I would need to return two records as follows
part_serial | limit
-------------------
1234        | 1000
123         | 400

A: Try this:
SELECT
    PART_SERIAL,
    MIN(LIMIT)
FROM (
    SELECT
        NVL(PRIOR LIMIT.PART_SERIAL, LIMIT.PART_SERIAL) PART_SERIAL,
        LIMIT.LIMIT LIMIT,
        LEVEL
    FROM
        LIMIT
    CONNECT BY PRIOR
        LIMIT IS NULL AND
        PRIOR PART_SERIAL <> PART_SERIAL AND
        INSTR(PRIOR PART_SERIAL, PART_SERIAL) > 0 AND LEVEL < 10
)
GROUP BY PART_SERIAL;

It's do the job, but it returns more results, so you must do filtering.


text:
Q: Usage of RAM acquiring frames I created a C# application that receive a RGB stream in input, then compress the stream and save it on the disk.
For my test I'm running an application that acts as server(on the same pc) which streams out the video.
The core of my client application is:
void client_ColorFrameReady(object sender, ColorFrameReadyEventArgs e)
{
    if (writer != null)
    {
        count++;
        if (count % 2 == 0)
            writer.WriteVideoFrame(ResizeBitmap(BitmapImage2Bitmap(e.ColorFrame.BitmapImage), 320, 240));
        }
        else
        {
            writer.Close();
        }
    }
}

the type of writer is VideoFileWriter from aforge.net library.
My application works well, but I have a problem related to the amount of RAM used.
When my application is acquiring frames the RAM used from the server application (the application that stream out the video) increases linearly with time. The RAM is freed only when writer.Close() is executed.
The methods BitmapImage2Bitmap and ResieBitmap are shown below:
private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
    // BitmapImage bitmapImage = new BitmapImage(new Uri("../Images/test.png", UriKind.Relative));

    using (MemoryStream outStream = new MemoryStream())
    {
         BitmapEncoder enc = new BmpBitmapEncoder();
         enc.Frames.Add(BitmapFrame.Create(bitmapImage));
         enc.Save(outStream);
         System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(outStream);

         // return bitmap; <-- leads to problems, stream is closed/closing ...
         return new Bitmap(bitmap);
    }
}

private static Bitmap ResizeBitmap(Bitmap sourceBMP, int width, int height)
{
    Bitmap result = new Bitmap(width, height);
    using (Graphics g = Graphics.FromImage(result))
    g.DrawImage(sourceBMP, 0, 0, width, height);
    return result;
}

Can I limit the usage of RAM in my application?

A:
I use always using

You are not.  Unfortunately you also use it when you should not.  There are three bitmap objects being 'leaked' here for every frame.
You got in trouble by using using on the MemoryStream.  And patched the problem by copying the bitmap, but the bitmap object is not being disposed.  Fix this the right way, do not dispose the MemoryStream.  Not disposing the MemoryStream is fine, it only uses memory and has no disposable members when you don't use the MemoryStream(Stream) constructor.  Now you don't need the copy you make with the Bitmap(image) constructor anymore either.   That's one.
The bitmap returned by BitmapImage2Bitmap() is not being disposed.  That's two.
The bitmap returned by ResizeBitmap() is not being disposed.  That's three.
It should look like this:
using (var frame = BitmapImage2Bitmap(e.ColorFrame.BitmapImage))
using (var thumb = ResizeBitmap(frame, 320, 240)) {
    writer.WriteVideoFrame(thumb);
}

and:
private Bitmap BitmapImage2Bitmap(BitmapImage bitmapImage)
{
    var outStream = new MemoryStream();
    var enc = new BmpBitmapEncoder();
    enc.Frames.Add(BitmapFrame.Create(bitmapImage));
    enc.Save(outStream);
    return new System.Drawing.Bitmap(outStream);
}

You may well still have a firehose problem as I mentioned in the comment, this code certainly is faster than the original by avoiding the bitmap copy but still won't burn rubber.


text:
Q: Boost Asio - Why do my asynchronous operations not launch? I recently met a problem with boost::asio asynchronous tasks. I want to return a pointer on an object listening to a port.
It works when I use the socket.read_some method but this method blocks my main and I want my MyClass::create method to return.
So I tried a async_read call but I saw that inside my read() method, no asynchronous tasks are launched. I tried to figure out what may cause the problem but see no solution to this issue.
Here is my code, here it's not with an async_read but with an async_wait, and the same problem appears, the timer is not launched.
Thanks for any help I might get.
The header file:
#ifndef MYCLASS_HPP
#define MYCLASS_HPP

#include <memory>
#include <boost/asio.hpp>

class MyClass
{
public:
MyClass(boost::asio::io_service& ios);

void read();
void read_handler(const boost::system::error_code& error);

static std::shared_ptr<MyClass> create(std:: string const & host, uint16_t port);

bool connect (std::string const & host, uint16_t port);
void connect_handler(const boost::system::error_code& error);

boost::asio::ip::tcp::socket    m_socket;
bool                m_flag;
std::vector<uint8_t>        m_buffer;
};

#endif

Source file:
#include "MyClass.hpp"

#include <boost/bind.hpp>

MyClass::MyClass(boost::asio::io_service& ios)
    :m_flag(false), m_socket(ios), m_buffer(20)
{
}

void MyClass::read_handler(const boost::system::error_code& er)
{
    std::cout << "Timer waited 5 sec" << std::endl;
}

void MyClass::read()
{
    boost::asio::deadline_timer t(m_socket.get_io_service(),boost::posix_time::seconds(5));
    t.async_wait(boost::bind(&MyClass::read_handler,this,boost::asio::placeholders::error));
    m_socket.get_io_service().run();//Should make the io_service wait for all asynchronous tasks to finish
    std::cout << "This message should be displayed after the wait" << std::endl;
}

void MyClass::connect_handler(const boost::system::error_code& error)
{
    if(!error)
    {
        std::cout << "Connection done" << std::endl;
        m_flag = 1;
    }
    else
    {
        std::cout << "Error in connection: " << error.message() << std::endl;
    }
}

//connect method
bool MyClass::connect(std::string const & host, uint16_t port)
{
    boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(host),port);

    m_socket.async_connect(endpoint,
            boost::bind(&MyClass::connect_handler, this,
            boost::asio::placeholders::error));

    m_socket.get_io_service().run();//Wait async_connect and connect_handler to finish

    if (m_flag == 0) return false;
    else return true;
}

std::shared_ptr<MyClass> MyClass::create(std:: string const & host, uint16_t port)
{
    boost::asio::io_service ios;

    std::shared_ptr<MyClass> ptr(new MyClass(ios));

    bool bol = ptr->connect(host, port);
    ptr->read();

    //while(1){}

    if(bol == true)
    {
        //connection success, reading currently listening, pointer is returned to the user
        return ptr;
    }
    else
    {
        //connection failure, pointer is still returned to the user but not listening as he's not connected
        return ptr;
    }
}

And my main:
#include <boost/date_time/posix_time/posix_time.hpp>
#include <boost/asio.hpp>
#include "MyClass.hpp"

int main()
{
    try
    {
    std::cout << "Creation of instance" << std::endl;

    std::shared_ptr <MyClass> var = MyClass::create("127.0.0.1", 8301);

    std::cout << "Instance created" << std::endl;

    }
    catch (std::exception& e)
    {
        std::cerr << e.what() << std::endl;
    }

    return 0;
}

A: I figured out how to solve my problem.
I had indeed problems with io_service being destroyed after "create" method, so the pointer returned in the main was not able to continue reading.
I had to call run() at one point to launch callbacks but i couldn't do it in the main, as I wanted the main to keep doing other things.
So I created a class launching a separated thread and containing an io_service. That thread is calling run() periodically. It was then added as an attribute to MyClass.
Now I have the call to "create" returning a pointer to MyClass who doesn't stop whatever asynchronous task was launched in MyClass.


text:
Q: Number of solutions to linear diophantine equation in 3 variables Find the number of ordered tuples $(x,y,z)$ such that $x,y,z$ are positive integers that satisfy the equation $14x+6y+21z=504$.
My first thought was generating function. Let
$$f(z)=(z^{14}+z^{28}+z^{42}+\cdots)(z^6+z^{12}+z^{18}+\cdots)(z^{21}+z^{42}+z^{63}+\cdots)$$ $$=\frac{z^{14}}{1-z^{14}}\cdot \frac{z^{6}}{1-z^{6}}\cdot \frac{z^{21}}{1-z^{21}},$$
then the number of solutions to the desired equation is the coefficient of $z^{504}$ of $f(z)$, or coefficient of $z^{463}$ of
$$\frac{1}{1-z^{14}}\cdot \frac{1}{1-z^{6}}\cdot \frac{1}{1-z^{21}},$$
which incidentally happens to be a prime number. But decomposing the function into partial fractions would to unpractical, I don't know if there is an easy way to find coefficient of a prime power.
After attacking the problem with generating functions in failure, I tried to look at the numbers $6=2\cdot 3,14=2\cdot 7, 21=3\cdot 7$ and notice a cyclic structure here but don't know if that's relevant.

A: solving for $y$ we get
$$y=84-4z-2x+\frac{3z-2x}{6}$$ substututing $$t=\frac{3z-2x}{6}$$ then $$x=2z-3t-\frac{z}{2}$$ and substituting
$$z=-2s$$ we get
$$x=-5s-3t$$
$$y=84+18s+6t$$
where $s,t$ are integers


text:
Q: Does node-cache uses locks I'm trying to understand if the node-cache package uses locks for the cache object and can't find anything.
I tried to look at the source code and it doesn't look like it, but this answer suggests otherwise with the quote:

So there is Redis and node-cache for memory locks.

This cache is used in a CRUD server and I want to make sure that GET/UPDATE requests will not create a race condition on the data.

A: I don't see any evidence of locking in the code.
If two requests for the same key which is not in the cache are made one after the other, then it will launch two separate fetch() operations and whichever request comes back last is the one that will remain in the cache. This is probably not normally a problem, but an improved implementation could make only one request for that same key and have the second request just wait for the first request to provide the value that was already in flight.
Since the cache itself is all in-memory, all access to the cache is synchronous and thus regulated by Javascript's single threaded nature. So, the only place concurrency issues could affect things in the cache code itself are when they launch an asynchronous fetch() operation.
There are, of course, race conditions waiting to happen in how one uses the code that accesses the data just like there are with a database interface so the calling code has to be smart about how it uses the interface to avoid creating race conditions because of how it calls things.

A: Unfortunately no, you can write a unit test to confirm it.
I have written a library to fix that and also added read through method to easy the code usage:
https://github.com/KhanhPham2411/node-cache-async-lock


text:
Q: Django-Haystack/Whoosh - Rebuild Index Error Python 2.5, Django 1.2.1, most recent haystack, most recent whoosh
This is my first delve into Django-Haystack. I was following the "Getting Started" guide from Haystack and everything seemed to be going along fine, until I went to build the index.
So, running "manage.py rebuild_index" shot this back at me:
Traceback (most recent call last):
  File "/Users/steenb/Documents/Aptana Studio Workspace/bucksac/buckshr/manage.py", line 11, in <module>
    execute_manager(settings)
  File "/Library/Python/2.5/site-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/Library/Python/2.5/site-packages/django/core/management/__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 191, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 218, in execute
    output = self.handle(*args, **options)
  File "/Library/Python/2.5/site-packages/haystack/management/commands/rebuild_index.py", line 13, in handle
    call_command('clear_index', **options)
  File "/Library/Python/2.5/site-packages/django/core/management/__init__.py", line 166, in call_command
    return klass.execute(*args, **defaults)
  File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 218, in execute
    output = self.handle(*args, **options)
  File "/Library/Python/2.5/site-packages/haystack/management/commands/clear_index.py", line 38, in handle
    sb.clear()
  File "/Library/Python/2.5/site-packages/haystack/backends/whoosh_backend.py", line 212, in clear
    self.index.commit()
AttributeError: 'FileIndex' object has no attribute 'commit'

Not sure even where to start with this... has anyone run into this before?
Any thoughts on a solution?
Update:
Tried this with python 2.6 as well, got the same error. Is there some Whoosh configuration that I have not done?
Update:
After using the below suggestion from philippbosch, the first error didn't show up anymore but now I am getting this:
Traceback (most recent call last):
  File "/Users/steenb/Documents/Aptana Studio Workspace/bucksac/buckshr/manage.py", line 11, in <module>
    execute_manager(settings)
  File "/Library/Python/2.5/site-packages/django/core/management/__init__.py", line 438, in execute_manager
    utility.execute()
  File "/Library/Python/2.5/site-packages/django/core/management/__init__.py", line 379, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 191, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 218, in execute
    output = self.handle(*args, **options)
  File "/Library/Python/2.5/site-packages/haystack/management/commands/update_index.py", line 69, in handle
    return super(Command, self).handle(*apps, **options)
  File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 282, in handle
    app_output = self.handle_app(app, **options)
  File "/Library/Python/2.5/site-packages/haystack/management/commands/update_index.py", line 123, in handle_app
    index.backend.update(index, small_cache_qs[start:end])
  File "/Library/Python/2.5/site-packages/haystack/backends/whoosh_backend.py", line 163, in update
    writer = AsyncWriter(self.index.writer, postlimit=self.post_limit)
TypeError: __init__() got an unexpected keyword argument 'postlimit'

I am wondering if I am using an incompatable version of Whoosh.... I grabbed the latest which is 1.0.0b2 ... http://pypi.python.org/pypi/Whoosh/
update:
Turns out it is a version problem. Currently, Haystack is tied to whoosh 0.3.18

A: I had the same problem just now. Did you try »update_index« instead of »rebuild_index«? That seemed to work for me …

A: Installing Whoosh 0.3.18 solved the problem on my side

A: If you found this question while attempting to delete an entry from an index, you might need to use an IndexWriter to delete the entry, rather than a FileIndex object; e.g.:
Instead of:
ix = open_dir('index')
ix.delete_by_term('path', u'/a/b/c')
ix.commit()

which throws the error discussed above, you can delete a file by running:
ix = open_dir('index')
writer = ix.writer()
writer.delete_by_term('path', u'/a/b/c')
writer.commit()


text:
Q: MySql Single Table, Select last 7 days and include empty rows I have searched similar problems here on stackoverflow but I could not understand how to make this work, what I'm trying to do...
So, I want to get last 7 days transactions from database and get total sales amount and also include empty rows if there is no data for some day.
What I have so far:
http://sqlfiddle.com/#!2/f4eda/6
This outputs:
| PURCHASE_DATE | AMOUNT |
|---------------|--------|
|    2014-04-25 |     19 |
|    2014-04-24 |     38 |
|    2014-04-22 |     19 |
|    2014-04-19 |     19 |

What I want:
| PURCHASE_DATE | AMOUNT |
|---------------|--------|
|    2014-04-25 |     19 |
|    2014-04-24 |     38 |
|    2014-04-23 |      0 |
|    2014-04-22 |     19 |
|    2014-04-21 |      0 |
|    2014-04-20 |      0 |
|    2014-04-19 |     19 |

Any help appreciated :)

A: Simply put together a subquery with the dates you want and use left outer join:
select d.thedate, coalesce(SUM(amount), 0) AS amount
from (select date('2014-04-25') as thedate union all
      select date('2014-04-24') union all
      select date('2014-04-23') union all
      select date('2014-04-22') union all
      select date('2014-04-21') union all
      select date('2014-04-20') union all
      select date('2014-04-19')
     ) d left outer join
     transactions t
     on t.purchase_date = d.thedate and vendor_id = 0
GROUP BY d.thedate
ORDER BY d.thedate DESC;

A: This is not easy. I took help from this thread generate days from date range and combined it with your query.
So the idea was to get the list of dates from last 7 days then left join these dates with a static amount 0 to the query you have and then finally sum them. This could be used for any date range, just need to change them in both the queries
select
t1.purchase_date,
coalesce(SUM(t1.amount+t2.amount), 0) AS amount
from
(
  select DATE_FORMAT(a.Date,'%Y-%m-%d') as purchase_date,
  '0' as  amount
  from (
    select curdate() - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY as Date
    from (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as a
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as b
    cross join (select 0 as a union all select 1 union all select 2 union all select 3 union all select 4 union all select 5 union all select 6 union all select 7 union all select 8 union all select 9) as c
  ) a
  where a.Date BETWEEN NOW() - INTERVAL 7 DAY AND NOW()
)t1
left join
(
  SELECT DATE_FORMAT(purchase_date, '%Y-%m-%d') as purchase_date,
  coalesce(SUM(amount), 0) AS amount
  FROM transactions
  WHERE purchase_date BETWEEN NOW() - INTERVAL 7 DAY AND NOW()
  AND vendor_id = 0
  GROUP BY purchase_date
)t2
on t2.purchase_date = t1.purchase_date
group by t1.purchase_date
order by t1.purchase_date desc

DEMO

A: This is for last 7 days;
select d.thedate, coalesce(SUM(amount), 0) AS amount
from (select DATE(NOW()) as thedate union all
      select DATE(DATE_SUB( NOW(), INTERVAL 1 DAY)) union all
      select DATE(DATE_SUB( NOW(), INTERVAL 2 DAY)) union all
      select DATE(DATE_SUB( NOW(), INTERVAL 3 DAY)) union all
      select DATE(DATE_SUB( NOW(), INTERVAL 4 DAY)) union all
      select DATE(DATE_SUB( NOW(), INTERVAL 5 DAY)) union all
      select DATE(DATE_SUB( NOW(), INTERVAL 6 DAY))) d left outer join
     transactions t
     on t.purchase_date = d.thedate and vendor_id = 0
GROUP BY d.thedate
ORDER BY d.thedate DESC;

A: with recursive all_dates(dt) as (
    select '2014-04-19' as dt
    union all
    select dt + interval 1 day
    from all_dates
    where dt + interval 1 day <= '2014-04-25'
)
select d.dt as purchase_date, coalesce(m.amount, 0) as purchased
from all_dates as d
left join mytable m
on d.dt = m.purchase_date
order by purchase_date desc;


text:
Q: Custom CSS in Customer Portal without "repainting" flicker I've experimenting with the Customer Portal and figured out how to inject CSS and JS via custom code in the header.  Unfortunately, on every page load there's a flicker as Salesforce first loads the default formatting and only then loads and applies my changes.  (The flicker is less noticeable after the first few page loads, but still there.)  Is there a good way to eliminate this flicker or to get my custom CSS to apply earlier?
FYI, I want to choose stylesheets dynamically based on which page I'm on, so rather than including <link rel="stylesheet" ... /> elements directly, I'm using Javascript to add them to the page header.
Thanks!

A: are you using onready in jquery to wait until the page has loaded to interact with the DOM? some things to consider:

*

*get your javascript to execute as early in the page load as possible, but after the stanard css references.

*dynamically remove the standard css reference elements. OR

*override them by placing your css reference after the standard and liberally dose your css code with !important

A: Two possible solutions. In your header file:
1) first load ALL stylesheets in your html, instead of dynamically, eg:
<link rel="stylesheet" type="text/css" href="ideas.css" />
<link rel="stylesheet" type="text/css" href="cases.css" />
<link rel="stylesheet" type="text/css" href="solutions.css" />

then use the body class in your CSS to differentiate the pages, eg:
body.ideaTab h3.lbHeader {}
body.caseTab h3.lbHeader {}
body.solutionTab h3.lbHeader{}

which should limit the FOUC (Flash Of Unstyled Content) to the first page load only.
OR 2) you can combine all your styles into one string and include it in a style tag:
<style type="text/css">/* ... */</style>

so that rendering will be blocked until all your styles are loaded, at the expense of making all pages heavier and probably incorporating a build step.

A: Due to the way you are trying to alter the css you will always see a flicker. This is because the javascript will not run until the browser has started loading the HTML and is starting to render. The flicker will shorten after you have loaded the page because the browser will have cached any image files used in your css and the css file you dynamically selected.
I would suggest you create a css file that contains any rules that are generic to all your styles. That way the css you dynamically load will be small and have less changes to make. This should lessen the effect of the flicker but not remove it. I would almost go as far as having css rules in here that remove the salesforce standard image / styles completely so that at least this isnt flashed before your javascript has a chance to set the correct image and styles dynamically.
Also as suggested in another answer make sure you are not containing your javascript in an onLoad function unless your javascript really needs to wait till the page has loaded.


text:
Q: Give the project result to the client in asp I have a basic question
I started to work with asp for a client, and I built some pages with buttons and grids and so on, and now I want to give him the result of the work.
How do I do it?
In a "normal" application - I give him the exe file and all the dlls, but in asp I didn't found any of this, so what I give to him?
thanks

A: Continue from comment ...
Right click on web project, and click on Publish...

Then create a new profile, and select File System at Publish method.


text:
Q: Integral of an angle that depends on a view The problem
There are two lines: $l_1$ and $l_2$. For any point $p$ in $\mathbb{R}^3$, we can calculate an angle between a plane that contains $p$ and $l_1$, and a plane that contains $p$ and $l_2$. Let's call this angle $A(p)$. Now what I need is to find a formula for $A(D)$, where $D$ is a planar figure contained by two lines and a
hyperbola. This needs to be implemented in a real-time computer application, so the formula has to be simple in terms of computational complexity. However, I haven't found any solution at all so far, so let's say the formula complexity is not that important for now.
What I have so far
We can always transform the system in a way, that the area $D$ is laying on the $XOY$ plane (so every point that belongs to $D$ will have coordinates
 $[x,y,0]$). Let's describe input lines $l_1$ and $l_2$ as two pairs of a point and a unit direction vector:
$$l_1: [a,b,c] + t[d,e,f]$$
$$l_2: [g,h,i] + u[j,k,l]$$
$$\text{where}: t, u \in \mathbb R$$
$A([x,y,z])$ equals to the angle between planes normals, and the normals can be found using cross product. If we normalize the vectors (dividing by their lengths), the angle can be retrieved by "reversing" the dot product with arcus cosinus:
$$\begin{align}A([x,y,0]) & = \operatorname{acos}\left(\frac{\left[x - a,y - b, -c\right] \times [d,e,f]}{\sqrt{(x - a)^2 + (y - b)^2 + c^2}} \circ \frac{[x - g, y - h, -i] \times [j, k, l]}{\sqrt{(x - g)^2 + (y - h)^2 + i^2}}\right) \\
& = \operatorname{acos} \left( \frac{\left((x - a)(x - g) + (y - b)(y - h) + ci \right) (dj + ek + fl) - \left((x - a)j + (y - b)k\right)\left((x - g)d + (y - h)e\right)}{\sqrt{(x - a)^2 + (y - b)^2 + c^2}\sqrt{(x - g)^2 + (y - h)^2 + i^2}} \right)\end{align}$$
To find the formula for $A(D)$ we simply need to integrate $A([x,y,0])$ over $D$:
$$\iint_D {A(x,y,0) \ \mathrm{d}x \ \mathrm{d}y}$$
I have no ideas of how to solve manually even the first, internal integral and the only CAS I have is Derive 6 - I had entered this integral and left computer running non-stop. After 4 days of
 nothing, I turned it off... And that's where I got so far.
I would appreciate any help on solving this problem.

A: This is not a solution, but it might inspire someone (who's better in geometry) to find the final answer. Previously, I solved similar problem in $\mathbb{R}^2$:
I needed to find occludance at point E, which was equal to the length of an arc on the unit circle (with center in E), created by projecting occluder on
that circle. To calculate length of the arc, I needed to find angle alpha (arc length = arc radius * arc angle = 1 * alpha):
Click here for image (I have < 10 reputation points so I can't embed images yet...)
So I needed to find an angle beetween vectors $[P_x - E_x, P_y - E_y]$ and $[K_x - E_x, K_y - E_y]$. At first, I did that using the dot product:
$$A(x,0) = \operatorname{acos}\left(\frac{\overline{P} - \overline{E}}{|\overline{P} - \overline{E}|} \circ \frac{\overline{K} - \overline{E}} {|\overline{K} - \overline{E}|}\right)$$
Let's say that this angle formula is the final occludance at point E (one still needs to perform some scaling by $2\pi$ afterwards, but that's not the point here and let's just skip it).
Now what I needed was to find occludance not at a single point E, but for some whole segment of coordinates $[0;0]$ - $[L;0]$. So I needed to integrate $A(x)$ with lower bound limit = $0$ and the higher one = $L$. Let's give one letter labels to every vector coordinate ($m = P_x$; $n = P_y$; $k = K_x$; $l = K_y$) and after separating them, the result is:
$$\int_0^L{\operatorname{acos}\left(\frac{(x - k)(x - m) + ln}{\sqrt{(x-k)^2+l^2}\sqrt{(x-m)^2+n^2}}\right)dx}$$
It wasn't that hard to solve this integral, but the final computational complexity was to high in practice.
Then I found, that the whole problem can be solved without vector math, just bare trigonometry as soon as possible. Instead of taking $A(x)$ from the dot product, I took one angle that was between $Y$ axis and $\overline{EK}$, and second one that was between $Y$ axis and $\overline{EP}$, and then summed them up (that's possible because tan() is continuous in range $(-\frac{\pi}{2} ; \frac{\pi}{2})$), or rather calculate the difference between them because tan is $0$ on Y axis, $>0$ on the left side and $<0$ on the right side:
Click here for another image
$\operatorname{tan}(\operatorname{FirstAngle}) = \frac{k}{l}$, so $\operatorname{atan}(\frac{k}{l}) = \operatorname{FirstAngle}$. Analogicaly we can get the SecondAngle. Now our unit circle moves on $X$ axis from $0$ to $L$, so we need to adjust coordinates $k$ and $m$ by $L$. And that's how I got to a much better formula:
$$\int_0^L{\left(\operatorname{arctan}\left(\frac{k - x}{l}\right)-\operatorname{arctan}\left(\frac{m - x}{n}\right)\right)dx}$$
These two arcus tangens integrals are extremely simple to solve and their solutions are very easy in terms of comutational complexity.
Like I said in some comment above: having some kind of reference hyperplane (in this case $Y$ axis) and eliminating the square root from denominator were the "tricks" to success. I feel that similar "tricks" need to be apply in the 3D variant, but I can't find them.

A: I will refer constantly to the graphical representation at the bottom. It gathers the main ideas together with notations used hereafter.
One can see that reference axes are such that the $x$ axis is directed by the shortest distance segment and $y$ and $z$ axis have been chosen in such a way that the angles made by lines $L_1$ and $L_2$ are symmetrical with respect to plane $x0y$.
Consider a generic point $M_0=(x_0,y_0,z_0)$. Let us call (P) the plane (in green on the figure) with equation $x=x_0$. In plane (P), "moving" from $Q_0(x_0,0,0)$ to $M_0(x_0,y_0,z_0)$ can be decomposed into a red "move" and a blue "move". In the red move, the first plane doesn't change ; in the blue move the second plane doesn't change.
Let $c=\cos(\alpha)$ and $s=\sin(\alpha)$, with $u_1=(0,c,s)$ and $u_2=(0,-c,s)$ (unit vectors).
Let $\vec{i}$ be the unit directing vector of $x$ axis.
An immediate computation gives
$$\tag{1}c_1=\dfrac{z_0c+y_0s}{2sc} \ \ \text{and} \ \ c_2=\dfrac{z_0c-y_0s}{2sc}.$$
Thus, we can write:
$$\vec{Q_0P_0}=c_1\vec{u_2} \ \ \text{and} \ \ \vec{P_0M_0}=c_2\vec{u_1}.$$
Let us be more precise. The normal vector $N_2$ to the plane defined by $M_0$ and $L_2$ is:
$$N_2=\vec{u_2} \times \vec{A_2M_0} = \vec{u_2} \times (\vec{A_2Q_0}+\vec{Q_0P_0} + \vec{Q_0M_0})= $$
$$N_2=\vec{u_2} \times \vec{A_2Q_0}+ \vec{u_2} \times \vec{Q_0P_0} + \underbrace{ \vec{u_2} \times \vec{Q_0M_0}}_{0}$$
$$N_2=(a+x_0)\vec{u_2} \times \vec{i} +c_1\vec{u_2} \times \vec{u_1}$$
$$\tag{i}N_2=(x_0+a)\underbrace{\vec{u_2} \times \vec{i}}_{\text{unit vector}} -2c_1cs \ \vec{i}$$
For similar reasons, the normal vector $N_1$ to the plane defined by $M_0$ and $L_1$ is:
$$\tag{ii}N_1=(x_0-a) \vec{u_1} \times \vec{i} +2c_2cs \ \vec{i}$$
It suffices now to use formulas (i) and (ii) in order to have a vectorial expression of the looked for angle:

*

*either as the arcsine of the cross product $N_1/\|N_1\| \times N_2/\|N_2\|.$

*or as the arccosine of the dot product $N_1/\|N_1\| \bullet N_2/\|N_2\|.$
Remark 1: One could arrive at formulas (i) and (ii) by using the following analytical computations:

*

*the plane defined by $(x_0,y_0,z_0)$ and line $L_1$ has the following equation:

$$\begin{vmatrix}a & a & x_0 & x\\
    0 & c & y_0 & y\\
    0 & s & z_0 & z\\
    1 & 1 & 1 & 1\end{vmatrix}=0 \iff acz_0 - acz + asy - asy_0 - cxz_0 + cx_0z + sxy_0 - sx_0y=0 $$

*

*the plane defined by $(x_0,y_0,z_0)$ and line $L_2$ has the following equation:

$$\begin{vmatrix}-a & -a & x_0 & x\\
    0 & -c & y_0 & y\\
    0 & s & z_0 & z\\
    1 & 1 & 1 & 1\end{vmatrix}=0 \iff
acz_0 - acz - asy + asy_0 + cxz_0 - cx_0z + sxy_0 - sx_0y=0$$
From these equations, it is easy to extract the normal vectors to these two planes:
$N_1=\begin{pmatrix}sy_0-cz_0\\as-sx_0\\cx_0-ac\end{pmatrix}=(-a+x_0)\begin{pmatrix}0\\c\\s\end{pmatrix}\times\begin{pmatrix}1\\0\\0\end{pmatrix}+2c_1cs\begin{pmatrix}1\\0\\0\end{pmatrix}$ which, using the expression of $c_1$ given in (1) is identical to (ii) (up to a global sign change).
and $N_2=\begin{pmatrix}sy_0+cz_0\\-as-sx_0\\-cx_0-ac\end{pmatrix}=(-a-x_0)\begin{pmatrix}0\\-c\\s\end{pmatrix}\times\begin{pmatrix}1\\0\\0\end{pmatrix}+2c_2cs\begin{pmatrix}1\\0\\0\end{pmatrix}$ which is identical to (i) (up to a global sign change).
2) It is interesting to note that, in formulas (i) and (ii), $2cs=sin(2\alpha)$.


text:
Q: How to get a specific set out of an array with json objects with angular Good evening,
I have an array of json objects and i am able to display them with angular one by one (in this care I am creating a blog ). I get the array of json object with a HTTP GET.
So I have a landing page and that displays blog tittle and teasertext, when i click on the teasertext i want to jump to a detail page for that specific blog where you can see the long text.
I have created the service, and the components. When i click on the teasertext I see in the adressbar it has the correct ID of the post i clicked on (i am using mongoDB so the ID is rather big :) )
I suspect the error is in the method , but I am stuck with it. Reading and displaying the whole array was easy, displaying a specific set has me stumped. As I mentioned if i click on the post i want the details of I see the _id of the post in the adressbar as i would expect, like so:
http://127.0.0.1/goals/detail/5ed81b205822000001007632
So how do i get Angular to give me the records of only that specific json. so i can use it in the html like:  Details off:  {{blog.title}} etc etc
My components is:
blog-detail.component.ts:
import { Component, OnInit, Input } from '@angular/core';
import { Blog } from 'src/app/core/models/blog';
import { BlogService } from 'src/app/core/services/blog.service';
import { ActivatedRoute, Router } from '@angular/router';
//import { Location } from '@angular/common';

@Component({
  selector: 'app-blog-detail',
  templateUrl: './blog-detail.component.html',
  styleUrls: ['./blog-detail.component.css']

})
export class BlogDetailComponent implements OnInit {

  @Input() blog: Blog;
  pageTitle: string = 'Blog Detail';
  blogList: Blog[];

constructor(
  private route: ActivatedRoute,
  private blogservice: BlogService,

) {}

ngOnInit(): void {
  this.getBlogs();
}

getBlogs(): void {
  const id = +this.route.snapshot.paramMap.get('_id');
  this.blogservice.getBlogs()
    .subscribe(blog => this.blogList = blog);
}

}

My blogservice is:
import { Injectable } from '@angular/core';
import { Blog } from '../models/blog';
import { Observable, of } from 'rxjs';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, map, tap } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class BlogService {
  private blogUrl = 'http://127.0.0.1/blog';  // URL to web api
  httpOptions = {
    headers: new HttpHeaders({ 'Content-Type': 'application/json' })
  };

  constructor(
    private http: HttpClient
    ) { }

    getBlogs(): Observable<Blog[]> {
      return this.http.get<Blog[]>(this.blogUrl);
    }

  }

The result from the http get is: something like
{"_id":"5ed81b205822000001007632","title":"Title blog 1","content":"Main blog text with pictures and stuff.","updated_at":"2020-06-07 03:58:58","created_at":"2020-06-03 21:50:24","shorttext":"teaser text","created_by":"user 1"},{"_id":"5ed81b2b5822000001007633","title":"Title blog 2","content":"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.","updated_at":"2020-06-07 06:49:39","created_at":"2020-06-03 21:50:35","shorttext":"Lorem ipsum dolor sit amet, teaser text","created_by":"user 2"}]

EDIT: I now created an extra methode in my service:
 /** GET blog by id. **/
    getBlogDetail(_id: string): Observable<Blog> {
    const url = `${this.blogUrl}/${_id}`;
    return this.http.get<Blog>(url);
  }

and used that in in the component:
ngOnInit(): void {
  this.getBlogDetail();
}

getBlogDetail(): void {
  const id = +this.route.snapshot.paramMap.get('_id');
  this.blogservice.getBlogs()
    .subscribe(blog => this.blogList = blog);
}

But i still cant get it to work.

A: Demo you can use as service with stringfiying object but you loose data if refresh page
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
@Injectable()
export class ShareService  {
  constructor() { }
  private paramSource = new BehaviorSubject("");
  getParam = this.paramSource.asObservable();
  setParam(param:string) { this.paramSource.next(param)}
}

you can use localStorage with stringying object if in same tab, you loose data if open new browser
or you can call api in page with related id to get details (recommended)
getBlogDetail(): void {
  const id = this.route.snapshot.paramMap.get('blogId');
  this.blogservice.getBlogDetail(id)
    .subscribe(blog => console.log(blog));
}

A: 5ed81b205822000001007632 using this id you need make a new api call for getting particular id data.there is no other options.

A: pc_coder's answers help a lot and pointed me in the right direction. I had to take several more steps I realised from my initial attempts
First of all i had to get laravel to allow a GET to a specific blogId. (this was achieved with a fairly simple function in Laravel public function form($_id = false){
        if($_id){
            $data = Post::findOrFail($_id);
            return  $data;
Inside the controller that manages the posts. Besides this function i had to add a route Route::get('/post/{_id?}', 'PostController@form')->name('post.form');
in laravel. These 2 things setup the url for the get.
On the angular side I was still struggling to pass the _id to the url, PC-Coder's question about the routes pointed me in the right direction. I noticed the route actually was
{path: 'detail/:blogId', component: BlogDetailComponent}
So i did two things, first of all i made a second url: private blogUrlDetail= 'http://127.0.0.1/post'; , this was to point to the right 1st part of the GET address, and next i realised that passing _id wasn't correct *hence the "NULL" i was getting all the time, but that it should be "blogId".
The function in the service now became:
    getBlogDetail(blogId: string): Observable<Blog> {
    const url = `${this.blogUrlDetail}/${blogId}`;
    return this.http.get<Blog>(url);
  } ```

The class in the blog-detail-component now became:
`` export class BlogDetailComponent implements OnInit {

  @Input() blog: Blog;
  pageTitle: string = 'Blog Detail';
  blogList: Blog[];

constructor(
  private route: ActivatedRoute,
  private blogservice: BlogService,

) {}

ngOnInit(): void {
  this.getBlogDetail();

}

getBlogDetail(): void {
  const id = this.route.snapshot.paramMap.get('blogId');
  this.blogservice.getBlogDetail(id)
    .subscribe(blog => this.blog = blog)
}```

Now i can just get all the fields with {{ blog.title}}, {{ blog.content }} etc

Thanks pc_coder. your help is very much apreciated.


text:
Q: Compare and exchange weak an atomic variable I have code (updated to correct the union-struct ordering):
union A {
    struct {
         short b;
         short c;
    };

    std::atomic<int> d;
}

and I want to swap both b and c (hence the atomic d) with the value zero, using compare_exchange_weak(). So I have this:
A a;
.
.
.
std::atomic<int32_t> x = a.d.load(std::memory_order_relaxed);
int32_t valToReplace = 0;

return a.d.compare_exchange_weak(valToReplace, x, std::memory_order_release, std::memory_order_relaxed);

How do I do this? The argument to compare_exchange_weak(), x, cannot be atomic- so I am confused?

A: The local variable x shouldn't be atomic. There's no reason for it to be, and it can't be used as the argument to compare_exchange_weak, which expects a regular value.
I won't comment on whatever you're trying to do with the union, since that makes no sense to me.


text:
Q: running node.js application with nginx I have a node application running on port 8443. My nginx handles the web requests on port 80 and 443 and should redirect the user to 8443.
here's my /etc/nginx/sites-enabled/default config:
upstream my_upstream {
   server 127.0.0.1:8443;
   keepalive 64;
}

server {
    listen 80;
    server_name myapp.com;
    rewrite ^/(.*) https://myapp.com/$1 permanent;
}

server {
    listen 443 ssl;
    server_name 12.34.12.34 www.myapp.com myapp.com *.myapp.com;
    ssl_certificate /path/to/my/cert.crt;
    ssl_certificate_key /path/to/my/private.key
    // other ssl params

    location / {
        proxy_redirect off;
        proxy_pass https://my_upstream;
        // other params
    }
}

with this config I can access my app via
http(s)://myapp.com:8443

only when I add the following iptables
iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 8443
iptables -t nat -A OUTPUT -p tcp --dport 443 -o lo -j REDIRECT --to-port 8443

I can access
http(s)://myapp.com

Questions:
It seems kinda silly to me to redirect from port 80 to 443 to 8443 using iptables. Is there a way to do this with nginx only (or is this the way to go?).
Is this approach (having the application on a non standard port like 8443) a good idea at all?

A: Easy. Since your node.js is running on port 8443, and as far as I understood, you don't have any other service listening for requests in other ports, you can simply do this in your nginx configuration:
server {
    # here comes the rest of your nginx configuration
    location / {
        proxy_pass http://127.0.0.1:8443;
    }
}

You don't have to use any iptables rules, nor create an upstream section in your nginx configuration. nginx can (and should) do all the port redirect out of the box (as normally any reverse proxy does).
I could be wrong, but the reason your application starts working after the iptables rules is because your clients start to access your node.js server directly, because of the port redirect, which is similar to when we use Squid as a transparent proxy.
This article can help you. Ignore the fact the it was addressed to Apache:

*

*https://www.digitalocean.com/community/tutorials/how-to-configure-nginx-as-a-reverse-proxy-for-apache
Good luck and best regards!

A: It's a bit pointless and wasteful to be doing encryption on 127.0.0.1 between nginx and your upstream, when your upstream is running at 127.0.0.1.
If anything, your solution with iptables redirect would actually be much more efficient than simply getting nginx into the mix, without any changes to the upstream.
But we have to ask -- if you're not using any extra cool features of nginx, why do you want to add it into the mix in the first place?
The proper approach would be to run your upstream without https, and redirect both the http and https to the upstream with nginx.  The reason your present config doesn't work likely has to do with some configuration error, which is not obvious from the snippets you've pasted so far.


text:
Q: Web services clients in Java I'd like you to list all the solutions available to generate web-service clients in Java platform.
I need to extract the structured information from the web-service to work with.
What do we have in the box? Preferably available as Eclipse plugins.

*

*Axis2

*JBossTools

*Apache CXF

What else ?
The problem here is that most tools do not work with web-services I need to consume.
Apache CXF does not generate the client.
JBoss only partially does the job.
I would like to try something and find what really works with particular web services.

A: java.sun.com/webservices/.../wsit/.../Examples_glassfish6.html
this is for creating web services

A: No one gave a clear answer yet.
I got one advice: always try different versions of a framework, and try the latest.
It may sometimes be the key answer.


text:
Q: How does Quaternion.eulerAngles work in Unity? I'm trying to make a function that converts a Quaternion in Unity to euler angles, but I can't get the correct angles at all! I know that Unity can do this for me, but I want to know how to do this myself in a custom function. I've looked up many implementations online, but they don't seem to work.
This is what I have to check if the output is correct:
Quaternion quat = new Quaternion(0.45f, 0.45f, 0.45f, 0.5f);
Debug.Log(quat.eulerAngles);  // Correct euler angles
Debug.Log(MathFunctions.QuaternionToEulerAngles(quat));  // My implementation

This is the method I'm using to get the euler angles:
public static Vector3 QuaternionToEulerAngles(Quaternion quaternion)
    {
        Vector4 q = new Vector4(quaternion.x, quaternion.y, quaternion.z, quaternion.w);
        Vector3 res;

        double sinr_cosp = +2.0 * (q.w * q.x + q.y * q.z);
        double cosr_cosp = +1.0 - 2.0 * (q.x * q.x + q.y * q.y);
        res.x = (float)Math.Atan2(sinr_cosp, cosr_cosp);

        double sinp = +2.0 * (q.w * q.y - q.z * q.x);
        if (Math.Abs(sinp) >= 1)
        {
            res.y = (float)((Math.PI / 2) * Math.Sign(sinp));
        }
        else
        {
            res.y = (float)Math.Asin(sinp);
        }

        double siny_cosp = +2.0 * (q.w * q.z + q.x * q.y);
        double cosy_cosp = +1.0 - 2.0 * (q.y * q.y + q.z * q.z);
        res.z = (float)Math.Atan2(siny_cosp, cosy_cosp);

        return ConvertRadiansToDegrees(res);
    }

How do I get my function to work? Unity's euler angles are different from my euler angles.


text:
Q: Cereal: deserialize a vector of objects without default constructor I'm trying to use Cereal to serialize an object without default constructor. Storing such objects directly or via smart pointer works. However,
when I put the object into a container, it no longer compiles:
error: no matching function for call to 'Node::Node()'
Is there a way to get cereal to store/restore vectors of objects without default constructor?
My test code:
#include <fstream>
#include <cereal/archives/json.hpp>
#include <cereal/types/memory.hpp>
#include <cereal/types/vector.hpp>

class Node {
public:
    Node(int* parent) {};

    int value_1;

    template<class Archive>
    void serialize(Archive& archive) {
        archive(
                CEREAL_NVP(value_1)
        );
    }

    template<class Archive>
    static void load_and_construct(Archive& archive, cereal::construct<Node>& construct) {
        construct(nullptr);
        construct->serialize(archive);
    }
};

int main() {
    std::string file_path = "../data/nodes.json";
    Node node_1{nullptr};  // this would serialize

    std::vector<Node> nodes;  // this does not
    nodes.push_back(Node{nullptr});
    nodes.push_back(Node{nullptr});

    std::vector<std::unique_ptr<Node>> node_ptrs;  // this would serialize
    node_ptrs.push_back(std::make_unique<Node>(nullptr));
    node_ptrs.push_back(std::make_unique<Node>(nullptr));

    {  //store vector
        std::ofstream out_file(file_path);
        cereal::JSONOutputArchive out_archive(out_file);
        out_archive(CEREAL_NVP(nodes));
    }

    {  // load vector
        std::ifstream in_file(file_path);
        cereal::JSONInputArchive in_archive(in_file);
        in_archive(nodes);
    }

    return 0;
}

A: As far as I understand the way this library works, there is no way to deserialize something that doesn't have a default constructor at least for dynamically allocated objects.
The logic under this is the following:

*

*You need to deserialize vector<Node>

*In order to do that you need to allocate an appropriate amount of memory

*cereal doesn't know about the constructor and can't properly allocate object memory by itself

*In order to provide a proper object building it requires the default constructor


text:
Q: Why do i need both std and string library to use strings in c++ I know that string type exists in namespace std. I also know there is the <string> library which needs to be included in order to use the string type. My question is: why do i need both (to include the library and use the std namespace) to define a string? Why cant i just use it by including the library? More generally, what does the namespace std contains that is missing from the library?

A: Namespaces and headers are two separate concepts doing entirely different things:

*

*The header <string> declares the various entities related to the strings library like the class template std::basic_string, some typedefs like std::string and std::wstring, and some functions.

*Namespaces are used to group related functionality and allow use of the same names in different namespaces. For example, a "vector" is essentially an array for some (this is the view taken by the standard C++ library defining this name in namespace std) while in other contexts it is a mathematical entity.

When you included <string> you got all entities related to the strings library declared inside namespace std. Some people object to the idea to use std::string because it is so much easier to use string instead. To aide this practice a using directive, i.e., a statement like using namespace std; can be used to look in namespace std for entities when looking up names. That is, the using directive merely makes names available without qualification.

A: Look at it this way: std::string is the complete name of the type, much like "M. Kostas" is your complete name.
#include <string> gives you std::string. You can call it string only if you have first established the correct context, e.g. by using namespace std or by using std::string, or if you yourself happen to be library code within namespace std { /* ... */ }.
Again, consider the analogy with family names. I can only refer to you by "M." if I have first established that I am talking about the "Kostas" family (= using namespace std), or if I previously said that by "M." I actually mean "M. Kostas" (= using std::string) , or if I am myself a member of the "Kostas" family (= namespace std { /* ... */ }).
Note that you should (in the opinion of many programmers, at least, mine included) rarely use using namespace std or using std::string. It's often better to just use complete names everywhere. At global scope in header files, using shortcuts is even no longer a matter of style but can lead to real technical problems.


text:
Q: How should I transform this time series such that the magnitude of each value can be compared without the effect of the decreasing variance? this is my first post and it's nice to join this community. I'm not exactly an expert at statistics, but I really enjoy it. The following problem has become somewhat of an enigma for me.
I have this time series, which I first detrended using nonparametric regression of a moving median. I decided to use the moving median as an intermediate step as I wanted to the model to be as robust as possible and I want it to best reflect the central tendency of the data (do you approve of this approach?). I am now looking for a way to scale these values so that magnitudes can be compared without the effect of the decreasing volatility over time. I suppose this is a case of having to remove heteroskedasticity, and I'm uncertain of the best way to go about this.
I've already tried this:

*

*I've tried a type of median absolute deviation with a moving window, and then divided each value in the detrended series by it. This seems to blow areas of low volatility out of proportion, regardless of the window used.

*I took a moving median across several seasonal cycles, for instance, you take the median of n past values of Monday, then Tuesday, and so on. I then took a moving standard deviation of this new series and used it to divide each of the detrended values. Again, the results weren't stellar, with non-uniform variance across the series and values further to the right getting blown out of proportion.

In my research I've come across a few possible tools. The Box-Cox power transform is frequently mentioned. I've also read a lot about GARCH models, but how I would use it to achieve my goal isn't very clear to me. Again, I want to transform this series in such a way that, apart from outliers, volatility is more or less constant throughout, and the magnitude of values can be compared independent of the level of volatility prevailing at the time. In other words, I want to know how large a certain deviation is, given the current expected deviation. What would your approach to this problem be?
Any help is much appreciated.


text:
Q: Is it possible to have a view have the same primary key as its underlying table? Suppose I have the following table:
CREATE TABLE item (id int PRIMARY KEY, name text, price numeric);

I am able to run queries such as
SELECT COUNT(*), id, name, price FROM item GROUP BY id;

I assume because id is the primary key of the table, even though name and price are not in the GROUP BY clause.
Now suppose I create a view on the item table as so:
CREATE VIEW item_view AS SELECT * from item;

If I try to run the same query against this view, it doesn't work:
SELECT COUNT(*), id, name, price FROM item_view GROUP BY id;

ERROR:  column "item_view.name" must appear in the GROUP BY clause or be used in an aggregate function

And I assume this is because the item_view view does not respect the primary key constraint of its underlying item table.
I guess I have two questions here:

*

*Is there a way I can make the last query on the view valid so that it is equivalent to the first query?

*Is it bad practice to group by the primary key and then select whatever fields I want?


text:
Q: Jenkins Deploy Plugin to Multiple Tomcat Servers I would like to use Jenkins Deploy Plugin to deploy my war file to multiple remote tomcat 7 servers.
Via the UI i can only do one server though.  Once I select 'Deploy war/ear to a container', I cannot select it again.  The option is greyed out.
Note the deployment to the one server works just fine, I just want to be able to deploy to multiple servers.  Can I do this with Jenkins Deploy Plugin?

A: I don't think so, I believe that is the limitation of this plugin in jenkin. Ideally it should allow us to deploy the same war on more than one servers.Hope this helps.


text:
Q: Getting the amount of rows in your dataset that aren't NULL for several columns? My query:
SELECT name,address,phone,fax FROM clients WHERE state='TX';

What I'm trying to find out is how can I get the number of rows that have data in them for each column - as some fields may be NULL, but I'm interested to find out how many in the result set actually have data.
I do NOT want to restrict the result set I get back in any way other then I have already done above with the WHERE clause. What I want returned in addition to the result set for example is: the number of fields in the name field that have data (are not NULL) & the same thing for the address field etc
I do not need it for every column, just some.

A: I'm not sure if this is what you're asking for but I think you want this:
select count(*)
from clients
where state = 'TX'
  and (
       name    is not null
    or address is not null
    or phone   is not null
    or fax     is not null
)

That will tell you how many rows in clients have a state of Texas and at least one of name, address, phone, and fax is not NULL.
UPDATE: Based on your question update I think you're looking for something like this:
select
    sum(if(name    is null, 0, 1)) as have_names,
    sum(if(address is null, 0, 1)) as have_address,
    sum(if(phone   is null, 0, 1)) as have_phone
    sum(if(fax     is null, 0, 1)) as have_fax
from clients
where state = 'TX'

You'll have to do two queries — one for the column values and one for the counts — as you're trying to get two distinct things.

A: Note that :
sum(if(name    is null, 0, 1)) as have_names

is equivalent to (but slower) :
count(name) AS have_names

As for the original question, since a SELECT returns a tabular list of rows/colums your problem is where would the counts fit ? If you return them as extra lines, they will be in the wrong columns, and if you return them as extra columns, you'll get one for each line.
So you need to do two queries...


text:
Q: Select row by specifying date column I have this record in my table
Name   UserName     Password     DateAdded
skype  someusername somepassword 05/06/2012 01:18:50

I am trying to execute this statement but it always fails.
Some attempts: (all fails)
Select * from Passwords where DateAdded = '05/06/2012 01:18:50'
Select * from Passwords where DateAdded = #05/06/2012 01:18:50#
Select * from Passwords where DateAdded = '06/05/2012 01:18:50'
Select * from Passwords where DateAdded = '2012/06/05 01:18:50'
Select * from Passwords where DateAdded = '2012/05/06 01:18:50'
Select * from Passwords where DateAdded like '2012/06/05 01:18:50'

The column DateAdded in my database is of type datetime and not nvchar.
I am new in SQL, what is wrong with this query?

A: Could you perhaps have fractional seconds stored?  Try this:
SELECT * FROM Passwords
    WHERE DateAdded BETWEEN '2012-05-06 01:18:50' AND '2012-05-06 01:18:51';

(I prefer that format of datetime literal because it's unambiguous, but yours should work as well.  Tsql will take almost anything you throw at it.


text:
Q: Nashorn Parser API on JDK 8 Looking for a Java/JDK API for parsing JavaScript (including Nashorn Extensions) I stumbled upon this Gist, which according to an inline comment requires JDK 9 to run. Is there a reliable way to accomplish the same on current or planned releases of JDK 8?

A: Nashorn Parser API ( http://openjdk.java.net/jeps/236 ) is jdk9 specific API. On jdk8 or jdk8 update, there is support for script parser function.
load("nashorn:parser.js");
and call "parse" function from script. This function returns a JSON object that represents AST of the script parsed.
See this sample: http://hg.openjdk.java.net/jdk8u/jdk8u-dev/nashorn/file/bfea11f8c8f2/samples/astviewer.js

A: While you can definitely use the parser via Nashorn's JavaScript, it's even nicer in Java to use it through the JAVA API
    import jdk.nashorn.api.scripting.ScriptUtils;
    import jdk.nashorn.internal.runtime.Context;
    import jdk.nashorn.internal.runtime.ECMAException;
    import jdk.nashorn.internal.runtime.ErrorManager;
    import jdk.nashorn.internal.runtime.options.Options;

    // set up the environment
    Options options = new Options("nashorn");
    options.set("anon.functions", true);
    options.set("parse.only", true);
    options.set("scripting", true);

    ErrorManager errors = new ErrorManager();
    Context contextm = new Context(options, errors, Thread.currentThread().getContextClassLoader());
    Context.setGlobal(contextm.createGlobal());

    // then for each bit of parsing
    String parseTree = ScriptUtils.parse(some_code_string, "nashorn", false);


text:
Q: I followed examples and I can't get facet_grid to work to split my data I am trying to represent my data as box plots and my data frame currently looks as  follows:
  V1    V2     V3         V4       V5
1  1 12.18 FEMALE A_ambiguus     Host
2  2 11.81 FEMALE A_ambiguus     Host
3  3 10.70   MALE A_ambiguus     Host
4  4 11.07   MALE A_ambiguus     Host
5  5  7.95 FEMALE  A_ameliae Parasite
6  6  7.42 FEMALE  A_ameliae Parasite

I run the following script and produce a figure with species (V4) as the x-axis, total length (V2) as the y-axis, ordered by V2, and colored by V5.
box <- ggplot(TL_sub, aes(x = V4, y = V2, group = V4)) +
  scale_y_continuous(name = "TL (mm)") +
  theme(axis.text.x=element_text(angle = 45, hjust = 1)) +
  geom_boxplot(aes(fill=Condition)) +
  aes(x=reorder(V4,V2),y=V2,label=TL)

box

The problem is that when I then run
box + facet_grid(. ~ V5)

The goal is to create two plots separated by sex (V3), but it does not work. I get the following error:
Error in combine_vars(data, params$plot_env, cols, drop = params$drop) :
  At least one layer must contain all variables used for facetting

I can provide the full data set if needed.
Any help would be great!
Thanks,
Steven M.

A: This works fine for me using your complete dataset.
TL_subset %>%
  ggplot(aes(reorder(Species, TL), TL)) +
    geom_boxplot(aes(fill = Condition)) +
    labs(x = "Species", y = "TL (mm)") +
    theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
    facet_grid(. ~ Sex)

A: Here is another example from your sample data
dataset<-data.frame(V2=c(12.18,11.81,10.70,11.07,7.95,7.42),
                    V3=c("FEMALE","FEMALE","Male","Male","FEMALE","FEMALE"),
                    V4=c("A_ambiguus","A_ambiguus","A_ambiguus","A_ambiguus","A_ameliae","A_ameliae"),
                    V5=c("Host","Host","Host",'Host',"Parasite","Parasite"))

library(ggplot2)

ggplot(data=dataset,aes(x=V4,y=V2)) + geom_boxplot(aes(fill=V5))+facet_grid(.~V3) +xlab("Species") +
  ylab("TL (mm)") + scale_fill_discrete(name="Condition")


text:
Q: VS2015 throw caught exception within DebuggerStepTrough? I just upgraded my VS2013, and the same code has a different behavior in debug mode.
In VS2013, I was having the debug breaking on exception I got.
Some of them that might happens and are handled were put in Try-catch block with a DebuggerStepTrough:
Example:
[DebuggerStepThrough]
private void DoSomething(){
    try{
        throw new InvalidOperationException();//Obviously in my case, it's not a throw exception here but a method
    }catch(InvalidOperationException){
        //log something & handling this case
    }
}

private void SomeEntryPoint(){
    DoSomething();//In VS2015 I got the debug breaking here. In VS2013 I don't
}

I was not having this behavior in VS2013. Is there a way to avoid it?
(I've the "Just My Code" enabled)

A: You are correct, the behavior you described is a result of a new performance improvement that was introduced in the Visual Studio 2015. The new feature  greatly reduces debugging overhead of processing clr exceptions thrown and caught within non-user modules (With Just My Code enabled).
Unfortunately, in an oversight, exceptions thrown and caught within functions with [DebuggerHidden], [DebuggerNonUserCode], and/or [DebuggerStepThrough] attributes are no longer treated as if they were thrown and caught within non-user code - the debugger essentially ignores those attributes with regard to exceptions in Visual Studio 2015 (Step filtering and Call stack filtering still work the same as they did in Visual Studio 2013).
The bad news is that there is no good way to restore the previous version's behavior for this scenario. There are 2 possible options:

*

*Target your application to use .net framework version < 4.0

*Refactor your code such that the functions/classes with those debugger attributes are in a different module and build that module optimized and/or without symbols.

The good news is that the Visual Studio debugger team has acknowledged the issue and will provide a workaround in the next update for Visual Studio 2015.
Update
The workaround for this issue is available in Visual Studio 2015 Update 2 and is detailed in the Using the DebuggerNonUserCode Attribute in Visual Studio 2015 blog post.
For those who just want to know what to do. Run the following in a command prompt:
reg add HKCU\Software\Microsoft\VisualStudio\14.0_Config\Debugger\Engine /v AlwaysEnableExceptionCallbacksOutsideMyCode /t REG_DWORD /d 1


text:
Q: Prolog infix operator definition I am recently learning about Prolog and I find the three types used for defining infix operators confusing.
What are the differences between xfx, xfy and yfx when specifying the type of an operator?
I have googled about the problem and haven't found anything useful.
I tried typing the following codes in Prolog:
:- op(500,yfx,is_alive).
is_alive(A,B) :- display([A,B]).
:- op(500,xfy,is_alive2).
is_alive2(A,B) :- display([A,B]).
:- op(500,xfx,is_alive3).
is_alive3(A,B) :- display([A,B]).

and the output:
| ?- 1 is_alive 2.
'.'(1,'.'(2,[]))

yes
| ?- 1 is_alive2 2.
'.'(1,'.'(2,[]))

yes
| ?- 1 is_alive3 2.
'.'(1,'.'(2,[]))

yes

The results showed no difference to me.

A: The 'type' of the operator controls associativity, e.g. whether expression "5 - 4 - 3" should be interpreted as "(5 - 4) - 3", which is known as left associativity or as "5 - (4 - 3)", which is right associativity.
If the minus operator should work as usually expected, is needs to be defined as 'yfx' which makes it left-associative. Other types as 'xfx and 'xfy' are variations on this. See more at http://www.cse.unsw.edu.au/~billw/cs9414/notes/prolog/op.html.

A: If your Prolog is ISO compliant, you can use write_canonical to analyze the effect of operators precedence and associativity. For instance
?- write_canonical(1+2*3).
+(1,*(2,3))
true.


text:
Q: Compare 2 integers in a do while loop Write a program that has the user enter integers between 0 and 9999 until the user enters some integer twice.  Program should to the console window how many distinct integers were entered.
How do i make the condition for the while loop? Or how do i compare if 2 integers entered by user in a do while loop are equal?
int n1,n2,count=0;
do {
     Scanner kb = new Scanner(System.in);
     System.out.print("Enter an int: ");
     n1= kb.nextInt();
     n2= kb.nextInt();
     count++;
} while(n1 != n2);
System.out.println("you entered " + count + "times");

This is why i tried

A: If you use set you could implement it as follows:
package com.company;

import java.util.HashSet;
import java.util.Scanner;
import java.util.Set;

public class Main {

    public static void main (String[]args) {

        Scanner in = new Scanner(System.in);
        Set<Integer> set = new HashSet<>();

        System.out.print("Enter your number: ");

        while (set.add(in.nextInt())){
            System.out.print("Enter next number: ");
        }

        System.out.println("There are " + set.size() + " distinct numbers entered into a set.");

    }
}

Set add() method returns true if set didn't contain added element and element was successfully added, or false if Set already contained entered element and the element wasn't added. So we ask user for numbers until he enters one that is already contained in a Set (he entered it before) then we break from the loop and print out the size of elements in the Set, which will be the number of distinct elements user entered.

A: Hope this helps
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//one class needs to have a main() method
public class Beta {
    // arguments are passed using the text field below this editor
    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        List<Integer> list = new ArrayList<Integer>();
        boolean doExist = false;
        int inputVal;
        do {
            System.out.print("\nEnter an Integer:");
            inputVal = kb.nextInt();
            doExist = list.contains(inputVal);
            if (!doExist) {
                list.add(inputVal);
            }

        } while (!doExist);

        System.out.println("The Number of Non Duplicate Integers:"+list.size());

    }
}


text:
Q: BeforeStep & AfterStep Annotation I've discovered an issue with the BeforeStep and AfterStep annotations in an ItemReader. I'm hoping someone can give me some clarification.
What Works:
I have an ItemReader implementation with the following methods:
 public class ReaderImpl implements ItemReader<String> {

      @BeforeStep
      public void beforeStep(StepExecution stepExecution) {
         //do before step processing...
      }

      @Override
      public String read() {
         //do read...
      }

      @AfterStep
      public ExitStatus afterStep(StepExecution stepExecution) {
         //do after step processing...
      }
 }

XML configuration:
<step id="step1">
    <tasklet>
        <chunk reader="readerImpl" writer="writer" commit-interval="100" />
    </tasklet>
</step>

<bean id="readerImpl" class="package.to.ReaderImpl" scope="step"/>

The above context works just fine, and the BeforeStep and AfterStep methods are being executed properly.
What Does NOT Work:
When I wrap my ReaderImpl with another bean, spring no longer executes the BeforeStep and AfterStep methods.
Example:
<step id="step1">
    <tasklet>
        <chunk reader="synchronizedReaderImpl" processor="processor" writer="writer" commit-interval="100" />
    </tasklet>
</step>

<bean id="synchronizedReaderImpl" class="org.springframework.batch.item.support.SynchronizedItemStreamReader" scope="step">
    <property name="delegate" ref="readerImpl" />
</bean>


text:
Q: How to determine the sequence of this graph? I can solve a Fourier series, but I don't know how to determine the sequence.
It is necessary to determine the values of the imaginary part of the Fourier coefficients of the following sequence: Graph in Picture.

A: You can define this as a periodic function with period $T$: $$f(t)=\dfrac{1}{T}t\quad\text{where}\,\,kT\lt t\le (k+1)T\quad\text{for}\,\,k\in\mathbb Z$$ since when $t=0$, $f(0)=0$ and when $t=T$, $f(T)=1.$