text:
Q: My mail hosting provider rejects test email relayed from postfix on FQDN-less host, but thunderbird ok When I send mail with Thunderbird via my mail hosting provider, there's no problem. However I set up postfix in the usual way so that it functions as a send-only SMTP server on my DHCP client with no FQDN, but it fails to send.
postfix/pickup[21225]: 264F118807D3: uid=1000 rom=<my.real.acct@my.real.domain.com>
postfix/cleanup[21258]: 264F118807D3: message-id=<20190913174236.264F118807D3@localdomain>
postfix/qmgr[21226]: 264F118807D3: \
    from=<my.real.acct@my.real.domain.com>, size=366, nrcpt=1 (queue active)
postfix/smtp[21261]: 264F118807D3: to=<my-test@blah.com>, \
    relay=mail.myhosting-provider.com[5.6.7.8]:25, delay=3.3, \
    delays=0.03/0.01/3.3/0.04, dsn=5.7.1, status=bounced (host \
    mail.myhosting-provider.com[5.6.7.8] said: 550 5.7.1 Service unavailable; \
    client [1.2.3.4] blocked using zen.spamhaus.org (in reply to RCPT TO command))
postfix/cleanup[21258]: 7D65918807E6: message-id=<20190913174239.7D65918807E6@ecocore.org>
postfix/bounce[21264]: 264F118807D3: sender non-delivery notification: 7D65918807E6
postfix/qmgr[21226]: 7D65918807E6: from=<>, size=2393, nrcpt=1 (queue active)
postfix/qmgr[21226]: 264F118807D3: removed
postfix/smtp[21261]: 7D65918807E6: to=<my.real.acct@my.real.domain.com>, \
    relay=mail.myhosting-provider.com[5.6.7.8]:25, delay=3.2, \
    delays=0.01/0/3.1/0.03, dsn=5.7.1, status=bounced (host \
    mail.myhosting-provider.com[5.6.7.8] said: 550 5.7.1 Service unavailable; \
    client [1.2.3.4] blocked using zen.spamhaus.org (in reply to RCPT TO command))

It seems something about the relaying by postfix is different to the SMTP info that Thunderbird is sending.
I assume the configuration on my mail hosting provider is just set up to block relayed SMTP, and that there's a fundamental difference betweeen that and what Thunderbird is doing.
If so, can I do this at all? Is there a way to configure postfix to use simple SMTP protocol, assuming it's not?

A: Your home/home office IP address is blacklisted for sending email at Spamhaus, as most residential IP addresses are. Any mail recipient whose server subscribes to these blackhole lists will reject your attempts to send mail.
Your options are:

*

*Move your mail server out of the house.

*Switch your Internet connection to business class service.


text:
Q: LaTeX dynamic \rule width depending on text length with titleformat I have a section divider as below:
\documentclass[a4paper,11pt]{article}
\usepackage{xcolor}
\usepackage{titlesec}

\definecolor{pink}{HTML}{F8CBAD}
\definecolor{grey}{HTML}{D9D9D9}

\titleformat{\section}{
  \vspace{-4pt}\scshape\raggedright\large
  }{}{0em}{}[\vspace{-5pt}\color{pink}\rule{5cm}{0.7mm} \color{grey}\rule{13.3cm}{0.7mm}]

\begin{document}
  \section{Research Interests}
  ...
  \section{Selected Courses and Grades}
\end{document}

which gives me output like this:

What I need?
I want to specify the length of the pink line exactly as the text above it, coming from titleformat. and the grey line takes the rest of the line.

A: You can measure the text and use this length. The only complication is that this setting should be global.
\documentclass[a4paper,11pt]{article}
\usepackage{xcolor}
\usepackage{titlesec}

\definecolor{pink}{HTML}{F8CBAD}
\definecolor{grey}{HTML}{D9D9D9}

\titleformat{\section}
 {\large\scshape\filright}
 {}
 {0em}
 {\makesectiontitle}
 [%
  \vspace{-5pt}%
  \color{pink}\rule{\sectiontitlewd}{0.7mm}\hspace{0.33333em}%
  \color{grey}\rule{\dimexpr\textwidth-\sectiontitlewd-0.33333em}{0.7mm}%
 ]
\newlength{\sectiontitlewd}
\newcommand{\makesectiontitle}[1]{%
  \settowidth{\dimen0}{#1}%
  \global\sectiontitlewd=\dimen0
  #1%
}

\begin{document}
  \section{Research Interests}
  ...
  \section{Selected Courses and Grades}
\end{document}

A: Here is a solution with the calcwidth option of titlesec:
\documentclass[a4paper,11pt]{article}
\usepackage{xcolor}
\usepackage[calcwidth]{titlesec}

\definecolor{pink}{HTML}{F8CBAD}
\definecolor{grey}{HTML}{D9D9D9}

\titleformat{\section}{\scshape\raggedright\large}{}{0em}{}%
[\color{pink}{\rule[7pt]{\titlewidth}{0.7mm}}\color{grey}{\rule[7pt]{\dimexpr\textwidth-\titlewidth}{0.7mm}}]

\begin{document}

  \section{Research Interests}

The Clangle-Wangle

  \section{Selected Courses and Grades}

\end{document}

A: \documentclass[a4paper,11pt]{article}
\usepackage{xcolor}
\usepackage{titlesec}

\definecolor{pink}{HTML}{F8CBAD}
\definecolor{grey}{HTML}{D9D9D9}

\titleformat{\section}{
  \vspace{-4pt}\scshape\raggedright\large
  }{}{0em}{}[\vspace{-5pt}\color{pink}\rule{\wd8}{0.7mm}\color{grey}%
  \rule{\dimexpr\linewidth-\wd8}{0.7mm}]

\let\svsection\section
\renewcommand\section[2][\relax]{%
  \sbox8{\large\textsc{#2}}%
  \ifx\relax#1\def\next{\svsection}%
  \else\def\next{\svsection[#1]}%
  \fi\next{#2}%
}

\begin{document}
  \section{Research Interests}
  ...
  \section{Selected Courses and Grades}
\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Store array with parse and use it to filter result Hi Im creating an app where the user can choose between a set of 20 tags when creating their account. The tags they select are stored in an array in the User class. I also have a class with group chats and i want to load the group-chats according to the tags the user choose upon signing in. I understand that I need to use the .wherekey to filter the result. My idea is to access the current users "tags-array" and then use that to filter the result. The backend Im using is parse.com

A: Follow below steps to meet your requirements -
1) While user is in process of profile creation -
1.1) Add the user selected tags to the NSMutableArray.
1.2) Save the tags list to the users data(server/ cloud).
2) After the user signs in
2.1) Load the group chats according to the above tags in the list.
Example source -
- (NSArray *)filterObjects:(NSArray *)objects withTags:(NSArray *)tags
 {
  return [objects filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"tags IN %@", tag]];
}

// given that the 'objects' array is what you get from server
  NSArray *objects = @[
                       @{@"id" : @"1A", @"tag" : @"1"},
                       @{@"id" : @"2A", @"tag" : @"2"},
                       @{@"id" : @"3A", @"tag" : @"3"},
                       @{@"id" : @"1B", @"tag" : @"4"},
                       @{@"id" : @"2B", @"tag" : @"5"},
                       @{@"id" : @"3B", @"tag" : @"6"}
                       ];

  NSArray *filteredObjects = [self filterObjects:objects withTags:@[@"1", @"3", @"4"]];
  NSLog(@"filteredObjects: %@", filteredObjects); // prints them out as dictionaries


text:
Q: Fetch multiple files and write to AWS S3 with nodejs Lambda function I have an array of image urls that I get from an SQS message. I need to download the images and store them in an S3 bucket. If downloading or storing an image fails, I need to catch the error, so I can push the image to another SQS queue for retrying later.
What I have so far does download and store the images, but I don't know how to access the results of the fetch and putObject functions. Also I'm not sure if I'm going about this the right way or if there's a more efficient/better/elegant way to do this.
This is what I have now
const AWS = require("aws-sdk");
const fetch = require("node-fetch")
const s3 = new AWS.S3();

exports.handler = function(event, context) {

    // SQS may invoke with multiple messages
    for (const message of event.Records) {
        const bodyData = JSON.parse(message.body);
        const bucket = 'my_images_bucket';
        const images = bodyData.images;

        let urls = [];

        for (const image of images) {
            urls.push(image);
        }

        let promises = urls.map(image => {
            fetch(image)
                .then((response) => {
                    if (!response.ok) {
                        throw new Error('An error occurred while fetching ' + image + ': ' + response.statusText);
                    }
                    return response;
                })
                .then(async res => {
                    try {
                        const buffer = await res.buffer();

                        console.log(image);

                        // store
                        return s3.putObject(
                            {
                                Bucket: bucket,
                                Key: image,
                                Body: buffer,
                                ContentType: "image/jpeg"
                            }
                        ).promise();

                    } catch (e) {
                        console.log('An error occurred while storing image ' + image + ': ' + e);
                    }
                })
                .catch((error) => {
                    console.error(error);
                });
        });

        Promise.all(promises)
            .then(d => {
                console.log('All images downloaded.');
                console.log('PromiseAll result: ' + d);
            }).catch(e => {
            console.log('Whoops something went wrong!', e);
        });
    }
}

The output I get from this:
INFO All images downloaded.
INFO PromiseAll result: ,,,,
INFO https://myserver/10658272812/image14.jpg
INFO https://myserver/10658272810/image12.jpg
INFO https://myserver/10658272804/image6.jpg
INFO https://myserver/10658272813/image15.jpg
INFO https://myserver/10658272816/image18.jpg

A: I attach the code that I wrote for a similar problem.
     const s3Put = (filename, data, mime, s3Params = {}) => {
        return new Promise((resolve, reject) => {
            s3.putObject({
                Bucket: bucket,
                Key: filename,
                Body: data,
                ContentType:
                ...s3Params
            }, (err, data) => {
                if (err) {
                    return reject(err);
                }
                return resolve(data);
            });
        });
    };

    let filePromise = s3Put(to, content, fileMime, s3Params)
                    .then(() => console.log("MyCode"))
                    .catch(err => {
                        const error = {
                            message: `S3: ${(err.pri && err.pri.message) || (err.internal && err.internal.message)}`,
                            to
                        };
                        errors.push(error);
                        return onError(error);
                    });


text:
Q: TypeError: Cannot read property 'method' of undefined express Im making a dashboard for a Discord Bot, but i keep getting the error TypeError: Cannot read property 'method' of undefined. The code of my app is:
const http = require('http');
const path = require('path');
const client = require("./Client");
const express = require('express');
const reqip = require('request-ip');
const passport = require('passport');
const Discord = require('discord.js');
const session = require('express-session');
const getFilesSync = require("..//Utils/fileWalk");
const SQLiteStore = require("connect-sqlite3")(session);
const { Strategy } = require('passport-discord').Strategy;
const port = process.env.port || 80;

class App {
  constructor(locals = {}) {
    this.express = express();
    this.express.set("view engine", "ejs");
    this.express.set("port", port);
    this.express.set("json spaces", 2);
    this.express.locals = locals;

    / * MiddleWare Functions * /;
    this.express.use(express.json());
    this.express.use(express.urlencoded({
      extended: false
    }))

    this.express.use(reqip.mw());
    this.express.use('/assets', express.static(__dirname + "/../Assets"));

    bindAuth(this.express, client);

    this.express.use(passport.initialize());
    this.express.use(passport.session());
    this.express.use(async (req, res, next) => {
      req.bot = client;
      next();
    });

  this.loadRoutes().loadErrorHandler();
  }

