text:
Q: Best language to write linux services I want to create a crawler that scans one single web page and sends me an email in case something is wrong on the page (the page holds some webservers' status - Up/Down).
What would be the best language to write such a service in?
I've considered PHP or Python, but as they are interpreted languages (+PHP has a max time limit that a script runs), I don't think they're the best fit for this.
Also, C/C++ is not an option. I was thinking about Java, since it has Threading and I may need it, but I'm not sure.

A: Just use the language you are the most comfortable with. This kind of application is not CPU-/memory-bound.
You were mentioning Python. It is interpreted but I really don't see why this would be a problem. Youtube/Tornado/Django/etc. run Python. All the things that you will ever want for your specific purpose are already available as modules (daemonize, http, etc.).
PHP does not seem to be a good fit because of the limit that you mention, but also because you need apache (not completely true, but whatever). Still, it is possible.
Java would also perfectly fit. You can also daemonize your process and use existing libraries.
C/C++ seems a bit to much, but with the available libraries, you should be able to generate some working code very quickly.
As manatwork stressed, bash also just fits...
Well, you guessed it, my point here is that for this kind of application, there is no "best language". There is a family of language which already implement a http_client library of some sort and the others. Your CPU and memory are not limiting. You can just enjoy the language you want. :) But generally speaking, if this is your server, checking your web service is up should be checked internally (cron job, nagios, etc.). From your home you may just want to ping the server to see if the hardware is up and responding.

A: What I would do is write it in a scripting language such as Perl or Python and then scale up to Java if need to in search of features such as better concurrency management.  You always want to use the simplest tool for the job and scale up if you need to.  I am a huge fan of both languages and even though I know Java better, I would always try to solve any problem in Perl before resorting to Java.  Perl is a great candidate for offline workload processing, especially single-threaded.
Yet another question to be asked is the availability of APIs for the particular application, although nowadays there are APIs and web services for just about anything.  Still, I would bet there are more APIs for Java than Perl.  I was, however, recently disappointed not to be able to find a Java API for IBM Clear Case.  So for some version management stats and monitoring, I used shell invoking their CLI and passing data to Perl for further processing.


text:
Q: ¿Como incluir wp-config.php? Estoy realizando un script en php y necesito incluir el wp-config.php de Wordpress, lo estoy haciendo de esta forma:
include_once $_SERVER['DOCUMENT_ROOT'] . '/wp-config.php';

Cuando ejecuto el script manualmente funciona bien, pero cuando lo hago a traves de un cron no. Alguien sabe a que se debe esto?. Gracias!

redpajama_set_name: RedPajamaStackExchange


text:
Q: ERROR: Access is denied, when creating scheduled task Here is the error that I'm getting:
Create task command: '/cygdrive/c/Windows/System32/schtasks.exe /create /SC MINUTE /MO 10 /TN "Name of task" /TR "D:\path\to\exe /REQUIRED_PARAMETER" /RU System /F'
ERROR: Access is denied.

One of the tips I found was to run this:
cd\
cacls c:\windows\tasks /T /E /P Administrators:F
cacls c:\windows\tasks /T /E /P SYSTEM:F

A few other things:

*

*I confirmed that the Task Scheduler service is running

*The Event Viewer didn't show anything specific to the task creation

*I've captured and filtered events in Procmon, where no events with the results ACCESS DENIED could be found.

*The user is part of a group (ie Users) having read and execute on schedtasks.exe

*The user has full access to c:\Windows\tasks manually provided

*The user owns the folder of the executable targetted with the task

Edit #1

*

*User creating the task is not part of Administrators. When I put him into Administrators, it works. However, we believe that he shouldn't be in Administrators.


text:
Q: How to install kde-plasma with lightdm instead of kdm I like lightdm and especially its webkit-greeter a lot. Is there a way to install kde without installing kdm and using lightdm instead?
I have tried everything from installing kdm and then remove it to dpkg-reconfigure kdm and lightdm to lightdm is the default. but I always got kdm when I boot up or a broken system, when I remove it completely.
Does anyone know how to get kde together with lightdm?
By the way. I am doing this on a minimal installation.

A: Since your initial setup is a minimal installation, I'll take Ubuntu 14.04.1 Server as the base OS.
After installation, all that you get is a command-line prompt without lightdm nor a desktop environment.
Open a user session and type the following commands:
sudo apt-get update
sudo apt-get install lightdm-webkit-greeter --no-install-recommends
sudo apt-get install lightdm --no-install-recommends
sudo apt-get install kubuntu-desktop --no-install-recommends
sudo reboot

Now the lightdm greeter will open a kde plasma desktop:

A: You can change the default greeter by changing the configuration file under the [SeatDefaults] section, to state:
/etc/lightdm/lightdm.conf

[SeatDefaults]
...
greeter-session=lightdm-yourgreeter-greeter

Enabling lightdm
Make sure to enable lightdm.service using systemctl so lightDM will be started at boot.
Command line tool
Lightdm offers a command line tool, dm-tool which can be used to lock the current seat, switch sessions, etc, which is useful with  window managers and for testing. To see a list of available commands, execute:
dm-tool --help


text:
Q: Getting error in flutter dart application. The operator '[]' isn't defined for the type 'DocumentSnapshot'. Try defining the operator '[]' This is my code. I tried using data() instead but that didn't work either.
  Future getUserInterests(userId) async {
    User currentUser = User();

    await _firestore.collection('users').doc(userId).get().then((user) {
      currentUser.name = user['name'];
      currentUser.photo = user['photoUrl'];
      currentUser.gender = user['gender'];
      currentUser.interestedIn = user['interestedIn'];
    });
    return currentUser;
  }

A: You will need to call data() in order to get to the data inside the DocumentSnapshot.
Map<String, dynamic> data = user.data();
currentUser.name = data['name'];

A: what firebase package version are you running? The new version changed the operator [] and getter data for the method get() and data() respectively
Future getUserInterests(userId) async {
User currentUser = User();

await _firestore.collection('users').doc(userId).get().then((user) {
  Map<String, dynamic> doc = user.data();
  currentUser.name = doc['name'];
  currentUser.photo = doc['photoUrl'];
  currentUser.gender = doc['gender'];
  currentUser.interestedIn = doc['interestedIn'];
});
return currentUser;
}

A: Well, you are treating the user variable as if it was a Map<String, dynamic> (using the [] accessor notation), but the error tells you that it is an instance of DocumentSnapshot.
Not sure what field DocumentSnapshot has (what library are you using ?). You should check the documentation of whichever library you are using to find out how to access the fields you need.


text:
Q: printing inside switch , c++ , but outside of cases? #include <stdio.h>
#include <windows.h>
#include <iostream>
using namespace std;

int main(){

    int n  ;
    cout << "insert n " <<endl ;
    cin >> n ;

    switch(n){
              cout <<"inside switch " <<endl ;
              case 2 :
               cout << "this is 2 " <<endl ;
               break ;
              case 5 :
                cout << "this is 5 " <<endl ;
                break ;
              default :
                cout << "this is default - any number" <<endl ;
                break ;

              }

    return 0 ;

    }

Does switch structure print the cout before cases?
It does not , i checked it, is this a rule that inside switch only stuff inside cases will be printed?

A: A switch is essentially just a computed goto; the individual cases are essentially just labels.
In your example code, the switch will always jump past the first cout statement.


text:
Q: Obtain location using service(background) and update gui at regular intervals I am trying to run a service in the background. Where location is obtained at regular interval and the activity text views are updated whether the app is in E background or foreground. Any pointers or tutorials you guys aware of the? Maybe working examples? I searched a lot and couldn't find something concrete
Thank you
Note: Battery consumption is not an issue for this app

A: My first recommendation would be not to run location services like that, battery consumption would be a really bad issue, to get the location on regular intervals you can either use the Alarm Manager or TimerTask depending on what fits your needs, sorry I cant be more specific but I'm on my phone, hope it helps though.

A: I did a small blog post about Android location services that should help. It's not service based but it will provide you live location updates in the activity whilst running. Once your activity is paused there is little point in the service providing updates any way and it will hammer your battery as @aehs29 mentioned.
Example code in the blog too: http://www.scotthelme.co.uk/blog/android-location-services/


text:
Q: When to use Conservation of Energy vs Conservation of Momentum I am confused as to when each should be used to solve problems.I am not looking for the answer to this question, but I will include it here so you have all the information about what I am asking about.

A 15.0 kg block is attached to a very light horizontal spring of force
  constant 400.0 N/m and is resting on a frictionless horizontal table.
  (See (Figure 1) .) Suddenly it is struck by a 3.00 kg stone traveling
  horizontally at 8.00 m/s to the right, whereupon the stone rebounds at
  2.00 m/s horizontally to the left. Find the maximum distance that the block will compress the spring after the collision.

I see that the idea suggested here (at Yahoo Answers) is to use conservation of momentum to solve this problem. But I wanted to solve using conservation of energy in the following way:
$K.E =\frac{mv^2}{2}$
$Spring-P.E=\frac{kx^2}{2}$
$KE_i = KE_f + PE_f$
$KE_i - KE_f = PE_f$
Solving the equations, you get
$x = 0.670m$
The correct answer given is 0.387m.

A: When to use which law
Your assumption that conservation of energy (considering only kinetic energy) works while dealing with the collision in the above question is not correct.
Conservation of energy (kinetic energy) doesn't appear to work in all kinds of collision. Some of the initial kinetic energy of the bodies are lost as heat and/or part of it is stored in the form of potential energy of the bodies (deformed body). These kind of collisions are called inelastic collisions.
Hence, direct application of conservation of energy with just kinetic energy terms is not possible. In these cases, the problem cannot be solved with just conservation of momentum. You need some experimental input (usually the coefficient of restitution is given).
However, there are cases where conservation of energy (initial kinetic energy = final kinetic energy) is applicable. Such collisions are called elastic collisions.
Conservation of momentum is always valid and safe whereas conservation of energy requires all forms of energy including heat, sound, light, etc to be considered (which ever stated)
Solution to the given problem
In the above problem, the final velocity of the block is already given. By using the conservation of momentum, you can calculate the final velocity of the block.
Initial Momentum of the stone= $mv$ = $24$ $kg.ms^{-2}$
Applying the law of conservation of momentum,
$24 = m_{stone}v_{final-stone} + m_{block}v_{block-final}$
Substituting the given values in the equation, you get the final velocity of the block to be $2 ms^{-2}$.
Before the collision, the block was at its mean position. After the collision the block will begin to oscillate with the same mean position.
The total energy of the system is equal to the kinetic energy supplied by the moving stone. When the block reaches its extreme position, all the energy will exist in the form of potential energy of the spring. Therefore, by applying the law of conservation of energy,
$\frac{mv^2}{2} = \frac{kx^2}{2}$
You get x to be $\sqrt{\frac{3}{20}}$

