text:
Q: Dynamic predicates for Linq-to-Entity queries The following Linq-to-Entities query works fine:
var query = repository.Where(r => r.YearProp1.HasValue &&
                                  r.YearProp1 >= minYear &&
                                  r.YearProp1 <= maxYear);

My database has a dozen or so columns that all report year-related information (short? data type). I want to reuse the same Linq-to-Entities logic for all these columns. Something like:
Func<RepoEntity, short?> fx = GetYearPropertyFunction();
var query = repository.Where(r => fx(r).HasValue &&
                                  fx(r) >= minYear &&
                                  fx(r) <= maxYear);

This results in the error:

LINQ to Entities does not recognize the method
  'System.Nullable`1[System.Int16] fx(RepoEntity)' method, and this
  method cannot be translated into a store expression.

I understand why I am getting the error, but am wondering if there is a workaround that doesn't involve duplicating code a dozen times just to change the property on which the SQL query is operating.
I would be reusing the function in more than one query, so I guess the general version of my question is: Is there a way to convert a simple property-getter lambda function to an Expression that can be consumed by Linq-to-Entities?

A: Building off of Raphaël Althaus' answer, but adding the generic selector you were originally looking for:
public static class Examples
{
    public static Expression<Func<MyEntity, short?>> SelectPropertyOne()
    {
        return x => x.PropertyOne;
    }

    public static Expression<Func<MyEntity, short?>> SelectPropertyTwo()
    {
        return x => x.PropertyTwo;
    }

    public static Expression<Func<TEntity, bool>> BetweenNullable<TEntity, TNull>(Expression<Func<TEntity, Nullable<TNull>>> selector, Nullable<TNull> minRange, Nullable<TNull> maxRange) where TNull : struct
    {
        var param = Expression.Parameter(typeof(TEntity), "entity");
        var member = Expression.Invoke(selector, param);

        Expression hasValue = Expression.Property(member, "HasValue");
        Expression greaterThanMinRange = Expression.GreaterThanOrEqual(member,
                                             Expression.Convert(Expression.Constant(minRange), typeof(Nullable<TNull>)));
        Expression lessThanMaxRange = Expression.LessThanOrEqual(member,
                                          Expression.Convert(Expression.Constant(maxRange), typeof(Nullable<TNull>)));

        Expression body = Expression.AndAlso(hasValue,
                      Expression.AndAlso(greaterThanMinRange, lessThanMaxRange));

        return Expression.Lambda<Func<TEntity, bool>>(body, param);
    }
}

Could be used somewhat like the original query you were looking for:
Expression<Func<MyEntity, short?>> whatToSelect = Examples.SelectPropertyOne;

var query = Context
            .MyEntities
            .Where(Examples.BetweenNullable<MyEntity, short>(whatToSelect, 0, 30));

A: A predicate is a filter in itself that should evaluate to bool (for whether or not to include it in the results). You can rework your method to look like this and it should work:
public static Expression<Func<RepoEntity, bool>> FitsWithinRange(int minYear, int maxYear)
{
    return w => w.HasValue && w >= minYear && w <= maxYear;
}

Edit: Oh and to use it:
var query = repository.Where(Repository.FitsWithinRange(minYear, maxYear));

A: You could do something like that (not sure if it will work "as is" in linq2 entities, but if you have a problem... just tell)
usage
var query = <your IQueryable<T> entity>.NullableShortBetween(1, 3).ToList();

function
public static IQueryable<T> NullableShortBetween<T>(this  IQueryable<T> queryable, short? minValue, short? maxValue) where T: class
        {
            //item (= left part of the lambda)
            var parameterExpression = Expression.Parameter(typeof (T), "item");

            //retrieve all nullable short properties of your entity, to change if you have other criterias to get these "year" properties
            var shortProperties = typeof (T).GetProperties().Where(m => m.CanRead && m.CanWrite && m.PropertyType == typeof(short?));

            foreach (var shortProperty in shortProperties)
            {
                //item (right part of the lambda)
                Expression memberExpression = parameterExpression;
                //item.<PropertyName>
                memberExpression = Expression.Property(memberExpression, shortProperty);
                //item.<PropertyName>.HasValue
                Expression firstPart = Expression.Property(memberExpression, "HasValue");
                //item.<PropertyName> >= minValue
                Expression secondPart = Expression.GreaterThanOrEqual(memberExpression, Expression.Convert(Expression.Constant(minValue), typeof (short?)));
                //item.<PropertyName> <= maxValue
                var thirdPart = Expression.LessThanOrEqual(memberExpression, Expression.Convert(Expression.Constant(maxValue), typeof (short?)));
                //item.<PropertyName>.HasValue && item.<PropertyName> >= minValue
                var result = Expression.And(firstPart, secondPart);
                //item.<PropertyName>.HasValue && item.<PropertyName> >= minValue && item.<PropertyName> <= maxValue
                result = Expression.AndAlso(result, thirdPart);
                //pass the predicate to the queryable
                queryable = queryable.Where(Expression.Lambda<Func<T, bool>>(result, new[] {parameterExpression}));
            }
            return queryable;
        }

EDIT : another solution, based on "simple" reflection, which "looks" as the one you want
public static short? GetYearValue<T>(this T instance)
        {
            var propertyInfo = typeof(T).GetProperties().FirstOrDefault(m => m.CanRead && m.CanWrite && m.PropertyType == typeof(short?));
            return propertyInfo.GetValue(instance, null) as short?;
        }

usage
var result = list.Where(item => item.GetYearValue() != null && item.GetYearValue() >= 1 && item.GetYearValue() <= 3).ToList();


text:
Q: Phonegap Android application restarting instead of resuming on coming back after home button click I have created PhoneGap 1.4/ with Android application with plugins.
My client reports that, when he leaves the app using the Home button, and then relaunches it using the app icon, the app relaunches from the start instead of resuming. However, when he press on lock or go to sleep the app resumes in the expected way.
The initialization process of the app is declared this way :
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d("EMOFIDActivity", "onCreatee " + this.getIntent());
    super.loadUrl("file:///android_asset/www/index.html");
}
    @Override
public void onPause() {
    Log.d("EMOFIDActivity", "onPause " + this.getIntent());
    super.onPause();
}// On click of home button this method is getting called

@Override
public void onResume() {
    Log.d("EMOFIDActivity", "onResume " + this.getIntent());
    super.onResume();
} // On click of app icon application is getting relaunched without coming to this function.

I have included three android Plugins and overridden the onPause() & onResume() methods like this. Here also OnResume() method is not at all getting called.
    @Override
public void onPause(boolean multitasking) {
    Log.d(TAG, "onPause " + ctx.getIntent());
    super.onPause(multitasking);
    stopNfc();
}

@Override
public void onResume(boolean multitasking) {
    Log.d(TAG, "onResume " + ctx.getIntent());
    super.onResume(multitasking);
    startNfc();
}

Is there a way to resolve this problem and come back to state where I Paused my application? What could be the problem in this process?

A: I had the same problem . My app was getting restarted when i click the app icon to relaunch the already running app in the background.
Basically if the

android:launchMode

is set to standard or not set ,then a new intent is created for the app and the old paused state of app is not resumed .
So the best way around i found was to apply
android:launchMode="singleTask"

in the AndroidManifest.xml -> inside  .
please conside this example :
  <activity android:name="Example" android:label="@string/app_name"
                 android:theme="@android:style/Theme.Black.NoTitleBar"                android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale"
                 android:launchMode="singleTask">
              <intent-filter>
                  <action android:name="android.intent.action.MAIN" />
                  <category android:name="android.intent.category.LAUNCHER" />
              </intent-filter>
          </activity>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Custom post url in search.php isn't the correct rewrited url I'm trying to get the rewrited URL of my custom post type on the search result page by using:
echo get_permalink(get_the_ID());
This returns the basename of my site plus the post slug, which isn't correct since I've rewritten the URL using the 'rewrite' argument in my register_taxonomy function.
On every page, using get_permalink in the post loop I get the correct URL, except on the search results page. Does anyone have an idea how to solve this?

A: Solved, it was an issue with assigned parent- and subcategories.
Because I'm using the 'WP All Import' plugin connected to Google Drive, posts are automatically imported. Since some of the posts don't have categories assign in the Google Drive document, 'WP All import' doesn't assign a category on importing the data.
For some reason this has resulted in duplicate content, importing already existing posts but without a category. Because the latest imported posts are without category and ordered descending by date on the search page, I was under the impression that there was something wrong with the permastructure.