  listen(port) {
    return new Promise((resolve) => this.express.listen(port, resolve));
  }

  loadRoutes() {
    const routesPath = path.join(__dirname, "../routes");
    const routes = getFilesSync(routesPath);

    if (!routes.length) return this;

    routes.forEach((filename) => {
      const route = require(path.join(routesPath, filename));

      const routePath =
        filename === "index.js" ? "/" : `/${filename.slice(0, -3)}`;

      try {
        this.express.use(routePath, route);
      } catch (error) {
        console.error(`Error occured with the route "${filename}"\n\n${error}`);
      }
    });

    return this;
  }

  loadErrorHandler() {
    this.express.use((req, res) => {
      res.status(404);

      if (req.accepts("html")) return res.render("404", {req});

      if (req.accepts("json"))
        return res.send({
          status: 404,
          error: "Not found",
        });

      res.type("txt").send("404 - Not found");
    });

    return this;
  }
}

function bindAuth(app, client) {
  app.use(session({store: new SQLiteStore(), secret: "nosecretlol", resave: false, saveUninitialized: false}))

  passport.serializeUser(function(user, done) {
    done(null, user);
  })

  passport.deserializeUser(function(obj, done) {
    done(null, obj);
  })

  passport.use(
    new Strategy(
      {
        clientID: process.env.bot_id,
        clientSecret: process.env.bot_secret,
        callbackURL: process.env.bot_redirect,
        scope: ["identify", "guilds"]
      },
      function(accessToken, refreshToken, profile, done) {
        process.nextTick(function() {
          profile.tokens = { accessToken }
          return done(null, profile)
        })
      })
    )
  }

module.exports = App;

And in my index i make my app like this:
const App = require("myfile");
(async () => {
await new App().listen(process.env.port || 80)
})()

The error says is in: node_modules\express\lib\router\index.js:139:34)
I tried with all and i cannot solve this, i asked many persons but no ones give me a answer that can solve my question.
Like i said this is for a Discord Bot Dashboard


text:
Q: How to make position absolute responsive? I am building a site in NEXTJS. I have a position absolute on a textbox. When I make the screen smaller the text box stretches all the way to the nav bar rather than staying in its background image.
You can see it https://wycombe-hive.vercel.app/.
I am not sure how to make it responsive for smaller screens.  This is the CSS I have now for the text box
.centeredtwo {
  position: absolute;
  top: 0;
  margin-top: 85%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: black;
  font-weight: bold;
  font-size: 100px;

}


text:
Q: Getting Base64 string from ImageAttachment Control in K2 I am trying to upload an image in sql server using K2 ImageAttachment when I am doing InputMapping the image gets stored as an xml having file path. I want to store it as base64 string of image not xml path but the actual image base64 string. Any clue?
<collection><object><fields><field name='FileName'><value>Capture.PNG</value></field><field name='FilePath'><value>AB177CDDBA29104CD0E1AE3F14DCDD4B\Capture.PNG</value></field><field name='FileRequestData'><value></value></field><field name='FileDataURL'><value></value></field></fields></object></collection>

A: I did this via C#;
    // BMP, GIF, JPEG, PNG, TIFF
using (System.Drawing.Image img = System.Drawing.Image.FromFile(imgPath))
{
    using (MemoryStream ms = new MemoryStream())
    {
        img.Save(ms, img.RawFormat);
        imgNode.Attributes["src"].Value = "data:image/" + imgName.Substring(imgName.LastIndexOf('.') + 1) + @";base64," + Convert.ToBase64String(ms.ToArray());
    }
}


text:
Q: Passing dictionary values to a function, with missing keys I have a class with a constructor that receives several arguments. These arguments I get from an external file, which is a list of dictionaries.
My problem is that some dictionaries have missing fields. If a field is missing, I want the constructor to simply receive None instead. But as the code is written now, it exits on an exception.
This is a simple illustration of the situation
class Person()

    def __init__(self, id, age, name, gender):
        self.id = id
        self.age = age
        self.name = name
        self.gender = gender

people_list = pickle.load(open("some_file.p", "rb"))
first_person = people_list[0]  # this is a dictionary {'id': '1234', 'age': 27, 'name': 'robert'}
Person(first_person['id'], first_person['age'], first_person['name'], first_person['gender'])

As the code is written right now, I get an exception that 'gender' does not exist as a key in the dictionary, which is true. I want any missing field to gets passed a None value, but without doing a billion ifs or try .. excepts. Is there a good way to do this? Obviously without still incurring an exception.

A: In general, you can get a value from a dict with a default if it doesn't exist with:
d = {'a': 1}
print(d.get('b'))  # prints None

But in your case, this would be more appropriate:
class Person():
    # the defaults are defined in the constructor
    def __init__(self, id, age=None, name=None, gender=None):
        self.id = id
        self.age = age
        self.name = name
        self.gender = gender

people_list = pickle.load(open("some_file.p", "rb"))
for person in people_list:
    Person(**person)  # assuming they at least all have an 'id'

Of course, this only works if the keys of the dictionaries match the names of the parameters exactly.
The ** operator 'unpacks' the dictionary, so this:
d = {'a': 1, 'b': 2}
f(**d)

Is the same as:
f(a=1, b=2)


text:
Q: Node.js + Express I was creating a contact form using nodemailer. I implemented it and it was working fine, but some time later I came back to do a final test in postman it started to give me the following error"message": Not Found - /contact and "stack": "Error: Not Found - /contact\n . I am not sure what's causing the error.
this is code:

const transport = {
  host: 'smtp.gmail.com', // Don't forget to replace with the SMTP host of your provider
  port: 587,
  secure: false, // use SSL
  auth: {
    user: process.env.GMAIL,
    pass: process.env.PASSWORD
  }
}

const transporter = nodemailer.createTransport(transport)

transporter.verify((error, success) => {
  if (error) {
    console.log(error);
  } else {
    console.log('Server is ready to take messages');
  }
});

app.post('/contact', (req, res, next) => {
  const name = req.body.name
  const email = req.body.email
  const message = req.body.message
  const content = ` name: ${name} \n email: ${email} \n message: ${message} `

  const mail = {
    from: name,
    // to: 'RECEIVING_EMAIL_ADDRESS_GOES_HERE',  // Change to email address that you want to receive messages on
    to: 'xxx@gmail.com', // Change to email address that you want to receive messages on
    subject: 'New Message from Contact Form',
    text: content
  }

  transporter.sendMail(mail, (err, data) => {
    if (err) {
      res.json({
        status: 'fail'
      })
    } else {
      res.json({
        status: 'success'
      })
    }
  })
})


text:
Q: Export SharePoint Online list to csv via Powershell I tried to export a SharePoint Online list to .csv by using this script:
 How to save a list in a csv file via Powershell
