text:
Q: Formatting thousand separator for integers in a pandas dataframe I'm trying to use '{:,}'.format(number) like the example below to format a number in a pandas dataframe:
# This works for floats and integers
print '{:,}'.format(20000)
# 20,000
print '{:,}'.format(20000.0)
# 20,000.0

The problem is that with a dataframe that has integers does not work, and in a dataframe with float works ok. See the examples:
# Does not work. The format stays the same, does not show thousands separator
df_int = DataFrame({"A": [20000, 10000]})
print df_int.to_html(float_format=lambda x: '{:,}'.format(x))

# Example of result
#

#   0
#    20000
# </tr

# Works OK
df_float = DataFrame({"A": [20000.0, 10000.0]})
print df_float.to_html(float_format=lambda x: '{:,}'.format(x))

# Example of result
#

#   0
#   20,000.0
#

What i'm doing wrong?

A: The formatters parameter in to_html will take a dictionary of column names mapped to a formatting function.  Below has an example of a function to build a dict that maps the same function to both floats and ints.
In [250]: num_format = lambda x: '{:,}'.format(x)

In [246]: def build_formatters(df, format):
     ...:     return {column:format
     ...:               for (column, dtype) in df.dtypes.iteritems()
     ...:               if dtype in [np.dtype('int64'), np.dtype('float64')]}
     ...:

In [247]: formatters = build_formatters(df_int, num_format)

In [249]: print df_int.to_html(formatters=formatters)

      A

      0
      20,000

      1
      10,000

A: pandas (as of 0.20.1) does not allow overriding the default integer format in an easy way. It is hard coded in pandas.io.formats.format.IntArrayFormatter (the lambda function):
class IntArrayFormatter(GenericArrayFormatter):

    def _format_strings(self):
        formatter = self.formatter or (lambda x: '% d' % x)
        fmt_values = [formatter(x) for x in self.values]
        return fmt_values

I'm assuming what you're actually asking for is how you can override the format for all integers: modify (i.e. "monkey patch") the IntArrayFormatter to print integer values with thousands separated by comma as follows:
import pandas

class _IntArrayFormatter(pandas.io.formats.format.GenericArrayFormatter):

    def _format_strings(self):
        formatter = self.formatter or (lambda x: ' {:,}'.format(x))
        fmt_values = [formatter(x) for x in self.values]
        return fmt_values

pandas.io.formats.format.IntArrayFormatter = _IntArrayFormatter

Note:

*

*before 0.20.0, the formatters were in pandas.formats.format.

*before 0.18.1, the formatters were in pandas.core.format.

Aside
For floats you do not need to jump through those hoops since there is a configuration option for it:

display.float_format: The callable should accept a floating point number and return a string with the desired format of the number. This is used in some places like SeriesFormatter. See core.format.EngFormatter for an example.

A: You can always cast your table to float64 and then use float_format as you like, especially if you are constructing a small table for viewing purposes. Instead of dealing with ints and floats separately this gives a quick solution.
df.astype('float64',errors='ignore').to_html(float_format=lambda x: format(x,',.2f'))
errors='ignore' is there to prevent raising an exception when a column can not be converted to floats, like strings.


text:
Q: How does setPublicChainlinkToken work, what if this function does not sense the current chain environment? As we know, within ChainlinkClient.sol, there is a function: setPublicChainlinkToken, it would sense current chainlink info and set up the LINK token for transferAndCall, but when we enter into a totally new chain, how do we deal with such a situation?

A: It works to use setChainlinkToken(official LINK token address) instead of setPublicChainlinkToken() for other chains. In order to make use of the transferAndCall function it must be a token following the ERC677 standard, you can find all official LINK token addresses here:
https://docs.chain.link/docs/link-token-contracts/#config

redpajama_set_name: RedPajamaStackExchange


text:
Q: Retrieve Data From Api Using Angular Here is my api from which i want to parse the first author name.
{
  status: "ok",
  source: "the-next-web",
  sortBy: "latest",
  articles: - [
    {
      author: "Napier Lopez",
      title: "Microsoft reveals the first Cortana-powered Amazon Echo competitor",
      description: "We first got wind of a Cortana-powered speaker was on the way back in December, but now it's finally here. Microsoft and Harmon Kardon today revealed the 'Invoke,' the first Amazon ...",
      url: "https://thenextweb.com/microsoft/2017/05/08/microsoft-reveals-first-cortana-powered-amazon-echo-competitor/",
      urlToImage: "https://cdn2.tnwcdn.com/wp-content/blogs.dir/1/files/2017/05/Harmon-Kardon-Invoke-Cortana-Speaker-Microsoft.jpg",
      publishedAt: "2017-05-08T18:35:18Z"
    },
    {
      author: "Rachel Kaser",
      title: "Facebook fights fake news in UK with newspaper ads and account purges",
      description: "As the UK election draws near, Facebook is cleaning house. The social media giant is taking two major steps to combat false news at a critical moment: deleting accounts and buying ...",
      url: "https://thenextweb.com/facebook/2017/05/08/facebook-fights-fake-news-uk-newspaper-ads-account-purges/",
      urlToImage: "https://cdn2.tnwcdn.com/wp-content/blogs.dir/1/files/2017/04/Screen-Shot-2017-04-14-at-14.24.46.jpg",
      publishedAt: "2017-05-08T18:03:29Z"
    }
  ]
}

I have stored all this data in $scope.content and retrieving the first author name by this
{{content.author}}
But it is not showing anything.
Can u tell me why is that and how to fix it.?

A: You should do a ng-repeat over content.articles

    {{ x.author }}
    {{ x.title }}

DEMO

var app = angular.module("myApp", []);
app.controller("PatientsController", function($scope) {
 $scope.content = {
"status": "ok",
"source": "the-next-web",
"sortBy": "latest",
"articles":  [
 {
"author": "Napier Lopez",
"title": "Microsoft reveals the first Cortana-powered Amazon Echo competitor",
"description": "We first got wind of a Cortana-powered speaker was on the way back in December, but now it's finally here. Microsoft and Harmon Kardon today revealed the 'Invoke,' the first Amazon ...",
"url": "https://thenextweb.com/microsoft/2017/05/08/microsoft-reveals-first-cortana-powered-amazon-echo-competitor/",
"urlToImage": "https://cdn2.tnwcdn.com/wp-content/blogs.dir/1/files/2017/05/Harmon-Kardon-Invoke-Cortana-Speaker-Microsoft.jpg",
"publishedAt": "2017-05-08T18:35:18Z"
},
 {
"author": "Rachel Kaser",
"title": "Facebook fights fake news in UK with newspaper ads and account purges",
"description": "As the UK election draws near, Facebook is cleaning house. The social media giant is taking two major steps to combat false news at a critical moment: deleting accounts and buying ...",
"url": "https://thenextweb.com/facebook/2017/05/08/facebook-fights-fake-news-uk-newspaper-ads-account-purges/",
"urlToImage": "https://cdn2.tnwcdn.com/wp-content/blogs.dir/1/files/2017/04/Screen-Shot-2017-04-14-at-14.24.46.jpg",
"publishedAt": "2017-05-08T18:03:29Z"
}
]};
});
<!DOCTYPE html>

    {{ x.author }}
    {{ x.title }}


text:
Q: Firebase database (WEB) - Securely editing data without a server running Firebase Admin SDK I realize this is probably impossible, but setting up a server running the firebase admin sdk and communicating with that seems like it's a bit of a hassle so and kinda removes everything that was an advantage about Firebase. If I have to communicate with the server constantly it seems like it'd be much faster just to make it all in php and MySQL.
Is it in any way possible to edit data constantly (Health, money, lvl, etc), without letting the user touch it, without running the Admin SDK?
Like, I guess what I'm trying to ask is, if there's a way that you can call the database using php instead and then edit the data from there so you prevent the user from editing any of it.

A: You can access the Firebase Database from PHP through its REST API. See the documentation for that, or search for similar questions.
But where would you run that PHP code? Because it'll either be on server or on your own machine, where you could in that case just as easily run the Firebase Admin SDK and get a much nicer API.


text:
Q: Python programming from my phone? I have searched to the point of confusion, so I need some guidance. I want to make a game on Android with Python - ONLY using my android device.
I'm confused in the difference between Kivy and Sl4a and what steps i need to take in order to be able to program and run my game on my phone. I seem to only be able to find outdated or misleading information,  so i apologize if this is simple.
Any guidance is much appreciated. Thanks!

A:
I have searched to the point of confusion, so I need some guidance. I want to make a game on Android with Python - ONLY using my android device.

As others have said, this is somewhere between 'really hard and annoying' and 'impossible'. Especially without a computer to do any of the process!

I'm confused in the difference between Kivy and Sl4a

Kivy is a cross-platform (linux, windows, osx, android, ios, maybe more) graphical framework for python. The same developers maintain a python-for-android project that lets you very easily compile a kivy program to an android apk. You can also do java api interaction etc. using the pyjnius project, which is also maintained by the same devs, and some apis (vibrate, accelerometer etc.) are already abstracted as a python module so you don't have to touch java.
sl4a was originally (I think) a way to run python scripts on android. It has its own way to do some stuff with the android apis, but I don't know the details or what is possible. There are also some ways to package as an apk or to do some kinds of graphical work, but I'm not familiar with this either - I think they're much more limited as a graphical framework than kivy is (not that it sets out to be a full framework in the same way), but I don't know much about it, and at the very least the graphical stuff works in a quite different way that has advantages of its own.
(Edit: Notice all the 'I think' in the previous paragraph? That's because I really don't know for sure and don't want to say something wrong. Don't take my word for it, try it!)
Overall, kivy and sl4a (plus both of their related projects) are separate projects, with different focuses and technical capabilities. I personally think kivy is a more obvious choice for purposes other than basic scripting (though even simple sl4a scripts are useful to make tasker scripts etc.), but while some of kivy's advantages are arguably objective, some of my opinion is subjective.

what steps i need to take in order to be able to program and run my game on my phone

