text:
Q: LNK2019 constructor/destructor using C++ Dll I am developping a C++ DLL with a C wrapper in order to use it in Python and C#. So I create on Visual Studio a project (DLL) to develop and compile it. No problem here. I even can use my DLL on Python without trouble.
But, on Visual, I want to create another project in the same solution as the DLL to test the DLL too.
So I created the second project (Win32 Windows Application), added the .h to the header files, added the link to the .lib file I added in the folder of the test project, but when I try to compile it, I have errors about LNK2019, beginning with the constructor:
error LNK2019: unresolved external symbol "public: __cdecl Projet::Projet(void)" (??Projet@@QEAA@XZ) referenced in function main

DLL = Projet / Test = Projet_Test
Projet.h
#pragma once
#include "Projet_inc.h"

class Projet
{
public:
    Projet();
    ~Projet();

    int multiply(int arg1, int arg2);
    int result;
};

Projet_inc.h
#ifdef PROJET_EXPORTS
#  define EXPORT __declspec(dllexport)
#else
#  define EXPORT __declspec(dllimport)
#endif

#define CALLCONV_API __stdcall

#ifdef __cplusplus
extern "C" // C wrapper
{
#endif

    typedef struct Projet Projet; // make the class opaque to the wrapper

    EXPORT Projet* CALLCONV_API cCreateObject(void);
    EXPORT int CALLCONV_API cMultiply(Projet* pDLLobject, int arg1, int arg2);
#ifdef __cplusplus
}
#endif

Projet.cpp
#include "stdafx.h"
#include "Projet.h"

Projet::Projet() {}
Projet::~Projet() {}

int Projet::multiply(int arg1, int arg2) {
    result = arg1 * arg2;
    return result;
}

Projet* EXPORT CALLCONV_API  cCreateObject(void)
{
    return new Projet();
}

int EXPORT CALLCONV_API  cMultiply(Projet* pDLLtest, int arg1, int arg2)
{
    if (!pDLLtest)
        return 0;
    return pDLLtest->multiply(arg1, arg2);
}

Projet_Test.cpp
// Projet_Test.cpp : définit le point d'entrée pour l'application console.
//

#include "stdafx.h"
#include "Projet.h"

int main()
{
    Projet object;
    return 0;
}

On Visual, I select the test project as startup project for information. And I look a lot of posts on SO but I didn't find the solution for now. Thank you in advance.

A: You need to __declspec(dllexport) all functions that you want to call directly, not just the C ones.
In your example, you should be able to correctly call the C wrapper functions cCreateObject and cMultiply, as those were exported correctly, but you will not be able to call the underlying C++ functions like Projet::Projet() and Projet::~Projet().
You have two ways of solving this: You can change these functions to inline functions and move their implementation to the header. That way, the client project will no longer invoke the code from the DLL for those functions, but instead just compile the inline definitions directly itself. This is obviously not a sensible approach in general. Alternatively, mark your C++ member functions with __declspec(dllexport), just as you did with the C functions.
Note that Visual Studio has a tendency of breaking the C++ ABI between versions, so you need to make sure that the compiler version you used for compiling the dll is compatible with the one you used for compiling the client application. This is not an issue if both parts are compiled with the same Visual Studio version or if you stick with a plain C interface.

A: First, the error about the missing symbol EpsCndCoreDll seems to be out of context here and you should rather be getting a compile error about redefining struct as a class (class Projet).
Probably you need to use something like:
class Projet;
typedef Projet* PProjet;

and use PProject as the opaque handle further on.
You also need to export the Projet class like:
class EXPORT Projet

to be able to instantiate that class by a client or add a factory function that returns a reference.

A: Make sure that you have added the DLL reference to your DLL.


text:
Q: Horizontal webpage in WebKit I'm trying to create a webpage that is simular to "The Horizontal Way." The goal is to make all the container boxes fall horizontally instead of vertically without setting the width of the body.
Bellow is a basic version of my page. I've also played around with the idea of rotating the body 90deg but quickly ran into limitations.
<!DOCTYPE html>

One

Two

Three

I'm not concerned with compatibility in other browsers but it must work in rescent versions of WebKit (Safari 5, Chrome 9, etc.).
edit: While looking at the base stylesheet for webkit I had come across the '-webkit-block-flow' property. I wasn't able to find much information on this, but it might give me the behavior I'm looking for.

A: To me it seems that the most simple solution would be an unordered list with list elements containing body text/content.

A: Using the -webkit-box display type I was able to achieve exactly what I was looking for. I've posted the revised code bellow.
<!DOCTYPE html>

One

Two

Three

redpajama_set_name: RedPajamaStackExchange


text:
Q: Two smooth atlases are smoothly equivalent IFF their corresponding spaces of smooth functions coincide I'm trying to do below exercise from this lecture note, i.e.,

Ex 3.1. Given any two smooth atlases $\mathcal A_1, \mathcal A_2$ on a topological space $M$, we have $\mathcal A_1$ is smoothly equivalent to $\mathcal A_2$ if and only if $\mathcal C^\infty(M, \mathcal A_1) = \mathcal C^\infty(M, \mathcal A_2)$.

I have found a proof here that uses an extension theorem. My proof does not use this theorem and is thus simpler.

Could you check if I made some subtle mistake?

My attempt The direction "$\implies$" is straightforward. Let's prove the reverse. Let $\mathcal C^\infty(M, \mathcal A_1) = \mathcal C^\infty(M, \mathcal A_2)$. We will show that $\mathcal A_1$ is smoothly equivalent to $\mathcal A_2$. Fix charts $f:U \to \mathbb R^m$ in $\mathcal A_1$ and $g:V \to \mathbb R^m$ in $\mathcal A_2$. Let $f = (f_1, \ldots, f_m)$ and $N := U \cap V$. Then $N$ is open in $M$. It suffices to prove that
$$
f_1 \circ g^{-1} : g(N) \to f(N)
$$
is smooth in the usual sense.
Let $\mathcal A_1' := \{h |_{N} : h \in \mathcal A_1\}$ and $\mathcal A_2' := \{h |_{N} : h \in \mathcal A_2\}$. Then $\mathcal A_1', \mathcal A_2'$ are two smooth atlases on the topological space $N$ (endowed with subspace topology). It follows from $\mathcal A_1$ is smoothly equivalent to $\mathcal A_2$ that $\mathcal A'_1$ is smoothly equivalent to $\mathcal A'_2$. By direction "$\implies$", we get $\mathcal C^\infty(N, \mathcal A'_1) = \mathcal C^\infty(N, \mathcal A'_2)$.
Clearly, $f_1 |_N \in \mathcal C^\infty(N, \mathcal A'_1)$. So $f_1 |_N \in \mathcal C^\infty(N, \mathcal A'_2)$. On the other hand, $g|_N \in \mathcal A'_2$. It follows that $f_1 \circ g^{-1} |_{g(N)}$ is smooth. This completes the proof.

A:
It follows from $\mathcal A_1$ is smoothly equivalent to $\mathcal A_2$ that $\mathcal A'_1$ is smoothly equivalent to $\mathcal A'_2$.

You use this line to conclude that $\mathcal{A}_1'$ is smoothly equivalent to $\mathcal{A}_2'$. But you never proved that $\mathcal{A}_1$ is smoothly equivalent to $\mathcal{A}_2$. In fact, the equivalence of $\mathcal{A}_1$ and $\mathcal{A}_2$ is the very thing you're trying to prove. Your reasoning is circular.


text:
Q: setuid flag doesn't change the effective userid Here I have a file called uid_demo.c, which displays the real userid and the effective userid.
#include <stdio.h>

int main() {
    printf("real uid: %d\n", getuid());
    printf("effective uid: %d\n", geteuid());
}

And I ran the following commands:
gcc -o uid_demo uid_demo.c
sudo chown root:root ./uid_demo
sudo chmod u+s ./uid_demo
ls -l uid_demo

Output:
-rwsrwxr-x 1 root root 8712 Jun 29 15:09 uid_demo

When I run the program, it should display my real userid (1000) and the effective userid of 0 (root), as the owner of the file is root and the setuid permission is turned on. However, it displays the following:
real uid: 1000
effective uid: 1000

Any help? Thanks in advance.

A: You are probably running the program on a filesystem that is mounted wit the nosuid flag, thus your setuid bit is not respected.
Move your code to another location on the filesystem that does not have this, or disable the nosuid flag in the mount options for the current filesystem.
The nosuid flag is a security feature.


text:
Q: C++ conditional template type with template functions error I have such piece of code
    namespace bg = boost::geometry;
    typedef typename std::conditional<highDimension,
                                    typename bg::model::point<double, 6, bg::cs::cartesian>,
                                    typename bg::model::point<double, 5, bg::cs::cartesian>>::type point;
    ..........
    point p;
    p.set<0>(0);
    p.set<1>(0);
    p.set<2>(0);
    ..........

GCC show me a lot of errors like "error: invalid operands of types '' and 'int' to binary   'operator<'
      p.set<1>(col.a());" So it just try to 'compare' p.set and 1
The boost class really has template function set, but compiler don't use it as function.
If i make typedef directly from boost type, like typedef bg::model::point<double, 5, bg::cs::cartesian> point; everything works fine.
I just want to select different dimension sizes depending on template argument highDimension. But now I have no idea how to force GCC understand me :)

A: Since highDimension is a template argument, point becomes a dependent type, so you need to write template here:
p.template set<0>(0);

As to why you need template there, read the answer here:

*

*Where and why do I have to put the "template" and "typename" keywords?

BTW, you don't need typename in the arguments:
typedef typename std::conditional<highDimension,
                 bg::model::point<double, 6, bg::cs::cartesian>,
                 bg::model::point<double, 5, bg::cs::cartesian>>::type point;

You could also use using:
using point = typename std::conditional<highDimension,
                 bg::model::point<double, 6, bg::cs::cartesian>,
                 bg::model::point<double, 5, bg::cs::cartesian>>::type;

This looks better from readability point of view (IMHO).
Or you could simply write this:
using point = bg::model::point<double, highDimension?6:5, bg::cs::cartesian>;

Looks even better.


text:
Q: How to configure Serilog MSSqlSink in net core 3 to use a different connection string for each web request? I have a .net core 3.1 multi-tenant Web API application which accesses single-tenant databases.  So each request acts on any one of the n databases.  I have the EF Core DbContext configured such that it resolves the connection string from a claim in the http request, but I do not know the correct approach to have a similar setup for Serilog's MSSqlSink.  Here's the abbreviated DbContext setup to give you an idea of what I'm trying to accomplish:
        services.AddDbContext<MyContext>((serviceProvider, options) =>
        {
            // IHttpContextAccessor enables us to get at the claims
            var httpContext = serviceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
            var httpRequest = httpContext.Request;

            var claim = httpContext.User.Claims.FirstOrDefault(x => x.Type == "MyClaim");
            var customerIdentifier = claim.Value;
            var connectionString = GetConnectionString(customerIdentifier);

            options.UseSqlServer(connectionString);
        });

So far, I've only been able to find examples for setting up Serilog's MSSqlSink with a known single connection string via appsettings or environment variables.


text:
Q: Google App Engine deployment debug "Error Response: [4] Timed out waiting for the app infrastructure to become healthy" In short:
We have web app running at Google App Engine Nodejs runtime, flex environment. Starting 5 days ago all our deployments started to fail with the reason:
ERROR: (gcloud.app.deploy) Error Response: [4] Timed out waiting for the app infrastructure to become healthy.

