text:
Q: animateWithDuration Completion block fires over and over again I've got a little animation going, and when that animation ends I want the App to automatically push the next ViewController on. Well that ViewController gets pushed on like 8 times in a row! Its pretty crazy.
here's the code:
     if CGRectIntersectsRect(whichButton.frame, targetZoneImgView.frame) {
        panGesture.cancelsTouchesInView = true
        let buttonSnapX = UIScreen.mainScreen().bounds.width / 2.0 - 35.0
        let buttonSnapY = UIScreen.mainScreen().bounds.height - 122.0

        UIView.animateWithDuration(0.75, delay: 0.0,
                usingSpringWithDamping: 0.1,
                 initialSpringVelocity: 0.0,
                               options: UIViewAnimationOptions.CurveEaseOut,
                            animations: {
                                 myButton.frame.origin.x = buttonSnapX
                                 myButton.frame.origin.y = buttonSnapY
                            }, completion: { (finished: Bool) -> Void in
                                  print("Animation done!")
                                  let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
                                  let coursesScreen = storyBoard.instantiateViewControllerWithIdentifier("coursesScreen") as! CoursesVC
                                  self.navigationController!.pushViewController(coursesScreen, animated: true)
                               }
                           )

That print("Animation done!") statement also fires like 8-9 times in a row, so its really got nothing to do with the fact that I'm pushing a ViewController. I took out the ViewController code - and its still happening.
Basically, anything I put in completion is firing a whole bunch of times in a row.
What in the world is going on?

A: You may enter completion block with false value of finished variable. Just add a basic check:
UIView.animateWithDuration(0.75, delay: 0.0,
                usingSpringWithDamping: 0.1,
                 initialSpringVelocity: 0.0,
                               options: UIViewAnimationOptions.CurveEaseOut,
                            animations: {
                                 myButton.frame.origin.x = buttonSnapX
                                 myButton.frame.origin.y = buttonSnapY
                            }, completion: { (finished: Bool) -> Void in
                                 if finished {
                                    print("Animation done!")
                                    let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
                                    let coursesScreen = storyBoard.instantiateViewControllerWithIdentifier("coursesScreen") as! CoursesVC
                                    self.navigationController!.pushViewController(coursesScreen, animated: true)
                                 } else {
                                    print("Animating...")
                                 }
                            }
                          )


text:
Q: Azure Functions TimerTrigger Restarted after hours of running My Azure Function App (TimerTrigger) restarted after hours of running. How to prevent my Function App from stop running before it finishes? It is running on App Service plan.
Always On = True

This image shows what happens before it stopped running.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple field comparison in Rails where clause Is there a cleaner, DRYer, way to write this in Rails 5.0 using Postgres as the DB?
CrmRevenueLineItem.references(:crm_account)
.where("crm_accounts.name ILIKE :qry OR crm_accounts.legal_name ILIKE :qry
        OR crm_accounts.website ILIKE :qry", qry: wildcard_query)

I feel like I'm repeating myself a lot in there. It was worse before I learned about named parameters (the :qry) and was using ? as the placeholder.

A: A little bit shorter variant using concat_ws function
CrmRevenueLineItem.references(:crm_account)
.where("CONCAT_WS(' ', crm_accounts.name, crm_accounts.legal_name, crm_accounts.website) ILIKE :qry", qry: wildcard_query)


text:
Q: Рекурсивный запрос в MS SQL, в чем ошибка? Имеется рекурсивный запрос. По условиям задачи необходимо вывести иерархическую структуру имя, уровень в иерархии и кол-во подчинённых. Данный запрос выдает мне одну строку (верх дерева) с parent_id равный NULL. Как вывести всю таблицу в нужном формате?
WITH
    Rec (id, parent_id, name, level)
AS (
        SELECT e.id, e.parent_id, e.name, 0 AS level
        FROM Employee e
        UNION ALL
            SELECT e.id, e.parent_id, e.name, Rec.level+1 AS level
            FROM Employee e
            JOIN Rec ON Rec.id = e.parent_id
    )
SELECT Rec.*, COUNT = (
        SELECT COUNT(*)
        FROM Employee e
        WHERE e.id = Rec.id
    )
FROM Rec
WHERE Rec.parent_id IS NULL;

A:
WHERE Rec.parent_id IS NULL;

Видимо, это условие для корня. Оттого и выводит только его. Это условие нужно поместить в анкорную часть, и от него уже раскручивать.


text:
Q: Laravel mysql query shut down server I'm currently building an application with Laravel php Framework using Eloquent ORM. Im just trying to optimize this query because it takes very long time to display results.
Here's the code, How can i optimze it?
$messages = DB::table('mp as m1')
            ->select(DB::raw('m1.id as id, m1.user_id, m1.titre, m1.titremd5, content, m1.vu, users.name, users.slug, users.avatar, m1.horodateur, m1.id_conversation'))
            ->join('users', 'm1.user_id', '=', 'users.id')
            ->whereRaw('id_conversation IN (SELECT id FROM conversations_in WHERE user_id = '.Auth::user()->id.' AND visible=1 AND horodateur_fin = "") AND m1.id = (SELECT MAX(mp.id) FROM mp WHERE mp.id_conversation = m1.id_conversation)')
            ->orderBy('m1.id', 'DESC')
            ->paginate(10);

I have no idea why this work so slow and it takes like 10 seconds to load page. Can somebody help me out?

A: Add db indexes for columns: horodateur_fin, visible


text:
Q: how can I check when i run my program how much memory is occupied by my program in memory I want to check that when i run my program how much memory is occupied by my program in memory because I want to reduce the size of my program if I get that how much memory occupy my program then its help to me to reduce the size. so any one can tell me how can I do this in C?
In detail,
 lets suppose that I used 4 integer variables and some statements in our program and then I run my program on that time in memory how much memory reserved/ use by my program ?? Thats my main question.. and how chack I check that


text:
Q: Twitter Bootstrap 3 responsive text media queries I am trying to implement responsive text using media queries in bootstrap 3.
Sample "mystyles.less" media queries for less:
@media (min-width: @screen-sm-min) {
 @font-size-base:10px;
}
@media (min-width: @screen-md-min) {
@font-size-base:12px;
}
@media (min-width: @screen-lg-min) {
@font-size-base:14px;
}

now when i add "mystyles.less" to "bootstrap.less" like this:
.
.
.
@import "variables.less";
@import "responsive-fontsize.less";
.
.
.

now nothing is happening, font sizes are not responsive. Any idea about problem ?


text:
Q: Reliably Extracting String In Flutter List Every Time So I have a quite interesting exercise I've been trying to solve for a while now, but haven't come up with a reliable solution, so I thought you guys could help me out. I have this String that is composed of few random custom parts, for example:
"William\nWilliam description here...\n$170.00 usd") + Uuid().v4();

I need to extract the part after '$' and '.', in this case 170, but it can be any number between.
UPDATE
as I said in the last comment, if I wanted to do it in a function (find the price only), it could go something like this:
deleteSumItem(item) {
final regEx = RegExp(r'\$\d+(?:\.\d+)?');
const textToSearch = r'item';
final priceValueMatch = regEx.firstMatch(textToSearch);
print(priceValueMatch.group(0));
_totalPrice.remove(priceValueMatch);
_counter = _counter - priceValueMatch; //getting error here to convert to num
  //but int.parse won't work either, then I get the String error
  //RegExp can't be assigned to paremeter String

}

Also, this function returns null for regex, so there is some mistake I'm making, any thoughts?
deleteSumItem(item) {
final regEx = RegExp(r'\1\d+(?:\.\d+)?');
final priceValueMatch = regEx.firstMatch(r'item');
print('THIS IS REGEX: $priceValueMatch');} //priceValueMatch returns null

fix
deleteSumItem(item) {
RegExp regExp = RegExp(r'\^(\d+)\^');
String input = item;
String match = regExp.firstMatch("r" + '"' + input + '"').group(1);
print('Match: $match');
int number = int.parse(match);
print('Number: $number');

_totalPrice.remove(number);
_counter = _counter - number;}

A: Assuming you can answer 'yes' to the questions in my above comment, you can simply use regular expressions to find the price value in your string:
final regEx = RegExp(r'\$\d+(?:\.\d+)?');
const textToSearch = r'William\nWilliam description here...\n$170.00 cm';
final priceValueMatch = regEx.firstMatch(textToSearch);
print(priceValueMatch.group(0)); // this will print $170.00

The regular expression is looking for a dollar sign \$ followed by 1 or more digits d+ followed by optional decimal point and optional digits behind that decimal (?:\.\d+)?.
This actually ignores a lot of the questions in my above comment.  This simply looks for a price value preceded by a dollar sign within the string you give it.
Here is another approach based on your comments.  This is assuming the new line characters will always exist
const textToSearch = 'William\nWilliam description here...\n170.00 cm';
final lines = textToSearch.split('\n'); // Split on new line character
// If your template is always the same,
// then your number will be at the start of line 3:
print(lines[2]); // Will print: 170.00 cm
// If you want just your 170 value then:
final regEx = RegExp(r'\d+');
final priceValueMatch = regEx.firstMatch(lines[2]);
final priceInt = int.parse(priceValueMatch.group(0));
print(priceInt); // Will print: 170


text:
Q: Does django set_cookie method encrypts the cookie value? That's what I want to know. If I have to encrypt the cookie value manually or if the method does it automatically.
Thanks!

A: For cookies, you likely care more about signing (can someone modify or forge data) than encryption ( can someone read it).
That said, according to this documentation if you use cookie based sessions, django does support it since version 1.4


text:
Q: Can't resolve BitBucket git conflict I'm trying to merge development into master, but I'm getting merge conflicts.
Merge pull request
 Bitbucket cannot automatically merge this request due to conflicts.

Review the conflicts on the Overview tab. You can then either decline the request or merge it manually on your local system using the following commands:

git checkout master
git merge --no-ff -m 'Merged in development (pull request #85)' remotes/origin/development

Bitbucket tells me I should checkout master locally, and resolve the conflicts. But if I do that there are no merge conflicts to fix. Furthermore it tells me Master is up to date.
How do I solve this?

A: You can merge master into dev locally, then fix conflicts. And after that push dev branch. If you do these, you won't face conflict on BitBocket

A: Try this:
(I assume the name of the development branch is dev, replace it with the actual name)

*

*git merge --abort

*git fetch origin

*git checkout master

*git merge origin/master # merges latest changes from origin to the local master

*Fix conflicts if any then git add . ;  git commit # fix conflicts if any and commit the merge

*git checkout dev # switch to the dev (replace to actual the branch name) branch

*git merge origin/dev # merge the latest changes from the remote dev branch to the local dev branch, fix conflicts if any

*git merge master # merge master into dev, fix conflicts if any

*git push origin HEAD:dev
The merge conflicts from the PR should be gone


text:
Q: Why is it wrong to say "an ancient Athenian neighborhood settled on the fourth century BC."
While diging the foundation, builders discovered the remains of an ancient Athenian neighborhood ____ the fourth century BC.  ( An ACT exam question)

why can't I insert "settled on" as an post-modifer to the sentence? I don't think there is any syntactical errors.

A: It doesn't make sense for at least two reasons:

*

*A 'neighbourhood' is an area or district. An area can't move, so how can it settle somewhere?

*The fourth century BC isn't a place, it is a time. How can something settle in a time?
My guess would be the answer is "from". You can say something is 'from' a time.


text:
Q: Need explanation on the solution of a combinatorics problem involving squares with parallel sides Let a finite number of squares with parallel sides in the plane, such that if any $k+1$ squares are chosen, then there exist $2$ intersecting squares among them. Prove that the squares can be grouped into $2k-1$ sets such that any two squares in the same set intersect.
I found this problem on AOPS, but I couldn't understand the solution.
https://artofproblemsolving.com/community/q1h1805602p12209708
This is the link. I couldn't understand properly why "Squares that do intersect with $ABCD$ either contains point $B$ or point $C$ or both." (as it is written in the last comment to the post). Can you please enlighten me? Or if the problem is wrong, could you please help me with a counterexample? Thank you so much!
Need counterexample on a combinatorics problem

A: There is the additional assumption in the question as posed on AoPS that the squares are all congruent; without loss of generality we may take the side length as $1$. $ABCD$ is, in the solution provided there, (one of) the leftmost squares in the collection; say that its lower-left corner has coordinates $(x,y)$. Then any square $S$ intersecting $ABCD$ must have lower-left corner $(u,v)$ where $x\le u\le x+1$ (since $ABCD$ is the leftmost square) and $y-1\le v\le y+1$.
It is easy to show that if $y-1\le v\le y$ then $S$ contains $C$; if $y\le v\le y+1$ then $S$ contains $B$. Thus $S$ will always contain at least one of $B$ and $C$.


text:
Q: How to work with Magento staging env? I need to prepare content and when the time is coming schedule merge on the main website. I think that I can use staging env for this purpose. But it's seems not working or I'm doing something wrong.
I'm creating new cms page on staging, I change setting at BO for staging to show this page as home page. After it I go to staging and plan merge. After merge I expect that created cms page will be home page. But nothing happens. What I'm doing wrong? How to make created cms page on staging home page on live?

A: this is an enterprise feature.
Maybe this helps: https://github.com/magento-hackathon/firegento-contentsync
It is a module to sync a lot of stuff, e.g. cms pages and blocks


text:
Q: NSManagedObjectContext giving an error asking for a ";" and I'm not sure why When in Xcode 5 I am using the code below, which is in the @interface area, to get data from my CoreData model. It is telling me that I should insert a semi-colon here,
- (NSManagedObjectContext *)managedObjectContext;

Any help is appreciated!
Below is my full code block.
//Get Data
- (NSManagedObjectContext *)managedObjectContext{
        NSManagedObjectContext *context = nil;
        id delegate = [[UIApplication sharedApplication] delegate];
        if ([delegate performSelector:@selector(managedObjectContext)]) {
            context = [delegate managedObjectContext];
        }
        return context;
    }

A:
When in Xcode 5 I am using the code below, which is in the @interface area, to get data from my CoreData model.

This is you problem, you're only supposed to but declarations in the @interface. Actual implementations go in the @implementation section.
Your interface goes
@interface
- (NSManagedObjectContext *)managedObjectContext;
@end

In you implementation you put the actual method:

@implementation
...
//Get Data
- (NSManagedObjectContext *)managedObjectContext{
        NSManagedObjectContext *context = nil;
        id delegate = [[UIApplication sharedApplication] delegate];
        if ([delegate respondsToSelector:@selector(managedObjectContext)]) {
            context = [delegate managedObjectContext];
        }
        return context;
    }
...
@end

UPDATE:
Thanks to Abizern for noticing that there was another bug in your code: the line [delegate performSelector:@selector(managedObjectContext)] should actually be [delegate respondsToSelector:@selector(managedObjectContext)], because otherwise the application will crash if it doesn't respond to the selector.

A: you have weird getter in my opinion, try ti use something like this one
- (NSManagedObjectContext *)managedObjectContext {

     if (_managedObjectContext != nil)
     {
         return _managedObjectContext;
     }

     NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
     if (coordinator != nil)
     {
         _managedObjectContext = [[NSManagedObjectContext alloc] init];
         [_managedObjectContext setPersistentStoreCoordinator:coordinator];
     }
     return _managedObjectContext;
}


text:
Q: Resample time series using Polars in Rust I'm trying to learn rust by doing some data parsing and re-work some of my trading tools but got stuck pretty quick.
I want to resample my data from 5 min to 15 min and Polars seems to be able to do this in an optimized way.
This is my try so far. I manage to group the times from 5 min into 15 min but I cannot wrap my head around how to apply this grouping to the other columns.
use polars::prelude::*;
use std::error::Error;

fn type_of<T>(_: T) {
    println!("--- DATA TYPE: {}", std::any::type_name::<T>());
}

fn main() -> Result<(), Box<dyn Error>> {
    let path = "path/to/.csv";
    let df = LazyCsvReader::new(path)
        .has_header(true)
        .with_parse_dates(true)
        .finish()?
        .fetch(20)?;

let tt = df.groupby_dynamic(
        vec![df.column("close")?.clone()],
        &DynamicGroupOptions {
            index_column: "time".into(),
            every: Duration::parse("15m"),
            period: Duration::parse("5m"),
            offset: Duration::parse("0s"),
            truncate: true,
            include_boundaries: false,
            closed_window: ClosedWindow::Left,
        },
    )?;

    //type_of(&tt);
    println!("{:?}", tt);

}

OUTPUT
Series: 'time' [datetime[μs]]
[
        2019-09-03 09:00:00
        2019-09-03 09:15:00
        2019-09-03 09:30:00
        2019-09-03 09:45:00
        2019-09-03 10:00:00
        2019-09-03 10:15:00
        2019-09-03 10:30:00
        2019-09-03 10:45:00
        2019-09-03 11:00:00
], [], Slice { groups: [[0, 1], [1, 1], [1, 4], [4, 4], [7, 4], [10, 4], [13, 4], [16, 4], [19, 1]], rolling: false })