A: There is no general rule about which principle to apply. Both principles are always true. However, whether both or one or neither can be used in a particular problem depends on what information is available and what is required to be found.
The usual advice still holds good : Make a list of the knowns, the unknowns, and what principles or equations might apply. Then look for the easiest or most reliable method of solution. There is no magic formula, no substitute for methodical thinking and intuition about what works best, both of which come from getting plenty of practice.
There are 2 parts to the given problem. As it happens, the 1st can only be solved by Conservation of Momentum and the 2nd only by Conservation of Energy.
Collision between the Stone and Block
You do not know (and cannot presume) that this is an elastic collision (ie one in which Kinetic Energy is conserved), so you cannot apply Conservation of Energy. Total energy is conserved, but there is no way of knowing how much of the initial KE is dissipated as heat or sound or permanent deformation of stone or block.
You can apply Conservation of Momentum here because you are told the 2 initial momenta and the final momentum of the stone. There is only 1 momentum left to find, so the 1 equation for Conservation of Momentum is enough to find it.
Note: If you had been told that the collision is elastic (ie KE is conserved) but not told the recoil velocity of the stone, you could use both conservation principles to find the 2 unknowns - viz. the final velocities of the stone and block.
Compression of the Spring
Here you know the initial KE (that of the 15kg block) and elastic PE (zero because the spring is not compressed). You also know the final KE (zero). The only unknown is the final elastic PE, so this can be found from the equation for Conservation of Energy.  From the latter you can calculate the compression of the spring.
Even if there is friction present then provided you are told the coefficient of friction you can calculate how much work is done against friction and include that in the energy balance equation. The same applies to other forms of energy transfer also.
Conservation of Momentum is not useful here because the compression in the spring is not related to its momentum.


text:
Q: Filtering Date in where clause of EntityDataSource I have a EntityDataSource and I have to filter all items older 30 days.
my approach on my MSSQL database:
protected void EntityDataSource1_Selecting(object sender, EntityDataSourceSelectingEventArgs e)
{
    EntityDataSource1.WhereParameters.Clear();
    EntityDataSource1.Where = "DATEDIFF(day, GETDATE(), it.CreateDate) < 30" ;
}

gives the error: DATEDIFF cannot be resolved into a valid type or function

A: You need call SqlServer.DATEDIFF(), use this:
EntityDataSource1.Where = "SqlServer.DATEDIFF(day, GETDATE(), it.CreateDate) < 30" ;

instead
EntityDataSource1.Where = "DATEDIFF(day, GETDATE(), it.CreateDate) < 30" ;

Here you find similar question but with DATEADD function


text:
Q: Method Illuminate\Support\Collection::find does not exist Edit function:
public function editCheck($id, LanguagesRequest $request)
{
    try{
        $language = language::select()->find($id);
        $language::update($request->except('_token'));
        return redirect()->route('admin.languages')->with(['sucess' => 'edit done by sucsses']);
    } catch(Exception $ex) {
        return redirect()->route('admin.addlanguages');
    }
}

and model or  select function
public function scopeselect()
{
    return  DB::table('languages')->select('id', 'name', 'abbr', 'direction', 'locale', 'active')->get();
}

A: This code is very inefficient, you're selecting every record in the table, then filtering it to find your ID.  This will be slow, and is entirely unnecessary.  Neither are you using any of the Laravel features specifically designed to make this kind of thing easy.
Assuming you have a model named Language, if you use route model binding, thing are much simpler:

*

*Make sure your route uses the word language as the placeholder, eg maybe your route for this method looks like:
Route::post('/languages/check/{language}', 'LanguagesController@editCheck');

*Type hint the language as a parameter in the method:
public function editCheck(Language $language, LanguagesRequest $request) {

*Done - $language is now the single model you were afer, you can use it without any selecting, filtering, finding - Laravel has done it all for you.
public function editCheck(Language $language, LanguagesRequest $request) {
    // $language is now your model, ready to work with
    $language::update($request->except('_token'));
    // ... etc

If you can't use route model binding, or don't want to, you can still make this much simpler and more efficient.  Again assuming you have a Language model:
public function editCheck($id, LanguagesRequest $request) {
    $language = Language::find($id);
    $language::update($request->except('_token'));
    // ... etc

Delete the scopeselect() method, you should never be selecting every record in your table.  Additionally the word select is surely a reserved word, trying to use a function named that is bound to cause problems.

A: scopeselect() is returning a Collection, which you're then trying to filter with ->find() which is a method on QueryBuilders.
You can instead filter with ->filter() or ->first() as suggested in this answer
$language = language::select()->first(function($item) use ($id) {
    return $item->id == $id;
});

That being said, you should really find a different way to do all of this entirely. You should be using $id with Eloquent to get the object you're after in the first instance.


text:
Q: Form doesn't submit all fields I have a pretty huge form which I am able to extend dynamically with JavaScript. In this form I am having different DataSets with about 50 fields to submit each. When I submit the form I am running through a for loop from 0 to 100 to check which fields are set. So I create the HTML like this:
<form id = "formUpdate" role="form" action="index.php?action=update" method="post">

             Head1
             Head2
             Head3
             Head4
             Head5
             Head6
             ...

                    <?php
                        for ($i=0;$i<$dataSets;$i++){  ?>

                                <?php echo $test[$i]['1']; ?>
                                 <input required class="form-control formsUser" form="formUpdate" name="fieldA<?php echo $test[$i]['2']; ?>" value=""></input>
                                 <textarea style="height:34px" class="form-control formsUser" form="formUpdate" name="fieldB<?php echo $test[$i]['3'];?>" required></textarea>
                                 <input class="form-control formsUser" form="formUpdate" name="fieldC<?php echo $test[$i]['4']; ?>" required value=""></input>
                                 <input class="form-control formsUser" form="formUpdate" name="fieldD<?php echo $test[$i]['5']; ?>" required value=""></input>
                                 <input class="form-control formsUser" form="formUpdate" name="fieldE<?php echo $test[$i]['6']; ?>" value=""></input>

                   <?php } ?>

   <button class="btn btn-success" form="formUpdate" type="submit"> Submit </button>
</form>

PHP:
public function update(){
     print_r($_REQUEST);
     for ($i=0;$i<100;$i++){
          $string = "fieldA".$i;

          if (isset($_POST[$string])){
              // set the other _POSTS
          }
          else {
              //do something different
          }
      }
}

But this works only for the first 10 Datasets. When I call print_r($_REQUEST); it also just contains the content of the fields of the first 10 Datasets. I read about the limit of max_input_vars in the php.ini and increased this value, but nothing has changed. Besides I shouldn't reach the default value of 1,000 with my data. I also tried changing the value of max_input_nesting_level, memory_limit and post_max_size.

A: OMG. Got the Problem. I am using DataTables and when submitting the form, the table is redrawed showing the first 10 Datasets only...sorry for that guys and thanks for your help :)


text:
Q: Determine the closest point in a subspace to a given point Let $S$ be the subspace of $\mathbb{R}^4$ given by the intersection of the planes
$$P_1 = \{(x,y,z,w)| x + 3y -2z + w =0\}$$
$$P_2 = \{(x,y,z,w)| 2x - 2y + z - w =0\}$$
$i)$ Find an orthogonal basis of $S$ and $ii)$ determine the Point in $S$ which is closest to the point $P (1,2,2,1)$ with respect to the standard norm given by the dot product.
For the first part of the question, I found a basis and then made it orthogonal with the standard Gram-Schmidt Process,
resulting in a basis of $\left[\begin{array}{c}
-\frac{5}{3} \\
1 \\
0 \\
0
\end{array}\right]$ , $\left[\begin{array}{c}
\frac{9}{34} \\
\frac{15}{34} \\
1 \\
0
\end{array}\right]$, $\left[\begin{array}{c}
-\frac{6}{43} \\
-\frac{10}{43} \\
\frac{6}{43} \\
1
\end{array}\right]$.
However, I am unsure how to proceed with the second part of the question, I just cant intuitively understand what it is asking for, is it perhaps the orthogonal Projection of P onto S?

A: Actually, none of those three vectors belongs to $S$. Besides, since $\dim S=2$, $S$ cannot possibly have a basis consisting of $3$ vectors.
A basis of $S$ is $\{v_1,v_2\}$, with $v_1=(1,0,3,5)$ and $v_2=(0,1,1,-1)\}$. It is not orthogonal, but you can get an orthogonal basis form it: $\{v_1,v_3\}$, where$$v_3=v_2-\frac1{\|v_1\|^2}\langle v_2,v_1\rangle v_1=\left(\frac2{35},1,\frac{41}{35},-\frac57\right).$$Now, the point of $S$ closest to $(1,2,2,1)$ is$$\frac1{\|v_1\|^2}\langle(1,2,2,1),v_1\rangle v_1+\frac1{\|v_3\|^2}\langle(1,2,2,1),v_3\rangle v_3=\left(\frac{42}{101},\frac{129}{101},\frac{255}{101},\frac{81}{101}\right).$$


text:
Q: Is it possible to use a custom work item type on the kanban board in azure devops? My organization uses an inherited process based off of the Agile process.  However I created a custom work item type called Product Backlog Item because I liked this naming convention from the Scrum template and I use it for different purposes than User Stories.  Is there a way to use these on the Boards part of DevOps?
These are the only options, and I didn't see anywhere to add custom work item types to this section.
In the settings this is all that I see as well.

A: You can add your custom work items in process. Here are the steps:

*

*Create a new work item type.

*Add top level portfolio backlog.

*Select your custom work item type and set it as default.

*Select Product Backlog Item in Boards settings.

*You can use Product Backlog Item on the Boards now.

Another way is edit Requirement backlog. You can change the name and select default work item type here.


text:
Q: Dividing canvas to regions, then attracting nearby items to the nearest region? I'm creating GUI using python tkinter to visualize Road Scenarios (the main vehicle & close by vehicles). I draw in the canvas lines to give road top view (as the Picture below).
The user can insert a rectangle (vehicle) then move it freely on the canvas.
What I want is: after the user moves the rectangle to where ever he wants, the y coordination of the rectangle will relocate to the nearest lane, to have a nice looking png at the end.
My thought about it:

*

*Divide the canvas to regions (each Region represent a lane)

*Create a function which knows when the rectangle finished moving, then modify the y coordination of it to the nearest Region (lane).

Not sure how to apply this in Code though. Any useful canvas functions or another approach are much appreciated.

A: The approach I mentioned at the question worked for me.

*

*A list identifing the y-axis sides of each Region was created.

*After creating the items needed, they all share a common Tag.