Below is the script:
[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SharePoint.Client') | Out-Null

$login = 'test@test.onmicrosoft.com'
$password = ConvertTo-SecureString 'password' -AsPlainText -Force
$webUrl = 'https://test.sharepoint.com/sites/test/'
$listName = 'My List'

$context = New-Object Microsoft.SharePoint.Client.ClientContext $webUrl
$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials $login, $password

$web = $context.Web
$list = $web.Lists.GetByTitle($listName)
$query = New-Object Microsoft.SharePoint.Client.CamlQuery
$items = $list.GetItems($query)

$context.Load($items)
$context.ExecuteQuery()

$items | Select @{ L = "Title"; E = { $_["Title"] } }, @{ L = "Created"; E = { $_["Created"] } } | Export-Csv -Path export.csv

but I always get this Error:

Cannot contact site at the specified URL
  https://sharepoint.sharepoint.com/Lists/demolist/. There is no Web
  named "/Lists/demolist/_vti_bin/sites.asmx".

When I try to load the site "manually" I can load it.

A: To accomplish your requirement, you need following component locally.
Microsoft.SharePoint.Client.dll

So download it from here
I have tried following script and it worked.
Add-Type -Path "LocalPath\Microsoft.SharePoint.Client.dll"

$webUrl = "https://XXX.sharepoint.com"

$listName = "List Name"

$login = "xxx@yyy.onmicrosoft.com"
$password = Read-Host -Prompt "Enter password" -AsSecureString

$context = New-Object Microsoft.SharePoint.Client.ClientContext $webUrl
$context.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials $login, $password

$web = $context.Web
$list = $web.Lists.GetByTitle($listName)
$query = New-Object Microsoft.SharePoint.Client.CamlQuery
$items = $list.GetItems($query)

$context.Load($items)
$context.ExecuteQuery()

$items | Select @{ L = "Title"; E = { $_["Title"] } }, @{ L = "Created"; E = { $_["Created"] } } | Export-Csv -Path d:\export.csv


text:
Q: Div Overflow on mouse out of div I have a <div> which I set to:
height: 200px;
overflow: auto;

If I point my mouse inside the <div> and scroll up and down, when my mouse leaves the <div>, I need to click outside the <div> to get back my scroll control.
How do I change or add code to make it that on my mouse move out of the <div>, I will gain back the scroll control to the main scroll bar and does not have to click anywhere else.


text:
Q: Using destructuring and renaming with import I'm currently building a bot for Slack using the node-slack-sdk. In their examples they got the following line:
var CLIENT_EVENTS = require('@slack/client').CLIENT_EVENTS;

The CLIENT_EVENTS is then used as follow:
rtm.on(CLIENT_EVENTS.RTM.AUTHENTICATED, function handleRTMAuthenticated() {
  console.log('RTM client authenticated!');
});

I've changed the require in order to use destructuring to directly get the CLIENT_EVENTS.RTM object that I renamed RTM_CLIENT_EVENTS.
const {
  CLIENT_EVENTS: { RTM: RTM_CLIENT_EVENTS },
} = require('@slack/client');

Now, I wanted to change the require to an import:
import {
  CLIENT_EVENTS: { RTM: RTM_CLIENT_EVENTS },
}  from '@slack/client';

But I got the following error:

ES2015 named imports do not destructure. Use another statement for destructuring after the import

Any idea why they don't destructure?

A: The import statement in javascript does not natively support the destructuring syntax.
But you can rename the imports in the following ways:
import {RTM_CLIENT_EVENTS as RTM} from '@slack/client'

Here the RTM_CLIENT_EVENTS propery will be imported and renamed to RTM using the as keyword.

A: import has strict syntax that only mimics shallow destructuring syntax but is supposed to be statically analyzed. So does export, it mimics object literal syntax.
As the error suggests, the proper way to do this is
import { CLIENT_EVENTS }  from '@slack/client';

const { RTM: RTM_CLIENT_EVENTS } = CLIENT_EVENTS;


text:
Q: iPhone & Mailcore memory leak problem In the app I'm currently working, I use Mailcore (http://www.mronge.com/m/MailCore/API/) to handle mail server operations. I'm trying to send a message over an SMTP connection in the background. The problem is, Leaks is telling me that I get a decent amount of memory leaks every time a message sends. I'm trying to figure if this is my fault or Mailcore's fault. Here's the code:
From my view controller:
-(void) send_rfq {

    CTCoreMessage *repMsg = [[[CTCoreMessage alloc] init] autorelease];
    NSDate *now = [NSDate date];

    NSString* msgString = [NSString stringWithFormat:@"Date#%@\nRFQ#%@\nSalesRep#%@",[now description], [rfq_entry get_uid],[rfq_entry get_repid]];
    [repMsg setBody:msgString];
    [repMsg setSubject:@"RFQ Assign"];

    [myAppDelegate performSelectorInBackground:@selector(send_msg:) withObject:repMsg];

    [self.navigationController popViewControllerAnimated:YES];
}

From my app delegate:
-(BOOL) send_bg:(CTCoreMessage*) msg {
    BOOL success = TRUE;
    @try {
        [CTSMTPConnection sendMessage:msg server:smtp_server username:smtp_uname password:smtp_pass port:smtp_port useTLS:smtp_tls useAuth:smtp_auth];
    }
    @catch (NSException * e) {
        //Msg failed to send;
        success = FALSE;
    }
    return success;
}

-(void) send_msg:(CTCoreMessage*) msg {
    NSAutoreleasePool *pool = [ [NSAutoreleasePool alloc] init];
    [msg setTo:[NSSet setWithObject:[CTCoreAddress addressWithName:@"testaccount" email:rfq_dest]]];
    [msg setFrom:[NSSet setWithObject:[CTCoreAddress addressWithName:@"RFQapp" email:rfq_src]]];
    if(![self send_bg:msg]) {
        UIAlertView * empty_alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Could not send." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [empty_alert show];
        [empty_alert autorelease];
    }
    [pool release];
}

A: There are no leaks in the code you've posted. Either the leak is a false positive or it's elsewhere in your code. Have you tried profiling your app with Instruments? Have you tried using Build and Analyze to do static analysis of your code?


text:
Q: Does VS Community 2019 support Xamarin Forms Shell UWP? When I started my solution in VS Community 2019 it said that the Xamarin Forms Shell did not support UWP. I just upgraded VS to 16.9.2 and it now says UWP is a "Preview feature."
So I have a partially-completed Solution with Android and iOS projects. How do I add a UWP project to the existing mostly-completed solution? I try Solution->Add->Project and it seems to want to start a whole new app.

A:
Does VS Community 2019 support Xamarin Forms Shell UWP?

Currently, Visual Studio has not provide complete project template for Xamarin Forms Shell
for UWP platform, and derive from Xamarin Shell document.

Xamarin.Forms Shell is fully available on iOS and Android, but only partially available on the Universal Windows Platform (UWP). In addition, Shell is currently experimental on UWP

As @Jason said, If you do want to add UWP support, please add the project manually, and here is official code sample that contains UWP client. you could refer this to add UWP client.
Xamarin.Forms.Forms.SetFlags("Shell_UWP_Experimental");

For add UWP project for xamarin forms please refer this document.

A: I've got it kind of working. Some issues, but it loads and runs. I created a vanilla app from the new solution template, and used that as a model to hack on the project that was created in my solution from New, Project, UWP.


text:
Q: How to Automatically pull printer settings from printer into the print queue? Is there a way to automate (trigger) the queue properties -> configuration -> 'Update Now-Ask Printer' button?  I need to pull configuration information directly from the printer itself into the queue.  Driver is Lexmark Universal v2 XL if that matters... I think PrintUI only triggers specifics if they are in the registry.  Not sure if Printui can be used? (Win server 2008 r2, 32bit)

A: I think I found a way to automatically do this, the three corresponding checkbox registry keys under configuration are DCDPrtPropOK (On Properties Open), OnPortChange and UpdateConfigurationFromPrinter.  Values are 1 – ON, or 0 – OFF.  Actual location is (computer\HKLM\SYSTEM\CurrentControlSet\Control\Print(drivername)\PrinterDriverData.
Essentially, we need to change DCDPrtPropOK to 1, then run this command:
rundll32 printui.dll,PrintUIEntry /p /n "Lexmark Universal v2 XL"

as a non adm (users if the have the rights) command prompt to trigger Printer Properties.  This should force the printer to open the Printer Properties window, and ask the printers for the settings.


text:
Q: Using $this when not in object context php. Function decode BLOB datatype

<?php

include("config.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// connect to the mysql server
$link = mysql_connect($db_host, $db_user, $db_pass)
or die ("nonono ".mysql_error());

// select the database
mysql_select_db($db_name)
or die ("nonono".mysql_error());
class data {
 public function getchardata($charname,$opt){
            $char = $this->myfetch($this->myquery("select decode(Column1,'decodekey') FROM TableName where Name = '$charname' "));
            $blob = $this->strToHex($char[0]);
        if($opt =='level')return hexdec(substr($blob,52,2));
        if($opt =='coin')return hexdec(substr($blob,26,2).substr($blob,24,2).substr($blob,22,2).substr($blob,20,2));
        if($opt =='pet')return hexdec(substr($blob,66,2).substr($blob,64,2).substr($blob,62,2).substr($blob,60,2));
        if($opt =='credit')return hexdec(substr($blob,74,2).substr($blob,72,2).substr($blob,70,2).substr($blob,68,2));
        if($opt =='exp')return hexdec(substr($blob,44,2).substr($blob,42,2).substr($blob,40,2).substr($blob,38,2).substr($blob,36,2));

    }
}
?>

I have problem with this function: Using $this when not in object context.
Anyone can help please?
updated

A: The idea is to pass $this as parameter of your method/function.
So to call your function you will use something like : getchardata($charname,$opt,$this) and inside your function you refer is as $_this.
    <?php

include("config.php");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
// connect to the mysql server
$link = mysql_connect($db_host, $db_user, $db_pass)
or die ("nonono ".mysql_error());

// select the database
mysql_select_db($db_name)
or die ("nonono".mysql_error());
class data {
    public function getchardata($charname,$opt,&$_this){
            $char = $_this->myfetch($this->myquery("select decode(Column1,'decodekey') FROM TableName where Name = '$charname' "));
            $blob = $_this->strToHex($char[0]);
        if($opt =='level')return hexdec(substr($blob,52,2));
        if($opt =='coin')return hexdec(substr($blob,26,2).substr($blob,24,2).substr($blob,22,2).substr($blob,20,2));
        if($opt =='pet')return hexdec(substr($blob,66,2).substr($blob,64,2).substr($blob,62,2).substr($blob,60,2));
        if($opt =='credit')return hexdec(substr($blob,74,2).substr($blob,72,2).substr($blob,70,2).substr($blob,68,2));
        if($opt =='exp')return hexdec(substr($blob,44,2).substr($blob,42,2).substr($blob,40,2).substr($blob,38,2).substr($blob,36,2));

    }
}
?>


text:
Q: Regex array (["number", "number",...]) Can you help me with expression for array: ["232","2323","233"]
I try this: /^\[("\d{1,7}")|(,"\d{1,7}")\]$/
But this expression is not working properly.
I use ruby(rails).

A: You may try this ( though it may allow leading ,):
^\[(,?"\d{1,7}")*]$

A: This would validate the array structure well, blocking an entry like [,"123"]
^\[(("\d{1,7}")(,"\d{1,7}")*)?\]$

A: Try this: /^\[("\d{1,7}")(, ?"\d{1,7}")*\]$/


text:
Q: How to add a value to an NSOrderedSet I'm using a NSOrderedSet to store the data in a Json server and do it that way because data arrives duplicated and I have to filter them to keep only one value. Now I need to add a value at the beginning of NSOrderedSet. I know how to add value to an NSArray, but not how to pass data from NSOrderedSet to the NSArray.
This is an example of what I get from the server:
{(
    AMAZONAS,
    AMAZONAS,
    ANTIOQUIA,
    ANTIOQUIA,
    ARAUCA,
    "AREA EN LITIGIO",
    "AREA EN LITIGIO",
    ATLANTICO,
)}

with NSOrderedSet sorts the data to avoid repeated as follows:
    deptoArray=[NSOrderedSet orderedSetWithArray:[_data valueForKey:@"Nombre"]];

{(
    AMAZONAS,
    ANTIOQUIA,
    ARAUCA,
    "AREA EN LITIGIO",
    ATLANTICO,
)}

but now I need to add a data at the beginning so that it is as follows:
{(
    Seleccione,
    AMAZONAS,
    ANTIOQUIA,
    ARAUCA,
    "AREA EN LITIGIO",
    ATLANTICO,
)}

A: The standard foundation collection classes are all immutable. So you need to create a mutable version of the collection. Either create it as a mutable ordered set
NSMutableOrderedSet *deptoArray = nil;
// ...
deptoArray= [NSMutableOrderedSet
                 orderedSetWithArray:[_data valueForKey:@"Nombre"]];
[deptoArray insertObject:@"Seleccione" atIndex:0];

or create a mutable copy of the ordered set (skip autorelease if you use ARC)
NSMutableOrderedSet *mutableDeptoArray =
            [[deptoArray mutableCopy] autorelease];
[mutableDeptoArray insertObject:@"Seleccione" atIndex:0];


text:
Q: Why Java SVNKit add folder in a wrong place In my svn repository, the directory hierarchy is like this:
/dirA(exists)/
   /dirB(exists)/

which dirB is in dirA, and both are exist.
Now, i want to add a folder(dirC) in dirB, and a file(file1.txt) in dirC, so i wish directory hierarchy is like this:
/dirA(exists)/
        /dirB(exists)/
                /dirC(added)/
                        /file1.txt(added)

With SVNKit, my SVNRepository's instance is points to dirA,
i use getCommitEditor() to get an ISVNEditor's instance, and call it's openRoot(-1) method, like this:
ISVNEditor svnEditor = svnRepository.getCommitEditor("add folder and file.", null);
svnEditor.openRoot(-1);

i call ISVNEditor's addDir() method and addFile() method to add folder and file, like this:
svnEditor.addDir("dirB/dirC", null, -1);
svnEditor.addFile("dirB/dirC/file1.txt", null, -1);
svnEditor.applyTextDelta("dirB/dirC/file1.txt", null);

SVNDeltaGenerator deltaGenerator = new SVNDeltaGenerator();
String checksum = deltaGenerator.sendDelta("dirB/dirC/file1.txt", new ByteArrayInputStream(data), svnEditor, true);
svnEditor.closeFile("dirB/dirC/file1.txt", checksum);//Closes the new added file.
svnEditor.closeDir(); //Closes the new added folder.
svnEditor.closeDir(); //Closes the root folder.

svnEditor.closeEdit();

After that, why the dirC is being added in dirA, not in dirB, directory hierarchy is become like this:
/dirA(root)/
        /dirB(exists)/
        /dirC(added)/
                /file1.txt(added)

I had indicate the dirC is under dirB when I call
svnEditor.addDir("dirB/dirC", null, -1),

but it doesn't seem to work?
Thanks in advance to answer my question.

A: In order to change the folder you need to provide the local revision of dirB.
//provide your local revision of dirB
long r = ...;
svnEditor.openDir( "dirB" , r );

so now you're under your dirB. Once you're there, you can add the file or folder under dirB. If you want to go further deep say for example in dirC, then you have to provide again local revision of your dirC and add a file there.


text:
Q: SQL Server sort slow with many common values I have a view of invoices that brings in customer name, things like that.
There are a few million rows here over a few hundred customers.  The view is lightning fast - but if I add a sort on Customer Name it takes a while to load (like 3000ms compared to 5ms).
The query joins Invoice to Customer, then sorts by Customer Name then by order number.
I understand why - just wondering if there are any tricks for improving the sort speed?

A: You could add an index on the customer id/name.
You could partition by the table by customer.
The order by is going to take a long time, because -- without an index -- it has to read all the data.  If you use and index or table partition, then you can get the rows without reading the entire table.
To elaborate on the index.  There are two considerations.  The first is whether you are selecting all the rows or only a few.  An index will definitely help the time to first record returned, in most cases.
The second consideration is whether the index helps in fetching all the records.  The question here is selectivity.  If a data page in the invoice table has several hundred records, and there are only several hundred customers, then the index will not help.  On average, each page would have each customer.
If a data page has only a few dozen invoices, then, on average, only one page in about ten would have a given customers invoice -- and, voila, the index would reduce the I/O from a full table scan by a factor of about 10.  (There are other considerations, such as read-ahead but I'm skipping those.)
You don't provide enough information about the system and table structure for a definitive answer, but an index might be useful.


text:
Q: Not returning anything I have
public void mouseClicked(MouseEvent arg0) {
            Number rs = new Number();
            textField_tf.setText(rs.getRandom());
            }

Seperate class
public class Number {

public int getRandom(){

Random rand = new Random();

return rand.nextInt(10) + 1;
}

}

When I click the button nothing is generated in the TextField. I'm quite new to programming but if anything could be pointed out where I'm going wrong would be appreciated.

A: Based on you limited, out of context, code snippets, I'd suggest that the code can't even compile, as JTextField#setText expects a String not an int
For example...
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.border.EmptyBorder;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }

                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel {

        private JTextField field;

        public TestPane() {
            setBorder(new EmptyBorder(10, 10, 10, 10));
            field = new JTextField(2);
            JButton btn = new JButton("Randomise");

            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            add(field, gbc);
            add(btn, gbc);

            btn.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    Number rs = new Number();
                    field.setText(Integer.toString(rs.getRandom()));
                }
            });

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    Number rs = new Number();
                    field.setText(Integer.toString(rs.getRandom()));
                }
            });
        }

    }

    public class Number {

        public int getRandom() {
            Random rand = new Random();
            return rand.nextInt(10) + 1;
        }

    }

}