Full error stack trace:
Updating service [default] (this may take several minutes)...\DEBUG: Operation [apps/PROJECT_ID/operations/45d6fec1-9261-41d2-943a-648976b971ed] not complete. Waiting to retry.
Updating service [default] (this may take several minutes)...-DEBUG: Operation [apps/PROJECT_ID/operations/45d6fec1-9261-41d2-943a-648976b971ed] complete. Result: {
    "metadata": {
        "user": "SOME_EMAIL@mail.com",
        "target": "apps/PROJECT_ID/services/default/versions/release-0-6-3",
        "@type": "type.googleapis.com/google.appengine.v1.OperationMetadataV1",
        "insertTime": "2018-02-19T06:08:56.439Z",
        "method": "google.appengine.v1.Versions.CreateVersion"
    },
    "done": true,
    "name": "apps/PROJECT_ID/operations/45d6fec1-9261-41d2-943a-648976b971ed",
    "error": {
        "message": "Timed out waiting for the app infrastructure to become healthy.",
        "code": 4
    }
}
Updating service [default] (this may take several minutes)...failed.
DEBUG: (gcloud.app.deploy) Error Response: [4] Timed out waiting for the app infrastructure to become healthy.
Traceback (most recent call last):
  File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/calliope/cli.py", line 797, in Execute
    resources = calliope_command.Run(cli=self, args=args)
  File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/calliope/backend.py", line 757, in Run
    resources = command_instance.Run(args)
  File "/usr/lib/google-cloud-sdk/lib/surface/app/deploy.py", line 65, in Run
    parallel_build=False)
  File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/command_lib/app/deploy_util.py", line 588, in RunDeploy
    flex_image_build_option=flex_image_build_option)
  File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/command_lib/app/deploy_util.py", line 394, in Deploy
    extra_config_settings)
  File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/api_lib/app/appengine_api_client.py", line 188, in DeployService
    message=message)
  File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/api_lib/app/operations_util.py", line 246, in WaitForOperation
    sleep_ms=retry_interval)
  File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/api_lib/util/waiter.py", line 266, in WaitFor
    sleep_ms=sleep_ms)
  File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/core/util/retry.py", line 222, in RetryOnResult
    if not should_retry(result, state):
  File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/api_lib/util/waiter.py", line 260, in _IsNotDone
    return not poller.IsDone(operation)
  File "/usr/lib/google-cloud-sdk/lib/googlecloudsdk/api_lib/app/operations_util.py", line 171, in IsDone
    encoding.MessageToPyValue(operation.error)))
OperationError: Error Response: [4] Timed out waiting for the app infrastructure to become healthy.
ERROR: (gcloud.app.deploy) Error Response: [4] Timed out waiting for the app infrastructure to become healthy.

Before that (3 weeks ago) deploys began to be really slow (5-20 minutes).
Info about operation provided by command:
gcloud beta app operations describe OPERATION_ID

gives this:
done: true
error:
  code: 4
  message: Timed out waiting for the app infrastructure to become healthy.
metadata:
  '@type': type.googleapis.com/google.appengine.v1.OperationMetadataV1
  endTime: '2018-02-19T06:36:02.752Z'
  insertTime: '2018-02-19T06:08:56.439Z'
  method: google.appengine.v1.Versions.CreateVersion
  target: apps/PROJECT_ID/services/default/versions/release-0-6-3
  user: SOME_EMAIL@mail.com
name: apps/PROJECT_ID/operations/45d6fec1-9261-41d2-943a-648976b971ed

Any ideas how to get more info about the operation and what actions are performed?
Best,
Alex

A: At the moment of writing I haven't found the way to get more verbose error messages during Google App Engine deployment from CLI at Ubuntu rather than passing verbosity option gcloud app deploy --verbosity=debug or getting more info about the operation with gcloud beta app operations describe OPERATION_ID.
But they found the cause of the problem:
The reason for the Compute Engine VMs never becoming healthy is because your 'In-use IP addresses' quota [1] in the region of your App Engine Flexible application has reached its limit. More here - https://issuetracker.google.com/issues/73583699. And promised to provide better error messages with the next update of the CLI


text:
Q: Strategy for Rest API Authentication and How to Store Tokens on Client Applications I'm setting up a Rest API for both native (mobile apps) and browser-based applications (react etc.). I'm using express.js and passport.js with LocalStrategy and JwtStrategy.
I've researched about this topic and there are a lot of different conversations or tutorials. Most of the tutorials just creates an access token and never talks about how to refresh it. And a lot of others just uses providers like Okta or Auth0. I don't want to reinvent the wheel but I think I should be able to create a simple authentication mechanism.
My current process is like this;
* Create an access and refresh token on login. Return them as response.
* Client stores it. In react I use localStorage to store the tokens.
* Add Authorization: Bearer <access_token> header to requests.
* When the access_token expires, get new tokens by using the current refresh_token.
I'm storing refresh tokens to DB on the server. So, a users can track all of their current sessions or an admin can invoke them when there is a security issue.
After a lot of research I see that there is a big disagreement on either using localStorage to store tokens on the browser, or return tokens as httpOnly cookies.
And when I examined  some popular websites I saw that, websites like Facebook, Github, Youtube, 9gag use cookies to keep you signed in. They don't send an Authorization: Bearer <access_token> header. There are mainly information about UI states in the localStorage. But when you delete the SID cookie, all of them logs you out. Are they using session-based authentication?
When you login to TMDb (the movie database), it sets 2 cookies named as access_token (which is just a JWT) and session. I guess this is an implementation which the server returns the access token and some sort of a "persistance" information (session) as cookies.
Firebase (one of my favorites about this topic) just stores both the access and refresh token to localStorage. It actually uses indexedDB but I've read it falls back to localStorage when it can't use indexedDB.
But OWASP recommends that "browser-based applications should never retrieve a refresh token". I guess this means when the access token is expired, authorization server should be checked to see if there is still a session going on and then a new access token is retrieved. (Silent renew)
The only exception that I've seen is Azure Portal. It sends bearer tokens in the Authorization header. It stores the refresh token in the localStorage. And a lot of "security sensitive" corporations use it to deploy/maintain their applications or databases etc.
So, Firebase and Azure Portal are examples to access/refresh tokens saved to localStorage on the browser. TMDb is an example to getting tokens in httpOnly cookies. And Facebook, Youtube etc. are using some sort of authentication mechanism that I couldn't understand. Cookies and sessions I think?
Returning access and refresh tokens to both native and browser-based applications has a really simple logic and implementation. Storing them in localStorage always felt like it is a big risk. But I didn't want to set cookies for web applications and return JSON response for mobile applications. I felt like they should be the same. And after seeing examples like Firebase and Azure Portal, I don't feel like it is that much wrong.
But is it really safe even if there are a lot of disagreement and articles about this? And even if Firebase and Azure Portal are good examples to this strategy, why are websites like Facebook, 9gag, Youtube mainly use cookies (and sessions I think) for authentication?
I know this is a big topic. I know there may be a lot of different approaches. But I think I need some sort of a cornerstone idea to implement authentication for simple applications.


text:
Q: ssh port forwarding, who has access to localhost? I've done an ssh remote port forwarding:
me@host1.a.com% ssh -R 127.0.0.1:11999:host2.a.com:99 me@host3.b.com
My understanding is that this creates a TCP socket on host3.b.com's localhost port 11999.
I then checked that from host3.b.com I can indeed access the service exposed at host3.b.com's localhost port 11999.
I've also checked that I can login to host3.b.com with a different ssh session (thus creating a new login shell) and can also access the service exposed at host3.b.com's localhost port 11999.  This kind of scares me.  I naively thought I'd get a different loopback interface for each login shell, but apparently not.
My question is: what about other people who can log into host3.b.com like my friend buddy and my enemy aHacker?  Do they get assigned to the same loopback interface that I get when I log into host3.b.com?  Or do they get their own private loopback interfaces and can't see my open port on my host3.b.com's localhost:11999?  Is there a way to make sure that I'm the only user who can access a forwarded port?


text:
Q: Node.js hash updated password Well, i have simple user edit in node,express,mongodb. But i am unable to hash password to bcrypt. In registration works everything allright but that was tutorial...
Here is part of my routes/users.js
Everything is updated but password is not hashed and i dont know what to do.
router.post("/profile", function (req, res) {
  let user = {};

  user.firstname = req.body.firstname;
  user.lastname = req.body.lastname;
  user.email = req.body.email;
  user.password = req.body.password;
  user.password2 = req.body.password2;

  req.checkBody("firstname", "Firstname is required").notEmpty();
  req.checkBody("lastname", "Lastname is required").notEmpty();
  req.checkBody("email", "Email is required").notEmpty();
  req.checkBody("email", "Email is not valid").isEmail();
  req.checkBody("password", "Password is required").notEmpty();
  req
    .checkBody("password", "Password must be longer then 8 chars bitch")
    .len(8, 64);
  req
    .checkBody("password2", "Passwords do not match")
    .equals(req.body.password);

  var errors = req.validationErrors();

  if (errors) {
    res.render("profile", {
      errors: errors
    });

  } else {

  bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(user.password, salt, function(err, hash) {
      user.password = hash;
    });
  });

  let query = {_id:req.user.id}

  User.update(query, user, function(err){
    if(err){
      console.log(err);
      return;
    } else {
      res.redirect('/');
    }
  });
}});

Here is my hasing for registration in models/users.js that i was inspired by.
module.exports.createUser = function(newUser, callback) {
  bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(newUser.password, salt, function(err, hash) {
      newUser.password = hash;
      newUser.save(callback);
    });
  });
};

I will be thankfull for any help.

A: Well after hous its solved.
I just changed it to.
  bcrypt.genSalt(10, function(err, salt) {
    bcrypt.hash(user.password, salt, function(err, hash) {
      user.password = hash;

  let query = {_id:req.user.id}

  User.update(query, user, function(err){
    if(err){
      console.log(err);
      return;
    } else {
      res.redirect('/');
    }
  });
});
  });
}});


text:
Q: ActionBar title weight won't be applied I'm currently trying to set the font weight of my ActionBar title to bold, with the following code, but it isn't working as expected. What am i doing wrong?
<style name="dActionBar" parent="@android:style/Widget.Holo.ActionBar">
        <item name="android:background">#DDDDDD</item>
        <item name="android:textColor">#FFFFFF</item>
        <item name="android:textStyle">bold</item>
        <item name="android:foreground">#000000</item>
    </style>

The background color and so on is working pretty well.

A: not all Android fonts have bold style,for example Chinese words must use setFakeBoldText
        final int actionBarTitle = getResources().getIdentifier("action_bar_title", "id", "android");
        final TextView title = (TextView) getActivity().getWindow().findViewById(actionBarTitle);
        title.getPaint().setFakeBoldText(true);


text:
Q: PHP / preg_replace: Removing multimedia extentions I want strip all multimedia extensions from filename by preg_replace.
Would you help me create pattern for preg_replace?

.m4a .wav .ogg .flac .avi .flv .mov .m3u .mid .webm .mkv
.asf
.mpg .mpeg .mp(INT) .mpg(INT) .mpeg(INT) => mp(?:eg?)(\d+)
.aif AND .aiff       => aif(?:f?)
.3gp AND .3gpp       => 3gp(?:p?)
.wma AND .wmv         => wm(a|v)

<?php
$filename = 'bla.mp3 bla bla.mid.mp3.mp4.mid.mp10.mpeg.mpg.mpg10';
echo preg_replace('/[\.(m4a|wav|ogg|flac|avi|flv|mov|m3u|mid|webm|mkv|asf|wm(a|v)|mp(\d+)|aif(?:f?)|3gp(?:p?))]*$/', '', $filename);
?>

Very thanks for help!

A: try this:
<?php
$filename = 'bla.mp3 bla bla.mid .mp3 .mp4 .mid .mp10 .mpeg .mpg .mpg10';
echo preg_replace('/\.(m4a|wav|ogg|flac|avi|flv|mov|wmv|m3u|mid|wma|webm|mkv|asf|mp\d|aif(?:f?)|3gp(?:p?))*/', '', $filename);
?>