As soon as i try to add a series I want to group in the "by" field (first argument in groupby_dynamic) no resampling is taking part, I only get the same series as the put it.
The function outputs a Slice { groups: ..." which is of type polars_core::frame::groupby::proxy::GroupsProxy
But I don't know how I should handle it.
My cargo.toml:
[dependencies]
polars = { version = "0.25.1", features = ["lazy"] }

My .csv-file:
time,open,high,low,close,volume
2019-09-03 09:00:00,1183.9999,1183.9999,1183.9999,1183.9999,150
2019-09-03 09:30:00,1178.69,1180.69,1178.47,1178.47,5180
2019-09-03 09:35:00,1177.03,1180.6146,1176.0,1179.47,70575
2019-09-03 09:40:00,1180.6345,1186.89,1180.6345,1185.5141,37267
2019-09-03 09:45:00,1185.9,1186.43,1182.43,1182.47,20569
2019-09-03 09:50:00,1183.54,1184.0,1180.0,1181.96,20754
2019-09-03 09:55:00,1182.5,1186.0,1182.49,1184.83,20848
2019-09-03 10:00:00,1185.5,1185.59,1184.03,1185.145,18581
2019-09-03 10:05:00,1184.65,1184.65,1175.5,1175.86,27714
2019-09-03 10:10:00,1175.49,1176.5,1173.65,1175.47,21779
2019-09-03 10:15:00,1175.295,1177.42,1173.5,1173.68,13588
2019-09-03 10:20:00,1173.01,1176.3717,1173.01,1175.44,9853
2019-09-03 10:25:00,1175.7896,1178.985,1175.7896,1177.468,7866
2019-09-03 10:30:00,1178.05,1179.0,1176.0038,1178.72,11576
2019-09-03 10:35:00,1179.005,1179.005,1176.53,1177.0077,9275
2019-09-03 10:40:00,1177.18,1178.02,1176.0201,1178.02,8852
2019-09-03 10:45:00,1178.3,1182.5,1178.3,1181.7113,14703
2019-09-03 10:50:00,1181.74,1181.9952,1180.01,1181.738,10225
2019-09-03 10:55:00,1182.11,1183.428,1181.33,1183.428,7835
2019-09-03 11:00:00,1183.41,1184.665,1183.41,1184.24,9078

The next thing would be to get the first,last,max,min out of the "closed" columns (yes, i'm trying to get OHLC candles).
Happy for any help!

A: Finally, I solved it!
I had not used the Lazy-API correctly. I had and somehow used some other implementation of group_dynamic, I guess it is used for the inner workings of Polars or something. The main point was that I forgot .lazy()
However, this is how I solved it:
use polars::prelude::*;
use std::error::Error;

fn type_of<T>(_: T) {
    println!("--- DATA TYPE: {}", std::any::type_name::<T>());
}

fn main() -> Result<(), Box<dyn Error>> {
    let path = "/home/niklas/projects/ML-trader/Datasets/Raw/GOOG.csv";
    let df = LazyCsvReader::new(path)
        .has_header(true)
        .with_parse_dates(true)
        .finish()?
        .collect()?;

    type_of(&df);
    // println!("{}", &df["close"]);

    let tt = df
        .lazy()
        .groupby_dynamic(
            vec![],
            DynamicGroupOptions {
                index_column: "time".into(),
                every: Duration::parse("15m"),
                period: Duration::parse("15m"),
                offset: Duration::parse("0s"),
                truncate: false,
                include_boundaries: false,
                closed_window: ClosedWindow::Left,
            },
        )
        .agg([
            col("close").first().alias("firstClose"),
            col("close").last().alias("lastClose"),
            col("close"),
        ])
        .fetch(20);

    println!("{:?}", tt);

    Ok(())
}

OUTPUT
--- DATA TYPE: &polars_core::frame::DataFrame
--- DATA TYPE: &core::result::Result<polars_core::frame::DataFrame, polars_core::error::PolarsError>
Ok(shape: (8, 4)
┌─────────────────────┬────────────┬───────────┬─────────────────────────────────┐
│ time                ┆ firstClose ┆ lastClose ┆ close                           │
│ ---                 ┆ ---        ┆ ---       ┆ ---                             │
│ datetime[μs]        ┆ f64        ┆ f64       ┆ list[f64]                       │
╞═════════════════════╪════════════╪═══════════╪═════════════════════════════════╡
│ 2019-09-03 09:00:00 ┆ 1183.9999  ┆ 1183.9999 ┆ [1183.9999]                     │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2019-09-03 09:30:00 ┆ 1178.47    ┆ 1185.5141 ┆ [1178.47, 1179.47, 1185.5141]   │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2019-09-03 09:45:00 ┆ 1182.47    ┆ 1184.83   ┆ [1182.47, 1181.96, 1184.83]     │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2019-09-03 10:00:00 ┆ 1185.145   ┆ 1175.47   ┆ [1185.145, 1175.86, 1175.47]    │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2019-09-03 10:15:00 ┆ 1173.68    ┆ 1177.468  ┆ [1173.68, 1175.44, 1177.468]    │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2019-09-03 10:30:00 ┆ 1178.72    ┆ 1178.02   ┆ [1178.72, 1177.0077, 1178.02]   │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2019-09-03 10:45:00 ┆ 1181.7113  ┆ 1183.428  ┆ [1181.7113, 1181.738, 1183.428] │
├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌┼╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌┤
│ 2019-09-03 11:00:00 ┆ 1184.24    ┆ 1184.24   ┆ [1184.24]                       │
└─────────────────────┴────────────┴───────────┴─────────────────────────────────┘)

my .toml
[dependencies]
polars = { version = "0.25.1", features = ["lazy", "dynamic_groupby"] }

Thank y'all for coming to my ted talk!


text:
Q: What's the best way to find the getters of a class I have a for (Field field : CLASS.getDeclaredFields())
And i want to find if every field in the CLASS have a getter method that returns its value
So i use inside that loop:
List<Field> FieldGettersNotFound = new ArrayList<>();

for (PropertyDescriptor descriptor : Introspector.getBeanInfo(CLASS).getPropertyDescriptors()){

                //Check for getters

                if (descriptor.getReadMethod() != null){

                    if (!( descriptor.getReadMethod().getParameters().length == 0 &&
                            descriptor.getReadMethod().getReturnType().equals(field.getType()))){

                        if (!FieldGettersNotFound.contains(field)) FieldGettersNotFound.add(field);

                    }

                    else {

                        FieldGettersNotFound.remove(field);
                        break;

                    }

                }

            }

if (FieldGettersNotFound.size()>0) throw an Exception;

Its seems fine but when it gets in a situation like this, no exception is thrown
because the program is double checking the getName();
public class RandomSituation {

private String Name;
private String LastName;

public String getName(){

    return Name;

}

}

One way of solving this problem is:
(its all the same i just added 1 if in the else)
for (PropertyDescriptor descriptor : Introspector.getBeanInfo(CLASS).getPropertyDescriptors()){

                //Check for getters

                if (descriptor.getReadMethod() != null){

                    if (!( descriptor.getReadMethod().getParameters().length == 0 &&
                            descriptor.getReadMethod().getReturnType().equals(field.getType()))){

                        if (!FieldGettersNotFound.contains(field)) FieldGettersNotFound.add(field);

                    }

                    else {

                        if (descriptor.getReadMethod().getName().equals("get"+field.getName()){

                        FieldGettersNotFound.remove(field);
                        break;

                      }

                    }

                }

            }

But some psychopaths may call their method returnName() or something like this
Is there any better way of checking if a class have a getter method for all its fields?

A: Well the solution was very simple ...
I just created a List<Method> Getters = new ArrayList<>(); that keeps track of every method i have checked
for (PropertyDescriptor descriptor : Introspector.getBeanInfo(CLASS).getPropertyDescriptors()){

                //Check for getters

                if (descriptor.getReadMethod() != null && !Getters.contains(descriptor.getReadMethod())){

                    if (!( descriptor.getReadMethod().getParameters().length == 0 &&
                            descriptor.getReadMethod().getReturnType().equals(field.getType()))){

                        if (!FieldGettersNotFound.contains(field)) FieldGettersNotFound.add(field);

                    }

                    else {

                        FieldGettersNotFound.remove(field);
                        Getters.add(descriptor.getReadMethod());
                        break;

                    }

                }

            }


text:
Q: attach derby database into jar file I am midway through a database application(SWING). I am using Java DB and NetBeans 7.1.2. Within the IDE, the app runs good, provided I initially connect the database manually in the 'services' window. Also, I have added the derby.jar and derbyclient.jar files to the libraries. But when running the app from the "dist" folder, it fails to connect to the database. I want to know whether i can attach the db within the jar file so that i can run the app from outside the IDE. Thank you.

A: You can do the following

*

*Start java DB outside the netbeans or

*If you use Derby, go with Embedded mode. Such a way you can run your application without separate db server.


text:
Q: Detecting Angular Velocity in a React-Native mobile application I'm hoping to make a feature in a mobile application which detects how fast the user is spinning their phone and which direction. I believe this is angular velocity, but please correct me if I'm wrong.
For what it's worth, I'm experimenting with this idea using react-native (create-react-native-app) with the help of Expo dev tools, and the Expo accelerometer API.
https://docs.expo.io/versions/v15.0.0/sdk/accelerometer.html
My question is perhaps more fundamental though.
Can I reliably detect the speed at which the phone is rotating, and which direction? And would any code solution that I write provide consistent values across different mobile devices, or vary wildly?
Then, if it is a plausible feat, how would I determine such a value? Would I compare value from millisecond to millisecond, and if so, which values?
Thanks for helping me get my head around this.

A: While I'm still not certain what the correct term is, I've managed to attain the value that I'm looking for by making use of the gyroscope API and monitoring the 'Z-value'. Here is my working example. (Needs to be run with expo)
import React from 'react';
import Expo, {
  Gyroscope,
} from 'expo';

import { Text, TouchableOpacity, View } from 'react-native';

export default class Test extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      gyroscopeData: {
        x: 0,
        y: 0,
        z: 0
      },
    }
  }
  componentDidMount() {
    this._toggle();
  }

  componentWillUnmount() {
    this._unsubscribe();
  }

  _toggle = () => {
    if (this._subscription) {
      this._unsubscribe();
    } else {
      this._subscribe();
    }
  }
  _slow = () => {
    Gyroscope.setUpdateInterval(1000);
  }

  _fast = () => {
    Gyroscope.setUpdateInterval(16);
  }
  _subscribe = () => {
    this._subscription = Gyroscope.addListener((result) => {
      this.setState({gyroscopeData: result});
    });
  }

  _unsubscribe = () => {
    this._subscription && this._subscription.remove();
    this._subscription = null;
  }
  render() {
    let { x, y, z } = this.state.gyroscopeData;
    return (
      <View>
        {/*<Text> x: {round(x)}</Text>*/}
        {/*<Text> y: {round(y)}</Text>*/}
        <Text> z: {z}</Text>

        <View>
          <TouchableOpacity onPress={this._toggle}>
            <Text>Toggle</Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={this._slow}>
            <Text>Slow</Text>
          </TouchableOpacity>
          <TouchableOpacity onPress={this._fast}>
            <Text>Fast</Text>
          </TouchableOpacity>
        </View>
      </View>
    );
  }
}
function round(n) {
  if (!n) {
    return 0;
  }

  return Math.floor(n * 100) / 100;
}