A: You need to move the declaration of 'Ran' outside of main. It needs to be a class level variable in order for the 'getRan' function to be able to access it.
On a separate note, Java convention would be to name that variable with a lowercase first letter.
Edit. That answer applied to a previous version of the question.
Given the new modification to the question:
public class Number {
    public int getRandom() {
        Random rand = new Random();
        return rand.nextInt(10) + 1;
    }
}

The main problem with this one is declaring a new Random object for each call. You should move the line 'Random rand = new Random()' out of the function, to the class level.


text:
Q: Overriding Method on Instance C# I've been programming Java for years but now I'm working with C#.
Is it possible in C# to override a function when creating an instance of an object?
In  Java it is possible to do this:
View v = new View(this) {
    @Override
    protected void onDraw(Canvas canvas) {
        System.out.println("large view on draw called");
        super.onDraw(canvas);
    }
};

This means that the object v will have it's method "onDraw" overrided. Is it possible to do this in C#? if yes, How?
Many Thanks!

A: You need to do the same thing in C# - create a new version of the class - assume your original code was in a method 'testMethod' within a class 'TestClass':
internal class TestClass : SomeBaseClass
{
    internal virtual void testMethod()
    {
        View v = new ViewAnonymousInnerClassHelper();
    }

    private class ViewAnonymousInnerClassHelper : View
    {
        protected internal override void onDraw(Canvas canvas)
        {
            System.Console.WriteLine("large view on draw called");
            base.onDraw(canvas);
        }
    }
}


text:
Q: Finding and loading global population density raster data into R? I am using the Bioclim dataset for a maxent project right now, but I want to add demographic predictors along with climatic ones. I have the 19 layer raster data from Bioclim and I'm hoping to use the raster::addLayer function to add the demographic data (population density, etc). I'm having a hard time finding a dataset (I've found this one on gridded population density but I'm not sure how to use it) and if I did find one, I'm not sure how to integrate it into R (what I'm using now is a saved .Rdata file which has it loaded in already). This type of project is completely foreign to me.
My concern with any dataset is mismatching spatial resolutions between the layers when using maxent from the dismo package. Is this valid? Here's what I have from the Bioclim:
class       : RasterBrick
dimensions  : 900, 2160, 1944000, 19  (nrow, ncol, ncell, nlayers)
resolution  : 0.1666667, 0.1666667  (x, y)
extent      : -180, 180, -60, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +ellps=WGS84
data source : in memory

It looks like the resolution is 10 arc-minutes, and I see other datasets that are more fine grain. Can I convert from the fine to this coarse? The other problem is the extent of this dataset, it's a little larger than others, can I pad other raster data with blank cells to fit the -60:90 extent?

A: So I was able to take the data from the GPW link above and load that into R with simply raster("path to .bil file"). Converting resolution and dealing with the extent was pretty simple too. Here's how it originally looked:
class       : RasterLayer
dimensions  : 3432, 8640, 29652480  (nrow, ncol, ncell)
resolution  : 0.04166667, 0.04166667  (x, y)
extent      : -180, 180, -58, 85  (xmin, xmax, ymin, ymax)
coord. ref. : NA
data source : /path/to/glds00ag.bil
names       : glds00ag
values      : 0, 123083  (min, max)

Now a few lines will modify the raster to conform to how I want it.
pop.dens <- raster("/path/to/glds00ag.bil")
projection(pop.dens) <- "+proj=longlat +ellps=WGS84" # not sure if entirely necessary
e <- extent(-180,180,-60,90) # match the existing raster
pop.dens <- extend(pop.dens, e) # pad a few values to reach all Latitudes
pop.dens <- aggregate(pop.dens, fun=mean, fac=4) # multiply resolution by 4

Now I've got it aligned with the RasterBrick to which I want to combine it using the function addLayer(bioStack, pop.dens)
class       : RasterLayer
dimensions  : 900, 2160, 1944000  (nrow, ncol, ncell)
resolution  : 0.1666667, 0.1666667  (x, y)
extent      : -180, 180, -60, 90  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +ellps=WGS84
data source : /path/to/tmp/file.bil
names       : glds00ag
values      : 0, 23032.25  (min, max)


text:
Q: psql query to return values that contain space at the start/end of the value specified I have a DB with more than 1,000,000 entries in it, some of them contain space char at the start/end of the value.
I have tried the following queries and it works but i would have to go through 1,000,000 records because all id's are unique
select * from tablename where id like '%1234%';
select * from tablename where id='1234 ';
select * from tablename where id=' 1234';
select * from tablename where id=' 1234 ';

is there a query that can be run that returns all values with space/empty char at the start/end of the value?
Appreciate your help
B

A: You can use a regular expression that says "one or more spaces at the start of the string OR one of more spaces at the end of the string".
select * from tablename where id ~ '^\s+|\s+$';

Each special character:

*

*^ match start of the string

*\s match a white space character

*| the or operator

*+ one or more times

*$ match the end of the string.

A: I found the way to do this
select * from tablename where id like '% %';


text:
Q: How do I get beefalos into caves? The wiki says you can get beefalos into caves.
I tryed with the beefalo horn, getting them to follow me into the cave, but they don't want to go down. Did I do it wrong? Is it impossible?
I am not using any dlcs.

A: You cannot get beefalos into caves, the wiki page says it is a bug.
(Credit to Kyralessa for this, I am merely putting this in answer form because they still have not after months.)

A: It worked fine for me. On Don't Starve ROG for ps3. Just had to carefully get a group over with the horn then wait until they are almost right there at the hole and havn't stopped following  yet. The first time I went down they didn't follow. I went back up and called them towards me again. There was only one or two this time, the others were heading back to their biome but they were very close to the hole this time and when I got down all 5 made it into the caves. They have a directive in the caves apparently maybe the same as where they came from above. So I'm still figuring out where they will settle and might make fence them off in a few areas down there until they settle.


text:
Q: Ansible playbook stops after loosing connection (even for few seconds) with ssh window of VM on which it is running? My ansible playbook consist several task in it and I am running my ansible playbook on Virtual Machine. I am using ssh method to log in to VM and run the playbook. if my ssh window gets closed during the execution of any task (when internet connection is not stable and not reliable), the execution of ansible playbook stops as the ssh window already got closed.
It takes around 1 hour for My play book to run, and sometimes even if I loose internet connectivity for few seconds , the ssh terminal lost its connection and thus entire playbook stops. any idea how to make ansible script more redundant to avoid this problem ?
Thanks in advance !!

A: If you need to run a job on an external system that hangs for a long time and it is relevant that the task completes. It is extremly bad idea to run that job in the foreground.
It is not important that the task is Ansible or the connection is SSH. In every case you would always just "push" the command to the remote host and send it to background with something like "nohup" if available. The problem is of course the tree of processes. Your connection creates a process on the remote system and that creates the job you want to run. Is the connection gets lost, al subprocesses will be killed automatically by the OS.
So - under Windows - maybe use RDP to open a screen that stays available even after connection is lost or use something like Cygwin and nohup via SSH to change the hung up your process from the ssh session.
Or - when you need to run a playbook on that system install for example a AWX container and use that. There are many options based on your requirements, resources and administrative options.


text:
Q: How to fit curve with asymmetric error bars? I got some data as a result of a series of computer simulation with possible results of 1 and 0. They have asymmetric errorbars.
I.E:
xdata = [...]
pdata = [...]
pdatamax = [...]
pdatamin = [...]

I want to fit a sigmoidal curve to my data and tried to do so using the scipy.optimize.curve_fit1 function:
def sigmoid(x,x0,k):
        y = 1./(1+np.exp(-k*(x-x0)))
        return y

popt, pcov = curve_fit(sigmoid, xdata, ydata)

The curve_fit apparently only expects the standard derivation sigma as an argument. How can I fit the curve taking in account the asymmetric error bars?

A: The easiest way to do this is using lmfit.
https://lmfit.github.io/lmfit-py/
it comes with capabilities to run least-sq fitting using scipy routines with a specified "parameters" object that allows you to specify vary/not-vary, min/max and complex relationships:
%pylab inline
import lmfit

def sigmoid(x,x0,k):
        y = 1./(1+np.exp(-k*(x-x0)))
        return y

x = linspace(0,10,100)
x0 = 1
k = 1
y = sigmoid(x, x0, k)
noise = (np.random.rand(100) - 0.5) / 20
y_data = y + noise

def residuals(params, x, y_data):
    x0 = params['x0'].value
    k = params['k'].value
    y_calc = sigmoid(x, x0, k)
    return y_data - y_calc

parameters = lmfit.Parameters()
parameters.add("x0", value=1, vary=True, min=0.1, max=2.0)
parameters.add("k", value=1, vary=True, min=0.1, max=2.0)

result = lmfit.minimize(residuals, parameters, args=(x, y_data))
lmfit.report_fit(result.params)

plot(x, y_data)
plot(x, sigmoid(x, result.params['x0'].value, result.params['k'].value))

output:
Populating the interactive namespace from numpy and matplotlib
[[Variables]]
    x0:   1.01570966 +/- 0.012437 (1.22%) (init= 1)
    k:    0.99250215 +/- 0.012903 (1.30%) (init= 1)
[[Correlations]] (unreported correlations are <  0.100)
    C(x0, k)                     =  0.355

A: curve_fit() accepts the bounds argument starting from SciPy 0.17.0.


text:
Q: Cant DOM added html buttons I want to do something simple, a page that has 0 buttons when loaded, then every click I add a button in a line. when I click any of these buttons it removes it.
I tried to
$(":button").click(function(){
})