*Choose which part of the items you want to consider the original Point (which will be used later as the item's current location). Canvas.bboc(CURRENT) can be sufficient to do that.

*Detect when does the item enter a Region, by comparing if the item's current Location is within the boundaries of a Region.

*Use Canvas.coords() or Cancas.move() methods to move the items at the middle of the regoin they have entered.


text:
Q: Detect if word at selectionStart is a URL I am trying to detect the full word the user is tapping when they focus in on an HTML input element, and then see if it is a URL.  I am using the following method:
let el = this.reminderInput.nativeElement
var fullText = el.value;
console.log(fullText) //logs 'test http://www.google.com'

var split =  el.selectionStart
console.log(split) //logs 18
var a = fullText.substring(0, split).match(/[A-Za-z]*$/)[0]
var b = fullText.substring(split).match(/^[A-Za-z]*/)[0]

I have the following string in my input element:
test http://www.google.com

In this example, if the user clicked in between the o's in google, a will print out go and b will print out gle.
I'd like for a to print out http://www.go and b to print out ogle.com, and thus, when I combing a + b, I'd get the full string http://www.google.com and check if it is a valid URL, and if so, open it in another tab.
How do I update my regex to only detect if the word is not a whitespace/return so I can get the full word of the selection and check if it is a URL?

A: Here's a general idea: match all non-whitespace chunks but preserve indexes of each match. Then iterate over the matches looking for the word that best fits target.selectionStart. From there, it's a known problem to detect if that word is a URL.

const findWordUnderCursor = e => {
  const words = [];

  for (let m, re = /\S+/g; m = re.exec(e.target.value);) {
    words.push([m[0], m.index]);
  }

  const cursor = e.target.selectionStart;
  const target = words.find(([word, i]) => i + word.length >= cursor);
  document.querySelector("#output").innerText = `{${target ? target[0] : ""}}`;
};

const inpElem = document.querySelector("input");
inpElem.addEventListener("keyup", findWordUnderCursor);
inpElem.addEventListener("click", findWordUnderCursor);
inpElem.addEventListener("blur", e => {
  document.querySelector("#output").innerText = "";
});
* { font-family: monospace; }
<input value="foo test http://www.google.com bar" size=40>

If you're using a framework (it looks like you are), replace the DOM interaction with your framework's calls.
If the idea of matching and iterating the entire input seems non-performant, you can always go the pointer route and walk forwards and backward from selection start until you hit whitespace on either end:

const findWordUnderCursor = e => {
  let start = e.target.selectionStart;
  let end = start;
  const val = e.target.value;

  for (; start > 0 && /\S/.test(val[start-1]); start--);
  for (; end < val.length && /\S/.test(val[end]); end++);

  document.querySelector("#output").innerText = `{${val.slice(start, end)}}`;
};

const inpElem = document.querySelector("input");
inpElem.addEventListener("keyup", findWordUnderCursor);
inpElem.addEventListener("click", findWordUnderCursor);
inpElem.addEventListener("blur", e => {
  document.querySelector("#output").innerText = "";
});
* { font-family: monospace; }
<input value="foo test http://www.google.com bar" size=40>

A: The below regex should work for any URL and can match all domains too.
let el = this.reminderInput.nativeElement
var fullText = el.value;
console.log(fullText) //logs 'test http://www.google.com'

var split =  el.selectionStart
console.log(split) //logs 18
var a = fullText.substring(0, split).match(/(http|https):\/\/(www.)?([a-zA-Z0-9]+)/g)[0] //logs http://www.go
var b = fullText.substring(split).match(/^[a-zA-Z0-9]*.[a-z]{2,9}/)[0] //logs ogle.com


text:
Q: Akka.net VS Azure Service Fabric I am learning about Akka.net and have heard about service fabric from Azure. As far as I know, they both are used for building microservices.
Apart from the difference in the scaling model, what else can be the difference between Akka.net and Azure Service fabric.
I see that the conclusion mentioned in the following blog gives hint to using Akka.net with persistent storage from Azure.
Can the real-time implementation developer's share their experiences in these technologies.
I find many use cases that can be solved, but one simple one would be a user import process, which typically contains the following steps,

*

*Create user,

*Add roles to user

*Send welcome email to the new user

*Manage user based metering for the company to which the user is being added to.

I see that all the above steps qualified to contain an actor on its own to perform the activities. Kindly comment on the approach that I have understood.


text:
Q: Unable to determine the identity of domain using System.IO.Packaging I am getting "Unable to determine the identity of domain" when using System.IO.Packaging through COM Interop, there are a few articles describing why this is happening and the solution is to run the offending function in its own AppDomain.
So I took the sample code, which looks like the below but I still get the error, I am wondering what i am doing wrong and also, with VS 2010 it says AddAssembly and AddHost are obsolete - I wonder if that means they are no longer implemented, but if thats the case I dont really understand how to use the new methods (AddAssemblyEvidence and AddHostEvidence)??
 AppDomainSetup setup = new AppDomainSetup();
 setup.ApplicationBase = AppDomain.CurrentDomain.BaseDirectory;

 Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence);
 evidence.AddAssembly(Assembly.GetExecutingAssembly().FullName);
 evidence.AddHost(new Zone(SecurityZone.MyComputer));

 AppDomain domain = AppDomain.CreateDomain("BlobPackage", evidence, setup);

 BlobPackage blob_interal = (BlobPackage)domain.CreateInstanceAndUnwrap(typeof(BlobPackage).Assembly.FullName, typeof(BlobPackage).FullName);

 blob_interal.pack(FilePath, RootPath, m_source_files); <-- STILL FAILS

 AppDomain.Unload(domain);

A: I solved this one myself, I forgot to inherit my class from MarshalByRefObject.
Its a bit stupid, it allows you to create an instance and call it except its still running in the default domain, you would think it would throw an exception or something, anyway by marking the class as [Serializable()] and deriving from MarshalByRefObject fixes it.


text:
Q: Cypress-image-snapshot not working in CircleCI I am using cypress-image-snapshot plugin as per the document :
https://github.com/jaredpalmer/cypress-image-snapshot
But they are not working on circleCI:
Locally if there is any difference the tests throw error and the difference image is added to the diff_output folder
When running the same tests on CI they dont throw any error even when there is a difference
Tried adding --env failOnSnapshotDiff=true and also --env updateSnapshots=false, nothing helping me.
Can some guide me here as this is very important for my release and i am stuck.


text:
Q: Can I run a function when uploading a new picture to Instagram? Is there a way to launch a function on my server every time I upload a photo on Instragram via API?
I would like to create a page on my CMS automatically every time I upload a photo.

A: You can use Real-time Photo Updates
Or you want publish photo via API ? If yes, it's not possible via official API.


text:
Q: injectivity of the function $f: \quad \mathbb{R}^2_+ \longrightarrow \mathbb{R}^2 \quad : (x,y)\quad \longmapsto \ (x^2-y^2, 2xy)$ Consider the function:
$$f: \quad \mathbb{R}^2_+ \ \longrightarrow \ \mathbb{R}^2  \quad : \quad (x,y) \ \longmapsto \ (x^2-y^2, 2xy)$$
I had to show that this function is injective. According to the exercise, I had to prove the identity:
$$ (\tilde{x}^2 + y^2)(\tilde{y}^2-y^2) = 0 \qquad \ \ \ \text{if} \ \ \  \ \ f(x,y) \ = \ f(\tilde{x},\tilde{y})$$
Maybe this this very easy, but I didn't know how to show this, and I didn't know how to establish injectivity by this either. I haven't produced anything fruitful. Could you please help me?

A: $$(a,b)=(x^2-y^2,2xy)\iff(x,y)=\left(\sqrt{\frac{a}2+\frac12\sqrt{a^2+b^2}},\sqrt{-\frac{a}2+\frac12\sqrt{a^2+b^2}}\right)$$

A: If $f(x,y)=f(\tilde x, \tilde y)$ then $$(\tilde x^2 + y^2)(\tilde y^2 - y^2) = \tilde x^2\tilde y^2 - y^4 + y^2(\tilde y^2 - \tilde x^2) = x^2y^2 - y^4 + y^2(y^2 - x^2) = 0$$
Also if this is zero then one of the brackets is zero. Then either $\tilde x = y = 0$ or $|\tilde y | = |y|$ and in either case you can work out the rest.

A: $g:\left\{ z\in\mathbb{C}\mid\text{Re }z,\text{Im }z>0\right\} \rightarrow\mathbb{C}$
defined by $z\mapsto z^{2}$ is injective.
So the corresponding $f:\mathbb{R}_{+}^{2}\rightarrow\mathbb{R}^{2}$
defined by $\left(x,y\right)\mapsto\left(x^{2}-y^{2},2xy\right)$
is injective.


text:
Q: How can I access a shared mailbox through Graph explorer My outlook account at work is a member of a group called GraphTest which has email address GraphTest@companyname.net.
I'm trying to use the graph explorer to access mail in that group's inbox.
When I run the query https://graph.microsoft.com/v1.0/users/graphtest@companyname.net/messages I get the error message

Group Shard is used in non-Groups URI.

When I replace graphtest@companyname.net with my own email it works. Also I've consented to the permissions Mail.Read and Mail.Read.Shared.
What does this error message mean, and how can I fix it?

A:
https://graph.microsoft.com/v1.0/users/graphtest@companyname.net/messages

Firstly the above API call which you used is invalid because you are giving a group email id to get it from user like /users/graphtest@companyname.net/messages which is invalid.
Even there is no mention in documentation that we can use something like /groups/graphtest@companyname.net/messages.
You can get some details from List Conversations using something like this.
https://graph.microsoft.com/v1.0/groups/{group_id_only}/conversations


text:
Q: php currency take I need to know how to take

10.25 and turn it to 1025

basically it needs to remove full stop from any number for e.g.
1500.25 it should be 150025

A: $number = str_replace('.','',$number);

A: if the currency is a float: multiply with 100 (and cast the result to int).
$currency = 10.25;
$number = (int)($currency * 100); //1025

note that this solution will only get the first two decimals saved - if you have a number like 10.123, the 3 will simply be cut off without rounding.