text:
Q: Enqueue, Dequeue and ViewQueue in Java I am doing a queue in java. Here is my code:
public class ListQueue {
public static void main(String[] args){
    Queue myQueue;
    Scanner sc = new Scanner(System.in);
    String input;
    int choice = 99;
    do{
        System.out.println("================");
        System.out.println("Queue Operations Menu");
        System.out.println("================");
        System.out.println("1,Enquene");
        System.out.println("2,Dequeue");
        System.out.println("3,Empty?");
        System.out.println("4,Count?");
        System.out.println("5,View Queue");
        System.out.println("0, Quit\n");
        System.out.println("Enter Choice:");
        try{
            choice = sc.nextInt();
            switch(choice){
            case 1:
                System.out.println("Please enter name: ");
                input = sc.next();
                myQueue.enqueue(input);
                System.out.println(input + "is successful queued");
                break;
            case 2:
                if(myQueue.isEmpty()){

                }
                break;
            case 3:
                if(myQueue.isEmpty()){
                    System.out.println("Queue is empty");
                }else{
                    System.out.println("Queue is not empty");
                }
                break;
            case 4:
                System.out.println("Number of people is " + "the queue" + myQueue.size());
                break;
            case 5:
                if(!myQueue.isEmpty())
                    myQueue.viewQueue();
                else
                    System.out.println("Queue is empty");
                break;
            case 0:
                System.out.println("Good-bye");
                break;
            default:
                    System.out.println("Invalid choice");
            }
        }
        catch(InputMismatchException e){
            System.out.println("Please enter 1-5, 0 to quit");
            sc.nextLine();
        }
    }while(choice != 0);
}

}
However, I have error at the enqueue() and viewQueue() which I wonder why. Am I declare the queue in a wrong way? Thanks in advance. I am new to queue so please bear with me.

A: You have not initialized myQueue:
Queue myQueue;

Note that Queue is an abtract class,you need initialize myQueue to the appropriate implementation.
Refer below javaDoc:
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Queue.html

A: Java queues don't have enqueue and dequeue methods, these operations are done using the following methods:
Enqueuing:

*

*add(e): throws exception if it fails to insert the object

*offer(e): returns false if it fails to insert the object

Dequeuing:

*

*remove(): throws exception if the queue is empty

*poll(): returns null if the queue is empty

Take a look to the first object in the queue:

*

*element(): throws exception if the queue is empty

*peek(): returns null if the queue is empty

The add method, which Queue inherits from Collection, inserts an
  element unless it would violate the queue's capacity restrictions, in
  which case it throws IllegalStateException. The offer method, which is
  intended solely for use on bounded queues, differs from add only in
  that it indicates failure to insert an element by returning false.