This is really a big topic on its own. Already knowing kivy, I reckon I could throw together a process to do it, but I'd absolutely not want to because it would need a  horribly painful mishmash of other tools interacting in ways that are not a good user experience. In essence, I'd use text editors to create android files to run with kivy's interactive launcher (which is on the play store), and can probably in principle compile to an apk using kivy's online buildozer tools. However, I'll really stress that this is only in principle possible and I can't recommend trying - I think android really does not have a good set of tools for general purpose programming of this sort, and the os doesn't fit well with the multitasking of coding.
If you just want to write scripts and run them, you may have more luck. You can look at apps like qpython and codepad2 lite, along with the sl4a stuff (and probably other apps, these are just a couple I've seen or tried recently) for apps that can let you edit and run these kinds of scripts. This might be usable for certain things, but even then I don't think it would be a fun experience if you also need to switch between reading docs in a different app etc.
So overall...certain things are possible, but building full apps with (say) kivy is not likely to be an easy or pleasant experience with the current tools. Since you say you're constrained by circumstance and not choice, I suggest playing with qpython etc. and seeing what happens, but you aren't missing some fabulous ide that takes all the pain away.


text:
Q: Bootstrap element not hidden I wanna hidden search box in Small Devices(sm) size and instead of that a search button should take place. i wanna my search be like this at sm size.
enter image description here
this is my code:

                        <input type="text" class="form-control" placeholder="جستجو">

                    <button class="btn">ورود</button>
                    <button class="btn">ثبت نام</button>

A: Use

hidden-sm

for more details follow https://getbootstrap.com/docs/3.3/css/

                    <input type="text" class="form-control hidden-sm" placeholder="جستجو">

Devices list

*

*Extra small devices - Phones (<768px)

*Small devices - Tablets (≥768px)

*Medium devices -Desktops (≥992px)

*Large devices -Desktops (≥1200px)

A: To show or hide elements with bootstrap you have to use the display utilities. For example, if you want to show only on Small Devices you must use d-none d-block d-sm-none.
Your code would be like this:

                        <input type="text" class="form-control" placeholder="جستجو">

                    <button class="btn">ورود</button>
                    <button class="btn">ثبت نام</button>

You can find the doc here: https://getbootstrap.com/docs/4.0/utilities/display/


text:
Q: change size or resolution of screen with jquery can we change size of screen of browser with  jquery or something else that affect CSS media screen?
i want to test my responsive site with default resolutions. i have to change windows screen resolution now.
how do http://groundwork.sidereel.com/?url=home change size of screen? -please look at top of front page.

A: This has nothing to do with changing the screen size.
You can set size in CSS or JS. So: "when the document has a width/height of x do a, etc"
It looks like it changes the resolution, but it doesn't.
Check out CSS viewports


text: Q: Can we can get (Job Title) by signing in to Google Auth in the response object Can we get the job title info after signing in with google auth in my response object. I am only getting  the basic info like email, photo URL, name


text:
Q: How to use soot to modify a byte code file, so that I can print some things? I have a target.java:
static void main(){
    int a = 0;

    a++;
    a++;
    return 0;
}

I want to use soot to insert a command so that target.java can output the following sentence "a is = 2" (I do not need the same code format as followed):
static void main(){
    int a = 0;

    a++;
    a++;
    System.out.println("a is = " + a + "\n");
    return 0;
}

Anyone knows how to do it?
I know some things about soot is that I should make an expression first then I should find the last position of main method then I convert the expression into a statement finally I should add the statement into the byte code.
InvokeExpr reportExpr = Jimple.v().newStaticInvokeExpr(//something here);
Stmt reportStmt = Jimple.v().newInvokeStmt(reportExpr);
units.insertBefore(reportStmt, stmt);

What should I put inside the newStaticInvokeExpr()?


text:
Q: Opencv error: assertion failed in wrapPerspective i'm trying to make an AR app, using aruco and Opencv (i'm a newbie). It detects aruco marker, and puts an image on it. I have tried to use wrapPerstective() function, however somethig is wrong, it returns Opencv error assertion failed ((m0.type() == cv_32f m0.type() == cv_64f) in wrapPerspective. Please give me a way to solve it
int main() {
    cv::VideoCapture inputVideo;
    inputVideo.open("gal.mp4");
    cv::Ptr<cv::aruco::Dictionary> dictionary = cv::aruco::getPredefinedDictionary(cv::aruco::DICT_4X4_50);

    cv::Mat sq = imread("zhuz.jpg", CV_LOAD_IMAGE_UNCHANGED);

    while (inputVideo.grab()) {

        vector<Point2f> sqPoints;
        vector<Point2f> p;

        sqPoints.push_back(Point2f(0, 0));
        sqPoints.push_back(Point2f(sq.cols, 0));
        sqPoints.push_back(Point2f(sq.cols, sq.rows));
        sqPoints.push_back(Point2f(0, sq.rows));

        cv::Mat image, warp_matrix;
        inputVideo.retrieve(image);

        Mat cpy_img(image.rows, image.cols, image.type());
        Mat neg_img(image.rows, image.cols, image.type());
        Mat gray;
        Mat blank(sq.rows, sq.cols, sq.type());

        std::vector<int> ids;
        std::vector<std::vector<cv::Point2f>> corners;

        cv::aruco::detectMarkers(image, dictionary, corners, ids);

        if (ids.size() > 0) {
            p.push_back(corners[0][0]);
            p.push_back(corners[0][1]);
            p.push_back(corners[0][2]);
            p.push_back(corners[0][3]);

            Mat wrap_matrix = getPerspectiveTransform(sqPoints, p);

            blank = Scalar(0);
            neg_img = Scalar(0);        // Image is white when pixel values are zero
            cpy_img = Scalar(0);        // Image is white when pixel values are zero

            bitwise_not(blank, blank);

            warpPerspective(sq, neg_img, warp_matrix, Size(neg_img.cols, neg_img.rows)); // Transform overlay Image to the position - [ITEM1]
            warpPerspective(blank, cpy_img, warp_matrix, Size(cpy_img.cols, neg_img.rows));  // Transform a blank overlay image to position
            bitwise_not(cpy_img, cpy_img);       // Invert the copy paper image from white to black
            bitwise_and(cpy_img, image, cpy_img);      // Create a "hole" in the Image to create a "clipping" mask - [ITEM2]
            bitwise_or(cpy_img, neg_img, image);      // Finally merge both items [ITEM1 & ITEM2]
        }

        cv::imshow("out", image);
    }
}


text:
Q: C# expose events with properties I need to expose an event of an instance of a class using a property from a different class.
If I expose an event defined in MyClass with a property defined in the same MyClass, so that the event works like a backing field, everything is fine:
private event EventHandler<EventArgs> _somethingHappened;
public EventHandler<EventArgs> SomethingHappened
{
     get => _somethingHappened;
}

Could sound weird, but it might be useful for some reason.
But if I expose (in the same manner) an event defined in AnotherClass, accessed by an instance of that AnotherClass, as follows:
public EventHandler<EventArgs> SomethingStarted
{
    get => Instance.Started;
}

where Instance is the instance of that AnotherClass and Instance.Started is defined in AnotherClass as follows:
public event EventHandler<EventArgs> Started;

then I get the error: "The event can only appear on the left hand side".
I just don't get why the first case is allowed and the second is not, although they seem very similar.

A: Events do not have getters nor setters, they only have add and remove accessors thus they cannot be used as properties.
By code get => Instance.Started you're trying to get the value of Instance.Started but there is no getter.
What you can do is make SomethingStarted also an event and override add and remove accessors to forward the value to the Instance.Started event:
public event EventHandler<EventArgs> SomethingStarted
{
    add => Instance.Started += value;
    remove => Instance.Started -= value;
}

This way any subscription to SomethingStarted would be "redirected" to Instance.Started without causing event to be re-fired.
Internally, this would be translated into something like:
public void add_SomethingStarted(EventHandler<EventArgs> eventHandler) {
    Instance.add_Started(eventHandler);
}

public void remove_SomethingStarted(EventHandler<EventArgs> eventHandler) {
    Instance.remove_Started(eventHandler);
}

A:
I need to expose an event of an instance of a class using a property from a different class.

You shouldn't use events this way. Event should always be exposed as an event.
What you can do is to expose other class' event through your own class:
public event EventHandler<EventArgs> SomethingHappened
{
    add => Instance.Started += value;
    remove => Instance.Started -= value;
}

This way a subscriber will actually subscribe to the Instance's event. You can wrap it to a method and re-fire an event to change the sender.


text:
Q: SQL Database Operational Error - no such table : users sqlalchemy.exc.OperationalError: (sqlite3.OperationalError) no such table: users
[SQL: SELECT users.id AS users_id, users.username AS users_username, users.password AS users_password
FROM users
WHERE users.username = ?]

the above is the error im getting.
class User(db.Model):

    __tablename__ = "users"
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(24), unique=True, nullable=False)
    password = db.Column(db.String(), nullable=False)

this is my User code.
@app.route('/', methods=['GET', 'POST'])
def index():
    reg_form = Registeration()
    if reg_form.validate_on_submit():
        username = reg_form.username.data
        password = reg_form.password.data

        # for checking if someone has taken the username already
        user_object = User.query.filter_by(username=username).all()
        if user_object:
            return "This username has been taken. Try another one.."

        #registering in the database and commiting and etc
        user = User(username=username, password=password)
        db.session.add(user)
        db.session.commit()
        return 'Registered into the database!'

        return db.create_all()

the application code.
I'm unable to figure out.. any help would be greatly appreciated. Btw im trying to make a registration system where the username and the pass get stored in Postgres Database.


text:
Q: logging with util-linux without systemd unit specified If I log with util-linux logger as below:
/bin/logger "hello world"

I can see through journalctl my log line:
journalctl --since "-1m"
Oct 08 09:12:17 myhomepc duda[11670]: hello world

however what is the default pseudo unit file used that I can filter with?
journalctl -u "duda" --since "-1m"

doesn't return anything.

A: journalctl -t duda --since "-1m" should work.
logger interfaces to the syslog(3) system log module and makes entries in the system log with its SYSLOG_IDENTIFIER (--id), see man logger(1).
journalctl allows filtering of a specified SYSLOG_IDENTIFIER, per man journalctl(1)
-t, --identifier=SYSLOG_IDENTIFIER|PATTERN
    Show messages for the specified syslog identifier SYSLOG_IDENTIFIER, or for any of the messages with a
    "SYSLOG_IDENTIFIER" matched by PATTERN.


text:
Q: Wpf Docking Control with UI Automation compatibility We have slowly been creating UI Automation tests using Ranorex on our product but have ran into several problems.
We are using Telerik Wpf controls (TabControl, TreeView, Grid and Docking) and so far we've only been able to test the TreeView and Grid using Ranorex. We replaced the TabControl for the standard Wpf TabControl which works with Ranorex. However the Docking control does not work and of course there is no standard out of the box Wpf Docking control for us to use instead.
My question is this: Does anybody know of any Wpf Docking controls that can be tested using an UI Automation tool (preferably Ranorex)?
I found AvalonDock, which at first looked promising, but according to this thread on their site it doesn't support UI Automation :(
Cheers for any comments,
Siy

A: As of now, Telerik has their own product that supports UI automation for WPF -  Telerik Test Studio - including RadDocking control.


text:
Q: Silverlight 4 open pdf file in native client application Hi i am working on a silverlight4 application running in browser. now i am trying to open PDF files but pdf files being opened in new tab of the browser. I want them to be open in native  application as adobe or acrobat reader if installed. otherwise prompt a message to user. Any help is welcome. i tried many ways but nothing seems to be working.Tried to use AutomationFactory but not available.

A: Uri uri = new Uri(searchFolder, UriKind.RelativeOrAbsolute);
HtmlPage.Window.Navigate(uri, "_blank", "Left=0,Top=0,Width=900,Height=500,toolbar=no,scrollbars=yes,location=yes,status=no,menubar=no,resizable=yes");


text:
Q: Ansible with dpkg-reconfigure command How to write Ansible YAML for tasks done using dpkg-reconfigure command that ask question during the process?
Example
sudo dpkg-reconfigure slapd

I was trying to write an Ansible playbook to automate reconfiguring slapd with default values.

A: Since Ansible is mainly a Configuration Management Tool with which one declared a Desired State, a Version Control System should be used in general, a non-interactive approach should be the main goal and any interaction should be prevented.
To do so, the within the comments mentioned debconf module – Configure a .deb package could come in place and which can then be used like in How do I make Ansible actually compile a config file having changed my debconf settings for an application?.
Further Similar Q&A

*

*dpkg-reconfigure openssh-server in Ansible playbook

*How to do dpkg-reconfigure dash as bash automatically?

*Feeding input values to dpkg-reconfigure in a non-interactive way


text:
Q: new RecursiveIteratorIterator in Laravels custom model I try to call inside of my laravel models method PHP's RecursiveIteratorIterator as follows
$columns = new RecursiveIteratorIterator(new RecursiveArrayIterator($feeds));

but I get
Class 'App\Models\RecursiveIteratorIterator' not found

How do I include in my Model normally should be accessible
Found it
use \RecursiveIteratorIterator;
use \RecursiveArrayIterator;

A: Try this example:
foreach (new \RecursiveIteratorIterator(new \RecursiveDirectoryIterator($PATH)) as $filename) {
    echo $filename."<br>";
}


text:
Q: Send an SMS for a cloudwatch Alarm outside of us-east? It looks like AWS does not provide SMS as a protocol for SNS topic subscribers outside of US East. I wanted to hook up my CloudWatch alarms and receive text messages when something breaks but cannot send them to SMS.

A: YES!
After some digging I was able to get this to work. It's a little more complicated than just selecting a topic or inputing an alarm but it works great!
The key to the solution was using AWS's lambda functions!
The flow of data is such:

> Alarm triggered
>  -> Push notification to SNS
>  -> SNS posts to lambda
>  -> lambda reposts to SNS on us-east-1
>  -> subscriber receives message

Just the services:

> CloudWatch Alarm   (us-west-2)
>  -> SNS            (us-west-2)
>  -> Lambda         (us-west-2)
>  -> SNS            (us-east-1)
>  -> SMS subscriber (us-east-1)

I won't talk too much about setting up SNS or setting up lambda, you can go through the examples that already exist for that. However, I will share the lambda code that I wrote to perform this. You can test it by using the publish message to topic functionality.
console.log('Loading function');

var Aws = require('aws-sdk');

var usEastSns = new Aws.SNS({
    accessKeyId: "ENTER YOUR ACCESS KEY HERE",
    secretAccessKey: "ENTER YOUR SECRET KEY HERE",
    region: "us-east-1",
    logger: console
});

exports.snsProxy = function(event, context) {
    var message = event.Records[0].Sns;
    console.log("received message: ", message);
    var newMessage = buildNewMessage(message);
    console.log("publishing: ", newMessage);
    usEastSns.publish(newMessage, function(err, data) {
        if (err) {
            console.log(err, err.stack); // an error occurred
        } else {
            // It's important that we succeed in the callback
            // otherwise it seems to succeed without sending
            console.log(data);
            context.succeed(message);
        }
    })
};

function buildNewMessage(message) {
    // For some reason the message that gets sent in the event
    // does not contain the same interface as what the library
    // expects so it needs to be created
    return {
        TargetArn: "ENTER YOUR ARN IN US EAST HERE",
        Message: message.Message,
        Subject: message.Subject,
        MessageAttributes: collectAttr(message.MessageAttributes)
    };
}

function collectAttr(attrs) {
    var newAttrs = {};
    for (var attr in attrs) {
        newAttrs[attr] ={
            DataType: attrs[attr].Type,
            StringValue: attrs[attr].Value
        }
    }
    return newAttrs;
}

This doesn't require any additional libraries other than the aws-sdk that is already in the lambda function. You can feel free to leave out the console logging if you don't want it but it was useful for debugging.
If you use there test functionality, it will likely fail. I believe this is because the callback never happens.
Remember that the lambda should not be on us-east-1 since it will be triggered on whatever region you are using.
Links to tutorials:
SNS Publish api:
http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#publish-property
How to node.js in lambda:
http://docs.aws.amazon.com/lambda/latest/dg/programming-model.html
A really great tutorial on using other aws functions:
http://docs.aws.amazon.com/lambda/latest/dg/with-s3-example.html

A: Here's a more modern/concise similar solution leveraging the new Node 8.10 an environment variable:
const AWS = require('aws-sdk');
const TARGET_ARN = process.env.TARGET_ARN;
var sns = new AWS.SNS({
    region: "us-east-1"
});

exports.handler = async (event) => {
    const message = event.Records[0].Sns;
    return await forwardMessage(message);
};

function forwardMessage(message) {
    const messageToForward = {
        TargetArn: TARGET_ARN,
        Message: message.Message,
        Subject: message.Subject
    };

    return sns.publish(messageToForward).promise();
}

A: Outside of us-east-1 you will not find any protocol like SMS in the protocols dropdown

AWS is not providing a proper solution but you can do some hacks for this
To implement this Solution I am using AWS Lambda but if you are having some HTTP endpoint(any sort of API) then you can also use it, the basic steps are same.

*

*Create a Topic under the SNS section

*Create a Subscription and attach the subscription to the Topic created in point 1

*Go to Lambda service and create a Lambda like below

import json
import boto3
import os

ACCESS_KEY = os.environ.get("ACCESS_KEY", "<your key>")
ACCESS_SECRET = os.environ.get("ACCESS_SECRET", "<your-secret>")
AWS_REGION = os.environ.get("AWS_REGION_NAME", "<your-regoin>")

def execute_sms_service(event, context):
    message = json.loads(event['Records'][0]['Sns']['Message'])
    alarm_name = message['AlarmName']
    alarm_description = message['AlarmDescription']

    recipient_numbers = [<recipient number list>]
    sender_id = <sender_id>
    message = 'Alarm Name: {}\nAlarm Description:{}\n\n '.format(alarm_name, alarm_description)

    sns = boto3.client('sns', aws_access_key_id=ACCESS_KEY,
                   aws_secret_access_key=ACCESS_SECRET,
                   region_name=AWS_REGION)
    for number in recipient_numbers:
        response = sns.publish(
            PhoneNumber=number,
            Message=message,
            MessageAttributes={
                'AWS.SNS.SMS.SenderID': {'DataType': 'String',
                                     'StringValue': sender_id},
                'AWS.SNS.SMS.SMSType': {'DataType': 'String',
                                    'StringValue': 'Promotional'}
            }
        )
        print(response)

*

*After creating the AWS Lambda check the lambda is working properly or not then attach this lambda in the Subscription protocol created in the second point.

*Create an Alarm and configure the action to send the notification to the Topic created in first point

Hope this helps, and please comment if there is some doubt on the above procedure.


text:
Q: Could SALib support other probability distribution when inputing parameters in sensitivity analysis? from SALib.sample import saltelli
import numpy as np

problem = {
  'num_vars': 3,
  'names': ['x1', 'x2', 'x3'],
  'bounds': [-10,10]
}

Must bounds be for a uniform distribution? Could it be an other probability distribution? Such as normal, binormial, poisson, Beta...

A: I want to make an addition to Calvin Whealton's answer which is based on this blog post of (I suppose the same) Calvin Whealton:
SALib supports defining different input parameter distributions in the problem dictionary, although this functionality does not seem to be documented on their official website.
You just need to add a new key 'dists' to the problem dictionary and give a list of strings which encode the distribution type.
The problem definition in that case looks like this:
# problem definition
prob_dists_code = {
'num_vars':6,
'names': ['P1','P2','P3','P4','P5','P6'],
'bounds':[[0.0,1.0], [1.0, 0.75], [0.0, 0.2], [0.0, 0.2], [-1.0,1.0], [1.0,0.25]],
'dists':['unif','triang','norm','lognorm','unif','triang']
}

The values given in 'bounds' then correspond to the parameters of each distribution, e.g. to the mean and standard deviation in the case of a normal distribution. More details can be found in the blog post.

A: If you want other distributions besides uniform from SALib you can do the following:

*

*Generate uniform samples on the interval (0,1).

*Use the inverse cumulative distribution function to convert the input for each parameter into the desired distribution. You can use scipy for the transformation, which should give plenty of flexibility for distributions.

*Evaluate the model with these transformed inputs.

The following example to convert to normal distributions is based on code modified from the SALib site (https://github.com/SALib/SALib).
from SALib.sample import saltelli
from SALib.analyze import sobol
from SALib.test_functions import Ishigami
import numpy as np
import scipy as sp # for inverse CDF (ppf) function for distributions

problem2 = {
  'num_vars': 3,
  'names': ['x1', 'x2', 'x3'],
  'bounds': [[0,1]]*3
}

# Generate samples
param_values2 = saltelli.sample(problem2, 1000, calc_second_order=False)

# using normal inverse CDF, can change to other distributions as desired
# look at scipy documentation for other distributions and parameters
param_values2[:,0] = sp.stats.norm.ppf(param_values2[:,0],0,np.pi/2.)
param_values2[:,1] = sp.stats.norm.ppf(param_values2[:,1],0,np.pi/2.)
param_values2[:,2] = sp.stats.norm.ppf(param_values2[:,2],0,np.pi/2.)

# Run model (example)
Y = Ishigami.evaluate(param_values2)

# Perform analysis
Si = sobol.analyze(problem2, Y, print_to_console=True)


text:
Q: Auto rotation of generated random password I have created a secret.yaml for generating a random password or my application and it works perfect.
{{- if .Values.useSecurity -}}
apiVersion: v1
kind: Secret
metadata:
  name: {{ template "couchdb.fullname" . }}
  labels:
type: Opaque
data:
  {{ if .Values.adminPassword -}}
  couchdb-admin-password: {{ .Values.adminPassword | b64enc | quote }}
  {{ else -}}
  couchdb-admin-password: {{ randAlphaNum 10 | b64enc | quote }}
  {{ end -}}
  couchdb-admin-user: {{ .Values.adminUser | b64enc | quote }}
{{- end }}

But when the user logged in after a few days the rotation of password should take place using a cronjob. It would be great if anyone helps me to achieve this.

A: You can periodically run helm upgrade with the --set flag to change a value in your values yaml. Helm should then update your secret.
helm upgrade <release_name> --set adminPassword=$(openssl rand -hex 16)

You can use other means to generate your secret, but I like using openssl:
$ openssl rand -hex 16
0fec302c52e2d1d2185f404d33be91fb

A: Your CronJob file should look similar like this:
apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: demo-cronjob
spec:
  schedule: "0 0 */1 * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: demo-cron
            image: demo-image:latest
            envFrom:
            - secretRef:
              name: "{{ template "couchdb.fullname" . }}"
              # in your case pass here helm install  command - to run your script
              command: [ "/bin/sh" ]
              args: [ "/var/httpd-init/croyscript.sh" ]
          restartPolicy: OnFailure

Above CronJob named demo-cron will be created, which will run everyday at 00:00 hours (cron format "0 0 */1 * *" ). You can specify scheduling as you wish example: "0 0 * * 0 " - run once a week at midnight on Sunday morning. Once pod is created, I added reference to your secret  - {{ template "couchdb.fullname" . }} . In example above there is defined command which will run bash script which will be executed in pod, in your case you will have to change these two lines with helm install ... command.
Take a look: cronjob-password.


text:
Q: What is the true antonym of "successive"? What is the true antonym of "successive"?
Did the the "true" sound weird?
Well everywhere I looked, I only found subjective antonyms like Broken, Discontinuous, Infrequent, Intermittent, Interrupted, Unconsecutive etc..
But what is the "true" antonym?
For example, if the subjective antonym of "Concentrated" is "Dilute", then the True antonym of "concentrated" is "dispersed". Hope you understand.
Or the True antonym of "Forward" is "Backward" or "moving in reverse"
Likewise, if "successive" was understood as something in relation to "progressive", what is its antonym? Definitely something in the lines of "anti-succession" or likewise.
If it does not in fact exist in the English vocabulary, will I be wrong in the convenient neologism "anti-succession"?
The premise is where I was drafting a question in the Microsoft forum, answers.microsoft.com, in which I wanted to know how to view elements in the clipboard. The elements are supposed to be stacked and displayed in "succession" but I was only seeing the last element (that was stored in succession to the previous element(s) that was strangely extant). So to draft the question I had to address the elements that were lost or not displayed, that were in fact stored previously/opposite to succession.
So what is the true antonym or opposite of succession? Thanks immensely!

*

*well sorry, my bad. well here it is:
I don't just want the programmers at Microsoft to know that, the "previous elements" seem to have dropped out of display (of which I could have just said "the elements prior to the only one displayed are not.. err don't seem to be there). I want to specify that the "order" of elements don't "stretch back" from the one's displayed. Now I hadn't hoped to expect that the Programmers at Microsoft are "linguistic morons". The correct word usage may be essential in their coming with the accurate response ye?

*here it is Trevor. Well what I meant was this:
the clipboard programme is supposed to list out all the clipboard elements in order of their employment. so imagine the carriages of a train, starting from the engine (if the engine is the "middle" carriage). there are 5 carriages before/behind the engine and 5 after/in front of the engine. in my case, the problem is not the carriages in front of the engine, but the carriages behind the engine. I want the programmers to know that the carriages behind the engine are not displayed, and not just "displayed", but they are not displayed in the way they should: in order. or the backward order. now is there a word for backward order? "reverse order" could be a solution, but is there a word, an antonym for the forward flow of things, or "succession". there. cheers!
counter-successive sounds perfect thanks indeed Kris. But I still haven't come across the availability of a single word. but thank you all!

A: If successive means

following another without interruption

then the antonym might be disjunctive

marked by breaks or disunity a disjunctive narrative sequence

An alternative might be discontinuous

a (1) : not continuous  (2) : not continued : discrete discontinuous features of terrain
b : lacking sequence or coherence

A: Concentrated has an inward direction to the concept (particles moving closer together and filling more of the space) while dispersed has an outwardness. Seems what you're looking for is an antonym that addresses the forward flow of successive. *Disjunctive* or discontinuous only contribute an opposite meaning to half of the concept of successive (the continuous part, but not the forward or progressive part).
They wouldn't have worked for your forum question but I think you're looking for something along the lines of regressive and retrograde. They both have that sense of flow/continuity as well as a reverse direction.

added:
Your post seems to ask two questions.
1. How could you have worded your forum question?
2. Is there a better antonym for successive than the ones you've found, an antonym that addresses more aspects of the concept of successive than just continuity?
It also seems that #1 gave rise to #2 out of sheer intellectual curiosity.
Answer to #2 already offered.
Answer to #1: It would have sufficed to ask about all the preceding elements (all emphasizing the reverse flow and that you are interested in more than just the few preceding elements) or about all the elements leading up to the one displayed (meaning all the elements from the 1st to the one displayed).

A: The basic premise of your question is flawed; many words do not have "one true antonym".  This is because most words have multiple meanings or a spectrum of similar meanings with different semantic loads.  Even where a word has one clear meaning, that does not mean there is only one concept which stands in clear contrast to it.  Is "few" the true antonym of "many" or is "one"?
There are several ways in which multiple events could be shown not to be successive:

*

*There might be one large interruption in the sequence, with other conflicting events filling the gap

*Some or all of the events may happen in parallel

*There might only be one event

Which of these is truly not successive?  All of them (and the list is not exhaustive).  Which is most pertinent to you is entirely contextual.

A: It appears that you and this poster are approaching the same words form opposite directions.
I would use in parallel to describe your circumstance.

A: When wanting to refer to "the elements that were ... stored previously", I would have said "the preceding elements. But, in that context, I don't think you want the "opposite [of] succession", but rather the opposite of, perhaps, "following" or "subsequent".
The definition of "succession" is as follows:

succession noun
  1a. a series of people or things that come, happen, etc one after the other;
  1b. the process or an instance of this.
  2a. the right or order by which one person or thing succeeds another;
  2b. the process or act of doing this.
  3. [not relevant]
successional adj. successionally adverb. successionless adj.
in succession one after the other.
in quick succession quickly one after the other.

Note that, by definition, "succession" refers to "a series of people or things".
When you were wanting to view a list of items in the clipboard, they were stored sequentially - i.e. one after the other in the sequence in which they were placed in the clipboard. And, yes, you could describe them as stored in succession (one after the other), but any order of succession (order of storage) would be arbitrary because the items were unrelated.
So, bearing in mind that succession refers to a series of people or things:

*

*You can't really have the opposite of a series in that context, so there can be no opposite of succession.

*You weren't really interested in the series, but merely in the preceding items in the list, with the actual order or sequence being immaterial (if I understand correctly).
In those circumstances, you merely need a word that describes the items that were stored in the list prior to the item you were looking at, and I think preceding is therefore an apt choice.  You could alternatively referred to items that were stored earlier than or prior to the item referred to.
Having said that, one antonym of successor (i.e. the person or item that follows the current one) would be predecessor (i.e. the person or item that precedes (goes before) the current one).


text:
Q: Deliberate Blocking in Akka Actors I understand that Akka actors should not block in order to stay reactive to messages, but how do I structure my service where I want to monitor a process running for an indefinite period of time?
For example, we are using the Amazon Kinesis Connector library. You create a connector with a given configuration, which inherits from Runnable, and then call the Run() method. The connector simply runs indefinitely, pulling data from Kinesis, and writing it to Amazon S3. In fact, if the runnable returns, then that is an error, and it needs to be restarted.
Approach (1) would be to simply create a child actor for each Kinesis Connector running, and if the Run() method returns, you throw an exception, the Supervising Actor notices the exception and restarts the child actor. One connector per child actor per thread.
Approach (2) would be for the child actor to wrap the Kinesis Connector in a Future, and if the future returns, the actor would restart the Connector in another Future. Conceivably a single actor could manage multiple Connectors, but does this mean each Future is executing in a separate thread?
Which approach would be most in line with the philosophy of Akka, or is there some other approach people recommend? In general, I want to catch any problems with any Connector, and restart it. In total there would not be more than a half dozen Connectors running in parallel.

A: I would take approach 1. It should be noted though that actors do not have a dedicated thread by default but they share a thread pool (the so called dispatcher, see: http://doc.akka.io/docs/akka/2.3.6/scala/dispatchers.html). This means that blocking is inherently dangerous because it exhausts the threads of the pool not letting other non-blocked actors to run (since the blocked actors do not put the thread back into the pool). Therefore you should separate blocking calls into a fixed size pool of dedicated actors, and you should assign these actors a PinnedDispatcher. This latter step ensures that these actors do not interfere with each other (they each have a dedicated thread) and ensures that these actors do not interfere with the rest of the system (all of the other actors will run on another dispatchers, usually on default-dispatcher). Be sure though to limit the number of actors running on the PinnedDispatcher since the number of used threads will grow with the number of actors on that dispatcher.

A: Of your two options, I'd say 1 is the more appropriate. No.2 suffers from the fact that, in order to exit from the future monad's world you need to call an Await somewhere, and there you need to specify a max duration which, in your case, does not make sense.
Maybe you could look into other options before going for it, tough. A few keywords that may inspire you are streams and distributed channels.


text:
Q: Tips on making a video uploader secure? So, I cannot seem to find any decent PHP Video Uploaders that use FFMPEG so I've decided to attempt to create my own.
Video uploading is more scarier than images because images has many more tools offered by PHP to validate it's legitimacy. But how do we validate legitimacy with videos? Is there any tips that could help me? Much appreciated!
Also, if you know any Video converters that are useful, could help me further :)


text:
Q: Actual syntax for procedure ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM instead. CONTEXT:  PL/pgSQL function dataret() line 4 at SQL statement SQL state: 42601
I have written procedure code in postgreSQl 11. But while calling the procedure it is giving this error..
create or replace procedure dataret()
language plpgsql
as $$
declare
begin
select * from public.score;
end $$;

I expect output to retrieve all columns from score table but i am getting this error.

A: If you want to return a result use a function, not a procedure.
And you don't need PL/pgSQL for that either, a SQL function will be much more efficient:
create or replace function dataret()
  returns setof public.score
  language sql
as $$
select * from public.score;
$$;

Then use:
select *
from dataret();


text:
Q: How do I get LUA syntax highlighting inside of XML quotes in Sublime Text 3? I have a situation where I end up coding a lot of LUA inside of XML strings,
and it looks quite ugly, to be honest.
It would be extremely nice to be able to have syntax highlighting for the LUA, since that's the main focus of the file; I'm fairly sure that this is supported (apparently SQL is highlighted inside of PHP in some cases), but I have looked for how to edit the syntax files and I'm honestly just stumped. Some of the solutions even seem to suggest I need to edit a .tmLanguage file, but I can't find any of those files and none of the sublime-syntax files look like the same kind of format.
If it makes the situation any easier, the strings containing the LUA always begin with "%function(self) and they always end with end", and I only really want this highlighting functionality in XML.

A: The first step is to open the XML syntax definition for editing. I will explain how to do that. Anything referring to a tmLanguage (XML format) file is out-of-date, Sublime Text 3 now uses sublime-syntax (YAML format) files for all it's default syntax highlighting.
I would recommend cloning the official git repo https://github.com/sublimehq/Packages (please follow the instructions in the repo's readme, which details how to clone a package in such a way that Sublime Text picks it up) so that you will be able to include any future changes made to the official version into your version using git (because we are overriding the default one that would get upgraded automatically with ST, with this customized version). (Basically, you want the XML folder from the repo in your Sublime Packages folder, which is accessible from ST by navigating to the Preferences -> Browse Packages menu item.)
The file we are interested in is XML/XML.sublime-syntax. As you can see, it is full of regular expressions. The one we are most interested in is where it parses XML attributes.
Search for double-quoted-string:. Immediately under this line, paste in the following:
- match: '"(?=%function\(self\))'
  scope: string.quoted.double.xml punctuation.definition.string.begin.xml
  push:
    - clear_scopes: true
    - match: '"'
      scope: string.quoted.double.xml punctuation.definition.string.end.xml
      pop: true
    - include: scope:source.lua

Note that the first character (the - before match) should line up with the original - match: '"' that was there.
Save it. And that's it!

Basically, what we are doing, is:

*

*before the syntax checks for a plain double quote ("), it will look for a double quote followed by the literal string %function(self). It does this using a lookahead, so that it can then include the source.lua scope, and have that %function(self) text/code highlighted properly as LUA (along with the rest of the LUA code).

*Note that it uses clear_scopes: true to ensure that the LUA code doesn't look like XML text/attributes.

*Then, it looks for the closing XML attribute quote (") and "pops" the context off the stack, back to being inside a plain XML tag. (I chose to look for the " without end before it, so that end would still be picked up by the LUA syntax definition. Otherwise we would have to duplicate the match regex and scope for it in the XML syntax, which isn't ideal.)

(You might want to create a new branch in your local repo, and commit these changes, to make it easier to merge future official changes in.)


text:
Q: Can I use OAuth without an app? We have a service we host ourselves (on Azure) that accesses Office 365 via CSOM. We'd like to access a user's site on their behalf without previously installing an app on their site collection.
Is this possible using OAuth, or by any means that doesn't require asking for the user's login details?

A: Having learned a fair bit about OAuth in Office 365 since I posted the question, I can now answer myself:
No, you cannot use OAuth without an app.
However, in on-premise solutions you can set up a High Trust server to communicate without having to use OAuth at all.

A: I think this answers your question.
MSDN - Tips and FAQs: OAuth and remote apps for SharePoint 2013

Get tips and answers to some FAQs for a app for SharePoint that runs
  in a remote web application and communicates back to SharePoint 2013.

A: It can be done (I just finished doing it, it works fine) -
You can read about in more detail in my blog here -
https://medium.com/@yash_agarwal2/performing-oauth-and-rest-calls-with-sharepoint-online-without-creating-an-add-in-677e15c8d6ab#.6pf4wp83b
High level overview -
1) Get client id and secret by registering yourself here -
https://sellerdashboard.microsoft.com/Registration
2) Then follow this link -
https://msdn.microsoft.com/en-us/library/office/jj687470.aspx
(This has a step by step process on how to do this at the end of the article, you will need client id and secret from first step)
More information here -
https://msdn.microsoft.com/en-us/library/office/dn790707.aspx#Flows (search for authentication code flow)
https://msdn.microsoft.com/en-us/library/office/jj687470.aspx
https://msdn.microsoft.com/en-us/library/office/jj220033.aspx


text:
Q: Fixed salt generation based on input string - C# I have this simple class which has 2 methods:
private static byte[] PBKDF2(string field, byte[] salt, int iterations, int outputBytes)

   {
        Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(field, salt);
        pbkdf2.IterationCount = iterations;
        return pbkdf2.GetBytes(outputBytes);
    }

public static string CreateHash(string field, String salt)
    {
        //if (Array.TrueForAll(salt, x => x == 0))
        //{
        //    RNGCryptoServiceProvider csprng = new RNGCryptoServiceProvider();
        //    csprng.GetBytes(salt);
        //    string s = Convert.ToBase64String(salt);
        //}
        byte[] salts = Encoding.ASCII.GetBytes(salt);
        byte[] hash = PBKDF2(field, salts, PBKDF2_ITERATIONS, HASH_BYTE_SIZE);
        return Convert.ToBase64String(hash);
    }

I need to provide a front-end where user enters a simple string like "abc" and I need to generate a salt based on that. This is what I am going to store in the database and use it to pass to the above method (CreateHash) to de-identify
data. This salt/key needs to be able to get decrypted back, which I have to show in the front-end.
I can use other classes/library as well. It need not be Rfc2898DeriveBytes.
Please provide me some inputs on how I can achieve this salt/key generation functionality. This salt can't be a random value.
Thanks!

A: You mention that you need to decrypt the hashed string.
PBKDF2 is NOT an encryption algorithm, but a key derivation function, and you will not be able to calculate the original input from the resulting hash, with or without the salt.
What you should be looking for is encryption, not hashing.
Take a look at this link for some examples.


text:
Q: Mount user-specific folder on logon There is a small network with an active directory, and there is one machine with RAID-1 storage. How can I mount a user-specific shared folder, for example:
\\NetworkStorage\Storage\%USERNAME%

when %USERNAME% performs logon?

A: you can use the NET command to mount a drive:
NET USE F: \\NetworkStorage\Storage\%USERNAME%

(Note that you need to use back slashes, not forward slashes)
This could be added to your logon script.
ALSO, you can specify a "home" drive for each user in his or her active directory profile.  This can be mounted automatically, or with the following command:
NET USE F: /HOME


text:
Q: Raygun client unable to send - failed resolution of InetAddressUtils Is anyone who is using Raygun in their Android apps seeing this error exception:
java.lang.NoClassDefFoundError: Failed resolution of: Lorg/apache/http/conn/util/InetAddressUtils;
    at main.java.com.mindscapehq.android.raygun4android.messages.NetworkInfo.readIPAddress(SourceFile:117)
    at main.java.com.mindscapehq.android.raygun4android.messages.NetworkInfo.<init>(SourceFile:20)
    at main.java.com.mindscapehq.android.raygun4android.messages.RaygunMessageDetails.setNetworkInfo(SourceFile:61)
    at main.java.com.mindscapehq.android.raygun4android.RaygunMessageBuilder.setNetworkInfo(SourceFile:81)
    at main.java.com.mindscapehq.android.raygun4android.RaygunClient.buildMessage(SourceFile:508)
    at main.java.com.mindscapehq.android.raygun4android.RaygunClient.send(SourceFile:221)

This exception is very intermittent, but when it does happen, it always occurs when the app calls RaygunClient.send(...). I'm using Raygun in my app to report error conditions such as a failed webservice call, however, when I report this to Raygun it crashes my app!

A: The release of v3.0.6 includes fixes that address the problems seen with InetAddressUtils NoClassDefFoundError exceptions. Please update to release v3.0.6 and let us know if the problems persist.
Please see our documentation on how to update. https://raygun.com/documentation/language-guides/android/crash-reporting/installation/
Regards,
Mitchell.


text:
Q: generating api without artifacts We have a requirement, saying that generating api without artifacts.
Means there will be no WADL, WSDL, and no services.
As per discussion we need to sniff on a port and generate some sort of WADL?
I don't know how to implement, any thoughts?

A: have a look at the python service on google app engine I have found theme helpful in the past


text:
Q: What is it about natural numbers that makes them a prerequisite for Godel's Incompleteness Theorem to hold? I came across an old question on here asking about Gödel's Incompleteness Theorem and the theory of Real Closed Fields, specifically about why the former doesn't apply to the latter. The top answer explained that the theory of Real Closed Fields avoids the Incompleteness Theorem because it lacks the ability to distinguish between natural numbers and non-natural numbers.
I understand that this inability to pick out a distinct class of natural numbers is relevant because the Incompleteness Theorem requires a formal system to contain natural number arithmetic of a certain complexity, but I'm curious about why the theorem specifically requires natural numbers. I have a very basic understanding of the mechanics behind the Incompleteness Theorem: I know that Gödel's strategy was to encode formulas by mapping symbols to numbers and then using these numbers as the exponents in a product of prime numbers. However, I'm not sure what specific property of natural numbers is required here, beyond some vague intuition about discreteness and the sense that the theory of Real Closed Fields may be "too analog" for Gödel encoding to work.
Is this intuition on the right track? What is it about the distinction between real & natural numbers that determines whether or not the Incompleteness Theorems apply?
Edit: After submitting this question, it occurred to me that perhaps the answer has something to do with the way Gödel encoding relies on the unique factorization theorem to ensure a unique mapping for every sequence of characters. Is this why natural numbers are required?

A: Fundamentally what is needed for the incompleteness theorem argument to go through is that it is possible to use arithmetic to talk about Turing machines. This is explained e.g. by Scott Aaronson:

Alright, should I let you in on a secret? The proof of the Incompleteness Theorem is about two lines. The caveat is that, to give the two-line proof, you first need the concept of a computer.

In particular, Peano arithmetic is capable of making statements of the form "this Turing machine halts on this input" or "this Turing machine halts on some input," etc. Consider a Turing machine $T$ which takes as input another Turing machine and searches for a proof in Peano arithmetic that that Turing machine will halt or not (this is possible because the axioms of Peano arithmetic themselves are computable, so Turing machines can discuss them). Now we can ask: does $T$ halt on every input or run forever on some input?

*

*If $T$ always halts, then (assuming Peano arithmetic is sound!) $T$ can solve the halting problem. But we know that that's impossible. On the other hand:

*If $T$ runs forever on some Turing machine $S$, then Peano arithmetic can't either prove or disprove the statement "$S$ halts," so we've found a statement independent of PA.

This is the first incompleteness theorem. You can click the link to see Scott Aaronson explain the proof of the second incompleteness theorem using a slightly different Turing machine $T'$.
This argument is extremely general. It applies to any consistent formal system which is 1) computable, so Turing machines can talk about it, and 2) powerful enough to talk about Turing machines. These are the "recursive" and "sufficiently powerful" hypotheses in the incompleteness theorem, and as this argument makes clear they are both essential. It is extremely common to see informal statements of the incompleteness theorem which drop one or both of these hypotheses!
So, now the question is: what is it about Peano arithmetic that makes it possible to talk about Turing machines in it, while the same is not true of the theory of real closed fields (RCF)? There are different ways to do this but they all start with some variation of the fact that you can use a natural number to describe a finite list of natural numbers. Godel did this using prime factorizations but this is inessential; any bijection from natural numbers to finite lists of natural numbers that can be described in Peano arithmetic can be used here, e.g. interleaving binary digits.
RCF is much too weak to do anything like this (because its theory is decidable by Tarski's theorem); you might think that we have even more ability to do this here because a real number has infinitely many digits so could store an infinite amount of information, but we can't access any of this information in RCF. In fact it is not possible to talk about the digits of a real number in RCF; RCF can basically only talk about polynomials and the digits, as functions of a real number, are not continuous so are not polynomials.


text:
Q: How to open a project in read-only mode? I manage a lot of similar projects with PhpStorm and it's easy to make changes to the wrong one.
I haven't the opportunity to manage file systems. Currently, I'm using git, and I'm always rolling back changes done on the wrong project. I don't lose data, but I'm still losing my time. It isn't a good enough solution.
Does anyone know if there is a way to open a project in PhpStorm in read-only mode?

A: There's no such option in IDE at this moment. You can vote for a corresponding feature request at https://youtrack.jetbrains.com/issue/IDEABKL-4178 to increase its priority.


text:
Q: How do I use RequestPromise in TypeScript? I have installed request-promise library and trying to use it in my TypeScript app but without much luck.
If I use it like this:
import {RequestPromise} from'request-promise';

RequestPromise('http://www.google.com')
        .then(function (htmlString) {
            // Process html...
        })
        .catch(function (err) {
            // Crawling failed...
        });

I see this on TS compile output:
error TS2304: Cannot find name 'RequestPromise'.

If I use it this way:
import * as rp from'request-promise';

rp('http://www.google.com')
    .then(function (htmlString) {
        // Process html...
    })
    .catch(function (err) {
        // Crawling failed...
    });

I see an error that says that there is no '.then()' method on object rp.
How do I properly use it with TypeScript?

A: You must import all (*) not just RequestPromise:
import * as request from "request-promise";
request.get(...);

This answer elaborates on the differences between import/from and require.

A: request-promise has a package for typescript
npm i --save-dev @types/request-promise
import { get, put, post } from 'request-promise';

Usage
get(options).then(body => {

    console.log(body)

}).catch(e => reject);

A: I use request-promise in this way
import * as requestPromise from 'request-promise';

const options = {
    uri: _url,
    proxy: https://example.host.com:0000,
    headers: {
        Authorization: 'Bearer ' + token
    }
};

requestPromise.get(options, (error, response) => {
    if (error) {
        // Do error handling stuff
    } else {
        if (response.statusCode !== 200) {
             // Do error handling stuff
        } else {
             // Do success stuff here
        }
    }
});


text:
Q: Proof that the generalized inverse of an increasing right-continuous function is also right-continuous Let $a:[0,\infty) \to [0,\infty]$ be an increasing right continuous function, and $\tau:[0,\infty) \to [0,\infty]$ be the generalized inverse, i.e. $\tau(s):=\inf\{t\ge 0: a(t)>s\}, \inf \emptyset = \infty$. Prove that $\tau$ is right continuous.
Proof. $$\{t:a(t)>s\} = \inf_{\epsilon>0} \{t:a(t)>s+\epsilon\}.$$ Therefore, $\inf\{t\ge 0: a(t)>s\} = \inf_{\epsilon>0} \inf \{t\ge 0: a(t)>s+\epsilon\}$ proving right continuity.
I have trouble figuring out why this last equality proves right-continuity. Is there a way to see this immediately? I would greatly appreciate any help.

A: Substituting in the definition of $\tau(s)$, that equation is $$\tau(s)=\inf_{\epsilon>0}\tau(s+\epsilon).$$  This means for any $\delta>0$, there exists $\epsilon>0$ such that $\tau(s+\epsilon)<\tau(s)+\delta$.  Since $\tau$ is increasing, this means $\tau(s)\leq\tau(t)<\tau(s)+\delta$ for any $t$ such that $s\leq t<s+\epsilon$.  This exactly verifies the $\epsilon$-$\delta$ definition of right continuity.

A: Proof that $\tau$ is nondecreasing. If $s'\ge s$, then the set inclusion
$\{t:a(t)>s'\}\subset\{t:a(t)>s\}$ implies
$$\tau(s'):=\inf\{t:a(t)>s'\}\ge\inf\{t:a(t)>s\}=:\tau(s).\tag1$$

Proof that $\tau$ is right continuous. For given $s$, suppose $t$ is such that $a(t)>s$. Then there exists $\delta>0$ such that $a(t)>s+\delta$. So
$$t\ge \inf\{t:a(t)>s+\delta\}=:\tau(s+\delta)\ge\inf_{\delta >0}\tau(s+\delta),\tag2$$
so the RHS of (2) is a lower bound for $\{t: a(t)>s\}$. Therefore
$$\inf_{\delta>0}\tau(s+\delta)\le \inf\{t: a(t)>s\}=:\tau(s).\tag3$$
Let $\epsilon>0$. Inequality (3) says there exists $\delta>0$ such that $\tau(s+\delta)<\tau(s)+\epsilon$. If $s\le s'<s+\delta$ then
$$\tau(s)\stackrel{(1)}\le\tau(s')\stackrel{(1)}\le\tau(s+\delta)<\tau(s)+\epsilon;$$ this means that $\tau$ is right continuous at $s$.

Note that these properties follow from the condition $a(t)>s$ and the definition of infimum. Nowhere do we use the assumption that $a$ is increasing or right-continuous.


text:
Q: Excel VBA GoalSeek by each row in a table I am looking to perform a goal seek within each row of a specified table. The following VBA code successfully executes the GoalSeek.
Sub GoalSeek()
 Dim lo As ListObject
 Dim rw
 Set lo = Sheet1.ListObjects("Table1")

 For rw = lo.DataBodyRange.Rows.Count To 1 Step -1
  Range("M" & rw).GoalSeek Goal:=Range("N" & rw).Value, ChangingCell:=Range("E" & rw)
 Next
End Sub

It fails to execute all the way through and generates run-time error 1004: GoalSeek method of Range class failed

f
Any suggestions on how to resolve? I have attached a copy of the workbook below.
Excel file copy

A: In your loop you have reach the first row and it is not possible to GoalSeek that row.  so change this line of code
For rw = lo.DataBodyRange.Rows.Count To 1 Step -1
to =>
For rw = lo.DataBodyRange.Rows.Count To 2 Step -1


text:
Q: Axios wont send image over form in React-Native I have been chasing this bug for several days and finally found that it is axios. Why does fetch work to upload an image from React-Native to Django REST here:
export const uploadBusinessImage = createAsyncThunk(
  "business/uploadBusinessImage",
  async (imgPath, { rejectWithValue }) => {
    var formData = new FormData();
    formData.append("image", {
      uri: imgPath,
      name: "myfoto.jpg",
      type: "image/jpg",
    });
    const url = "http://10.0.0.241/api/upload/";
    fetch(url, {
      method: "POST",
      headers: {
        "Accept": "application/json",
        "Content-Type": "multipart/form-data",
      },
      body: formData,
    })
  }
);

but axios doesn't work here:
export const uploadBusinessImage = createAsyncThunk(
  "business/uploadBusinessImage",
  async (imgPath, { rejectWithValue }) => {
    try {
      var formData = new FormData();
      formData.append("image", {
        uri: imgPath,
        name: "myfoto.jpg",
        type: "image/jpg",
      });
      const response = await axiosInstance({
        method: "post",
        url: "/api/upload/",
        data: formData,
        headers: {
          "Accept": "application/json",
          "Content-Type": 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'
        },
      });
      console.log(response.data);
      return response.data;
    } catch (err) {
      console.log(err.response.data);
      return rejectWithValue(err.response.data);
    }
  }
);

It creates the object in the database as image: null


text:
Q: How to centre Navigation Bar Currently updating my website and have run into a problem that I can't find a working solution to.
The problem is to do with positioning my nav bar, at the moment it is below some JavaScript and on the left edge of the page, I would like it to be directly below the Java Script and centred, the css followed by the html is below:
ul {
position: absolute;
left: 0;
top: 50%
width: 100%;
text-align: center;
}
li {
float: left;
}

li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
margin: 0
}

li a:hover:not(.active) {
background-color: #111;
}

.active {
background-color: #4CAF50;
}

And the html:

Home

About

Contact

Here is a link to the subdomain I'm currently using to test it on:
http://www.beta.trinity-international.com/
Thanks

A: If you remove all the styling within ul { } and in the li swap float: left; for display: inline-block; it will align in the middle.
I suggest refraining from taking elements out of the flow of the document via absolute positioning where ever possible.

A: First, you missed a ; after top: 50%.
1) Remove position: absolute;
2) Change width of ul to something like 400px (For Test)
3) Add: margin: 0 auto; to ul


