text:
Q: calculate the median by excluding outliers (+-25% of median of four columns) for values of four columns values I have four columns containing the amount of unit sold in last 4 years. I want to calculate the median and then calculate the mean by excluding the column values based on condition (+-25% of median).
df = df[['Date','ID','amount']] # df has daily data

df['dayofYear'] = df['Date'].dt.dayofyear

df['Year_Lag1']= df.groupby(['ID','dayofYear'])['amount'].transform(lambda x: x.shift(1))

df['Year_Lag2']= df.groupby(['ID','dayofYear'])['amount'].transform(lambda x: x.shift(2))

df['Year_Lag3']= df.groupby(['ID','dayofYear'])['amount'].transform(lambda x: x.shift(3))

df['Year_Lag4']= df.groupby(['ID','dayofYear'])['amount'].transform(lambda x: x.shift(4))

df['YearLag_median']= df[['Year_Lag1','Year_Lag2','Year_Lag3','Year_Lag4']].median(axis=1) #median amount on same date (is there a better way to calculate median by avoiding outliers)

how to calculate the average by avoiding values in four columns that lies in +- 25% of median.
suppose Year_Lag1 = 5000, Year_Lag2= 230, Year_Lag3=4500, Year_Lag4= 4300.
how to calculate average by avoiding Year_Lag2 value.
I want this to be done for all rows in a dataframe.
(also if someone can help with a better way to calculate median by avoiding outliers)
Data set[data has values for 2nd and 3rd january (2014,15,16,17,18). Year_Lag1(shift(1)) has values from previous year for 2nd and 3rd jan. Year_Lag2(shift(2) has values from last to last year)  so on..]
last row is the example where I want to ignore 589.0 to calculate the mean.
  [1]: https://i.stack.imgur.com/26Dvp.pngenter code here

A: Would be great if you could add a dataframe for reference. Tried generating a df as you've specified below by generating random dates in this year, random float amounts and random IDs. A 5-row head of my df looks like this:
df.head(5)
   amount                          Date   ID
0      93 2019-01-01 00:00:00.000000000  AAA
1      40 2019-01-03 08:43:38.181818181  AAA
2      47 2019-01-05 17:27:16.363636363  BBB
3      37 2019-01-08 02:10:54.545454545  CCC
4      13 2019-01-10 10:54:32.727272727  CCC

Is this what your dataset looks like?
If so then running the commands you've mentioned to get lags don't seem to work as expected. When i run it I get this as mentioned below:
df['dayofYear'] = df['Date'].dt.dayofyear
df.head(5)
                           Date   ID  amount  dayofYear
0 2019-01-01 00:00:00.000000000  AAA      93          1
1 2019-01-03 08:43:38.181818181  AAA      40          3
2 2019-01-05 17:27:16.363636363  BBB      47          5
3 2019-01-08 02:10:54.545454545  CCC      37          8
4 2019-01-10 10:54:32.727272727  CCC      13         10

df['Year_Lag1']= df.groupby(['ID','dayofYear'])['amount'].transform(lambda x: x.shift(1))
df.head(5)
                           Date   ID  amount  dayofYear  Year_Lag1
0 2019-01-01 00:00:00.000000000  AAA      93          1        NaN
1 2019-01-03 08:43:38.181818181  AAA      40          3        NaN
2 2019-01-05 17:27:16.363636363  BBB      47          5        NaN
3 2019-01-08 02:10:54.545454545  CCC      37          8        NaN
4 2019-01-10 10:54:32.727272727  CCC      13         10        NaN

Have made sure that the head is not the only one with nans. The whole column gets nans. If you could modify your original post to include a df it would make it a lot easier to answer your question.

A: Here is a solution, I think there should be something better to do it, but still it works:

*

*Define a function to calculate the mean according to your specifications

def calculateMean(row):
    s = 0
    n = 0
    for i in range(4):
        if ~np.isnan(row[i]) and abs(row[i] - row[-1]) < 0.25 * row[-1]:
            s += row[i]
            n += 1
    return (s/n if n else np.nan)

*Apply this function on every rows

df["YearLag_mean"] = df.loc[:, ['Year_Lag1','Year_Lag2','Year_Lag3','Year_Lag4', 'YearLag_median']]\
                       .apply(lambda row: calculateMean(row), axis=1)

Output:
            Date   ID  amount  dayofYear  Year_Lag1  Year_Lag2  Year_Lag3  Year_Lag4  YearLag_median  YearLag_mean
2258  2014-01-02  200  1778.0          2        NaN        NaN        NaN        NaN             NaN           NaN
2259  2014-01-03  200  2149.0          3        NaN        NaN        NaN        NaN             NaN           NaN
2623  2015-01-02  200  2057.0          2     1778.0        NaN        NaN        NaN          1778.0       1778.00
2624  2015-01-03  200  2401.0          3     2149.0        NaN        NaN        NaN          2149.0       2149.00
2988  2016-01-02  200  2315.0          2     2057.0     1778.0        NaN        NaN          1917.5       1917.50
2989  2016-01-03  200   589.0          3     2401.0     2149.0        NaN        NaN          2275.0       2275.00
3354  2017-01-02  200  1709.0          2     2315.0     2057.0     1778.0        NaN          2057.0       2050.00
3355  2017-01-03  200  1659.0          3      589.0     2401.0     2149.0        NaN          2149.0       2275.00
3719  2018-01-02  200  1991.0          2     1709.0     2315.0     2057.0     1778.0          1917.5       1964.75
3720  2018-01-03  200  1570.0          3     1659.0      589.0     2401.0     2149.0          1904.0       1904.00

As you can see, the last row didn't use 589 but also 2401 because of your threshold.
To remove outliers instead of using the median, you can look at IQR or Z-score, but I'm not sure it works well on small data, you can give it try and just adapt or create new functions.


text:
Q: PHP Delete File if other file exists Note: The file number is just so I can refer to each file easier
I am testing some code in which I have a file called first.txt (file 1) and and file called tom-first.php (file 2), file 2 file checks for the file 1's existence and sets a variable, then in my index.php(file 3), I require file 2 and if the variable is 1, I redirect to startup.php(file 4). File 4 deletes a text file called text.txt
My error is when I run the code, no matter what happens, test.txt is always deleted
tom-first.php
<?php

if (file_exists('first.txt')) {
    $first = '1';
} else {
    $first = '0';
}

echo $first;
?>

index.php
<?php
require 'tom-first.php';
if($first = '1')
{
    header("Location: startup.php");
}
else
{
    echo 'HI';
}

?>

Startup.php
<?php
unlink('text.txt')
?>

First.txt is Empty
I feel like the error is to do with setting variables on file 2 although echoing out $first shows the right number.
Any help is appreciated, even a completely different method of this would be useful, I am basically trying to make a system where it has a setup that runs on first time use.

A: You have a typo in index.php file.
Equality comparison operator in PHP is '==', not '='.
Your if statement below assigns value '1' to $first variable and always evaluates to '1'.
index.php
<?php
require 'tom-first.php';
if($first = '1') // this should be $first == '1'
{
    header("Location: startup.php");
}
else
{
    echo 'HI';
}

?>

A: With = you make an assignment (you assign a value to a variable). But == is a comparison operator. In your case you're evaluating 1 which is always TRUE. Another thing is, why so verbose and so many files if you can just write:
$first = file_exists('first.txt') ? 1 : 0;

and then the rest. Or even better...
if (file_exists('first.txt') {
    unlink('first.txt');
    // and do some other stuff
}
echo 'whatever';

But... :)
If you have to do something like this, it very much smells.
Why would you check for the presence of a file only to delete it right away?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Getting the first 10-digit prime number using lazy lists in Raku I'm trying to get the first 10-digit prime number using the lazy lists. Here is my take based on the (already given) code for computing the prime numbers:
my @primes = 2,3,5, {first * %% none(@_), (@_[*-1] ... Inf)} ...  -> $s {$s.chars == 10};

say @primes[@primes.elems-1];

The problem with that code is that it takes too long to finish.
Is there any quick method to get that first 10-digit prime number?

A: You can make it faster by:

*

*Starting from the smallest 10 digit number (no point going through a bunch of candidates that would never match even if they are prime)

*Using the fast built-in is-prime method rather than a hand-rolled algorithm

Thus getting:
say (1_000_000_000..*).first(*.is-prime)

Which produces:
1000000007

You could filter out evens too, but I suspect is-prime rejects those as fast as you'd separately test them anyway. (Also, it turns out the number is so close to the first 10-digit number that nothing aside from stating at 1_000_000_000 matters in practice.)


text:
Q: WebAPI2, OWIN and AutoFac: Cannot Inject anything into any controller I've scoured the internet and stack overflow but simply cannot work out why my AutoFac flatly refuses to inject anything into any controller. My code is below - everything SEEMS to be in order but I receive the following message:

An error occurred when trying to create a controller of type
  'SimpleController'. Make sure that the controller has a parameterless
  public constructor.

Startup.cs
using System.Reflection;
using System.Web.Http;
using Autofac;
using Autofac.Integration.WebApi;
using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;
using Microsoft.Owin.Security.DataHandler;
using Microsoft.Owin.Security.DataHandler.Serializer;
using Microsoft.Owin.Security.DataProtection;
using Owin;
using WebApiDependancyViaOwinTest.Models;

[assembly: OwinStartup(typeof(WebApiDependancyViaOwinTest.Startup))]

namespace WebApiDependancyViaOwinTest
{
    public partial class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();
            var config = new HttpConfiguration();
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            builder.RegisterType<TestObject>().As<ITestObject>().InstancePerRequest();
            //ASP.NET Identity Related
            builder.RegisterType<ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType<TicketDataFormat>().As<ISecureDataFormat<AuthenticationTicket>>();
            builder.RegisterType<TicketSerializer>().As<IDataSerializer<AuthenticationTicket>>();
            builder.Register(c => new DpapiDataProtectionProvider().Create("Test")).As<IDataProtector>();
            var x = ApplicationDbContext.Create();
            builder.Register(c => x);
            builder.Register(c => new UserStore<ApplicationUser>(x)).AsImplementedInterfaces();
            builder.Register(c => new IdentityFactoryOptions<ApplicationUserManager>
            {
                DataProtectionProvider = new DpapiDataProtectionProvider("Test")
            });

            var container = builder.Build();
            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);
            app.UseAutofacMiddleware(container);
            app.UseAutofacWebApi(config);
            app.UseWebApi(config);

            ConfigureAuth(app);
        }
    }

    public interface ITestObject
    {
        string Name { get; set; }
    }
    public class TestObject : ITestObject
    {
        public string Name { get; set; }
    }
}

StartUp.Auth.cs
using System;
using Microsoft.AspNet.Identity;
using Microsoft.Owin;
using Microsoft.Owin.Security.Cookies;
using Microsoft.Owin.Security.OAuth;
using Owin;
using WebApiDependancyViaOwinTest.Providers;