text:
Q: Pack squares into a rectangle I have a rectangle width x height, and N squares of same unknown size.
I must determine the maximum size of these squares and number of rows and columns to fit perfectly (UPD. I mean not to fill all space, but fill as much space as possible) into the rectangle.
I guess, mathematically it looks like this:
x * size <= width                  //x - number of columns
y * size <= height                 //y - number of rows
x * y <= N                         //N - number of squares
size -> max                        //size - size of squares

Final result can look like this:
1 1 1 1
1 1 1 1
1 1 0 0

Where 1 = squares, 0 = empty space`.
Actually I saw similar problems, but with predefined size of squares. Also, I wrote some clumsy algorithm, but its results are very unsatisfactory..
Edit: My current algorithm:
I tried a lot of variations, but I cant make it work flawlessly for all cases. Actually, I can go through all possible sizes, but I do not like this approach.
// to make things more simple I put width as bigger size
int biggerSize = this.ClientSize.Width;
int lowerSize = this.ClientSize.Height;
int maxSize = int.MinValue;
int index = 0;
int index2 = 0;

// find max suitable size
for (int i = _rects.Count; i > 0; i--) {
  int size = biggerSize / i;
  int j = (int)Math.Floor((double)lowerSize / size);

  if (i * j >= _boards.Count && size > maxSize) {
    maxSize = size;
    index = (int)i;
    index2 = (int)j;
  }
}

int counter = 0;

// place all rectangles
for (int i = 0; i < index; i++) {
  for (int j = 0; j < index2; j++) {
    if (counter < _rects.Count) {
      _rects[counter].Size = new Size(maxSize, maxSize);
      _rects[counter].Location = new Point(i * maxSize, j * maxSize);
    }

    counter++;
  }
}

A: This problem came up recently in a project I was working on. Here is the solution that was determined:
int numItems; // the number of squares we need to pack in.
double rectWidth; // the width of the space into which we want to pack our squares.
double rectHeight; // the height of the space into which we want to pack our squares.

double tableRatio = rectWidth / rectHeight;
double columns = sqrt(numItems * tableRatio);
double rows = columns / tableRatio;

columns = ceil(columns); // the number of columns of squares we will have
rows = ceil(rows); // the number of rows of squares we will have

double squareSize = rectWidth / columns; // the size of each square.

A: Your question is not consistent.  First, you state the problem as "determine the maximum size of these squares and number of rows and columns to fit perfectly into the rectangle." (emphasis added).
But then you give a sample final result that allows empty space.
So which is it?
If you need the squares to fit perfectly in the rectangle with no empty space and no squares extending beyond the bounds of the rectangle, then the size of the maximal square would equal the greatest common divisor of the length and width of the rectangle.
See http://en.wikipedia.org/wiki/Greatest_common_divisor#A_geometric_view


text:
Q: Google chrome not remembering password I'll have to login to http://192.168.1.1/ each session to access internet.
I want chrome to store this password but it's not  happening.
However, in other sites (like fb,gmail) chrome is able to store the passwords.
How can i make it store passwords for this IP?

A: Steps to make Google Chrome offer to save (prompt) password for a particular site (for e.g abcd.com) and Auto-login the site with the credentials thus saved.
-> Go to the given URL 'abcd.com'
-> Right-click Page Info and disable 'JavaScript'
-> Reload the page.
-> Enter the credentials (uid,pwd)
-> A prompt appears to save password.
-> Click on Save password.
-> Auto-Login Extension bubble appears on this page.
At this point it is important because the extension 'Auto-Login' (like many other extensions) require
JavaScript to be enabled.
-> Re-enable the JavaScript for this page and reload the page.
-> Now Click on the 'Auto-Login' bubble for remembering automatically logging into the site hereafter!


text:
Q: Manual sorting of dimensions in Tableau CRM I have two text field where values are numeric- 1,2,3...500. When creating a heat map, it's not sorted as field is dimensions. And they are not sorted in correct order.
Is there any way to sort the field and have it in correct order?

A: You will need to convert from dimension to a measure.
You can either do it via the data recipe or in the dataflow itself using the transformation like dim2mea transformation.


text:
Q: org.openqa.selenium.WebDriverException: chrome not reachable while launching Chrome 80 on Ubuntu 18.04 I've Ubuntu 18.04 which has chrome with version 80.0.3987.87 and I trying to run Selenium tests on it with different following chromedriver versions

*

*79.0.3945.36

*80.0.3987.16

*80.0.3987.106

but it results into error -
    [testng] WARNING: WebDriverException thrown by findElement(By.id: j_username)
   [testng] org.openqa.selenium.WebDriverException: chrome not reachable
   [testng]   (Session info: chrome=80.0.3987.87)
   [testng]   (Driver info: chromedriver=79.0.3945.36 (3582db32b33893869b8c1339e8f4d9ed1816f143-refs/branch-heads/3945@{#614}),platform=Linux 4.15.0-74-generic x86_64) (WARNING: The server did not provide any stacktrace information)
   [testng] Command duration or timeout: 0 milliseconds
   [testng] Build info: version: '3.14.0', revision: 'aacccce0', time: '2018-08-02T20:13:22.693Z'
   [testng] Driver info: org.openqa.selenium.chrome.ChromeDriver
   [testng] Capabilities {acceptInsecureCerts: false, acceptSslCerts: false, applicationCacheEnabled: false, browserConnectionEnabled: false, browserName: chrome, chrome: {chromedriverVersion: 79.0.3945.36 (3582db32b3389..., userDataDir: /tmp/.com.google.Chrome.pFnA2S}, cssSelectorsEnabled: true, databaseEnabled: false, goog:chromeOptions: {debuggerAddress: localhost:41391}, handlesAlerts: true, hasTouchScreen: false, javascriptEnabled: true, locationContextEnabled: true, mobileEmulationEnabled: false, nativeEvents: true, networkConnectionEnabled: false, pageLoadStrategy: normal, platform: LINUX, platformName: LINUX, proxy: Proxy(), rotatable: false, setWindowRect: true, strictFileInteractability: false, takesHeapSnapshot: true, takesScreenshot: true, timeouts: {implicit: 0, pageLoad: 300000, script: 30000}, unexpectedAlertBehaviour: ignore, unhandledPromptBehavior: ignore, version: 80.0.3987.87, webStorageEnabled: true}
   [testng] Session ID: 215e1bff4f63437dbf8a0b8f0570c41b
   [testng] *** Element info: {Using=id, value=j_username}
   [testng]     at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
   [testng]     at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
   [testng]     at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
   [testng]     at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
   [testng]     at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:214)
   [testng]     at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:166)
   [testng]     at org.openqa.selenium.remote.http.JsonHttpResponseCodec.reconstructValue(JsonHttpResponseCodec.java:40)
   [testng]     at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:80)
   [testng]     at org.openqa.selenium.remote.http.AbstractHttpResponseCodec.decode(AbstractHttpResponseCodec.java:44)
   [testng]     at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:158)
   [testng]     at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
   [testng]     at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
   [testng]     at org.openqa.selenium.remote.RemoteWebDriver.findElements(RemoteWebDriver.java:349)
   [testng]     at org.openqa.selenium.remote.RemoteWebDriver.findElementsById(RemoteWebDriver.java:372)
   [testng]     at org.openqa.selenium.By$ById.findElements(By.java:180)
   [testng]     at org.openqa.selenium.remote.RemoteWebDriver.findElements(RemoteWebDriver.java:310)
   [testng]     at org.openqa.selenium.support.ui.ExpectedConditions.findElement(ExpectedConditions.java:895)
   [testng]     at org.openqa.selenium.support.ui.ExpectedConditions.access$000(ExpectedConditions.java:44)
   [testng]     at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:206)
   [testng]     at org.openqa.selenium.support.ui.ExpectedConditions$7.apply(ExpectedConditions.java:202)
   [testng]     at org.openqa.selenium.support.ui.ExpectedConditions$22.apply(ExpectedConditions.java:657)
   [testng]     at org.openqa.selenium.support.ui.ExpectedConditions$22.apply(ExpectedConditions.java:654)
   [testng]     at org.openqa.selenium.support.ui.FluentWait.until(FluentWait.java:260)
   [testng]     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
   [testng]     at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
   [testng]     at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
   [testng]     at java.lang.reflect.Method.invoke(Method.java:498)
   [testng]     at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:124)
   [testng]     at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
   [testng]     at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
   [testng]     at org.testng.internal.TestMethodWithDataProviderMethodWorker.call(TestMethodWithDataProviderMethodWorker.java:71)
   [testng]     at org.testng.internal.TestMethodWithDataProviderMethodWorker.call(TestMethodWithDataProviderMethodWorker.java:14)
   [testng]     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
   [testng]     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
   [testng]     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
   [testng]     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
   [testng]     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
   [testng]     at java.lang.Thread.run(Thread.java:745)

If I try to run this with latest version of chromedriver ie 81.0.4044.20 it gives following error which is expected-
org.openqa.selenium.SessionNotCreatedException: session not created: This version of ChromeDriver only supports Chrome version 81
But surprisingly, it fails with chromedriver 80 version. I could not find relevant issue on Selenium github. Please guide me with this.
**Additional Info: **
This reproduces only when we run tests through Jenkins pipeline along with Xvfb. If we run same test from the machine, it succeeds.


text:
Q: How to replace irrelevant data into mean values? Let's say I have 600,000 data points in column for age. In the data there are values 0 and -1, which is not relevant for age. How can I change both 0 and -1 values in my data to the column mean value using python?
The code so far:
df6 = df5['Vict Age'].replace([0, -1]).mean())
df6.update(df5)
df6

A: You can find the mean separatly and then use the correct replace syntax to replace desired values:
# Calculate mean ignoring -1, 0 values
age_mean = df5['Vict Age'][~df5['Vict Age'].isin([-1,0])].mean()
# Replace -1, 0 values
df5['Vict Age'] = df5['Vict Age'].replace({0: age_mean , -1: age_mean})

PS: Please use Stack Overflow code formatting instead of posting the image in the future. Thanks.


text:
Q: IOS Authentication using a LAMP stack I have a Cakephp app that runs on Amazon S3.  This app is the backend for my IOS app.  What is need to create a secure authentication from my ios register/login page to my MySQL page running on Amazon S3?

A: That's a very broad question with a lot of possible answers.  Token based authentication is a relatively simple option, and google has published a high level overview of that process.
https://developers.google.com/accounts/docs/MobileApps


text:
Q: Interpretation for Variance of Hypergeometric Distribution The standard formula for the Variance of the Hypergeometric Distribution is
$$ \operatorname{Var}(X) = n \frac{K}{N} \frac{N-K}{N} \frac{N-n}{N-1} $$
Where $$ X \sim \operatorname{Hypergeometric}(K, N, n)$$
Notice this has the following striking interpretation. If we consider the analogous drawing without replacement, say $$ Y \sim \operatorname{Binom}\left(n, \frac{K}{N}\right) $$ and the well known formula for its variance $$ \operatorname{Var}(Y) = n \frac{K}{N} \frac{N-K}{N} $$ then the ratio between the variance of the Hypergeometric drawing $X$ and its associated drawing with replacement $Y$ is a linear function in sample size. $$ \frac{\operatorname{Var}(X)}{\operatorname{Var}(Y)} = \frac{N-n}{N-1}$$ Furthermore, the linear function in $n$ is the unique linear function that has ratio $1$ when the sample size is $1$ (and hence the replacement has no effect--both are a Bernoulli trial), and that has the ratio is $0$ when $n=N$ (and one has drawn the whole bag, so the Variance is $0$). This makes it almost trivial to write down the formula for the Hypergeometric Variance as long as one remembers the Binomial Variance.
The Question
Is whether or not there is a way to see this interpretation at a glance. Is there an easy proof of the formula for the Variance of the Hypergeometric Distribution that reasons that the ratio between its variance and the associated Variance with replacement should be a linear function of sample size? Or at least, is there some obvious way to see this ratio is a linear function of sample size?

A: Facts:

*

*$\alpha=\frac{N-n}{N-1}$ is called the finite population correction factor.

*If $n=1$ (that is, the size of the drawn sample is just one) then $\alpha=1$ and we have the variance of binomial distribution. Indeed if a sample of size 1 is drawn, it doesn't matter whether it's with or without replacement. If $n=N$ then $\alpha=0$ and there is no variance at all since we get the entire population. In all other cases, $\alpha$ represents the reduction in variance caused by sampling without replacement.

*If $N\rightarrow \infty$ (that is, the population is very large) then $\alpha\approx1$. So the variance is about that of the binomial distribution. If the population is very large compared to the sample size (i.e. $N$ is much larger than $n$) then Hypergometric(K, N, n) is about Binomial(n, $\frac K N$).


text:
Q: PHP bugs with comparison operator I know the comparison operator of PHP is not 100% because of the automatic type declarations.
I did some tests and found this code
<?php
function foo($answer) {
    if ($answer > 10) {
        return true;
    } else {
        return $answer;
    }
}
if (foo(11)) {
    echo "11 is bigger than 10
";
}
if (foo(9)) {
    echo "9 is bigger than 10
";
}
?>

The output is:
11 is bigger than 10
9 is bigger than 10
Can someone explain me where and why the code fails in this comparison.

A: Because return $answer is truthy in both of your test cases.
This evaluates to:
if (11) { ...
if (9) { ...

A: Function foo() always returns some value. In this case both boolean and int type. Just make sure you are more strictly when you compare returned value.
<?php
function foo($answer) {
    if ($answer > 10) {
        return true;
    } else {
        return $answer;
    }
}

if (foo(11) === true) {
   // This returned TRUE
   echo "11 is bigger than 10
";
}

if ( is_int(foo(9)) === true ) {
   //This returned int
   echo "9 is bigger than 10
";
}
?>

A: You can do this,
<?php
function foo($answer) {
    return ($answer > 10);
}

if (foo(11)) {
    echo "11 is bigger than 10
";
}
if (foo(9)) {
    echo "9 is bigger than 10
";
}
?>

A: You are comparing it wrong way, $answer is non zero value and in PHP when you use it in condition every non zero value is consider to be true.
function foo($answer) {
    if ($answer > 10) {
        return true;
    } else {
        return false;
    }
}


text:
Q: Как вывести значение JSON файла в тег input Может вопрос и очень тупой, но всё же
Как мне строку из JSON файла занести в input, что бы в дальнейшем получить возможность редактировать её?
$('#wrapper').empty();
    $('#name').append($('<input>',
    {
        value: key,
        text :  JSON.stringify(database[key.selectedIndex].name),
    }));

A:

let jsn = {
  "text":"some text"
};
$('#wrapper').append($('<input>').val(jsn.text));


text:
Q: How to stop a node js server running as service I wrote a little server in node js, that I start as service when booting
My /etc/init.d/lightserver looks like this:
# Actions
case "$1" in
    start)
        # START
        /usr/bin/lightserver
        ;;
    stop)
        # STOP
        ;;
    restart)
        # RESTART
        ;;
esac
exit 0

I want to be able to stop the server properly with the command "/etc/init.d/lightserver stop". Without using of kill or killall.
How to implement this function into my server?
var i = 0;
var connect = require('connect');
var sleep = require('sleep');
var exec = require('child_process').exec;
var j = 1;

var server = connect().
use(function(req, res) {
    i++;
    res.write('Hello World! ' + i);
    res.end();
    let code = 83028 + j;
    j = 1 - j;
    exec("./433Utils/RPi_utils/codesend " + code, function(error, stdout, stderr) {
        console.log(stdout);
    });
}).listen(64084);
console.log("Server has started and is listening to http://localhost:64084/");

A: I think you are looking for something like this?
process.on('SIGTERM', () => {
  // some other cleanup code
  server.close();
});

What this does is intercept the kill command and close the server gracefully instead of just suddenly stopping the process, without warning.
To end the process gracefully you can just use the kill <PID> command, since SIGTERM is the default value. But if you want to be sure the sigterm is used you can always choose to use kill -SIGTERM <PID>, which will send a SIGTERM

The  default  signal  for  kill is TERM. Use -l or -L to list available
         signals.  Particularly useful signals include  HUP,  INT,  KILL,  STOP,
         CONT,  and  0.   Alternate  signals  may be specified in three ways: -9
         -SIGKILL -KILL.  Negative PID  values  may  be  used  to  choose  whole
         process  groups;  see the PGID column in ps command output. A PID of -1
         is special; it indicates all processes except the kill  process  itself
         and init.

http://linuxcommand.org/lc3_man_pages/kill1.html


text:
Q: Does robot framework support Python 3.x i can see online most of the videos and study materials are for robot framework with python 2.x, does robot framework support Python 3.x ?

A: Robot Framework supports Python 3 since the release of it's version 3.0. If you're using an earlier version of Robot Framework, it will not support Python 3.x
Next thing to take into consideration is, while Robot Framework's core itself now supports Python 3, not all of it's ecosystem does yet! For example, someone recently had problems using PaBot due to Python 3 incompatibility (see here)
Fortunately, most of the ecosystem is slowly getting updated by it's great community. As a matter of fact, the Selenium library, which is one of the most used libraries most of the time, has recently been updated to support Python 3
So, yes, Robot Framework does support Python 3.x, but not all of it's ecosystem does, so you should do an evaluation of your project's needs first before going with Python 3.

A: Yes, it does. More up-to-date information here: https://pypi.python.org/pypi/robotframework

A: Yes, Robot Framework supports Python 3. For more info you can visit this url:https://pypi.org/project/robotframework/

A: Finally I got the Robot Framework versions that Compatible for Python 3.x. PFB the details.
We need to install the mentioned version of python and also the mentioned version for all the PIP packaged  in sequence as mentioned below to work smoothly in Robot Framework Ride with Python 3.x
python 3.6.8...The
Chromedriver link:https://sites.google.com/a/chromium.org/chromedriver/home
1.wxPython==4.0.7.post2
2.decorators==0.1.1
3.setuptools-scm==3.3.3
4.selenium==3.141.0
5.robotframework==3.1.2
6.pywin32==227
7.Pypubsub==4.0.3
8.robotframework-ride==1.7.3.1

A: Yes, it does support python 3.x
I am using robot framework 3.2.1 with Python 3.7.4
You might need an IDE, for which you can either use RIDE or pycharm
Ride version 1.7.4.2


text:
Q: Android delivery information in Telephony.TextBasedSmsColumns How to check if the message is delivered in the sms content provider (Telephony.TextBasedSmsColumns fields)

A: By STATUS field
mCursor = contentResolver.query(Uri.parse("content://sms"),
                arrayOf("body", "date", "type", "status"),
                "address like ?",
                arrayOf("%$id"),
                "date asc")

val status = mCursor.getInt(3)
if (status == 0) {
    Toast.makeText(this, "Deliverd", Toast.LENGTH_SHORT)
} else if (status == 32)
    Toast.makeText(this, "Sent and waiting for delivery", Toast.LENGTH_SHORT)
} else if (status == 64) {
    Toast.makeText(this, "Failed", Toast.LENGTH_SHORT)
}

Telephony.TextBasedSmsColumns - STATUS


text:
Q: using vsftpd with inotify IN_CLOSE_WRITE event I'm trying to write event based ftp server that notifies me when some user uploads any file(users will never do any delete or other stuff, they just upload). Apache ftpServer with ftplets is what I need but it is java based and does not satisfy my environment. So what I'm planning to do is to run vsftpd and  another process besides it which listens to IN_CLOSE_WRITE event. When vsftpd close the file descriptor after finishing file upload, my process will be notified and I will do some appropriate action. My questions are:

*

*Is it possible that I miss any file upload?

*Is it possible that IN_CLOSE_WRITE fired in other situations that I get inconsistent files instead of ready to use files?

A: *

*if the incrond service crashes or is stopped you will loose notification during that time

*IN_CLOSE_WRITE should work.


text:
Q: Django Rest Swagger Not showing up all the APIs I am working with Django Rest swagger. But it's not showing up all the APIs.
The url paths for /tickets are missing:

Even path to /dj-rest-auth/user/ is missing as well:

Backend/urls.py
from django.contrib import admin
from django.urls import path, include
from rest_framework_swagger.views import get_swagger_view

schema_view = get_swagger_view(title='API')

urlpatterns = [
    path('admin/', admin.site.urls),
    #path('api/v1/', include(api_urlpatterns)),
    #path('dj-rest-auth/', include('dj_rest_auth.urls')),
    path('dj-rest-auth/', include('dj_rest_auth.urls')),
    path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')),
    path('api/', include('ticket.urls')),
    path('swagger/', schema_view)
]

Tickets/urls.py
from django.urls import path
from ticket import views

urlpatterns = [
    path('tickets/', views.ticket_list),
    path('tickets/<int:pk>/', views.ticket_detail),

]

My directory structure:

A: Try with below code:
REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': (
       'rest_framework.permissions.AllowAny',
    ),
    .......
    .......
}

A: I solved this by going in settings.py file and set DEBUG=True.


text:
Q: grade multiple responses from different users I want to grade/score the response of different users inputs. For this I have used Multinomial navie bayes. The below my code.
# use natural language toolkit
import nltk
from nltk.stem.lancaster import LancasterStemmer
import os
import json
import datetime
stemmer = LancasterStemmer()
# 3 classes of training data
training_data = []
# capture unique stemmed words in the training corpus
class_words={}
corpus_words = {}
classes = list(set([a['class'] for a in training_data]))
for c in classes:
    class_words[c] = []

for data in training_data:
    # tokenize each sentence into words
    for word in nltk.word_tokenize(data['sentence']):
        # ignore a few things
        if word not in ["?", "'s"]:
            # stem and lowercase each word
            stemmed_word = stemmer.stem(word.lower())
            if stemmed_word not in corpus_words:
                corpus_words[stemmed_word] = 1
            else:
                corpus_words[stemmed_word] += 1

            class_words[data['class']].extend([stemmed_word])

# we now have each word and the number of occurances of the word in our training corpus (the word's commonality)
print ("Corpus words and counts: %s" % corpus_words)
# also we have all words in each class
print ("Class words: %s" % class_words)
sentence="The biggest advantages to a JavaScript having a ability to support all modern browser and produce the same result."
def calculate_class_score(sentence, class_name):
    score = 0
    for word in nltk.word_tokenize(sentence):
        if word in class_words[class_name]:
            score += 1
    return score
for c in class_words.keys():
    print ("Class: %s  Score: %s" % (c, calculate_class_score(sentence, c)))
# calculate a score for a given class taking into account word commonality
def calculate_class_score_commonality(sentence, class_name):
    score = 0
    for word in nltk.word_tokenize(sentence):
        if word in class_words[class_name]:
            score += (1 / corpus_words[word])
    return score
# now we can find the class with the highest score
for c in class_words.keys():
    print ("Class: %s  Score: %s" % (c, calculate_class_score_commonality(sentence, c)))
def find_class(sentence):
    high_class = None
    high_score = 0
    for c in class_words.keys():
        score = calculate_class_score_commonality(sentence, c)
        if score > high_score:
            high_class = c
            high_score = score
    return high_class, high_score

Note: I haven't added any training data.
When I give the input as
find_class("the biggest advantages to a JavaScript having a ability to
 support all modern browser and produce the same result.JavaScript
 small bit of code you can test")

I'm getting the output as
('Advantages', 5.07037037037037)

But when I give the input as
find_class("JavaScript can be executed within the user's browser
without having to communicate with the server, saving on bandwidth")

I'm getting the response/output as
('Advantages', 2.0454545)

I'm building it for the JavaScript Interview/viva questions.
When a user type the same answer in the different way as I mentioned above I'm getting I'm getting different scores. I want the scores to be precise. How can I do it.

A: Multinomial Naive Bayes compares word occurrences. It does not take order into consideration since it considers every feature as independent of other. Thus, semantic similarity (different sentences, same meaning) is not always an easy problem to solve with Naive Bayes.
If in your case semantic similarity has some direct correlation to words present (to an extent that order can be ignored), then you can try following things:

*

*Play around with data. See what results efforts like stopwords removal or using techniques like TF-IDF yield.

*See if Word2Vec (or Doc2Vec) get you better results

*Use more training data

These are very lazy suggestions that I can give without knowing much about how your data looks.

A: Multinomial Naive Bayes will output different scores for different inputs. This is true for any classification algorithm actually.
The only way to get the same score for two different sentences is for the sentences to contain exactly the same words (in different order, or frequency)
See the algorithm's definition for more detail.


text:
Q: Generic convert I would like to be able to convert a type that inherits from a Role to a Role.  For example, a RoleWithApiResources.
My Convert function looks like this right now, but does not compile:
public static Role Convert<T>(T role) where T : Role
{
    var result = new Role();
    result.Id = T.Id;
    result.Name = T.Name;
    result.Description = T.Description;

    return result;
}

A: Based on your constraint, you should use role instead of T (and use the object initializer to simplify the code):
public static Role Convert<T>(T role) where T : Role
{
    var result = new Role
    {
        Id = role.Id,
        Name = role.Name,
        Description = role.Description
    };

    return result;
}

A: Inside your function you need to use the 'role' parameter instead of T
For example:
public static Role Convert<T>(T role) where T : Role
{
    var result = new Role();
    result.Id = role.Id;
    result.Name = role.Name;
    result.Description = role.Description;

    return result;
}


text:
Q: How to Record a call in AsteriskNOW? How to enable Call Recording on AsteriskNOW ?
I am a student doing my final year project in this domain.I have installed asterisk server and able to make the connections.
But unable to record the calls.
I have googled a lot and found something about monitor command.But I am still struggling where to place the monitor command in extensions.confPlease do help me.
Thanks in advance
Regards,
Rashmi.R

A: Do you use Monitor cmd ? If not: add it to your dialplan (there is also StopMonitor cmd). If you already use it then you will have to show us more details: dialplan, maybe some fragment of asterisk log with error.
There is example of my dialplan with Monitor cmd:
[afterwork_service]
exten => s,1,NoOp
exten => s,n,Answer
exten => s,n,PlayBack(recording_starting_info)
exten => s,n,Wait(2)
exten => s,n,Monitor(wav,${CALLFILENAME})

It plays info about recording starting and then customer can record praises to our service, software and developers :)


text:
Q: Kotlin: How to verify an extension function is called on a mock Say I have a Java class Metrics. I defined some extension functions on Metrics in Kotlin
fun Merics.expose(name: String, value: Number) {
 // do something
}

Note that the Java class Metrics also has a method called expose but with different signature.
I created a test where I mocked a metrics objects and call a code path where the extension function expose should be called. But how can I verify that those extension functions are invoked?
I tried to use mockk and mockito-kotlin, none of them seem to know that metrics object has a new function called expose with different signatures.

A: You can not verify that the extension function is called on your mock, as it is not part of that class. The extension function is just a top-level function with a receiver (in your case an instance of Metrics).
But you can still verify that the extension function was called in your code
You can do this using mockkStatic.
You are passing the the path of the (generated) extension function. Let's assume you created your Metrics extension function in package org.com. The extension class should get generated in: com.org.MericsExtensionKt.
A test that wants to verify the call to your extension function could look like:
@Test
fun check_metrics_expose_extension_was_called() {
  mockkStatic("com.org.MericsExtensionKt")

  // call your function that is calling Metrics.expose()
  // classUnderTest.someFunction()

  // this verifies a call to the extension function and their parameters
  verify { any<Metrics>().expose(name = any(), value = any()) }
}


text:
Q: Layering multiple canvases using z-index doesn't show highest layer In HTML, I am trying to create one canvas that just displays an image with the colour black, and another canvas that displays a white border on top of the black canvas beneath it. Here's the HTML code:
<body>
<canvas width=600 height=400 style="position:absolute;background-image:url('Black.png');z-index:1;"
</canvas>
<canvas width=400 height=200 style="position:absolute;border:1px solid #FFFFFF;z-index:2;"
</canvas>
</body>

When I run the code in Google Chrome, I can only see the black background and no white border. What have I done wrong here? I tried searching for the problem but I didn't find an answer.

A: It's because your HTML is not well formatted.
This:
<canvas width=600 height=400 style="position:absolute;background-image:url('Black.png');z-index:1;"

Should be this:
<canvas width=600 height=400 style="position:absolute;background-image:url('Black.png');z-index:1;">

A: Are you closing your canvas tags?
You have
<canvas width=600 height=400 style="position:absolute;background-image:url('Black.png');z-index:1;"

Try instead
<canvas width=600 height=400 style="position:absolute;background-image:url('Black.png');z-index:1;">


text:
Q: October CMS | Dynamic importExportConfig in same controller I want to implement two different import procedure in same controller. As October CMS configuration I created two import_export config files and two different Import Model Class. But it always point the Initial config file model class which I defined in public $importExportConfig = 'config_import_export.yaml'; controller property.
My implementation code is given bellow,
public $importExportConfig = 'config_import_export.yaml';

public function __construct()
{
...
}

public function import($context = null)
{
    $this->asExtension('ImportExportController')->setConfig('config_import_export.yaml');
    $this->asExtension('ImportExportController')->import($context);
}

public function system_import($context = null)
{
    $this->asExtension('ImportExportController')->setConfig('config_system_import_export.yaml');
    $this->asExtension('ImportExportController')->import($context);
    return $this->makePartial('system_import');
}

Code in config file,
import:
    title: 'Import Phone Numbers'
    modelClass: Bol\PhoneManager\Models\SimImport
    list: $/bol/phonemanager/models/sim/export_import_columns.yaml
    redirect: bol/phonemanager/sim/import

If I initially public $importExportConfig = ''; make the property blank then its points the proper Model Class as config file but then throw an error like bellow,

I am trying to solve in many ways but I can't found any solution. If there any other solution please help.


text:
Q: Please explain the loop below I made a GUI calculator by looking at my course video, but I am not able to understand what the "for loop" is doing in the code below.
 try:
    import tkinter
except ImportError: # python 2
    import Tkinter as tkinter

keys = [[('C', 1), ('CE', 1)],
        [('7', 1), ('8', 1), ('9', 1), ('+', 1)],
        [('4', 1), ('5', 1), ('6', 1), ('-', 1)],
        [('1', 1), ('2', 1), ('3', 1), ('*', 1)],
        [('0', 1), ('=', 1), ('/', 1)],
        ]

mainWindowPadding = 8

mainWindow = tkinter.Tk()
mainWindow.title("Calculator")
mainWindow.geometry('640x480-8-200')
mainWindow['padx'] = mainWindowPadding

result = tkinter.Entry(mainWindow)
result.grid(row=0, column=0, sticky='nsew')

keyPad = tkinter.Frame(mainWindow)
keyPad.grid(row=1, column=0, sticky='nsew')

row = 0
for keyRow in keys:
    col = 0
    for key in keyRow:
        tkinter.Button(keyPad, text=key[0]).grid(row=row, column=col, columnspan=key[1], sticky=tkinter.E + tkinter.W)
        col += key[1]
    row += 1

A: This for loop is basically used for laying out the buttons on your window.
for KeyRow in keys :

repeats all the code in the loop the amount of times rows of keys are present in the list keys (in this case, there are 5 rows)
col = 0 and row = 0 are used for positioning the keys on the window.
for key in keyRow:

repeats all the code in the loop the amount of times a key is present in a row (eg. the first row has 2 keys, so the loop will repeat all the sub code twice etc...)
tkinter.Button(keyPad, text=key[0]).grid(row=row, column=col, columnspan=key[1], sticky=tkinter.E + tkinter.W)

This is for the positioning of the keys.
col += key[1] shifts the key position on the y axis by one every time a key is placed on a window and row += 1shifts the row position on the x axis by one every time a row of keys is placed on the window.
Hope this answers your question !


text:
Q: Процесс не может получить доступ к файлу Пишу программу на C#, которая работает с файлами. Открыть на чтение (StreamReader) у меня нормально обрабатывает, а вот открыть файл на запись (StreamWriter) компилятор кидает ошибку System.IO такого типа:
Процесс не может получить доступ к файлу как этот файл используется другим процессом

A: При работе с файлами, надо помнить, что если вы открыли файл монопольно, то пока не закроете поток связанный с этим файлом, попытки привязать к тому же файлу другой поток будут завершаться исключением. Корректно работу с файлом на чтение и запись можно сделать двумя способами:
Без освобождения потока:
Stream myStream;

using (myStream = File.Open(@"\test.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
    StreamWriter myWriter = new StreamWriter(myStream);
    myWriter.WriteLine("test");
    //перед чтением необходимо вернуть указатель потока в нужное место, у меня - в начало файла.
    myStream.Position = 0;
    StreamReader myReader = new StreamReader(myStream);
    Console.Write(myReader.ReadToEnd());
}

При таком подходе важно указать FileAccess.ReadWrite при создании потока и не закрывать StreamWriter и StreamReader, т.к. они при закрытии закрывают и поток. На все время работы файл будет заблокирован для других приложений.
С освобождением потока:
Stream myStream;

using (myStream = File.Open(@"\test.txt",FileMode.OpenOrCreate,FileAccess.Write))
{
    StreamWriter myWriter = new StreamWriter(myStream);
    myWriter.WriteLine("test");
}

using (myStream = File.Open(@"\test.txt", FileMode.OpenOrCreate, FileAccess.Read))
{
    StreamReader myReader = new StreamReader(myStream);
    Console.Write(myReader.ReadToEnd());
}

В этом случае после чтения и записи поток освобождается. Соответственно между чтением и записью (в любом порядке) файл доступен другим процессам.
Блоки using гарантируют освобождение потока. Вместо этого можно использовать myStream.Close(), но про это можно случайно забыть, так что using надежнее.
В принципе, отдельно поток можно и не создавать, StreamWriter и StreamReader сами умеют создавать поток к файлу по его имени, в таком случае код короче:
using (StreamWriter myWriter = new StreamWriter(@"\test.txt"))
{
    myWriter.WriteLine("test");
}

using (StreamReader myReader = new StreamReader(@"\test.txt"))
{
    Console.Write(myReader.ReadToEnd());
}

Но вы лишаетесь возможности настроить FileShare, и запретить другим программам блокировать файл пока вы им не пользуетесь.
Кроме всего перечисленного крайне желательно прежде чем открывать потоки чтения-записи, проверять существование файла, наличие необходимых прав доступа и т.д. потому что отсутствие какой либо из проверок в большинстве случаев гарантирует исключение.


text:
Q: AlarmManager as a service, how can I get the set alarm to repeat? I have multiple AlarmManagers inside of a Service class. I set each AlarmManager to a different time and I can get it to repeat using setRepeating(). I start my service from an Activity. Ok, now for my real question.
Everyday, these times set change. And in my activity, I get a new instance of these timings (not modifying it directly, but by doing a series of calculations i.e. calling a method). And by getting a new instance of different times, I want to know how I can be able to update and restart the Alarm service with these new times, even if the app is closed?

A: Try this,
public class MainActivity extends AppCompatActivity {

    private PendingIntent pendingIntent;
    private AlarmManager manager;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Retrieve a PendingIntent that will perform a broadcast
        Intent alarmIntent = new Intent(this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
    }
    public void startAlarm(View view) {
        manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        int interval = 3000; // 3 seconds

        manager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval, pendingIntent);
        Log.e("System.currentTime", "" + System.currentTimeMillis());
        Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
    }

    public void cancelAlarm(View view) {
        if (manager != null) {
            manager.cancel(pendingIntent);
            Toast.makeText(this, "Alarm Canceled", Toast.LENGTH_SHORT).show();
        }

    }
}

and this is your AlarmReceiver
/**
 * Created by Techno Blogger on 1/2/17.
 */

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1) {
        // For our recurring task, we'll just display a message
        Toast.makeText(arg0, "I'm running", Toast.LENGTH_SHORT).show();

    }

}

and do remember to mention this in your Manifest.xml
 <receiver android:name=".AlarmReceiver"></receiver>


text:
Q: Im trying to print the "J" in initial = dotmatrix.dotJ("J") I have a project where I build a dotmatrix module and then import it into another program that will print out my initials. I have it done to the point where it will print out my initials, but it won't print the "J" in the
initial = dotmatrix.dotJ("J")

It will just print the "*". I have defined in my module:
def dotJ(char):
    """Creates a capital J in 7 x 7 dots"""
    dotJ =  "      * \n"
    dotJ += "      * \n"
    dotJ += "      * \n"
    dotJ += "      * \n"
    dotJ += " *    * \n"
    dotJ += " *    * \n"
    dotJ += "  ***   \n"
    return dotJ

where I have the *, I want it to print out whatever is called for in the
initial = dotmatrix.dotJ("J")

A: A simple way would be to define your dotJ variable with a star and then replace the star with the character:
def dotJ(char):
    """Creates a capital J in 7 x 7 dots"""
    dotJ =  "      * \n"
    dotJ += "      * \n"
    dotJ += "      * \n"
    dotJ += "      * \n"
    dotJ += " *    * \n"
    dotJ += " *    * \n"
    dotJ += "  ***   \n"
    dotJ = dotJ.replace("*",char)
    return dotJ

You could also use a format string. But I suspect this would be less easy to read.


text:
Q: Unable to access value from for loop in shell script when run from cron This is my first foray into shell scripting so if i'm asking a very basic question please be gentle with me!
I have a shell script which downloads a file via FTP, uses split to break the file into separate smaller files. I then use a for loop to call a PHP file which does some processing on the file, this PHP process is run in the background to completion.
This 2 script combo works fine when run from the command line under sudo, however when it is run from the cron I don't seem to be able to get the file name value to pass into PHP.
My 2 test scripts are as follows
shell-test.sh
#!/bin/bash

cd /path/to/directory/containing/split/files/

#Split the file into seperate 80k line files
split -l 80000 /path/to/file/needing/to/be/split/

#Get the current epoch time as all scripts will need to use the same update time
epochtime=$(date +"%s")

echo $epochtime

#Output a list of the files in the directory
ls

#For loop to run through each file in the working directory
#For each file we run the php script with safe mode off (to enable access to includes)
#We pass in the name of the file and epochtime
#The ampersand at the end of the string runs the file in the background in parallel so     that all scripts execute concurrently

for file in *
do
php -d safe_mode=Off /path/to/php/script/shell-test.php -f $file -t $epochtime &
done

#Wait for all scripts to finish
wait

shell-test.php
<?php

$scriptOptions = getopt("f:t:");

print_r($scriptOptions);

?>

When run from the command line outputs the following which is what I need - the file value is passed to the PHP script.
1319824758
xaa  xab  xac  xad
Array
(
[f] => xaa
[t] => 1319824758
)
Array
(
[f] => xac
[t] => 1319824758
)
Array
(
[f] => xad
[t] => 1319824758
)
Array
(
[f] => xab
[t] => 1319824758
)

However when run via the cron the following is outputted
1319825522
xaa
xab
xac
xad
Array
(
[f] => *
[t] => 1319825522
)

So what I need to know is how to get the value of * as the file name and not as the actual string * (and why this is happening would be useful too!).

A: My random guess is that cron is running the shell with the -f option for safety. Try adding
set +f

to your script. Or find some other way of enumerating the files.


text:
Q: What does the "*" mean in this recursive ruby function? I read this code that is about quicksort with monkey-patching for the Array class.
class Array
  def quicksort
    return [] if empty?

    pivot = delete_at(rand(size))
    left, right = partition(&pivot.method(:>))

    return *left.quicksort, pivot, *right.quicksort
  end
end

I don't know what the star (*) sign seen at the start of *left.quicksort is. Can't we just use left.quicksort?

A: The star (in this case) stands for array unpacking. The idea behind it is that you want to get one array with the given elements, instead of array of array, element, array:
left  = [1, 2, 3]
pivot = 4
right = [5, 6, 7]

[left, pivot, right] # => [[1, 2, 3], 4, [5, 6, 7]]

[*left, pivot, *right] # => [1, 2, 3, 4, 5, 6, 7]

A: The * takes a list of arguments and splits them into individual elements.
This allows you to return one un-nested array even when the left and right themselves return an array.
Regarding can't we just use left.quicksort did you give it a try?
def a()
  return *[1,2,3], 4, *[5,6]
end

def b()
 return [1,2,3], 4, *[5,6]
end

b()
=> [[1, 2, 3], 4, 5, 6]
a()
=> [1, 2, 3, 4, 5, 6]

A: Without the asterisk,  you will have three values returned... the first and last value will be a single array with multiple values
[array1], pivot, [array2]

With the asterisk, the array values will be returned as separate components...
array1_value_1, array1_value_2, array1_value_3, ..., pivot, array2_value_1, array2_value2, array2_value_3, ...


text:
Q: AWS Certificate Manager for ELB pointing to a Apache Server Running on EC2 I was reading the aws documentation for Certificate Manager. I can associate a SSL certificate for a ELB. I have already done that and my application is still residing on Apache server deployed on a Ubuntu EC2 server.

And in the documentation it has the following,

Note Currently, ACM Certificates are associated with Elastic Load
  Balancing load balancers or Amazon CloudFront distributions. Although
  you install your website on an Amazon EC2 instance, you do not deploy
  an ACM Certificate there. Instead, deploy the ACM Certificate on your
  Elastic Load Balancing load balancer or on your CloudFront
  distribution.

To my understanding, that means we can just deploy the application on a EC2 and add it under a load balance that has certificate from the ACM.
And that is all you need to have to work SSL for your web application.
But when I am not using this approach, I was using the following Apache configuration to configure SSL.
<VirtualHost *:80>
        DocumentRoot /var/www/html/
        ServerName example.com
        ServerAlias example.com
        ErrorLog ${APACHE_LOG_DIR}/diyoron-error_log
        CustomLog ${APACHE_LOG_DIR}/diyoron-access_log common

        <Directory /var/www/html/>
                RewriteEngine on
                RewriteCond %{HTTPS} off
                RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R]
        </Directory>

</VirtualHost>

<VirtualHost *:443>
        # ServerAdmin webmaster@example.com
        DocumentRoot /var/www/html/

        ServerName example.com
        ServerAlias example.com
        ErrorLog ${APACHE_LOG_DIR}/example-error_log
        CustomLog ${APACHE_LOG_DIR}/example-access_log common
        SSLEngine On

        SSLCertificateKeyFile /etc/letsencrypt/live/example.com/privkey.pem
        SSLCertificateFile /etc/letsencrypt/live/example.com/cert.pem
        SSLCertificateChainFile /etc/letsencrypt/live/example.com/chain.pem

</VirtualHost>

But In my current arrangement I can not configure SSLCertificateKeyFile, SSLCertificateChainFile , SSLCertificateFile in my Apache configuration.
If anybody can direct me to a right path that is much appreciated.
AH00016: Configuration Failed
[Fri Apr 21 23:14:01.184314 2017] [ssl:emerg] [pid 1190] AH02572: Failed to configure at least one certificate and key for example.com:443
[Fri Apr 21 23:14:01.184826 2017] [ssl:emerg] [pid 1190] SSL Library Error: error:140A80B1:SSL routines:SSL_CTX_check_private_key:no certificate assigned
[Fri Apr 21 23:14:01.184834 2017] [ssl:emerg] [pid 1190] AH02311: Fatal error initialising mod_ssl, exiting. See /var/log/apache2/error.log for more information

A: You will terminate SSL on youe ELB and configure it to forward both HTTP and HTTPS requests as HTTP (to your instance's port 80):

Therefore, you will not need <VirtualHost *:443> anymore.
Also, in your Apache configuration, in <VirtualHost *:80> you are redirecting users to https:// if the connection is not using SSL/TLS (btw, that condition was unnecessary, request would have never reached that point if it was using https - you could just unconditionally redirect it). This will not be possible any more since, from apache's point of view, all incoming connections use http://.
To determine the protocol used between the client and the load balancer, use the X-Forwarded-Proto request header (Elastic Load Balancing stores the protocol used between the client and the load balancer in the X-Forwarded-Proto request header and passes the header along to your server):
RewriteCond %{HTTP:X-Forwarded-Proto} !https [NC]
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]


text:
Q: project.json vs csproj adding packages My question is how to specifically search for asp.net core packages to add to my projects.  I was using the project.json file fluently.  So far my experience with csproj and nuget and getting the specific .net core package is that it is cumbersome.
For example, I can search for entityframework and the list will include many packages and extensions but not the entityframeworkcore package. I can search the nuget website and use the tags option which assists, but this really seems like a step backwards from the ease of project.json. Is there a simple trick that I am missing? Ideally, I would like to be able to use nuget commands from command line, pull back packages with a keyword like entityframework, and filter the list of returned packages to those specific to .net core
https://www.nuget.org/packages?q=Tags%3A%22Core%22


text:
Q: Adding up buffers into one I have a mesh consisting of several entries.
Every entry contains it's own list of faces, vertices, normals, colors and texture coordinates.
Can I loop though all of my entries and use glVertexAttribPointer to cummulate data of an attribute in a single buffer object, like this?:
glBindBuffer(vbo);
for(Entry* e : entries) {
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, e->vertices);
    ...
}

In other words, will repeated calls on glVertexAttribPointer for attribute 0 of buffer vbo rewrite the data pointed on before or not?
If yes, is there any effective solution out of copying all vertices into one consecutive memory block before calling glVertexAttribPointer only once for the whole buffer?

A: glVertexAttribPointer does only store (for each attribute) the last information you supplied to it. So appending buffers is not possible by this method.
You have two options when you have a situation like yours:

*

*Issue for each buffer a separate draw-call

*Copy the data off all buffers into a single buffer and issue one draw-call for it. Note that in this case the indices might have to be adjusted to point to the correct positions in the combined buffer.

A: glVertexAttribPointer() does not copy anything. It only sets state that specifies where the vertex data will be fetched from. If you call it repeatedly for the same attribute, each call will replace the previous state, and the last one wins.
Starting with OpenGL 3.1, there is a glCopyBufferSubData() call (man page) that allows you to copy data from one buffer to another. Using this, you could allocate a buffer with enough space for all verctices, and then copy the smaller buffers into the buffer holding all vertices.
That being said, it does not sound like a great idea to use it this way. If you want all vertices in the same buffer, it's much easier and more efficient to store them in that buffer right from the start.
You definitely should not copy around the vertex data on each draw call. While reducing the number of draw calls is desirable, copying around vertex data is much more expensive.


text:
Q: Is it true that $cl_{\beta X} Z(f) = Z(\hat f)$? Suppose $f\in C^* (X)$ and let $\hat f$ be its continuous extension to $\beta X$. It is clear that
$cl_{\beta X} Z(f)=cl_{\beta X} f^{-1}(${$0$}$)\subseteq \hat f ^{-1}(${$0$}$)= Z(\hat f)$, but I am having some difficulty showing the reverse inclusion.

A: It is not necessarily true.  Consider, for instance, $X=(0,1)$, and $f(x) = x$.  Then $Z(f) = \emptyset$, but $Z(\hat{f})$ is not empty; for instance, the set $\{\frac{1}{2}, \frac{1}{3}, \frac{1}{4}, \dots\}$ has a limit point $y \in \beta X$ by compactness, and by continuity we must have $\hat{f}(y) = 0$.


text:
Q: issue with rotation and uilabels with size set using NSString's sizeWithFont I have a few UILabels in my view with their height set using sizeWithFont:.
I set the autoreszingMask to flexible width and height, however on rotate the width changes (am assuming because self.view's width changes and its set with a width relative to self.view) but the height of it doesn't change to fit the content again. This results in a large white space at the top and bottom.
Just wondering how I would go about re-sizing the UILabel on rotation? Is there any automatic way of doing this, or is there a way of getting all UILabels and re-doing sizeWithFont when the device is rotated?
The UILabels are subviews of UIView heirarchies used as headers for sections in my UITableView.
Thanks
Tom

A: You should really send sizeToFit to any UIView, especially UILabel, instead of forcing some arbitrary size on them.
The best approach is usually to first set the maximum width and current height, then send sizeToFit, then adjust the width again if necessary. In case of multiline labels it looks like the most foolproof way to avoid layout bugs.

A: The problem was having a flexible left and right margin on a slightly offset uilabel.
If the label isn't centered then you need to choose left or right and set the flexible margin for one of those.


text:
Q: Uniform Limits of Analytic functions, complex analysis question Here's the question I'm trying to answer:
Let $f$ be analytic on an open set $U$, let $z_{0}\in U$ and $f'(z_{0})\neq 0$. Show
\begin{equation*}
    \frac{2\pi i}{f'(z_{0})}=\int _{C}\frac{1}{f(z)-f(z_{0})}dz
\end{equation*}
where C is a small circle centered at $z_{0}$.
I'm unsure how to start this problem. I've tried some manipulation of the Cauchy Integral formula, but haven't really gotten anywhere.
Additionally, this problem appears in a section where only one theorem is given, so I'm confident you need to use it but I can't figure out how. Here's the theorem:
Let $\{f_{n}\}$ be a sequence of analytic functions on an open set $U$, converging uniformly on every compact subset $K\subseteq U$ to a function $f$. Then $f$ is holomorphic. Furthermore, the sequence of derivatives $\{f'_{n}\}$ converges uniformly on every compact subset $K$ to $f'$.
Any hints would be appreciated. Thanks so much in advance.

A: Cauchy integral theorem says that if $f(z)$ is analytic inside a contour then
$\oint_\gamma \frac {f(z)}{z-z_0} \ dz = 2\pi i f(z_0)$
What can we do to get this integral into that form?
$\oint_\gamma \frac {z-z_0}{(z-z_0)(f(z) - f(z_0)} \ dz$
Let $g(z) = \frac {z - z_0}{f(z) - f(z_0)}$
$\oint_\gamma \dfrac {g(z)}{z-z_0} \ dz = 2\pi i g(z_0)$
So what is $g(z_0)$?
$f'(z_0) = \lim_\limits{z\to z_0} \frac {f(z) - f(z_0)}{z-z_0} = \lim_\limits{z\to z_0} \frac 1{g(z)}$
Since $f(z)$ is analyitc and $f'(z_0) \ne 0$ we can say $g(z_0) = \frac {1}{f'(z_0)}$

A: Hint: $1/(f(z)-f(z_0))$ has a simple pole at $z_0$ and nowhere else inside the circle $C$ if $C$ is small enough. Use the residue theorem.

A: Another approach would be to note that $f(z)-f(z_0) = f'(z_0)(z-z_0) + g(z) (z-z_0)^2$, where $g$ is analytic on an open set containing $U$ and for sufficiently small $|z-z_0|$ we have
${1 \over f(z)-f(z_0)} = {1 \over f'(z_0)(z-z_0)} \sum_{k=0}^\infty ( -{ g(z)(z-z_0) \over f'(z_0)} )^k$ and so
$\int_C {dz \over f(z)-f(z_0)} = \int_C {1 \over f(z)'(z-z_0)} dz
= 2 \pi i \operatorname{res}(\eta, z_0)$, where
$\eta(z) = {1 \over f(z)'(z-z_0)}$.


text:
Q: SQL Query: calculating percentage If I wanted to find the percentage of people that are from the zip code area of 12345, I would take the number of people with that zip code and divide it from the total number of people… what am I missing in the example query below? I can't figure out how to display the percentage correctly. It just keeps saying 0%.
select (count(P.PERSON_ID) / (select count(*) from PERSON P)) * 100.00
as "12345 Zip Code Percentage"
from PERSON P
where P.ZIP = '12345'

Thank you.

A: You're doing an integer division. If the result is lower to 1, it will always display 0 * 100.00, so always 0. If you want an accurate percentage, you need to cast one of the variables as a float.
select (count(P.PERSON_ID) / CAST ((select count(*) from PERSON P) As Float)) * 100.00
as "12345 Zip Code Percentage"
from PERSON P
where P.ZIP = '12345'

A: If you want to choose the number of decimal points you could also incorporate ROUND() as follows:
,ROUND(CAST(COUNT(var1) AS FLOAT)/COUNT(var2),[# decimals]) AS 'mypercentage'

A: You're dividing an integer by a larger integer. The result is always going to be zero. Instead, multiply the first count by 100.0 before division. That converts the first count to a floating point number which, when divided by an integer, will give a floating point number and thus the percentage you need.

A: Try this:
SELECT (P.SubSet * 100.00)/p.Total AS "12345 Zip Code Percentage"
  FROM (
        SELECT COUNT(CASE WHEN ZIP = '12345' THEN 1 ELSE 0 END ) Subset,
               COUNT(*) Total
          FROM PERSON
       ) P

A: Try this, i added extra condition to avoid divide by 0 error:
select
    CASE
    WHEN  (select count(*) from PERSON P) > 0 THEN (CAST(count(P.PERSON_ID) As Decimal) / CAST((select count(*) from PERSON P)As Decimal)) * 100.00
    ELSE 0 END
    as "12345 Zip Code Percentage"
    from PERSON P
    where P.ZIP = '12345'

A: select AVG(CASE WHEN ZIP = '12345'
           THEN 1 ELSE 0
           END) * 100.00 as "12345 Zip Code Percentage"
from PERSON P


text:
Q: Design of concurrent processing of a dual buffer system? I have a long-running application that basically:

*

*read packets off network

*save it somewhere

*process it and output to disk

A very common use-case indeed - except both the data size and data rate can be quite large. To avoid overflow of the memory and improve efficiency, I am thinking of a dual buffer design, where buffer A and B alternate: while A is holding networking packet, B is processed for output. Once buffer A reaches a soft bound, A is due for output processing, and B will be used for holding network packets.
I am not particularly experienced on concurrency/multi-thread program paradigm. I have read some past discussion on circular buffer that handle multiple-producer and multiple consumer case. I am not sure if that is the best solution and It seems the dual buffer design is simpler.
My question is: is there a design pattern I can follow to tackle the problem? or better design for that matter? If possible, please use pseudo code to help to illustrate the solution.  Thanks.

A: I suggest that you should, instead of assuming "two" (or any fixed number of ...) buffers, simply use a queue, and therefore a "producer/consumer" relationship.
The process that is receiving packets simply adds them to a buffer of some certain size, and, either when the buffer is sufficiently full or a specified (short...) time interval has elapsed, places the (non-empty) buffer onto a queue for processing by the other.  It then allocates a new buffer for its own use.
The receiving ("other...") process is woken up any time there might be a new buffer in the queue for it to process.  It removes the buffer, processes it, then checks the queue again.  It goes to sleep only when it finds that the queue is empty.  (Use care to be sure that the process cannot decide to go to sleep at the precise instant that the other process decides to signal it... there must be no "race condition" here.)
Consider simply allocating storage "per-message" (whatever a "message" may mean to you), and putting that "message" onto the queue, so that there is no unnecessary delay in processing caused by "waiting for a buffer to fill up."

A: It might be worth mentioning a technique used in real-time audio processing/recording, which uses a single ring buffer (or fifo if you prefer that term) of sufficient size can be used for this case.
You will need then a read and write cursor.  (Whether you actually need a lock or can do with volatile plus memory barriers is a touchy subject, but the people at portaudio suggest you do this without locks if performance is important.)
You can use one thread to read and another thread to write.  The read thread should consume as much of the buffer as possible.  You will be safe unless you run out of buffer space, but that exists for the dual-buffer solution as well.  So the underlying assumption is that you can write to disk faster then the input comes in, or you will need to expand on the solution.

A: Find a producer-consumer queue class that works. Use one to create a buffer pool to improve performance and control memory use.  Use another to transfer the buffers from the network thread to the disk thread:
#define CnumBuffs 128
#define CbufSize  8182
#define CcacheLineSize 128

    public class netBuf{
      private char cacheLineFiller[CcacheLineSize];  // anti false-sharing space
      public int dataLen;
      public char bigBuf[CbufSize];
    };

    PCqueue pool;
    PCqueue diskQueue;
    netThread Thread;
    diskThread Thread;

    pool=new(PCqueue);
    diskQueue=new(PCqueue);

    // make an object pool
    for(i=0;i<CnumBuffs,i++){
      pool->push(new(netBuf));
    };

    netThread=new(netThread);
    diskThread=new(diskThread);
    netThread->start();
    diskThread->start();
    ..

    void* netThread.run{
      netbuf *thisBuf;
      for(;;){
        pool->pop(&thisBuf};  // blocks if pool empty
        netBuf->datalen=network.read(&thisBuf.bigBuf,sizeof(thisBuf.bigBuf));
        diskQueue->push(thisBuf);
      };
    };

    void* diskThread.run{
      fileStream *myFile;
      diskBuf *thisBuf;
      new myFile("someFolder\fileSpec",someEnumWrite);
      for(;;){
        diskQueue->pop(&thisBuf};  // blocks until buffer available
        myFile.write(&thisBuf.bigBuf,thisBuf.dataLen);
        pool->push(thisBuf};
      };
    };


text:
Q: running two powershell commandlets into a single command I require file properties and its MD5 hash piped into a csv file, using two different commandlets for this purpose.
 Can I combine both into a single command or maybe a snippet and get the desired output?
I'm using the following to get hash of the desired file aswell as file properties
Get-FileHash C:\Windows\System32\drivers\1394bus.sys Algorithm SHA512 | Format-List

Get-ChildItem C:\Windows\System32\drivers\1394bus.sys | Get-ItemProperty | Select VersionInfo | Format-List *

I'm basically new to this so any tips would be helpful!

A: You could reuse the Path property from the output of Get-FileHash in a calculated property, like so:
Get-FileHash C:\Windows\System32\drivers\1394bus.sys -Algorithm SHA1 |Select *,@{Label='VersionInfo';Expression={(Get-Item $_.Path).VersionInfo}} |Format-List


text:
Q: How to animate background to become transparent? Using keyframes. how would I animate this background to become transparent?
background: linear-gradient(120deg, #155799, #159957);

I would add a delay to it until the video is in-front of the background, then it would animate to become transparent.
I do not know how the code would be written to do that.
How would I do that in the code?
Video can be seen in the code.
code: https://jsfiddle.net/kh67yr4z/

const videoPlayer = (function makeVideoPlayer() {
  const config = {};
  let player = null;

  const tag = document.createElement("script");
  tag.src = "https://www.youtube.com/iframe_api";
  const firstScriptTag = document.getElementsByTagName("script")[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

  function onYouTubeIframeAPIReady() {
    const frameContainer = document.querySelector(".video");
    videoPlayer.addPlayer(frameContainer, config.playlist);
  }

  function shufflePlaylist(player) {
    player.setShuffle(true);
    player.playVideoAt(0);
    player.stopVideo();
  }

  function onPlayerReady(event) {
    player = event.target;
    player.setVolume(100); // percent
    shufflePlaylist(player);
  }

  function addPlayer(video, playlist) {

    const config = {
      height: 360,
      host: "https://www.youtube-nocookie.com",
      width: 640
    };
    config.playerVars = {
      autoplay: 0,
      cc_load_policy: 0,
      controls: 1,
      disablekb: 1,
      fs: 0,
      iv_load_policy: 3,
      loop: 1,
      playlist,
      rel: 0
    };
    config.events = {
      "onReady": onPlayerReady
    };
    player = new YT.Player(video, config);

  }

  function init(videos) {
    config.playlist = videos.join();
    window.onYouTubeIframeAPIReady = onYouTubeIframeAPIReady;
  }

  return {
    addPlayer,
    init
  };
}());

videoPlayer.init([
  "CHahce95B1g",
  "CHahce95B1g",
  "CHahce95B1g",
  "CHahce95B1g"
]);
html,
body {
  height: 100%;
  margin: 0;
  padding: 0;
}

body {
  background: black;
}

.container {
  position: absolute;
  left: 0;
  right: 0;
  min-height: 100%;
  display: flex;
}

.video-wrapper {
  flex: 1 0 0;
  margin: auto;
  max-width: 640px;
  position: relative;
  overflow: hidden;
  background: linear-gradient(120deg, #155799, #159957);
}

.ratio-keeper {
  position: relative;
  height: 0;
  padding-top: 56.25%;
  margin: auto;
}

.video-frame {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  animation: fade 10s ease-in 0s forwards;
}

@keyframes fade {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

iframe {
  user-select: none;
}

.hide {
  display: none;
}