text:
Q: Custom directive with $http injection angularjs I want to make a widget by using angularjs's custom directive, but stuck somewhere injecting $http service in it.
var app = angular.module('app',[]);

app.directive('users',function($scope,$http){

  return {

  $http.get('https://jsonplaceholder.typicode.com/users')
  .then(function(response) {

     $scope.user = response.data;
   })
  }

})

Any thought how can it be done? I know above code doesn't work but I have no clue how to continue.

A: This should probably look like:
var app = angular.module('app',[]);

app.directive('users', users);

users.$inject = ['$http'];

function users($http){
  return {
     restrict: 'E', // if it's element
     template: '

{{user.name}}

{{user}}
',  // example template
     link: function($scope){
        $http.get('https://jsonplaceholder.typicode.com/users')
          .then(function(response) {
             $scope.users = response.data;
          });
     }
  };
}

Here's a working jsbin: http://jsbin.com/qepibukovu/1/edit?html,js,console,output


text:
Q: Pass namespaces from java to xslt and use params from java as node in xslt I have a xslt file to transform xml file to pdf using apache-fop. But I don't have all information about namespaces in my xslt. It depends on xml. I can analyze xml document in java and get all namespaces from xml. But I don't know how I can pass this namespaces from java to my xslt file and how next declare it in <xsl:stylesheet> tag. Is it possible?
I can't paste my original xslt and xml because it has sensitive data, but I prepared sample files to show my problem:
    <?xml version="1.0" encoding="UTF-8"?>