namespace WebApiDependancyViaOwinTest
{
    public partial class Startup
    {
        public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

        public static string PublicClientId { get; private set; }

        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);
        }
    }
}

Global.asax.cs
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace WebApiDependancyViaOwinTest
{
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

SimpleController.cs
using System.Web.Http;

namespace WebApiDependancyViaOwinTest.Controllers
{
    public class SimpleController : ApiController
    {
        private readonly ITestObject _testObject;
        public SimpleController(ITestObject testObject)
        {
            _testObject = testObject;
        }

        [AllowAnonymous]
        [HttpGet]
        public string TestInjection()
        {
            return (_testObject == null).ToString();
        }
    }
}

AccountController.cs (Snippet)
[Authorize]
[RoutePrefix("api/Account")]
public class AccountController : ApiController
{
    private const string LocalLoginProvider = "Local";
    private ApplicationUserManager _userManager;
    private readonly ITestObject _testObject;

    public AccountController(ApplicationUserManager userManager,
        ISecureDataFormat<AuthenticationTicket> accessTokenFormat,
        ITestObject testObject)
    {
        UserManager = userManager;
        AccessTokenFormat = accessTokenFormat;
        _testObject = testObject;
    }

    [AllowAnonymous]
    [HttpGet]
    public string TestInjection()
    {
        return (_testObject == null).ToString();
    }


text:
Q: Infrastructure for a "news-feed" I'd like to offer a news-feed like feature for users of our website.  When the user logs in, he is shown a list of the latest updates across various areas of the site.
I'm afraid that this is going to be difficult to scale.
What are some networking / database topologies that can support a scalable infrastructure without having lots of copies of the same data?  (I'd like to make it so if a piece of data is updated, each user's feed is also updated live).
Thanks for the assistance and advice.

A: *

*Don't prematurely optimize.

*This might be more of a question for the Server Fault crowd.

*Performance at scale often requires having lots of copies of the same data - you tagged the question "facebook," and that's part of how Facebook does it.  Twitter, too.  You are asking for a system that's fast ("updated live"), cheap ("without having lots of copies of the same data") and good (does the previous two correctly).  Pick two.


text:
Q: How to stop VSCode from autosuggesting after period (comma) in jupyter notebooks? Is there a way to prevent VSCode from suggesting "%%!" or anything really after periods (comma) inside jupyter notebooks?
This behavior (like in the screenshot below) is really annoying and it doesn't happen in .py files.


text:
Q: Normalizing Sales Database for sales amounts Right now, there is a Sales database which contains sales product detail columns as well as the sales amounts together in one table.
For example:
ProductID, ProductName, Jan14...Dec14, Jan15...Dec15
The issue right now is that there are too many columns right now since we keep on adding 12 columns every year to accommodate the sales amount data. We are trying to separate this table into 2 tables, one for the product information, and one for the sales amount data based on period. Any ideas on how the sales amounts table should be structured?
We are collection amounts on a monthly basis,so what should be the period identifier for the sales amounts table?
Should it be '201501' for jan 2015 or should we have 2 separate columns for month and year for every sales.

A: First of all, congratulations on deciding to normalize your data.
This is a very simple question with a very simple answer.   You just need two tables:

Product Table (ProductID, ProductName)
ProductSales Table (ProductID, SalesPeriod, SalesAmount)

ProductID and ProductName are nothing new.  In the SalesPeriod column you would store the periods you are summarizing Sales Totals for (2014, 2015 etc, or maybe 2014Q1, 2014Q2 etc, whatever you want to summarize by); and the SalesAmount column is the Total Sales for that period.
You'll populate ProductSales with one row for every Product/SalesPeriod combination.
Finally you add a Foreign Key to ProductSales that says that ProductID references the ProductID column in the Product Table.

A: I think sales amount is calculating data which can be calculated when you need it.
But if calculating takes long time and you using this data often
Separated table for sales amounts can be created
ProductID (INT PRIMARY KEY), FOREIGN KEY from Product information table
MonthNumber (INT PRIMARY KEY),
YearNumber (INT PRIMARY KEY)
Amount (DECIMAL)
Product information table remain same, except columns for sales periods
ProductID (INT PRIMARY KEY),
ProductInfo (NVARCHAR),
OtherInfo (NVARCHAR)
Then every month you just adding new row with amount for every products  '
Period of the amounts can be represents in different ways
Based on your needs: Month and Year are only values you need to represent a period of sales.
It can be little bid faster querying data without manipulating and take advantage of the indexes
For example if Period will be represented as DateTime
then query with WHERE MONTH(PeriodDate) = 4  will be executing without using of indexes


text:
Q: Как перенаправить на другую страницу в Bottle? Логика такая, есть страница авторизации с  формой, получаем через метод get логин и пароль.
@route('/auth', method='GET')
def home():
    login = request.forms.get('login')
    paswd = request.forms.get('pass')
    check_credentials(login, paswd)

обработка логина и пароля.
def check_credentials(user, pw):
    username = "dark"
    password = "dark"
    if pw == password and user == username:
        return template('index.html')
    return template('static/templete/auth.html')

Не получается вернуть страницу при успешной авторизации (т.е index.html, открывается снова страница авторизации). Что я делаю не так? Нужна просто небольшая проверка, без подключения дополнительных библиотек.


text:
Q: WordPress tinymce default link's target I'm trying to edit the WordPress TinyMCE editor so all the links has the target = "_blank". I've tried with jquery to set the 'Open link in new tab' checkbox to be always checked but, no results.
Thank you

A: You can accomplish this with the default_link_target setting in your TinyMCE configuration:  https://www.tinymce.com/docs/plugins/link/#default_link_target
Here is a TinyMCE Fiddle of this in action:  http://fiddle.tinymce.com/31faab
To do this in Wordpress you will need to create a simple plugin that modifies this setting as TinyMCE is loaded.  It would look something like this:
<?php
add_filter('tiny_mce_before_init', 'add_my_options', 1000);

function add_my_options($opt) {
    $opt['default_link_target'] = "_blank";

    return $opt;  //you must return $opt to not break things
}
?>

If you have never created a WP plugin they are not hard to build and there are plenty of examples on the web.


text:
Q: Median of three values I am trying to write a C program that takes 3 values as function arguments and returns the median. The program was running quite well - until I realized it did not work with same values twice or more.
For examples if the input is 1,2,3 - I get 2 ,correct median but if the input is 1,2,1 or 1,1,1 ..The loop keeps repeating from beginning .I think I have the logic right but there must be some tiny error which I am making .
My attempt :
int median(int firstInt,int secondInt, int thirdInt) {

   if (secondInt>firstInt && secondInt>thirdInt ||
      thirdInt>firstInt && firstInt>secondInt) {
      printf("The median value is %d\n", firstInt);
   }
   if (firstInt>secondInt && secondInt>thirdInt ||
      thirdInt>secondInt && secondInt>firstInt) {
      printf("The median value is %d\n", secondInt);
   }
   if (firstInt>thirdInt && thirdInt>secondInt ||
      secondInt>thirdInt && thirdInt>firstInt) {
      printf("The median value is %d\n", thirdInt);
   }
}

void main() {

   int count = 100;
   int firstInt,secondInt,thirdInt;

   while(count--)
   {

      printf("Enter first Integer : ");
      scanf("%d", &firstInt);
      printf("Enter second Integer : ");
      scanf("%d", &secondInt);
      printf("Enter third Integer : ");
      scanf("%d", &thirdInt);
      median(firstInt, secondInt, thirdInt); //calling

   }
}

Input : 1,2,1
Output :Enter first integer : // WHY is this happening?

A: The first thing you should do is decide what your function is meant to do. Its signature and name suggest it's supposed to return the median but the code actually prints it (and, if it just prints it, it should probably have a void return type).
The printing is probably best left to the caller, leaving the function to just calculate and return the median. This makes it a much more general-purpose function.
In any case, it's the use of > rather than >= which is causing your problem here since data sets where two or more numbers are identical will tend to result in none of the if statements being true.
A "cleaner" solution (in my opinion) would just be to cover all of the six possibilities in turn:
int median (int a, int b, int c) {
    if ((a <= b) && (b <= c)) return b;  // a b c
    if ((a <= c) && (c <= b)) return c;  // a c b
    if ((b <= a) && (a <= c)) return a;  // b a c
    if ((b <= c) && (c <= a)) return c;  // b c a
    if ((c <= a) && (a <= b)) return a;  // c a b
    return b;                            // c b a
}

Note that I've used <= here, simply because it more closely aligns the conditions with the sequences shown in the comment. The important thing is to use an inclusive comparison operator, whether >= or <=, rather than an exclusive one like >.
You could even refactor out the comparison so that the code is more readable, with something like:
static int is_ordered(int x, int y, int z) {
    return (x <= y) && (y <= z);
}
int median (int a, int b, int c) {
    if (is_ordered(a, b, c)) return b;
    if (is_ordered(a, c, b)) return c;
    if (is_ordered(b, a, c)) return a;
    if (is_ordered(b, c, a)) return c;
    if (is_ordered(c, a, b)) return a;
    return b;                          // Only one left is c, b, a.
}

I wouldn't initially worry about the extra function calls involved here unless you want to call it many, many times per second. Even then, you may find the compiler is smart enough to inline the function anyway. My general advice is to optimise for readability first, then worry about performance only if it becomes an issue.

There is, of course, another option (there almost always is).
Since there are only three values, it's a simple matter to sort them and just return the middle one. It doesn't have to be a complicated sort since you can just use an unrolled bubble sort created from a few conditionals. The code for doing that is shown below:
int median (int a, int b, int c) {
    // Unrolled bubble sort, then return middle one.

    if (a > b) { int t = a; a = b; b = t; }
    if (b > c) { int t = b; b = c; c = t; }
    if (a > b) { int t = a; a = b; b = t; }

    return b;
}

Personally, I don't think that's as readable as the earlier code but, if you prefer it, it's certainly functional.

A: In generic C++ code, the use of the smaller-than operator is typically preferred.
This could result in something like:
template<typename T>
T median(T a, T b, T c)
{
   return (b<a)
              ?   (b<c)  ?  (c<a) ? c : a  :  b
              :   (a<c)  ?  (c<b) ? c : b  :  a;
}


text:
Q: Can you initiate a phone call by sending an SMS message using twilio? As the title states what I would like to do is be able to text a number and have that number initiate a phone call.
is this possible with Twilios API?

A: yes; Twilio will make a request to the SMS url that you specify when it receives a SMS.  You can initiate the phone call in the logic on the page that the SMS url points to.
check out http://www.twilio.com/docs/api/twiml/sms/twilio_request

A: Yes. You configure an SMS endpoint for your application / telephone number. When someone SMS's that number, Twilio will request the endpoint and the logic you have on that page can initiate a Telephone Call.


text:
Q: Angular2 + Webpack DefinePlugin not working? I tried to run the Angular2 app from the tutorial on the angular.io website
Angular2 with Webpack Tutorial on angular.io
Installation worked well (with a few hiccups, it's Ubuntu 14.04 LTS) but I got to the point where the npm start task works, the server works, and even the app works in the browser, so far so good. But
Everytime I run npm start, I get the following 2 errors in the terminal, AND in the browser console:
ERROR in ./src/polyfills.ts
(4,5): error TS2304: Cannot find name 'process'.

ERROR in ./src/main.ts
(7,5): error TS2304: Cannot find name 'process'.

If you look at the tutorial, it is explained how to create the webpack configs, there is a webpack.common.js, a webpack.prod.js and a webpack.dev.js. In the webpack.prod.js, a var is created with this code:
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
new webpack.DefinePlugin({
    'process.env': {
        'ENV': JSON.stringify(ENV)
    }
})

In main.ts and in polyfills.ts the var is referenced by this:
if (process.env.ENV === 'production') {
    enableProdMode();
}

but it seems, that Typings does not know how to inject these variables, created with webpack.DefinePlugin into the compiled Javascript (that's what I'm thinking, I maybe wrong)
If anyone ran into the same problem, or anyone can help me with this, I would be very thankful! (All the code is from the tutorial, so anyone who tried the tutorial may have run into the same problem, I guess?!)
Thank You!

A: I was having the same issue here (doing the same tutorial). To solve this I created a file named typings.d.ts on the same folder where typings.json is (this file will be included by default by the compiler) and added the following declaration to it:
declare var process: any;

Hope it helps! :)


text:
Q: Getting field names of a listItem - (Strongly typed?) in SharePoint 2010 Client API I'm very new to SharePoint, using 2010.  Trying to see what we can do with it, in particular with Lists.  And I have a feeling I'm missing something pretty obvious, but can't find it.....
In a Sharepoint site I created a list called Famous People:  Added a few people in, Frank Sinatra etc.

*

*Last Name: Sinatra

*First Name: Frank

*E-mail Address: frank.sinatra@ratpack.com

*Job Title: Singer

*etc

So then I've been trying to get that information into a simple C# console application, referring and trying many examples I have found.
But I get stuck around working out what the actual fieldNames(?) are that I need to refer to, as it doesn't appear to be strongly typed.  But also using the likes of "E-mail Address" doesn't seem to work either
Here's one example I've been trying.  (From: How to: Retrieve List Items)
            string siteUrl = "http://servername/site/";
        var clientCtx = new ClientContext(siteUrl);
        Microsoft.SharePoint.Client.List oList = clientCtx.Web.Lists.GetByTitle("Famous People");

        var camlQuery = new CamlQuery {ViewXml = "<View><RowLimit>100</RowLimit></View>"};

        ListItemCollection collListItem = oList.GetItems(camlQuery);

        clientCtx.Load(collListItem,
             items => items.Include(
                item => item.Id,
                item => item.DisplayName,
                item => item.HasUniqueRoleAssignments));

        clientCtx.ExecuteQuery();

        foreach (ListItem oListItem in collListItem)
        {
            Console.WriteLine("ID: {0} \nDisplay name: {1} \nUnique role assignments: {2}",
                oListItem.Id, oListItem.DisplayName, oListItem.HasUniqueRoleAssignments);
        }

        Console.ReadLine();
        clientCtx.Dispose();

Which brings back:
ID: 1
Display name: Clough
Unique role assignments: False
ID: 2
Display name: Sinatra
Unique role assignments: False
ID: 3
Display name: Simpson
Unique role assignments: False
ID: 4
Display name: Skywalker
Unique role assignments: False

I have tried each of the methods on the examples link I provided above.  But from there I have no idea how to get to the other properties such as "Job", or "E-mail address".
Or for example if I'm dealing with a List which I don't know, how do I find out the valid field names from my application via web service?
Thanks.

A: The thing to be aware of is that each SPListItem has a different set of field depending on the underlying content type.
This is also modified depending on which list the item is sitting in.
So this is why there is no strongly typed indexing into the fields...
However, adding the following code should help you get a feel for what is inside each listitem
 foreach(SPField field in oListItem.Fields)
 {
     Console.Write(field.Title + " (" + field.InternalName + "): ");
     Console.WriteLine(oListItem[field.Id].ToString());
 }

The property SPField.SchemaXml shows the full detail on the configuration of each field.
Having a copy of SharePointManager will give you a good idea of how any given site hangs together.
If you can only use the client object model to discover this
foreach(string fieldName in oListItem.FieldValues.Keys)
{
     Console.Write(fieldName);
     Console.WriteLine(oListItem.FieldValues[fieldName]);
}

A: If you go to your list settings you can find the column name by clicking on it. This will send you to a link like: http://servername/_layouts/FldEdit.aspx?List=%7BEACD90E2%2DED64%2D42EE%2DB1FB%2D2631687C545F%7D&Field=Title
The name of the field is the RHS of Field=Title.
Given that you know the column names you can use the following code:
cxt.Load(items,
   c => c.Include(
      item => item["ID"],
      item => item["Title"],
      item => item["AssignedTo"],
      item => item["Status"]));
   cxt.ExecuteQuery();

A: You can access the other properties via the indexed property on the ListItem.
You have to add the properties as ViewFields to the ViewXml:
var camlQuery = new CamlQuery
{
  ViewXml = "<View><ViewFields><FieldRef Name='Last_x0020_Name'/></ViewFields><RowLimit>100</RowLimit></View>"
};

Note the _x0020_ encoding for spaces.


text:
Q: For SEO purposes, what are the pros/cons of defining page titles client side vs server side? Programmatically, which is better for SEO purposes: defining web page titles client side (e.g., via Javascript that executes before the closing body tag) or server side (e.g., dynamically generating the title based on page content before sending the whole page to the client)?
Thanks!

A: As a simple rule - if it's done client-side then it simply doesn't exist as far as SEO is concerned.
That said, there's really no need to be setting such things client-side via JavaScript unless you're substantially changing the page content dynamically and even then the change in title isn't guaranteed to work on all browsers, may negatively affect the end user experience, etc.

A: It is entirely worthless to use JavaScript to define your page titles. Most web-crawlers do not download the javascript, and certainly don't run it. The source of the page is pretty much everything a web crawler sees.
Client Side -> Pros: You get to use JavaScript. Cons: Ruins your SEO
Server Side -> Pros: Actually read by search engines. Cons: You don't get to use JavaScript.


text:
Q: WPF - What is the proper binding method for multiple layers? I've been looking into this problem for a while now, and I would like to know the proper way to do this. I want to make re-usable controls that the properties can be bound to, Then update the controls themselves when the bound property is updated from another source.
So this is kind of the layout;
I have a page (we can call it Page X) that implemented a View Model (View Model X). There is a property in the View Model X (RealPropertyX of type Boolean).
I have a user control that is a sliding checkbox that has a View and View Model.
The View has a Dependency Property:
public bool ValueChecked
    {
        get { return (bool)GetValue(ValueCheckedProperty); }
        set { SetValue(ValueCheckedProperty, value); }
    }

    public static readonly DependencyProperty ValueCheckedProperty =
        DependencyProperty.Register("ValueChecked", typeof(bool), typeof(SliderCheckbox),
            new PropertyMetadata(false));

The View Model implements the bindable property to the view of my user control:
private bool _valueChecked;

    public bool ValueChecked
    {
        get { return _valueChecked; }
        set
        {
            _valueChecked = value;
            OnPropertyChanged(nameof(ValueChecked));
        }
    }

In my SliderUserControl
<CheckBox ... IsChecked="{Binding ValueChecked}"/>

In my Page X View
<controls:SliderCheckbox ValueChecked="{Binding RealPropertyX, Mode=TwoWay}"/>

If my thinking is correct, then from my App View I would be binding to the dependency property on my User Control View. The User Control itself is bound to the property in the View Model. But how do I link the two properly allowing them all to communicate the same value?

A: Generally speaking, a UserControl shouldn't be tied to a specific view model. It typically inherits its DataContext from a parent element which means that you can bind its dependency properties to several different view models depending on the context:
<local:UserControl1 SomeProperty="{Binding SomeSourceProperty}" />

To bind a control in the XAML markup of the UserControl to any of its own dependency properties that are defined in the code-behind, you could use a relative source:
<CheckBox ... IsChecked="{Binding ValueChecked,
    RelativeSource={RelativeSource AncestorType=UserControl}}" />


text:
Q: ObservableCollection exposed as IEnumerable still treated as former? I have a view model that exposes a ObservableCollection<TInheritor> collection as IEnumerable<TBaseInterface> (for the covariance). If I bind that property to the ItemsSource property on a ListBox, is that ListBox still smart enough to use my source as an ObservableCollection?

A: Yes it will do that, there shouldn't be any problems using an ObservableCollection like this. Here is an example: http://www.c-sharpcorner.com/UploadFile/e06010/observablecollection-in-wpf/


text:
Q: How to deploy a vuejs project to heroku I am working on this project locally https://github.com/misterGF/CoPilot but now that it is finished, I would like to push it to heroku. the problem is telling heroku to start the app.
In the heroku example, the demo server runs after picking up the info from Procfile with contains this data
web: node index.js

But in my vuejs project, there is no index.js that servers the content.
I only have the main entry point which is index.html and the procfile doesn't work with HTML.

A: You also need to define a small static server to serve your index.html file.
A simple example setup would be with http-server:
npm install -S http-server

And your Procfile becomes:
web: http-server ./ -p $PORT

A: You need to update your package.json file to let heroku know about the packages, for example if you are using express to serve your files:
"scripts": {
   "postinstall": "npm install express"
 }
 // "start": "node server.js" (executing server.js) during start

server.js
var express = require('express')
var path = require('path')
var serveStatic = require('serve-static')

var app = express()
app.use(serveStatic(path.join(__dirname, 'dist')))

var port = process.env.PORT || 8000
app.listen(port)
console.log('server started ' + port)

Don't forget to build.
Look here to read more about build conf: Customizing build process - Heroku

You can also install the http-server globally like this if that is a option:
npm install -g http-server

and update the Procfile to add the configuration as mentioned in above answers.

Just to know:

*

*npm install will install both "dependencies" and "devDependencies"

*npm install --production will only install "dependencies"

*npm install --dev will only install "devDependencies"

A: Using http-server. but the package is not installed globally, so you will have to use the full path to it like so:
web: ./node_modules/http-server/bin/http-server ./ -p $PORT


text:
Q: .NET open PDF in winform without external dependencies Is there a FREE library which will allow me to open a pdf and show it on a winform project. I know I could open it in adobe reader or something but it always seems so bloated to me and I would be relying on it being installed. Is there a nice lightweight alternative where I could just include a dll in my project or similar avoiding external dependencies.
I don't need much functionality just view, change page zoom..
I have seen a few libraries but they seem to be about creating PDF's not viewing.

A: I'm not sure what you call a 'dependency' since you'll always have to rely on some external code to render the PDF unless you bundle the whole PDF rendering source inside your project.
There are some commercial renderers and very few free ones.
If you want to avoid dependencies that you can't bundle then maybe you could have a look at the source code for SumatraPDF, an OpenSource PDF viewer for windows that uses MuPDF.
There is also Poppler, a rendering engine that uses Xpdf as a rendering engine.
All of these are great but they will require a fair amount of commitment to make make them work and interface with .Net.
Most other open source libraries are only used for creating and managing PDF pages and I don't know any that actually does rendering; it's such a hard problem to solve right.
You may still want to consider using GhostScript as an interpreter because rendering pages is a fairly simple process.
The drawback is that you will need to either re-package it to install it with your app, or make it a pre-requisite (or at least a part of your install process).
It's not a big challenge, and it's certainly easier than having to massage the other rendering engines into .Net.
Have a look at this SO question I answered today.
It contains some more information and a link to some working .Net code I posted on another forum a few months ago.

A: First you need to reference the Adobe Reader ActiveX Control
Adobe Acrobat Browser Control Type Library 1.0
%programfiles&\Common Files\Adobe\Acrobat\ActiveX\AcroPDF.dll
Then you just drag it into your Windows Form from the Toolbox.
And use some code like this to initialize the ActiveX Control.
private void InitializeAdobe(string filePath)
{
    try
    {
        this.axAcroPDF1.LoadFile(filePath);
        this.axAcroPDF1.src = filePath;
        this.axAcroPDF1.setShowToolbar(false);
        this.axAcroPDF1.setView("FitH");
        this.axAcroPDF1.setLayoutMode("SinglePage");
        this.axAcroPDF1.Show();
    }
    catch (Exception ex)
    {
        throw;
    }
}

Make sure when your Form closes that you dispose of the ActiveX Control
this.axAcroPDF1.Dispose();
this.axAcroPDF1 = null;

otherwise Acrobat might be left lying around.

A: I would look into Foxit Reader as a lightweight alternative to Adobe Reader.  It consists of a single .exe file that you can bundle with your application and thus shouldn't require any installation.  According to their EULA this is allowed, as long as your application is not installed on mobile devices.  All you would have to do is launch the reader as a new process, pointing to the appropriate pdf.  Obviously the downside to this approach is it won't be integrated into your application's interface.

A: The ActiveX control installed with acrobat reader should work, either drop it in via the designer or use something like this.
This will require the relevant version of the reader is installed on the client but since you indicate that you could just launch that anyway this should not be a problem. reader

A: Take a look at this.  It requires quite a few libraries (including GhostScript), so it's not terribly light weight.  But all dependencies included native reading of PDF.  It's in VB--but could be translated if you need C#:
http://www.codeproject.com/Articles/37458/PDF-Viewer-Control-Without-Acrobat-Reader-Installe

A: There is a free PDF library. It is mainly editing the contents but it might help.

A: This is a guess.
The way browser render PDF inside it with a plug-in. I am not sure whether it requires the application to be installed.
You can use Foxit reader OR Sumatra PDF.
And, you can host the browser control on your winform.

A: Put a webBrowser control on your form.
strPdfFile = "C:\SomeFile.pdf"
webBrowser.Url = new Uri(strPdfFile);
This is worked for us until tried on a Win7-64bit system. Need to do some debugging now.

A: You can use Spire.PDFViewer from Nuget. See here


text:
Q: How to use return in for loop in a function? I have a code below, but I am yielding an error that says

missing return in a function expected to return 'String'

func returnMultipleGreetings (name: String...) -> String {
    for names in name {
        return names
    }
}

How do I edit this code to remove the error?

A: Try source code:
func returnMultipleGreetings (name: String...) -> String {
    var result = ""
    for names in name {
        result = names
    }
    return result
}

Hope it's OK.

A: You must return within the scope of the function. NOT within the scope of the for-loop, which is where you currently have it. If you are not familiar with "scope" then do some reading as it is an important topic to understand. As of right now, returnMultipleGreetings cannot "see" return names. The following should fix your error...
func returnMultipleGreetings (name: String...) -> String {
     for names in name {
   //iterate thru array within loop
     }
  //return AFTER loop finishes
 return names
}


text: Q: Why are static content and scripts in separate folders By default in ASP.NET MVC 3, you get a separate folder for Content (including CSS and images mainly) and Scripts (javascript).  Is there an advantage to this?


text:
Q: Intellij not showing coverage I wrote one test case for the controller. Inside that controller, calling one service class method.
When I Selected RunAsCoverage in the IntelliJ test case got passed. But it shows test coverage only for the controller class. For the service class, it's showing 0 percent.
When I run test coverage with the Jacoco plugin it's showing for both controller and service class
Please help with this. Thankyou


text:
Q: Configuración de Node Modules para Firebase Realtime Database + Ionic + Angular Me gustaría que me brindaran asesoramiento con este problema.
El problema surgió cuando empecé a usar angularfire2, ya que al momento de querer instalarlo surgían varios problemas con node_modules, lo más probable es que lo haya instalado mal, así que me decanté por volver a instalar todas las dependencias pero el error seguía. Por lo tanto, como se trata de proyecto universitario, decidí hacer todo sin node_modules para evitar retrasos de actividades, ahora que ya dispongo de todo lo necesario me gustaría recibir ayuda con este problema, enseguida les adjuntaré el package.json y angular.json:
Cabe recalcar que ya tengo todo respaldado por si las dudas
Con esto planteado, espero que me asesoren sobre que comandos npm o ng debería usar, sería de gran ayuda.
package.json
  "name": "ionic-basic",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "https://ionicframework.com/",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "~13.0.0",
    "@angular/core": "~13.0.0",
    "@angular/forms": "~13.0.0",
    "@angular/platform-browser": "~13.0.0",
    "@angular/platform-browser-dynamic": "~13.0.0",
    "@angular/router": "~13.0.0",
    "@capacitor/app": "1.0.7",
    "@capacitor/core": "3.3.4",
    "@capacitor/haptics": "1.1.3",
    "@capacitor/keyboard": "1.2.0",
    "@capacitor/status-bar": "1.0.6",
    "@ionic/angular": "^6.0.0",
    "rxjs": "~6.6.0",
    "tslib": "^2.2.0",
    "zone.js": "~0.11.4",
    "angularfire2": "^5.4.2",
    "firebase": "^7.24.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~13.0.1",
    "@angular-eslint/builder": "~13.0.1",
    "@angular-eslint/eslint-plugin": "~13.0.1",
    "@angular-eslint/eslint-plugin-template": "~13.0.1",
    "@angular-eslint/template-parser": "~13.0.1",
    "@angular/cli": "~13.0.1",
    "@angular/compiler": "~13.0.0",
    "@angular/compiler-cli": "~13.0.0",
    "@angular/language-service": "~13.0.0",
    "@capacitor/cli": "3.3.4",
    "@ionic/angular-toolkit": "^5.0.0",
    "@types/jasmine": "~3.6.0",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "^12.11.1",
    "@typescript-eslint/eslint-plugin": "5.3.0",
    "@typescript-eslint/parser": "5.3.0",
    "eslint": "^7.6.0",
    "eslint-plugin-import": "2.22.1",
    "eslint-plugin-jsdoc": "30.7.6",
    "eslint-plugin-prefer-arrow": "1.2.2",
    "jasmine-core": "~3.8.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.3.2",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.0.3",
    "karma-coverage-istanbul-reporter": "~3.0.2",
    "karma-jasmine": "~4.0.0",
    "karma-jasmine-html-reporter": "^1.5.0",
    "protractor": "~7.0.0",
    "ts-node": "~8.3.0",
    "typescript": "~4.4.4"
  },
  "description": "An Ionic project"
}```

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "defaultProject": "app",
  "newProjectRoot": "projects",
  "projects": {
    "app": {
      "root": "",
      "sourceRoot": "src",
      "projectType": "application",
      "prefix": "app",
      "schematics": {},
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "www",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": [
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "assets"
              },
              {
                "glob": "**/*.svg",
                "input": "node_modules/ionicons/dist/ionicons/svg",
                "output": "./svg"
              }
            ],
            "styles": ["src/theme/variables.scss", "src/global.scss"],
            "scripts": [],
            "aot": false,
            "vendorChunk": true,
            "extractLicenses": false,
            "buildOptimizer": false,
            "sourceMap": true,
            "optimization": false,
            "namedChunks": true
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "namedChunks": false,
              "aot": true,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true,
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "2mb",
                  "maximumError": "5mb"
                }
              ]
            },
            "ci": {
              "progress": false
            }
          }
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            },
            "ci": {
              "progress": false
            }
          }
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "app:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "main": "src/test.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "styles": [],
            "scripts": [],
            "assets": [
              {
                "glob": "favicon.ico",
                "input": "src/",
                "output": "/"
              },
              {
                "glob": "**/*",
                "input": "src/assets",
                "output": "/assets"
              }
            ]
          },
          "configurations": {
            "ci": {
              "progress": false,
              "watch": false
            }
          }
        },
        "lint": {
          "builder": "@angular-eslint/builder:lint",
          "options": {
            "lintFilePatterns": [
              "src/**/*.ts",
              "src/**/*.html"
            ]
          }
        },
        "e2e": {
          "builder": "@angular-devkit/build-angular:protractor",
          "options": {
            "protractorConfig": "e2e/protractor.conf.js",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "devServerTarget": "app:serve:production"
            },
            "ci": {
              "devServerTarget": "app:serve:ci"
            }
          }
        },
        "ionic-cordova-build": {
          "builder": "@ionic/angular-toolkit:cordova-build",
          "options": {
            "browserTarget": "app:build"
          },
          "configurations": {
            "production": {
              "browserTarget": "app:build:production"
            }
          }
        },
        "ionic-cordova-serve": {
          "builder": "@ionic/angular-toolkit:cordova-serve",
          "options": {
            "cordovaBuildTarget": "app:ionic-cordova-build",
            "devServerTarget": "app:serve"
          },
          "configurations": {
            "production": {
              "cordovaBuildTarget": "app:ionic-cordova-build:production",
              "devServerTarget": "app:serve:production"
            }
          }
        }
      }
    }
  },
  "cli": {
    "analytics": false,
    "defaultCollection": "@ionic/angular-toolkit"
  },
  "schematics": {
    "@ionic/angular-toolkit:component": {
      "styleext": "scss"
    },
    "@ionic/angular-toolkit:page": {
      "styleext": "scss"
    }
  }
}


text:
Q: Seaborn: plot dictionary of lists with different colour I was wondering, is there a simple way, to plot a dictionary of keys:list of values, using seaborn, possibly each list of values belonging to a key, with different colour.
avx = {'A': [8.06390789458573,
      11.350427821200224,
      18.253071171324542],
      'B': [34.32754544872351,
      26.565496693414225,
      26.565496693414225]}

What I was trying to do, but fails:
sns.scatterplot(data=avx,
                x=avx.keys(),
                y=avx.values(),
                palette="deep")


text:
Q: Mapping multiple domains on localhost to single MVC app Is it possible to map multiple domains  to a single MVC app, deployed with IIS Express on Localhost?
Ideally I would like to use a wildcard or regex type mapping, something like: (http://my[a-zA-Z]website.com).  That would mean the app would run for all the examples below:

*

*mylovelywebsite.com

*mygreatwebsite.com

*myspiffingwebsite.com

I have been following these instructions for mapping domains to localhost, but I have no idea how to approach mapping multiple/wildcard domains.
Is it possible?
Update
20 hours later and I don't think it is possible. I tried using the * as a wildcard letter but I couldn't get it to work. Eventually I just manually typed in all 200 domains :(.
If I'm wrong, please leave an answer below, because it would be good to know for future reference.


text:
Q: wechat pay returnKey null value in iOS I m trying to implement WeChat pay, everythings done but when i PayReq send than WeChat app will open and than just this kind of image show with just only 'Ok' button and when i click on ok button than it returns back to my app and get '(null)' return key.
Return message is:
//Code:
PayReq* req             = [[[PayReq alloc] init]autorelease];
        req.partnerId           = [dicParams objectForKey:@"mch_id"];
        req.prepayId            = [dicParams objectForKey:@"prepay_id"];
        req.nonceStr            = [dicParams objectForKey:@"nonce_str"];
        req.timeStamp           = timeStamp;
        req.package             = @"Sign=WXPay";
        req.sign                = [dicParams objectForKey:@"sign"];
        [WXApi sendReq:req];

Return value :
://pay/?returnKey=(null)&ret=-2

Check Screen ::


text:
Q: How to return just the values from sqlplus using set variables? Can someone please help me here?
Looks like I setup the right values in the set variables, but it's returning lot of things. See below:
################################
# Main
################################

RETVAL=`sqlplus user/pass@DB <<EOF
SET PAGESIZE 0 FEEDBACK OFF VERIFY OFF HEADING OFF ECHO OFF
SELECT process_id, source, destination, type FROM table WHERE process_id IN ('12311','12322');
EXIT;
EOF`
if [ -z "$RETVAL" ]; then
  echo "No rows returned from database"
  exit 0
else
  echo $RETVAL
fi

The output is:
SQL*Plus: Release 9.2.0.8.0 - Production on Thu Jun 27 19:37:39 2013 Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved. Connected to: Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production With the Partitioning, OLAP, Data Mining and Real Application Testing options SQL> SQL> 12311 ,AAA BBB ,2 12322 ,AAA BBB ,5 SQL> Disconnected from Oracle Database 11g Enterprise Edition Release 11.2.0.2.0 - 64bit Production With the Partitioning, OLAP, Data Mining and Real Application Testing options
I just would like:
12311, AAA, BBB, 2,
12322, AAA, BBB, 5,
*the commas is also not right

A: Use -s option of sqlplus to supress:
sqlplus -s user/pass@DB


text:
Q: How to show dialog for alarms android I am making an app where it has this alarm features. What i want is that when the alarm fires, a dialog shows up (in or outside the application). I am new to android. I tried reading some sources about it and i am very much confused.
btw, im already done on how to set up the alarm.
I dont have a problem setting up the alarms and etc. my problem is making a dialog when the alarm fires.
Can you help me?

A: When your alarm fire than call activity you have to make transparent activity, and make dialog layout what you want.
You can use AlarmManager and Broadcast Receiver for create Alarm.

A: Replace the Toast in the following code with a Dialog (http://developer.android.com/guide/topics/ui/dialogs.html)
public void onReceive(Context context, Intent intent)
{
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
    wl.acquire();

    // Put here YOUR code.
    Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example

    wl.release();
}

A: Here is code for building a dialog:
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
        builder1.setMessage("Write your message here.");
        builder1.setCancelable(true);
        builder1.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });
        builder1.setNegativeButton("No",
                new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
            }
        });

        AlertDialog alert11 = builder1.create();
        alert11.show();

A: I'm not sure if this is possible. Where are you trying to make/show your Dialog? Are you doing this on the BroadcastReceiver?
If that's the case then it probably won't work and you might want to change from using Dialogs to Notifications. This happens because Dialogs need an Activity.
This is the error I get when I try to shoot/create a Dialog from the BroadcastReceiver in the onReceive() method:

java.lang.RuntimeException: Unable to start receiver
  com.voxnet.autohop.helpers.AlarmReceiver:
  android.view.WindowManager$BadTokenException: Unable to add window --
  token null is not valid; is your activity running?


text:
Q: Rxdart BehaviorSubject make its value null I have a wired problem with Rxdart BehaviorSubject! I created a screen in flutter that has two TextField and one DropdownButton and I receiving their data with bloc pattern.
But when I change TextFields values, The value of BehaviorSubject that connected to DropdownButton get null and when I change DropdownButton value, the value of two BehaviorSubjects that connected to TextFields gets null.
Also it does not affect widget rendering.
Can anyone help me understand what am I doing wrong here. here is my bloc code:
class Bloc {
  final _type = BehaviorSubject<String>();
  final _amount = BehaviorSubject<String>();
  final _title = BehaviorSubject<String>();

  Stream<String> get type => _type.stream;
  Stream<String> get amount => _amount.stream;
  Stream<String> get title => _title.stream;

  Function(String) get changeType => _type.sink.add;
  Function(String) get changeAmount => _amount.sink.add;
  Function(String) get changeTitle => _title.sink.add;

  createTransaction() {
    final validType = _type.value;
    final validAmount = _amount.value;
    final validTitle = _title.value;

    print(validType);
    print(validAmount);
    print(validTitle);
  }

  dispose() {
    _type.close();
    _amount.close();
    _title.close();
  }

}

A: So after rewriting code I finally found what was the problem. This was so annoying I hope this answer helps someone else.
The problem was I added provider inside routes so the code was like this:
Route routes(RouteSettings settings) {
  switch(settings.name) {
    case '/app':
      return MaterialPageRoute(
        builder: (context) {
          return MainProvider(child: MainScreen());
        }
      );
    ...
  }
}

And so I changed that to this code and bring all providers in main build function:
class App extends StatelessWidget {
  Widget build(context) {
    return UserProvider(
      child: ListsProvider(
        child: TransactionsFormProvider(
          child: MaterialApp(
            onGenerateRoute: routes,
            ...
          ),
        ),
      ),
    );
  }
}

But finally I didn't understand what the heck is the relation between BehaviorSubject and This solution :))


text:
Q: bash script to move files from deep directory structure I would like to be able to move files to a directory (eg Desktop/tbb) from a directory structure where each file is kept deep in the structure in different folders.
The directory structure  with the files I want is like this:
/Users/me/Desktop/SeqS/Plots/Results/FTF/freak/5M/5M_T1/SNAPSHOT/CN/Jimbob/LP7005321bam_ratio.txt

/Users/me/Desktop/SeqS/Plots/Results/FTF/freak/5M/5M_T2/SNAPSHOT/CN/Salad/LP9904920bam_ratio.txt

/Users/me/Desktop/SeqS/Plots/Results/FTF/freak/5M/5M_T3/SNAPSHOT/CN/Spags/LP6005334bam_ratio.txt

To move all of them to
    /Desktop/tbb
Is there a way of asking in bash to search for example for all files that end in ...bam_ratio.txt within a folder and it to search folders within that to retrieve the correct files?

A: You can use the find command to find the files you want, e.g.:
find . -type f -iname "*bam_ratio.txt"

Will find all files ending in 'bam_ratio.txt' in the current directory.
To move them to your desired directory you can use the -exec flag like:
find . -type f -iname "*bam_ratio.txt" -exec mv {} ~/Desktop/tbb/ \;

A: find command.  It's different in different versions of bash, but it looks something like this.
find /Users/me/Desktop/SeqS/Plots/Results/FTF/freak/ -type f -name "*bam_ratio.txt" -exec mv {} /Desktop/tbb/ \;


text:
Q: Report in .rdlc format exported to PDF as read only C# I'm working in an app in .NET where i'm using a report (.rdlc format) that i export to PDF. My client needs the PDF to be read only for security purposes. I already tried with FileAttributes and FileInfo libraries.
My biggest problem is that when i see my PDF properties, the checkbox for read-only is ticked but then i try to edit the fields with Adobe Acrobat and i am able to do it.
Any ideas?

A: I think you need create PDF/A files. It is separate archive standard of PDF (not "readonly" property). So when you open PDF/A files you get notification that it is archive file. End-user could edit any file, but in such case "archive" property will lost.
Unfortunately SSRS could not make PDF/A files.

A: May be, you should look for another report generator. Something like Crystal or FastReport. I checked FR and ensured that it can create PDF/A.

A: This can be done by importing iTextSharp library and using the following code:

I couldn't solve my problem without rendering and saving the PDF first in the file system as a dummy file, i.e., with all permissions. As you can see in the code, afterwards, i refer to the same dummy file and change it's permissions with static method Encrypt() from the iTextSharp library. Then, i save my finished and restricted PDF to the file system and delete the dummy one.


text:
Q: What library does the arg "-lphp5" refer to for GCC? Where can I get the library -lphp5 refers to?  Is it a part of a metapackage for YUM?
Can I find the source somewhere?  I'm having some configuration issues with PHC and this seems to be at the root of them.

A: On an overview level, it means link with the php5 library.  If PHC is this: http://www.phpcompiler.org then it makes sense that it would be looking for the PHP lib.  Where is this installed on your machine?  You should be able to do: locate libphp5 and find it.  If locate doesn't see it, you need to install PHP.
On a more specific level, -l means to look for a library.  -lNAME will make the linker look for libNAME.so first, and then if it can't find it, try libNAME.a.  Where will it look?  Generally /usr/lib, /lib, some compiler specific directories, and any directories provided with -L.  How can you make PHC find it if it isn't in a common path?  You should be able to set something in the build script for PHC.

A: You are probably getting this when installing PHP5.
From PHP5 Install Problems - libphp5.so not created :

When compiling you are receiving the
  message that the libphp5.so is not
  found, you must configure with the
  following option:
./configure
  --with-apxs2=/usr/local/apache/bin/apxs
You'll see immediately when compiling
  with "make install" that the library
  will be created.

If that's the case, why don't you install a binary release of PHP5, instead of compiling it from the sources?


text:
Q: How to parse a value from HTML form to a PHP value? I want to update the order preparation time. I have this little HTML form, but I'cant pass it in a PHP variable right after this code. I've used Cookies, I've used POST method but none helped me about it.
<form>
            <input type="text" id="save_order_time" name="order_time<?php echo $order_id ?>" />
            <input type="submit" name="submit" value="Update Order Time" onclick="order_time_a();">
            </form>

<script>

            function order_time_a(){
                var input = $('.menu-order-detail').find('input[name="order_time<?php echo $order_id ?>"]').val();
                //var input = 25;
                    <?php
                    //$order_time = '<script>var input = $(".menu-order-detail").find("input[name="order_time<?php echo $order_id "]").val();</script>';
                    //update_post_meta($order_id, 'foodbakery_order_time', $order_time); ?>

                console.log("Lets show something "+input);
                var d = new Date();
                d.setTime(d.getTime() + (1*24*60*60*1000));
                var expires = "expires="+ d.toGMTString();
                document.cookie = "order_time" + "=" + input + ";" + expires + ";path=/";
                console.log("Cookie was set. " + input);
            }

            </script>

            <?php

            echo ("<script>console.log('This code is executed first')</script>");
            //echo ('order_time'.$order_id);
            $order_time = $_COOKIE['order_time'];
            update_post_meta($order_id, 'foodbakery_order_time', $order_time);

When I use COOKIE solution the value that I've set in previous time is stored in the $order_time value. That's normal because I can't access COOKIE right after is set.
When I use POST method I get NULL in my database.
How can I implement the above?

A: There are a few things unclear in your explanation. Why are you using these different concepts next to each other?

*

*Form / POST

*Javascript

*COOKIE variable

I think you should try to only use the Form / POST option, see explanation here: HTML Form POST to PHP page

Besides that, in your javascript part I see this: var input = $('.menu-order-detail').find('input[name="order_time<?php echo $order_id ?>"]').val();
You should create it like this to find the right object:
var input = $('.menu-order-detail').find('input[name="order_time"]').val();


text:
Q: GGPLOT2: Two graphs in the first axis and the last one in the second axis I have the following code:
require(ggplot2)
require(extrafont)

loadfonts(device="pdf")

#set the x-axis now
xaxis <- seq(0,1, by=0.01)

#set the functions here
aij <- sqrt(1 - (1-xaxis)**1.02)
bij <- 1 - (1 - xaxis)**1.50
cij <- aij - bij

ggplot(transform(stack(data.frame(aij, bij, cij)), x = xaxis),
       aes(x = x, y = values, linetype = ind)) +
  geom_line() +
  theme_bw() +
  xlab("x ratio") +
  ylab("Function values") +
  theme(text=element_text(family="Times New Roman", face="bold", size=12),
        legend.title = element_blank()) +
  scale_linetype_manual(values = c("solid", "dashed", "dotted"))

I wish to have cij plotted in the second axis. How would that be possible?


text:
Q: Perl : How to match data in entire text In the following code I am trying to use data from Input File 1 to edit data in Input File 2. But the problem is the code is not able to match or substitute when the possible match text is anywhere other than at the last, towards right.
Could you please help me in figuring out way to match it in the entire text.
I am still new to coding so if you find any other possible enhancements, i will highly appreciate your guidance.
Input File 1
Saint   st

Saint   saint

Saint   st.

Saint   snt

Saint   snt.

Hotel   htl

Hotel   htl.

 Road   rd

 Road   rd.

Input File 2
Part.Name.

Gordon house st

Gordon saint house

Gordon st. house

Gordon snt house

Gordon snt. house

htl palace

htl. Indiana

nuav rd hotel

dankei hotel rd.

Code Starts Here
use strict;
use warnings;
open (my $fh1, "< $filename1") or die $!;
my @incomin_data1=<$fh1>;
my $array_length1=$#incomin_data1;
my @key; my @value;
for (my $count=0;$count<=$array_length1;$count++)
{($key[$count],$value[$count])=split /,/,$incomin_data1[$count];}
my $key_length=$#key;
open (my $fh2, "< $filename2") or die $!;
my @incomin_data2=<$fh2>;
my $array_length2=$#incomin_data2;
for (my $count2=0;$count2<=$array_length2;$count2++)
{     for (my $count3=0;$count3<=$key_length;$count3++)
{     my $ky=$key[$count3];
my $val=$value[$count3];
if ($incomin_data2[$count2]=~/\s?$val\s?/g)
{     $incomin_data2[$count2]=~s/$val/$ky/;  }}}
print "\n\n",@incomin_data2;

A: The best I can do for you is to simply write a solution. Your own code is irretrievable.
use strict;
use warnings;

my ($file1, $file2) = @ARGV;

my %abbrevs;

open my $fh, '<', $file1 or die $!;
while (<$fh>) {
  chomp;
  my ($phrase, $abbrev) = split /,/;
  if ( exists $abbrevs{$abbrev} ) {
    die sprintf 'Abbreviation "%s" already assigned to "%s"', $abbrev, $phrase;
  }
  $abbrevs{$abbrev} = $phrase;
}

my $re = join '|', map quotemeta, sort { length $b <=> length $a } keys %abbrevs;
$re = qr/$re/;

open $fh, '<', $file2 or die $!;
while (<$fh>) {
  s/(?<![\w.])($re)(?![\w.])/$abbrevs{$1}/g;
  print;
}

output
Part.Name.
Gordon house Saint
Gordon Saint house
Gordon Saint house
Gordon Saint house
Gordon Saint house
Hotel palace
Hotel Indiana
nuav Road hotel
dankei hotel Road


text:
Q: On create method not called after constructor I am creating an object of class which has  Sqlite database methods but when I call that class, my constructor is called but call is not going inside onCreate method..
My call is again returned back to caller class ...please tell me what I do to take the call inside onCreate method
I am calling KotDBHelper class using:
QueryListBean queryListBean=new QueryListBean();
            queryListBean.setQueryList(queryList);

             db=new KotDBHelper(context,queryListBean);
             db.getWritableDatabase();

my code for sqlite helper class

    public class KotDBHelper extends SQLiteOpenHelper {

        private static final int DB_VERSION = 3;
        private static final String DB_NAME = "eKOT";
        ArrayList<String> queryList;
        KotDBHelper objKotDBHelper;
        BeanInterface bean;
        /*private static final String TABLE_CATEGORIES="category_master";
        private static final String TABLE_KOT="kot_master";
        private static final String TABLE_ITEM="item_master";
        private static final String TABLE_KOT_DETAIL="kot_detail";
        private static final String TABLE_WAITER_MASTER="waiter_master";
        private static final String TABLE_TABLE_MASTER="table_master";
        private static final String TABLE_CONFIGURATION_MASTER="configuration_master";
        private static final String TABLE_USER_MASTER="user_master";*/

        public KotDBHelper(Context context,BeanInterface bean){
                    super(context, DB_NAME, null, DB_VERSION);
                    this.bean=bean;

        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            try{
                String address;
                BluetoothAdapter adpt=BluetoothAdapter.getDefaultAdapter();
                address=adpt.getAddress();
// casting bean here
            QueryListBean objBean=(QueryListBean)bean;
            objBean.getQueryList();

                AsyncClass objAsyncClass=new AsyncClass(objKotDBHelper,null,address);
                objAsyncClass.execute("");

                for(int i=0;i<queryList.size();i++){
                    db.execSQL(queryList.get(i));
                }
                /*db.execSQL(CREATE_TABLE_CATEGORIES);
                db.execSQL(CREATE_TABLE_ITEM);
                db.execSQL(CREATE_WAITER_MASTER);
                db.execSQL(CREATE_TABL_KOT);
                db.execSQL(CREATE_TABLE_KOT_DETAIL);
                db.execSQL(CREATE_TABLE_MASTER);
                db.execSQL(CREATE_CONFIGURATION_MASTER);
                db.execSQL(CREATE_USER_MASTER);
                db.execSQL("insert into table_master(table_no,curDate,type) values(1,'','Room')");
                db.execSQL("insert into table_master(table_no,curDate,type) values(10,'','Table')");
                db.execSQL("insert into user_master(username,password) values('admin','admin')");*/
            }catch(Exception e){
                e.printStackTrace();
            }
        }

A: This is sample code for creating database in android using sqlite helper class:
public class SQLite_Helper extends SQLiteOpenHelper {
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;

    // Database Name
    private static final String DATABASE_NAME = "mydb.db";

    // Contacts table name

    private static final String USER_TABLE = "User";
    public static final String TABLE_ACCOUNT = "Account";

     static String CREATE_TABLE_TRANSACTION = "CREATE TABLE " + TABLE_TRANSACTION + "("
                + TRAN_ID + " INTEGER PRIMARY KEY NOT NULL," + PAYEE + " TEXT," + CATEGORY + " TEXT," + AMOUNT + " NUMERIC,"
                + DUEDATE + " TEXT," + PAYFROM + " TEXT," + NOTES + " TEXT,"  + IS_REPEAT + " TEXT," + TYPE + " TEXT,"    + " FOREIGN KEY ("+TRAN_ID+") REFERENCES "+USER_TABLE+" ("+USER_ID+"));";

    String CREATE_USER_TABLE = "CREATE TABLE " + USER_TABLE + "("
            + USER_ID + "  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL," + FIRST_NAME + " TEXT not null unique," + LAST_NAME + " TEXT not null unique," + EMAIL + " TEXT not null unique,"
            + PASSWORD + " TEXT not null unique" + ")";

    static String CREATE_TABLE_ACCOUNT = "CREATE TABLE " + TABLE_ACCOUNT + "("
            + ACCT_ID + " INTEGER PRIMARY KEY NOT NULL," + ACCT_NAME + " TEXT,"
            + ACCT_HEAD_NAME + " TEXT," + OPEN_BAL + " TEXT,"+ ACCOUNT_EMAIL + " TEXT," + " FOREIGN KEY ("+ACCT_ID+") REFERENCES "+USER_TABLE+" ("+USER_ID+"));";

    public SQLite_Helper(Context context) {
        super(context, "login.db", null, 1);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub

        db.execSQL(CREATE_TABLE_ACCOUNT);
        db.execSQL(CREATE_USER_TABLE);
        db.execSQL(CREATE_TABLE_TRANSACTION);
    }
//      code or methods something here...
}

A: Database helper onCreate() runs once when

*

*opening the database with getWritableDatabase() or getReadableDatabase() and

*the database file didn't exist.
Once onCreate() returns successfully without throwing, the database is considered created.
See for more: When is SQLiteOpenHelper onCreate() / onUpgrade() run?
Doing other stuff than database setup in onCreate() is incorrect. Just create your tables and populate them with some default values if any. Remove all other code from onCreate().
Hiding problems by catching exceptions is incorrect. If there's a problem setting up the database, onCreate() should propagate the problem (exception) to the framework. Remove the try-catch.


text:
Q: Access a column from a Flask-SQLAlchemy paginate result My Document model has a text_location column, a file path that I need to read from after querying. I am using paginate when querying.
That is created through this code:
class Document(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    text_location = db.Column(db.String)

page_views = Document.query.paginate(page, 1, False)

I can display {{ page_views }} correctly in the template. However, if I try to open text_location, I get "Pagination" object has no attribute "text_location".
with open(page_views.text_location) as f:
    document_text = f.read()

How can I read the text_location for the Documents I queried?

A: Flask-SQLAlchemy's paginate method returns a Pagination object. The list of items retrieved is in the items attribute. Iterate over items to get individual model results.
pager = Document.query.paginate()

for document in pager.items:
    with open(document.text_location) as f:
        document.text = f.read()


text:
Q: Enter password with masking I have a simple example pieced together from some other posts:
[CmdletBinding(
    DefaultParameterSetName = 'Secret'
)]
Param (
    [Parameter(Mandatory=$True)]
    [string]$FileLocation,

    [Parameter(
        Mandatory = $True,
        ParameterSetName = 'Secret'
    )]
    [Security.SecureString]${Type your secret password},
    [Parameter(
        Mandatory = $True,
        ParameterSetName = 'Plain'
    )]
    [string]$Password
)

if ($Password) {
    $SecretPassword = $Password | ConvertTo-SecureString -AsPlainText -Force
} else {
    $SecretPassword = ${Type your secret password}
}

Write-Host $SecretPassword
$BSTR = `
    [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($SecretPassword)
    $PlainPassword = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($BSTR)
    Write-Host $PlainPassword

https://social.technet.microsoft.com/wiki/contents/articles/4546.working-with-passwords-secure-strings-and-credentials-in-windows-powershell.aspx
How can I use powershell's read-host function to accept a password for an external service?
When running the script how can I make it possible for the entered password to be masked?
So instead of this:
PS C:\temp> .\test.ps1 -FileLocation C:\Temp\file.csv  -Password secret

This
PS C:\temp> .\test.ps1 -FileLocation C:\Temp\file.csv  -Password ******

A: First capture the password using the below statement:
$password = Read-Host "Enter Your Password" -AsSecureString

This will mask the characters entered by the user on the screen.
But you can not use this string directly. In order to use this secure string in your script you need to convert this to a binary string:
$Newpass = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($password))