Update:
echo preg_replace('/\.(mpg10|mpeg|mpg|m4a|wav|ogg|flac|avi|flv|mov|wmv|m3u|mid|wma|webm|mkv|asf|mp\d|aif(?:f?)|3gp(?:p?))*/', '', $filename);

A: try this
$filename = 'bla.mp3 bla bla.mid.mp3.mp4.mid.mp10.mpeg.mpg.mpg10';
echo preg_replace('/\.(m4a|wav|ogg|flac|avi|flv|mov|wmv|m3u|mid|wma|webm|mkv|asf|mp(\d+)|aif(?:f?)|3gp(?:p?)|mp(eg(\d+)?|g(\d+)?))/g', '', $filename);

you can check it out here

Edit
echo preg_replace('/\.(m4a|wav|ogg|flac|avi|flv|mov|wmv|m3u|mid|wma|webm|mkv|asf|mp(\d+)|aif(?:f?)|3gp(?:p?)|mpe?g\d*)/g', '', $filename);

you can check it out here

Final Edit
removed handling mp(\d+) and handling mpe?g\d*
and used only mp(e?g)?\d* to handle both cases and that is the simplest it could get -in my humble opinion-
echo preg_replace('/\.(m4a|wav|ogg|flac|avi|flv|mov|wmv|m3u|mid|wma|webm|mkv|asf|aif(?:f?)|3gp(?:p?)|mp(e?g)?\d*)/g', '', $filename);

you can check it out here
author edit
this is the simplified form of it
echo preg_replace('/\.a(if(?:f?)|sf|vi)|fl(ac|v)|m(3u|4a|id|kv|ov|(p(e?g)?\d*))|ogg|w(av|ebm|m(a|v))/g', '', $filename);


text:
Q: Trouble sanitizing an array from input I have trouble sanitizing my array and am hoping someone can take a look!
here is my input:
<input type="text" name="courseno[]" id="courseno" size="12" />

here is my function to sanitize my data:
function sanitizeData ($datastring) {
    if (is_array($datastring)) {
        foreach ($datastring as $indivdata) {
            $indivdata = sanitizeData($indivdata);
        }
    }
    else {
        $datastring=trim($datastring);
        $datastring=htmlspecialchars($datastring);
        $datastring = mysql_real_escape_string($datastring);
        return $datastring;
    }
}

if (isset($_POST['courseno'])) {
    $courseno = sanitizeData($_POST['courseno']);
}

the $courseno data won't post when I try to sanitize the array, while all my other data gets posted.  When I don't sanitize $courseno, the data gets posted to the database just fine.

A: Well, it would help if sanitizeData() returned a value when $datastring is an array.
if (is_array($datastring)) {
    foreach ($datastring as $indivdata) {
        $indivdata = sanitizeData($indivdata);
    }
    // you need to actually return something here
}

A: In your if (is_array($datastring)) test, you assign the output of the sanitizeData call back to $indivData. So if the input contains an array, a real value is never returned. $courseno will be assigned a NULL value. You'd probably want to change it to something along the lines of this:
function sanitizeData ($datastring) {
    if (is_array($datastring)) {
        $result = '';
        foreach ($datastring as $indivdata) {
            $result .= sanitizeData($indivdata);
        }
    return $result;
}
else {
    $datastring=trim($datastring);
    $datastring=htmlspecialchars($datastring);
    $datastring = mysql_real_escape_string($datastring);
    return $datastring;
  }
}

if (isset($_POST['courseno'])){
    $courseno = sanitizeData($_POST['courseno']);
}

A: I think you have put your text box outside the form tag.

A: It is just a variable scope problem.
function sanitizeData ($datastring) {
    // This is needed to hold the value between function calls ...
    static $indivdata = array();

    if (is_array($datastring)) {
       foreach ($datastring as $indivdata) {
          $indivdata[] = sanitizeData($indivdata);
       }
       return $indivdata;
   }
   else {
     $datastring=trim($datastring);
     $datastring=htmlspecialchars($datastring);
     $datastring = mysql_real_escape_string($datastring);

     return $datastring;
     }
  }
 // $courseno will be an array now.
 if (isset($_POST['courseno'])){
       $courseno= sanitizeData($_POST['courseno']);
 }

Unless I missed something at this late hour, it seems your function does not return the data array.
There are a couple of ways to solve this, but the above code should get you in the right track.


text:
Q: Are there some tools to automate the final submission to IEEE? I got a mail from the editor of the IEEE TEC journal where he explains the procedures which are needed to finalize the submission to the journal:

The IEEE requires that you submit the following materials through the "Awaiting Final Files" queue in your Author Center on Manuscript Central:
...
Separate pages for listing figure captions and table captions.
Each figure and table in its own individual file. This includes
sub-figures. Figures should be identified with the figure number in
the file name.  Acceptable file formats are Word, tiff, ppt, excel, ps
and eps.  PNG and JPEG are not acceptable file formats.

This seems like an error-prone process. So I was wondering if there are some tools that would automatically generate the required files.

If there are none, I would like to ask if somebody else has gone through the procedure and if they can clarify some details:

*

*What is meant by "separate pages"? Does this mean a separate file?

*How do I deal with captions that refer to equations or figures or contain citations? Do I copy the cited number as shown in the generated pdf?

*How do I generate a file containing just a table in one of the mentioned formats? Should I use the IEEEtran class with the document containing only a table and then do for example pdf->ps?

*What if my figures are all pdf's? Should I manually convert them to ps, or does pdf "count" as ps?

It would be also helpful if somebody with insider knowledge could explain the editorial process, so that I can better understand the requirements and make everyone's life easier.


text:
Q: How to do IntelliJ android gradle intra module dependencies? I'm comfortable with maven, so gradle doesn't seem like it's a huge jump. But, I cannot figure out how to make intra module dependencies work.
In IntelliJ I created 4 modules like this:
SharedLib1
FooApp
    FooAppLib
    FooAppMain

The dependencies I want are:
FooAppMain -> FooAppLib
FooAppLib -> SharedLib1

In maven all I'd need to do is refer to other things by their group, artifactid, and version. However, none of the build.gradle files generated contain anything that looks like a group or artifactid, so I don't know how to refer modules to each other.
Something like this seems appropriate for the FooAppMain build.gradle file:
compile project(":FooAppLib")

However, that just doesn't work. There are other dependencies like this:
compile 'com.android.support:support-v4:19.1.0'

But again, I don't know where to put the group and artifactid values in the build.gradle so I can refer to them.

A: create a settings.gradle file in the project root and configure the lib project path there.
include ':app', ':FooAppLib'

project(':FooAppLib').projectDir = file('../yourLibProjectRoot/app')

And then in your build.gradle file, add the dependency to this project
compile project(":FooAppLib")


text:
Q: How does ath9k introduce itself to mac80211? My question is about Linux kernel and ath9k wireless driver:

*

*How does ath9k announce itself to the mac80211?

*How come the mac80211 knows how to configure ath9k?

Thanks in advance

A: In the modern kernel, devices are described via the device tree.  The device tree will contain a description of various hardware elements and names of their respective drivers.  When a device matches a device tree entry, the device driver associated with it is alerted.  The device driver then probes the device to test capabilities.
mac80211 is a framework made available for writing wireless drivers.  ath9k is the driver the kernel loads to interface with the card


text:
Q: accordion menu jquery active menu I have accordion menu width JQuery, it works well but I want to keep the selected menu active when I open it: exactly like this: http://www.3ds.com/fr/
This is what I did:
$(function() {
                $('#accordion > li').hover(
                    function () {
                        var $this = $(this);
                        $this.stop().animate({'width':'480px'},500);
                        $('.heading',$this).stop(true,true).fadeOut();
                        $('.bgDescription',$this).stop(true,true).slideDown(500);
                        $('.description',$this).stop(true,true).fadeIn();
                    },
                    function () {
                        var $this = $(this);
                        $this.stop().animate({'width':'115px'},1000);
                        $('.heading',$this).stop(true,true).fadeIn();
                        $('.description',$this).stop(true,true).fadeOut(500);
                        $('.bgDescription',$this).stop(true,true).slideUp(700);
                    }
                );
            });


text:
Q: Airflow - Why is the externalDatabase configuration breaking helm upgrade? I am trying to deploy Airflow using Helm charts, for a personal POC, but I have been facing some issues with the deployment and could not find clear instructions to solve my issue - which is why I am seeking help here.
Context around the issue
A bit of background of the POC first - I want to deploy a K8S cluster that hosts airflow, connect it to a git repo that hosts the dags and has the metastore and cache hosted externally from K8S Airflow.
I have successfully deployed Airflow to a local Kubernetes cluster using kind and Airflow's default helm chart. On the helm chart I have specified that the executor mode to be used must be KubernetesExecutor.
I have also configured Airflow to sync up the DAGs to/from a bitbucket repository.
The issue and current implementation
I am having issues with connecting Airflow with the external services - I have created an Azure PostgreSQL server, created a airflow database, created a admin user on the psql as follows:
CREATE DATABASE airflow;
CREATE USER aflw_admin WITH PASSWORD 'some_password';
GRANT ALL PRIVILEGES ON DATABASE airflow TO aflw_admin;
ALTER USER aflw_admin SET search_path = public;

Since I am using helm to deploy, I have my values.yaml as follows:
postgresql:
  enabled: false

externalDatabase:
  type: postgres
  host: dbname.postgres.database.azure.com
  port: 5432
  database: airflow
  user: aflw_admin
  passwordSecretKey: "postgresql-password"

data:
  metadataSecretName: ~
  resultBackendSecretName: ~

  metadataConnection:
    user: aflw_admin
    pass:  some_password
    protocol: postgresql
    host: dbname.postgres.database.azure.com
    port: 5432
    db: airflow
    sslmode: require

  resultBackendConnection:
    user: aflw_admin
    pass:  some_password
    protocol: postgresql
    host: dbname.postgres.database.azure.com
    port: 5432
    db: airflow
    sslmode: require

The secret postgresql-password was created by the following:
kubectl create secret generic airflow-postgresql --from-literal=postgresql-password=$(openssl rand -base64 13) --namespace airflow

I deployed the solution using:
kubectl apply -f ./helm/variables.yaml
helm upgrade --install airflow apache-airflow/airflow -n airflow -f ./values.yaml --debug

What I have tried and problem details
After some back and forward, I figured out that by reverting the configuration - aka, setting postgresql enabled to true and removing the metadataConnection, resultBackendConnection  and externalDatabase sections from the values.yaml file - I could deploy the postgres service successfully but with the tradeoff that the postgresql is NOT a external service, which helps to at least partially isolate the problem.
So, if I go back to the initial configuration and try to deploy it, the results I get are :

*

*first I get a timeout --> in order to face this issue, I naturally  increased the timeout duration to a bigger value like 20m0s;

*after I increase the timeout I get an error BackoffLimitExceeded and nothing is deployed.