<ns0:OtherCompany xmlns:ns8="http://www.company.com/schema/SF/definition/type/test"  xmlns:ns0="http://www.company.com/schema/SF/definition/type/a" xmlns:ns7="http://www.company.com/schema/SF/definition/type/b" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <ns0:Header>
      <ns8:From>2018-01-01</ns8:From>
      <ns8:To>2018-12-31</ns8:To>
      <ns8:CheckDate>2019-03-28</ns8:CheckDate>
      <ns7:Code sysCode="1">Report</ns7:Code>
      <ns7:Type>1</ns7:Type>
   </ns0:Header>
   <ns0:Changes>
      <ns7:I>
         <ns8:AmountA>1499142.61</ns8:AmountA>
         <ns8:AmountB>54979.16</ns8:AmountB>
      </ns7:I>
      <ns7:II>
         <ns8:AmountA>3398983.19</ns8:AmountA>
         <ns8:AmountB>1499142.61</ns8:AmountB>
      </ns7:II>
      <ns7:III>
         <ns8:AmountA>3398983.19</ns8:AmountA>
         <ns8:AmountB>1499142.61</ns8:AmountB>
      </ns7:III>
   </ns0:Changes>
</ns0:OtherCompany>

and xslt:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:fn="http://www.w3.org/2005/xpath-functions"
        xmlns:fo="http://www.w3.org/1999/XSL/Format" exclude-result-prefixes="fo" xmlns:ns0="http://www.company.com/schema/SF/definition/type/a" xmlns:ns7="http://www.company.com/schema/SF/definition/type/b">

    <xsl:param name="xmlPathPrefix"/>

    <xsl:template match="/">
        <fo:root xmlns:fo="http://www.w3.org/1999/XSL/Format">
          <fo:layout-master-set>
            <fo:simple-page-master master-name="simpleA4" page-height="30cm" page-width="26cm" margin-top="2cm" margin-bottom="2cm" margin-left="1cm" margin-right="1cm">
              <fo:region-body region-name="xsl-region-body" margin-top=".80in" margin-bottom=".50in"/>
            </fo:simple-page-master>
          </fo:layout-master-set>
          <fo:page-sequence master-reference="simpleA4">
            <fo:flow flow-name="xsl-region-body">
                <fo:block font-size="10pt" font-family="Arial">
                  <fo:table table-layout="fixed" width="100%">
                    <fo:table-column column-width="12cm" xsl:use-attribute-sets="columnStyle"/>
                    <fo:table-column column-width="12cm" xsl:use-attribute-sets="columnStyle"/>
                    <fo:table-header>
                        <fo:table-row xsl:use-attribute-sets="columnStyle">
                            <fo:table-cell xsl:use-attribute-sets="centerCellStyle">
                                 <fo:block font-weight="bold">Name</fo:block>
                            </fo:table-cell>
                            <fo:table-cell xsl:use-attribute-sets="centerCellStyle">
                                 <fo:block font-weight="bold">Value</fo:block>
                            </fo:table-cell>
                        </fo:table-row>
                    </fo:table-header>
                    <fo:table-body>
                        <xsl:apply-templates select="$xmlPathPrefix//*[not(contains(name(), 'Content'))]"/>
                    </fo:table-body>
                  </fo:table>
                </fo:block>
            </fo:flow>
          </fo:page-sequence>
         </fo:root>
    </xsl:template>

    <xsl:template match="$xmlPathPrefix//*[not(contains(name(), 'Content'))]">
        <fo:table-row xsl:use-attribute-sets="columnStyle">
            <fo:table-cell>
                <fo:block>
                    <xsl:value-of select="sf:addSpaces(local-name(), sf:depth-of-node(.))"/>
                </fo:block>
            </fo:table-cell>
            <fo:table-cell xsl:use-attribute-sets="marginColumnStyle">
                <fo:block>
                    <xsl:choose>
                        <xsl:when test="*">
                            <xsl:value-of select="''"/>
                        </xsl:when>
                        <xsl:otherwise>
                            <xsl:value-of select="current()"/>
                        </xsl:otherwise>
                    </xsl:choose>
                </fo:block>
            </fo:table-cell>
        </fo:table-row>
    </xsl:template>

