text:
Q: Is leaving useless synchronous code under Async/Await an anti-pattern? To my understanding, the point behind await is to 'await' the acting upon the resolved value of a promise until it is encountered as a microtask, as Jake Archibald explains here.
This video by LLJS shows that async-await is essentially syntactical sugar for a generator runner/interpreter function that yields where it awaits and passes the settled value of the promise to the .next() method. This means that the runner's execution of .next() is enqueued as a microtask when an await occurs.
Effectively speaking, all the code under that await will only be executed at the next microtask checkpoint. This can be an issue if code that doesn't require the awaited value of the promise lies underneath it, which is exactly the issue with Async IIFEs.

async function ping() {
  for (let i = 0; i < 5; i++) {
    let result = await Promise.resolve("ping");
    console.log(result);
  }

  console.log("Why am I even here?");
}

async function pong() {
  for (let i = 0; i < 5; i++) {
    let result = await Promise.resolve("pong");
    console.log(result);
  }

  console.log("I have nothing to do with any of this");
}

console.log("Let the games begin!");
ping();
pong();
console.log("Placeholder for code that is not related to ping pong");

In this example, the outside logs are logged first as part of the task of running the script, then the values of the resolved promises in the order that they were queued in the microtask queue. Within this entire process, the logs left underneath the for loops have nothing to do with the loops and are needlessly paused until the last microtask in their respective function bodies is out of the queue.
This is exactly what happens when we use async functions as IIFEs though. If you have code under the await that is meant to execute synchronously, it would have to needlessly wait until all the awaits above it have been checked out of the microtask queue.
I can see this being a problem if someone blindly wraps their entire express routes in async functions, where they would needlessly await the resolving of certain promises like database operations, the sending of emails, reading of files, etc..., So why do people still do this?
app.post('/forgotPwd', async (req, res) => {
  const {email, username} = req.body;

  if (!email) {
    res.status(400).json({error: "No username entered"});
    return;
  }

  if (!username) {
    res.status(400).json({error: "No email entered"});
    return;
  }

  const db = client.db();

  const user = await db.collection("Users").findOne({username: username, "userInfo.email": email});

  if (!user) {
    res.status(400).json({error: "Account not found"});
    return;
  }

  const authToken = await getAuthToken({id: user._id.toHexString()}, "15m");

  // Would probably send a more verbose email
  await sgMail.send({
    from: process.env.EMAIL,
    to: email,
    subject: 'Forgot Password',
    text: `Use this url to reset your password: http://localhost:5000/confirmation/passConf/${authToken}`,
  });

  res.json({error: ""});
});

A: If you want something in an async function to run synchronously, make sure it's prior to the first await in the function.

So why do people still do this?

That's probably an off-topic question for SO since it largely calls for opinion-based answers, but it's likely going to be either A) Because they don't want that code to run until the code above it has finished, or B) Because they don't understand async functions.

A: The point of using async/await is to make asynchronous code look synchronous because it's easier to read. In fact, it is a syntactic sugar that hides a callback hell underneath. You don't need to deal with callbacks in order to handle async operations.
In your case, if you think that the code after the for loop has nothing to do with the awaited operation, you shouldn't have place it after await. Or you should refactor the code so that it does not use await (callbacks).
As for the question of why people do this. Well, can you tell why people use .map() as a replacement of .forEach()? Or can you tell why they don't handle exceptions? They probably don't fully understand it or (as T.J. Crowder mentioned) they do want the code to run after the awaited operation. Simple as that.


text:
Q: Maven parent pom vs modules pom There seem to be several ways to structure parent poms in a multiproject build and I wondering if anyone had any thoughts on what the advantages / drawbacks are in each way.
The simplest method of having a parent pom would be putting it in the root of a project i.e.
myproject/
  myproject-core/
  myproject-api/
  myproject-app/
  pom.xml

where the pom.xml is both the parent project as well as describes the -core -api and -app modules
The next method is to separate out the parent into its own subdirectory as in
myproject/
  mypoject-parent/
    pom.xml
  myproject-core/
  myproject-api/
  myproject-app/

Where the parent pom still contains the modules but they're relative, e.g. ../myproject-core
Finally, there's the option where the module definition and the parent are separated as in
myproject/
  mypoject-parent/
    pom.xml
  myproject-core/
  myproject-api/
  myproject-app/
  pom.xml

Where the parent pom contains any "shared" configuration (dependencyManagement, properties etc.) and the myproject/pom.xml contains the list of modules.
The intention is to be scalable to a large scale build so should be scalable to a large number of projects and artifacts.
A few bonus questions:

*

*Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).

*How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?

Edit: Each of the sub projects have their own pom.xml, I've left it out to keep it terse.

A: From my experience and Maven best practices there are two kinds of "parent poms"

*

*"company" parent pom  - this pom contains your company specific information and configuration that inherit every pom and doesn't need to be copied. These informations are:

*

*repositories

*distribution managment sections

*common plugins configurations (like maven-compiler-plugin source and target versions)

*organization, developers, etc

Preparing this parent pom need to be done with caution, because all your company poms will inherit from it, so this pom have to be mature and stable (releasing a version of parent pom should not affect to release all your company projects!)

*second kind of parent pom is a multimodule parent. I prefer your first solution - this is a default maven convention for multi module projects, very often represents VCS code structure

The intention is to be scalable to a large scale build so should be scalable to a large number of projects and artifacts.

Mutliprojects have structure of trees - so you aren't arrown down to one level of parent pom. Try to find a suitable project struture for your needs - a classic exmample is how to disrtibute mutimodule projects
distibution/
documentation/
myproject/
  myproject-core/
  myproject-api/
  myproject-app/
  pom.xml
pom.xml

A few bonus questions:

*

*Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).

This configuration has to be wisely splitted into a "company" parent pom and project parent pom(s). Things related to all you project go to "company" parent and this related to current project go to project one's.

*

*How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?

Company parent pom have to be released first. For multiprojects standard rules applies. CI server need to know all to build the project correctly.

A: *

*An independent parent is the best practice for sharing configuration and options across otherwise uncoupled components. Apache has a parent pom project to share legal notices and some common packaging options.

*If your top-level project has real work in it, such as aggregating javadoc or packaging a release, then you will have conflicts between the settings needed to do that work and the settings you want to share out via parent. A parent-only project avoids that.