A: Floating-point arithmetic is by it's definition not exact. Therefore it's worthwhile to NOT cast the value to a float if it's a string, and avoid casting it into a string if it's a float.
Here's a function which takes care to check the value type:
function toCents($value) {
  // Strings with a dot is specially handled
  // so they won't be converted to float
  if (is_string($value) && strpos($value, '.') !== false) {
    list($integer, $decimals) = explode('.', $value);
    $decimals = (int) substr($decimals . '00', 0, 2);
    return ((int) $integer) * 100 + $decimals;

  // float values are rounded to avoid errors when a value
  // like ".10" is saved as ".099"
  } elseif (is_float($value) {
    return round($value * 100);

  // Other values are strings or integers, which are cast
  // to int and multiplied directly.
  } else {
    return ((int) $value) * 100;
  }
}

A: if you want replace one character only, use strtr instead str_replace
$number = str_replace('.','',$number);

and
$number = strtr($number, array('.', ''));

same output but strtr is better.


text:
Q: Product Sorting with layered navigation I have products listed in a catagory and able to sort with layered navigation.  However, I wanted to add a table prior to the products to better describe each one.  See link below to see:
http://www.oxidationtech.com/products/ozone-generators.html
What I want, is when a selection from the layered navigation on the left is selected, the table should disappear as it is no longer necessary.  I would prefer after a selection to narrow-down from layered navigation is selected that only the selected products in that range appear.
Any ideas how I can have both?  Table on landing page + usable layered navigaion?

A: In your category view template file, or wherever else you are displaying the table, you can do this
<?php if (Mage::getSingleton('catalog/layer')->getState()->getFilters()): ?>
    ... DISPLAY TABLE ...
<?php endif; ?>

I didn't test whether the filters also include the page number, so you may want to test that out.


text:
Q: how to left justify text in quote environment with the rest of the text in justified format I need to left justify text in quote environment. The rest of the text is justified to both margins.
I just need to raggedright the text inside the quote environment.
I'm using this
\usepackage{etoolbox}
\patchcmd{\quote}{\rightmargin}{\leftmargin 0.5in \rightmargin 0}{}{}

to change the margins.
Thanks in advance

A: The patch you need is the following:
\AtBeginEnvironment{quote}{\raggedright}

so that each time a quote environment starts, the text is typeset ragged right.
MWE:
\documentclass{article}

\usepackage{lipsum} % just for the example

\usepackage{etoolbox}
\AtBeginEnvironment{quote}{\raggedright}

\begin{document}
\lipsum[2]

\begin{quote}
  \lipsum[1]
\end{quote}

\lipsum[2]
\end{document}

Output:

A: Use the quoting environment, which is easily customisable:
\documentclass{book}
\usepackage[utf8]{inputenc}%
\usepackage[T1]{fontenc} %
\usepackage{erewhon} %
 \usepackage{quoting} %
\usepackage{lipsum}
\quotingsetup{font={itshape, raggedright, noindent}, leftmargin=0.5in, rightmargin=0in, begintext=', endtext='}

 \begin{document}

 \lipsum[2]
\begin{quoting}
Sed feugiat. Cum sociis natoque penatibus et magnis dis parturient
 montes, nascetur ridiculus mus. Ut pellentesque augue sed urna.
 Vestibulum diam eros, fringilla et, consectetuer eu, nonummy id,
 sapien. Nullam at lectus. In sagittis ultrices mauris. Curabitur
 malesuada erat sit amet massa. Fusce blandit. Aliquam erat volutpat.
 Aliquam euismod. Aenean vel lectus. Nunc imperdiet justo nec dolor.
\end{quoting}
\lipsum[3]

\end{document}


text:
Q: How to install OmniXml for Delphi Xe2/ OExport XLSX/ODS native Delphi/Lazarus import/export library I know this might be a simple question but i searched the internet and couldn't find an answer. I am trying to install OExport - XLSX/ODS native Delphi/Lazarus import/export library http://www.kluug.at/xlsx-ods-delphi.php , but in order to install it I need to have prior installed OmniXMl. So I have downloaded from here http://www.kluug.at/xlsx-ods-delphi.php as well. I have extracted the archive and I opened from the dpk folder the OmniXml_Dxe2 package. And in the Delphi IDE i know that i need to right click on the project name (respectively OmniXml_Dxe2.bpl ) and then click install; but install option is missing (attached a picture); Then I thought that i need to run the project instead. So I when I run the project an error appears "Cannot run project unless a host application is defined. Use the Run|Parameters..dialog..box"
Could somebody please tell me where I am doing something wrong and what should I do in order to install OmniXml

A: The error you are seeing is because you are making a DLL or package, and they cannot be run. They only run when a host application is loading them, and you can use the Run/Parameters dialog to set this. But I suggest that you are really looking for the "Install" option for the project to load it as a package into Delphi.


text:
Q: Html and javascript extrating Id I'm having trouble understanding how to use javascript and html together. I have managed to access the file ok and get id's from the file. But I can only access an id when the id's defined before the id I want has been used. Is there a way to get around this problem?
<!DOCTYPE html>

<link href="site.css" rel="stylesheet">

<title>This is my website</title>

Here is my HTML code.
document.getElementById("foot01").innerHTML = "©  " + new Date().getFullYear() + " Dane. All rights reserved.";
document.getElementById("head01").innerHTML = "Dane & Co";

document.getElementById("HouseName01").innerHTML = "House 1 name";
document.getElementById("HouseAdress01").innerHTML = "House 1 adress";
document.getElementById("HouseImage01").setAttribute("src", "C:/Users/currys/Pictures/House01.jpg");

document.getElementById("HouseName02").innerHTML = "House 2 name";
document.getElementById("HouseAdress02").innerHTML = "House 2 adress";

document.getElementById("HouseName03").innerHTML = "House 3 name";
document.getElementById("HouseAdress03").innerHTML = "House 3 adress";

document.getElementById("HouseName04").innerHTML = "House 4 name";
document.getElementById("HouseAdress04").innerHTML = "House 4 adress";

document.getElementById("HouseName05").innerHTML = "House 5 name";
document.getElementById("HouseAdress05").innerHTML = "House 5 adress";

document.getElementById("HouseName06").innerHTML = "House 6 name";
document.getElementById("HouseAdress06").innerHTML = "House 6 adress";

document.getElementById("tempVar").innerHTML = "House22";

Here is my javascript code. Sorry for not adding the code first time.

A: If you want to get the HTML element whose id is "tempVar" before to be defined, You can not do that:
`document.getElementById(<id>)` method is to get existing element identified by its id.

If you want to create a HTML element using js:
var newElement = document.createElement("p"); //i.e.

var node = document.createTextNode("House22");
newElement.appendChild(node);

And later you can add this element newElement  inside the DOM.


text:
Q: MKDirectionsRequest returns wrong coordinates I'm trying to display a route between to points on a map. I'm using Mapbox, so tell me if I'm doing it the wrong way, but I'm using MKDirectionsRequest in order to get all the MKMapPoint I need to display the route with the Mapbox class RMPolylineAnnotation. However MkDirectionsRequest returns unusable coordinates:
   <__NSArrayM 0x7fd88bfa6810>(<+43224681.35381404,+104172185.41666411>
   +/- 0.00m (speed -1.00 mps / course    -1.00) @ 4/28/15, 10:31:51 AM Central European Summer Time, ...)

When I print MKDirectionsRequest.source object before calling directions API (the coordinates are correct):
<MKMapItem: 0x7fca6ad48de0> {
    isCurrentLocation = 0;
    name = "Unknown Location";
    placemark = "<+37.33233141,-122.03121860> +/- 0.00m, region CLCircularRegion (identifier:'<+37.33233141,-122.03121860> radius 0.00', center:<+37.33233141,-122.03121860>, radius:0.00m)";
}

Here is the code:
MKDirectionsRequest *directionsRequest = [[MKDirectionsRequest alloc] init];
        MKPlacemark *sourcePlacemark = [[MKPlacemark alloc] initWithCoordinate:_userCoordinates
                                                             addressDictionary:nil];
        MKPlacemark *destinationPlacemark = [[MKPlacemark alloc] initWithCoordinate:carCoordinates
                                                                  addressDictionary:nil];
        directionsRequest.source = [[MKMapItem alloc] initWithPlacemark:sourcePlacemark];
        directionsRequest.destination = [[MKMapItem alloc] initWithPlacemark:destinationPlacemark];
        directionsRequest.transportType = MKDirectionsTransportTypeWalking;
        directionsRequest.requestsAlternateRoutes = NO;

        MKDirections *directions = [[MKDirections alloc] initWithRequest:directionsRequest];

        [directions calculateDirectionsWithCompletionHandler:^(MKDirectionsResponse *response, NSError *error) {
             if (error) {
                 // Handle Error
             } else {
                 NSMutableArray *routePoints = [[NSMutableArray alloc] init];
                 MKRoute *route = response.routes[0];

                 for (NSUInteger i = 0; i < route.polyline.pointCount; i++) {
                      MKMapPoint point = route.polyline.points[i];
                      CLLocation *location = [[CLLocation alloc] initWithLatitude:point.x longitude:point.y];
                      [routePoints addObject:location];
                 }

                 RMPolylineAnnotation *polylineAnnotation = [[RMPolylineAnnotation alloc] initWithMapView:_mapView
                                                                                points:[routePoints copy]];
                 [polylineAnnotation setLineWidth:10.0f];
                 [polylineAnnotation setLineColor:[UIColor orangeColor]];

                 [_mapView addAnnotation:polylineAnnotation];
             }
         }];

Many thanks for your help :)


text:
Q: Prove or disprove: $Z_{25}$ is isomorphic to $R = Z_{5}[x]/\langle x^2+x+1\rangle$ Prove or disprove:
$Z_{25}$ is isomorphic to $R = Z_{5}[x]/\langle x^2+x+1\rangle$.
I tried to use the isomorphism theorems to show the two above are isomorphic, But i could not find homomorphism as required.
I belive this statement is false but I can't disprove it.
I know $Z_{25}$ is cyclic, But could not show R is not.
Any hints will be appericiated.

A: Hint: Think about the additive order of $1$.

A: Hints:  Check if your quadratic is irreducible.   Here it's as simple as plugging in the numbers 0 through 4.
If you mod a ring out by an irreducible polynomial, you get a field.

A: Hint: The polynomial is irreducible over $\Bbb Z_5$ as it has no root in $\Bbb Z_5$.
So the quotient ring is a field with 25 elements, written as $GF(25)$ (Galois Field), but its not isomorphic to the ring $\Bbb Z_{25}$.


text:
Q: Martingale w.r.t. the filtration $\{\mathcal{F}_{t \wedge \tau}\}$ I want to show that any martingale w.r.t. the filtration $\{\mathcal{F}_{t \wedge \tau}\}$ is also a martingale w.r.t. the filtration $\{\mathcal{F}_{t}\}$.
So, suppose $(X_n)_{n \geq 0}$ is a martingale w.r.t. $\{\mathcal{F}_{t \wedge \tau}\}$. That is, $X_t$ is $\mathcal{F}_{t \wedge \tau}$-measurable and integrable and $\mathbb{E}[X_t | \mathcal{F}_{t \wedge \tau}] = X_s$ for $s<t$.
Since $\mathbb{1}_{\{\tau \leq s\}} X_t$ is $\mathcal{F}_{t \wedge \tau}$-measurable,
\begin{align*}
\mathbb{E}[X_t \mid \mathcal{F}_{t \wedge \tau}] &= X_s \\
\mathbb{1}_{\{\tau \leq s\}} \cdot \mathbb{E}[X_t \mid \mathcal{F}_{t \wedge \tau}] &= \mathbb{1}_{\{\tau \leq s\}} X_s\\
\mathbb{E}[\mathbb{1}_{\{\tau \leq s\}}X_t \mid \mathcal{F}_{t \wedge \tau}] &= \mathbb{1}_{\{\tau \leq s\}} X_s  \qquad \text{(is this step correct?)}\\
\mathbb{1}_{\{\tau \leq s\}}X_t &= \mathbb{1}_{\{\tau \leq s\}} X_s.
\end{align*}
Then I want to show that $(X_n)$ is indeed a martingale w.r.t. $\{\mathcal{F}_{t}\}$. With $s<t$ and $A \in \mathcal{F}_s$,
\begin{align*}
\mathbb{E}[\mathbb{1}_A X_t] &= \mathbb{E}[\mathbb{1}_A \mathbb{1}_{\{\tau \leq s\}}X_t] + \mathbb{E}[\mathbb{1}_A \mathbb{1}_{\{\tau > s\}}X_t] \\
&= \mathbb{E}[\mathbb{1}_A \mathbb{1}_{\{\tau \leq s\}}X_s] + \mathbb{E}[\mathbb{1}_A \mathbb{1}_{\{\tau > s\}}X_t].
\end{align*}
Where I got stucked... Why should we elaborate $\mathbb{E}[\mathbb{1}_A X_t]$? How is this related to $\mathbb{E}[X_t \mid \mathcal{F}_s]$ and how to find that this is equal to $X_s$?


text:
Q: Is combination of markdown and LaTeX a future trend of LaTeX development? I think markdown language is encroaching on the market of LaTeX, could latex developers share about your opinions on this language? Do you think a kind of combination of markdown and LaTeX be a good idea?
For me, when I use Mou on my mac, I found some markdown editors are able to insert images quite nicely, so I was thinking if someday somehow it could even live preview the flowchart (including the TikZ in markdown), it would make life much easier. Isn't that the dream of original LaTeX project?


text:
Q: How to change caption font color on TCheckBox, TRadioButton, TGroupBox? I don't know what my problem is, but I cannot set the font color in DEx2 for controls like TCheckBox, TRadioButton, TGroubBox, and TRadioGroup.  It doesn't matter if I do it in the IDE or programmatically.
I have set my form color to clBlack and want my captions to be clWhite, but they won't render any color but clBlack.  When I assign a color on a form's OnShow event and step through it in the debugger, it shows the value I assigned it, but on the screen it is still black.
I am not using styles or anything else.  Any ideas?
Here is a sample form:
white on black example http://www.skippix.us/temp/Delphi-Font-Problem.bmp