</xsl:stylesheet>

I want to pass from java param xmlPathPrefix and use it in xslt file in <xsl:template> match attribute
<xsl:template match="/$xmlPathPrefix/values">

or in xsl:apply-templates select attribute
<fo:table-body>
    <xsl:apply-templates select="$xmlPathPrefix//*[not(contains(name(), 'Content'))]"/>
</fo:table-body>

But I get following error:

Type error evaluating ($xmlPathPrefix) in xsl:apply-templates/@select on line 38 column 75 of test.xsl:
    XPTY0019: The required item type of the first operand of '/' is node(); the supplied value
    u"ns0:OtherCompany/ns0:Changes..." is an atomic value

How I can pass xmlPathPrefix from java and use it in my xslt? I want pass example string as xmlPathPrefix

"ns0:OtherCompany/ns0:Changes"

The second problem is my namespace, the pathPrefix can be different, but local-name always the same, Example it can be:
"ns0:OtherCompany/ns0:Changes"
"ns10:OtherCompany/ns15:Changes"
"companyType:OtherCompany/companyChanges:Changes"

or more other options. When I have xslt i must declare tag in <xsl:stylesheet> example ns0, ns10, companyType etc. If I not declare it I get error. But I don't know what namespaces is declared in my xml. How I can pass it to xslt?
Example i pass