*A common pattern (ignoring #1 for the moment) is have the projects-with-code use a parent project as their parent, and have it use the top-level as a parent. This allows core things to  be shared by all, but avoids the problem described in #2.

*The site plugin will get very confused if the parent structure is not the same as the directory structure. If you want to build an aggregate site, you'll need to do some fiddling to get around this.

*Apache CXF is an example the pattern in #2.

A: In my opinion, to answer this question, you need to think in terms of project life cycle and version control. In other words, does the parent pom have its own life cycle i.e. can it be released separately of the other modules or not?
If the answer is yes (and this is the case of most projects that have been mentioned in the question or in comments), then the parent pom needs his own module from a VCS and from a Maven point of view and you'll end up with something like this at the VCS level:
root
|-- parent-pom
|   |-- branches
|   |-- tags
|   `-- trunk
|       `-- pom.xml
`-- projectA
    |-- branches
    |-- tags
    `-- trunk
        |-- module1
        |   `-- pom.xml
        |-- moduleN
        |   `-- pom.xml
        `-- pom.xml

This makes the checkout a bit painful and a common way to deal with that is to use svn:externals. For example, add a trunks directory:
root
|-- parent-pom
|   |-- branches
|   |-- tags
|   `-- trunk
|       `-- pom.xml
|-- projectA
|   |-- branches
|   |-- tags
|   `-- trunk
|       |-- module1
|       |   `-- pom.xml
|       |-- moduleN
|       |   `-- pom.xml
|       `-- pom.xml
`-- trunks

With the following externals definition:
parent-pom http://host/svn/parent-pom/trunk
projectA http://host/svn/projectA/trunk

A checkout of trunks would then result in the following local structure (pattern #2):
root/
  parent-pom/
    pom.xml
  projectA/

Optionally, you can even add a pom.xml in the trunks directory:
root
|-- parent-pom
|   |-- branches
|   |-- tags
|   `-- trunk
|       `-- pom.xml
|-- projectA
|   |-- branches
|   |-- tags
|   `-- trunk
|       |-- module1
|       |   `-- pom.xml
|       |-- moduleN
|       |   `-- pom.xml
|       `-- pom.xml
`-- trunks
    `-- pom.xml

This pom.xml is a kind of "fake" pom: it is never released, it doesn't contain a real version since this file is never released, it only contains a list of modules. With this file, a checkout would result in this structure (pattern #3):
root/
  parent-pom/
    pom.xml
  projectA/
  pom.xml

This "hack" allows to launch of a reactor build from the root after a checkout and make things even more handy. Actually, this is how I like to setup maven projects and a VCS repository for large builds: it just works, it scales well, it gives all the flexibility you may need.
If the answer is no (back to the initial question), then I think you can live with pattern #1 (do the simplest thing that could possibly work).
Now, about the bonus questions:

*

*Where is the best place to define the various shared configuration as in source control, deployment directories, common plugins etc. (I'm assuming the parent but I've often been bitten by this and they've ended up in each project rather than a common one).

Honestly, I don't know how to not give a general answer here (like "use the level at which you think it makes sense to mutualize things"). And anyway, child poms can always override inherited settings.

*

*How do the maven-release plugin, hudson and nexus deal with how you set up your multi-projects (possibly a giant question, it's more if anyone has been caught out when by how a multi-project build has been set up)?

The setup I use works well, nothing particular to mention.
Actually, I wonder how the maven-release-plugin deals with pattern #1 (especially with the <parent> section since you can't have SNAPSHOT dependencies at release time). This sounds like a chicken or egg problem but I just can't remember if it works and was too lazy to test it.

A: There is one little catch with the third approach. Since aggregate POMs (myproject/pom.xml) usually don't have parent at all, they do not share configuration. That means all those aggregate POMs will have only default repositories.
That is not a problem if you only use plugins from Central, however, this will fail if you run plugin using the plugin:goal format from your internal repository. For example, you can have foo-maven-plugin with the groupId of org.example providing goal generate-foo. If you try to run it from the project root using command like mvn org.example:foo-maven-plugin:generate-foo, it will fail to run on the aggregate modules (see compatibility note).
Several solutions are possible:

*

*Deploy plugin to the Maven Central (not always possible).

*Specify repository section in all of your aggregate POMs (breaks DRY principle).

*Have this internal repository configured in the settings.xml (either in local settings at ~/.m2/settings.xml or in the global settings at /conf/settings.xml). Will make build fail without those settings.xml (could be OK for large in-house projects that are never supposed to be built outside of the company).

*Use the parent with repositories settings in your aggregate POMs (could be too many parent POMs?).

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# TCP Socket receive part of data on slow cellular network connection while connection still not broken I am using Console application as a server on windows 10 Pro.
Android application made with Unity Engine as Client.
For both application I use TCP socket on the .Net framework.
Note: the server is always running on wire connection.
Everything work pretty well on both wire and Wi-Fi connections with no problem no meter how packet length is.
The Problem
Each evening the cellular network became too bad and the client app receive only part of the data when the data is little bigger about 50 kb
The code on the server side:
_socket.Send(Encoding.ASCII.GetBytes(s));

_socket: is an instance System.Net.Sockets.Socket.
s: is string.
The code on the client side:
public static void ReceiveData()
{
    message = string.Empty;
    _socket.BeginReceive(globalBuffer, 0, globalBuffer.Length, SocketFlags.None, ReceiveCallBack, null);
}
public static void ReceiveCallBack(IAsyncResult ar)
{
    int internalBuffer = _socket.EndReceive(ar);
    byte[] subtractedBuffer = new byte[internalBuffer];
    Array.Copy(globalBuffer, subtractedBuffer, internalBuffer);
    string stmp = Encoding.ASCII.GetString(subtractedBuffer);
    message += stmp;

    while (message.Contains("</Cargo>"))
    {
       string stringOne = message.Substring(0, message.IndexOf("</Cargo>") + "</Cargo>".Length);
       string stringLeft = message.Substring(message.IndexOf("</Cargo>") + "</Cargo>".Length);
       message = stringLeft;

       Thread thread = new Thread(TreatOrder);
       thread.Start(stringOne);
    }

    if (!(_socket.Poll(1000, SelectMode.SelectRead) && _socket.Available == 0))
    {
        NetWorkScript.LastConnectedTime = DateTime.Now;
        _socket.BeginReceive(globalBuffer, 0, globalBuffer.Length, SocketFlags.None, ReceiveCallBack, null);
    }
    else
    {
      Debug.log("Connection lost");
    }
}

What I have notice:
The next line of code never executed
else
{
   Debug.log("Connection lost");
}

The server keep receiving messages from the client on the same Socket instance by another thread and that is how came to know the connection is not broken unless TCP connection could be broken on one way only.
What I understand so far
The TCP will make sure the packets will arrive at the exact order.
The next line of code in my server application end its responsibility and the Operation System will carry on the mission to send the data.
_socket.Send(Encoding.ASCII.GetBytes(s));

What I am confused about
How the Operation System will deliver the data to the client?, why it is not keep trying until send all the data if the connection still exist?
Should I created my own protocol and send small packet then retransmit if client does not confirm receiving the packet?


text:
Q: Django: time zone issue NOTE: I deleted the question as it existed previously and providing only the relevant info here.
Our database server (RH) has TIME_ZONE = "Europe/London" specified. And, within the Django settings.py, we specify TIME_ZONE = "America/New_York".
And, in my Model class I have specified:
created = models.DateTimeField(editable=False,auto_now=False, auto_now_add=True)
modified = models.DateTimeField(editable=False,auto_now=True, auto_now_add=True)

When I then go look at the data in the admin site, I get UTC/GMT time instead of Eastern.
I thought that all time is adjusted automagically by Django since I specified  "America/New_York" as Django's Time Zone.
Any help/clarification is appreciated.
Thanks
Eric

A: The simplest/fastest fix [said above by Ajay Yadav] is this ,
Just add TIME_ZONE attribute to the Database's section in settings.py,
settings.py
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
        'TIME_ZONE': 'Asia/Tokyo',
    }
}

For the available Timezone choices , See the Official documentation linked below ,
DJANGO TIMEZONE CHOICES

A: First off, I would want to store my data as UTC cause its a good starting point.
So let me ask this, Why do you need the time in EST, is this for the end-user, or do you need to do logic on the server and need it in EST?
If its for the enduser, an easy fix is to let the users browser handle converting to the correct time. On the server convert the datetime object to a timestamp:
timestamp = time.mktime(datetime_obj.timetuple()) * 1000

And then on the web page instantiate a Date object:
var date_obj = new Date({{ timestamp }});
var datetime_string = date_obj.toString();
// the datetime_string will be in the users local timezone

Now, on the other hand, if you want to have the time in the correct zone on the server so you can perform logic on it. I recommend using the help of python-dateutil. It will allow you to easily swap to a different timezone:
from datetime import datetime
from dateutil import zoneinfo

from_zone = zoneinfo.gettz('UTC')
to_zone = zoneinfo.gettz('America/New_York')

utc = created # your datetime object from the db

# Tell the datetime object that it's in UTC time zone since
# datetime objects are 'naive' by default
utc = utc.replace(tzinfo=from_zone)

# Convert time zone
eastern_time = utc.aztimezone(to_zone)

Now if you really wanna store the datetime in EST, you need change the time on the DB server (like Ajay Yadav and gorus said). I don't know why you want to store them as EST, but then again I don't know what your application is.

A: Relying on date/time 'automagic' is dangerous and these auto_add model parameters are a trap. Always understand the timezone(s) you are dealing with. Python makes this easier by attaching a tzinfo member to its datetime objects. While these objects are 'naive' by default, I encourage you to always attach tzinfo detail. Still Python needs some extra help with either python-dateutil or pytz (what I use). Here's a universal rule though - always store your datetimes in a database as UTC.
Why? Your users may be in different locals, mobile phones and laptops travel, servers are misconfigured or mirrored in different timezones. So many headaches. Datetimes should never be naive and if they are (as in a database) and you need the context, also include a timezone field in the table.
So in your case.

*

*Don't use the auto_now fields, use a custom save() instead.

*Store UTC in the database

*If you need to know the timezone - for say a user event - store the timezone in the database as well.

*Convert to the necessary/requested timezone

If you are using pytz, the localize() method is great. Python's datetime object has the useful replace() and astimezone().
One more note, if your database is timezone naive (like MySQL) make sure your datetimes are in UTC and then use replace(tzinfo=None) because the database connector can't handle tz-aware objects.
Here is a thread with detail on Django's auto_now fields.

A: When you say auto_now_add=True, the value will be added by your database server and not your django server. So you need to set time zone on your database server.

A: Since you edited the question, I'll edit my answer :)  Django cannot control the time zone of your db, so the way to fix this is to update the time zone for your db.  For MySql, run this query:
SELECT @@global.time_zone, @@session.time_zone;
This should return SYSTEM, SYSTEM by default, which in your case means "Europe/London", and the cause of your problem.  Now that you've verified this, follow the instructions in the first comment on this page:
http://dev.mysql.com/doc/refman/5.5/en/time-zone-support.html
Remember to restart MySql server after you've updated the time zone for the changes to take effect.


text:
Q: Why this differential equation can only find half of the satellite's trajectory I calculate the orbit of the satellite according to the gravity, but the following code can only find half of the elliptical orbit and output the warning message:
G = 6.672*(10^-11)(*Gravitational constant \
N·m\.b2/kg\.b2*); M =
 5.965*10^24(*The mass property of Earth kg*); m = 10(*The mass \
property of satellite kg*);
r0 = 6.371*10^6;(*Earth radius 6371km*)
vθ =
 1.3*7.9*10^3;(*First cosmic speed of near earth satellite 7.9km/s*)

vr = 0;

(*ε=1.2;
p=0.5;*)
L = m*r0*vθ;(*Initial angular momentum of satellite*)

\[DoubleStruckCapitalE] =
 1/2 m (vr^2 + vθ^2) -
  G*(M*m)/r0;(*Initial total energy of satellite*)
p = L^2/(G*M*m^2);
ε = Sqrt[
  1 + (2 \[DoubleStruckCapitalE]*L^2)/(G^2*M^2*m^3)];
sol = NDSolve[{r'[θ] ==
     r[θ]^2*
      Sqrt[(ε/p)^2 - (1/r[θ] - 1/p)^2],
    r[0] == r0}, r[θ], {θ, 0, 4 Pi}] // FullSimplify
PolarPlot[r[θ] /. First[sol], {θ, 0, 2 Pi}]

What should I do to plot a complete satellite trajectory?
The derivation process used is as follows:

According to the analysis of the actual process, it is likely that when the satellite turns, that is, when x changes to $\pi$, the radial velocity will switch to 0, which leads to the difficulty of solution.

A: Your ODE is stiff. There is a limit of 10,000 steps build in NDSolve and it reached that at Pi. You can see that from the output

Notice the upper limit is 3.16 and not 2 Pi which is 6.28319
You can improve this by using Method -> "StiffnessSwitching"
sol = NDSolve[{r'[θ] == r[θ]^2*Sqrt[(ε/p)^2 - (1/r[θ] - 1/p)^2], r[0] == r0}, r,
       {θ, 0, 2 Pi},   Method -> "StiffnessSwitching"]

And now it goes to 5.47

  Plot[Abs@Evaluate[r[θ] /. sol], {θ, 0, 2 Pi}]

Noticed also the solution becomes complex near Pi. This tells me may be your ODE is not physically correct. You might want to double check the physics.

A: There is a typical typo here when in equation $r'=r^2\sqrt {…}$ only one branch is used, while there are two branches $r'=\pm r^2\sqrt{…}$. To take both branches into account, we must square the equation and differentiate by $\theta $ , then we obtain
G = 6.672*(10^-11)(*Gravitational constant \
N·m\.b2/kg\.b2*); M =
 5.965*10^24(*The mass property of Earth kg*); m = 10(*The mass \
property of satellite kg*);
r0 = 6.371*10^6;(*Earth radius 6371km*)vθ =
 1.3*7.9*10^3;(*First cosmic speed of near earth satellite \
7.9km/s*)vr = 0;

(*ε=1.2;
p=0.5;*)
L = m*r0*vθ;(*Initial angular momentum of satellite*)\
\[DoubleStruckCapitalE] =
 1/2 m (vr^2 + vθ^2) -
  G*(M*m)/r0;(*Initial total energy of satellite*)p = L^2/(G*M*m^2);
ε =
  Sqrt[1 + (2 \[DoubleStruckCapitalE]*L^2)/(G^2*M^2*m^3)];
sol = NDSolve[{2 r''[θ] ==
     D[r[θ]^4 ((ε/p)^2 - (1/r[θ] -
            1/p)^2), r[θ]], r[0] == r0,
    r'[0] == r0^2*Sqrt[(ε/p)^2 - (1/r0 - 1/p)^2]},
   r[θ], {θ, 0, 4 Pi}] // FullSimplify
PolarPlot[r[θ] /. First[sol], {θ, 0, 2 Pi}]


text:
Q: Use
A: If you put tinyMCE in fullpage mode, you can put styles in the <head>. It will not put the comment node there.
<script type="text/javascript">
tinyMCE.init({
        plugins : "fullpage",
});
</script>

A: The last poster on this thread (http://www.tinymce.com/forum/viewtopic.php?id=25443) writes:

TinyMCE produces XHTML and we wrap the style contents in a comment to
  keep any XML parser from failing to parse the contents all browsers
  support the comment syntax. --Spocke

so the answer is that no, this cannot be changed, because tiny mce not only is sworn to generate valid HTML, but must also generate valid (ughh) XHTML. Since they say all browsers support the comment syntax then it shouldn't really be a problem for you.


text:
Q: Can I tell a function explicitly to not accept pointers to non-heap variables? I've noticed that g++ is smart enough to identify when a function is returning a pointer to a temporary/local variable, e.g.
int *foobar()
{
      int a;
      return &a;
}

Will result in:
 warning: address of local variable 'a' returned

Is there a way that I can define a function prototype to only accept pointers that the compiler can tell are not temporary.  So lets say I have a function
 barfoo(int *a_int);

Is there a way I can tell g++ to complain if someone passes a pointer to a local/temporary object into it?  This would prohibit people from calling barfoo with invalid pointers and potentially save debugging some annoying issues.
Example:
   void barfoo(int *a)
   {
        cerr << a << endl;
   };

   void foobar()
   {
        int a;
        barfoo(&a);
   }

I would like the compiler to complain about the `barfoo(&a)'.

A: You could instruct the compiler to flag that warning as an error. But beware of defining your problem incorrectly. A function that accepts a pointer to a local is valid use case:
int a;
...
do_something (&a);
printf ("%d\n", a);

A: No, it can be totally useful to do what you want to avoid there. GCC/G++ cannot guess that the function taking the reference/pointer will store it somewhere to later reuse, when the original caller of the function has already left the call-stack.

A: You can tell gcc to treat warnings as errors with -Werror option. Or make the specified warning as error -Werror=. 3.8 Options to Request or Suppress Warnings.

A: You might be able to get a compiler set up to treat warnings as errors (as you should anyway!), but I don't believe there's a way to do what you're asking aside from that.

A: I don't think there is any way to get the compiler to enforce it, but you can detect some instances earlier by using malloc_size.
void someFunc(int * mustBeHeap) {
   assert(0!=malloc_size(mustBeHeap));
   //do stuff
}

Unfortunately you will get false positives from code like this:
void someOtherFunc() {
    int * myInts=(int *)malloc(sizeof(int)*20);
    someFunc(&(myInts[3]));
}

It won't work too well with anything allocated with new, boost::pool, etc.  In fact, you will get false positives from just about everything.
Also, malloc_size is non-standard.
Edit:
After looking at one of your comments above about taking ownership, it looks like some of the things I described as false positives are in fact situations you also want to detect since you intended to free the memory from the pointer.

A: Never, ever, use raw pointers in C++ without a good reason. In this case, since you plan on taking ownership of the pointer, accept an object that reflects that. Either auto_ptr \ unique_ptr, if you want sole ownership, or shared_ptr otherwise. If you aren't taking ownership, accept a (possibly const) reference.

A: In c++ you could write a "guaranteed heap pointer" template class that contains a single real pointer inside but has tightly restricted constructors such that the only way to create one was by new. Overload enough operators, and you could have it behave almost like a naked pointer, except that it will have no conversion
from such a pointer.
(I have my doubts about whether that will be worth the trouble, though).


text:
Q: Call a method that requires a derived class instance typed as base class in VB.NET or C# I have two objects - "Spaceship" and "Planet" derived from a base "Obj". I have defined several classes - Circle, Triangle, Rectangle, etc. which all inherit from a "Shape" Class.
For collision detection purposes, I want to give Obj a "shape":
Dim MyShape as Shape

So that in "Spaceship" I can:
MyShape = new Triangle(blah,blah)

and in "Planet" I can:
MyShape = new Circle(blah,blah)

I have a method (overloaded several times) which checks for collisions between different shapes, for example:
public shared overloads function intersects(byval circle1 as circle, byval circle2 as circle) as boolean

AND
public shared overloads function intersects(byval circle as circle, byval Tri as triangle) as boolean

This works fine when I call the function using the derived classes, for example:
dim A as new circle(blah, blah)
dim B as new triangle(blah, blah)
return intersects(A,B)

But when I call it using MyShape, I get an error because the method is being passed a "Shape" (rather than the derived type) which the method does not have an overload for.
I could solve it by doing something like:
Public Function Translate(byval MyShape1 as Shape, byval MyShape2 as Shape )as boolean
if shape1.gettype = gettype(circle) and shape2.gettype=gettype(circle) then ''//do circle-circle detection
if shape1.gettype = gettype(triangle) and shape2.gettype=gettype(circle) then ''//do triangle-circle detection
End Function

But that seems messy. Is there a better way?

A: A way around it is to insert MyActualFunction as a class member.
In Shape:
Public MustOverride Function MyActualFunction()
End Function

In Circle and Triangle:
Public Overrides Function MyActualFunction()
End Function

Then call it like that:
MyShape.MyActualFunction()

and this will know which function to call.

A: Polymorphism can't help you with that therefore you'll have to create a common method with both parameters of type Shape and then distinguish them inside it:
Public Function DoCollide(ByRef shape1 As Shape, ByRef shape2 As Shape) As Boolean
    If TryCast(shape1, Circle) IsNot Nothing And TryCast(shape2, Circle) IsNot Nothing Then
        Return DoCollide(TryCast(shape1, Circle), TryCast(shape2, Circle))
    ElseIf TryCast(shape1, Circle) IsNot Nothing And TryCast(shape2, Triangle) IsNot Nothing Then
        Return DoCollide(TryCast(shape1, Circle), TryCast(shape2, Triangle))
    Else
        Return False
    End If
End Function

I would put this function along with all the specialized implementations doing the actual collision detection in their own class CollisionDetector
Public Class CollisionDetector

    Public Function DoCollide(ByRef shape1 As Shape, ByRef shape2 As Shape) As Boolean
        If TryCast(shape1, Circle) IsNot Nothing And TryCast(shape2, Circle) IsNot Nothing Then
            Return DoCollide(TryCast(shape1, Circle), TryCast(shape2, Circle))
        ElseIf TryCast(shape1, Circle) IsNot Nothing And TryCast(shape2, Triangle) IsNot Nothing Then
            Return DoCollide(TryCast(shape1, Circle), TryCast(shape2, Triangle))
        Else
            Return False
        End If
    End Function

    Public Function DoCollide(ByRef circle1 As Circle, ByRef circle2 As Circle) As Boolean
        Return True
    End Function

    Public Function DoCollide(ByRef circle As Circle, ByRef triangle As Triangle) As Boolean
        Return True
    End Function

End Class


text:
Q: Installing and Linking OpenCV 2.4.3 on 64 bit windows with CMake I am currently attempting to transition a CMake project from Linux to Windows that is dependent on OpenCV, but I'm having trouble linking the libraries to the executable.
I've posted the approximate CMakeLists.txt file below with some private stuff left out:
project(my_project_name)
cmake_minimum_required(VERSION 2.8)

SET(CMAKE_CXX_FLAGS "-g -Wall")
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/../bin)

FIND_PACKAGE(OpenCV REQUIRED)

IF(NOT OpenCV_FOUND)
    MESSAGE(FATAL_ERROR "OpenCV not found")
ENDIF()

SET(PROJECT_HDRS
    #headers here
)

SET(PROJECT_SRCS
    #sources here
)

add_executable(${PROJECT_NAME} ${PROJECT_SRCS})
TARGET_LINK_LIBRARIES(${PROJECT_NAME} ${OpenCV_LIBS})

This CMakeLists.txt file works just fine on Linux, but has trouble linking on Windows. My first instinct was that it was a bad install of OpenCV? Here are the approximate steps I used while installing OpenCV

*

*Download OpenCV 2.4.3 executable (a self-extracting archive)

*Extract to some directory

*Use CMake-Gui to configure and generate OpenCV.sln

*Open in Visual Studio C++ 2010 Express and build the ALL_BUILD project in Debug and Release configurations

*Build the INSTALL project

When I try to build my own project, I get back the errors "undefined reference to 'cv::waitKey(int)' errors, which makes me think that it's a linker issue. I've attempted pointing to the .lib files directly, such as:
target_link_libraries(${PROJECT_NAME} C:/someDirectory/opencv_core243.lib)

but I still get back the same errors.
I've also attempted the methods in described in these StackOverflow threads:
here and here.
I apologize beforehand if I'm missing something obvious, but this is more or less the first time I've developed on windows and I'm running out of ideas.

A: to my knowledge the problem is that visual studio2010 or vc++2010 comes with .net framework 4.5
Downgrade it to .net framework4 (i.e. uninstall .net 4.5 and install 4.0).
That would solve the problem...
I hit my head to my table solving the above problem..
or else
patch the visual c++ with new Service pack

A: it´s a little bit late but... let´s go
for me this tutorial was perfect
http://kevinhughes.ca/tutorials/opencv-install-on-windows-with-codeblocks-and-mingw/


text:
Q: Widget not saved in sidebar (Wordpress) Good evening, everyone. I've got such a task as creating a plugin that will create a widget that performs certain functions. Namely - to display the list of users from the database.
Actually, the problem is that the widget created by the plugin, after updating - disappears from the sidebar.
    <?php

/*
Plugin Name: Название плагина
Plugin URI: http://страница_с_описанием_плагина_и_его_обновлений
Description: Краткое описание плагина.
Version: Номер версии плагина, например: 1.0
Author: Имя автора плагина
Author URI: http://страница_автора_плагина
*/

/**
 * Adds Foo_Widget widget.
 */
class Foo_Widget extends WP_Widget {

    /**
     * Register widget with WordPress.
     */
    function __construct() {
        parent::__construct(
            'foo_widget', // Base ID
            esc_html__( 'Widget Title', 'text_domain' ), // Name
            array( 'description' => esc_html__( 'A Foo Widget', 'text_domain' ), ) // Args
        );
    }

    /**
     * Front-end display of widget.
     *
     * @see WP_Widget::widget()
     *
     * @param array $args     Widget arguments.
     * @param array $instance Saved values from database.
     */
    public function widget( $args, $instance ) {
        echo $args['before_widget'];
        if ( ! empty( $instance['title'] ) ) {
            echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
        }
        echo esc_html__( 'Hello, World!', 'text_domain' );
        echo $args['after_widget'];
    }

    /**
     * Back-end widget form.
     *
     * @see WP_Widget::form()
     *
     * @param array $instance Previously saved values from database.
     */
    public function form( $instance ) {
        $title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'New title', 'text_domain' );
        ?>

        <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_attr_e( 'Title:', 'text_domain' ); ?>
        <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">

        <?php
    }

    /**
     * Sanitize widget form values as they are saved.
     *
     * @see WP_Widget::update()
     *
     * @param array $new_instance Values just sent to be saved.
     * @param array $old_instance Previously saved values from database.
     *
     * @return array Updated safe values to be saved.
     */
    public function update( $new_instance, $old_instance ) {
        $instance = array();
        $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';

        return $instance;
    }

} // class Foo_Widget

// register Foo_Widget widget
function register_foo_widget() {
    register_widget( 'Foo_Widget' );
}
add_action( 'widgets_init', 'register_foo_widget' );

?>

There is still such a point that if you put the standard widget creation code inside the plugin, it will save everything
<?php

    /*
    Plugin Name: Название плагина
    Plugin URI: http://страница_с_описанием_плагина_и_его_обновлений
    Description: Краткое описание плагина.
    Version: Номер версии плагина, например: 1.0
    Author: Имя автора плагина
    Author URI: http://страница_автора_плагина
    */

    /
     * Adds Foo_Widget widget.
     */
    class Foo_Widget extends WP_Widget {

  /
   * Register widget with WordPress.
   */
  function __construct() {
    parent::__construct(
      'foo_widget', // Base ID
      esc_html__( 'Widget Title', 'text_domain' ), // Name
      array( 'description' => esc_html__( 'A Foo Widget', 'text_domain' ), ) // Args
    );
  }

  /
   * Front-end display of widget.
   *
   * @see WP_Widget::widget()
   *
   * @param array $args     Widget arguments.
   * @param array $instance Saved values from database.
   */
  public function widget( $args, $instance ) {
    echo $args['before_widget'];
    if ( ! empty( $instance['title'] ) ) {
      echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ) . $args['after_title'];
    }
    echo esc_html__( 'Hello, World!', 'text_domain' );
    echo $args['after_widget'];
  }

  /
   * Back-end widget form.
   *
   * @see WP_Widget::form()
   *
   * @param array $instance Previously saved values from database.
   */
  public function form( $instance ) {
    $title = ! empty( $instance['title'] ) ? $instance['title'] : esc_html__( 'New title', 'text_domain' );
    ?>

    <label for="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>"><?php esc_attr_e( 'Title:', 'text_domain' ); ?>
    <input class="widefat" id="<?php echo esc_attr( $this->get_field_id( 'title' ) ); ?>" name="<?php echo esc_attr( $this->get_field_name( 'title' ) ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">

    <?php
  }

  /
   * Sanitize widget form values as they are saved.
   *
   * @see WP_Widget::update()
   *
   * @param array $new_instance Values just sent to be saved.
   * @param array $old_instance Previously saved values from database.
   *
   * @return array Updated safe values to be saved.
   */
  public function update( $new_instance, $old_instance ) {
    $instance = array();
    $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? sanitize_text_field( $new_instance['title'] ) : '';

    return $instance;
  }

    } // class Foo_Widget

    // register Foo_Widget widget
    function register_foo_widget() {
        register_widget( 'Foo_Widget' );
    }
    add_action( 'widgets_init', 'register_foo_widget' );

    ?>

That is, it does not save only if there is a custom PhnP code.
And in case if you put the dummy and rewrite it with custom, it will be saved until the first change of theme or deactivation of the plugin.
Can you point to errors in my code?
Thank you for your attention.


text:
Q: Using PS and TTY
I execute on a different shell 'sleep 600'. I open a different terminal and I executed 'ps' to see my current process , however , I dint see any sleep process. I don't know why i couldn't see it and  Why is that , different terminals contained different PID and PTS if the command is the same on both (ps) ?

A: Straight from man ps:
By default, ps selects all processes with the same effective user ID
(euid=EUID) as the current user and associated with the same terminal
as the invoker.

To see all your processes, you'll need something like ps -ef | grep <userid>.


text:
Q: Angular Chain HTTP is causing errors I am trying the following code in an angular.js application to migrate data from one database to another.  This is one part of the function in order to gain authorization credentials to send POSTs to the receiving database.  However, it doesn't work.  My first function, ATsintegrationsService.beginBackfill(clientIDs), returns the list of applicants fine.  The error begins at getAuthToken().  Even though it hits the URL with the correct data, I keep on getting an error in the service.  Can anyone shed some light on what is going on here, I'd really appreciate it.  I'm at a loss for what may be causing my issues.
Main function (triggered by hitting an apply button):
$scope.beginBackfill = function() {
    $scope.loading = true;
    AtsintegrationsService.beginBackfill($scope.clientids).then(function (response) {
       $scope.applicants = response.data;
       $scope.getAuthToken();
       $scope.createSuccess = true;
       $scope.loading = false;
     },
       function(error) {
          $scope.loading = false;
          $scope.createFailure = true;
          console.log("Failure to backfill data - " + error);
       });
   };

Here is $scope.getAuthToken():
$scope.getAuthToken = function() {
    AtsintegrationsService.getAuthToken().then(function (response) {
        $scope.authToken = response.data;
        console.log($scope.authToken);
    },
    function(error) {
        $scope.loading = false;
        $scope.createFailure = true;
        console.log("Failure to obtain auth token - " + error);
        console.log(error);
    });
};

And finally, the service code for getAuthToken() - some data has been removed and is indicated by {snip}.
srvc.getAuthToken = function () {
var url = {snip};

return $http({
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    },
    responseType: 'json',
    method: 'POST',
    url: url,
    data:
    {
        "grant_type": "{snip}",
        "client_id": {snip},
        "client_secret": "{snip}"
    }
})
  .success(function (data) {
    console.log("We have a proper return.");
    return data;
  })
  .error(function (data) {
    console.log("There was an error in the service.");
    return data;
  });
 };

A: We figured out the problem was with CORS headers; the code I have was fine.


text:
Q: Vendoring package which resides in another project's vendor folder I'm writing a library package which depends on certain imports but I'm not sure how to handle it correctly.
Let me start with the directory structure:
go/src/github.com/
├── developer A/
│   ├── project 1
│   └── project 2
│
└── developer B/
    └── project 3
        └── vendor
            └── project 4

Project 1 is a library. It is used in project 2 and gets pulled into 2s vendor folder. Therefore, project 1 should contain all its dependencies such that clients (e.g. project 2) don't need to pull them as well. However, one dependency of project 1 is project 4 which is contained in project 3s vendor folder. It is essential that this dependency is always exactly the version vendored by project 3. Go doesn't allow imports to point to packages inside vendor folders, so I can't import it directly from there. How do I solve this with govendor?

A: Go won't let you reach into another project's vendor directory. It sounds like your intention is to ensure versions. This is what go modules are tasked to do. Take a look at the wiki for more information.


text:
Q: Why is mysqli_query() breaking? [mysqli_query(): Couldn't fetch mysqli] Mysqli_query is contained in the following encapsulating function in my code:
function QueryDatabase($query){
error_log("Database Line 134: " . memory_get_usage(true));
$QueryResult = NULL;

    switch($this->RDBType){
        case 'MySQL':
            error_log('MySQLi link IS Valid?:'); error_log(boolval($this->link));
            error_log(get_class($this->link));
            error_log("Database Line 139: " . memory_get_usage(true));
            error_log("Performing Query: '" . $query . "'");
            $QueryResult = mysqli_query($this->link, $query);
            error_log("Result: " . gettype($QueryResult));
            error_log("Database Line 141: " . memory_get_usage(true));
            break;
        case 'PostGreSQL':
        default:
            break;
    }
error_log("Database Line 147: " . memory_get_usage(true));
return $QueryResult;
}

The PHP error log looks like this:

[11-May-2016 17:04:00 Europe/Berlin] Database Line 134: 262144
[11-May-2016 17:04:00 Europe/Berlin] MySQLi link IS Valid?:
[11-May-2016 17:04:00 Europe/Berlin] 1
[11-May-2016 17:04:00 Europe/Berlin] mysqli
[11-May-2016 17:04:00 Europe/Berlin] Database Line 139: 262144
[11-May-2016 17:04:00 Europe/Berlin] Performing Query: 'SELECT * FROM
  scans
              INNER JOIN landlot
                  on scans.scansId = landlot.scansId
              INNER JOIN district
                  on scans.scansid = district.scansId
              INNER JOIN streetname
                   on scans.scansid = streetname.scansId WHERE Lot = 1;'
[11-May-2016 17:04:00 Europe/Berlin] PHP Warning:  mysqli_query():
  Couldn't fetch mysqli in
  I:\xampp\htdocs\GLS_DBSearchProject\Database.php on line 145
[11-May-2016 17:04:00 Europe/Berlin] Result: NULL
[11-May-2016 17:04:00 Europe/Berlin] Database Line 141: 262144
[11-May-2016 17:04:00 Europe/Berlin] Database Line 147: 262144
[11-May-2016 17:04:00 Europe/Berlin] PHP Notice:  Trying to get
  property of non-object in
  I:\xampp\htdocs\GLS_DBSearchProject\DatabaseSearch.php on line 86
[11-May-2016 17:04:00 Europe/Berlin] Database Line 134: 262144
[11-May-2016 17:04:00 Europe/Berlin] MySQLi link IS Valid?:
[11-May-2016 17:04:00 Europe/Berlin] 1
[11-May-2016 17:04:00 Europe/Berlin] mysqli
[11-May-2016 17:04:00 Europe/Berlin] Database Line 139: 262144
[11-May-2016 17:04:00 Europe/Berlin] Performing Query: 'SELECT * FROM
  scans
              INNER JOIN landlot
                  on scans.scansId = landlot.scansId
              INNER JOIN district
                  on scans.scansid = district.scansId
              INNER JOIN streetname
                   on scans.scansid = streetname.scansId WHERE Lot = 1 LIMIT 10 OFFSET 0;'
[11-May-2016 17:04:00 Europe/Berlin] PHP Warning:  mysqli_query():
  Couldn't fetch mysqli in
  I:\xampp\htdocs\GLS_DBSearchProject\Database.php on line 145
[11-May-2016 17:04:00 Europe/Berlin] Result: NULL
[11-May-2016 17:04:00 Europe/Berlin] Database Line 141: 262144
[11-May-2016 17:04:00 Europe/Berlin] Database Line 147: 262144
[11-May-2016 17:04:00 Europe/Berlin] PHP Fatal error:  Call to a
  member function fetch_assoc() on a non-object in
  I:\xampp\htdocs\GLS_DBSearchProject\DatabaseSearch.php on line 126

I'm really confused as to why mysqli_query is failing to return a result. I have used my QueryDatabase() function numerous times throughout my project and have encountered no issues until now. I have a PHPUnit test which shows that my QueryDatabase() function appears to be working properly, and all other signs point to the problem occurring during the mysqli_query() function call.
I have extensively checked to make sure that the database link (the mysqli object contained within $this->link) is valid and points to the appropriate database. I have also checked to ensure that my query works as expected by manually copying and pasting it into the mysql query browser.
If my query is valid AND my database link is valid why could mysqli_query() be failing?
Edit: I never closed any of my database connections. So the database connection should not be closed

A: There is nothing wrong with your logs.
A live mysqli instance doesn't mean there is a live mysql connection. Unlike PDO, you can close mysql connection but have a mysqli object all right. So the error message says:
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn = new mysqli('localhost','root','','test');
$conn->query("SELECT 1");
$conn->close();
var_dump(get_class($conn));
$conn->query("SELECT 1");

will give you expected output:

string(6) "mysqli"
  Warning: mysqli::query(): Couldn't fetch mysqli in mysqli.php on line 10

You have to find the place where your code is closing connection and fix it.


text:
Q: Profiling Camel routes using JConsole I have an application consisting of number of Camel routes; I would need to profile them using JConsole. I have noticed upon bringing up the JConsole and selecting the local JVM that is running these Camel routes; various MBeans under domain name org.apache.camel is displaying information about such as End points, Processors, Routes etc. Note: I did not setup any instructions given on the link Camel JMX
I would like to know how would these instructions differ in the information display in the later case?

A:
By default, JMX instrumentation agent is enabled in Camel which means that Camel runtime creates and registers MBean management objects with a MBeanServer instance in the VM. This allows Camel users instantly obtain insights into how Camel routes perform down to the individual processor's level.
The supported types of management objects are endpoint , route, service, and processor. Some of these management objects also expose lifecycle operations in addition to performance counter attributes.

The other link you referenced describes how to programmatically create listeners for JMX events...


text:
Q: Angular + Bazel + Socket.IO: TypeError: decodePacket is not a function Issue
I want to user Socket.IO with my Angular application. I build and run the app with Bazel.
However there is an error in the browser console when running the dev server. Note that running the prod server works fine.
I think that the error is caused by node_modules/engine.io-client/lib/transport.js line 95.
onData(data) {
  const packet = parser.decodePacket(data, this.socket.binaryType);
  this.onPacket(packet);
}

That's most likey because parser, which is imported from engine.io-parser doesn't use the browser libs. So we probably need to patch it in such a way that it uses the browser libs.
The actual error in the console is:
ERROR TypeError: decodePacket is not a function
    at Object.decodePayload (ts_scripts.js?v=89114305:17072)
    at XHR.onData (ts_scripts.js?v=89114305:15937)
    at Request.<anonymous> (ts_scripts.js?v=89114305:15559)
    at Request.Emitter.emit (ts_scripts.js?v=89114305:14385)

Minimal Reproduction
You can try it yourself here: flolu/angular-bazel-socketio3-issue
Dev
yarn client:dev
yarn server:dev

throws error in browser console
Prod
yarn client:prod
yarn server:prod

works fine

A: This engine.io-parser+4.0.1.patch patch fixed it
diff --git a/node_modules/engine.io-parser/lib/index.js b/node_modules/engine.io-parser/lib/index.js
index a412b46..b9f7d50 100644
--- a/node_modules/engine.io-parser/lib/index.js
+++ b/node_modules/engine.io-parser/lib/index.js
@@ -1,5 +1,5 @@
-const encodePacket = require("./encodePacket");
-const decodePacket = require("./decodePacket");
+const encodePacket = require("./encodePacket.browser");
+const decodePacket = require("./decodePacket.browser");

 const SEPARATOR = String.fromCharCode(30); // see https://en.wikipedia.org/wiki/Delimiter#ASCII_delimited_text

Thanks to Ramil
See this commit for more information


text:
Q: iOS-Chart : Increasing bar width in grouped sets of BarChartView I'm trying to increase the bar width in chartBarView .
there is my code :
let groupSpace = 0.01
let barSpace = 0.01
let barWidth = 0.32
// (0.32 + 0.01) * 3 + 0.01 = 1.00

let groupCount = 9
let startMonth = 0

chartData.barWidth = barWidth;
barChartView.xAxis.axisMinimum = Double(startMonth)
let spaceIndividualBar = chartData.groupWidth(groupSpace: groupSpace, barSpace: barSpace)
print("spaceIndividualBar must be equan to 1 : \(spaceIndividualBar)")
barChartView.xAxis.axisMaximum = Double(startMonth) + spaceIndividualBar * Double(groupCount)

chartData.groupBars(fromX: Double(startMonth), groupSpace: groupSpace, barSpace: barSpace)

I want to double the width of the individual bars than this result :

A: Decrease the space between two bar its increase the bar Width.


text:
Q: ListBoxItem animation with delay I want to play an animation with delay on each of the dynamically generated listbox items for example:

*

*Item[0] -> animation duration from 0 to 2 seconds.

*Item[1] -> animation duration from 0.5 to 2.5 seconds.

*Item[2] -> animation duration from 1 to 3 seconds.

and so on...(Here delay is 0.5 seconds).
How can I manage to do this?? Thanks.


text:
Q: Enable multithreaded BLAS/LAPACK in NumPy @ macOS BigSur 12.1 I would like to enable a multithreaded BLAS/LAPACK backend for Python's (v3.9.9) NumPy on my macOS BigSur (v12.1). When I run my NumPy code, I see in htop, that only one python process is running and the core utilisation is 20–25%. I remember in the past, stock MacPorts NumPy installation would use Apple's Accelerate library including the multithreaded BLAS and LAPACK. As I understand this is no longer the case.
I run Python code using a virtual environment located under
/opt/venv/zipfstime/lib/python3.9/site-packages/numpy/core

When I change there and issue
otool -L _multiarray_umath.cpython-39-darwin.so

_multiarray_umath.cpython-39-darwin.so:
@loader_path/../.dylibs/libopenblas.0.dylib (compatibility version 0.0.0, current version 0.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1281.100.1)

i.e. NumPy relies on OpenBLAS. Command port variants openblas returns
OpenBLAS has the variants:
  g95: Build using the g95 Fortran compiler
    * conflicts with gcc10 gcc11 gcc8 gcc9 gccdevel
  gcc10: Build using the MacPorts gcc 10 compiler
    * conflicts with g95 g95 gcc11 gcc8 gcc9 gccdevel
[+]gcc11: Build using the MacPorts gcc 11 compiler
    * conflicts with g95 g95 gcc10 gcc8 gcc9 gccdevel
  gcc8: Build using the MacPorts gcc 8 compiler
    * conflicts with g95 g95 gcc10 gcc11 gcc9 gccdevel
  gcc9: Build using the MacPorts gcc 9 compiler
    * conflicts with g95 g95 gcc10 gcc11 gcc8 gccdevel
  gccdevel: Build using the MacPorts gcc devel compiler
    * conflicts with g95 g95 gcc10 gcc11 gcc8 gcc9
[+]lapack: Add Lapack/CLapack support to the library
  native: Force compilation on machine to get fully optimized library
  universal: Build for multiple architectures

I tried installing the "native" variant of OpenBLAS port with sudo port install openblas +native and setting the environment variable OMP_NUM_THREADS=8, but I didn't see any improvement when running my Python code. I would welcome your help and guidance on this subject.


text:
Q: how to display (flash?) messages as to the success/types of failure/errors that occur from passport local strategy authentication I am following a tutorial on node, express, passport, mongo, EJS, and a few other supporting libraries and concepts.  It walks you through the app, the routes, authentication, and strategies.  You end up with all the CRUD operations of an API and a few unassuming HTML pages to sign up, login, and view entries from the DB.  Here are two snippets that work together:
    ```authRouter.route('/signin')
      .post(passport.authenticate('local', {
        successRedirect: '/',
        failureRedirect: '/auth/signin'
      }));```

and (true to the documentation) code in the local strategy:
    ```if(user) {
      done(null, user);
    } else {
      done(null, false)
    }
  } catch (error) {
    done(error, false);```

...that almost literally doesn't do much more than defining the three states a local strategy can produce:  success, failure, and error.  This actually works.  I tested it.  If the user is in the database (and the password checking not shown here passes)...or not...or an exception arises, debugging or developer tools reveal that each of these 3 states occur.  But the only difference you'd see is the redirection that occurs from the options/settings in the second parameter of authenticate.
But a user needs to know more than he/she has just been taken back to the home page or is staying at the login page.  Yes, some of those signatures have overrides or are even open-ended.  You could pass back messages you'd like to the user to see or whole objects that could be the fodder for those messages.  The local strategy snippet could look like this:
    ```if ( user ) {
      done(null, user, { message: `You are logged in.  Welcome back ${user.name}.` } );
    } else {
      done(null, false, { message: 'Invalid username/password combination.' } );
    }
  } catch (error) {
    done(error, false, { message: error } );```

and the authRouter could be as sophisticated as:
```authRouter.route('/signin')
  .post(
    passport.authenticate(
      'local',
      {
        successRedirect: '/',
        successMessage: true,
        successFlash: true,
        failureRedirect: '/auth/signin',
        failureMessage:  true,
        failureFlash: true
      },
      function (err, user, msg) {
        try {
          if (err) {
            //?
          } else {
            if (user) {
              //?
            }```

(extra options that don't seem to have an effect and aren't documented very well by passport or blogs/help sites AND a custom callback) but I am still left with the conundrum of what to do with those "//?"s up there.  As far as I know, this is normally where you'd put your res.render or res.redirect and pass extra info to the view that can be picked up with conditional ejs <% ... %>s.  But there is no res or reqs to be had or next()s.  Some sites even want you to install express-flash.  That is supposed to make "messages.error" show up in your <% ... %> checks, but it doesn't.
I just want a little note that ultimately is based on the decision/return values of the local strategy to be able to be bubbled up via the router and get to the HTML page somehow.  I would triple this post length if I included all the googling and demo/example/tutorial reading I've logged.  But this is a basic boilerplate function, right?  All (basic or good) websites have this:  little messages that let you know if you've logged in successfully or if you need to keep trying for some reason or another?  Please smart people of StackOverflow, you're my only hope!


text: Q: Хранение файлов в базе данных На данный момент у меня в программе реализована возможность обмена сообщениями между студентами и преподавателями, где я просто использую заголовок, дату, имя отправителя и само сообщение. Хотел бы попробовать добавить возможность перетаскивать файлы в поле для написания сообщения и тем самым отправлять их вместе с текстом. Поскольку сообщения хранятся в базе данных, следовательно, сами файлы так же придется хранить в ней, однако я не знаю, возможно ли это в принципе и если да, то как это стоит делать)


text:
Q: What is the largest sigma-field on R ? And also what is borel sigma field? I take taking an introductory course on probability and stochastic processes and want to understand the sigma field on R.
What is the largest sigma-field on R ? And also what is the Borel sigma field?
Omega (Sample Space) = R
F' = {phi, omega, (a,inf), (a,b], (-inf,a), [a,inf), (a,b), [a,b], [a,b), {a} }
Is F' a borel sigma field?
Please help.

A: What do you mean by largest? One that contains most sets? Well, you can take the power set of $\mathbb{R}$, it is a sigma field. (though a not so interesting one, it contains way too many sets, so it's difficult to define an interesting measure on it)
As for Borel sigma field, this is the smallest sigma field which contains all the open subsets of $\mathbb{R}$. A formal definition-the intersection of all sigma fields on $\mathbb{R}$ which contain all the open sets. (it is easy to check that any intersection of sigma fields is also a sigma field). Now this is really an important sigma field-it isn't too large but still contains all the "good sets".


text:
Q: VBA to run 500 line query won't run I am trying to write vba code that includes running a query and pasting the results into excel. I have done this many times in the past, but all with just one line queries. I am trying to do it with a 500 line query and I am getting errors due to the line breaks
I have already tried doing line breaks and carriage returns, but I am obviously way over the line break maximum
previously my final code would look like
finalquery = " SELECT * from tbl1 with (nolock) where column1 (" & finalresult & ")"

Now I have a really long query and iIwant to do this with and am not sure how to

A: I'm not sure that I have ever seen a query that long and think you could run into trouble!  But you could do...
finalquery +"This is the first " & _
            "part of my query "
finalquery = finalquery  & "This is the second " & _
            "part of my query"
finalquery = finalquery  & "This is the third" & _
            "part of my query"

etc.

A: There's a maximum number of physical lines a VBA logical line of code can span; that maximum is around 20, but generally speaking you should avoid such long instructions in code.
The SQL statement is a string literal, and thus can't easily be debugged or maintained.
Make a parameterized stored procedure on the server, and you won't need to concatenate anything.


text:
Q: Midedlware class is not working in Laravel 5.3 I have a laravel application in this application i have following function for login user
     public function login() {
    try {
        $inputs = Input::except('_token');
        $validator = Validator::make($inputs, User::$login);
        if ($validator->fails()) {
            return Redirect::to('/')->with('message', 'Please Enter Valid Credentials');
        } else {
            $respones = \UserHelper::processLogin($inputs);
            if ($respones) {

                return Redirect::to('/dashboard')->with('success_message', 'Welcome to Tressly Admin Dashboard');
            } else {
                return Redirect::to('/')->with('message', 'Please Enter Valid Information ');
            }
        }
    } catch (Exception $ex) {
        return CommonHelper::AdminExceptions($ex);
    }
}

Now as user logout and presses the back button , browser show previous page as it is present in cache. Now on this page as user tries to access any protected route application It shows following error
I want to redirect it to '/'( home route)as logged out user tries to acess any protect routes following error comes
   Class App\Illuminate\Auth\Middleware\AdminAuthenticate does not exist

I have made a custom Authentication Middle , handle function of the middleware is
      public function handle($request, Closure $next, $guard = null) {
    if (Auth::check()) {
        return $next($request);
    }
    return redirect('/');
}

I have also registered it in kernal.php in $routeMiddleware like
   'authAdmin' => \Illuminate\Auth\Middleware\AdminAuthenticate::class,

and protected my route like
  Route::group(['middleware' => 'authAdmin'], function () {
      ///routes
   });

Any ideas ?

A: use
    'authAdmin' => \App\Http\Middleware\AdminAuthenticate::class,

Instead of
   'authAdmin' =>\Illuminate\Auth\Middleware\AdminAuthenticate::class,

I hope it it will work

A: Is there a reason you made a custom middleware class that does exactly the same thing as the already present 'auth' middleware?
RedirectifAuthenticated.php does this;
public function handle($request, Closure $next, $guard = null)
{
    if (Auth::guard($guard)->check()) {
        return redirect('/home');
    }

    return $next($request);
}

https://laravel.com/docs/5.3/authentication#protecting-routes


text:
Q: Python: creating empty lists within empty lists? EDIT: so I figured out that if I declare this at the beginning it works fine:
RelayPlaceHolder = [[],[],[],[],[],[],[],[],[]]

Why can't something like this create the same sort of empty containers? the number of empty lists might change:
for SwimTeams in SwimTeamList:
                empty = []
                RelayPlaceHolder.append(empty)

this was my old question...

I have a list of lists of further lists of single dictionaries:
TeamAgeGroupGender[team#][swimmer#][their dictionary with a key such as {"free":19.05}]

I have a loop that for every team in the first level of my lists, it then loops through every swimmer within that team's list, and add's their swim that corresponds to the key value "free" to a new list called RelayPlaceHolder[teamid][***the thing I just added***]
    for SwimTeams in SwimTeamList:
            empty = []
            RelayPlaceHolder.append(empty)
            teamid = SwimTeamList.index(SwimTeams)
            print SwimTeams
            print teamid

            for swimmers in TeamAgeGroupGender[teamid]:
                swimmerID = TeamAgeGroupGender[teamid].index(swimmers)
                RelayPlaceHolder[teamid].append({SwimTeams:TeamAgeGroupGender[teamid][swimmerID]["Free"]})
            print RelayPlaceHolder[teamid][0]

Desired:
RelayPlaceHolder[0][*** list of swims that go with this team#0 ***]
RelayPlaceHolder[1][*** list of swims that go with team#1, ie the next teamid in the loop***]

for some reason, my loop is only adding swims to RelayPlaceHolder[0], even the swims from team#1. I tried using the print to troubleshoot, however, the teamid index and swimteam names are changing just fine from #0 to #1, however, my RelayPlaceHolder[teamid].append is still adding to the #0 list and not the #1. I also know this because a key value from later code is failing to find the correct key in RelayPlaceHolder[1] (because its turning up empty). I'm not sure why my loop is failing. I've used similar structure in other loops...
Thank you.

A: As commented by @doukremt: A concise syntax if you need to define an arbitrary number of lists is:
[[] for i in range(some_number)]

If you need to do it more often, you can implement it in a function:
>>> lists = lambda x: [[] for i in range(x)]
>>> lists(3)
[[], [], []]


text:
Q: Geofencing Algorithm Given the latitude and longitude of a point. How do I get all the readings of latitude and longitude with in a particular radius of that point? Is there any known method to calculate all latitudes and longitudes with in a radius with respect to a given point?

A: This kind of thing can be done efficiently by using an R-Tree

A: That would be a very very large number of lat/longs! For geofencing what you want to do is calculate the distance (as per pythagoras) and decide if you are outside the radius based on the distance from the point.
If you want to take it 1 step further you can calculate the distance from the line intersecting 2 points.
I suggest you have a look at this site for some geometry formulas.

A: It is not possible to get all the lat/long pairs within a 500m radius of a given point (as @Cobusve and I have pointed out) -- there is an infinite number of such pairs.  You have to tell us more precisely what you want.
To help you work things out I suggest you take a map of the area you are interested in, choose a point and draw a circle of radius 500m around it.  That will give you all the points you are after and perhaps suggest why you need to be more clear.
And, in passing, since the distance is only 500 metres I suggest you work out your answer, when you do, in plane geometry and forget the near-sphericity of the Earth.  Any inaccuracies introduced by this simplification will be very very small and it will greatly simplify the mathematics and I am beginning to form the view that this will be useful to you.


text:
Q: Syntax Error(missing operator) in query expression - MS-Access This doesn't produce syntax errors but it gives wrong arguments error:
SELECT left(
  [aname],
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
  IIF(instr([aname], ",") = 0,
    InStr(1,[aname]," ")-1,
    InStr(1,[aname],",")-1)))
&  ","  &

right(
   [aname],
 IIF(instr([aname], " " = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
    IIF(instr([aname], ",") = 0,
      Len(aname)-InStr(1,[aname]," "),
      Len(aname)-InStr(1,[aname],",")))))
 &  " " &

defense_final.middle_initial AS fullname INTO FinalForgottenWithMiddle
FROM FinalForgotten INNER JOIN defense_final ON (right(FinalForgotten.aname,
 IIF(instr([aname], ",") = 0,
 Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname]," "),
 Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname],",")
  )
 )=defense_final.first_name) AND (left(FinalForgotten.aname,
IIF(instr([aname], ",") = 0,
  InStr(1,FinalForgotten.[aname]," ")-1,
  InStr(1,FinalForgotten.[aname],",")-1
    )
)=defense_final.last_name);

So adding the extra arguments I now get syntax error "Missing ), ], or Item in query expression" :
   SELECT left(
  [aname],
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
  IIF(instr([aname], ",") = 0,
    InStr(1,[aname]," ")-1,
    InStr(1,[aname],",")-1)))
&  ","  &

right(
   [aname],
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),
    IIF(instr([aname], ",") = 0,
      Len(aname)-InStr(1,[aname]," "),
      Len(aname)-InStr(1,[aname],","))))
 &  " " &

defense_final.middle_initial AS fullname INTO FinalForgottenWithMiddle
FROM FinalForgotten INNER JOIN defense_final ON

left(FinalForgotten.aname,
   IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
      Len(FinalForgotten.aname),
      IIF(instr([aname], ",") = 0,
        InStr(1,FinalForgotten.[aname]," ")-1,
        InStr(1,FinalForgotten.[aname],",")-1)))

 =defense_final.last_name AND

 right(FinalForgotten.aname,
      IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
      Len(FinalForgotten.aname),
       IIF(instr([aname], ",") = 0,
        Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname]," "),
        Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname],","))))

=defense_final.first_name;

Any workaround?
Thanks for response.

A: line 10
right(

has no corresponding right parenthesis

A: SELECT left( [aname],
 So [aname] is a text field.
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,

If this condition is true you want the length of the Left String to be:
 FinalForgotten.aname,

Which is not an integer. You want:
SELECT left(
  [aname],
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,
   Len(FinalForgotten.aname),

A:  IIF(instr([aname], " " = 0 AND instr([aname], ",") = 0,

on line 12 should be
 IIF(instr([aname], " ") = 0 AND instr([aname], ",") = 0,

A: It would be easier to put that logic into VBA functions so your query looks like this
SELECT GetFullNameWithMiddle([aname]) AS fullname
INTO FinalForgottenWithMiddle
FROM FinalForgotten INNER JOIN defense_final
    ON GetLastName([aname])=defense_final.last_name
    AND GetFirstName([aname])=defense_final.first_name

Since you say you don't want to use VBA, try this instead.  I enclosed every
InStr(x, y) = 0

in parentheses, so
IIf(InStr(x, y) = 0 AND InStr(p, q) = 0, g, h)

becomes
IIf((InStr(x, y) = 0) AND (InStr(p, q) = 0), g, h)

Making that change allowed me to switch into the query design grid, which means that the SQL parser liked it:
SELECT left(
    [aname],
    IIF((instr([aname], " ") = 0) AND (instr([aname], ",") = 0),
    Len(FinalForgotten.aname),
    IIF((instr([aname], ",") = 0),
    InStr(1,[aname]," ")-1,
    InStr(1,[aname],",")-1)))

    &  ","  &

right(
    [aname],
    IIF((instr([aname], " ") = 0) AND (instr([aname], ",") = 0),
    Len(FinalForgotten.aname),
    IIF((instr([aname], ",") = 0),
      Len(aname)-InStr(1,[aname]," "),
      Len(aname)-InStr(1,[aname],","))))

    &  " " &

defense_final.middle_initial AS fullname INTO FinalForgottenWithMiddle
FROM FinalForgotten INNER JOIN defense_final ON

left(FinalForgotten.aname,
    IIF((instr([aname], " ") = 0) AND (instr([aname], ",") = 0),
    Len(FinalForgotten.aname),
    IIF((instr([aname], ",") = 0),
    InStr(1,FinalForgotten.[aname]," ")-1,
    InStr(1,FinalForgotten.[aname],",")-1)))

=defense_final.last_name AND

right(FinalForgotten.aname,
    IIF((instr([aname], " ") = 0) AND (instr([aname], ",") = 0),
    Len(FinalForgotten.aname),
    IIF((instr([aname], ",") = 0),
    Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname]," "),
    Len(FinalForgotten.aname)-InStr(1,FinalForgotten.[aname],","))))

=defense_final.first_name;


text:
Q: Formula to derive angle and radius from Bezier circular curve control points I know the x,y coordinates for the 2 endpoints and the 2 control points for a Bezier circular curve that is less than 180 degrees.  I do not know the radius of the circle or the angle of the curve.  Could someone give me a formula--or two--where I could plug in the 4 sets of coordinates and return the radius and angle?

A: One way ...
Compute the point on the curve at $t=\tfrac12$. If the four control points are $P_0$, $P_1$, $P_2$, $P_3$, then this point is
$$
P_m = \tfrac18 P_0 + \tfrac38 P_1 + \tfrac38 P_2 + \tfrac18 P_3
$$
The three points $P_0$, $P_m$, $P_1$ define a circle whose center and radius you can compute fairly easily. These answers show you how.


text:
Q: Is it a correct / not dangerous / common approach to pass an 'ActiveRecord::Relation' object as a method parameter? I am using Ruby on Rails 3.2.2 and I would like to know if it is a correct / not dangerous / common approach to pass an ActiveRecord::Relation object as a method parameter.
At this time I am planning to use this approach in a scope method of a my model this way:
class Article < ActiveRecord::Base
  def self.with_active_associations(associations, active = nil)
    # associations.class
    # => ActiveRecord::Relation

    case active
    when nil
      scoped
    when 'active'
      with_ids(associations.pluck(:associated_id))
    when 'not_active'
      ...
    else
      ...
    end
  end
end

Note I: I would like to use this approach for performance reasons since the ActiveRecord::Relation is lazy loaded (in my case, if the active parameter value is not active the database is not hit at all).
Note II: the usage of the pluck method may generate an error if I pass as association parameter value an Array instead of an ActiveRecord::Relation.

A: 1) In my opinion it's a sound tradeoff, you lose the ability to send an array as argument but you gain some perfomance. It's not that strange; for example, every time you define a scope you are doing exactly that, a filter than works only on relations and not on arrays.
2) You can always add Enumerable#pluck so the method works transparently with arrays. Of course it won't work if you use more features of relations.
module Enumerable
  def pluck(method, *args)
    map { |x| x.send(method, *args) }
  end
end


text:
Q: Вызов функции класса Как сделать загрузку функций более простой и быстрой?
Необходим такой результат:
AdminController::actionIndex();

Если таких action будет много проблематично подключить каждую функцию.
Не могу сообразить как сделать что-то подобное, чтобы работало  AdminController::{action}{имя Action(например actionIndex, actionLogin)}

A: $action = 'index';
$controller = 'admin';

if(method_exist(ucfirst($controller) . 'Controller', 'action' . ucfirst($action))) {
   call_user_func([
       cfirst($controller) . 'Controller',
       'action' . ucfirst($action)
   ]);
} else {
   header("HTTP/1.0 404 Not Found");
   echo 'Не найдена';
}

Где то так определяем по url какой controller и action запрашивается, смотрим есть ли метод и вызываем.


text:
Q: JSF error al enviar valores al managedbean Buenas tardes, estoy aprendiendo Java EE y entre practica y practica me he encontrado con un error que no puedo resolver, es pero me puedan colaborar para seguir con mi proceso de aprendizaje. El error que me da es el siguiente:

/index.xhtml @23,111 value="#{alumno.nombre}": The class 'videotutoriales.PrimeFaces.alumno' does not have a readable property 'nombre'.

he intentado cambiar las anotaciones pero no se me ocurre que puede estar mal, aquí les dejo parte de mi código:
<?xml version='1.0' encoding='UTF-8' ?>

    <ui:composition template="./plantilla.xhtml">

        <ui:define name="top">

Datos personalizados de alumnos

        </ui:define>

        <ui:define name="content">

            <h:form>

                    <h:panelGrid columns="2">
                        <h:outputLabel for="nombre" value="Nombre " styleClass="requiredLbl"/>
                        <h:inputText id="nombre" label="Nombre" value="#{alumno.nombre}" required="true"/>

                        <h:outputLabel for="primerApellido" value="Primer Apellido"/>
                        <h:inputText id="primerApellido" label="Primer Apellido" value="#{alumno.primerApellido}"/>

                        <h:outputLabel for="segundoApellido" value="Segundo Apellido"/>
                        <h:inputText id="segundoApellido" label="Segundo Apellido" value="#{alumno.segundoApellido}"/>

                        <h:outputLabel for="fechaNacimiento" value="Fecha de Nacimiento"/>

                        <h:panelGroup/>

                    </h:panelGrid>

            </h:form>

        </ui:define>

    </ui:composition>

y el managedbean que estoy usando es solo getter y setter y se los dejo a continuación:
package videotutoriales.PrimeFaces;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

/**
 *
 * @author Ana Sofia
 */
@Named(value = "alumno")
@RequestScoped
public class alumno {

/**
 * Creates a new instance of alumno
 */
public alumno() {
}

private String nombre;
private String primerApellido;
private String segundoApellido;
private Date fechaNacimiento;
private final SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");

public String getFechaNacimiento(){

    String fechaNacimientoFormateada = "";

    if(fechaNacimiento != null){

        fechaNacimientoFormateada = sdf.format(fechaNacimiento);
    }

    return fechaNacimientoFormateada;
}

public void setFechaNacimiento(Date fechaNacimiento){

    this.fechaNacimiento = fechaNacimiento;
}

public String nombre(){

    return nombre;
}

public void setNombre(String nombre){

    this.nombre = nombre;
}

public String getPrimerApellido(){

    return primerApellido;
}

public void setPrimerApellido(String primerApellido){

    this.primerApellido = primerApellido;
}

public String getSegundoApellido(){

    return segundoApellido;
}

public void setSegundoApellido(String segundoApellido){

        this.segundoApellido = segundoApellido;
    }
}

Gracias de antemano.

A: Tienes un error en el método get del atributo nombre. Tienes esto:
public String nombre(){
    return nombre;
}

Y debería ser así:
public String getNombre(){
    return nombre;
}

A: Debes conformar un getter completo, el nombre no tiene un get completo, un get completo es una funcion con get   en este caso public string getNombre(){}


text:
Q: GDB find command error "warning: Unable to access x bytes of target memory at y, halting search" I'm trying to find current flag count in KMines by using gdb. I know that I should look for memory mappings first to avoid non-existent memory locations. So I ran info proc mappings command to see the memory segments. I picked up a random memory gap (0xd27000-0x168b000) from the result and executed the find command like this: find 0x00d27000, 0x0168b000, 10
But I got the warning: Unable to access 1458 bytes of target memory at 0x168aa4f, halting search. error. Although the address 0x168aa4f is between 0xd27000 and 0x168b000, gdb says that it can't access to it. Why does this happen? What can I do to avoid this situation? Or is there a way to ignore unmapped/unaccessible memory locations?
Edit: I tried to set the value of the address 0x168aa4f to 1 and it works, so gdb can actually access that address but gives error when used with the find command. But why?

A: I guess I have solved my own problem, I can't believe how simple the solution was. The only thing I did was to decrease the 2nd parameter's value by one. So the code should be find 0x00d27000, 0x0168afff, 10 because linux allocates the memory by using maps in [x,y) format, so if the line in root/proc/pid/maps says something like this;
01a03000-0222a000 rw-p

The memory allocated includes 0x01a03000 but not 0x0222a000. Hope this silly mistake of mine helps someone :D
Edit: The root of the problem is the algorithm implemented in target.c(gdb's source code I mean) the algorithm reads and searches the memory as chunks at the size of 16000 bytes. So even if the last byte of the chunk is invalid, gdb will throw the entire chunk into the trash and won't even give any proper information about the invalid byte, it only reports the beginning of the current chunk.


text:
Q: Cleaning up Socket.io session data with timers I was thinking about extending the functionality of node.js server running Socket.io which I am currently using to allow a client (iOS app) to communicate with a server, so that it could have persistent session data between connection.
On initial connection the server passes the client a session id which the client will store and pass to the server later on if it reconnects after disconnecting, this would allow the client to resume its session without having to re-provide the server with certain information about its current state (obviously when it comes to actual implementation it will be more secure than this).
I want to make it so that the session eventually expires, so it has a max lifetime or if it hasn't been continued after a certain time it times-out. To do this I was thinking of using timers for each session. Im not actually sure how node.js or javascript timers (setTimeout) work in the background and am concerned that having 1000s of session timers could lead to a lot of memory/cpu usage. Could this be a potential issue, should I have a garbage collector that cycles every minute or so and deletes expired session data? What is the kind of most optimal way in terms of least impact on performance method I can do to accomplish this, or are timers already exactly that?

A: They are used frequently for timeouts, and are very efficient in cpu.
// ten_thousand_timeouts.js
for (var i=0;i<=10000;i++) {
  (function(i){
    setTimeout(function(){
      console.log(i);
    },1000)
  })(i)
}

With 10,000 the results of logs only took .336 seconds and the act of logging it to the console took most of that time.
//bash script
$> time node ten_thousand_timeouts.js
1
...
9999
10000

real    0m1.336s
user    0m0.275s
sys     0m0.146s

I cannot imagine this being an issue for your use case.


text:
Q: Stay logged in while RDP session is over I wasn't able to find answer to my question. Is it possible to use RDP protocol (I am using Windows 8.1) and once I finish with remote control and disconnect from session, last logged user would stay logged in or he would log in automaticly?
I am using teamviewer to remotly controll my PC, even from my bed, but it transfers image data, which makes it slow and in many cases unusable for me (it also has other disadvantages for me but it's not important for my question). I tryed application with RDP protocol on my tablet which works just fine, only bad thing is, that once I disconnect from the session, pc which is beeing controlled is stucked on user login screen, therefore it is unusable for me.
Any ideas?

A: I found a solution and it is really simple as expected. There is a command which disconnects you from remote session and reconnects that session to the remote computer's console. In human language: it closes your RDP session and "route" it to the console of the logged user so the user stays "connected" and there's no need to manually fill the password again. For the info., in RDP settings there is no option for this behaviour. At least not in gpedit.msc.
The "mojo" command:
tscon [SessionID] /dest:console

SessionID can be obtained with this command:
qwinsta

And some links:

*

*info about tscon

*tscon man page

*info how to get session id


text:
Q: on publish feed, facebook 3.0 examples so i followed the tutorial pages in the facebook dev site and i have this code:
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.view.Menu;

        public class MainActivity extends FragmentActivity {

        private MainFragment mainFragment;

        @Override
        public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        // Add the fragment on initial activity setup
        mainFragment = new MainFragment();
        getSupportFragmentManager().beginTransaction()
                .add(android.R.id.content, mainFragment).commit();
    } else {
        // Or set the fragment from restored state info
        mainFragment = (MainFragment) getSupportFragmentManager()
                .findFragmentById(android.R.id.content);
    }
    }

        @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
    }

        }
and this is the fragment class
    import java.util.Arrays;
    import java.util.Collection;
    import java.util.List;

    import org.json.JSONException;
    import org.json.JSONObject;

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.util.Log;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Button;
    import android.widget.Toast;

    import com.facebook.FacebookRequestError;
    import com.facebook.HttpMethod;
    import com.facebook.Request;
    import com.facebook.RequestAsyncTask;
    import com.facebook.Response;
    import com.facebook.Session;
    import com.facebook.SessionState;
    import com.facebook.UiLifecycleHelper;
    import com.facebook.widget.LoginButton;

    public class MainFragment extends Fragment {

    private static final List<String> PERMISSIONS = Arrays.asList("publish_actions");
    private static final String PENDING_PUBLISH_KEY = "pendingPublishReauthorization";
    private boolean pendingPublishReauthorization = false;
    private UiLifecycleHelper uiHelper;
    private Button shareButton;

        private Session.StatusCallback callback = new Session.StatusCallback() {
    @Override
    public void call(Session session, SessionState state,
            Exception exception) {
        onSessionStateChange(session, state, exception);
    }
    };
    protected String TAG;

    @Override
    public void onResume() {
    super.onResume();
    Session session = Session.getActiveSession();
    if (session != null && (session.isOpened() || session.isClosed())) {
        onSessionStateChange(session, session.getState(), null);
    }
    uiHelper.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    uiHelper.onActivityResult(requestCode, resultCode, data);
    }

        @Override
    public void onPause() {
    super.onPause();
    uiHelper.onPause();
    }

    @Override
    public void onDestroy() {
    super.onDestroy();
    uiHelper.onDestroy();
    }

        @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putBoolean(PENDING_PUBLISH_KEY, pendingPublishReauthorization);
        uiHelper.onSaveInstanceState(outState);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    uiHelper = new UiLifecycleHelper(getActivity(), callback);
    uiHelper.onCreate(savedInstanceState);
  }

  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.activity_main, container, false);
    LoginButton authButton = (LoginButton) view.findViewById(R.id.authButton);
    shareButton = (Button) view.findViewById(R.id.shareButton);
    shareButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            publishStory();
        }
    });
    authButton.setFragment(this);

    return view;
  }

  private void onSessionStateChange(Session session, SessionState state,Exception exception) {
    if (state.isOpened()) {
        shareButton.setVisibility(View.VISIBLE);
        if (pendingPublishReauthorization &&
                state.equals(SessionState.OPENED_TOKEN_UPDATED)) {
            pendingPublishReauthorization = false;
            publishStory();
        }

    } else if (state.isClosed()) {
        shareButton.setVisibility(View.INVISIBLE);
    }
}

private void publishStory() {
    Session session = Session.getActiveSession();
    Log.i(TAG,session.toString());
    if (session != null){

        // Check for publish permissions
        List<String> permissions = session.getPermissions();
        if (!isSubsetOf(PERMISSIONS, permissions)) {
            pendingPublishReauthorization = true;
            Session.NewPermissionsRequest newPermissionsRequest = new Session
                    .NewPermissionsRequest(this, PERMISSIONS);
        session.requestNewPublishPermissions(newPermissionsRequest);
            return;
        }

        Bundle postParams = new Bundle();
        postParams.putString("name", "Facebook SDK for Android");
        postParams.putString("caption", "Build great social apps and get more installs.");
        postParams.putString("description", "The Facebook SDK for Android makes it easier and faster to develop Facebook integrated Android apps.");
        postParams.putString("link", "https://developers.facebook.com/android");
        postParams.putString("picture", "https://raw.github.com/fbsamples/ios-3.x-howtos/master/Images/iossdk_logo.png");

        Request.Callback callback= new Request.Callback() {
            public void onCompleted(Response response) {
                JSONObject graphResponse = response
                                           .getGraphObject()
                                           .getInnerJSONObject();
                String postId = null;
                try {
                    postId = graphResponse.getString("id");
                } catch (JSONException e) {
                    Log.i(TAG,
                        "JSON error "+ e.getMessage());
                }
                FacebookRequestError error = response.getError();
                if (error != null) {
                    Toast.makeText(getActivity()
                         .getApplicationContext(),
                         error.getErrorMessage(),
                         Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getActivity()
                             .getApplicationContext(),
                             postId,
                             Toast.LENGTH_LONG).show();
                }
            }
        };

        Request request = new Request(session, "me/feed", postParams,
                              HttpMethod.POST, callback);

        RequestAsyncTask task = new RequestAsyncTask(request);
        task.execute();
    }

}
private boolean isSubsetOf(Collection<String> subset, Collection<String> superset) {
    for (String string : subset) {
        if (!superset.contains(string)) {
            return false;
        }
    }
    return true;
}

}
so i have all the code its mean to work in this two pages
https://developers.facebook.com/docs/howtos/androidsdk/3.0/login-with-facebook/
and
https://developers.facebook.com/docs/howtos/androidsdk/3.0/publish-to-feed/
for some reason i can log in, that is done, but now when i click share it just stays loading forever untill my android device ask me to shut down the application because is frozen, the log cat says facebook.katana is not respoding, so how can i work around this. is something related to permisions in the app dashboard? or what is wrong. i need to know if i did something wrong. before i start again and do it all over again.
Update : after almost 24 hours finally i got the posted message in my wall, so it seems this work after all, but facebook seems unresponsive sometimes.