(see: http://docs.oracle.com/javase/tutorial/collections/interfaces/queue.html)
You can also check this as this is more useful:
http://docs.oracle.com/cd/B10500_01/appdev.920/a96587/apexampl.htm

A: @By the way how do I loop thru the element inside queue? Can you post me some example –
I have just added functionality in your Case 5: which is for viewing the List elements.
case 5:
    if(!myQueue.isEmpty())
    {
    for(Iterator it=myQueue.iterator();it.hasNext();)
        System.out.println(it.next());
//or using as a Object in Enhanced for loop
        //for (Object element : myQueue)
        //System.out.println(element);
    }
    else
        System.out.println("Queue is empty");
    break;

And as Ryman Holmes suggested you can use ArayDeque.
Queue<String> myQueue = new ArrayDeque<String>();

Benefits:
 - It is faster than Stack and LinkedList
 - ArrayDeque have no capacity restrictions so they can grow as necessary to support usage.
Risk:
 - They are not thread-safe; in the absence of external synchronization.
 - They do not support concurrent access by multiple threads.

A: Like zerocool said you are not initializing the Queue, as Queue is an interface and you cannot instantiate an interface directly, you need to instantiate a class that implements the interface Queue such as ArrayDequeue, LinkedList etc...
To initialise the Queue and get rid of the errors you need something like this:
Queue<Integer> myQueue = new ArrayDeque<Integer>();

or
Queue<String> myQueue = new LinkedList<String>();

Here's the API for the type of Queues you can instantiate
Also see


text:
Q: Powershell sort two fields and and get latest from CSV I am trying to find a way to sort a CSV by two fields and retrieve only the latest item.
CSV fields: time, computer, type, domain.
Item that works is below but is slow due to scale of CSV and I feel like there is a better way.
$sorted = $csv | Group-Object {$_.computer} | ForEach {$_.Group | Sort-Object Time -Descending | Select-Object -First 1}

A: As Lee_Dailey suggests, you'll probably have better luck with a hashtable instead, Group-Object (unless used with the -NoElement parameter) is fairly slow and memory-hungry.
The fastest way off the top of my head would be something like this:
# use the call operator & instead of ForEach-Object to avoid overhead from pipeline parameter binding
$csv |&{
  begin{
    # create a hashtable to hold the newest object per computer
    $newest = @{}
  }
  process{
    # test if the object in the pipeline is newer that the one we have
    if(-not $newest.ContainsKey($_.Computer) -or $newest[$_.Computer].Time -lt $_.Time){
      # update our hashtable with the newest object
      $newest[$_.Computer] = $_
    }
  }
  end{
    # return the newest-per-computer object
    $newest.Values
  }
}


text:
Q: Why C program in whch two functions call each other recursively gives segmentation fault on linux? I am trying to compile the following C code on linux:
#include <stdio.h>
/////
void func1();
void func2();
//////
void func1()
{
  func2();
}
void func2()
{
  func1();
}
int main()
{
  func1();//call to function 1
}

If I am not wrong then the program should execute infintely but when i compile and run it on linux it gives Segmentation Fault.
Why is this happening?

A: Each nested function call consumes some stack space for the arguments and the return address. In your code the nested function calls are unbounded, so they consume an unbounded amount of stack. Once the stack is exhausted, the program goes on to write return addresses outside the memory allocated to the process and crashes.
Depending on the compiler, turning on optimizations might help because of tail call optimization.

A: Behaviour you are experiencing is called stack overflow. This means, the call stack contained too many items and it overflowed (there was no space left on it to continue execution), and the program crashed with SIGSEGV. There is no exit routine so it was inevitable that such thing would happen.


text:
Q: woocommerce products category order I have created a template and I'm using the code to show the product categories on a page:
<?php $wcatTerms = get_terms('product_cat', array('hide_empty' => 0, 'orderby' => 'ASC',  'parent' =>0)); //, 'exclude' => '17,77'
                foreach($wcatTerms as $wcatTerm) :
                    $wthumbnail_id = get_woocommerce_term_meta( $wcatTerm->term_id, 'thumbnail_id', true );
                    $wimage = wp_get_attachment_url( $wthumbnail_id );

When I change the order in the backend it won't change.
How can I hard-code the order or set it to order by id?

A: You confused orderby with order, they're 2 different arguments (see get_terms):
$wcatTerms = get_terms('product_cat', array(
    'hide_empty' => 0,
    'orderby'    => 'id',
    'order'      => 'ASC',
    'parent'     => 0
));

A: Actually you do not have to hardcode anything.
1- Just go under Appearance->Widgets
2- Under sidebar you added Woocommerce Product Categories expand "Woocommerce Product Categories"
3- At Order By dropdown box choose "Category Order" instead of name.
it should work now.


text:
Q: Fortify AWB Out of Memory Opening FPR File When opening an FPR file, Fortify AWB is running out of memory. The java process climbs to about 1150mb before it plateaus and then the error message is displayed. I have tried setting AWB_VM_OPTS and SCA_VM_OPTS to -Xmx4G but the amount of memory allocated doesn't seem to change.
What can be done to increase the amount of allocated memory?

A: When running SCA, the amount of physical RAM required is dependent on a number of factors. These factors, which include the size and complexity of the source file, make it impossible to quantify and provide guidance -- each situation is unique. If you do encounter a low memory error, increasing the amount of memory available to SCA may resolve the problem.
By default, SCA uses up to 600 MB of memory. If this is not sufficient to analyze a particular code base, you might have to provide more memory in the scan phase. This can be done by passing the -Xmx option to the sourceanalyzer command.
For example, to make 1000 MB available to SCA, include the option -Xmx1000M.
You can also use the SCA_VM_OPTS environment variable to set the memory allocation.
Do not allocate more memory for SCA than the machine has available, because this will degrade performance. As a guideline, assuming that no other memory-intensive processes are running, do not allocate more than 2/3 of the available physical memory.
If memory problems persist, set the Windows paging file to a fixed amount of about 1.5 times the amount of hardware RAM on your computer. Go to System Properties, Select Performance Settings. Then under the Advanced tab, note the "Total paging file size for all drives."  That amount should match the amount of hardware RAM in your computer. Push the Change button; un-check "Automatically manage paging file size for all drives." Select the "Custom size" option and enter a value 1.5 times the size of RAM in your computer as the "Initial size" and the "Maximum size."

A: We got around this problem by opening the file C:\Program Files\Fortify\Fortify_SCA_and_Apps_20.1.0\bin\auditworkbench.cmd and adding this to the end of the "call" command:
-Xmx10G -64

So, afterwards, our line looks like this:
call "%~dp0\..\Core\private-bin\awb\productlaunch.cmd" -showSplash platform:/base/plugins/com.fortify.awb.app/splash.bmp -application com.fortify.awb.app.Main -product com.fortify.awb.app.MainProduct "-Dosgi.splashPath=platform:/base/plugins/com.fortify.awb.app" %* -Xmx10G -64

A: After confirming that AWB_VM_OPTS was the value I wanted to change, I decided to create a short script that set the value and then called the AWB bat file that starts the application. Previously I was setting AWB_VM_OPTS manually in the command prompt. I set the value to 4096M instead of 4G and it worked fine.

A: C:\Program Files\Fortify\Fortify_SCA_and_Apps_18.20\Core\config\fortify.properties
com.fortify.model.ExecMemorySetting=5460M
C:\Program Files\Fortify\Fortify_SCA_and_Apps_18.20\bin\auditworkbench.cmd
set SCA_VM_OPTS=-Xmx5460M

A: The best solution for this is to not edit environmental variables. If you have done this delete it and follow these steps. NOTE This is for SCA 20.2+

*

*Navigate to: C:\Forityscainstallpath\Core\private-bin\awb

*Open productlaunch.cmd in a text editor such as Notepad++

*Scroll to the bottom which is line 56 for me and update the following line. Where I have Xmx12g input your preference. NOTE: It took me a few tries to get it right.

start "Fortify" /B /MIN "%FORTIFY_CORE%\private-bin\awb\eclipse\eclipse.exe" -vm "%JAVA_CMD%" -startup "%FORTIFY_CORE%\lib\awb-startup-20.2.2.0003.jar" -os win32 -ws win32 -arch x86_64 %USER_OPTS% %AWB_ARGS% -vmargs -Xmx12G -XX:-UseCompressedOops %AWB_VM_OPTS% %USER_VM_OPTS% -Dcom.fortify.InstallRoot="%FORTIFY_HOME%" >NUL

*Save the file

*Close and retry

*Increase memory until it works, but do not exceed available memory.


text:
Q: TestCafe Element is Visible but cannot be clicked I'm running TestCafe in an Alpine docker image using Chromium 68 headless to test a React application. I'm able to get other tests working, but for some reason, I have an issue where an element appears to be visible but cannot be clicked.
.expect(Selector('.ui.text.vertical.marketplace-side-nav.menu').find('a').withText('Pending').visible).ok()
.click(Selector('.ui.text.vertical.marketplace-side-nav.menu').find('a').withText('Pending'))

The first line passes, but the second line gives the following error:
1) The element that matches the specified selector is not visible.
I've tried setting up the test on TestCafe Studio and tried multiple selectors. I've set .resizeWindow(2000, 1000) at the beginning to ensure it's not an issue with responsive UX.
Edit
The Dockerfile has a bit of other dev stuff, but is fairly straight-forward.
The project itself is proprietary so I can't share the code here.

A: As per the author's comment:
Final result if anyone else is stuck: Older version of Alpine Docker image was installing Chromium 57 (I had v68 elsewhere and ran the build to confirm). Upgrading Alpine and Chromium (now at 61+) fixed a lot of issues, and now emulation (and in turn resize) works as well.


text:
Q: Table Controller - Azure Mobile Services .Net backend not returning I have an Azure Mobile Service with .Net backend with a table controller on the service side.
I can query the table on the service webpage (the default "try it" pages) and get the table data back but in my Windows Phone client it gets stuck on the statement.
ContactTable = AzureClient.GetTable<Contact>();
var res = await ContactTable.Select(c => c.Owner == _userId).ToCollectionAsync();
obj = res; // It never gets to this line

Contact definition (the same as the service side):
    [DataContract]
    public class Contact
    {
    public Contact()
    {
        ImageTags = new HashSet<ImageTag>();
    }

    [DataMember]
    public long Id { get; set; }

    [DataMember]
    public long Owner { get; set; }

    [DataMember]
    public string Name { get; set; }

    public virtual ICollection<ImageTag> ImageTags { get; set; }
}