A: When you uses the windows themes in an application, most of the custom settings like the font colors are ignored. As workaround and depending of the component you can ownerdraw the control (only when this feature is supported), override the paint method in order to use your own color in the font  (TRadioGroup, TGroupBox), and for components like TCheckBox and TRadioButton (which are WinAPI controls wrappers) you must intercept the WM_PAINT windows message and implement your own code to draw the control.
Also starting with Delphi-xe2 you can use the vcl styles which allow you to change the appearance of the controls, from here (and when is possible) you can modify the style hooks to apply your own font colors and other customizations.

A: A simple and easier workaround is to create a checkbox without caption and add a label after it. You can easily change the label's color. You can also create a new component that binds a label to the checkbox itself. That's what worked for me on Delphi 2007.

A: It will work under the following setting:
Project Options > Application > Runtime Themes = none


text:
Q: how to put the text in the same line with the button I'm trying to put the button on the same line as the text and yet,the button goes to the next line (see picture below).

My html and css (using bootstrap) is the following:

        <svg class="svg-icon svg-circle-cross float-right" aria-hidden="true" focusable="false">
            <use xlink:href="{% static 'svg-icons/icon-sprite.svg' %}#circle-cross"></use>
        </svg>

The d-inline on the 4th line, used on the div class allows to have everything in a block (or I guess). The float-right on the 5th line allows the svg button to go to the right. Yet, it goes to the next line as you can see in the picture.
I've tried to use a text-nowrap in the div class, to remove the next line, to no effect. I've also tried .justify-content-end and also .align-self-end and other bootstrap tricks found here, to no avail.
If you have any ideas, I'm all ears.

A: In your case, you need to change div tag to span tag
Here's a simple example

Sample Text

<button>button(change this with your svg button)</button>


text:
Q: Has anyone created any Angular2 auth wrapper classes for IdentityServer 3/4? i see angular2-jwt but i don't know how to use it with IdentityServer.  has anyone done anything with angular2 and identityserver?

A: I managed to get it working after following the example's in this blog post:
https://damienbod.com/2016/03/02/angular2-openid-connect-implicit-flow-with-identityserver4/


text:
Q: Building an array of strings from user input I have the following simple program that will take user string input (" ") from the terminal and parse the input into an array of strings (called array) , character by character. Whenever a numeric character is encountered a new string is created: i.e ./programname "Hello1 my name is 2john" would output as:
Hello

1 my name is

2john

So, I am checking each character of the input and then deciding whether to strcat it to the current string at array[j] or allocate another string array[j+1] and append it to the beginning of that.
The code is as follows:
/*concatenates ts[i] and array[j]*/
char *add_to(char * copy, char ** array, int i , int j,int current_size){
    /* expand size of string at array[j]*/
    array[j] = realloc(array[j],sizeof(char)*(current_size+2));
    /*concate next character of ts*/
    char * target = malloc(sizeof(char)*2);
    strncpy(target,copy+i,1);
    target=strcat(target,"\0");
    array[j]=strcat(array[j],target);
    return array[j];

}

int main(int argc, char** argv){

    /*will hold literals*/
    char ** array = malloc(sizeof(char*)*1);
    /* current size */
    int array_size =1 ;
    /* terminal input */
    char * ts = *(argv+1);

    /* index of array */
    int j =0;
    /* index of terminal input */
    int i =0;
    /*current place to concatenate to in array[j] */
    int current_size=0;
    /* while there is more input */
    while(i<strlen(ts)){
    /* if we need more space */
        if(j==array_size){
            printf("%s\n","Expand");
            array_size++;
            /* assign old pointer to new pointer */
            array=realloc(array,array_size*sizeof(char*));
        }
        /* concatenate array[j] and character at ts[i]*/
        array[j]=add_to(ts,array,i,j,current_size);
        /*new spot to concatenate when loop around */
        current_size++;
        /* move onto next character of ts */
        i++;
        /*if this new character is a digit move to next slot of array */
        if(i<strlen(ts)&&isdigit(*(ts+i))!=0){
            j++;
            current_size=0;
        }
    }
    /* print all literals in array */
    j=0;
    while(j<array_size){
        printf("%s\n",array[j]);
        j++;
    }
return 0;
}

However, when the input is too larger, the program starts to print either multi-byte characters along with the correct string: (ؼ-�3)
) or if even bigger results in segmentation-fault.
Any idea what I am doing wrong when I am dynamically allocating memory?

A: reduce and fix your code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

char *add_to(char * copy, char ** array, int i , int j, int current_size){//i: start position, j: length of parts
    char *target = malloc(j + 1);//+1 for NUL
    strncpy(target, copy + i, j);
    target[j] = '\0';
    return array[current_size-1] = target;
}

int main(int argc, char** argv){
    const char *digits = "0123456789";
    char **array = NULL;
    int array_size = 0;//current size
    char *ts = argv[1];//terminal input

    int i, j;

    for(i = 0; ts[i] != '\0'; i += j){//i: index of the string
        //no need size check when expand one by one
        array = realloc(array, ++array_size * sizeof(char*));//fail check omitted
        j  = strspn(ts + i,      digits);//The length containing digit
        j += strcspn(ts + i + j, digits);//add length containing no digit
        add_to(ts, array, i, j, array_size);
    }
    /* print all string in array */
    for(j=0; j<array_size; j++){
        puts(array[j]);
    }
    //deallocate
    return 0;
}


text:
Q: How to grab the records when one table changes I am exporting client data from a database into Salesforce. I have two tables (Fiddle shown below)
Table: SALESFORCE_CONTACTS

user_id
start_at
end_at
company_id

37483
2021-12-12
NULL
88

23982
2020-03-02
2021-04-02
169

Table: DB_CONCATS

user_id
start_at
end_at
company_id

37483
2021-12-12
NULL
88

23982
2020-03-02
2021-04-02
169

Every so often a column in DB_CONCATS will change and on the export (every 2 hours) the Salesforce data will change. Right now I am exporting every single contact every 2 hours.
But I only want to export the records that do not match the Salesforce table. The only way I can think of is to write something like this:
SELECT
    DB_CONTACTS.*
FROM
    DB_CONTACTS
LEFT JOIN
    SALESFORCE_CONTACTS ON DB_CONTACTS.user_id = SALESFORCE_CONTACTS.DB_USER_ID
WHERE
    DB_CONTACTS.user_id <> SALESFORCE_CONTACTS.db_user_id
    OR DB_CONTACTS.created_at <> SALESFORCE_CONTACTS.db_created_at
    OR DB_CONTACTS.disabled_at <> SALESFORCE_CONTACTS.db_disabled_at
    OR DB_CONTACTS.company_id <> SALESFORCE_CONTACTS.db_company_id

Great! That produces no records because the two tables are exactly alike at the moment. Once the end_at in DB_CONCATS is filled out a record will appear in the query and then, on the next extract, it will transfer it over to SALESFORCE_CONTACTS
The trouble is that the sales team is constantly adding new fields to transfer data to. So every time that is done I would have to add a line to the query above and it would be trouble to maintain. Is there an easier way to compare the two tables without so many lines of code?
http://sqlfiddle.com/#!9/3ca536/9
Thank you

A: compare the schema and build a string to build the sproc / alter table programatically if they change it constantly. If the schema has changed you might throw all away and re-build the table and re-populate it from scratch, and if the schema has NOT changed:
SQL discards rows if you have any comparison against a NULL value. so <> won't cut it for such scenarios, I suggest the following as long as USER_ID is never null and is UNIQUE in both tables:
declare @a table (user_id int,  start_at datetime,  end_at datetime,    company_id int);
declare @b table (user_id int,  start_at datetime,  end_at datetime,    company_id int)

insert into @a values(37483,'2021-12-12',   NULL,   88)
insert into @a values(23982,'2020-03-02',   '2021-04-02',   169)

insert into @b values(37483,'2021-12-12',   NULL,   88)
insert into @b values(23982,'2020-03-02',   '2021-04-02',   169)

update @b set start_at = null where user_id = 37483

SELECT
  *
FROM
  @a a
  full join @b b on a.user_id = b.user_id
WHERE NOT EXISTS(
    select a.start_at, a.end_at, a.company_id
    intersect
    select b.start_at, b.end_at, b.company_id
)


text:
Q: Analysis of sorting Algorithm with probably wrong comparator? It is an interesting question from an Interview, I failed it.
An array has n different elements [A1 .. A2 .... An](random order).
We have a comparator C, but it has a probability p to return correct results.
Now we use C to implement sorting algorithm (any kind, bubble, quick etc..)
After sorting we have [Ai1, Ai2, ..., Ain] (It could be wrong)。
Now given a number m (m < n), the question is as follows:

*

*What is Expectation of size S of Intersection between {A1, A2, ..., Am} and {Ai1, Ai2, ..., Aim}, in other words, what is E[S]?

*Any relationship among m, n and p ?

*If we use different sorting algorithm, how will E[S] change ?
My idea is as follows:

*

*When m=n, E[S] = n, surely

*When m=n-1, E[S] = n-1+P(An in Ain)

I dont know how to complete the answer but I thought it could be solved through induction.. Any simulation methods would also be fine I think.

A: Hm, if A1,A2,...,An are in random order (as stated in the question), then all that sorting and probability of correctness of Comparator C does not really matter. The question is then reduced to the expectation of the length of intersection of two random subsets, each of size m, of {A1,...,An}.
The probability that S is k is then (m k)*((n-m) (n-k))/(n m), where (a b) shall denote "a over b", the number of possibilities chosing b elements from a elements. (Because for the second subset we have to choose k elements out of the first subset and m-k elements from the rest.)
E[S] is then the sum(0 <= k <= m) k*(m k)*((n-m) (n-k))/(n m), which reduces to m/(n m) * sum(0 <= k <= m) ((m-1) (k-1))*((n-m) (n-k)). This sum is a basic (well-known) binomial identity giving ((n-1) (m-1)), so finally we get m/(n m) * ((n-1) (m-1)) = m^2/n.

A: Partial answer for modified question:

*

*Let's assume that Ai1,...,Aim is not intersected with the initial (random) array start, but with the first m values of the correctly sorted array Aj1,...,Ajn. (which seems to be more interesting)

*Let us further assume that the comparator C is non-deterministic.

*And for simplicity we assume all array elements are different and n=2^N.

Now the partial answer here is at first restricted to

*

*m=1

*sorting-algorith=merge sort

Aj1 is the smallest element. In merge sort each element is compared ld(n)=N times. The smallest element is sorted to the first position if and only if it turns out smaller in each of its ld(n)=N comparisons. So the probability P(Ai1=Aj1) = p^N, which equals for m=1 the requested E[S]. So we get
E[S] = p^ld(n)

And here is a partial answer for

*

*m=1

*sorting-algorith=bubble sort with getting the smallest elements in place first

If the smallest element is on position k at the beginning (Ak=Aj1), then it takes max(k-1,1) correct comparisons to bring Ak to the front (Ak=Ai1). Since all n start positions are equally probable we get
E[S] = P(Ai1=Aj1) =
     = P(Ai1=Aj1|Aj1=A1)*P(Aj1=A1) + ... + P(Ai1=Aj1|Aj1=An)*P(Aj1=An) =
     = 1/n (p + p + p^2 + ... + p^(n-1)) = 1/n ((1-p^(n-1))/(1-p)+p-1) =
     = (2p - p^2 - p^(n-1)) / (n(1-p))

Good luck for the general case!