And then use $Newpass as the password entered by the user.

A: To start with, your example isn't going to happen. You are suggesting that you want whatever shell they execute the script from to mask the password, as it is entered as a parameter, before the script even executes. Not happening.
Now, an alternative would be to not accept the password as a parameter, and instead prompt for it every time. In that case you could reduce that entire If($Password) statement to just be:
$SecretPassword = Read-Host 'Type your secret password' -AsSecureString

A: AsSecureString parameter does this:

-AsSecureString
Indicates that the cmdlet displays asterisks (*) in place of the characters that the user types as input.


text:
Q: rasa core interactive chatbot training error I am trying to train a chatbot using the interactive module of rasa_core in Python 3.7, but I get an error. Is there a solution to fix this error?
I have written my source code in a file named "train_online.py" based on an example from the Book titled "Building Chatbots with Python Using Natural Language Processing and Machine Learning"
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import logging

from rasa_core import utils, train
from rasa_core.utils import AvailableEndpoints
#from rasa_core.training import online
from rasa_core.training import interactive
from rasa_core.interpreter import NaturalLanguageInterpreter
import os

logger = logging.getLogger(__name__)

def train_agent(interpreter):
    return train(domain_file="mybot_domain.yml",
     stories_file="./data/stories.md",
     output_path="./models/dialogue",
     endpoints=AvailableEndpoints("endpoints.yml"),
     interpreter=interpreter,
     policy_config='config.yml',
     kwargs={"batch_size": 50, "epochs": 200, "max_training_samples": 300})