but it cant seem to get the button that have been clicked, if I start the page with these buttons already in it , it works. am i missing anything ?

A: Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call.
You need to use Event Delegation using .on() delegated-events approach, when generating elements dynamically or manipulation selector (like removing and adding classes).
General Syntax
$(parentStaticContainer).on('event','selector',callback_function)

Example
$(document).on('click', ":button", function(){
    //Your code
});

In place of document you should use closest static container.

The delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, we can use delegated events to bind the click event to dynamically created elements and also to avoid the need to frequently attach and remove event handlers.

A good read Direct and delegated events


text:
Q: When submitting a form with POST method, 405 Error shows up My project is to have a user input a name of an anime and it will call the Jikan API to give out a list of shows and also display the theme songs links with the Spotify API on a separate HTML file (search.html). However, when trying to submit the form, it will display the correct URL "{website}/search.html" but will give me a 405 error.  I'm using glitch.me to help host my website so I am able to see that the search.html works, but only when I type out the URL not when submitting the form.  When I use a GET request for the form, however, it will display the shows but the Spotify API will give an error ({"error":"invalid_grant","error_description":"Invalid authorization code"}). It will still display the links from Spotify, but Im worried about that error.  I wondering whether it was because of the POST method or something with my code.
index.html
<form action="search.html" onsubmit="testJS()" method="POST" id="theFormID" class="input-wrapper">
    <button name="search" class="fa fa-search"></button>
    <input type="text" id="search" placeholder="Search for anime..." value="" minlength="3">

</form>

If you need to see more of my code let me know!


text:
Q: Determining audio level peaks with ffmpeg Is there a plugin I'm missing that allows me to determine the volume samples over the length of an audio file?
For example, a sample of every second to gain the dB vs timestamp?

A: The ebur128 filter provides info in terms of the Loudness Recommendation EBU R128 metric.
The astats filter can provide this info, in terms of dBs:
ffmpeg -i in.mp3 -af astats=metadata=1:reset=1,ametadata=print:key=lavfi.astats.Overall.RMS_level:file=log.txt -f null -

This produces an output like this:
frame:221  pts:226304  pts_time:4.71467
lavfi.astats.Overall.RMS_level=-67.437152
frame:222  pts:227328  pts_time:4.736
lavfi.astats.Overall.RMS_level=-67.159036
frame:223  pts:228352  pts_time:4.75733
lavfi.astats.Overall.RMS_level=-63.862748
frame:224  pts:229376  pts_time:4.77867
lavfi.astats.Overall.RMS_level=-63.666815

If this is too fine-grained in terms of temporal resolution, increase the reset value which is the frame count for the filter's sampling frequency. For a 1-second slice, an integer approximating audio sampling rate/1000 should be used.


text:
Q: Scope-resolution operator :: versus member-access operator . in C# In C#, what's the difference between A::B and A.B? The only difference I've noticed is that only :: can be used with global, but other than that, what's the difference? Why do they both exist?

A: the :: operator only works with aliases global is a special system provided alias.
so ... this works:
using Foo = System.ComponentModel;

public MyClass {

  private Foo::SomeClassFromSystemComponentModel X;

}

but not this:
public MyClass {

  private System.ComponentModel::SomeClassFromSystemComponentModel X;

}

This lets you escape from the hell of sub namespaces that can come about when you are integrating with a library where they have:
namespace MyAwesomeProduct.System
{

}

And you in you code have
using MyAwesomeProduct;

global:: lets you find the real System.
MSDN info here

A: with :: you can do things like...
 extern alias X;
 extern alias Y;
 class Test
 {
   X::N.A a;
   X::N.B b1;
   Y::N.B b2;
   Y::N.C c;
 }

and there are times when . is ambiguous so :: is needed.  here's the example from the C# language spec
namespace N
{
   public class A {}
   public class B {}
}
namespace N
{
   using A = System.IO;
   class X
   {
      A.Stream s1;         // Error, A is ambiguous
      A::Stream s2;        // Ok
   }
}

http://download.microsoft.com/download/0/B/D/0BDA894F-2CCD-4C2C-B5A7-4EB1171962E5/CSharp%20Language%20Specification.htm


text:
Q: Xcode 7 GM created generic archive instead of iOS app archive I recently started using Xcode 7 GM.
When I archive my project, I get a generic Xcode archive instead of an iOS archive.
I'ved tried pretty much all the following:

*

*xcode is creating generic xcode archive instead of iOS App Archive

*Cannot generate iOS App archive in xcode
I compared the contents of a previous successful archive and a different folder structure for some components:

*

*Swift libraries are inside a sub folder

*The app extension is outside of the .app package

*The info.plist is missing keys

Has anyone else encountering this problem? If so, did you solve and how?
Edit
We are using Cocoapods 0.38.2

A: OP here.
The members of my team all tried Cocoapods' beta and it fixed the problem for us. Therefore I'm going to accept my own answer.
Although it might fix the problem, I believe Christian Navelot's answer to not be scalable and certainly not manageable within a team.
Also, all of us tried using the cp beta without removing the Copy Pod Resources build phase. This means that I won't be accepting Todd Anderson's answer either.
We are not using static libraries either, we are using frameworks (aka use frameworks! inside the Podfile).
Thanks to all for contributing to this question. Looks like we all got put into the same boat by Xcode 7!
Cheers!

A: In my case clearing the "Installation Directory" build setting in all static libraries fixed the issue. It was set to "/usr/local/lib" before.
When using "Save Built Product" as export method the Products folder got these sub directories. That's what pointed me in this direction.
I'm using cocoapods 0.38.2.

A: I add the same problem : an old Xcode project, Xcode 7 (not the GM, the App Store version) and Cocoapods.
I have been tinkering a lot, tried Cocoapds 0.39 b3 and b4 without success, changed params in Build Settings, but finally - for me - the problem was shown by mrezk in https://github.com/CocoaPods/CocoaPods/issues/4021 :

Missing ApplicationProperties in Info.plist

As I'm not used to tinker with Info.plist and these keys, I've found in the Apple Dev forums a very useful answer : https://forums.developer.apple.com/thread/17063
In summary, for info.plist newbies like me ;) :

*

*Archive your project

*Organizer will show a Generic Xcode Archive

*Right Click, Show in finder

*Right Click, Show Package Contents

*Open the Info.plist file in a XML editor

*As mochs indicates, add these lines in the  section :

<key>ApplicationProperties</key>
<dict>
  <key>ApplicationPath</key>
  <string>Applications/<<APP_NAME>>.app</string>
  <key>CFBundleIdentifier</key>
  <string><<BUNDLE_IDENTIFIER>></string>
  <key>CFBundleShortVersionString</key>
  <string><<YOUR_MARKETING_NUMBER>></string>
  <key>CFBundleVersion</key>
  <string><<YOUR_BUILD_NUMBER>></string>
  <key>SigningIdentity</key>
  <string>iPhone Distribution: <<CERTIFICATE_NAME>> (<<CERTIFICATE_ID>>)</string>
</dict>

and replace the tags with your own values.
Save, close Xcode, double click the archive : it should open in the Organizer as a iOS Type Archive.
Thanks to mrezk and mochs for the solution.

A: The other answers mentioned here were temporary fixes, but each required manual effort, either after every archive or after every pod install.
The new, better solution, is to update cocoapods to the latest version and remove your 'Copy Pod Resources' build phase from each app extension.
See https://github.com/CocoaPods/CocoaPods/issues/4021 for more information.

A: I had a similar issue with XCode7.1.1 and an app project with WatchKit Extension.
I fixed the issue by the following step

*

*Open Build Settings of my app target and set NO to "Skip Install".

*Open Build Settings of my WatchKit Extension target and set YES to "Skip
Install"

*Open Build Settings of my WatchKit App target and set YES to "Skip
Install"
Then I could make iOS archive.


text:
Q: Look up value in shadowmap Why does the glsl-function for sampler2DShadow take a vec3, when the depth buffer texture is a 2D texture?
float texture(sampler2DShadow sampler, vec3 P, [float bias]);

A: This texture access does not return real value under the shadow map, but actually the result of comparison between point.z and a value in the map on location (point.x, point.y)- 0 or 1 (for nearest filtering), or value in between when linear filtering is used.

*

*http://www.opengl.org/wiki/Sampler_(GLSL)#Shadow_samplers

*http://www.opengl.org/wiki/Sampler_Object#Comparison_mode
note that GL_TEXTURE_COMPARE_MODE used in glSamplerParameter or glTexParameter should be enabled.