Here's a log of the helm deployment in question:
history.go:56: [debug] getting history for release airflow
upgrade.go:142: [debug] preparing upgrade for airflow
upgrade.go:150: [debug] performing update for airflow
upgrade.go:322: [debug] creating upgraded release for airflow
client.go:218: [debug] checking 20 resources for changes
client.go:501: [debug] Looks like there are no changes for ServiceAccount "airflow-create-user-job"
client.go:501: [debug] Looks like there are no changes for ServiceAccount "airflow-migrate-database-job"
client.go:501: [debug] Looks like there are no changes for ServiceAccount "airflow-scheduler"
client.go:501: [debug] Looks like there are no changes for ServiceAccount "airflow-statsd"
client.go:501: [debug] Looks like there are no changes for ServiceAccount "airflow-triggerer"
client.go:501: [debug] Looks like there are no changes for ServiceAccount "airflow-webserver"
client.go:501: [debug] Looks like there are no changes for ServiceAccount "airflow-worker"
client.go:501: [debug] Looks like there are no changes for Secret "airflow-airflow-metadata"
client.go:501: [debug] Looks like there are no changes for Secret "airflow-webserver-secret-key"
client.go:501: [debug] Looks like there are no changes for ConfigMap "airflow-airflow-config"
client.go:501: [debug] Looks like there are no changes for Role "airflow-pod-launcher-role"
client.go:501: [debug] Looks like there are no changes for Role "airflow-pod-log-reader-role"
client.go:501: [debug] Looks like there are no changes for RoleBinding "airflow-pod-launcher-rolebinding"
client.go:501: [debug] Looks like there are no changes for RoleBinding "airflow-pod-log-reader-rolebinding"
client.go:501: [debug] Looks like there are no changes for Service "airflow-statsd"
client.go:501: [debug] Looks like there are no changes for Service "airflow-webserver"
client.go:510: [debug] Patch Deployment "airflow-scheduler" in namespace airflow
client.go:510: [debug] Patch Deployment "airflow-statsd" in namespace airflow
client.go:510: [debug] Patch Deployment "airflow-triggerer" in namespace airflow
client.go:510: [debug] Patch Deployment "airflow-webserver" in namespace airflow
client.go:267: [debug] Deleting Secret "airflow-postgresql" in namespace airflow...
client.go:270: [debug] Unable to get obj "airflow-postgresql", err: secrets "airflow-postgresql" not found
client.go:267: [debug] Deleting Service "airflow-postgresql-headless" in namespace airflow...
client.go:270: [debug] Unable to get obj "airflow-postgresql-headless", err: services "airflow-postgresql-headless" not found
client.go:267: [debug] Deleting Service "airflow-postgresql" in namespace airflow...
client.go:270: [debug] Unable to get obj "airflow-postgresql", err: services "airflow-postgresql" not found
client.go:267: [debug] Deleting StatefulSet "airflow-postgresql" in namespace airflow...
client.go:270: [debug] Unable to get obj "airflow-postgresql", err: statefulsets.apps "airflow-postgresql" not found
client.go:299: [debug] Starting delete for "airflow-run-airflow-migrations" Job
client.go:128: [debug] creating 1 resource(s)
client.go:529: [debug] Watching for changes to Job airflow-run-airflow-migrations with timeout of 20m0s
client.go:557: [debug] Add/Modify event for airflow-run-airflow-migrations: ADDED
client.go:596: [debug] airflow-run-airflow-migrations: Jobs active: 0, jobs failed: 0, jobs succeeded: 0
client.go:557: [debug] Add/Modify event for airflow-run-airflow-migrations: MODIFIED
client.go:596: [debug] airflow-run-airflow-migrations: Jobs active: 1, jobs failed: 0, jobs succeeded: 0
client.go:557: [debug] Add/Modify event for airflow-run-airflow-migrations: MODIFIED
upgrade.go:433: [debug] warning: Upgrade "airflow" failed: post-upgrade hooks failed: job failed: BackoffLimitExceeded
Error: UPGRADE FAILED: post-upgrade hooks failed: job failed: BackoffLimitExceeded
helm.go:84: [debug] post-upgrade hooks failed: job failed: BackoffLimitExceeded
UPGRADE FAILED
main.newUpgradeCmd.func2
        helm.sh/helm/v3/cmd/helm/upgrade.go:199
github.com/spf13/cobra.(*Command).execute
        github.com/spf13/cobra@v1.3.0/command.go:856
github.com/spf13/cobra.(*Command).ExecuteC
        github.com/spf13/cobra@v1.3.0/command.go:974
github.com/spf13/cobra.(*Command).Execute
        github.com/spf13/cobra@v1.3.0/command.go:902
main.main
        helm.sh/helm/v3/cmd/helm/helm.go:83
runtime.main
        runtime/proc.go:255
runtime.goexit
        runtime/asm_amd64.s:1581
make: *** [Makefile:46: deploy-airflow] Error 1

This behavior leads me to think that it is some sort of configuration error, but I can't pinpoint what.
What can I be misconfiguring in my helm chart that could have broken the helm upgrade?
The versions for helm/airflow/psql are below:

*

*Airflow -> apache/airflow:2.2.3