text:
Q: Why are arguments used to pass in a inputted value from outside of function. Rather than asking for and storing input all in function itself? Why are arguments used to pass in a input from user most of the time instead of using code like scanf in function itself.
It would just make code cleaner.
But i most of the time see people write prompts ask for input store it in variable and pass it in as argument outside of function even when they dont re use value later on in code.
Is it just habit of people who write complex code so most of the time its better idea to save input in separate variable and then pass it in rather than just use scanf in body of function?
Because other option of putting everything in function always seems easier to read you dont need arguments which add another layer of unnecessary complexity because whole sub problem is contained in one abstraction?

A: It is too have a better overview and re usability of the code, exactly like most functions do not allocate their own memory and ask for a buffer instead.
Let us look at an examples.:
void reverse(const char* input, char* output, int len) {
    for (int i = 0; i < len; i++) {
        output[len - 1 - i] = input[i];
    }
    output[len] = 0;
}

int main() {
    char* my_input = malloc(MAX_INPUT_SIZE + 1);
    int len = read(1, my_input, MAX_INPUT_SIZE);
    if (len < 0) exit(1);
    char* my_output = malloc(len + 1);
    reverse(my_input, my_output, len);
    free(my_input);
    printf("%s", my_output);
    free(my_output);
}

If we look at the main function the programs control flow is very clear. We can see where memory is allocated and where it is freed. But most importantly, we can change the input method, without having to touch the reverse() function. If reverse would be a very complicated function, this would be pretty hard to do.
Let us look at an examples.:
char* reverse() {
    char* input = malloc(MAX_INPUT_SIZE + 1);
    int len = read(1, input, MAX_INPUT_SIZE);
    if (len < 0) exit(1);
    char* output = malloc(len + 1);
    for (int i = 0; i < len; i++) {
        output[len - 1 - i] = input[i];
    }
    output[len] = 0;
    free(input);
    return output;
}

int main() {
    char* my_output = reverse();
    printf("%s", my_output);
    free(my_output);
}

As you can see, the calling method is a lot shorter. But the big drawback is, that we can't really see what reverse is doing on the first look. Now you would need to write a long comment (at least for a more complex function) what this does. Also we can not customize the memory allocation function, input function and error handling, without having to change reverse. And if we would use reverse in hundreds of places in our code, with slight differences in how they read input, you would have to write a new function for every of them.


text:
Q: Preventing user login method running every single time after first login I'm trying to find a way to create a session/cookie to handle user login so that the method below doesn't run query against the database every singe time. It is being called in nearly all the scenarios and slows the test suite a lot.
Important note: There are 2 different users login: user and admin so there may be three different sessions.
When I login as "user"
When I login as "admin"

class FeatureContext extends MinkContext implements KernelAwareInterface
{
    /**
     * @When /^I login as "([^"]*)"$/
     *
     * @param $type User role type.
     */
    public function iLoginAs($type)
    {
        $userData['user']  = array('username' => 'you', 'password' => '111');
        $userData['admin'] = array('username' => 'mee', 'password' => '222');

        $this->visit('/login');
        $this->fillField('username', $userData[$type]['username']);
        $this->fillField('password', $userData[$type]['password']);
        $this->pressButton('_submit');
    }
}

A: The biggest problem here comes from the fact that you send an actual request to the server, which gets processed by both Behat and your app. Instead you can take that logic into your context and do it like this in Behat 3:
Given I am logged in as "…"

class MinkContext extends \Behat\MinkExtension\Context\MinkContext
{

    /**
     * @Given /(?:|I am )logged in as "(?P<type>\d+)"/
     */
    public login($type)
    {
        // Here goes the same logic as per your login action: load the user details, create
        // session, etc. In theory you can store the signed in user model or session id in a
        // static property and don't load it every time the step is invoked.
    }

    /**
     * @beforeStep
     *
     * @param BeforeStepScope $scope
     */
    public function synchroniseClientSession(BeforeStepScope $scope)
    {

        // Setup session id and Xdebug cookies to synchronise / enable both.

        $driver = $this->getSession()->getDriver();

        // Cookies must be set per a specific domain + Chrome might start with a weird url.

        if ($driver instanceof Selenium2Driver && $driver->getCurrentUrl() === 'data:,') {
            $driver->visit($this->getMinkParameter('base_url'));
        }

        $driver->setCookie(session_name(), session_id());
        $driver->setCookie('XDEBUG_SESSION', 'PHPSTORM'); // Can also do that to enable debugging…
    }
}

It's all fairly simple if you understand how the sessions work and passed between the server and the client. You basically do it "manually" in your context, but the idea is exactly the same with what happens in the controller / action.
You'll need to ensure no session is open before you start the new one in the login, there you might run into some nasty problems, but hopefully not.


text:
Q: What's wrong with this 1 = -1 proof? Stared at this proof for 10 minutes, perhaps even more. Still a quite stumped, but I'm pretty sure the answer is staring me right in the face.
Okay, so we know that $i^2 = -1$.
Dividing both sides by $i$:
$$i = - \frac{1}{i}$$
Squaring both sides:
$$i^2 = -\frac{1^2}{i^2}$$
Obviously $i^2 = -1$, as previously shown, so therefore:
$$-1 = -\frac{1}{-1}$$
Both negatives become a positive, so we're left with:
$$-1 = \frac{1}{1}$$
Which simplifies to:
$$-1 = 1$$
I'm not quite sure what's wrong here. Unless I'm there's an important step I skipped, I don't really see any problem here.

A: The square of $-x$ is $x^2$, not $-(x^2)$. Your error is in the "squaring both sides" step.

A: You're doing mistake in the "squaring both side" step. You're squaring like this -(1/i)²
It should be done like this (-1/i)²

A: $\left(\frac{-1}{i}\right)^2=\frac{(-1)^2}{i^2}=\frac{1}{-1}=-1$


text:
Q: Clipped data frame clips labels? I have a large project with provincial data. The project is currently using a data driven map with a clipped data frame for the province. The issue is the data I'm trying to show is thousands of point labels within each province, and the now clipped border is clipping labels as well. How do I stop the labels from being clipped along with the data frame?
Also, I only want to show labels that are applicable to that specific province and not the neighbouring provinces.

A: if you create a duplicate of the layer you are labelling, and use this as your  "for label" version of the layer. Then turn off labels on the original. Then you should be able to exclude the "for label" layer by ticking it using the the Exclude Layers... button.
This button is below the Clip Options drop down within the data frame properties.

A: To solve this I used a Page Definition Query to match the Data Driven Page and also set the Point feature to ignore the boundary for the dataframe clip.


text:
Q: Help me with algorithm.. Javascript On my page I'm making ajax-request to get data from server. The data is list of JSON objects..
Every object has name, description and datetime. How can I get the object which is the closer to my real data in browser...
Example:
$(json).each(
    function(i) {
         alert(json.datetime)
        //here have to be some algorithm to comparing the time with my current time instead of alert..
    });

A: It sounds like you simply need to loop over each element and compare the date times, storing the current element if it's closer than the last element you compared.
This assumes your json array contains at least one element, and that your datetime fields are standard Unix timestamps.
var closest = json[0];
var current = Date.getTime() / 1000; // current datetime, in seconds since epoch

// start at the 2nd element
for (i = 1; i < json.length; ++i) {
  if (current - json[i].datetime < current - closest.datetime) {
    closest = current;
  }
}

A: Quite often, the UTC timestamps returned through JSON queries are in an ISO 8601 format (e.g. as returned by the JSON interface to the MediaWiki software that powers Wikipedia). Before performing date arithmetic, you will need to convert that to a format that the web browser will recognize.
(See Problem with date formats in JavaScript with different browsers for how to do this using regular expressions.)
Then you will need to subtract that time (new Date(timeString.replace(...)...)) from the current time (new Date()). That will give you the interval between the two times in milliseconds (1 second = 1000 milliseconds).
Be aware that this is affected by the accuracy of the client computer's system clock, which you have no control over if you are operating a public web site. If this is the case, you should compare times on your server or at least allow your server to send the accurate time to the client over JSON.

A: There is my version made from meagar's Answer... Thanks a lot!!!
$(json).each( function(i) {
if (Math.abs(cur_time - time) < Math.abs(cur_time - closest)) {
      closest = time;
      current_pk=pk;
  }
}
}
);