text:
Q: CRM Dynamics 2015 Plugin Cast Error, Specified Cast Is not valid Below is a snippet of the code for the plugin, I also added the WCF service to be consumed(code) as well.
PLUGIN CODE BELOW
if (context.InputParameters.Contains("Target") &&  context.InputParameters["Target"] is Entity)
            {

            Entity phoneCallEntity = (Entity)context.InputParameters["Target"];

            if (phoneCallEntity.LogicalName != "phonecall")
                return;

            if (context.MessageName == "Create")
            {
                try
                {

                    int NumberToCall = phoneCallEntity.Attributes.Contains("phonenumber") ? (int)phoneCallEntity.Attributes["phonenumber"] : 0;
                    int ReceiveCallOn = phoneCallEntity.Attributes.Contains("new_destination") ? (int)phoneCallEntity.Attributes["new_destination"] : 0;
                    string apiKey = phoneCallEntity.Attributes.Contains("new_apikey") ? phoneCallEntity.Attributes["new_apikey"].ToString() : null;
                    int fId = phoneCallEntity.Attributes.Contains("new_fid") ? (int)phoneCallEntity.Attributes["new_fid"] : 0;

                    BasicHttpBinding binding = new BasicHttpBinding();
                    binding.Name = "BasicHttpBinding_IService1";

Here i call the service
 binding.SendTimeout = new TimeSpan(0, 10, 0);
 EndpointAddress endPointAddress = new EndpointAddress("http://localhost:62009/Service1.svc");
 ServiceReference1.Service1Client client = new ServiceReference1.Service1Client(binding, endPointAddress);
 client.WebCall(NumberToCall, ReceiveCallOn, apiKey, fId);

Above I call the WCF Service
public void WebCall(Int64 NumberToCall, Int64 ReceiveCallOn, string APIkey, int FID)
    {
        string url = string.Format("https://xxxx{0},{1},{2}", NumberToCall, ReceiveCallOn, APIkey, FID);
        WebRequest webRequest = WebRequest.Create(url);
        WebResponse webResp = webRequest.GetResponse();
        webRequest.Method = "POST";
    }

Code snippet above is the actual WCF Service being consumed, So the issue is with the casting of the Number toi call and the ReceiveCallOn number, they are both cell phone numbers , in CRM they are a phone data type, any ideas why I cannot cast this.

A: the field phonenumber from entity phonecall is Single Type of Text (with format Phone), this means that is a string (as your custom field if the field settings are the same) so your code can be:
string NumberToCall = phoneCallEntity.Contains("phonenumber") ? phoneCallEntity["phonenumber"].ToString() : "";
string ReceiveCallOn = phoneCallEntity.Contains("new_destination") ? phoneCallEntity["new_destination"].ToString() : "";

A: You should rather use Parse or TryParse. Just casting to int will sometimes convert a char character to its asci value, or have an exception on NULL values. Since you are working with user input I guess the following should be saver. (if you absolutely want int's the below should be ok), I do however agree with the previous post\answer that you should look at working, with strings rather.
so ...
var NumberToCall =0;
var ReceiveCallOn =0;

if (phoneCallEntity.Contains("phonenumber"))
   int.TryParse(phoneCallEntity["phonenumber"].ToString(), out NumberToCall);
if (phoneCallEntity.Contains("new_destination") )
   int.TryParse(phoneCallEntity["new_destination"].ToString(), out ReceiveCallOn);

... just taking your parse exception into consideration .
Or just Parse
if (phoneCallEntity.Contains("phonenumber"))
{
    int NumberToCall = int.Parse(phoneCallEntity["phonenumber"].ToString());
}
if (phoneCallEntity.Contains("new_destination"))
{
    int ReceiveCallOn = int.Parse(phoneCallEntity["new_destination"].ToString());
}


text:
Q: how can I redefine the ruby and rails request.ip and request.remote_ip methods? I've a rails app and I'm trying to overload the request.remote_ip and request.ip in order to use the cloudflare header (HTTP_CF_CONNECTING_IP) if it's present...
I've tried these, but none of them work:
module Rack
  class Request
    class << self
      def ip
        @ip ||= (@env['HTTP_CF_CONNECTING_IP'] || super)
      end
    end
  end
end

module ActionDispatch
  class Request < Rack::Request
    class << self
      def remote_ip
        @remote_ip ||= (@env['HTTP_CF_CONNECTING_IP'] || super)
      end
    end
  end
end

I can't use an extra method like
def connecting_ip
  @env['HTTP_CF_CONNECTING_IP'] || request.remote_ip
end

in the application_controller because I've some other gems (like devise) which use request.ip
Thank you!

A: I believe request is an instance. But you are defining class methods.  Remove the class << self nonsense and you instead be redefining instance methods.
Just a note though, this sounds kind of crazy. Be careful in there. Frameworks dont always like having their guts rearranged.

Your error message when using instance methods means something else is going on.  super calls the superclass implementation. But when you reopen a class and override things, you are literally overwriting the original implementation.  Since the method doesn't exist in the superclass, super doesn't work.
Instead you can use alias to save the original implementation before you declare the new method that would replace it.
module ActionDispatch
  class Request < Rack::Request
    alias :remote_ip_orig :remote_ip
    def remote_ip
      @remote_ip ||= (@env['HTTP_CF_CONNECTING_IP'] || remote_ip_orig)
    end
  end
end

A: If you you want to use CloudFlare and detect the true IP like I did without an Ngingx or Apache module, this monkey patching approach is a really bad idea, this will lead to unexpected results in the future.  You'd be much better off using a Middleware as it should be used.  Here is one that I came up with and have implemented.
module Rack
  class CloudFlareFixup
    def initialize(app)
      @app = app
    end

    def call(env)
      if env['HTTP_CF_CONNECTING_IP']
        env['HTTP_X_FORWARDED_FOR'] = env['HTTP_CF_CONNECTING_IP']
        env['REMOTE_ADDR'] = env['HTTP_CF_CONNECTING_IP']
      end
      @app.call(env)
    end
  end
end

Simply add this into your application.rb
config.middleware.insert_before(0, Rack::CloudFlareFixup)

You can see the complete Gist for this at https://gist.github.com/mattheworiordan/9024372

A: I tried many solutions to this problem.  Here is what I found:

*

*cloudflare-rails gem => this sets both ip and remote_ip to the originating ip.  I wanted ip to represent the cloudflare ip that it came from, and remote_ip to represent the originating ip of the user, so that wouldn't work for me.  It operates by looking up the list of Cloudflare IP ranges every 12 hours and adding those to trusted_proxies.  It then patches: - ActionDispatch::Request.ip, ActionDispatch::Request.remote_ip and Rack::Attack::Request.trusted_proxy? with the cloudflare trusted proxies so that ip and remote_ip ignore them and use the originating ip of the user that initiated the request.

*actionpack-cloudflare gem => this is much simpler.  all it does is directly set ActionDispatch.remote_ip = @env['HTTP_CF_CONNECTING_IP'] which is in accordance with Cloudflare best recommended best practice, but it didn't seem worth it to use a gem for 1 line of code.

*Hand Rolled

# config/initializers/cloudflare.rb

# These values should rarely or never change and Cloudflare should alert us before that happens.
# The list of Cloudflare proxy server ip ranges comes from https://www.cloudflare.com/ips/
CLOUDFLARE_IP_RANGES = [IPAddr.new("103.21.244.0/22"),IPAddr.new("103.22.200.0/22"),IPAddr.new("103.31.4.0/22"),IPAddr.new("104.16.0.0/12"),IPAddr.new("108.162.192.0/18"),IPAddr.new("131.0.72.0/22"),IPAddr.new("141.101.64.0/18"),IPAddr.new("162.158.0.0/15"),IPAddr.new("172.64.0.0/13"),IPAddr.new("173.245.48.0/20"),IPAddr.new("188.114.96.0/20"),IPAddr.new("190.93.240.0/20"),IPAddr.new("197.234.240.0/22"),IPAddr.new("2405:8100::/32"),IPAddr.new("2405:b500::/32"),IPAddr.new("2606:4700::/32"),IPAddr.new("2803:f800::/32"),IPAddr.new("2a06:98c0::/29"),IPAddr.new("2c0f:f248::/32")
]

# By adding the cloudflare IP ranges as trusted_proxies, rails ignores those IPs when setting remote_ip and correctly sets it to the originating IP
Rails.application.config.action_dispatch.trusted_proxies = CLOUDFLARE_IP_RANGES + ActionDispatch::RemoteIp::TRUSTED_PROXIES

Lastly, I wanted to block non-proxied requests
# config/initializers/rack_attack.rb
class Rack::Attack
  class Request < ::Rack::Request
    # Create a remote_ip method for rack request by setting it equal to the cloudflare connecting ip header
    # To restore original visitor IP addresses at your origin web server, Cloudflare recommends your logs or applications
    # look at CF-Connecting-IP instead of X-Forwarded-For since CF-Connecting-IP has a consistent format containing only one IP.
    # https://support.cloudflare.com/hc/en-us/articles/200170986-How-does-CloudFlare-handle-HTTP-Request-headers-
    def remote_ip
      @remote_ip ||= (env['HTTP_CF_CONNECTING_IP'] || ip).to_s
    end

    # This checks the request IP against Cloudflare IP ranges and the action dispatch default trusted proxies.
    # These include various local IPs like 127.0.0.1 so that local requests won't be blocked.
    def proxied?
      Rails.application.config.action_dispatch.trusted_proxies.any? { |range| range === ip }
    end
  end

  # Block all requests coming from non-Cloudflare IPs
  blocklist("block non-proxied requests in production") do |req|
    if req.proxied?
      false
    else
      req.log :warn
      true
    end
  end
end


text:
Q: Visio Selected Page Event I want to do something when the selected (active) page is changed in Visio document. Is there any ways that I can do this?
Thanks.

A: Got the solution...
It can be done by handling WindowTurnedToPage event, fired by Window object.


text:
Q: Difference between Leap motion Gesture types Is there any difference between these two Leap.Gesture.GestureType values?
If there isn't any, then why they are written twice?

A: No, there is no real difference. The versions without the underscores violated the API naming conventions and are deprecated. They haven't been removed so that older code that uses them will still compile. You should use the versions with the underscore in the name.


text:
Q: How to correctly use TS typings with styled-components withComponent()? I have troubles wrapping my head around using withComponent() method of a StyledComponent in a Typescript environment. I have a simple styled component which I want to apply on a React component. But the Typescript compiler complains about a props mismatch.
How should I use the withComponent() method to get a styled component, which has also the props from my react component?
import React from 'react';
import styled from 'styled-components';

const RedBackground = styled.div`
    background-color: red;
`;

interface MenuContainerProps {
    focus?: boolean;
}

class MenuContainer extends React.Component<MenuContainerProps> {
    static defaultProps = {
        focus: true,
    };

    render() {
        return (

MenuContainer

        );
    }
}

const RedMenuContainer = RedBackground.withComponent(MenuContainer);
//                                       error here  ^^^^^^^^^^^^^

/*
    Usage of RedMenuContainer. It should have a red `background-color` and a `focus` prop.

    <RedMenuContainer focus={true}>
        ... children ...
    </RedMenuContainer>
*/

The error message:
[ts]
Argument of type 'typeof MenuContainer' is not assignable to parameter of type 'ComponentClass<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>>'.
  Types of property 'defaultProps' are incompatible.
    Type '{ focus: boolean; }' has no properties in common with type 'Partial<DetailedHTMLProps<HTMLAttributes<HTMLDivElement>, HTMLDivElement>>'.

A: This is a known issue with the Styled Component TypeScript types unfortunately.  The workaround for now would be to force the correct resulting type:
import styled, { StyledComponentClass } from 'styled-components';

// ...

type StyledRedMenuContainer = StyledComponentClass<MenuContainerProps, any, MenuContainerProps>
const RedMenuContainer = RedBackground.withComponent(MenuContainer as any) as StyledRedMenuContainer;

There has been some work to fix the TypeScript types for withComponent, but I believe it may be stalled as for Styled Components 4.0 the TypeScript types are being extracted externally to DefinitelyTyped.
As a side note, your MenuContainer in this case would need to accept a className prop and pass it to its child
 in order for it to actually pick up the red style.


text:
Q: LearnDash lesson_complete Shortcode I'm using LearnDash for WordPress and am trying to write a custom shortcode.
I need a shortcode that will display specific text when a Lesson is Complete.
I'm not great (at all!) with WordPress functions or writing shortcodes, but I really need this!
I'd like to be able to wrap shortcodes around some text and only display the text if the current lesson is complete.
[lesson_complete] TEXT HERE [/lesson_complete]
LearnDash provided some code for when the lesson is complete, but I'm not sure how I would use it to write the shortcode.
add_action("learndash_lesson_completed", function($data) {
    //Called when lesson is completed
}, 5, 1);

I've tried this, but I'm sure I'm way off...
//Create a shortcode for Lesson Complete
function is_lesson_complete ($content = null){
    $lessonDone = 0;
    add_action("learndash_lesson_completed", function($data) {
        $lessonDone = 1;
    }, 5, 1);
    if ( $lessonDone == 1 ){

        return $content;
    } else {

        return "";
    }
}
    //add a shortcode which calls the above function
    add_shortcode('lesson_complete', 'is_lesson_complete' );

Any help would be greatly appreciated!

A: It's very interesting question,Let's divide this problem into two small parts.
First is
how to create proper custom shortcode in wordpress ?
Second is How to check if course is complete call function that will display our desire text in our current scenario.
Good News! you're going good you just need to do few things clean.
For LearnDash -
If Course has been completed. it will display the function.
you just have to create a function like this and return whatever you want to return.
but before using learnDash course complete code.
here you go
learn how to make a proper shortcode in wordpress.
add_action("learndash_course_completed", function($data) {
//Called when course is completed
}, 5, 1);

Reference link
I hope this will help you :) Happy Coding.


text:
Q: Extraneous solutions without performing squaring operation
Solve in $[0, 2\pi]$ $$\sec x+\tan x=2\cos x$$

My mind boggled while solving the trigonometric equation in two different ways:
Method $1.$
Assuming $x\ne \frac{\pi}{2},\frac{3\pi}{2}$
We have:
$$\sec x+\tan x=2\cos x$$
$\implies$
$$\sec x-\tan x=\frac{1}{2\cos x}$$
Adding both we get
$$2\sec x=2\cos x+\frac{1}{2\cos x}$$
$\implies$
$$\frac{3}{2\cos x}=2\cos x$$
$\implies$
$$\cos x=\frac{\pm \sqrt{3}}{2}$$
which gives four solutions in $[0,2\pi]$ which are $\frac{\pi}{6},\frac{11\pi}{6},\frac{5\pi}{6},\frac{7\pi}{6}$ but only two of them which are $\frac{\pi}{6}, \frac{5\pi}{6}$ satisfying the original equation.
Method $2.$
Writing the given equation as
$$\frac{1}{\cos x}+\frac{\sin x}{\cos x}=2\cos x $$
Then we get
$$1+\sin x=2(1-\sin^2 x)$$
$\implies$
$$2\sin^2 x+\sin x-1=0$$
$\implies$
$$\sin x=-1, \sin x=\frac{1}{2}$$
Since $x\ne \frac{\pi}{2},\frac{3\pi}{2}$ we can ignore $\sin x=-1$. Thus we have
$\sin x=\frac{1}{2}$ which gives the two solutions $\frac{\pi}{6}, \frac{5\pi}{6}$
My question is why am i getting two extraneous solutions in Method $1$ even though they are in the domain of $\sec x$ and $\tan x$?

A: Note that this is not limited to trigonometric equations.
You obtained $\sec(x)-\tan(x)=\frac 1{2\cos(x)}$ by taking the inverse of both sides of the equation.
Let examine the very simple case $x=2\iff \dfrac 1x=\dfrac 12$
Notice that when summing these two equations $x+\dfrac 1x=\dfrac 52$ you now end up with two solutions $2$ and $\frac 12$.
This happens because you symmetrized the equation to $S(x,\frac 1x)=0$, therefore whenever $x$ is solution, $\frac 1x$ is solution too and the extraneous $\frac 12$ appears.
This is more or less the same issue here, but of course because we are dealing with trigonometric functions, the extraneous solutions are not just the inverses, but the principle is the same.

A: Hint
Subtract the two equation to find $$2\tan x=2\cos x-\dfrac1{2\cos x}$$
As $\cos x\ne0,$
multiply out both sides by $2\cos x,$ to find $$4\sin x=4\cos^2x-1=4(1-\sin^2x)-1$$
Your solution needs to satisfy this equation as well


text:
Q: Insert character between div bootstrap I've a simple row where there's a label and two input type number
<form class="form-horizontal">

    Numero documento:

      <input type="number" id="firstDocumentNumber" class="form-control">

      <input type="number" id="secondDocumentNumber" class="form-control">

</form>

I need to insert a slash ( / ) between the two input type like this

Can anyone help me, please? Here there's the code I use Bootply
Thanks in advance

A: Simplest way I found is with CSS (tried with Bootstrap 4):

  <input type="number" id="secondDocumentNumber" class="form-control">

#secondDocumentNumberCont:before {
    content: '/';
    position: absolute;
    margin-left: -8px;
    line-height: 2.3em;
}

margin-left & line-height might require some tuning.

A: You shuold use a span and format with size and align how you prefer..

    <form class="form-horizontal">

        Numero documento:

          <input type="number" id="firstDocumentNumber" class="form-control">

            /

          <input type="number" id="secondDocumentNumber" class="form-control">

    </form>

or use an add-on

   /
   <input type="text" class="form-control" placeholder="Username" aria-describedby="basic-addon1">


text:
Q: How to retrieve create statement for table from db in C# How to retrieve create statement for table from db in C#?
I need to create a script file containing create statement
for an existing table in db using C#.
I can generate create statement of storedproc using sp_helptext but can't generate it for table.
Please help.

A: this is joke.

*

*use sqlmetal.exe and compile output.

*use DataContext.CreateDatabase (use
Log property of DataContext to get SQL Code)

A: It's not supported for tables although a quick google gives a script
http://social.msdn.microsoft.com/Forums/en-US/transactsql/thread/28eeb603-1607-4b56-9461-3c0502cbec9c


text:
Q: javafx 1.3 jnlp not working I have a javafx 1.3 application that it is running perfectly with "javafx -jar myjar.jar" but I need to distribute it and I'm building the jnlp corresponding file. The problem is that each time that I run it I have the following error:
Java Web Start 1.6.0_31
Using JRE version 1.6.0_31-b04-415-11M3635 Java HotSpot(TM) 64-Bit Server VM
User home directory = /Users/ana
----------------------------------------------------
c:   clear console window
f:   finalize objects on finalization queue
g:   garbage collect
h:   display this help message
m:   print memory usage
o:   trigger logging
p:   reload proxy configuration
q:   hide console
r:   reload policy configuration
s:   dump system and deployment properties
t:   dump thread list
v:   dump thread stack
0-5: set trace level to <n>
----------------------------------------------------
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: com/sun/javafx/runtime/eula/Eula
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
at java.lang.ClassLoader.defineClass(ClassLoader.java:615)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at com.sun.jnlp.JNLPClassLoader.findClass(JNLPClassLoader.java:345)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:295)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at com.sun.javafx.tk.swing.SwingToolkit$StartupRoutine.run(SwingToolkit.fx:855)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:682)
at java.awt.EventQueue.access$000(EventQueue.java:85)
at java.awt.EventQueue$1.run(EventQueue.java:643)
at java.awt.EventQueue$1.run(EventQueue.java:641)
at java.security.AccessController.doPrivileged(Native Method)
at        java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:652)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Caused by: java.lang.ClassNotFoundException: com.sun.javafx.runtime.eula.Eula
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at com.sun.jnlp.JNLPClassLoader.findClass(JNLPClassLoader.java:345)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 30 more