*Helm chart -> default image with version 1.4.0 (https://artifacthub.io/packages/helm/apache-airflow/airflow)

*PSQL (on azure) -> Azure Database for PostgreSQL flexible server, PSQL version 13.4

A: It's sometimes difficult to diagnose such problems because there are so many moving parts. Although, I have set up Airflow on Azure AKS (Postgres sslmode: require) and AWS EKS (RDS Postgres sslmode: disable), each with their own issues.
Perhaps remove config for externalDatabase and resultBackendConnection. Why? - because resultBackendConnection will use metadataConnection if it is not configured. I haven't seen the externalDatabase key in my current config file v2.2.4. Are you using -f values.yaml to override helm install with the correct values.yaml?
If you disable postgresql
postgresql:
  enabled: false

as you have, then you need to configure metadataConnection for your external database.
I only configured the metadataSecretName once I had the connection to Postgres working properly.
Also, try sslmode: disable in the metadataConnection config.
Once I got the config file the way I wanted it, I un-installed Airflow then re-installed:

*

*helm delete airflow

*dropped airflow db and re-created it

*kubectl delete secrets [airflow-xxxxx-xxxxx] All the secrets in the
namespace, because the db migration didn't work properly inbetween the
errors.

*kubectl delete pvc (then made sure the pv's were also deleted)

After that I re-installed and it was all good, which is not a lot of work, but ensures I can re-deploy with the correct values.
Oh, and do remember to set up PSQL and make sure you can actually connect from your command line as an extra check.


text:
Q: Replace XML string using SQL Server Replace or CLR Regex? I have the following XML string:
<row>
  <id>
    <old></old>
    <new>2151</new>
  </id>
  <name>
    <old></old>
    <new>test</new>
  </name>
  <amount>
    <old></old>
    <new>62</new>
  </amount>
</row>

I need to parse and replace the string so that the end result will have the format:
columnname|oldvalue|newvalue^

Therefore the above example would look like this:
id||2151^name||test^amount||62^

The XML string will always contain one row node. The nodes within it (ig. id, name, amount, etc) will vary and it can range for a couple of nodes to over 100 nodes. The structure will however be always the same.
Is is possible to do it in SQL server directly or do I need to use a CLR function in order to use regular expressions?
The function must be generic because the column names will be different.

A: You can use local-name() to retrieve a node's name:
select  col1.value('local-name(.)', 'varchar(max)') + '|' +
        col1.value('(./old)[1]', 'varchar(max)') + '|' +
        col1.value('(./new)[1]', 'varchar(max)') + '^'
from    @x.nodes('/row/*') as tbl(col1)

-->
id||2151^
name||test^
amount||62^

Example at SQL Fiddle.

A: This should do, if the pattern of the XML is just same and not going to change.
string checkStr1 = @"<row>
    <id>
    <old></old>
    <new>2151</new>
    </id>
    <name>
    <old></old>
    <new>test</new>
    </name>
    <amount>
    <old></old>
    <new>62</new>
    </amount>
</row>";
Regex r1 = new Regex(@"\<([a-z]+)\>(?:\t|\r|\n|\s)*\<old\>(.*?)\<\/old\>(?:\t|\r|\n|\s)*\<new\>(.*?)\<\/new\>(?:\t|\r|\n|\s)*</[a-z]+?>");
MessageBox.Show(r1.Replace(checkStr1, m => "^" + m.Groups[1].Value + "|" + m.Groups[2].Value + "|" + m.Groups[3].Value));

And finally replace the "row" opening and closing tags...
Hope this helps...

A: Try this,
Declare @xml xml='<row>
  <id>
    <old></old>
    <new>2151</new>
  </id>
  <name>
    <old></old>
    <new>test</new>
  </name>
  <amount>
    <old></old>
    <new>62</new>
  </amount>
</row>'

select 'id||'+  xmlData.Col.value('(./id)[1]', 'varchar(MAX)')+'^' +
'name||'+ xmlData.Col.value('(./name)[1]', 'varchar(MAX)')+'^' +
'amount||'+ xmlData.Col.value('(./amount)[1]', 'varchar(MAX)')+'^'
from  @xml.nodes('//row') xmlData(Col)


text:
Q: Columns in data.frame appear empty when using head(data.frame), but when using levels(data.frame$column1) appear to have values I have a large data frame that includes names of sites, their latitude, and the longitude, among other data. When I write head(data.frame), the column with the site names looks correct, but the latitude and longitude columns are empty (there are no values at all in them). However, when I write levels(data.frame$longitude), all of the values for the longitudes of my site appear. The same issue is occurring with latitude.
I am wondering why these values don't appear when I look up the head of the data.frame, but do appear when I look up the level?
Many thanks!

A: levels() returns the levels associated with a factor.  Not all values need to exist.  For example, if you do
x <- factor(letters)
x[1:3]

you'll see
[1] a b c
Levels: a b c d e f g h i j k l m n o p q r s t u v w x y z

because all 26 levels are still associated with the factor, even though only 3 of them are observed.
In your case, it's possible that one of the levels of your factor is a blank string.  You can get this using
x <- factor("", levels = c("", letters))

or by reading in data containing blanks in some columns.
To find out all the values in a column, don't use levels(x), use unique(x).  That will still show all levels if x is a factor, but it will also show which values actually occur in the column.


text:
Q: VOID data type in C If i declare any variable using void, it gives error but sizeof(void) is 1.
What is reason for this?
void var; // it gives error
printf("sizeof(void) = %d", sizeof(void)); //prints 1

A: sizeof (void) is not valid in C and is allowed in GNU C as an extension to allow pointer arithmetic with void *.
From gcc documentation:

In GNU C, addition and subtraction operations are supported on pointers to void and on pointers to functions. This is done by treating the size of a void or of a function as 1. [...]  consequence of this is that sizeof is also allowed on void and on function types, and returns 1.

A: The void type, in several programming languages derived from C and Algol68, is the type for the result of a function that returns normally, but does not provide a result value to its caller. Usually such functions are called for their side effects, such as performing some task or writing to their output parameters.
Upto my knowledge, You cannot use void as datatype, as the value is true or false statement the Boolean value will be 1 by default, so, it prints 1.

A: c.f. Is there a specific reason why "void" was not simply defined as "typedef struct{} void" (i.e. an empty struct) with appropriate casting rules? ...
This was originally suggested by Steve Bourne in AB33/Mar 1972 for Algol68 ...
Note: Algol68 doesn't have pointer arithmetic... but array slicing is available.


text:
Q: How do you pass information from an 8 byte array into variable bit size data containers? I have an 8 byte message where the differing chunks of the message are mapped to datums of different types (int, bool, etc.), and they vary in bit sizes (an int value is 12 bits in the message, etc.).  I want to pass only the bits a datum is concerned with, but I am not sure if there is a better way.  My current thoughts is to make a bit array type with a vector back end and have a templated accessor to get the value contained within to the type specified.  Although as I am typing this I am starting to think a great big union of all the possible types could be passed to each datum.
EDIT:
The messages contain varying types of data.  For example, one message contains an 8-bit int and 5 1-bit bools, while another message contains a 16-bit Timestamped (my own class) and an 8-bit int.

A: Are the messages alway of the same format/order? Ie. 12bitsInt|8bitsChar|etc. If so a simple solution would be to set up appropriate bitmasks to grab each particular value. Ie. if the first 12 bits (low order) corresponded to an integer we could do:
__uint64 Message; // Obviously has data in it.
int IntPortion = Message & 0x00000111;

Which will copy the first 12 bits of the Message into the first 12 bits of your integer type. Set up appropriate bit masks for each chunk of the message and proceed. If the message format is not constant... well I would need you to elaborate maybe with an example message. Also the boost library has some nice bit manipulation classes:
Dynamic Bitset
Might be overkill if the format is constant though.

A: Have you looked at using a struct with explicit member sizes? For example, if you have a message where the field sizes are:

*

*1st field is 12 bits

*2nd field is 20 bits

*3rd field is 4 bits

*...

You could define a struct like:
typedef struct {
  unsigned int field_1 : 12;
  unsigned int field_2 : 20;
  unsigned int field_3 : 4;
  /* etc */
} message_t;

Assuming that you have the message in a simple char array, either copy the data into a message_t struct or cast it to a message_t* :-
char buffer[8] = /* however it's populated */
message_t* message_ptr = &buffer;
int field1 = message->field_1;
int field2 = message->field_2;


text:
Q: Symfony Dynamic class names are not allowed in compile-time I am trying to initialize dynamically a form. The form name is stored in $obj->getFormTypeName().
$formName = 'Acme\testBundle\Form\CustomType\\'.ucfirst($obj->getFormTypeName()).'Type';
$contactForms[$obj->getId()] = $this->createForm($formName::class);

But I get the error : Compile Error: Dynamic class names are not allowed in compile-time ::class fetch
Is there a way to initialize dynamically a form with the Scope Resolution Operator in Symfony ?
Thanks for reading.

A: To get around this issue, I'd do something like:
$contactForms[$obj->getId()] = $this->createForm(
    'Acme\\testBundle\\Form\\CustomType\\' . ucfirst($obj->getFormTypeName()) . 'Type'
);

After all, ::class only returns the fully qualified name of the class.

A: One should not want to call a ::class on a variable, string name of the class eg.
Acme\testBundle\Form\CustomType\FormType like this
'Acme\testBundle\Form\CustomType\'::class, as in the end the string var of the class, it's the classname itself.
Something similar is possible only in Javascript to my knowledge 'stringContents'.val()


text:
Q: A non-rigorous explanation of curvature of curves in 3-space In a second year calculus class there is usually the definition of curvature as $$\kappa=\left|\frac{d\bf{T}}{ds}\right|$$where $\bf{T}\rm(t)=\frac{r^\prime(t)}{|r^\prime(t)|}$ is the unit tangent vector and $s$ is the arc length. The curvature is described as a measure of how quickly the curve changes direction at a point. From the above formula, it is derived that $$\kappa(t)=\frac{\left|\bf{T}\rm^\prime(t)\right|}{\left|r^\prime(t)\right|}$$I am failing to see how either of these two formulas is measuring how quickly the curve changes direction. Taking the derivative with respect to arc-length just completely blows away my intuition. Where-as the ratio of the rate of change of tangent vectors by rate of change of the curve seems more plausible. However, it still isn't clear. How can you even calculate this desired quantity at a specific point, for to know how quickly the curve changes at a point you would need to know what the curve is doing before and/or after that point.
Basically, I am hoping that someone can explain to me, non-rigorously, the geometric intuition of curvature of a curve in $3$-space. From this description, how do we arrive at one of the two formulas?


text:
Q: Number of Prime Implicants VS Essential Prime implicants with don't care So the Prime implicants are those largest square or rectangle made up of bunch of adjacent minterms
Essential Prime implicants are those prime implicants which also cover a particular midterm/s.
But I can't find much definition about when the function has don't care.
This question asks about implicant, but not the essential ones
Let's say we have a function as f(x,y,z)=m(0,1,6,7)
the K-map as:
--------------------------------------------------
| c\ab |      |      |     |     |
--------------------------------------------------
|      |   1  |      |  1  |     |
--------------------------------------------------
|      |   1  |      |  1  |     |
--------------------------------------------------

From the k-map, we can see there are 4 implicants and 2 prime implicants and 2 essential prime implicants, right ?
My questions is: Are don't-cares considered as 1/0 when we counting essential/prime /implicants as well once we mark them as 1/0?
Now we have a similar function as f(x,y,z)=m(0,1,6,7) + d(2,3)
so the k map as:
--------------------------------------------------
| c\ab |      |      |     |     |
--------------------------------------------------
|      |   1  | x(1) |  1  |     |
--------------------------------------------------
|      |   1  | x(1) |  1  |     |
--------------------------------------------------

In this k-map, we have 6 implicants for each one: and 2 prime implicants from
1 x(1)
1 x(1)

of the left and
 x(1) 1
 x(1) 1

Of the right.
and 2 essential prime implicants from those prime implicants.
so 6 implicants and 2 prime implicants and 2 essential prime implicants for  f(x,y,z)=m(0,1,6,7) + d(2,3).


text:
Q: Big-O and function composition On the last page of this document, a property of big-O operations is listed which says that if
$$f_1(n) = O(g_1(n))\text{, and } f_2(n) = O(g_2(n))$$
Then
$$f_1 \circ f_2 = O(g_1 \circ g_2)$$
Why is that?
Trying to get this to a form that resembles the definition I get to:
$$f_1(f_2(n)) = k_1 * g_1(g_2(n))$$
and I'm kind of stuck... I don't see how the big-O definition inequality holds.
UPDATE: We can assume the functions are increasing monotonically.

A: This is false unless you make extra assumptions. Assume that $f_2(x) = 2x$, $g_2(x) = x$. Then $f_2(x) = O(g_2(x))$. Now take $f_1(x) = g_1(x) = e^x$. Then you get $f_1(f_2(x)) = e^{2x}$ and $g_1(g_2(x)) = e^x$, and $e^{2x} \neq O(e^x)$ so there's something wrong.

A: "$f = O(g)$" means that for some $c$ and some $x_0$, $f(x) \leq c\cdot g(x)$ for all $x \geq x_0$.
So, if $f_1 = O(g_1)$ and $f_2 = O(g_2)$, there are $c_1,c_2$ and an $x_0$ with $$
  f_1(x) \leq c_1 g(1) ,\quad f_2(x) \leq c_2g_2(x) \text{ for all $x > x_0$.}
$$
So what, then, can we say about $f_1 \circ f_2$?. We have for every $x > x_0$ that $$
  y = f_2(x) \leq c_2g_2(x)
$$
and therefore $$
  (f_1 \circ f_2)(x) = f_1(y) \leq c_1g_1(y) \text{.}
$$
If we additionally assume that $g$ increases monotonically, then we can replace $y$ with the larger value $c_2g_2(x)$ in that last inequality to get $$
    (f_1 \circ f_2)(x) = f_1(y) \leq c_1g_1(c_2g_2(x)) \text{.}
$$
which implies that $$
  f_1 \circ f_2 = O(g_1 \circ c_2g_2) \text{.}
$$
user2566092's example shows that we cannot, in general, get rid of that factor $c_2$ there. Though if, for example, $g_1(x) = x^n$, then $g_1(c_2g_2(x)) = (c_2g_2(x))^n = c_2^n (g_2(x))^n = O((g_1)^n)$, so for these $g_1$ you indeed have $$
  f_1 \circ f_2 = O(g_1 \circ g_2) \text{.}
$$
The general property that you need for your proposition to hold is thus that $$
  g_1(c\cdot x) = O(g_1(x)) \text{.}
$$


text:
Q: Server sent events work, but with a massive time delay Ill start off by saying this works perfectly on my local machine, the js example below connects to stream.php and receives a continuous update of the servers current time every second.
index.php
var source = new EventSource("stream.php");

source.addEventListener('message', function(e) {
    console.log(e);
}, false);

source.addEventListener('open', function(e) {
    console.log(e);
}, false);

source.addEventListener('error', function(e) {
    if (e.readyState == EventSource.CLOSED) {
        console.log('closed');
    }
}, false);

stream.php
while(true)
{
    // Headers must be processed line by line.
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

    // Set data line
    print "data: " . date( 'G:H:s', time() ) . PHP_EOL . PHP_EOL;

    // Toilet
    flush();

    // Wait one second.
    sleep(1);
}

I did expect a bit of a delay after uploading to the live dev. server. But there is a time delay of about 15 to 20 min. before I even see the first entry.
The connection does not drop. (Prob. been going 40 min. + now.) Is this just an Apache looping problem (means it time to look at web sockets) or is there something I can do to fix this?

A: @Derrick, your suggested ob_end_flush(); line got me close, but in more complex PHP than hello world code, I was still getting unwanted reopens on my SSE connections (I still don't fully understand why ob_end_flush() was doing that to me).  So here's the pattern I'm now using (otherwise identical to your stream.php).  In English, I'm turning off PHP output buffering before entering my infinite loop:
// per http://www.php.net/manual/en/book.outcontrol.php:
//     Clean (erase) the output buffer and turn off output buffering
ob_end_clean();

// how long PHP script stays running/SSE connection stays open (seconds)
set_time_limit(60);
while (true) {

  // use @Derrick's header/send code here

  ob_flush();  // note I don't turn off output buffering here again
  flush();
  sleep(1);
}

A: Sleep is blocking the SSE. I too had the same problem. I was advised to use event driven programming.

A: Server.php needs to be as follows:
stream.php
while(true)
{
    // Headers must be processed line by line.
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

    // Set data line
    print "Event: server-time" . PHP_EOL;
    print "data: " . date( 'G:H:s', time() ) . PHP_EOL;
    print PHP_EOL;

    ob_end_flush();     // Strange behaviour, will not work
    flush();            // Unless both are called !

    // Wait one second.
    sleep(1);
}

A: just add, ob_flush(); before flush() function in stream.php
updated stream.php script is as below, observe ob_flush() function before flush() function.
while(true)
{
    // Headers must be processed line by line.
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

    // Set data line
    print "data: " . date( 'G:H:s', time() ) . PHP_EOL . PHP_EOL;

    // Toilet
    **ob_flush();**
    flush();

    // Wait one second.
    sleep(1);
}

A: you can set delay via echo retry, for example

header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); //to prevent caching of event data
header('Access-Control-Allow-Origin: *'); //allows stream access from current domain only

$time = date('h:i:s');
$id = time(); //to set id with current timestamp

echo "data:$time\n";
echo "retry:2000\n";  //2 seconds
echo "id=$id \n\n";

ob_flush();
flush();


text:
Q: run bash script in raspberry pi via IFTTT I have a raspberry pi running Alexa (amazon echo) that can instantly push a trigger to IFTTT, for an example I say "Alexa, trigger email to blablabla" and I immediately receive an email.
My Goal I want to execute a bash script on the same raspberry pi with voice command (by Alexa) via IFTTT. Is there any IFTTT recipe that can instantly push a trigger to my raspberry pi? (so that I can instantly run a bash script) (Note: Dropbox doesn't support raspberry pi, though there is an uploader/downloader and the below script uses it with cronjob).
I found one (Raspi Runner) that runs cronjob every few minutes, but I'm not sure if I can setup cronjob for every second and use this script!!
How can I do this?

A: Short Answer:
IF
This - Alexa
Then
That - Adafruit/Maker Webhook

Longer Answer: There are two options:1)Alexa will notify IFTTT that trigger event has occurred. Against which, the action chosen is publishing an MQTT message. This MQTT channel is created by Adafruit. Needless to say, you need to write an MQTT feed reader at the RPi.
2) Maker web-hooks. You expose your RPi to the web, keep a server running on it. Expose a web-service which may be called from the Maker Webhook. This is personally my preferred option, but setup could be a pain, i.e. port forwarding from modem, router etc.

References:
1) Adafruit Official Site
2) MQTT Java Library
3) Hackster Tutorial - With option #1
4) Hackster Tutorial - With option #2


text:
Q: Android facebook login with OnClickListener I want to create a facebook login button for my application.
My problem is, that I want to call 'authorize' with an OnClickListener, but eclipse marks the 'authorize' part as an error. It suggests to replace it with authorizeCallback, but it's not the solution.
It seems like I'm just missing something, but don't know what. Any idea please?
This is where the error occurs (facebook.authorize):
LoginButton.setOnClickListener(new OnClickListener()
{
         public void onClick(View v)
         {
         facebook.authorize(this, new String[] { "email", "user_birthday" }, new FacebookLoginDialogListener());
          }});
    }