if __name__ == '__main__':
    utils.configure_colored_logging(loglevel="DEBUG")
    interpreter = NaturalLanguageInterpreter.create("./models/nlu/default/mybot")
    agent = train_agent(interpreter)
    #online.serve_agent(agent)
    interactive.run_interactive_learning(agent)

after running I got the following error:
Traceback (most recent call last):
  File "f:/prog/train_online.py", line 45, in <module>
    agent = train_agent(interpreter)
  File "f:/prog/train_online.py", line 38, in train_agent
    kwargs={"batch_size": 50, "epochs": 200, "max_training_samples": 300})
  File "F:\prog\env\lib\site-packages\rasa_core\train.py", line 77, in train
    policies=policies)
  File "F:\prog\env\lib\site-packages\rasa_core\agent.py", line 230, in __init__
    self.nlg = NaturalLanguageGenerator.create(generator, self.domain)
  File "F:\prog\env\lib\site-packages\rasa_core\nlg\generator.py", line 37, in create
    "".format(type(obj)))
Exception: Cannot create a NaturalLanguageGenerator based on the passed object. Type: `<class 'str'>`

The list of packages that I am using in this project is as follows:
absl-py==1.4.0
APScheduler==3.9.1.post1
astor==0.8.1
attrs==22.2.0
Automat==22.10.0
backports.zoneinfo==0.2.1
boto3==1.26.54
botocore==1.29.54
certifi==2022.12.7
cffi==1.15.1
charset-normalizer==3.0.1
click==7.1.2
cloudpickle==0.6.1
colorama==0.4.6
colorclass==2.2.2
coloredlogs==10.0
colorhash==1.2.1
ConfigArgParse==0.13.0
constantly==15.1.0
cryptography==39.0.0
cycler==0.11.0
docopt==0.6.2
fakeredis==0.10.3
fbmessenger==5.6.0
Flask==1.1.4
Flask-Cors==3.0.10
Flask-JWT-Simple==0.0.3
future==0.17.1
gast==0.5.3
gevent==1.5.0
greenlet==0.4.16
grpcio==1.51.1
h5py==3.7.0
humanfriendly==10.0
hyperlink==21.0.0
idna==3.4
importlib-metadata==6.0.0
incremental==22.10.0
install==1.3.5
itsdangerous==1.1.0
Jinja2==2.11.3
jmespath==1.0.1
jsonpickle==1.5.2
jsonschema==2.6.0
Keras-Applications==1.0.8
Keras-Preprocessing==1.1.2
kiwisolver==1.4.4
klein==17.10.0
Markdown==3.4.1
MarkupSafe==2.0.1
matplotlib==2.2.5
mattermostwrapper==2.2
mock==5.0.1
networkx==2.6.3
numpy==1.21.6
packaging==18.0
pika==0.12.0
prompt-toolkit==3.0.36
protobuf==3.20.0
pycparser==2.21
pydot==1.4.2
PyJWT==1.7.1
pykwalify==1.7.0
pymongo==3.13.0
pyparsing==3.0.9
pyreadline==2.1
python-crfsuite==0.9.8
python-dateutil==2.8.2
python-engineio==4.3.4
python-socketio==3.1.2
python-telegram-bot==11.1.0
pytz==2018.9
pytz-deprecation-shim==0.1.0.post0
PyYAML==6.0
questionary==1.10.0
rasa-core==0.14.0
rasa-core-sdk==0.13.1
rasa-nlu==0.15.0
redis==2.10.6
requests==2.28.2
requests-toolbelt==0.10.1
rocketchat-API==0.6.36
ruamel.yaml==0.15.100
s3transfer==0.6.0
scikit-learn==0.20.4
scipy==1.7.3
simplejson==3.18.1
six==1.16.0
sklearn-crfsuite==0.3.6
slackclient==1.3.2
tabulate==0.9.0
tensorboard==1.13.1
tensorflow==1.13.2
tensorflow-estimator==1.13.0
termcolor==2.2.0
terminaltables==3.1.10
tornado==6.2
tqdm==4.64.1
twilio==6.63.2
Twisted==22.10.0
twisted-iocpsupport==1.0.2
typing==3.7.4.3
typing-extensions==4.4.0
tzdata==2022.7
tzlocal==4.2
urllib3==1.26.14
wcwidth==0.2.6
webexteamssdk==1.6.1
websocket-client==0.54.0
Werkzeug==1.0.1
zipp==3.11.0
zope.interface==5.5.2