If I uncompress the jar file, I can see the class Eula.class in the path com/sun/javafx/runtime/eula so I don't know if I have to specify in some way that it should look on the jar file.
My jnlp file is:
<?xml version="1.0" encoding="UTF-8"?>
<jnlp spec="1.0+" codebase="file:/Users/ana/Projects/" href="MatchTestCaseGenerator.jnlp">
<information>
    <title>Match Test Case Generator</title>
    <vendor>Knowledge Values</vendor>
    <homepage href="null"/>
    <description>somc description</description>
    <offline-allowed/>
    <shortcut>
        <desktop/>
    </shortcut>
</information>
<security>
     <all-permissions/>
</security>
<update check="background" policy="always"/>
<resources>
    <j2se version="1.5+"/>
    <jar href="MatchTestCaseGenerator-2.0-jar-with-dependencies.jar" download="eager" main="true"/>
    <extension href="http://dl.javafx.com/1.3/javafx-rt.jnlp" name="JavaFX Runtime"/>
</resources>
<application-desc main-class="com.sun.javafx.runtime.main.Main" progress-class="com.javafx.progressbar.ProgressManager">
    <argument>MainJavaFXScript=com.knowledgevalues.mtcg.javafx.MainFx</argument>
</application-desc>
</jnlp>


text:
Q: No se define "edo" Buenas, les presento mi problema. Pasa que me aparece este error a la hora de iniciar:

Notice: Undefined index: edo in C:\xampp\htdocs\enviaMail.php on line 10.

Y no sé porque es, ni como solucionarlo agradecería toda posible solución.
Es muy urgente por favor.

<?php
if($_POST['edo']){
    $nombre = $_POST['nombre'];
    $apellido = $_POST['apellido'];
    $correo = $_POST['correo'];
    $comentario = $_POST['comentario'];
    if($nombre==""){
        print "El nombre es obligatorio
";
    } else if($apellido == ""){
        print "El apellido es obligatorio
";
    } else if($correo == ""){
        print "El correo es obligatorio
";
    }  else if($comentario == ""){
        print "El comentario es obligatorio
";
    } else {
        $mail = "fj_arce@yahoo.com.mx";
        $mensaje = "$nombre $apellido ha enviado un mail.
";
        $mensaje .= "Su mail es $correo y su mensaje es:
";
        $mensaje .= $comentario;

        $headers = "MIME-Version: 1.0\r\n";
        $headers .= "Content-type:text/html; charset=UTF-8\r\n";
        $headers .= "From: ".$_POST['correo']."\r\n";
        $headers .= "Repaly-to: $correo\r\n";

        $asunto = "$nombre $apellido ha enviado un mail";

        if(mail($mail, $asunto, $mensaje,$headers)){
            print "Su comentario ha sido enviado exitosamente
";
        } else {
            print "Error en el envío de su correo, intentarlo más tarde
";
        }

    }

} else {
?>
<form method="post" action="enviaMail.php">
Nombre: <input type="text" name="nombre"/>

Apellido:<input type="text" name="apellido"/>

Correo: <input type="text" name="correo"/>

Comentario:

<textarea name="comentario" cols="50" rows="6" wrap="off"></textarea>

<input type="submit" value="Enviar" />
<input type="hidden" value="1" name="edo" />
</form>
<?php } ?>

A: La variable edo no esta definida.
if(isset($_POST['edo'])){
    // tu codigo
}else{
    // tu codigo
}

Con eso tu problema debería de estar resuelto.


text:
Q: Is Moles Framework supported in visual studio 2019? If yes how to set it up? Recently I started writing Nunit code for unit testing my MVC c# code. So I am facing the difficulty to mock static classes and methods.
Is Moles Framework supported in visual studio 2019? If yes how to set it up?


text:
Q: DB2 external java jar file stored procedure error I have been trying to call a java jar file from DB2 stored procedure as external jar.
Below is my external jar file code.
package connection;
    public class Connect {

        static Connection con = null;
        static Statement stmt = null;

        public static void main(String[] args) throws SQLException {
                javastp("v1");
        }

        public static void javastp( String name) throws SQLException{
            try {
            con = DriverManager.getConnection( "jdbc:default:connection" );
            stmt = con.createStatement();
            stmt.executeUpdate("INSERT INTO SCHEMA_NAME.TEST(NAME, FLAG) VALUES ('"+name+"',true) ");
            }catch (Exception e) {
                // ...
              }finally {
            //Close open resources
            if (stmt != null) stmt.close();
            if (con != null) con.close();
            }
        }
    }

i install it using below command in db2 server
db2 call sqlj.install_jar('file:E:/jarpath../jarname.jar','jarname',0);

Below is the stored procedure for DB2 external jar.
CREATE OR REPLACE PROCEDURE SCHEMA_NAME.PROC6()
  LANGUAGE java
  PARAMETER STYLE java
  FENCED
  EXTERNAL NAME 'jarname:connection.Connect.main'

The stored procedure executes successfully without errors.
But when i try to call the stored procedure using below,
CALL SCHEMA_NAME.PROC6()

i get the below error
SQL Error [38503]: A stored procedure process has been terminated abnormally. Routine name: "SCHEMA_NAME.PROC6". Specific name: "SQL201016144125554".. SQLCODE=-1131, SQLSTATE=38503, DRIVER=4.8.86

The java jar works fine when executed directly in the command prompt and the records are being inserted into the table, but i cant seem to figure out why the external stored procedure gives me error when i try to call it that way.
Can somebody here please help me out as am stuck on this since a very long time and i have no background of DB2.
the db2level command gives the below output:
DB21085I  This instance or install (instance name, where applicable: "DB2")
uses "64" bits and DB2 code release "SQL10058" with level identifier
"0609010E".
Informational tokens are "DB2 v10.5.800.381", "s160901", "IP24000", and Fix
Pack "8".
Product is installed at "C:\PROGRA~1\IBM\SQLLIB" with DB2 Copy Name "DB2COPY1".