Rest of the code:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
        super.onActivityResult(requestCode, resultCode, data);
        facebook.authorizeCallback(requestCode, resultCode, data);
}

public class FacebookLoginDialogListener implements DialogListener
    {
        public void onComplete(Bundle values) {
            SharedPreferences.Editor editor = mPrefs.edit();
            editor.putString("access_token", facebook.getAccessToken());
            editor.putLong("access_expires", facebook.getAccessExpires());
            editor.commit();
            requestUserData();
        }

        public void onFacebookError(FacebookError error) {}

        public void onError(DialogError e) {}

        public void onCancel() {}

    }

A: do this way:
facebook.authorize(YourActivity.this, new String[] { "email", "user_birthday" }, new FacebookLoginDialogListener());

You are passing OnClickListener's this reference to the method, You have to pass Activity's Context to the method.


text:
Q: How can I recover data in a cell of my table (saved as an array) I save the rights of my users in my database as a table array
user    user_right (varchar 255)

1       ["write","delete"]
2       ["write","delete","update"]
3       ["add","write","delete"]
4       ["write"]

I would like to know how to list the data that is in the user_right column?
select ... from users where id = 1

Have a list that looks like this
write
delete


text:
Q: e1000 and e1000e network drivers I am using SUSE Linux 11, in Zenworks distro and i can see. kernel version is: 3.0.13-0.27-default.
I can see that when the distro is loaded, the e1000 driver is loaded and not e1000e although e1000e is also present. I have some questions:
1) Why the e1000e driver is not loaded automatically like e1000 ? Does the driver load, based on the compatibility with a particular version of kernel? If yes, how to determine the compatibility (any command)?
2) What is the basic difference between e1000 and e1000e?
3) When is e1000 required to use and e1000e?
modinfo of e1000
filename:       /lib/modules/3.0.13-0.27-default/initrd/e1000.ko
version:        7.3.21-k8-NAPI
license:        GPL
description:    Intel(R) PRO/1000 Network Driver
author:         Intel Corporation, <linux.nics@intel.com>
srcversion:     9156F163ACCABEA3C50ACF0
alias:          pci:v00008086d00002E6Esv*sd*bc*sc*i*
alias:          pci:v00008086d000010B5sv*sd*bc*sc*i*
alias:          pci:v00008086d00001099sv*sd*bc*sc*i*
alias:          pci:v00008086d0000108Asv*sd*bc*sc*i*
alias:          pci:v00008086d0000107Csv*sd*bc*sc*i*
alias:          pci:v00008086d0000107Bsv*sd*bc*sc*i*
alias:          pci:v00008086d0000107Asv*sd*bc*sc*i*
alias:          pci:v00008086d00001079sv*sd*bc*sc*i*
alias:          pci:v00008086d00001078sv*sd*bc*sc*i*
alias:          pci:v00008086d00001077sv*sd*bc*sc*i*
alias:          pci:v00008086d00001076sv*sd*bc*sc*i*
alias:          pci:v00008086d00001075sv*sd*bc*sc*i*
alias:          pci:v00008086d00001028sv*sd*bc*sc*i*
alias:          pci:v00008086d00001027sv*sd*bc*sc*i*
alias:          pci:v00008086d00001026sv*sd*bc*sc*i*
alias:          pci:v00008086d0000101Esv*sd*bc*sc*i*
alias:          pci:v00008086d0000101Dsv*sd*bc*sc*i*
alias:          pci:v00008086d0000101Asv*sd*bc*sc*i*
alias:          pci:v00008086d00001019sv*sd*bc*sc*i*
alias:          pci:v00008086d00001018sv*sd*bc*sc*i*
alias:          pci:v00008086d00001017sv*sd*bc*sc*i*
alias:          pci:v00008086d00001016sv*sd*bc*sc*i*
alias:          pci:v00008086d00001015sv*sd*bc*sc*i*
alias:          pci:v00008086d00001014sv*sd*bc*sc*i*
alias:          pci:v00008086d00001013sv*sd*bc*sc*i*
alias:          pci:v00008086d00001012sv*sd*bc*sc*i*
alias:          pci:v00008086d00001011sv*sd*bc*sc*i*
alias:          pci:v00008086d00001010sv*sd*bc*sc*i*
alias:          pci:v00008086d0000100Fsv*sd*bc*sc*i*
alias:          pci:v00008086d0000100Esv*sd*bc*sc*i*
alias:          pci:v00008086d0000100Dsv*sd*bc*sc*i*
alias:          pci:v00008086d0000100Csv*sd*bc*sc*i*
alias:          pci:v00008086d00001009sv*sd*bc*sc*i*
alias:          pci:v00008086d00001008sv*sd*bc*sc*i*
alias:          pci:v00008086d00001004sv*sd*bc*sc*i*
alias:          pci:v00008086d00001001sv*sd*bc*sc*i*
alias:          pci:v00008086d00001000sv*sd*bc*sc*i*
depends:
supported:      yes
vermagic:       3.0.13-0.27-default SMP mod_unload modversions 586TSC
parm:           TxDescriptors:Number of transmit descriptors (array of int)
parm:           RxDescriptors:Number of receive descriptors (array of int)
parm:           Speed:Speed setting (array of int)
parm:           Duplex:Duplex setting (array of int)
parm:           AutoNeg:Advertised auto-negotiation setting (array of int)
parm:           FlowControl:Flow Control setting (array of int)
parm:           XsumRX:Disable or enable Receive Checksum offload (array of int)
parm:           TxIntDelay:Transmit Interrupt Delay (array of int)
parm:           TxAbsIntDelay:Transmit Absolute Interrupt Delay (array of int)
parm:           RxIntDelay:Receive Interrupt Delay (array of int)
parm:           RxAbsIntDelay:Receive Absolute Interrupt Delay (array of int)
parm:           InterruptThrottleRate:Interrupt Throttling Rate (array of int)
parm:           SmartPowerDownEnable:Enable PHY smart power down (array of int)
parm:           copybreak:Maximum size of packet that is copied to a new buffer on receive (uint)
parm:           debug:Debug level (0=none,...,16=all) (int)
parm:           entropy:Allow e1000 to populate the /dev/random entropy pool (int)

modinfo of e1000e
filename:       /lib/modules/3.0.13-0.27-default/initrd/e1000e.ko
version:        1.10.6-NAPI
license:        GPL
description:    Intel(R) PRO/1000 Network Driver
author:         Intel Corporation, <linux.nics@intel.com>
srcversion:     D1F1E8DCB1431A5ED03735A
alias:          pci:v00008086d00001503sv*sd*bc*sc*i*
alias:          pci:v00008086d00001502sv*sd*bc*sc*i*
alias:          pci:v00008086d000010F0sv*sd*bc*sc*i*
alias:          pci:v00008086d000010EFsv*sd*bc*sc*i*
alias:          pci:v00008086d000010EBsv*sd*bc*sc*i*
alias:          pci:v00008086d000010EAsv*sd*bc*sc*i*
alias:          pci:v00008086d00001525sv*sd*bc*sc*i*
alias:          pci:v00008086d000010DFsv*sd*bc*sc*i*
alias:          pci:v00008086d000010DEsv*sd*bc*sc*i*
alias:          pci:v00008086d000010CEsv*sd*bc*sc*i*
alias:          pci:v00008086d000010CDsv*sd*bc*sc*i*
alias:          pci:v00008086d000010CCsv*sd*bc*sc*i*
alias:          pci:v00008086d000010CBsv*sd*bc*sc*i*
alias:          pci:v00008086d000010F5sv*sd*bc*sc*i*
alias:          pci:v00008086d000010BFsv*sd*bc*sc*i*
alias:          pci:v00008086d000010E5sv*sd*bc*sc*i*
alias:          pci:v00008086d0000294Csv*sd*bc*sc*i*
alias:          pci:v00008086d000010BDsv*sd*bc*sc*i*
alias:          pci:v00008086d000010C3sv*sd*bc*sc*i*
alias:          pci:v00008086d000010C2sv*sd*bc*sc*i*
alias:          pci:v00008086d000010C0sv*sd*bc*sc*i*
alias:          pci:v00008086d00001501sv*sd*bc*sc*i*
alias:          pci:v00008086d00001049sv*sd*bc*sc*i*
alias:          pci:v00008086d0000104Dsv*sd*bc*sc*i*
alias:          pci:v00008086d0000104Bsv*sd*bc*sc*i*
alias:          pci:v00008086d0000104Asv*sd*bc*sc*i*
alias:          pci:v00008086d000010C4sv*sd*bc*sc*i*
alias:          pci:v00008086d000010C5sv*sd*bc*sc*i*
alias:          pci:v00008086d0000104Csv*sd*bc*sc*i*
alias:          pci:v00008086d000010BBsv*sd*bc*sc*i*
alias:          pci:v00008086d00001098sv*sd*bc*sc*i*
alias:          pci:v00008086d000010BAsv*sd*bc*sc*i*
alias:          pci:v00008086d00001096sv*sd*bc*sc*i*
alias:          pci:v00008086d0000150Csv*sd*bc*sc*i*
alias:          pci:v00008086d000010F6sv*sd*bc*sc*i*
alias:          pci:v00008086d000010D3sv*sd*bc*sc*i*
alias:          pci:v00008086d0000109Asv*sd*bc*sc*i*
alias:          pci:v00008086d0000108Csv*sd*bc*sc*i*
alias:          pci:v00008086d0000108Bsv*sd*bc*sc*i*
alias:          pci:v00008086d0000107Fsv*sd*bc*sc*i*
alias:          pci:v00008086d0000107Esv*sd*bc*sc*i*
alias:          pci:v00008086d0000107Dsv*sd*bc*sc*i*
alias:          pci:v00008086d000010B9sv*sd*bc*sc*i*
alias:          pci:v00008086d000010D5sv*sd*bc*sc*i*
alias:          pci:v00008086d000010DAsv*sd*bc*sc*i*
alias:          pci:v00008086d000010D9sv*sd*bc*sc*i*
alias:          pci:v00008086d00001060sv*sd*bc*sc*i*
alias:          pci:v00008086d000010A5sv*sd*bc*sc*i*
alias:          pci:v00008086d000010BCsv*sd*bc*sc*i*
alias:          pci:v00008086d000010A4sv*sd*bc*sc*i*
alias:          pci:v00008086d0000105Fsv*sd*bc*sc*i*
alias:          pci:v00008086d0000105Esv*sd*bc*sc*i*
depends:
supported:      external
vermagic:       3.0.13-0.27-default SMP mod_unload modversions 586TSC
parm:           copybreak:Maximum size of packet that is copied to a new buffer on receive (uint)
parm:           TxIntDelay:Transmit Interrupt Delay (array of int)
parm:           TxAbsIntDelay:Transmit Absolute Interrupt Delay (array of int)
parm:           RxIntDelay:Receive Interrupt Delay (array of int)
parm:           RxAbsIntDelay:Receive Absolute Interrupt Delay (array of int)
parm:           InterruptThrottleRate:Interrupt Throttling Rate (array of int)
parm:           IntMode:Interrupt Mode (array of int)
parm:           SmartPowerDownEnable:Enable PHY smart power down (array of int)
parm:           KumeranLockLoss:Enable Kumeran lock loss workaround (array of int)
parm:           CrcStripping:Enable CRC Stripping, disable if your BMC needs the CRC (array of int)
parm:           EEE:Enable/disable on parts that support the feature (array of int)
parm:           Node:[ROUTING] Node to allocate memory on, default -1 (array of int)

A: They support different devices based on the same chip. All those PCI IDs in your modinfo output are used to select the right one. According to the kernel config help, e1000e is for PCI-Express cards so I guess the reason it wasn't loaded automatically is that you don't have one of those.