text:
Q: iOS CoreLocation not working over 3G in USA only My app is unable to determine lat/long coordinates over 3G in North America. It works perfectly when connected to Wi-Fi. This has been confirmed with both AT&T and Verizon with iOS 5. In the UK it works as expected on both 3G and Wi-Fi with o2.
I'm really stumped as to what the cause may be. I think my code is quite forgiving with regards to accuracy, but as I'm on the other side of the pond, I could be way off?
Can anyone sport any glaring mistakes in my code? (I've removed some unrelated methods).
static NSTimeInterval MaxLocationAge = 60.0; // Seconds.
static CLLocationAccuracy DesiredHorizontalAccuracy = 200.0; // Meters.
static NSTimeInterval UpdateTimeout = 30.0; // Seconds.

@implementation AFLocation

@synthesize locationManager = _locationManager, delegate = _delegate, bestEffortAtLocation = _bestEffortAtLocation, updateStartedAt = _updateStartedAt;

- (id)init
{
    self = [super init];
    if (self) {
        CLLocationManager *manager = [[CLLocationManager alloc] init];
        self.locationManager = manager;
        [manager release];
        self.locationManager.delegate = self;
        self.locationManager.distanceFilter = kCLDistanceFilterNone;
        self.locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    }
    return self;
}

- (void)update
{
    self.updateStartedAt = [NSDate date];
    isUpdating = YES;
    [self.locationManager startUpdatingLocation];
}

- (void)locationManager:(CLLocationManager *)manager
    didUpdateToLocation:(CLLocation *)newLocation
           fromLocation:(CLLocation *)oldLocation {

    if ([[NSDate date] timeIntervalSinceDate:self.updateStartedAt] > UpdateTimeout) {
        [self.locationManager stopUpdatingLocation];
        if (isUpdating) {
            [self updateDidTimeout];
        }
        isUpdating = NO;
    }

    NSTimeInterval locationAge = -[newLocation.timestamp timeIntervalSinceNow];

    if (locationAge > MaxLocationAge) {
     return;
    }

    if (newLocation.horizontalAccuracy < 0) {
        return;
    }

    if (self.bestEffortAtLocation == nil || self.bestEffortAtLocation.horizontalAccuracy > newLocation.horizontalAccuracy) {
        self.bestEffortAtLocation = newLocation;

        if (newLocation.horizontalAccuracy <= DesiredHorizontalAccuracy) {
            self.bestEffortAtLocation = nil;
            isUpdating = NO;
            [self.locationManager stopUpdatingLocation];

            [self didUpdateWithDesiredAccuracyToLocation:newLocation];
        }
    }
}

@end

A: WiFi and 3G are only used to speed up the process of getting a high accuracy (<300m) location.  Without internet connectivity it can take 3-10 minutes to get a fix using GPS only.  (They are used for low accuracy fixes with cell tower or wifi triangulation and also to download the satellite ephemeris data to speed up GPS signal acquisition).
The initial fix with WiFi or 3G could be around 800m accuracy that's expected, but if the device has 3G (or WiFi or Edge) connectivity and can get a strong enough signals from the GPS satellites it should be able to get a GPS position within 20-90 seconds.
Perhaps you're app isn't waiting long enough, or the user has weak GPS signal, or has a device without GPS (ie: iPhone1 or iPod Touch or non-3G iPads).  In that case they won't get enough the 200m accuracy required.

A: You've set the CLLocationManager to use a desired accuracy of kCLLocationAccuracyBestForNavigation, but you're comparing the location's accuracy with an arbitrary accuracy of 200 meters. With kCLLocationAccuracyBestForNavigation being an opaque type, how do you know that the manager is even striving for your 200 meter accuracy? When I receive location updates, I check to see if the accuracy is less than or equal to the desired accuracy set on my location manager.


text:
Q: Grails render named arguments are not allowed inside index operations In grails(currently using 2.2.1), with render, if I write something like this:
render [msg: msg] as JSON

Then it gives compile time error of "named arguments are not allowed inside index operations"
However if I write something like this:
def result=[msg: msg]
render result as JSON

Above works.
Wondering why its like that as I see no difference in assigning a map to another variable and using in render.Why unnecessary overhead of creating a separate variable?


text:
Q: How to get all page posts for a multilingual Facebook page? With the FB API I can only retrieve the stream for the country I'm registered (France) I would like to get ALL the posts even if they're not in French.
For example : http://www.facebook.com/Nina
I tried to put a "locale" parameter but it doesn't change anything.
Any ideas?


text:
Q: Find Exact Matches of SURF in openCV I am using openCV Surf tracker to find exact points in two images.
as you know, Surf returns many Feature points in both images. what i want to do is using these feature parameters to find out which matches are exactly correct (true positive matches). In my application i need only true positive matches.
These parameters existed : Hessian, Laplacian, Distance, Size, Dir.
I dont know how to use these parameters?
is exact matches have less distance or more hessian? laplacian can help ? size or dir can help ?
How can i find Exact matches(true positives)??

A: You can find very decent matches between descriptors in the query and image by adopting the following strategy -
Use a 2 NN search for query descriptors among the image descriptors, and the following condition-
if distance(1st match) < 0.6*distance(2nd match) the 1st match is a "good match".
to filter out false positives.

A: It obvious you can't be 100% sure which points truly match. You can increase (in the cost of performance) positives by tuning SURF parameters (see some links here). Depending on your real task you can use robust algorithms to eliminate outliers, i.e. RANSAC if you perform kind of model fitting. Also, as Erfan said, you can use spatial information (check out "Elastic Bunch Graph Matching" and Spatial BoW).

A: The answer which I'm about to post is just my guess because I have not tested it to see whether it exactly works as predicted or not.
By comparing the relative polar distance between 3 random candidate feature points returned by opencv and comparing it with the counterpart points in the template (with a certain error), you can not only compute the probability of true positiveness, but also the angle and the scale of your matched pattern.
Cheers!


text:
Q: How to log/ inspect a $resource in a $scope variable in AngularJS controller? In a controller, when I get a resource from a service
$scope.myVariable = MyObject.get($scope.id);

then myVariable is not defined as MyObject since it will be resolved later. Is there a way to inspect the variable in the controller (not in the service), for example for debugging or logging? Basically I am looking for something like
console.log("myVariable now has property "+ $scope.myVariable.myProperty);

A: From AngularJS Doc to $resource, you can read that:

It is important to realize that invoking a $resource object method
  immediately returns an empty reference.
  Once the data is returned from the server the existing reference is
  populated with the actual data. This is a useful trick since usually
  the resource is assigned to a model which is then rendered by the
  view. Having an empty object results in no rendering, once the data
  arrives from the server then the object is populated with the data and
  the view automatically re-renders itself showing the new data. This
  means that in most case one never has to write a callback function for
  the action methods.

But, if you need to print the value of $scope.myVariable once it gets populated, you will have to define a callback function:
$scope.myVariable = MyObject.get($scope.id, function(myVar){
   // From now, myVar == $scope.myVariable
   console.log("myVariable now has property "+ myVar.myProperty);
});


text:
Q: I have A POST Request, Need to pass body parameters, In My Code Below I have POST  request that takes body as parameters.

I tried this, but I didn't get any Response,
Does Alamofire allow to Send body parameters when making API Requests?
 let params = [
            "course":"1",
            "batch":"1"
        ]

Alamofire.request(markURL, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
            if((response.result.value) != nil) {
                var jsonVar = JSON(response.result.value!)
                print(jsonVar)
            }
        }

I'm Kinda stuck, Any help would be appreciated.

A: Change your encoding like this:
Alamofire.request(markURL, method: .post, parameters: params, encoding: URLEncoding.httpBody, headers: headers).responseJSON { (response) in
            if((response.result.value) != nil) {
                var jsonVar = JSON(response.result.value!)
                print(jsonVar)
            }
        }


text:
Q: display:grid CSS3 lay-out is not working I'm trying to make an HTML layout with display:grid but it is not working. I want to have a layout with 2 columns and 3 rows. Can anyone tell me what I'm doing wrong?
This is the simplified HTML code I use. I added a printscreen to show the result.
<!DOCTYPE html>

                header

                section

                aside

                footer


text:
Q: Semantic of `string.length()`? I want to convert a char buffer of known size (e.g. received from socket) into a string, but
with the caveat that the char array is not necessarily null-terminated.
So I tried to use string (InputIterator first, InputIterator last) constructor.
However,
I notice that string::length() isn't always the same as strlen,
at least in my case where strings are manually crafted from buffers
with many trailing zeros.
#include <string>
#include <iostream>

#include <string.h>

using namespace std;

int main()
{
    char a[20] {0};

    a[0] = 'a';
    string b(a, a + 20);
    cout << b.length() << endl;
    cout << strlen(b.c_str()) << endl;
}

Output is
20
1

Though this is a well-defined behavior for string::length (thanks to the comments and some initial answers for helping me to realize that), I'd like to find a better / more idiomatic solution.

A: The difference here is that, for a std::string, those NULL characters don't affect its length; it can hold them just fine.
However, for a c-style string, strlen with stop counting when it encounters the first NULL character, which for you is the second character, hence a size of 1.

A: You told it you wanted 20 bytes, so that's exactly what you got.
It sounds like you want to copy up to 20 bytes or until a null byte is encountered:
#include <string>
#include <iostream>
#include <cstring>

int main()
{
    char a[20]{};

    a[0] = 'a';
    std::string b(a, a + strnlen(a, sizeof(a)));
    std::cout << b.length() << '\n';
    std::cout << strlen(b.c_str()) << '\n';
}

You'll notice I've gone back to having the computer detect the number of input bytes for us, but with strnlen you can tell it to stop at 20, taking care of the problem that the array may not be null-terminated.
I've also changed {0} to {}, for style/sanity reasons.
(live demo)


text:
Q: Property for 4 consecutive positive integers?
I derive the answer G by randomly choosing four integers multiple times, which is a bit time-consuming for ACT Math. Could anyone offer me a quicker method to cope with it?

A: I is false since $24, 25, 26, 27$ are all not prime. To see this, I simply went through the primes in my head $2,3,5,7,11,13,17,19,23,29,\ldots$ until I found two which were more than four apart.
III is false since none of $4,5,6,7$ is a factor of the others. To see this, I simply noted that once $n$ gets "large enough", $n-3$, $n-2$, $n-1$, and $n$ are all bigger than $\tfrac{n}{2}$, which means none of them are small enough to be a factor of the others.
II is true since two of the four consecutive numbers must be even, and therefore have $2$ as a common factor.
Hence, the answer is G.

A: I) should be rejected outright.  It should be well known that we can have a gap in primes of more than $4$.  There is the excercise that $n! + 2$ through $n! + n$ will be $n-1$ consecutive digits with no primes.  But even if you don't think of that the statement should just seem absurd.  After all no even number over $2$ is prime so that would mean every other odd number is prime and surely that can't be true!  $25$ and $27$ are not prime so $24,25,26,27$ are a counter example.
II) is clear when you realize $2$ is prime and two of the numbers must be even.  (Otherwise $3$ being a common factor of the first and last is the only other possible option but its not guarenteed.)
III) is clearly false.  If two numbers have a common factor, $k$ the must be a multiple of $k$ apart.  As four consecutive numbers are at most $3$ apart $1,2,3$ are the only possible factors they can have in common and if these numbers are larger than $3$ this statement is false.
So II is the only correct one.


text:
Q: I am not able to receive remote video stream I am using google chrome 21.x  on linux , webrtc peer connection gets established but am not able to receive any remote video stream, the callback given to the peerconnection  ".onaddstream" never gets invoked, can some body advise where i need to look ?
I am pasting my entire code, still not able to receive the remote video stream, neither there are any errors.
var peerConnCreated = false;
var peerConn = null;
var cameraOn = false;
var clientId = 0;
var svcName = "";
var clientIdRecvd = false;
var myname = "";
var hisname = "";
var myJsep;
var hisJsep;
var mySdp;
var hisSdp;

function login()
{
    var loginid = document.getElementById("login").value;
    var jsonText = {"clientid":clientId, "service":"rtc", "mtype": "online", "username": loginid};
    myname = loginid;
    socket.send(JSON.stringify(jsonText));
}

function iceCallback(canditate, moreToFollow)
{
    if(canditate) {
        console.log("ice canditate");
        var jsonText = {"clientid":clientId, "service":"rtc", "mtype": "canditate", "sndr": myname, "rcpt": hisname,
            "label": canditate.label, "cand": canditate.toSdp()};
        socket.send(JSON.stringify(jsonText));
    }
}

function onSessionConnecting(message)
{
    console.log("session connecting ...");
}

function onRemoteStreamRemoved(event)
{
    console.log("remote stream removed");
    remotevid.src = "";
}

function onSessionOpened(message)
{
    console.log("session opened");
}

function onRemoteStreamAdded(event)
{
    console.log("remote stream added");
    remotevid.src = window.webkitURL.createObjectURL(event.stream);
    remotevid.style.opacity = 1;
}

function createPeerConnection()
{
    if (peerConnCreated) return;
    peerConn = new webkitPeerConnection00("STUN stun.l.google.com:19302", iceCallback);
    peerConn.onconnecting = onSessionConnecting;
    peerConn.onopen = onSessionOpened;
    peerConn.onaddstream = onRemoteStreamAdded;
    peerConn.onremovestream = onRemoteStreamRemoved;
    console.log("peer connection created");
    peerConnCreated = true;
}

function turnOnCameraAndMic()
{
    navigator.webkitGetUserMedia({video:true, audio:true}, successCallback, errorCallback);
    function successCallback(stream) {
        sourcevid.style.opacity = 1;
        sourcevid.src = window.webkitURL.createObjectURL(stream);
        peerConn.addStream(stream);
        console.log("local stream added");
    }
    function errorCallback(error) {
        console.error('An error occurred: [CODE ' + error.code + ']');
    }
    cameraOn = true;
}

function dialUser(user)
{
    if (!peerConnCreated) createPeerConnection();
    hisname = user;
    var localOffer = peerConn.createOffer({has_audio:true, has_video:true});
    peerConn.setLocalDescription(peerConn.SDP_OFFER, localOffer);
    mySdp =  peerConn.localDescription;
    myJsep = mySdp.toSdp();
    var call = {"clientid":clientId, "service":"rtc", "mtype": "call", "sndr": myname, "rcpt": hisname, "jsepdata": myJsep};
    socket.send(JSON.stringify(call));
    console.log("sent offer");
    //console.log(myJsep);
    peerConn.startIce();
    console.log("ice started ");
}