xmlPathPrefix: "ns10:OtherCompany/ns15:Changes"
and namespaces for this: ns10 and ns15

But I don't know how reach it.

A: Do you use an XSLT 2 processor like Saxon 9? Your XSLT code says version="2.0". If you are dealing with various namespaces then one way in XSLT/XPath 2 and later is to use a wildcard * for the namespace prefix e.g. *:OtherCompany/*:Changes will select those elements in any namespace.
To parametrize select expressions you would need to use an XSLT 3 processor like Saxon 9.8 or 9.9 and so called shadow attributes like _select and static parameters:
<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="#all"
    version="3.0">

  <xsl:param name="prefix" as="xs:string" static="yes" select="'/*:root/*:foo'"/>

  <xsl:output indent="yes"/>

  <xsl:template match="/">
      <xsl:apply-templates _select="{$prefix}/*:bar"/>
  </xsl:template>

  <xsl:template match="*:bar">
      <xsl:copy-of select="."/>
  </xsl:template>

</xsl:stylesheet>

https://xsltfiddle.liberty-development.net/ej9EGco
You would need to use Saxon's s9api programming interface to set static parameters I think.


text:
Q: Order of execution for Promises I am reading
this documentation
 about Promises and I don't understand something.
const wait = ms => new Promise(resolve => setTimeout(resolve, ms));

wait().then(() => console.log(4));
Promise.resolve().then(() => console.log(2)).then(() => console.log(3));
console.log(1);

There is this example which outputs 1 2 3 4.
So, it is normal that 1 is printed first, but why is 2 3 next and not 4?
They are both inside a then(), 4 is inside a setTimeout but it has no milliseconds passed as parameter.

A: The setTimeout is the entire reason. Try this in contrast:
const wait2 = ms => new Promise(resolve => resolve());

wait2().then(() => console.log(4));
Promise.resolve().then(() => console.log(2)).then(() => console.log(3));
console.log(1);

Where the wait function resolves with no timeout. This does what you expect, 1423
Even if you don't pass a number to setTimeout, the javascript interpreter will wait until the processing queue is cleared before before running the contents of a setTimeout


text:
Q: Kendo UI for Asp .Net core 2.0? Is Kendo UI works with asp .Net core 2.0 ?
If yes, can anyone have any demo on this. As, I am trying to use Kendo UI  for my asp .net core 2.0 project and I am getting some issue there.

A: The instructions from this Getting Started article worked at my side for ASP.NET Core 2.0.

A: The followings are the steps -

*

*Use offline NuGet package for server-side wrapper

*Copy Kendo client-side libraries inside wwwroot/lib/kendo-ui/

*Finally, refrence those in _Layout.cshtml
Inside _Layout.cshtml
<environment names="Development">
    ...
    <link rel="stylesheet" href="~/lib/kendo-ui/styles/kendo.bootstrap.min.css" />
    <link rel="stylesheet" href="~/lib/kendo-ui/styles/kendo.common-bootstrap.min.css" />
    ...
    <script src="~/lib/kendo-ui/js/kendo.all.min.js"></script>
    <script src="~/lib/kendo-ui/js/kendo.aspnetmvc.min.js"></script>
    ...
</environment>
<environment names="Staging,Production">
    ...
    <link rel="stylesheet"
          href="https://kendo.cdn.telerik.com/2017.3.913/styles/kendo.bootstrap.min.css"
          asp-fallback-href="~/lib/kendo-ui/styles/kendo.bootstrap.min.css"
          asp-fallback-test-class="k-common-test-class"
          asp-fallback-test-property="opacity"
          asp-fallback-test-value="0"/>
    <link rel="stylesheet"
          href="https://kendo.cdn.telerik.com/2017.3.913/styles//kendo.common-bootstrap.min.css"
          asp-fallback-href="~/lib/kendo-ui/styles/kendo.common-bootstrap.min.css"
          asp-fallback-test-class="k-theme-test-class"
          asp-fallback-test-property="opacity"
          asp-fallback-test-value="0"/>
    ...
    <script src="https://kendo.cdn.telerik.com/2017.3.913/js/kendo.all.min.js"
            asp-fallback-src="~/lib/kendo-ui/js/kendo.all.min.js"
            asp-fallback-test="window.kendo">
    </script>
    <script src="https://kendo.cdn.telerik.com/2017.3.913/js/kendo.aspnetmvc.min.js"
            asp-fallback-src="~/lib/kendo-ui/js/kendo.aspnetmvc.min.js"
            asp-fallback-test="kendo.data.transports['aspnetmvc-ajax']">
    </script>
    ...
</environment>

I have a sample project in GitHub which happens to use Kendo UI. I also use server-side wrapper, but I could not check-in to public repository due to licensing restriction.

A: The method is same as we use in .Net core 1.So,follow the steps that we are using in .Net core 1 for Kendo setup.


text:
Q: Acoustical Design considerations for Active Noise Cancellation Project for Air vent I am working on ''Active noise cancellation for air vent'' project. I am
using NI myRIO1900, Audio Technica ATR 3350 omni directional microphones
and Tevion Loudspeakers. I have done the programming using LabVIEW and I
have used FPGA module.
I am using sinusoidal noise source of (200-500 Hz) as test noise signal.
I have implemented LMS on LabVIEW, as a preliminary results I am getting
around 8dB noise reduction but these results are pretty random in a sense
only at certain volume levels( if I adjust very carefully), the noise
cancellation is happening and the variation in step size is not giving any
decent change ( again I have to make volume level changes to see some
results).
Over all, I am getting some results but I don't have control over the
results.
This is my set up

[the pipe length is 1 meter]
I know I have to consider secondary path modelling and feedback modelling.
I have actually completed the coding of FBFxLMS also but I dont have any reasonable results with this also.
But my question how to improve the acoustical design of my setup. What are
the problems using just cardboard material to simulate the environment of
air vent ??
I have read in 2-3 places that without proper acoustical design it is not
possible to reduce the noise effectively. Quoting from a paper ''If the
acoustical design of the system is not optimized,the digital controller
may not be able to attenuate the undesired noise adequately.''
The only point I am aware of is using low frequency noises (<= 500Hz) to
consider the sound wave propagation as plane acoustic wave. I am
completely unaware of any other details on how to better my acoustical
design.
I am wondering how to find the limitations of how much a DSP will affect and how much the actual acoustic design. If anyone can provide some reasonable resources to go through, it will be highly appreciated.
Please help me if some one has experience with ANC or Acoustical design.
Thank you.

A: If the duct structure has passive modes that are within the bandwidth of the 'noise' you are imposing, and the active controller they can sap and release energy resulting phase shifts. Also the tube like structure whether closed or open will impose a standing wave resonance with all the possible harmonics that may be near or not near to the frequency you are trying to attenuate. The fact that volume (amplitude ) results in differereces response suggests that there is some component acting in a nonlinear fashion.
But other than these suggestions, and without additional testing, and data, it's difficult to say precisely what your problem (s) are.


text:
Q: htaccess regex wordpress not working I have a wordpress site set up with some custom redirect rules set up. The weird thing is I am sure these all of these were working before but now some of them no longer function.
Here is the complete htaccess file:
RewriteRule ^properties/([a-zA-Z]+)/([a-zA-Z\+\'.]+) /properties/?prov=$1&city=$2&%{QUERY_STRING} [R,NC]
RewriteRule ^properties/([0-9]+) /properties/?id=$1 [R,NC]
RewriteRule ^([0-9][0-9][0-9][0-9][0-9])$ /properties/?id=$1 [R,NC]
RewriteRule ^expand.php?id=([0-9]+) /properties/?id=$1 [R,NC]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
</IfModule>

# END WordPress

right now the only rule that actually works (other than the directory change for wordpress itself) is
 RewriteRule ^([0-9][0-9][0-9][0-9][0-9])$ /properties/?id=$1 [R,NC]

I've tried throwing in simple rules to test, like
 RewriteRule ^/bob /contact [R,NC]

but that doesn't work either
* Edit  the below issue was fixed and is definitely not related to the issue above (but I'll leave it here in case there was a comment that referenced it)*
Also, not sure if this gives any insight but on the page where the redirect actually works, my wordpress theme is broken, the wp_footer never fires and the rest of the page fails

A: There are a couple of possible causes... You aren't enabling mod_rewrite until after your RewriteRules, the custom rules should be included inside their own <IfModule mod_rewrite.c> tag with RewriteEngine on preceding them, and you probably want to set RewriteBase to whatever the root of your site is (perhaps /wordpress subdirectory? you may want to include what you would like these rules to rewrite to and from.) You cannot match on a querystring within a RewriteRule either, you have to use a RewriteCond.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^properties/([a-zA-Z]+)/([a-zA-Z\+\'.]+) /properties/?prov=$1&city=$2&%{QUERY_STRING} [R,NC]
RewriteRule ^properties/([0-9]+) /properties/?id=$1 [R,NC]
RewriteRule ^([0-9]{5,5})$ /properties/?id=$1 [R,NC]
</IfModule>

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]
</IfModule>
# END WordPress

Also updated ^([0-9][0-9][0-9][0-9][0-9])$ to the form ^([0-9]{5,5})$ which is a bit more readable.
Your example/test should look like the following - omit the / because it is set in the RewriteBase.
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^bob /about [R,NC]
</IfModule>

A: Have it like this:
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wordpress/

RewriteRule ^bob/?$ /about [R,NC,L]
RewriteRule ^properties/([a-zA-Z]+)/([a-zA-Z+'.]+)/?$ /properties/?prov=$1&city=$2 [R,NC,QSA,L]
RewriteRule ^(?:properties/)?([0-9]+)/?$ /properties/?id=$1 [R,QSA,NC,L]

RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /wordpress/index.php [L]


text:
Q: iText - Java Android - Adding fields to existing pdf I'm trying to add interactive fields to an existing PDF, i use a PdfReader and a PdfStamper to do this, and when i open it on my tablet, everything is ok. However, when I want to open it on my computer, there are no fields.
This is a sample of my code, I have more than one field for each page but i only printed two fields here:
public class SelfNoteFragment extends Fragment {
    private PdfStamper pdfStamper;

    class MyCellField implements PdfPCellEvent {
        protected String fieldname;
        protected int page;
        public MyCellField(String fieldname, int page) {
            this.fieldname = fieldname;
            this.page = page;
        }
        public void cellLayout(PdfPCell cell, Rectangle rectangle, PdfContentByte[] canvases) {
            final PdfWriter writer = canvases[0].getPdfWriter();
            final TextField textField = new TextField(writer, rectangle, fieldname);
            try {
                final PdfFormField field = textField.getTextField();
                pdfStamper.addAnnotation(field, page);
            } catch (final IOException ioe) {
                throw new ExceptionConverter(ioe);
            } catch (final DocumentException de) {
                throw new ExceptionConverter(de);
            }
        }
    }

    class CheckboxCellEvent implements PdfPCellEvent {
        protected String name;
        protected boolean check;
        protected int page;

        public CheckboxCellEvent(String name, boolean check, int page) {
            this.check = check;
            this.name = name;
            this.page = page;
        }

        public void cellLayout(PdfPCell cell, Rectangle position,
                               PdfContentByte[] canvases) {
            PdfWriter writer = canvases[0].getPdfWriter();
            float x = position.getLeft();
            float y = position.getBottom();
            Rectangle rect = new Rectangle(x-5, y-5, x+5, y+5);
            RadioCheckField checkbox = new RadioCheckField(
                    writer, rect, name, "Yes");
            checkbox.setCheckType(RadioCheckField.TYPE_CROSS);
            checkbox.setChecked(check);
            try {
                pdfStamper.addAnnotation(checkbox.getCheckField(), page);
            } catch (Exception e) {
                throw new ExceptionConverter(e);
            }
        }
    }

    private void createPdf(int idPrevision) throws FileNotFoundException, DocumentException {

        try {
            PdfReader pdfReader = new PdfReader("/storage/emulated/0/Documents/fiche_chantier2.pdf");

            //Create time stamp
            Date date = new Date() ;
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);

            File pdfFolder = new File(Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DOCUMENTS), "Prevision_");
            if (!pdfFolder.exists()) {
                pdfFolder.mkdir();
            }

            File myFile = new File(pdfFolder + timeStamp + ".pdf");

            OutputStream output = new FileOutputStream(myFile);

            this.pdfStamper = new PdfStamper(pdfReader, output);

            PdfContentByte canvas1;
            PdfContentByte canvas2;

            canvas1 = pdfStamper.getOverContent(1);
            canvas2 = pdfStamper.getOverContent(2);

            PdfPCell cellFillFieldPage1 = new PdfPCell();
            cellFillFieldPage1.setCellEvent(new MyCellField("", 1));
            cellFillFieldPage1.setFixedHeight(15);
            cellFillFieldPage1.setBorder(Rectangle.NO_BORDER);
            cellFillFieldPage1.setVerticalAlignment(Element.ALIGN_MIDDLE);

            PdfPCell cellCheckBoxPage2 = new PdfPCell();
            cellCheckBoxPage2.setCellEvent(new CheckboxCellEvent("", false, 2));
            cellCheckBoxPage2.setBorder(Rectangle.NO_BORDER);

            // ************** PAGE 1 ************** //

            // SET TABLE
            PdfPTable tableSection1Page1 = new PdfPTable(1);
            tableSection1Page1.setTotalWidth(136);
            tableSection1Page1.setWidthPercentage(100.0f);
            tableSection1Page1.setLockedWidth(true);

            // ADD CELLS TO TABLE
            tableSection1Page1.addCell(cellFillFieldPage1);

            // PRINT TABLES
            tableSection1Page1.writeSelectedRows(0, -1, 165, 730, canvas1);

            // ************ PAGE 2 ************ //

            // SET TABLES
            PdfPTable tableSection1Page2 = new PdfPTable(1);
            tableSection1Page2.setTotalWidth(10);
            tableSection1Page2.setWidthPercentage(100.0f);
            tableSection1Page2.setLockedWidth(true);

            // ADD CELLS TO TABLE
            tableSection1Page2.addCell(cellCheckBoxPage2);

            // PRINT TABLES
            tableSection1Page2.writeSelectedRows(0, -1, 182, 736, canvas2);

            // I tried this, but it didn't change anything
            pdfStamper.setFormFlattening(false);

            pdfStamper.close();
            pdfReader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }
     }
}

Do you have an idea why my created PDF is good on my Tablet and not on my Computer (same when i want to send it by mail)? If so, do you know how to manage this problem?
Thank you,
Corentin

A: There actually are two issues in your code,

*

*you create the fields with empty names:
cellFillFieldPage1.setCellEvent(new MyCellField("", 1));
...
cellCheckBoxPage2.setCellEvent(new CheckboxCellEvent("", false, 2));

First of all fields need to have a name. And furthermore, even if the empty name was an allowed choice for a name, two fields with the same name are considered to be two representations of the same abstract field which hardly works out if one is a text field and the other a checkbox field.
As soon as you name those fields with non-empty, different names, you'll see that you have fields on Adobe Reader DC/Win: You can tab through them with the TAB key and change their values. Unfortunately, though, they are borderless and, therefore, hard to spot if empty. This is because

*you don't set border colors for your fields. iText, consequently, creates the form field appearance streams without borders.
You can set the border color like this:
...
final TextField textField = new TextField(writer, rectangle, fieldname);
textField.setBorderColor(BaseColor.BLACK);
...
RadioCheckField checkbox = new RadioCheckField(writer, rect, name, "Yes");
checkbox.setBorderColor(BaseColor.BLACK);
...

Having done so, you get the fields with black borders...

If you wonder why different viewers (even by the same company with the same name) behave different here...

*

*Some PDF viewers recognize early that they couldn't properly handle fields with empty names and, therefore, don't even show them while other viewers recognize that later when trying to save or post the form, or don't recognize it at all, producing broken outputs.

*PDF viewers are allowed to ignore appearance streams of form fields (actually of annotations in general) and create their own appearances; thus, in the case at hand they may ignore the borderless appearance generated by iText and draw one with a visible border.


text:
Q: How to iterate over json Data in XSL FO? I am trying to generate pdf with Apache FOP and I will be receiving input data in JSON format. Is there a way to loop over the JSON input in XSL-FO.

A: You need to transform your source -- JSON data, in your case -- into XML in the XSL-FO vocabulary that an XSL Formatter understands.
If you want to use XSLT to do the transformation into XSL-FO, you will find this easier to do if you use an XSLT 3.0 processor, since XSLT 3.0 added built-in support for transforming JSON.  See, e.g.:

*

*https://www.w3.org/TR/xslt-30/#json

*https://www.w3.org/TR/xpath-functions/#json

A: So let's be clear here; you cannot "loop" over anything in XSL-FO, per se.  XSL-FO is essentially an output formatting specification language.  It is not a "programming language" in the richer senses of that phrase.  There is looping that goes on behind the scenes ('for each page, do this and this'), but that's all handled by the engine.  You never declare a looping directly.
What you DO do is take in data (presumably XML data, but not always) using XSLT to transform the input data into XSL-FO.  This FO is a special kind of XML markup that PDF engines (like FOP, Antenna House Formatter, RenderX, Ecrion, etc.) understand and use to format the actual PDF.
It is the XSLT that does the looping (as explicitly programmed by you) through the original input data.
Now as to that input data being JSON, as Tony Graham stated, XSLT 3.0 makes processing that much easier.
There's a nice little blog post here that you can view which describes the process of going from JSON to XML using XSLT 3.0.  Instead of going all the way through, however, and converting the map into a different, neater form of XML, as done in the blog, you can of course just loop through the map elements directly to create your FO.
Now in terms of eliminating the JSON-to-XML step(s), this technically could be done, but would be far more trouble than it's worth just to claim you 'skipped the step'.  The efficiency that that phrase would imply would be horribly misleading, as it would not be efficient at all.  You would be looking at the XSLT taking as input the JSON as a text file, then doing a boat-load of awkward and unjustified string manipulations to output FO directly from that JSON text, as opposed to making things so much simpler and performing the simple step of utilizing the json-to-xml function and then working from that XML data to produce your FO.
Remember, XSLT is at its best when working with XML data.  That's what it was first and foremost designed to do, as opposed to handling large-scale string manipulations like SED or AWK, to take two examples.  Though it can take different inputs, like say a CSV file, the optimal way to handle such inputs is to ultimately represent them as XML input, and then let XSLT really shine by building out your FO.
I hope this helps you and anyone else viewing this post as to the relationships between various forms of possible input data, XSLT, XSL-FO, and PDF.