text:
Q: Not found :org.apache.hadoop.security.authentication.util.KerberosUtil I am running storm jar in a cluster ,where I configured hadoop,kafka,storm  cluster
when I run the jar in local mode it works fine ,when I run it on storm cluster, I am finding respective error in Storm UI:
java.lang.NoSuchMethodError: org.apache.hadoop.security.authentication.util.KerberosUtil.hasKerberosTicket(Ljavax/security/auth/Subject;)Z at
org.apache.hadoop.security.UserGroupInformation.<init>(UserGroupInformation.java:666) at org.apache.hadoop.security.UserGroupInformation.loginUserFromSubject(UserGroupInformation.java:861) at
org.apache.hadoop.security.UserGroupInformation.getLoginUser(UserGroupInformation.java:820)

pom.xml
Click here to view POM file
After some google I found I found we have add hadoop auth jar.even after i finding same error

A: I think you're packaging an old Hadoop jar.
Take a look at the storm-hdfs POM https://github.com/apache/storm/blob/v1.0.6/external/storm-hdfs/pom.xml. When you use the Shade plugin, the jar you end up with will contain all your dependencies, including transitive ones brought in through direct dependencies. Storm-hdfs declares a dependency on a list of Hadoop jars. You need to make sure that you're declaring the same list of Hadoop jars in your POM if you want to use a different version of Hadoop from the default.
Specifically what's happening is that you haven't declared hadoop-auth in your POM, so your POM gets packaged with the default version of that jar (2.6.1). Since that version of hadoop-auth is incompatible with the other Hadoop jars (which are 2.9.1), you get an exception at runtime.
You should either exclude all Hadoop jars from your import of storm-hdfs and then put the jars you want to use in Storm's lib directory, or add the right versions of the Hadoop jars to your dependency list in your POM.
Edit:
I think I found your issue. You haven't set the scope of storm-core to provided. Since storm-core depends on hadoop-auth, and you haven't declared it explicitly, Maven will try to guess which version of hadoop-auth you need based on where the dependency appears in the tree. Since hadoop-auth appears as 2.9.1 through some of your Hadoop dependencies, but 2.6.1 through storm-core, you happen to get 2.6.1 put in your jar.
If you want to avoid this kind of thing in the future, you should use Maven's dependencyManagement block https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html#Dependency_Management.
i.e. you should add something like the following to your pom, and then remove the exclusions of hadoop jars.
<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-client</artifactId>
                <version>${hadoop.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-auth</artifactId>
                <version>${hadoop.version}</version>
            </dependency>
            <dependency>
                <groupId>org.apache.hadoop</groupId>
                <artifactId>hadoop-common</artifactId>
                <version>${hadoop.version}</version>
            </dependency>
        </dependencies>
    </dependencyManagement>


text:
Q: Python requests with stream reads only 8-9 mb of a file and stops I am trying to read and encode 1 mb chunks of a file using requests library. One file is of 96 mb and another is of 15 mb in size. The code exits the loop without any error after 8-9 iterations.
I have tried the following:
    with requests.get(url, stream=True, verify=False) as r:
        r.raise_for_status()
        mb_pushed = 0
        # read 1048576 bytes at a time
        for block in r.iter_content(chunk_size=1048576):
            # encode content
            encoded_content = base64.standard_b64encode(block)
            # push the encoded block
            dbfs_rpc('add-block', {'data': encoded_content, 'handle': handler})
            _logger.info('Pushed %smb' % str(mb_pushed + 1))
            mb_pushed += 1

What am I missing here?


text:
Q: Three.js: OrbitControls zoom minDistance issue I'm using OrbitControl for navigation. In my scene, I have two planes which are defining a 100x100x100 cube in which I load different data.
JsFiddle: http://jsfiddle.net/k4p8h/1/
My problem is, that I can't zoom in my cube! I think it has something to do with minDistance, so I experimented with it like
controls.minDistance = -Infinity

but it has no effect. I found out that every number under zero has no effect.
I don't want to limit the zoomIn, the user should be able to zoom to every point in my cube. How can I fix this limitation?

A: You set controls.target in the wrong place -- in front of your cube. You need to set it to the center of your cube.
 controls.target.set( 50, 50, -50 );

updated fiddle: http://jsfiddle.net/k4p8h/2/
three.js r.62


text:
Q: Office 365 API authentication from backend I am just starting to use the O365 apis, so forgive me if this is a dumb question.
The samples I have seen so far uses manual login/authentication to the O365 account by a person. I need to Connect to SharePoint Online from a backend service that will provide New records to a list.
Is there a way for an unattended backend Application to authenticate With O365 without the need for a user to enter credentials each time?

A: You're describing the code grant authorization flow, which allows the app to act as a delegate for a single user and requires user login. You can also use the client credential flow, which allows an organization admin to login once to consent to the app for all users in the org. However, this is only or Exchange Online right now, SharePoint hasn't enabled client credential flow yet. (At least, there are no entries in the Application Permissions drop down in Azure Management Portal) Info and .NET sample here:
http://blogs.msdn.com/b/exchangedev/archive/2015/01/21/building-demon-or-service-apps-with-office-365-mail-calendar-and-contacts-apis-oauth2-client-credential-flow.aspx
Python sample here:
http://blogs.msdn.com/b/exchangedev/archive/2015/02/10/client-credentials-flow-for-mail-api-in-python.aspx


text:
Q: Only last row is returned in json using codeigniter I am trying to return json data using codeigniter which I will later use that json in javascript. Now the problem is that it only returns the last row from database table and make a json format from that one row. Here is my code in controller
public function v1 () {
    $this->load->model('model_jokes');

    $jokes = $this->model_jokes->readJokes();
    foreach ($jokes as $joke) {
        $arr = array(
                array(
                    'title' => $joke->title,
                    'description' => $joke->joke
                )
            );
    }
    echo json_encode($arr);
}

how can I make it so that all data that I am retrieving from database is returned in json?

A: Try
$arr = array();
foreach ($jokes as $joke) {
  $arr[] = array (
    'title' => $joke->title,
    'description' => $joke->joke
  );
}

In your snippet you are overwriting $arr with each iteration in your loop.
The above snippet in this post will append all entries to the array $arr which you can later encode to json.

A: You're assigning $arr to a new array each iteration rather than adding values to it.
$arr = array();
foreach ($jokes as $joke) {
    $arr[] =  array(
                'title' => $joke->title,
                'description' => $joke->joke
            );
}

A: Your controller is not right...
//CONTROLLER
    public function v1() {

    $this->load->helper('file');

    $data = $this->load->model('model_jokes');

    $this->output
        ->set_content_type('application/json')
        ->set_output(json_encode($data));
}

And make sure your model created the array instead of the controller:
public function model_jokes()
{
    $jokes = $this->_load_data();
    $list = array();

        foreach ($jokes as $joke) {
            $list['joke'] = array(
                'yourdata1' => $joke->yourvariable,
                'yourdata2' => $joke->yourvariable
            );
        }
        return $list;
}

I used a private function within the model to get all data.
Hope it helps!

A: I am always doing like..
 $arr = array();
 $key = 0;
 foreach ($jokes as $joke)
 {
   $arr[$key]['title'] = $joke->title;
   $arr[$key]['description'] = $joke->joke;
   $key++;
 }


text:
Q: How to quickly select Necronomicon Archer to use mana burn When I use necronomicon it summons two units, warrior and archer. How do I quickly switch to archer to use mana burn before my target gets out of range?
Using tab switch it can be slow (especially if I'm playing Chen or Beastmaster who have more summoned units) and clicking the archer is unreliable if everything is clustered.
How do professionals do it quickly?

A: One trick would be: the first time you summon your warrior, select the archer and assign it to a control groups (e.g. Ctrl+1). The next time you summon them, the control group 1 should already have the archer in it, so you can just press 1 then do the mana burn.

A: You can set "Select All Other Units" to "2" for example and once you have popped the Necrobook you can just use q and cast it. (You might have to press TAB before if the Archer isn't the first unit)

If you are playing a hero that already has units (such as Nature's Prophet, Invoker or Beastmaster) you probably need to use Control Groups.


text:
Q: Avoid Auto restart server meteor when file change when i save any change in file even inserting a space, meteor restart immediately, so cpu always run in high frequency. How I can fix it ? Any one have similar issues?

A: You can disable HCP (hot code push) by adding this anywhere in your client code:
Meteor._reload.onMigrate(function() {
  return [false];
});

After doing that, you'll need to manually refresh the page in order to see any new changes.


text:
Q: Jetty 6: Unknown Error 99 The system I'm developing is comprised of a jetty server (v6.1.2rc4) and a php frontend that sends http requests to jetty via curl_exec.
The server and the client are on the same machine.
The requests I send can be both POSTs and GETs, I get the same error for either which is:
Failed to connect to 127.0.0.1: Unknown error 99

This is rather cryptic.
It seems that after the first problematic request, some of the following (unrelated) requests also get corrupted.
It looks like jetty is simply refusing the connection, but I can't read more than that into the error message.
I thought it was a problem with the server's configuration, so I tried changing jetty's maxIdleTimeMs, but without success.
Any idea about what to do is welcome
thanks,
Silvio
EDIT: I get the error after the server has already answered some requests successfully

A: Double-check that your Jetty server is actually running - you probably have another server running on port 80 (the default server port, and used by Apache and IIS). Configure Jetty to listen to port 8080 or something (or your other server).


text:
Q: My PS4 account was attached to a Gmail that was hacked. How can I recover my PS4 account? I had my Gmail hacked recently, and I had to switch my gmail, but I forgot to change my PlayStation network Gmail account. Now it locked me out of my games and won't let me play them unless I verify myself with my previous email.
How would I fix this?

A: thanks to Ben I figured out how to fix this problem. but I didn't call them since its a harder hastle to anyways. I went to the official PlayStation website and went to PlayStation chat support where a live agent helped me resolve this solution. I recommend going there for all PS4 help since they were very helpful and decriptive.


text:
Q: Laravel 5.7 : 404 or 403 on storage/app/private whereas it works on storage/app/public I am struggling to offer the user a link to a file that they can download when logged in. I read this and that (because eventually I want to protect the file from public access).
So under my app /storage folder I created a "private" directory next to "public". Inside it there is a subfolder "A" containing a "fileA.tar.gz" (I also tried with a simple test.txt without luck).
MyLaravelApp/
├── storage/
│   ├── public/
│   ├── private/
│        └── A/
│            └──fileA.tar.gz

In my controller I do :
$softwarePath = "private/A/fileA.tar.gz";

$urlToArchive = \Storage::disk('local')->url(
                                $softwarePath);

$exists = \Storage::disk('local')->exists($softwarePath); // returns true

But in the view when I click on the link http://127.0.0.1:8000/storage/private/A/fileA.tar.gz I get 404 although the exists function returns true.
So I tried to define in /config/filesystems.php a direct "short-cut" to my "private" folder :
'private' => [
    'driver' => 'local',
    'root' => storage_path('app/private'),
    'url' => env('APP_URL').'/privateDownload',
    'visibility' => 'public',
],

and made the following changes in the controller :
$softwarePath = "A/fileA.tar.gz";

$urlToArchive = \Storage::disk('private')->url($softwarePath);

$exists = \Storage::disk('private')->exists($softwarePath); // keeps returning true

But now I get 403 when I click on the generated link http://localhost/privateDownload/A/fileA.tar.gz (note the localhost without port address) and if I change the address to localhost:8000 I get the 404 back.
The route to the aforementioned controller is :
Route::get('/account', 'AccountController@showAccountDetails')->middleware('auth');

And I also tried to remove the middleware('auth') and access to private/A/fileA.tar.gz without luck (404).
Please note : if I keep the same subdirectory hierachy and moved it under public like :
MyLaravelApp/
├── storage/
│   ├── public/
│        └── A/
│            └──fileA.tar.gz
│   ├── private/

There is no issue, and the file can be downloaded. This is not interesting because I want to prevent this file from being downloaded without being logged in.
According to the doc and other SO answers it seems possible to access to a different directory than public. How can it be done ? Why exists() returns true whereas I get 404 then ? What's my setup / code failure actually?
Any help appreciated!
Solution
Based on @Namoshek's answer, here is what I did (for the records) :
In the aforementioned controller I simply checked whether or not the user has the right to download fileA. If so then I return a view which has a link to a route named downloadFileA that points to a function downloadFileA still in the same aforementioned controller.
Finally in the function downloadFileA I return \Storage::disk('private')->download('fileA') after checking whether the user is entitled or not to download the file. So I check twice but that's not a problem because there is very low traffic (once a week or so).

A: You can use Storage::download('filename.xyz') instead of generating a URL with Storage::url('filename.xyu'). This will send the file as content of the response. It may be resource intensive for large files though.


text:
Q: Dropping an unindexed table with over 1.7 Billion rows on live database (SQL Admin Nightmare) A recent employee of our company had a stored procedure that has gone haywire, and caused mass inserts into a debug table of his. The table is unindexed, is now at close to 1.7 billion rows, and is taking up so much space that the backup no longer fits on the backup drive (Backups now reach close to 250GB).
I haven't really seen anything like this, so I'm seeking advice from the MSSQL Gurus out here.
I know I could nibble away at the table, but being unindexed, the DELETE FROM [TABLE] WHERE ID IN (SELECT TOP 10000 [ID] FROM [TABLE]) nearly locks up the server searching for them.
I also don't want my log file to get massive, it's currently sitting at 480GB on a 1TB drive. If I delete this table, will I be able to shrink it back down? (My recovery mode is simple)
We could index the id field on the table, though we only have around 9 hours downtime a day, and during business hours we can't be locking up the database.
Just looking for advice here, and a point in the right direction.
Thanks.

A: You may want to consider TRUNCATE
MSDN reference: http://technet.microsoft.com/en-us/library/aa260621(v=sql.80).aspx

Removes all rows from a table without logging the individual row deletes.

Syntax:
TRUNCATE TABLE [YOUR_TABLE]

As @Rahul suggests in the comments, you could also use DROP TABLE [YOUR_TABLE] if you no longer plan to use the table in question. The TRUNCATE option would simply empty the table but leave it in place if you wanted to continue to use it.
With regards to the space issue, both of these operations will be comparatively quick and the space will be reclaimed, but it won't happen instantly. When using TRUNCATE, the data still has to be deleted, but SQL Server will simply deallocate the data pages used by the table and use a background process to actually perform the clean up afterwards.
This post should provide some useful information.

A: One suggestion would be ... take the back up of only that 1.7 billion rows table (probably in a tape drive/somewhere with good enough space) and then drop the table saying drop table table_name.
That way, if at all that debug table data is needed in future; you have a copy and can restore from backup.

A: I would remove the logging for this table and launch a delete stored procedure that would commit every 1000 rows.


text:
Q: My clear() command not working in Google Chrome JavaScript console Every time I run the clear() command to clear space in my JavaScript console on Chrome, I run into the following error: VM229:1 Uncaught TypeError: clear is not a function
at :1:1
I'm aware that there are other ways to clear the console, but I'm wondering at what I'm doing wrong or if I have a weird setting enabled.

A: Type console.clear() into the console.
The command will fail with an appropriate error if you enabled the option "preserve log".


text:
Q: Is there a way to only load needed objects in Selenium Python For my project I have to log in a lot, only now I want to speed up that process by only loading what I need. (so no images and CSS and if possible also some divs not)
Is there a way to achieve that?

A: You can try this if images block is enough:
from selenium import webdriver

profile = webdriver.FirefoxProfile()
# 1 - Allow all images
# 2 - Block all images
# 3 - Block 3rd party images
profile.set_preference("permissions.default.image", 2)

driver = webdriver.Firefox(firefox_profile=profile)

For bigger blocking here you have solution from other SO thread:
from selenium import webdriver

options = webdriver.ChromeOptions()
prefs = {'profile.default_content_setting_values': {'cookies': 2, 'images': 2, 'javascript': 2,
                            'plugins': 2, 'popups': 2, 'geolocation': 2,
                            'notifications': 2, 'auto_select_certificate': 2, 'fullscreen': 2,
                            'mouselock': 2, 'mixed_script': 2, 'media_stream': 2,
                            'media_stream_mic': 2, 'media_stream_camera': 2, 'protocol_handlers': 2,
                            'ppapi_broker': 2, 'automatic_downloads': 2, 'midi_sysex': 2,
                            'push_messaging': 2, 'ssl_cert_decisions': 2, 'metro_switch_to_desktop': 2,
                            'protected_media_identifier': 2, 'app_banner': 2, 'site_engagement': 2,
                            'durable_storage': 2}}
options.add_experimental_option('prefs', prefs)
options.add_argument("start-maximized")
options.add_argument("disable-infobars")
options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
driver.get('https://play.google.com/store')


text:
Q: React и карта яндекса ПАМАГИТИ! Срочно нужно вставить карту, но пока только начато знакомство с рекат.
const Contact = props => {
  return (
    React.createElement("section", { id: "contact" },));
};

Куда нужно добавить код ниже, чтобы всё корректно заработало?
componentDidMount() {
    const script = document.createElement("script");
    script.src = "https://www.google.com/recaptcha/api.js?hl=en";
    script.async = true;
    document.body.appendChild(script);
}

Заранее спасибо!

A: import React from "react";

const App = () => {
  return (

App

  );
};

export default App;


text:
Q: how to send form data using AJAX in Bootstrap? I have a web application which is designed by twitter bootstrap. There is a JSP page with a small form, and I need to send its data to a Servlet without reloading the page. Below is my form.

   Back Add Custom Item

          <form class="form-horizontal" method="get" action="PastSurgicalCustomItem" id="customItemForm"  onsubmit="formSubmit(); return false;">
        <fieldset id="modal_form">

            Name

              <input name="customName" type="text" placeholder="" class="form-control input-md">

              <button id="additional" class="btn btn-primary" data-dismiss="modal">Submit</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>

        </fieldset>
      </form>

I use the below ajax query to send data to the servlet. This code is in the same page where the above form also in.

We have loaded the below scripts to the JSP page as well.
!-- Bootstrap Core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">

<link href="css/simple-sidebar.css" rel="stylesheet">
<link href="css/custom.css" rel="stylesheet">

Below is my servlet.
import DB.PastSurgicalHistoryTypeTable;
import beans.main.PastSergicalHistoryTypeBean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Yohan
 */
public class PastSurgicalCustomItem extends HttpServlet {

    /**
     * Processes requests for both HTTP GET and POST
     * methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/plain");  // Set content type of the response so that jQuery knows what it can expect.
        response.setCharacterEncoding("UTF-8");

        String name = request.getParameter("customName");
        System.out.println(name);

    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    public String getServletInfo() {
        return "Short description";
    }

}

The problem I am having is that the ajax is not sending data to the servlet. I used the same code without bootstrap as well, so I am thinking whether bootstrap has to do something with this. How can I solve this problem?

A: I managed to solve the issue. The way it works with bootstrap is different. Below is my new code.

You can get more idea from here - http://www.krizna.com/jquery/jquery-ajax-form-submit-using-twitter-bootstrap-modal/


text:
Q: Partial fraction decomposition of $ \frac{\pi}{\sin \pi z}$ I want to prove the partial fraction decomposition:
\begin{align}\frac{\pi}{\sin \pi z} = \frac{1}{z} + 2z\sum\limits _{n=1} ^{\infty} \frac{(-1)^n}{z^2-n^2}
\end{align}
with the help of the partial fraction decomposition of \begin{align} \pi \cot\pi z = \frac{1}{z} + 2z\sum\limits _{n=1} ^{\infty} \frac{1}{z^2-n^2}. \end{align}

A: Consider the Fourier series of $\cos{\alpha x}$, considered as a function on $[-\pi,\pi]$ (yes, this is perverse): it satisfies the Dirichlet conditions, so on the interior, we have
$$ \cos{\alpha x} = \frac{1}{2}a_0+\sum_{k=1}^{\infty} a_k \cos{kx}, $$
where we find $a_k$ with the usual formula,
$$ a_k = \frac{1}{\pi}\int_{-\pi}^{\pi} \cos{\alpha x} \cos{kx} \, dx = \frac{(-1)^k 2\alpha\sin{\pi\alpha}}{\pi(\alpha^2-k^2)}, $$
by an easy calculation. Oh dear, now it's fairly obvious what's about to happen:
$$ \cos{\alpha x} = \frac{\sin{\pi\alpha}}{\pi \alpha}+\sum_{k=1}^{\infty} \frac{(-1)^k 2\alpha\sin{\pi\alpha}}{\pi(\alpha^2-k^2)} \cos{kx}. $$
Now set $x=0$ and multiply everything by $\pi/\sin{\pi \alpha}$. You can do the same thing for the cotangent by setting $x=\pi$.

To get from the cotangent to the cosecant, we go hunting for a trigonometric identity. Let's think about where the poles of each are: $\csc{\pi z}$ has poles at integers, as does $\cot{\pi z}$, but the residues alternate for the $\csc{\pi z}$. Therefore, can we make a linear combination of cotangents that has these poles? If you think for a few minutes, you come up with
$$ \cot{\tfrac{1}{2}\pi z}-\cot{\pi z}, $$
which it is easy to verify works:
$$ \frac{\cos{x}}{\sin{x}}-\frac{\cos{2x}}{\sin{2x}} = \frac{\cos{x}}{\sin{x}}-\frac{2\cos^2{x}-1}{2\sin{x}\cos{x}} = \frac{1}{2\sin{x}\cos{x}} = \csc{2x} $$
Now we just have to fiddle with the series expansions.
$$ \pi\cot{\tfrac{1}{2}\pi z}-\pi\cot{\pi z} = \frac{2}{z} + \sum_{n=1}^{\infty} \frac{z}{z^2/4-n^2}-\frac{1}{z} - \sum_{n=1}^{\infty} \frac{2z}{z^2-n^2} \\
=\frac{1}{z} + 2\sum_{n=1}^{\infty} \frac{2z}{z^2-(2n)^2} - \sum_{n=1}^{\infty} \frac{2z}{z^2-n^2}. $$
Ah, but hang on: the term with $n=2m$, even, in the second sum are half of the $m$th term of the first sum, whereas the odd terms have no corresponding terms. Hence the sums collapse into
$$ \pi\csc{\pi z} = \frac{1}{z}+2z\sum_{n=1}^{\infty} \frac{(-1)^n}{z^2-n^2}. $$

A: Chappers' answer is very well-written and complete, but if you like another perspective, in order to prove that:
$$ \frac{\pi}{\sin(\pi z)}=\frac{1}{z}+\sum_{n=1}^{+\infty}(-1)^n\left(\frac{1}{z-n}+\frac{1}{z+n}\right) $$
holds, we just need to prove that the residues of the LHS and of the RHS at the integers match.
Pretty easy:
$$\text{Res}\left(\frac{\pi}{\sin(\pi z)},z=0\right) = \lim_{z\to 0}\frac{\pi z}{\sin(\pi z)}=1, $$
$$\text{Res}\left(\frac{\pi}{\sin(\pi z)},z=n\right) = \text{Res}\left(\frac{\pi}{\sin(\pi z+\pi n)},z=0\right)=(-1)^n\text{Res}\left(\frac{\pi}{\sin(\pi z)},z=0\right), $$
done.

A: Hint: Split both sums from your two formulas according to the parity of the iterator n, then notice that the former will be of the form $S_{\sin}=A-B$, and the latter $S_{\cot}=A+B$. Now, the value of B follows directly from your second formula, after a bit of factoring. Subtracting, we have A. Then replace both their values in the first, and voila ! :-$)$