Linux Suse db2 version 11.1.2
Database server = DB2/LINUXX8664 11.1.2
The log is as below:
2020-10-20-09.24.56.746633+330 I4952989679E1230      LEVEL: Error
PID     : 31693                TID : 140179352315648 PROC : db2sysc 0
INSTANCE:              NODE : 000            DB   :
APPHDL  :               APPID:
AUTHID  :               HOSTNAME:
EDUID   : 2768                 EDUNAME: db2agent () 0
FUNCTION: DB2 UDB, routine_infrastructure, sqlerWaitForFencedInvocation, probe:12115
MESSAGE : ZRC=0xFFFFFB38=-1224
          SQL1224N  The database manager is not able to accept new requests,
          has terminated all requests in progress, or has terminated the
          specified request because of an error or a forced interrupt.

A: Error SQL1131N has the following description

The DB2 architecture is designed so that applications run in a different address space than the database server. Running applications in a different address space prevents application programming errors from overwriting database manager internal buffers or files, and prevents application errors from crashing the database manager. The fenced mode process (db2fmp) is responsible for executing fenced stored procedures and user-defined functions in a different address space than the database server.

This message is returned when the db2fmp process terminates abnormally while running the named routine. The db2fmp process could have terminated abnormally for many reasons, including the following reasons:

*

*There was a coding error, such as division by zero or an out-of-bounds pointer reference, in the implementation of the stored procedure or user-defined function that the db2fmp process was executing.

*

*Another process terminated the db2fmp process using a signal, such as the termination signal SIGTERM.

*

*SQLJ.INSTALL_JAR failed while installing a Java routine because the fenced user does not have permission to create or write to the necessary directories on the server.

A: Db2 is unforgiving when you make mistakes with external non-SQL code, in this case, it just throws an exception and expects you to sort it out.
Only use java for Db2 stored procedures when there is a compelling reason to NOT use SQL PL procedures.
You have these mistakes

*

*You cannot use a main() for a Db2 java stored procedure entry point

*The stored procedure entry point should be in your case the javastp() method

*The EXTERNAL NAME clause in the DDL must not reference main() but should use javastp instead

*The parameters in the create procedure line must match those of the method
in number and type and sequence. (In your case that is (IN name varchar(255) or similar).


text:
Q: Excel VBA that Creates a Pivot Table I have this macro that takes all of sheet1 and creates a pivot table of it. However, it is currently only looking at the amount of rows I had when I made it and not the entire sheet no matter how many rows it has that day. Is there any way to make it select all of sheet1 as the pivot table data every time?
If possible I would also like to alter the fix duplicates to be the entire column based on the column name (IDNUMBER) if able.
Range("$A$1:$AM$2428")
Range("$A$1:$AM$4000")
"PIVOT_STATE_REPORT!R1C1:R1048576C39"
Sub PIVOT_STATE()
'
' PIVOT_STATE Macro
'

'
    'ActiveSheet.Range("$A$1:$AM$2428").RemoveDuplicates Columns:=36, Header:= _
        'xlYes
    Columns("AJ:AJ").Select
    ActiveSheet.Range("$A$1:$AM$4000").RemoveDuplicates Columns:=36, Header:= _
        xlYes
    Range("A2").Select
    Sheets.Add
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
        "PIVOT_STATE_REPORT!R1C1:R1048576C39", Version:=xlPivotTableVersion15). _
        CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="PivotTable1" _
        , DefaultVersion:=xlPivotTableVersion15
    Sheets("Sheet1").Select
    Cells(3, 1).Select
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("State (Corrected)")
        .Orientation = xlRowField
        .Position = 1
    End With
    ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
        "PivotTable1").PivotFields("Count"), "Sum of Count", xlSum
    ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
        "PivotTable1").PivotFields("Claim Age in CS"), _
        "Sum of Claim Age in CS", xlSum
    ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
        "PivotTable1").PivotFields("Days Since LHN"), _
        "Sum of Days Since LHN", xlSum
    Range("B3").Select
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Sum of Count")
        .Caption = "Count of Count"
        .Function = xlCount
    End With
    Range("C3").Select
    With ActiveSheet.PivotTables("PivotTable1").PivotFields( _
        "Sum of Claim Age in CS")
        .Caption = "Average of Claim Age in CS"
        .Function = xlAverage
        .NumberFormat = "0"
    End With
    Range("D3").Select
    With ActiveSheet.PivotTables("PivotTable1").PivotFields( _
        "Sum of Days Since LHN")
        .Caption = "Average of Days Since LHN"
        .Function = xlAverage
        .NumberFormat = "0"
    End With
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("State (Corrected)")

    End With
End Sub

Thanks in advance!

A: I would use the last row and column formulas provided in this function.
Then make the source a combo of these variables.
Function LastRowColumn(sht As Worksheet, RowColumn As String) As Long
'PURPOSE: Function To Return the Last Row Or Column Number In the Active
Spreadsheet
'INPUT: "R" or "C" to determine which direction to search

Dim rc As Long

Select Case LCase(Left(RowColumn, 1)) 'If they put in 'row' or column instead of 'r' or 'c'.
  Case "c"
LastRowColumn = sht.Cells.Find("*", LookIn:=xlFormulas, SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
 Case "r"
   LastRowColumn = sht.Cells.Find("*", LookIn:=xlFormulas, SearchOrder:=xlByRows, _
    SearchDirection:=xlPrevious).Row
 Case Else
  LastRowColumn = 1
End Select

 End Function

Then inside of your macro call out:
 x = LastRowColumn(ActiveSheet, "column")
 y = LastRowColumn(ActiveSheet, "Row")
 plast = cells(x,y)

Then make a range based off that for the source of the pivot table
    ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
"PIVOT_STATE_REPORT!A1:" & plast, Version:=xlPivotTableVersion15). _
    CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="PivotTable1" _
    , DefaultVersion:=xlPivotTableVersion15

A: I think the easiest way of doing this will be to replace these lines of your code
Columns("AJ:AJ").Select
ActiveSheet.Range("$A$1:$AM$4000").RemoveDuplicates Columns:=36, Header:=xlYes
Range("A2").Select

With
Dim rData As Range: Set rData = ActiveSheet.Range("A1", ActiveSheet.Range("A1").End(xlDown))
Set rData = Range(rData, rData.End(xlToRight))
rData.RemoveDuplicates Columns:=36, Header:=xlYes
ActiveWorkbook.PivotCaches.Create SourceType:=xlDatabase, SourceData:=rData

The update this be where you make your PivotCache
`
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
            "PIVOT_STATE_REPORT!R1C1:R1048576C39", Version:=xlPivotTableVersion15). _
            CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="PivotTable1" _
            , DefaultVersion:=xlPivotTableVersion15c
`

With the following code using the rData range as the Source Data
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:= _
    rData, Version:=xlPivotTableVersion15). _
    CreatePivotTable TableDestination:="Sheet1!R3C1", TableName:="PivotTable1" _
    , DefaultVersion:=xlPivotTableVersion15

Note this assumes that there are no gaps in the columns or rows of your Data. The End(xlDown) is the equivalent of holding the Ctrl and Down key


text:
Q: How do I AJAX in an XML file and parse the values? I have the following AJAX and XML code. You can see the values that I am trying to set. I'm just not sure how to go about parsing the XML file to set these variables.
AJAX code:
$.ajax({
          url: 'PATH TO XML',
          dataType: ($.browser.msie) ? "text" : "xml",
          success: function(data) {
                        var context = default;
                        if ( ... ) {
                           context = not-default;
                        }
                    }

XML code:
<messages>
 <message id="id1" context="default">
      <content>

Default HTML

      </content>
 </message>
 <message id="id2" context="not-default">
      <content>

Not Default HTML

      </content>
</message>
</messages>

A: It's pretty simple:
$(yourXmlFileContents);

From here, just use the .find() method to select elements:
$(yourXmlFileContents).find('foo[context=bar]');

NOTE: If you supply the document's contents as a string jQuery won't interpret it as XML, but as HTML instead.

A: See this example:
$(document).ready(function () {
    $.ajax({
        type: "GET",
        dataType: "xml",
        url: "XMLFile.xml",
        success: function (xml) {
            $(xml).find('type').each(function () { // find all "type" tag in XML
                if ($(this).text() == 'administrative_area_level_3') { // in here $(this) is our "type" tag
                    var result = $(this).parent().find('long_name').text(); // get result
                    $('#result').html('The Result is: ' + result) // write result
                }
            })
        }
    })
})

A: If you set the dataType as "xml", the value supplied to your success function will be an XML document object and passing it to the main jQuery function will do what you want. If you have XML as a string instead, you need to pass it jQuery's parseXML() method (new in version 1.5):
var xmlStr = "<foo>bar</foo>";
var xmlDoc = $.parseXML(xmlStr);
$xml = $(xmlDoc);
alert($xml.find("foo").text()); // Alerts "bar"


text:
Q: Additional Line in my Chapter I did not notice when the additional unwanted LINE at the upper part appeared.
I have changed from Article, Report and Book but in vain.
These are my code of chapter I used for the style ( I forgot from where I copied from). FYI, the language is Khmer ( Cambodian)
      \makeatletter
      \let\stdchapter\chapter

  \renewcommand*\chapter{%
\@ifstar{\starchapter}{\@dblarg\nostarchapter}}
  \newcommand*\starchapter[1]{%
\stdchapter*{#1}
\thispagestyle{fancy}
\markboth{\MakeUppercase{#1}}{}
   }
 \def\nostarchapter[#1]#2{%
\stdchapter[{#1}]{#2}
\thispagestyle{fancy}
 }
 \makeatother

Thanks in advance.

A: The problem is due to \thispagestyle{fancy} in
\newcommand*\starchapter[1]{%
\stdchapter*{#1}
\thispagestyle{fancy}
\markboth{\MakeUppercase{#1}}{}
 }

or
\def\nostarchapter[#1]#2{%
\stdchapter[{#1}]{#2}
\thispagestyle{fancy}
 }

I think one can remove it and use \pagestyle{plain} for the whole document


text:
Q: "heroku db:push" gives me: "Taps Load Error: no such file to load -- sqlite3..." By doing this:
bundle exec heroku db:push

I got this:
 !    Taps Load Error: no such file to load -- sqlite3
 !    You may need to install or update the taps gem to use db commands.
 !    On most systems this will be:
 !
 !    sudo gem install taps

This is my database.yml file:
development:
  adapter: mysql2
  encoding: utf8
  database: g_dev
  pool: 5
  username: root
  password:

A: I debuged it.
I need to put gem 'sqlite3' in the gemfile.
Because of this line 10 in cli.rb (taps-0.3.24):
require 'optparse'
require 'tempfile'
require 'taps/monkey'
require 'taps/config'
require 'taps/log'
require 'vendor/okjson'

Taps::Config.taps_database_url = ENV['TAPS_DATABASE_URL'] || begin
  # this is dirty but it solves a weird problem where the tempfile disappears mid-process
  require 'sqlite3'

It's in taps source code... :( I have no choice

A: I had this problem, but it suffices to just do:
gem install sqlite3

to make it available locally. That is, you do not need to pollute your gemfile with sqlite.
(Use sudo according to your environment.)