Does anyone know a solution?


text:
Q: plotting a MeijerG function I'm trying to plot the following function on Wolfram Mathematica, but I get nothing on the graph! Why is that? Does anyone know why?
Plot[{1 - ((1/(Gamma[2])^4)*Sum[((4/y)^(-i - 1)*
(1/(i!*1.6^i)))*MeijerG[{{1.08 - i, -1.1 - i, -1 - i}, {}}, {{0, 2.1,2},
{}}, {2}], {i, 0, 5}])},{y, 0, 10}, PlotRange -> {{0, 3}, {0, .1}}]

A: You have curly braces where they shouldn't be, making the output of the function a nested list that Mathematica doesn't know how to plot. Furthermore, that plot range isn't going to work.  Do this:
f[y_] = 1 - ((1/(Gamma[2])^4)*Sum[((4/y)^(-i - 1)*(1/(i!*1.6^i)))*MeijerG[{{1.08 - i, -1.1 - i, -1 - i}, {}}, {{0, 2.1, 2}, {}}, 2], {i, 0, 5}];
Plot[f[y], {y, 0, 10}]


text:
Q: Blazor Server - Session advice I have a Blazor Server app.  I would like store some data in a Session.  I am trying to create a Session Helper class where I store the Session Names as Enums so they are always strongly typed.  Also in this class I would like to put the Get and Set.  So I dont need to do lots of Injecting everywhere.  The session Value could be a string, object. list etc... I started to create below class but came across a few issues:

*

*Can I create the below into static methods so I dont have new the SessionManager object everytime

*How do I get the Get to return any type of object.  I think I need to make it generic some how.

Any help would be much appreciated
TIA
    using Microsoft.AspNetCore.Components;
    using Microsoft.AspNetCore.Components.Server.ProtectedBrowserStorage;
    using System.Threading.Tasks;

    namespace Core
    {
        public class SessionManager
        {
            [Inject] ProtectedSessionStorage storage { get; set; }

            public enum eSessionNames
            {
                UserName,
                UserRow
            }

            public async Task SetSession(eSessionNames SessionName, object Value)
            {
                await storage.SetAsync(SessionName.ToString(), Value);
            }

            public async Task<T> GetSession(eSessionNames SessionName)
            {
                return await storage.GetAsync<T>(SessionName.ToString());
            }
        }
    }

MY DAL trying to use your method

        public async static Task<Models.myModel> GetUserFromProtectedBrowserStorageAsync(string UserNetworkID)
        {
            using (var connection = new SqlConnection(Core.ConnectionStringManager.GetConnectionString()))
            {
                await connection.OpenAsync();

                MyBlogProtectedBrowserStorage pbs = new();  //I get an error on this line as im not sure how to new the object

                Models.myModel output = await pbs.GetAsync<Models.myModel>("UserRow");

                if (output == null)
                {
                    var values = new { UserNetworkID };

                    output await connection.QuerySingleAsync<CsatUserModel>("SELECT * FROM tblUsers WHERE NetworkID = @UserNetworkID", values, commandType: CommandType.Text);

                    pbs.SetAsync<Models.myModel>("UserRow", output);

                    return output;
                }
                else
                {
                    return output;
                }
            }
        }

A: The concept of session doesn't really exist in Blazor Server at least not in the traditional meaning.
You can use ProtectedSessionStorage ad you do or you can use dependency injection and inject a class that is scoped. This will make the class accessible while you have a connection (Circuit), if the connection fails for some reason the scoped class will disappear as well.
To answer your questions:

*

*Don't use static methods inject the Sessionmanager into your component and/or classes instead. This makes it easier to see dependencies and write tests.

*Here is an example:

public class MyBlogProtectedBrowserStorage
{
    ProtectedSessionStorage storage { get; set; }
    public MyBlogProtectedBrowserStorage(ProtectedSessionStorage storage)
    {
        this.storage = storage;
    }

    public async Task DeleteAsync(string key)
    {
        await storage.DeleteAsync(key);
    }

    public async Task<T?> GetAsync<T>(string key)
    {
        var value = await storage.GetAsync<T>(key);
        if (value.Success)
        {
            return value.Value;
        }
        else
        {
            return default(T);
        }
    }

    public async Task SetAsync(string key, object value)
    {
        await storage.SetAsync(key, value);
    }
}

A: You don't need to use protected session storage in Blazor server since Blazor sever can maintain the app session state on the server side.
For your purpose, I suggest you use IMemoryCache. It's simple to use and works with all types of classes.
https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-6.0


text:
Q: Jedis - Missing HostPort class for simple program I'm viewing RedisLab first course for Java developer,
In Hello World program they are using HostPort which isn't found in jedis:
Jedis jedis = new Jedis(HostPort.getRedisHost(), HostPort.getRedisPort());

What is HostPort class and why I can't find it?
There's HostAndPort, but it doesn't have those methods or similar getPort static methods

A: in the code you have a constructor to input these values
 public HostAndPort(String host, int port)

for the example, I guess you can use localhost and port 6379 that is the common port for redis
in the code example of redislabs you have the class:
package com.redislabs.university.RU102J;

public class HostPort {

final private static String defaultHost = "localhost";

final private static Integer defaultPort = 6379;

static {
}

public static String getRedisHost() {
    return defaultHost;
}

public static Integer getRedisPort() {
    return defaultPort;
}
}

make sure you downloaded the code source


text:
Q: renaming column names with variable I want to rename a specific column with new name which comes as a variable in dplyr.
newName = paste0('nameY', 2017)

What I tried was
iris %>%
    rename(newName = Petal.Length) %>%
    head(2)

Which gives
Sepal.Length Sepal.Width newName Petal.Width Species
         5.1         3.5     1.4         0.2  setosa
         4.9         3.0     1.4         0.2  setosa

I am getting newName not nameY2017 which is normal. So I tried
iris %>%
    rename_(eval(newName) = 'Petal.Length')

But then I am getting an error.

Error: unexpected '=' in "iris %>% rename_(eval(newName) ="

Is there a proper way to do it with dplyr?
I know I can do something like
names(iris)[3] <- newName

But that wouldn't be dplyr solution.

A: Credit and further information in this post for this dplyr 'rename' standard evaluation function not working as expected?
Your code:
newName = paste0('nameY', 2017)
iris %>%
  rename(newName = Petal.Length) %>%
  head(2)

Solution:
iris %>%
  rename_(.dots = setNames("Petal.Length",newName)) %>%
  head(2)

Output:
  Sepal.Length Sepal.Width nameY2017 Petal.Width Species
1          5.1         3.5       1.4         0.2  setosa
2          4.9         3.0       1.4         0.2  setosa


text:
Q: How to upload document versions with keywords/metadata/etc changes included? The situation is as follows: there is a document on two sites - on site A in versions 1-20 and on site B there are versions 20 - 27. Users are working only on the document located on site B - changing content, title, adding/removing keywords and metadata etc.
I would like to merge these copies so that I have only one copy with versions 1-27 as a result. I wrote some PowerShell scripts that allow me to download all the versions from site B as separate files and add them to the document on site A but I am missing the whole keywords and metadata history. I mean - for example - someone added a keyword in version 25 but in the result file, that I get when using my scripts, there is no indication of that action below version 25 in "Show history".
Is it possible to "move" all the actions performed during version change along with the proper files so that they are visible in "Show history" in right place?

A: As long as the documents whose versions I try to merge are Office 2010 documents, all the necessary metadata is stored inside the documents (vide How is metadata stored?).
So when I upload each version, every change made to that version is automatically applied to the version history.


text:
Q: Creating a batch script which allows to create specific folders given by the user I would like to create a batch script which allows to create number and name of folder chosen by the user.
However, I received a syntax error using the script below.

variable "nome" is not taken.

Here is my code:
echo How many folders?
set /p  cc=tell me how many
SETLOCAL EnableDelayedExpansion
FOR /L %%G IN (1,1,%cc%) DO (set /p nome=tell me the name
md %nome%)
pause

A: mr xyz, please use the search bar to search for delayed expansion. It's not that hard.

What Is DelayedExpansion
Batch-file variables are expanding in the moment the line is parsed. That means the nome variable isn't set when the entire for loop is parsed.

How-To Make The Variable Expand At Run-time?
SETLOCAL Method
Add
setlocal enableDelayedExpansion

anywhere before the for loop, so cmd will process the variable at run-time. And change %nome% to !nome!.

CALL MKDIR/MD Method
Change your MD statement to:
call MD %%nome%%

As this will trigger the emulated delayed expansion using the special property of call and %%.


text:
Q: How to stop thermal printer after printing data I have a thermal receipt printer. I am using javascript to print a div it's printing everything correctly apart from that it keeps printing whole roll(blank) after printing data in the start. I think the problem is in the CSS but I can't figure it out. Here is what I have got so far.
@media print {
html, body {
    border: 1px solid white;
    height: auto !important;
    page-break-after: always !important;
    page-break-before: always !important;
 }

.paper-size {
    width: 76mm !important;
}}


text:
Q: Rails Caching - XML Files? My Rails application is running on a VM. The VM's performance is just fine with static pages. In fact, I'm running another site using Apache virtual hosting that is just serving up static HTML files and the response is adequate. However, my Rails application that is dynamically generating XML files responds very slowly. In fact, it takes about 10 seconds or so for each XML file. These XML files that Rails generates do not change more than once a day.
What is the best practice to configure these XML files to be cached?
Edit 1:
I should mention that these XML files are not viewed by a browser. They are viewed by mobile applications in the "field." So, unfortunately sending "HTTP/1.0 304 not modified" won't work.
Edit 2:
If it matters, I'm using Phusion Passenger to host my Rails app.

A: If you're using rails' static page caching and serving through apache, just using an explicit xml extension on the urls would do it.
if you're only serving xml and no html you might also edit the apache conf to default to xml instead of html when looking for cached files.
cache expiry is a rather boring thing to code and test, but since you're seldom regenerating the files, you might just expire the entire cache.

Here's a trimmed selection of files and excerpts from how I handle cache in a small, seldom updated rails site:
In the controllers you want to cache
class XmlThingController < ApplicationController
  caches_page :index, :show, :other_actions

In the controllers/actions that modify data that would cause changes to the xmls:
class Admin::SomeCrudController < AppplicationController
  cache_sweeper :stupid_master_sweeper, :only => [ :save, :destroy ]

In 'config/environments/production.rb'
config.action_controller.page_cache_directory =
  File.join(RAILS_ROOT, 'public', 'cache')

Somehere in your vhost apache conf:
# 1.4. Handle caching

# 1.4.1. prevent direct cache access
RewriteRule  ^/cache - [F,L]

# 1.4.2. for index
RewriteCond  %{DOCUMENT_ROOT}/cache/index.html -f
RewriteRule  ^/?$ /cache/index.html [L]

# 1.4.3. for explicitly specified extensions
RewriteCond  %{DOCUMENT_ROOT}/cache%{REQUEST_URI} -f
RewriteRule  ^(.*)$ /cache$1 [L]

# 1.4.4. with html extension implied
RewriteCond  %{DOCUMENT_ROOT}/cache%{REQUEST_URI}.html -f
RewriteRule  ^(.*)$ /cache$1.html [L]

# 1.5. Finally, proxy everything else to mongrel
RewriteCond  %{DOCUMENT_ROOT}/%{REQUEST_FILENAME} !-f
RewriteRule  ^/(.*)$ balancer://your-website-proxy%{REQUEST_URI} [P,QSA,L]

The dumb sweeper that cleans that entire cache every time it's triggered:
class StupidMasterSweeper < ActiveRecord::Observer
  observe Foo, Bar # All models that affect caching here

  def after_save(record); end
  def after_destroy(record); end

  def filter(controller)
    # sweep everything.
    `cd #{RAILS_ROOT} && RAILS_ENV=#{ENV['RAILS_ENV']} rake cache:clear`
  end
end

lib/tasks/cache.rake
namespace :cache do

  desc "Remove all cached files"
  task :clear do
    puts `rm -rf #{RAILS_ROOT}/public/cache/*`
  end

end

If you prefer to default the default implied extension to xml, change the extension on the 1.4.2 index rule, and the following:
# 1.4.4. with html extension implied
RewriteCond  %{DOCUMENT_ROOT}/cache%{REQUEST_URI}.html -f
RewriteRule  ^(.*)$ /cache$1.html [L]

to:
# 1.4.4. with xml extension implied
RewriteCond  %{DOCUMENT_ROOT}/cache%{REQUEST_URI}.xml -f
RewriteRule  ^(.*)$ /cache$1.xml [L]

A: Send a "HTTP/1.0 304 not modified" HTTP status code to the client when the XML document is requested.


text:
Q: How to add my condition on concatenated query SQL Server I want to add my dynamic condition on my SQL Server query but found that I should use concatenated query.
I'm new on concatenated query. Here's below query I tried but having error incorrect systax.
DECLARE @value VARCHAR(500) = ' and ID IN (1,2)';
DECLARE @sql VARCHAR(MAX);

SET @sql = '
DECLARE @table TABLE
(
    ID INT,
    Amount INT,
    Name VARCHAR(500)
);

DELETE FROM @table
INSERT INTO @table
(
    ID,
    Amount,
    Name
)
VALUES
(1, 200, ''ab''),
(2, 300, ''ab''),
(3, -150, ''ac''),
(4, 200, ''ab'');

select SUM(Amount)
from @table
where name = ''ab'' ''' + @value + ''';';
EXEC (@sql);

What is the proper way adding condition query variable on my concatenated query.

A: You can remove extra quotes :
where name = ''ab'' ' + @value + ';';

A: Problems with your code:

*

*missing semi-column at the end of the delete statement

*extract quote after the where name = ''ab'' and at the end of the code

This should work:
DECLARE @value VARCHAR(500) = ' and ID IN (1,2)';
DECLARE @sql VARCHAR(MAX);

SET @sql = '
DECLARE @table TABLE
(
    ID INT,
    Amount INT,
    Name VARCHAR(500)
);

DELETE FROM @table;
INSERT INTO @table
(
    ID,
    Amount,
    Name
)
VALUES
(1, 200, ''ab''),
(2, 300, ''ab''),
(3, -150, ''ac''),
(4, 200, ''ab'');

select SUM(Amount)
from @table
where name = ''ab'' ' + @value + ';';
EXEC(@sql);

Notes:

*

*this is called dynamic SQL rather than concatenated query

*a simple way to debug such code is to replace the EXEC(@sql) command with SELECT @sql, which lets you see the SQL generated by your code; in this DB Fiddle, you can see the result:

DECLARE @table TABLE
(
    ID INT,
    Amount INT,
    Name VARCHAR(500)
);

DELETE FROM @table;
INSERT INTO @table
(
    ID,
    Amount,
    Name
)
VALUES
(1, 200, 'ab'),
(2, 300, 'ab'),
(3, -150, 'ac'),
(4, 200, 'ab');

select SUM(Amount)
from @table
where name = 'ab'  and ID IN (1,2);

A: Hi use below modify query
DECLARE @value VARCHAR(500) = ' and ID IN (1,2)';
DECLARE @sql VARCHAR(MAX);

SET @sql = '
DECLARE @table TABLE
(
    ID INT,
    Amount INT,
    Name VARCHAR(500)
);

DELETE FROM @table
INSERT INTO @table
(
    ID,
    Amount,
    Name
)
VALUES
(1, 200, ''ab''),
(2, 300, ''ab''),
(3, -150, ''ac''),
(4, 200, ''ab'');

select SUM(Amount)
from @table
where name = ''ab''' + @value+';'
EXEC (@sql);

Query Output: 500


text:
Q: Failure to import numpy in Jupyter notebook I am new to iPython/Jupyter. Python skills limited, but learning. I am trying to import numpy as np and get the following:
---------------------------------------------------------------------------
ImportError                               Traceback (most recent call last)
<ipython-input-1-4ee716103900> in <module>()
----> 1 import numpy as np

/Users/jmmiii/Library/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/numpy/__init__.py in <module>()
    166         return loader(*packages, **options)
    167
--> 168     from . import add_newdocs
    169     __all__ = ['add_newdocs', 'ModuleDeprecationWarning']
    170

/Users/jmmiii/Library/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/numpy/add_newdocs.py in <module>()
     11 from __future__ import division, absolute_import, print_function
     12
---> 13 from numpy.lib import add_newdoc
     14
     15 ###############################################################################

/Users/jmmiii/Library/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/numpy/lib/__init__.py in <module>()
      6 from numpy.version import version as __version__
      7
----> 8 from .type_check import *
      9 from .index_tricks import *
     10 from .function_base import *

/Users/jmmiii/Library/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/numpy/lib/type_check.py in <module>()
      9            'common_type']
     10
---> 11 import numpy.core.numeric as _nx
     12 from numpy.core.numeric import asarray, asanyarray, array, isnan, \
     13                 obj2sctype, zeros

/Users/jmmiii/Library/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/numpy/core/__init__.py in <module>()
      4 from numpy.version import version as __version__
      5
----> 6 from . import multiarray
      7 from . import umath
      8 from . import _internal # for freeze programs

ImportError: dlopen(/Users/jmmiii/Library/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/numpy/core/multiarray.so, 2): no suitable image found.  Did find:
    /Users/jmmiii/Library/Enthought/Canopy_32bit/User/lib/python2.7/site-packages/numpy/core/multiarray.so: mach-o, but wrong architecture

I have several python installs on my Mac, which has Yosemite, including Canopy and Anaconda. I want my Jupyter notebook to use the Anaconda install including all the modules, libraries, etc. associated with it. It seems however that jupyter is targeting Canopy instead.  Thus, I think my problem might stem from the wrong linkage.
QUESTION 1: Does my conclusion hold water? If not, what might I be missing?
QUESTION 2: How can I direct/link jupyter with Anaconda and not with Canopy so that I import everything from anaconda only?
Thanks for everyone's help!

A: You can either set the PATH to execute python commands from the ~/anaconda/bin directory by prepending it to your .bah_profile by running the following command.
export PATH="/Users/jmmiii/anaconda/bin:$PATH"

OR, you can create an alias for the command by editing your ~/.bash_profile and adding:
alias jupyter-notebook="/Users/jmmiii/anaconda/bin/jupyter-notebook"


text:
Q: Dropdown + Autofill I have a address list(name, street,city,telnumber)
On another sheet I have a form, where I can choose the name from an dropdown list. Now I want to get street,city, telnumber for this name. Is this possible with just excel formula? I know It would work with If but this get quite long when I have a lot of addresses

A: This can be done by data validation.
Copy your already existing range of values into the same sheet where your form is (you can go paste it somewhere hidden so it's not visible immediately (cell BB1 for instance).
Select the "data" from the menu bar,
When the ribbon drops, click on "data validation" in the "data tools" group
Chose "data validation" to open the data validation dialog box
On the settings tab, click the "Allow" drop down and select "list"
Click on the source field, and highlight your data range from your sheet.
Click OK.


text:
Q: Route/Redirect to another page in new tab using useNavigate I am using ag-grid and it has an event onSelectionChanged, which make the row clickable. When I click on row below function is called.
const onSelectionChanged = useCallback(() => {

  const selectedRow = gridRef.current.api.getSelectedRows(); //get the row data

  let navigate = useNavigate();   //import { useNavigate } from "react-router-dom";
  navigate('/Detail', { state: { data: selectedRow[0]} });  //navigate to detail page

}, []);

The function navigates to the detail page and the state is passed. But navigate() calls the Detail page in same tab.
I want to open the page in new tab. Is this possible using this method? or there is another way to accomplish my goal?

A: react-router isn't supposed to help preserve state when opening things in a new tab. In fact, fundamentally, react isn't supposed to help do this.
I'd approach this in two ways:

*

*If the data is simple enough, pass it as a query or path param using windows.open(window.open("http://link?key="+ value +"&key2="+ value2 ..."); )

*Look into other state management methods like localstorage or something else


text:
Q: Thousands of extraneous gunicorn workers I'm using gunicorn 19.7.1 appserver with nginx reverse proxy for a Django project (Ubuntu 14.04 machine).
ps aux | grep gunicorn | grep -v grep | wc -l yields 3043 at the moment.
Whereas in /etc/init/gunicorn.conf, I've always had -w 33. Yet these extra workers persist even if I do sudo service gunicorn stop and sudo service gunicorn start.
How do I kill the extraneous workers?

How did this happen?
The worker count of 33 has always been properly configured on my busy production system.
However a few hours ago, I was trying python's multiprocessing on the server and things went south. Gunicorn workers ate up all the memory and took out the resident redis instances as well.

I reverted the change and have managed to get everything back online, except the memory hasn't been released and I've had to cope with these legacy gunicorn workers. What's going on?

A:
Yet these extra workers persist even if I do sudo service gunicorn stop and sudo service gunicorn start.

service only manages service-initiated processes, so if you started Gunicorn workers outside of the service framework, these workers will continue to live even if you stop.

How do I kill the extraneous workers?

The fast way:
Run this command to list all gunicorn process IDs and terminate them, and then restart Gunicorn:
$ pkill gunicorn
$ sudo service gunicorn start

The better way:

*

*Identify your "desired" Gunicorn workers by finding the parent:
$ sudo service gunicorn status

Note the parent process ID. Let's say it's 123.

*Save a list of all the "desired" workers' PIDs:
 $ echo 123 > desired_workers
 $ pgrep -P 123 >> desired_workers

*Save a list of all workers' PIDs:
 $ pgrep gunicorn > all_workers

*Terminate the "undesired" workers:
 $ cat desired_workers all_workers | sort | uniq -u | xargs kill


text:
Q: show that inequality $(x-3)^4+(y-3)^4+(z-3)^4\ge 193$ Let $x,y,z\in R$,and such
$$xy+yz+xz=-1$$ show that
$$(x-3)^4+(y-3)^4+(z-3)^4\ge 193$$
it seem use Cauchy-Schwarz inequality to solve it?But I try sometime can't get this answer,even now I can't find this equality when $=$?

A: Mathematica is not happy (Unless I'm blind and missed an obvious typo).
$$
x := -\frac{485}{2048} \\
y := -\frac{5}{2048} \\
z := \frac{4196729}{1003520}
$$
Then $xy + yz + zx = -1$ (See WA). However
$$
(x-3)^4 + (y-3)^4 + (z-3)^4 = 192.98312371 < 193
$$
See WA.

Also it seems that Mathematica FindInstance cannot disprove your statement in $\mathbb{Z}$ so it might be true in this set.

A: Let $x+y+z=3u$, $xy+xz+yz=3v^2$, where $v^2$ can be negative, and $xyz=w^3$.
Hence, the expression $\sum\limits_{cyc}(x-3)^4$ is a linear expression of $w^3$,
which says that it gets a minimal value for an extremal value of $w^3$,
which happens for equality case of two variables.
Let $y=x$. Thus, $z=-\frac{1+x^2}{2x}$ and
$$\min_{xy+xz+yz=-1}\sum_{cyc}(x-3)^4=\min\left(2(x-3)^4+\left(-\frac{1+x^2}{2x}-3\right)^4\right)=191.779...,$$
which occurs for $x_1=-0.12...$, where $x_1$ is a negative root of the following equation.
$$11x^6-90x^5+321x^4-180x^3-107x^2-18x-1=0.$$


text:
Q: Matlab: command check whether positive or negative sign before a term? I am looking a command that would do:
a*b*c -----> +

-a --------> -

a*b -------> +

c*d*e*f*a--> +

where a, b, c, d, e and f are symbolic variables in Matlab.
Is there any command to return the initial sign of an expression?

A: If you have Matlab 2013 you can do this:
>> syms a b c
>> children(a*b*c)

ans =

[ a, b, c]

>> children(-a)

ans =

[ a, -1]

>> children(a*b)

ans =

[ a, b]

>> children(-a*-b)

ans =

[ a, b]

>> children(-a*-b*-c)

ans =

[ a, b, c, -1]

You will get the initial sign by looking at the the last element of the returned vector.
So test for that.
If you define a variable to a value the result will look like this:
>> c = -4;
>> children(-a*-b*-c)

ans =

[ a, b, 4]

Calling sign on the last element will give -1 if negative, 1 for positive.
Note that there may not always be a numeric value as the last element!
Sign(a) will give sign(a) so you will need to assume it is positive in that case.


text:
Q: JSON to String with inner array convertion I have a larga data JSON which I want to pass to the backend to be parsed there to become into java objects.
To make this I'm using the JSON.stringify function but inside the JSON there is an array attribute that the JSON.stringify is enclosing between quotes ("), so when Gson find it (the way I'm using at the backend to decode the string into objects), it throws an error because this is not an array inside a JSON string representation, but an string attibute inside a JSON string representation.
This is an example of the string generated with JSON.stringify:
{"id":0, "array": "[{\"id\":0, \"cod\": \"XXX\"}, {\"id\":0, \"cod\": \"XXX\"}]"}

The array attribute cannot be converted by Gson because is not an array.
Can anybody help me with this issue?
Thanks a lot.

A: I'd likely prefer to fix the generated JSON, but if that's not possible or otherwise preferable, it looks like you'll simply need to deserialize part of the JSON twice.  This could be accomplished with a custom deserializer as follows.
import java.lang.reflect.Type;
import java.util.Arrays;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

public class GsonFoo
{
  public static void main(String[] args)
  {
    // With the generated JSON corrected:

    // {"id":42, "array": [{"id":1, "cod": "aaa"}, {"id":2, "cod": "bbb"}]}
    String jsonInput = "{\"id\":42, \"array\": [{\"id\":1, \"cod\": \"aaa\"}, {\"id\":2, \"cod\": \"bbb\"}]}";

    Gson gson = new Gson();

    Bar bar1 = gson.fromJson(jsonInput, Bar.class);
    System.out.println(bar1);
    // Bar: id=42, array=[Thing: id=1, cod=aaa, Thing: id=2, cod=bbb]

    // -------------------------

    // With the funky JSON:

    // {"id":42, "array": "[{\"id\":1, \"cod\": \"aaa\"}, {\"id\":2, \"cod\": \"bbb\"}]"}
    String funkyJsonInput = "{\"id\":42, \"array\": \"[{\\\"id\\\":1, \\\"cod\\\": \\\"aaa\\\"}, {\\\"id\\\":2, \\\"cod\\\": \\\"bbb\\\"}]\"}";

    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.registerTypeAdapter(Thing[].class, new FunkyThingArrayDeserializer());
    gson = gsonBuilder.create();

    Bar bar2 = gson.fromJson(funkyJsonInput, Bar.class);
    System.out.println(bar2);
    // Bar: id=42, array=[Thing: id=1, cod=aaa, Thing: id=2, cod=bbb]
  }
}

class FunkyThingArrayDeserializer implements JsonDeserializer<Thing[]>
{
  @Override
  public Thing[] deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
      throws JsonParseException
  {
    String actualJson = context.deserialize(json, String.class);
    return new Gson().fromJson(actualJson, Thing[].class);
  }
}

class Bar
{
  int id;
  Thing[] array;

  @Override
  public String toString()
  {
    return String.format("Bar: id=%d, array=%s", id, Arrays.toString(array));
  }
}

class Thing
{
  int id;
  String cod;

  @Override
  public String toString()
  {
    return String.format("Thing: id=%d, cod=%s", id, cod);
  }
}

A: You need to write this code before invoke JSON.stringify
if(window.Prototype) {
    delete Object.prototype.toJSON;
    delete Array.prototype.toJSON;
    delete Hash.prototype.toJSON;
    delete String.prototype.toJSON;
}


text:
Q: Is it possible to check if the 15-puzzle is solvable with a different goal state? So I have a random 15-puzzle, or any N-puzzle with even width, and I also have a random goal-state. That is, the blank tile and other tiles are also randomly placed.
I am able to check if the 15 puzzle is solvable with the standard goal state of having the tiles in order and blank in the bottom right,  but randomizing the goal state seems to be more tricky than the standard 8 puzzle.
Example:
Start State
8    4    1   6
11   2    3   10
15   12   0   9
14   5    7   13

Goal State:
11   4    1   0
8    2    3   10
5    15   6   9
12   9    7   13

The rules for the standard 15-puzzle solvabilty are:

If the width is odd, then every solvable state has an even number of inversions.
If the width is even, then every solvable state has

*

*An even number of inversions if the blank is on an odd numbered row
  counting from the bottom;

*An odd number of inversions if the blank is on an even numbered row
  counting from the bottom;

A: I don't think different goal have any effect on solvability.
The simplest solution I can think of is to map numbers in the custom goal state to the numbers in the standard goal state. E.g: For the first row you treat 11 as if it was 0, 4-> 1, 1->2, 0->3 and so on.

A: The algorithm is the same as for standard puzzle, but you need a little change.
In general, the algorithm for reachability from start position S to goal position G is:

*

*Calculate number of inversions in G - I(G)

*Calculate number of inversions in S - I(S)

*If:

*

*width is odd and I(G) and I(S) have the same parity, G is reachable from S (in other words, S is solvable)

*width is even:

*

*Find the row number where blank is located in G - B(G)

*Find the row number where blank is located in S - B(S)

*If I(G)

*

*is even and I(S) and abs(B(G) - B(S)) have the same parity, G is reachable from S

*is odd and I(S) and abs(B(G) - B(S)) have different parity, G is reachable from S
In other cases G is unreachable from S.

Now let's see on your example. Represent a state as a list:
List<Integer> start = Arrays.asList(
        8, 4, 1, 6,
        11, 2, 3, 10,
        15, 12, 0, 9,
        14, 5, 7, 13);
List<Integer> goal = Arrays.asList(
        11, 4, 1, 0,
        8, 2, 3, 10,
        5, 15, 6, 9,
        12, 14, 7, 13); // in your example there's a second 9 instead of 14

A function, which will count number of inversions:
int inversions(List<Integer> numbers) {
    int inversions = 0;
    for (int i = 0; i < numbers.size(); i++) {
        int n = numbers.get(i);
        if (n <= 1) {
            continue;
        }
        for (int j = i + 1; j < numbers.size(); j++) {
            int m = numbers.get(j);
            if (m > 0 && n > m) {
                inversions++;
            }
        }
    }
    return inversions;
}

Finally, check the solvability:
boolean isSolvable(List<Integer> start, List<Integer> goal) {
    int inversions = inversions(start);
    int goalInversions = inversions(goal);
    if (width % 2 == 0) {
        int goalZeroRowIndex = goal.indexOf(0) / width;
        int startZeroRowIndex = start.indexOf(0) / width;
        // a little optimization is possible since we're only interested in parity
        return (goalInversions % 2) == ((inversions + goalZeroRowIndex + startZeroRowIndex) % 2);
    } else {
        // for odd width just compare parity of inversions
        return (inversions % 2) == (goalInversions % 2);
    }
}

This function will work on both standard and random variations, regardless of 0 position.
For a given start and goal positions:
I(G) = 32
I(S) = 36
B(G) = 0
B(S) = 2
abs(B(G) - B(S)) = 2

I(G) is even and both I(S) and abs(B(G) - B(S)) have the same parity, so the puzzle is solvable. In fact, it is solvable in 31 moves:
12, 2, 11, 15, 2, 12, 9, 10, 6, 1, 4, 11, 15, 2, 12, 5, 14, 12, 5, 15, 2, 8, 11, 4, 3, 6, 10, 9, 6, 3, 1


text:
Q: With Pyramid - How to get the host_url with the mount point? I have a pyramid application that I am mounting with MOD-WSGI in /myApp however request.host_url() returns the host URL without the mount point. For now I am fixing this by having the mount point in a variable in the INI file  that I concatenate later on to request.host_url() but is there a better way to get the host_url with the mount point?

A: presumably you aren't properly setting WSGIScriptAlias /mountpoint /path/to/my/foo.wsgi as defined https://modwsgi.readthedocs.io/en/develop/configuration-directives/WSGIScriptAlias.html - if this is done then mod_wsgi should be setting the request.script_name in your environ properly which will affect the request.host_url value.


text:
Q: Spring boot does not receive headers from react js I'm implementing a ReactJs applications.  I am using axios to invoke server side services built using Spring Boot.  I need to send the header "Authorization: Bearer token-value".  This is the client side code:
var options = {
    withCredentials: true,
    headers: {'Authorization': 'Bearer token-value'}
};
axios.post('http://localhost:9090/services/list', null, options)
    .then((data) => {
        console.log(data);
    })
    .catch((error) => {
        console.error(error);
    });

This is the Spring Boot controller:
@RestController
public class ServiceController {

    private static final String AUTHORIZATION_HEADER_NAME = "Authorization";
    private static final String BEARER = "Bearer ";

    private static String getToken(HttpServletRequest request) {
        String header = request.getHeader(AUTHORIZATION_HEADER_NAME);
        if (header == null || header.trim().equals("")) {
            return null;
        }
        header = header.trim();
        if (!header.startsWith(BEARER)) {
            return null;
        }
        return header.substring(BEARER.length()).trim();
    }

    @GetMapping
    @RequestMapping(value = "/services/list", produces = "application/json", method = RequestMethod.POST)
    public ResponseEntity<?> getTargets(HttpServletRequest request, HttpServletResponse response) {
        String token = getToken(request);
        if (token == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
        DTOObject obj = goForTheBusinessObject(token);
        return new ResponseEntity<>(obj, HttpStatus.OK);
    }
}

This is the CORS configuration
@Configuration
public class RestConfig {
    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowCredentials(true);
        config.addAllowedOrigin("*");
        config.addAllowedHeader("*");
        config.addAllowedMethod("POST");
        config.addAllowedMethod("GET");
        config.addAllowedMethod("DELETE");
        config.addAllowedMethod("PUT");
        source.registerCorsConfiguration("/**", config);
        return new CorsFilter(source);
    }
}

If I invoke the service using curl I got the expected response:
curl -X POST -H "Authorization: Bearer token-value" http://localhost:9090/services/list

If I invoke the service using post man, again I got the right answer.
But when I executed the ReactJS application, the server never receive the "Authorization" header.
Somebody help me please !!

A: You are facing CORS issues, Implement this class to resolve this-
@Component
public class CorsFilter  implements WebFilter  {

@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
    if (exchange != null) {
        exchange.getResponse().getHeaders().add("Access-Control-Allow-Origin", "*");
        exchange.getResponse().getHeaders().add("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE, OPTIONS");
        exchange.getResponse().getHeaders().add("Access-Control-Allow-Headers",
                "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range");
        exchange.getResponse().getHeaders().add("Access-Control-Max-Age", "1728000");

        if (exchange.getRequest().getMethod() == HttpMethod.OPTIONS) {
            exchange.getResponse().getHeaders().add("Access-Control-Max-Age", "1728000");
            exchange.getResponse().setStatusCode(HttpStatus.NO_CONTENT);
            return Mono.empty();
        } else {
            exchange.getResponse().getHeaders().add("Access-Control-Expose-Headers", "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Content-Range,Range");
            return chain.filter(exchange);
        }

    } else {
        return chain.filter(exchange);
    }

}
}

For more info on CORS visit this
Update: For scanning the component you can do following-
@ComponentScan(value = "com.pck", // cors filter package
    useDefaultFilters = false)
public class MainClass {
    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.
        run(MainClass.class, args);
    }
}


text:
Q: How to populate a column with random date in a table which falls between 2 dates from another table I have two tables like patient_record and surgery_record. I want to populate the surgery_Date column in surgery_record table with a random date which falls between the Beg_Date and End_Date values in the patient_record table (Beg_Date and End_Date are the dates of patient admittance and discharge respectively. Currently I have the following query. Thanks in advance
patient_record:
Beg_Date = DATEADD(DAY, ABS(CHECKSUM(NEWID()) % 365), '01/01/2000')
End_Date = DATEADD(DAY, 85 + ABS(CHECKSUM(NEWID()) % 11), Beg_Date)

surgery_record:
update Surgery_Record
set Surgery_Date =  DATEADD(DAY, 85 + ABS(CHECKSUM(NEWID()) % 11), patient_record.Beg_Date)

But I get the following error:
Msg 4104, Level 16, State 1, Line 2
The multi-part identifier "patient_record.Beg_Date" could not be bound.

I understand that I must have a relationship between these two tables to use the attributes commonly and I already have a foreign key constraint on a different attribute. If this is not enough please advice.

A: update Surgery_Record
set Surgery_Date =  DATEADD(DAY, 85 + ABS(CHECKSUM(NEWID()) % 11), patient_record.Beg_Date)
from patient_record
where patient_record.PatID=Surgery_Record.PatID


text:
Q: Powershell - how to obtain previous lines from text file? I have a text file containing hundreds of lines of text containing database info.
I'm trying to extract the DatabaseIds for any database which is 35GB.
I would like to interrogate the file using Powershell and produce a text file containing all the matching databases.
So in essence, I would like to scan through the file, find a DatabaseSize which is 35 and then extract the corresponding DatabaseId from 3 lines previous.
I've looked all over the net but can't seem to find anything which can do this.
Example extract of text file:
ServerId = VMlinux-b71655e1
DatabaseId = db-ecb2e784
Status = completed
LocationId = 344067960796
DatabaseSize = 30

ServerId = VMlinux-0db8d45b
DatabaseId = db-cea2f7a6
Status = completed
LocationId = 344067960796
DatabaseSize = 35

ServerId = VMlinux-c5388693
DatabaseId = db-9a421bf2
Status = completed
LocationId = 344067960796
DatabaseSize = 8

etc

A: Try with something like this:
(( GC myfile.txt |
   Select-String 'DatabaseSize = 35' -Context 3 ).context.precontext)[0]

In case of multiple match:
(GC myfile.txt |
SELECT-STRING 'DATABASESIZE = 35' -Context 3 ) | % { ($_.context.precontext)[0] }


text:
Q: How to generate intermediate tables from JPA2 models in eclipse I have to objects, User and Company and they have a one to many relationship. A user can have multiple companies. I want to model this in a database using three tables. User, UserCompany and Company where the UserCompany links the two tables together.
In my java code however I don't want to 'see' this table. E.g in the User class I want to have a getCompanies() method which returns a list (or set) of Company objects.
I also want to use JPA2 and will be running the application in Glassfish in the EE6 container.
I've been playing with Eclipse (the Dali generation plugin) to generate the database tables but it will not generate any intermediate table.
Is this at all possible? If yes, can you give me an example of two classes with JPA2 annotations from which I can generate the three database tables?
Thanks!

A: This was a simple case of RTFM. I copied the JoinColumn annotation from another class which is actually preventing a join table. I replaced it with a JoinTable annotation (which is not required but to keep the table and field names more logical I do use it) and now it works oke.


text:
Q: Delphi ADO: necessary to clean up parameters? Suppose I have a TADOQuery object that I reuse for different purposes in my program. Do I need to explicitly clean up the parameters when I'm done? Or does that happen automagically when I clear the SQL? e.g.
  adoGenericQuery.SQL.Text := '';
  adoGenericQuery.Parameters.Clear; // <- Is this redundant?

A: You don't need to clear the parameters manually. When the SQL text is assigned, first the query is closed if it is active, then the parameters are either initialized (if ParamCheck is true and the text is not empty) or cleared (if the text is empty).


text:
Q: Chrome slow to load resources `(from disk cache)` My site http://www.front-end.io configures the HTTP requests to load resources from cache with first priority. So my header will be like:
cache-control:max-age=315360000
ETag:W/"11913b-ks0rwRQM+ijHcl1HDuse3g"

Chrome indeed does not initiate any request (even 304) to the server, it loads from the cache directly:

It takes my Windows10 Chrome >400ms to load the js file from local disk.
My Ubuntu Chromium also takes >100ms.
But FireFox takes around 10ms only!
I found this question as well, Google Chrome load image from cache slower than download, but there are not explanations.
Could anybody help? Thanks.

A: Probably that is wrong timing information.
In order to Chrome Dev Tools such as Timeline display correct information you must disable extensions to exclude noise that they produce. Relevant excerpt from How to Use the Timeline Tool article by Kayce Basques:

Disable extensions. Chrome extensions can add unrelated noise to
  Timeline recordings of your application. Open a Chrome window in
  incognito mode, or create a new Chrome user profile to ensure that
  your environment has no extensions.

Although some extensions can intercept resource requests in blocking fashion Grammarly is not one of those extensions. It doesn't have required webRequestBlocking permission specified in manifest file. Check chrome.webRequest page for more information.
If you measure time that took browser to get /vendor.61e0ab918e699695d3a3.js script from disk cache, compile and execute it you will see that it is pretty much constant regardless of whether Grammarly enabled or disabled. You can use code snippet below:
<script>var startTime = performance.now();</script>
<script type="text/javascript" src="/vendor.61e0ab918e699695d3a3.js"></script>
<script>
  var endTime = performance.now();
  console.log("Time: " + (endTime - startTime) + " [ms].")
</script>