//handle the message from the sip server
//There is a new connection from our peer so turn on the camera
//and relay the stream to peer.
function handleRtcMessage(request)
{
    var sessionRequest = eval('(' + request + ')');
    switch(sessionRequest.mtype)
    {
        case 'online':
            console.log("new user online");
            var newuser = sessionRequest.username;
            var li = document.createElement("li");
            var name = document.createTextNode(newuser);
            li.appendChild(name);
            li.onclick = function() { dialUser(newuser); };
            document.getElementById("Contact List").appendChild(li);
            break;

        case 'call':
            console.log("recvng call");
            alert("Incoming call ...");
            if (!peerConnCreated) createPeerConnection();
            peerConn.setRemoteDescription(peerConn.SDP_OFFER, new SessionDescription(sessionRequest.jsepdata));
            hisname = sessionRequest.sndr;
            var remoteOffer = peerConn.remoteDescription;
            //console.log("remoteOffer" + remoteOffer.toSdp());
            var localAnswer = peerConn.createAnswer(remoteOffer.toSdp(), {has_audio:true, has_video:true});
            peerConn.setLocalDescription(peerConn.SDP_ANSWER, localAnswer);
            var jsonText = {"clientid":clientId,"service":"rtc", "mtype": "pickup", "sndr" :myname, "rcpt": hisname, "jsepdata": localAnswer.toSdp()};
            socket.send(JSON.stringify(jsonText));
            console.log("sent answer");
            //console.log(localAnswer.toSdp());
            peerConn.startIce();
            if (!cameraOn) turnOnCameraAndMic();
            break;

        case 'pickup':
            console.log("recvd pickup");
            peerConn.setRemoteDescription(peerConn.SDP_ANSWER, new SessionDescription(sessionRequest.jsepdata));
            hisname = sessionRequest.sndr;
            if (!cameraOn) turnOnCameraAndMic();
            break;

        case 'canditate':
            console.log("recvd canditate");
            var canditate = new IceCandidate(sessionRequest.label, sessionRequest.cand);
            peerConn.processIceMessage(canditate);
            break;

        case 'bye':
            console.log("recvd bye");
            break;
    }
}

//open the websocket  to the antkorp webserver
var socket = new WebSocket('ws://bldsvrub:9981');
var sourcevid = null;
var remotevid = null;

socket.onopen = function () {
    console.log("websocket opened");
    sourcevid = document.getElementById("sourcevid");
    remotevid = document.getElementById("remotevid");
};

socket.onmessage = function (event) {
    if (!clientIdRecvd) {
        var reqObj = eval('(' + event.data + ')');
        clientId = reqObj.clientid;
        svcName  = reqObj.service;
        clientIdRecvd = true;
    } else {
        //hookup the new handler to process session requests
        handleRtcMessage(event.data);
    }
};

socket.onclose = function (event) { socket = null; };

A: Many WebRTC Demos:

*

*https://github.com/muaz-khan/WebRTC-Experiment
E.g. one-to-one WebRTC audio/video/screen calls:

*

*https://github.com/muaz-khan/WebRTC-Experiment#one-to-one-calls
Note:
This question is TOOO-Old. That's why I don't think I should add a working snippet code snippet here. Above link answers all the questions.
However, if you're NEW-WebRTC user and you're facing similar issues then here are some hints:

*

*Before creating peers, make sure that both peers are ready for the handshake.

*Ready means, both peers are having access to media streams (audio and/or video)

*First peer should initiate RTCPeerConnection object, call "addStream" and create offer-descriptions.

*Second peer should receive OFFER-SDP from first peer.

*Second peer should initiate RTCPeerConnection object, call "addStream" and setRemoteDescription earlier before create ANSWER-description.

*Second peer should create ANSWER-SDP.

*First peer should get ANSWER-SDP and set-Remote-Descriptions.

*ICE-candidate-pairs should be exchanged in parallel to the above process.

You can find some tutorials here:

*

*https://www.webrtc-experiment.com/#documentations
Remember
This answer targets WebRTC-1.0. It isn't answering WebRTC-1.1 (ORTC) or newer versions.

A: onaddstream should be called upon the receipt of an answer that contains at least one stream. If you aren't getting the callback, make sure both setLocal and setRemoteDescription have been called and succeeded.

A: the above code pasted contains a small bug, the stream should be added to the peer connection before generating the answer or offer , that is "addStream" should be called before any of setlocalDescription or setRemoteDescription calls.

A: I discovered that in my case I can not receive video if not answering with another video.
I workarounded with a fake video stream:
            let w = 640;
            let h = 480;
            let canvas: any = Object.assign(document.createElement("canvas"), { w, h });
            canvas.getContext('2d').fillRect(0, 0, w, h);
            let blackStream = canvas.captureStream();
            outgoingStream.addTrack(blackStream.getVideoTracks()[0]);


text:
Q: jQuery slider problems: two buttons are getting confused about the state I have built a slider that has two possible buttons: one to .toggle, this one is always visible, and then the .click one which is only visable when the slide is open so i wanted it to only close. the problem is when you open with the .toggle and close with the .click then try to re-open with the original .toggle button. it needs 2 clicks of the mouse at that point.
<script type="text/javascript">

  $(document).ready(function(){

    $(".profile_slide_btn").toggle(

     function(){
       $("#sliding_header").animate({
         top: "0px"
       }, 300 );
     },

     function(){
      $("#sliding_header").animate({
         top: "-600px"
       }, 300 );
  });

 $(".profile_slide_btn2").click(

     function(){
       $("#sliding_header").animate({
         top: "-600px"
       }, 300 );
     });
  });

</script>

Thanks for any help!!

A: I think the issue is that the toggle runs one function & then the other, so because you closed with the .click, but the toggle doesn't know that, when you click the .toggle again, it tries to close first.
Might have to change your logic to manually do the toggle instead of relying on the .toggle function.
Edit: So something like this (note this is untested & you may have issues where clicking things during the animation cause weirdness):
<script type="text/javascript">

    $(document).ready(function(){

        $(".profile_slide_btn").click(
            function(){
                if ($("#sliding_header").css("top") == "0px") {
                    hideHeader();
                } else {
                    showHeader();
                }
            });

        $(".profile_slide_btn2").click(hideHeader);

        function showHeader() {
            $("#sliding_header").animate({ top: "0px" }, 300 );
        }

        function hideHeader() {
            $("#sliding_header").animate({ top: "-600px" }, 300 );
        }
    });

</script>

A: That's because the .toggle doesn't know the slider has been closed.

*

*Open with toogle : 0px

*Close with click: -600px

*Toggle still thinks you intend to close, so: -600px again

Use an if to know when the slider's top property is -600px and when 0, that way you know when to close and when to open.


text:
Q: How to commit and push projects in mercurial using MacOSx Hi friends how to commit and push projects in bitbucket using  MacOSx
$ hg commit
abort: no username supplied

In windows hg clients it ask username and password in pop up windows. How does this hapen on macosx? I did supply commands to terminal but no luck.

A: vim .hg/.hgrc

Then type
[ui]
username = YOUR_NAME <YOUR_MAIL>

to it.
then go back to the main directory and push it.

A: You can use the .hgrc in order to configure your local Mercurial client. Setting a username for commits is described here.


text:
Q: Restarts to install menu with usb in. Restarts to black screen and flashing underscore with usb out So i'm trying to install Ubuntu 14.04 and I can install Ubuntu, but when it restarts with the USB in, it acts like Ubuntu wasn't installed. It goes to the install, try, ect menu. When I take out the USB, after my pc says press ESC to go to boot options, it turns to a black screen with a flashing underscore. I've tried 2 different USB installers now.

A: What happened is GRUB, which is the bootloader (what allows Ubuntu on your hard drive to boot), was installed to your USB INSTEAD of your hard disk.
How to Fix:
Turn off your computer and plug your USB back in.
Turn on your computer.
Now, when a login prompt shows up, press CTRL + ALT + F1 to enter a TTY Session.
Now, it'll show a prompt like this:
ubuntu login: _

Enter your username and press Enter.
Then, enter your password and press Enter.
NOTE: The username and password are the ones you supplied during the installation process. Also, when you type your password, no characters will appear (be echoed back). This is normal behavior.
Now, once you login successfully, you should be at a prompt like this:
user@hostname:~$

Now, remove your USB from the computer (you can just pull it out, it's fine).
Then, enter the following command to install the bootloader. This command will ask for your password again.
sudo grub-install /dev/sda

Let it finish. Then once it's done, enter the following command to reboot your computer.
sudo reboot

If all goes well, your computer should reboot and boot into Ubuntu with no problems.
If this doesn't work / problems arise, please do comment!


text:
Q: Git directories - how to track directories but not content I have my .gitignore file like so
.gitignore

/data*
/node_modules/*
/bower_components/*

I want to have the directories pushed and pulled but not the contents of the directory. As it is above, the directories are ignored entirely. Is this possible?

A: You can put a .gitignore file in each directory you want to track without contents, and have its contents (the .gitignore's file, that is) be *, which would ignore all files in that directory.  git add those .gitignore files and commit them.  The result should be that the directories are tracked (because of the tracked .gitignore files in them), but any files in those directories will be ignored.

A: Git tracks content, not files. Sort-of as a result of this, it doesn't track directories either. You can kinda achieve this effect by putting a 'dummy' file in a directory, and tracking that file, but doing this and not tracking anything else in that directory can be annoying (if all your files don't have similar file names, ie: all end in .py)
Also: How to commit a directory into a git repository? answers the same question phrased differently.


text:
Q: Joint Distribution conditioned on a random variable This is one of my homework problems. Consider two random variables $X$ and $Y$.
$X \sim U(1,2)$, and the distribution of $Y$ given $X$ is $\operatorname{Exp}(X)$. Given that $X \leq 1.5$ what is the joint distribution of $X$ and $Y$?
I know that the joint distribution of $X$ and $Y$ is just $xe^{-xy}$ for $1 \leq x \leq 2, y > 0$ and $0$ otherwise, but I am not sure how to find the joint distribution conditioned on $X$.

A: You have $\Pr(X\le1.5) = 0.5.$ The conditional joint density given the event $X\le1.5$ is just the marginal joint density divided by that probability.
Consider for example $\Pr(X\le x\ \&\ Y\le y\mid X\le 1.5),$ where $1\le x\le 1.5.$
\begin{align}
& \Pr(X\le x\ \&\ Y\le y\mid X\le 1.5) \\[8pt]
= {} & \frac{\Pr(X\le x\ \&\ Y\le y\ \&\overbrace{\ X\le 1.5\,\,}\,)}{\Pr(X\le 1.5)} \\
& \text{(but, $x\le1.5,$ by hypothesis, the part under} \\
& \phantom{\text{(}}\text{the } \overbrace{\text{overbrace}} \text{ is redundant)} \\[10pt]
= {} & \frac{\Pr(X\le x\ \&\ Y\le y)}{\Pr(X\le 1.5)}.
\end{align}

A: You have the joint probability density function, so just apply the definition of conditioning to obtain:
$$\begin{align}f_{X,Y\mid X\leq 1.5}(x,y) &=\dfrac{f_{X,Y}(x,y)\,\mathbf 1_{x\leq 1.5}}{\mathsf P(X\leq 1.5)}\\[1ex] &= 2x\mathrm e^{-xy}\,\mathbf 1_{1\leq x\leq 1.5}\,\mathbf 1_{0\leq y}\end{align}$$

Likewise the conditional joint cumulative distribution function shall be $$F_{X,Y\mid X\leq 1.5}(x,y) =\dfrac{F_{X,Y}(x,y)\,\mathbf 1_{x\leq 1.5}+F_{X,Y}(1.5,y)\,\mathbf 1_{1.5\lt x}}{\mathsf P(X\leq 1.5)}$$