text:
Q: Wagtail insert code into body (streamfield) Is it possible to insert html in any other way than RawHTML? RawHTML is a threat and was wondering if I could do it another way.
Thanks in advance!

A: As @gasman says in his comment on the question, inserting HTML carries the same risks no matter what form field you give your editors to do it.
However, you can implement a .clean() method on your block type which sanitises the HTML using Bleach.
e.g. to allow only
 tags:
>>> raw_html = """

Hello

"""
>>> html = bleach.clean(raw_html,
                        tags=['p'],
                        attributes={'p': ['id']},
                        strip=True)
>>> print(html)

Hello


text:
Q: How to add two consequetive colors to bars in a plotly barchart with values of one pandas column I would like to have a barchart where two colors are used for the bars, f.i. first blue next red, than blue again followed by red.
In matplotlib this is possible see below code.
I would like to do this also with plotly express.
Suggestions are appreciated.
df_1 = pd.DataFrame(freqfinal, columns=['teller' , 'frequenties']) # df = dataframe, pd staat voor Pandas

    fig = go.Figure()
    fig.add_trace(go.Bar(x=df_1.teller, y=df_1.frequenties, showlegend= True))

    fig.show()

    # in matplotlib, it works with two colors

    bar_colors = ['red', 'blue']
    ax = df_1['frequenties'].plot(kind='bar', color=bar_colors, title= 'series per 100 trekkingen') # barchart met behulp van matplotlib
    ax.set_xlabel('volgorde frequenties') #label x-as
    ax.set_ylabel('serie grootte') # label y-as
    plt.show()

See above, first part is the plotly base code second part is the matplotlib code where I was succesful to have the two colors side by side

A: If you give us a list of desired color combinations for the marker color, we can create the expected color scheme.
import pandas as pd
import numpy as np

np.random.seed(1)
df_1 = pd.DataFrame({'teller': list('ABCDEFGHIK'), 'frequenties': np.random.randint(0,50,10)})

import plotly.graph_objects as go

fig = go.Figure()
fig.add_trace(go.Bar(x=df_1.teller, y=df_1.frequenties, marker_color=['blue','red']*5, showlegend=True))

fig.show()


text:
Q: Vim plugin to connect between tag or block?
Hello vimers !
As you see on the picture, there is a vertical line to connect between opening tag and closing tag(html) or on function data.
Is there a plugin in vim connect between tag or block program, like in modern text editor ???

A: Check the built-in help for list and listchars
This should do the trick:
:set listchars=tab:\|\
:set list

(notice, that there's a space after the last backslash)


text:
Q: Can't send mail on server using Laravel and mailjet I am working on a Laravel project and try to send emails using mailjet. Sending mails local works fine, but using the same settings on my centos 7 webserver gives me an error which I can't resolve for days now.
.env settings
MAIL_MAILER=smtp
MAIL_DRIVER=smtp
MAIL_HOST=in-v3.mailjet.com
MAIL_PORT=587
MAIL_USERNAME=***
MAIL_PASSWORD=***
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=no-reply@***.com
MAIL_FROM_NAME="${APP_NAME}"

Sending the email
Mail::send('emails.auth.verify-email', ['token' => $token, 'user' => $user], function($message) use($user){
   $message->to($user->email);
   $message->subject('Email Verification Mail');
});

Error on CentOS 7 Server

Swift_TransportException
Connection could not be established with host in-v3.mailjet.com :stream_socket_client(): unable to connect to tcp://in-v3.mailjet.com:587 (Permission denied)

I already tried

*

*restarting apache

*sudo reboot

*php artisan cache:clear

*php artisan config:clear

*I have also tried mailgun instead of mailjet, got me the same error (only on the server, worked fine local)

*hard coding the connection credentials in config/mail.php instead of loading them from the .env file

as requested in the comments, here is the output of: dd(Config::get('mail'))
array:4 [▼
"default" => "smtp"
"mailers" => array:8 [▼
  "smtp" => array:8 [▼
    "transport" => "smtp"
    "host" => "in-v3.mailjet.com"
    "port" => 587
    "encryption" => "tls"
    "username" => "***"
    "password" => "***"
    "timeout" => null
    "auth_mode" => null
  ]
  "ses" => array:1 [▼
    "transport" => "ses"
  ]
  "mailgun" => array:1 [▼
    "transport" => "mailgun"
  ]
  "postmark" => array:1 [▼
    "transport" => "postmark"
  ]
  "sendmail" => array:2 [▼
    "transport" => "sendmail"
    "path" => "/usr/sbin/sendmail -t -i"
  ]
  "log" => array:2 [▼
    "transport" => "log"
    "channel" => null
  ]
  "array" => array:1 [▼
    "transport" => "array"
  ]
  "failover" => array:2 [▼
    "transport" => "failover"
    "mailers" => array:2 [▼
      0 => "smtp"
      1 => "log"
    ]
  ]
]
"from" => array:2 [▼
  "address" => "no-reply@pokeshares.com"
  "name" => "PokeShares"
]
"markdown" => array:2 [▼
  "theme" => "default"
  "paths" => array:1 [▼
    0 => "/var/www/pokeshares/resources/views/vendor/mail"
  ]
]
]

These look like the correct settings.
Any help is appreciated!


text:
Q: YouTube API - Description snippet from YouTube does not match the API / Getting "Primary" description text content I want to use the YouTube API to get the snippet of their description. However, I want it to be the primary text snippet describing the video YouTube uses as the snippet, which is different from the data api's response.
Let me give an example to clear things up:

*

*This video will be the demonstration: https://www.youtube.com/watch?v=ADPFEw-7FtU
At the top of this description is the text "Compress Decades Into Days. Get Dan Lok's World-Class Training Solutions to Grow Your Income, Influence and Wealth Today. Start Here ► [redacted]"
On the YouTube data API search snippet the response is: "Compress Decades Into Days. Get Dan Lok's World-Class Training Solutions to Grow Your Income, Influence and Wealth Today.". This makes sense because they're both at the start of the description. Now this is where I get confused.
If you search the title on YouTube (not the API), you'll actually see that the description is "Have you ever thought of starting an exciting YouTube career on YouTube doing what you love? Or maybe you have started, but ..."
This is the snippet I want. I want their video's "Primary SEO Search Snippet", which describes the video. Is there anyway to calculate this or get this from the API using another method? I don't want to use any non-official API/library to do this.
What this is not:

*

*This is not any caching that has yet to expire/update

*Unique to this video. There are plenty of videos where this happens

A: As far as I know there isn't any official API providing the data you are looking for. Anyway if you change your mind about not using unofficial APIs, then you can proceed as follows by trying out my open-source YouTube operational API. Indeed by fetching https://yt.lemnoslife.com/search?part=snippet&q=YOUR_QUERY, you will notably get the primary SEO search snippet you are looking for in item["snippet"]["detailedMetadataSnippet"].
For instance with "How To Grow With 0 Views And 0 Subscribers" you would get:
{
    "kind": "youtube#searchListResponse",
    "etag": "NotImplemented",
    "items": [
        {
            "kind": "youtube#searchResult",
            "etag": "NotImplemented",
            "id": {
                "kind": "youtube#video",
                "videoId": "ADPFEw-7FtU"
            },
            "snippet": {
                "channelId": "UCs_6DXZROU29pLvgQdCx4Ww",
                "title": "How To Grow With 0 Views And 0 Subscribers",
                "thumbnails": [
                    {
                        "url": "https:\/\/i.ytimg.com\/vi\/ADPFEw-7FtU\/hq720.jpg?sqp=-oaymwEjCOgCEMoBSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLCKNA5T652tMTvnOw22llDniM9O6Q",
                        "width": 360,
                        "height": 202
                    },
                    ...
                ],
                "channelTitle": "Dan Lok",
                "channelHandle": "DanLok",
                "timestamp": "3 years ago",
                "duration": 887,
                "views": 4495095,
                "badges": [
                    "CC"
                ],
                "channelApproval": "Verified",
                "channelThumbnails": [
                    {
                        "url": "https:\/\/yt3.ggpht.com\/ytc\/AMLnZu_TXnQ07ufj6eGxco9yHndCCcV5KfAizZ9jbI8vmA=s68-c-k-c0x00ffffff-no-rj",
                        "width": 68,
                        "height": 68
                    }
                ],
                "detailedMetadataSnippet": "Have you ever thought of starting an exciting YouTube career on YouTube doing what you love? Or maybe you have started, but\u00a0...",
                "chapters": [
                    {
                        "title": "Intro",
                        "time": 0,
                        "thumbnails": [
                            {
                                "url": "https:\/\/i.ytimg.com\/vi\/ADPFEw-7FtU\/hqdefault_25933.jpg?sqp=-oaymwEjCNACELwBSFryq4qpAxUIARUAAAAAGAElAADIQj0AgKJDeAE=&rs=AOn4CLBVOtOt_jLJd1dRRt5_dj3SlGBtRA",
                                "width": 336,
                                "height": 188
                            }
                        ]
                    },
                    ...
                ]
            }
        },
        ...
    ]
}

A: I wanted to add an answer for anyone trying to do this in 2023 and onwards.
I opened a ticket on the Google Issue Tracker regarding this issue: This was their response.

Hi Conor,
I was able to reproduce this behavior, and also found that neither a search resource description nor a video resource description will display the "Primary SEO Search Snippet" that you are seeking. Thus, I have opened up a feature request with our internal team to request this functionality, but I can't guarantee this feature will be implemented. Thus for updates regarding this, I recommend keeping an eye on our revision history.

You can use the unofficial API as per Benjamin's answer, but unfortunately, that can cause other issues depending on the scale you need to use this feature.


text:
Q: Color of status bar using react navigation I use React Navigation and I need to set the background color of the status bar darker than header. But Android Emulator has already done this automatically, when my phone set bgColor: none.
If I use component StatusBar with attribute bg, I wont change bg(but I can change barStyle-_-)

A: Use this one to change the background color of status bar in react native app
<StatusBar barStyle="light-content" backgroundColor="#1D6D91" />


text:
Q: How to give custom colour for each date in angular bsDatepicker I am using bootstrap bsDatepicker in my angular application to show calendar.
I need to give different colour for some dates in the calendar. For eg;

Here i need to give blue background colour for 28 and 29, red for 30 and 31. I already search in web but i didn't find any way to do this. Thanks in advance.

A: I got the solution, I created a dateCustomClasses array by conditionally.
let dateCustomClasses = this.getDates(minDate, maxDate);

getDates = (startDate, endDate) => {
    var dates = [],
      currentDate = startDate,
      addDays = function (days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
      };
    while (currentDate <= endDate) {
      let className = "blue";
      if (myCondition) {
        className = "red";
      }
      dates.push({ date: currentDate, classes: [className] });
      currentDate = addDays.call(currentDate, 1);
    }
    return dates;
  };

<input type="text" name="new_buyback_date" class="form-control" placeholder="Date"
      [(ngModel)]="date" [bsConfig]="bsConfig" [minDate]="minDate"
      [maxDate]="maxDate" (bsValueChange)="onDateChange($event)"
      [dateCustomClasses]="dateCustomClasses" bsDatepicker required>


text:
Q: Usage of '_id' on ExpandableListView with a CursorTreeAdapter Usage of _id is not clear enough in my mind. Considering all possible actions(onChildClick,onItemClick,onExpand,onCollapse etc. or even drawings) on ExpandableListView below;
=A==============
   -B-----------
   -C-----------
=D==============
   -E-----------
   -B-----------    //Note: B is included in both groups

is it OK to use same _id values with CursorTreeAdapter on following relations:

*

*B with C (this is problem I know)

*A with D (this is problem too, I know)

*A with B (this is what I am confused)

*E with C (also this one confuses me)

*E with B (possible problem)

*C with D (OK, I guess)

A: The _id simply has to be unique for any given category. In other words the parents (groups) must have a unique _id from each other and each individual child within a particular group should have a unique _id from each other but it doesn't matter if any have the same _id as a parent.
Using your example, groups A & D should not have the same _id.
In group A, children B & C should not have the same _id as each other but if one of them has the same _id as group A or group D then it doesn't matter.
In group D, children E & B should not have the same _id and, again, if one of them has the same _id as group A or group D this also doesn't matter.
Finally, child B in both groups can (and probably will) have the same _id in both instances.
In short, the CursorTreeAdapter requires a single Cursor for the groups and multiple separate Cursors for each set of children. None of these are directly related and each are self-contained.


text:
Q: How to deal with the third party component dependencies conflict with react native or other component? Now I am writing a android app with react native 0.13.2, and I want to use some third party components. but those components might be developed base on react native 0.16.0 or other version of react native. For example:
My android app is based on react native 0.13.2
component1 is based on react native 0.14.0
component2 is based on react native 0.12.0
component3 is based on react native 0.16.0
As I tested,the react native is not downward compatibility.
what should I do to avoid version conflict? or is there a better way to fixed conflict?

A: You'll have to deal with things the manual way. Upgrade your project, create forks of the components, and update them all to the same base version. You can either update them all to the newest version of React Native, or just pick the newest version among the set of your app and all the components.
From my experience, since most components are on the smaller side they're easy to upgrade to the newest libraries. Most of the things all you have to do is update the package file and maybe change one or two things to go from an old name to a new name. But if you're trying to make anything go past a major version (e.g. when new Android specific APIs come out) it's going to be harder.