text:
Q: Javascript passing argument: Strange Syntax So I started to study javascript, and coming from .net background I found the following code:
File express.js:
var express = require('express');
module.exports = function() {
    var app = express();
    require('../app/routes/index.server.routes.js')(app);
    return app;
};

File index.server.routes.js:
module.exports = function(app) {
    var index = require('../controllers/index.server.controller');
    app.get('/', index.render);
};

As the book was explaining the index.server.routes.js have this function(app), and app is the express object used to configuration(it is configuring the '/' path). That is ok.
What I do not understand is the following syntax:
require('../app/routes/index.server.routes.js')(app);

What I understand is that he is passing the app argument to the index.server.routes.js module and this module is setting the get.
But can anyone me explain how this syntax works? Coming from .net background, it seems to me a casting(very strange and confusing).

A: The syntax is the syntax for calling functions. index.server.routes.js exports a function, therefore you can call it. Think that it is the same as:
var routes = require('../app/routes/index.server.routes.js')
routes(app) // routes is a function

It is common in Express to pass your app instance around as a form of explicit dependency injection.

A: It is rather simple. When you call require in Node.js, Node will load the module (the file), and return to you whatever that module exported via the module.exports property. In this case, it exported a function.
As such, require gives you a function and thus you can immediately call it by putting the parentheses right after the require statement.
The code is equivalent of doing this:
var routesFn = require('../app/routes/index.server.routes.js')
routesFn(app)


text:
Q: How Can I add My Captured Image to My Hashmap I am still learning hashmaps and database structures so please forgive me if this is a basic question. I've tried to research but nothing seems to work. I have a method in the same activity where I capture an image which is pushed to Firebase Storage. The image successfully goes to Firebase Storage, but I cannot figure out how to add the image to my hashmap to go to the Firebase Database. My hashmap is below and currently works.
Thank you for your help.
    String title = title_edit_text.getText().toString();
    String first_name = firstname.getText().toString();
    String last_name = lastname.getText().toString();

    if (TextUtils.isEmpty(title)) {
        title_edit_text.setError("Input is required!");
    } else {
        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Date date = new Date();
        String creation_date= dateFormat.format(date);

        DateFormat date_format_for_time = new SimpleDateFormat("hh:mm:ss a");
        Date time = new Date();
        String creation_time= date_format_for_time.format(time);

        HashMap userMap = new HashMap();
        userMap.put("title", title);
        userMap.put("creation_date", creation_date);
        userMap.put("creation_time", creation_time);
        userMap.put("first_name", first_name);
        userMap.put("last_name", last_name);

        String upload = UsersReference2.push().getKey();
        UsersReference2.child(upload).setValue(userMap).addOnCompleteListener(new OnCompleteListener() {
            @Override
            public void onComplete(@NonNull Task task) {
                if (task.isSuccessful()) {
                    sendBackActivity();
                    Toast.makeText(Adding_Activity.this, "Successfully Save.", Toast.LENGTH_LONG).show();

                } else {
                    String message = task.getException().getMessage();
                    Toast.makeText(AddingActivity.this, "Error. Did Not Save: " + message, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == Gallery_Pick && resultCode == RESULT_OK && data != null) {
        image_uri = data.getData();

        CropImage.activity(image_uri)
                .setGuidelines(CropImageView.Guidelines.ON)
                .setAspectRatio(3, 2)
                .start(this);
    }

    // when pressing the crop button//
    if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
        CropImage.ActivityResult result = CropImage.getActivityResult(data);

        if (resultCode == RESULT_OK) {
            Uri resultUri = result.getUri();

            StorageReference filePath = CoverPostReference.child(currentUserID + ".jpg");

            filePath.putFile(resultUri).addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                @Override
                public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                    if (task.isSuccessful()) {

                        Toast.makeText(Adding_Activity.this, "Image has been added sucessfully...", Toast.LENGTH_SHORT).show();
                        Task<Uri> result = task.getResult().getMetadata().getReference().getDownloadUrl();

                        result.addOnSuccessListener(new OnSuccessListener<Uri>() {
                            @Override
                            public void onSuccess(Uri uri) {
                                final String downloadUrl = uri.toString();
                                UsersReference2.child("cover_image").setValue(downloadUrl)
                                        .addOnCompleteListener(new OnCompleteListener<Void>() {
                                            @Override
                                            public void onComplete(@NonNull Task<Void> task) {
                                                if (task.isSuccessful()) {
                                                    Toast.makeText(Adding_Activity.this, "Image has been stored...", Toast.LENGTH_SHORT).show();
                                                } else {
                                                    String message = task.getException().getMessage();
                                                    Toast.makeText(Adding_Activity.this, "Error: " + message, Toast.LENGTH_SHORT).show();
                                                }
                                            }
                                        });
                            }
                        });
                    }
                }
            });
        } else {
            Toast.makeText(Adding_Activity.this, "Error: Image did not upload. Please try again.", Toast.LENGTH_SHORT).show();
        }
    }
}

A: You shouldn't/wouldn't store the image bitmap data into the hashmap, instead you should store the location to the bitmap (URI) to the hashmap (and database) and then use that to access the image.
Storing
Map<String, Uri> bitmapUriMap = new HashMap<String,Uri>();
bitmapUriMap.put("MyLocalBitmapName", UriOfBitmap);

Accessing
Then when you have the URI you just decode it
Uri uri = bitmapUriMap.get("MyLocalBitmapName);
Bitmap decodedUri = BitmapFactory.decodeFile(new File(uri.getPath()));

This is what you would store in the database. For instance if you want the image of a user, then you would store the image uri within your firebase database and then you would access it this way. Storing a bitmap in a database is not ideal and not recommended.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to know if checkbox is checked? I am looking for a solution to this matter for the last 2 hours and I can't find a simple answer to resolve it.
I want to check if the checkbox is checked or not and whatever I do, the console always tell me it is unchecked.
HTML :
<ion-checkbox ng-model="option1" ng-true-value="2" ng-false-value="0" id="itemOrder-checkbox1">With option 1 (+$2)</ion-checkbox>
      <ion-checkbox ng-model="option2" ng-true-value="3" ng-false-value="0" id="itemOrder-checkbox2">With option 2 (+$3)</ion-checkbox>
      <ion-checkbox ng-model="option3" ng-true-value="1" ng-false-value="0" id="itemOrder-checkbox3">With option 3 (+$1)</ion-checkbox>

        <input id="notes" type="text" placeholder="Add some notes...">

      <button class="button button-block button-dark" style="color:#F5E124;" type="submit" id="itemOrder-button3" ng-click="addToCart()">
          Add to cart (${{quantity * (15 + option1 + option2 + option3)}})
      </button>

Controller :
$scope.addToCart = function(){
    if ($scope.option1) {
        console.log("CheckBox is checked.");
    } else {
        console.log("CheckBox is not checked.");
    }

    firebase.database().ref('accounts/' + userId + '/cart/').push({
      item: "item1",
      quantity: document.getElementById('quantity').value,
      price: document.getElementById('price').textContent,
      notes: document.getElementById('notes').value,

    })
  $state.go("menu2.menu");
  }

A:

    <title></title>

        Do you have Passport?

            <input id="chkPassport" type="checkbox" ng-model="HasPassport" />

        <input type="button" value = "Check Passport" ng-click = "CheckPassport()" />

A: <input type="checkbox" checked ng-change="click()" ng-model="option1" value="Bike">
    I have a bike

Controller:
$scope.click = function(){
    if ($scope.option1) {
        alert("CheckBox is checked.");
    } else {
        alert("CheckBox is not checked.");
    }
  }

Here is the demo: Plnkr


text:
Q: How can I take an image with a white background and make it transparent I have a png image that has a white background.  Is there anyway to take the white and make it transparent.

A: you can use Photofiltre (small, fast, free and portable):

*

*load the image

*go to Image > Transparent Color...

*choose the color (white), set the desired tolerance with the slider, click OK

*go to File > Save as... and save the image as .PNG

A: I haven't seen a solution using Paint.NET here yet. It's an awesome lightweight image editor. To quote Jeff: "It raises the quality bar,"

*

*Download, install and run Paint.NET

*File > Open > Select your image

*Click the Magic Wand tool:

*Click the white background on your image

*Press Delete

*File > Save

You can also select the tolerance of the magic wand tool before your use it to get rid of the "crust" or whatever you want to call it around your leftover image.

A: The GIMP will allow you to convert a single colour to alpha, making it transparent.
The basic flow requires right-clicking on the image and choosing:
Filter > Color > Color to Alpha

And then selecting the white background. The GIMP will replace all white pixels in the image with transparent pixels.
Here's a good tutorial showing you how.

A: use GIMP...
Select the white area and erase or delete it, you can select and use the DEL key, or use the eraser if that doesn't work as needed. Then save it as a PNG.

A: Photoshop (and Photoshop Elements) magic wand tool will allow you to select contiguous colours.  You may want to play with the tolerance a bit...  Once selected, hit delete to remove the white.

A: You can use Paint.net to do this using the plugin Alpha Mask.

*

*Load the image. Select All (Ctrl-A) and Copy (Ctrl-C).

*Using the Effects menu, select Alpha Mask

*Leave the Mask File box blank and check the following options:

*

*Invert Mask

*Mix Alpha

*Paste From Clipboard

After running the effect, you can optionally duplicate the layer and merge down to "darken" the image.
I know that Paint.net was used in a previous answer, but using the Magic Wand tool, or the Paint Bucket (to fill with transparency), will leave the edges of the image jagged. It won't look good on color backgrounds. Using the Alpha Mask method your image will look crisp on any background.


text:
Q: Encountering a "this is undefined" TypeError when using this.router.navigate for Angular I am trying to implement an error handler that redirects the page to an error page upon encountering a status 0 error. However, in the console log, I received an error that "this" is undefined.
(There are some this is undefined questions on the site, but I don't think any are applicable)
To implement the error handler, I have the following code. Without the [this.router.navigate(['/error']);] line, everything works fine.
import { Router } from '@angular/router';

....

constructor(private httpClient:HttpClient,
          private router: Router) { }

....

private getProducts(searchUrl: string): Observable<Product[]> {
    return this.httpClient.get<GetResponseProducts>(searchUrl).pipe(
      map(response => response._embedded.products),
      catchError(this.handleError)
    );
}

....

private handleError(error: HttpErrorResponse) {
    if (error.status === 0) {
      // A client-side or network error occurred. Handle it accordingly.
      console.error('An error occurred:', error.error);
      this.router.navigate(['/error']);
    } ...
  }
}

The route in question directs to the BackendErrorComponent (app.module.ts)
const routes: Routes = [
  {path: 'error', component: BackendErrorComponent},
  {path: 'checkout', component: CheckoutComponent},
  {path: 'cart-details', component: CartDetailsComponent},
  {path: 'products/:id', component: ProductDetailsComponent},
  {path: 'search/:keyword', component: ProductListComponent},
  {path: 'category/:id', component: ProductListComponent},
  {path: 'category', component: ProductListComponent},
  {path: 'products', component: ProductListComponent},
  {path: '', redirectTo: '/products', pathMatch: 'full'},
  {path: '**', redirectTo: '/products', pathMatch: 'full'},
];

This is the component in question (backend-error.component.ts):
import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-backend-error',
  templateUrl: './backend-error.component.html',
  styleUrls: ['./backend-error.component.css']
})
export class BackendErrorComponent implements OnInit{
  constructor() { }

  ngOnInit() {
      console.log('backendErrorComponent | ngOnInit...');
  }
}

HTML (backend-error.component.html):

Error


text:
Q: How do I stop the output of my Python program after a specific length of time so I can start a new process? I'm using tweepy to scrape tweets and spit out the letters in the console line by line. However, I'd like to start a new process after I've printed out a specific number of characters or after a length of time.
Here's what I tried.
class Listener(StreamListener):
    def on_data (self, data):
        tweet = data.split(',"text":"')[1].split('","Liksource')[0]
        for letter in tweet:
            number = ord(letter)
            print (letter)
        if len(sys.stdout) == 50:
            print "Hello world!"

I want this to print "Hello World!" just to demonstrate I can start a new thing, but also would like to stop the streaming of data. I tried using a break and it wouldn't let me.


text:
Q: Spanish municipality level shapefile and population data I'm struggling with the Spanish municipality level.
I need to incorporate population data with the lat/long for each Spanish municipality and below are the details of my current files:

*

*I cannot find one master CSV having population for each municipality,
instead I have 52 files having population for municipalities within
each Spanish province;

*I have the lat/long for each municipality in a separate CSV, and

*The problem is, I need a master CSV with all data in one place and my CSV files don't have an id I can use to map the data.

A: I don't know whether you're still after an answer to this problem. Anyway, I'm assuming you're using ESRI GIS. There probably is a similar method in case you're using different software.
What you're after is the spatial join tool. Try this:

*

*Load one set of csv-data into your MXD.

*Right-click the loaded table, hit display X/Y coordinates and select the fields with your Lat/Lon

*Right-click the data again, select data --> export data and save in a GDB or as a shape file.

*Repeat for your second data set.

*Navigate to your Analysis toolbox and select spatial join. Use the data set you want to join your data to as "Target feature". Add a search radius (in case your coordinates aren't identical). Select an output feature class and hit OK.


text:
Q: Parcel JS - not wrapping background-image url in single quotes I'm using Parcel JS to do some simple SCSS compilation. On the Parcel live server everything looks fine, but when running the build command (in my case parcel build index.html --public-url ./) my background-images from the SCSS file are broken.
It seems as though even though the image is in single quotes e.g. background-image: url('images/image.jpg');, these are being removed on build and causing Chrome to think the image is an invalid property.
Is there any way to avoid this behaviour?

A: After not receiving an answer I think I've managed to solve the problem. This seems to be one of two issues.

*

*Out of date version of SASS (just a simple npm update)

*It not liking files with spaces in - simply rename any times.


text:
Q: The eigenvectors of a reflection and rotation symmetry operation In the book I'm reading there is a question,

Prove that given a rotation $R(\phi \hat{n})$ and a reflection $\sigma$, they commute iff $\sigma \perp \hat{n}$ and $\phi=\pi$. (Binary rotation normal to the reflection plane.)

The answer in the back of the book is,

Take $R(\phi z)$. For $\phi=\pi$, the eigenvectors, with eigenvalues in brackets, are: $\vec{z}(+1), \vec{x}(-1), \vec{y}(-1)$. If $\sigma$ is the $\vec{x}\vec{y}$ plane its eigenvectors are $\vec{x}(+1), \vec{y}(+1), \vec{z}(-1)$ and coincide with those of $R(\pi\vec{z})$.

My question:
I thought an eigenvector of a symmetry operation is one that after the symmetry operation $g\vec{r}$ leaves r changed only by the eigenvalues +1 or -1. In my mind, this means that the eigenvectors of a reflection operator $\sigma$ would be all vectors on the reflection plane and normal to the plane. Not just the two particular vectors that span the plane.

A: Eigenvectors are not unique in general and can be with respect to any eigenvalue. Generally what one does instead is pick a basis for a given eigenspace (the space of eigenvectors with respect to a particular eigenvalue) in the cases where such a basis exists. In this case the eigenspace associated to eigenvalue $1$ is the entire reflection plane, and any basis of this works.
However, in the generic case eigenspaces have dimension $1$ and this issue doesn't occur.


text:
Q: Create a function with optional arguments in MySQL I want to create a function with optional arguments in MySQL. For instance, I want to create function that calculates the average of its arguments. I create a function of five arguments, but when user passes just two arguments to the function then it should still run and return the average of the two arguments.

A: You cannot set optional parameters in MySQL stored procedures.
You can however set optional parameters in a MySQL UDF.
You do know that MySQL has an AVG aggregate function?
Workaround
If you can face the ugliness of this workaround here's samplecode that uses a comma separated string with values as input and returns the average.
DELIMITER $$

CREATE FUNCTION MyAvg(valuestr varchar) RETURNS float
BEGIN
  DECLARE output float;
  DECLARE arg_count integer;
  DECLARE str_length integer;
  DECLARE arg float;
  DECLARE i integer;

  SET output = NULL;

  SET i = LENGTH(valuestr);
  IF i > 0 THEN BEGIN

    SET arg_count = 1;
    WHILE i > 0 DO BEGIN
      IF MID(valuestr, i, 1)
      SET i = i - 1;
    END; END WHILE;

    /* calculate average */
    SET output = 0;
    SET i = arg_count;
    WHILE i > 0 DO BEGIN
      SET arg = SUBSTRING_INDEX(
                  SUBSTRING_INDEX(valuestr, ',' , i)
                  , ',', -1 );
      SET output = output + arg;
      SET i = i - 1;
    END; END WHILE;
    SET output = output / arg_count;

  END; END IF;
  RETURN output;
END $$

DELIMITER ;

Use concat_ws to feed the function.
SELECT MyAvg(CONCAT_WS(',',100,200,300,500)) AS test;

You can also write an UDF in C(++) or Delphi/Lazarus

A: While far from an ideal solution, here's how I solved optional parameters for a concat function I needed:
delimiter ||
create function safeConcat2(arg1 longtext, arg2 varchar(1023))
 returns longtext
 return safeConcat3(arg1, arg2, '');
||

create function safeConcat3(arg1 longtext, arg2 varchar(1023), arg3 varchar(1023))
 returns longtext
 return safeConcat4(arg1, arg2, arg3, '');
||

create function safeConcat4(arg1 longtext, arg2 varchar(1023), arg3 varchar(1023), arg4 varchar(1023))
returns longtext
  begin
      declare result longText;
      set result = concat(arg1, arg2, arg3, arg4);
      if( result is null) then
          set result=arg1;
      end if;
      return result;
  end
||

Note: This means you have to call the method that corresponds to the number of args.

A: Another approach is to pass only one 'super' parameter which is string with commas in it separating the real parameters. The mysql procedure can then parse the 'super' parameter into the separate real parameters.
Example:
create procedure procWithOneSuperParam(param1 varchar(500))
declare param2 varchar(100);
begin
 if LOCATE(',',param1) > 0 then
  .. param2=<extract the string after the ',' from param1> ..


text:
Q: How to check if an editText box(s) is empty or not in android using Java In my app, I have around 5 editText boxes in every screen.I want to check if they are empty or not and if all the text boxes are not empty, then there is an intent which takes you to the next screen. I want to know what code to write.

A: Just add this code in your java file when you want to call the intent.
EditText editTextBox1 = (EditText) findViewById(R.id.your_editTextBox1_id);
EditText editTextBox2 = (EditText) findViewById(R.id.your_editTextBox2_id);
EditText editTextBox3 = (EditText) findViewById(R.id.your_editTextBox3_id);
EditText editTextBox4 = (EditText) findViewById(R.id.your_editTextBox4_id);
EditText editTextBox5 = (EditText) findViewById(R.id.your_editTextBox5_id);

if((editTextBox1.getText().length() != 0) && (editTextBox2.getText().length() != 0) && (editTextBox3.getText().length() != 0) && (editTextBox4.getText().length() != 0) && (editTextBox5.getText().length() != 0)){
    //Start Activity
}
else{
    //else show an error or anything you want
}

Here, just replace the your_editTextBox1_id with the ID you set in your xml file.
If you want to check it when a Button is clicked, just add this code in the OnClick method of the button.


text:
Q: Prove a sequence converges almost surely
Let $X_1, X_2, \ldots$ be a sequence of random variables on a
  probability space $(\Omega, \mathcal{F}, P)$  such that $E(|X_{n}|)
 \leq 2^{-n}$. Prove that $X_{n}\rightarrow 0$ as $n\to\infty$

This is a follow up to a question I asked earlier here: Proving a sequence converges almost surely
Can somebody please explain to me how I can solve this problem using Borel-Cantelli Lemma and/or Markov's Inequality and/or Monotone Convergence? Note that the following question is slightly different than the one I asked in the earlier question (there are absolute values now). I'm trying to understand different ways to solve problems as I study for exams, but this problem has been giving me more trouble than usual.
I would really appreciate some help with this problem.

A: $P(|X_n| >2^{-n/2}) \leq 2^{n/2}|EX_n|\leq 2^{-n/2}$ so $\sum P(|X_n| >2^{-n/2}) <\infty$. By Borel Cantelli Lemma this shows that $X_n \to 0$ almost surely.
Borel Cantelli Lemma tells you that with probability $1$ we have $|X_n| \leq 2^{-n/2}$ for all $n$ sufficiently large. This implies that $X_n \to $ almost surely.

A: For any $\varepsilon > 0$,
$$\eqalign{\mathbb P\left(\bigcup_{n > N} \{|X_n|\ge\varepsilon\}\right)
&\le \sum_{n > N} \mathbb P\left(\{|X_n| \ge \varepsilon\}\right)
\cr&\le \varepsilon^{-1} \sum_{n > N} \mathbb E[X_n]\cr &\le \varepsilon^{-1} 2^{-N}\cr
&\to 0\ \text{as }N \to \infty }$$
Thus $\mathbb P(\limsup_{n \to \infty} |X_n| \ge \varepsilon) = 0$.


text:
Q: com.vaadin.server.ServiceException: java.lang.NullPointerException Please can you help with:
com.vaadin.server.ServiceException: java.lang.NullPointerException

it crashes mainLayout.setWidth("100%");
//***************************************
private void createUI() {
    final Window mainWindow = new Window("Raspberry Pi GPIO Control Center");
    VerticalLayout mainLayout = (VerticalLayout) mainWindow.getContent();
    setContent(mainLayout);
    System.out.println("1");
    mainLayout.setWidth("100%");
    System.out.println("2");
    mRefresher = new Refresher();
    mRefresher.setRefreshInterval(RefreshIntervalMilliSec);
    mRefresher.addListener(new RefreshListener() {
        private static final long serialVersionUID = 1L;

        @Override
        public void refresh(Refresher source) {
            periodicRefresh();
        }
    });
    mainLayout.addComponent(mRefresher);
    createTitle(mainLayout);
    mMainContentLayout = new VerticalLayout();
    mMainContentLayout.setWidth("100%");
    mainLayout.addComponent(mMainContentLayout);
    mainLayout.setComponentAlignment(mMainContentLayout, Alignment.MIDDLE_CENTER);
    createUIForUser();
}
//***************************************

A: mainWindow.getContent(); returns null because the Window has no default layout, so you get a NPE in mainLayout.setWidth("100%");
change the line
 VerticalLayout mainLayout = (VerticalLayout) mainWindow.getContent();

To
VerticalLayout content = new VerticalLayout();

and it should work.


text:
Q: Convert array of array into array of object with custom keys- React I am currently working on a array of array received from an endpoint and I want it to be converted into array of object. My array looks like bellow,

{
  "results": [
    [
      "ASIA",
      "INDIA",
      "2003",
      "Type 1",
      "Group 1",
      "Division 1"
    ],
    [
      "AFRICA",
      "Nigeria",
      "2004",
      "Type 2",
      "Group 2",
      "Division 2"
    ]
}

Code I have tried so far :

let finalArr = [];

  var objs = data.results.map((val) => {
    finalArr.push(Object.assign({}, val));
  });

console.log("Converted into Array of Object",finalArr)

The above code returns array of object with keys as 0,1,2,3 but ,I would like my array object to have custom keys and expected output is :

[
    {
      Region: "ASIA",
      Country: "INDIA",
      Year: "2004",
      Type: "Type 1",
      Group: "Group 1",
      Divison: "Division 1",
    },
    {
      Region: "AFRICA",
      Country: "Nigeria",
      Year: "2003",
      Type: "Type 2",
      Group: "Group 2",
      Divison: "Division 2",
    },
  ];

A: You can do it using the map function like this:

  const data = {
    results: [
      ["ASIA", "INDIA", "2003", "Type 1", "Group 1", "Division 1"],
      ["AFRICA", "Nigeria", "2004", "Type 2", "Group 2", "Division 2"]
    ]
  };
  const finalArr = data.results.map((el) => ({
    Region: el[0],
    Country: el[1],
    Year: el[2],
    Type: el[3],
    Group: el[4],
    Divison: el[5]
  }));
  console.log(finalArr);

or with custom keys:

  const customKeys = ["Region", "Country", "Year", "Type", "Group", "Division"];
  const data = {
    results: [
      ["ASIA", "INDIA", "2003", "Type 1", "Group 1", "Division 1"],
      ["AFRICA", "Nigeria", "2004", "Type 2", "Group 2", "Division 2"]
    ]
  };
  const finalArr = data.results.map((el) => {
    const obj = {};
    for (let i = 0; i < el.length; ++i) {
      obj[customKeys[i]] = el[i];
    }
    return obj;
  });
  console.log(finalArr);

A: You can try this piece of code
let keys = ["Region", "Country", "Year", "Type", "Group", "Division"];

const result = [
  ["ASIA", "INDIA", "2003", "Type 1", "Group 1", "Division 1"],
  ["AFRICA", "Nigeria", "2004", "Type 2", "Group 2", "Division 2"]
];

let final = [];

result.forEach(elem => {
  let obj = {}
  elem.forEach((param,i )=> {
      obj[keys[i]] = param
  });
  final.push(obj)
});

console.log(final)

A: Try This boss. If you are sure the data returned is in the right order of the country and so on
let finalArr = [];

  var objs = data.results.map((val) => {
     const obj = {
      Region: val[0],
      Country: val[1],
      Year: val[2],
      Type: val[3],
      Group: val[4],
      Divison: val[5],
    }
    return obj
  });
finalArray = objs

Since the returned values are in the array, It okay to get those return values using there indices

A: using Object.fromEntries and an array of keys makes this trivial

const data = {results: [["ASIA", "INDIA", "2003", "Type 1", "Group 1", "Division 1"],["AFRICA", "Nigeria", "2004", "Type 2", "Group 2", "Division 2"]]};

const keys = ["Region", "Cuntry", "Year", "Type", "Group", "Division"];
const result = data.results.map((el) =>
  Object.fromEntries(keys.map((key, i) => [key, el[i]]))
);

console.log(result);

A: You could do something like this, For example:
let arrs = [
    [1, 2],
    [3, 4],
    [5, 6],
    [7, 8]
];

let objs = arrs.map(x => ({
  key1: x[0],
  key2: x[1]
}));

console.log(objs);

A: This is dynamic solution with custom keys.

const data = [
  [
    "ASIA",
    "INDIA",
    "2003",
    "Type 1",
    "Group 1",
    "Division 1"
  ],
  [
    "AFRICA",
    "Nigeria",
    "2004",
    "Type 2",
    "Group 2",
    "Division 2"
  ],
];
const keys = ["Region", "Country", "Year", "Type", "Group", "Division"];

const finalArr = data.map((item) => {
  const _obj = {};
  for (let i = 0; i < item.length; ++i) {
    _obj[keys[i]] = item[i];
  }
  return _obj;
});
console.log(finalArr);

A:

let data = {
  "results": [
    [
      "ASIA",
      "INDIA",
      "2003",
      "Type 1",
      "Group 1",
      "Division 1"
    ],
    [
      "AFRICA",
      "Nigeria",
      "2004",
      "Type 2",
      "Group 2",
      "Division 2"
    ]
  ]
};

//custom keys array
let keys = ["Region", "Country", "Year", "Type", "Group", "Division"];

let finalArr = data.results.map((obj) => {
  //create array of key and value map for each object
  let keyValMap = keys.map((k, i) => [k, obj[i]]);
  return Object.fromEntries(keyValMap);
});

console.log("Converted into Array of Object", finalArr)

A:
Try with below code snippet

const data =  [
      ["ASIA", "INDIA", "2003", "Type 1", "Group 1", "Division 1"],
      ["AFRICA", "Nigeria", "2004", "Type 2", "Group 2", "Division 2"]
    ]

  const expectedOutput = data.map((el,i) => ({
    Region: el[i],
    Country: el[i],
    Year: el[i],
    Type: el[i],
    Group: el[i],
    Divison: el[i]
  }));
  console.log(expectedOutput);


text:
Q: How to get System Login and logoff time in ASP.net MVC4 Am new to ASP.net MVC4
I want to do program which can record the system login time and system logoff time along with IP address.
Thanks in advance....

A: To record Client IP Address use
HttpContext.Request.UserHostAddress //In Controller

or

HttpContext.Current.Request.UserHostAddress// In Classes

To record Login and Logout time.
Create a custom action filter class and record the datetime as given below.

[CustomFilter(CurrentAction="Login")]
public ActionResult Login()
{
  ...
}

[CustomFilter(CurrentAction="Logout")]
public ActionResult Logout()
{
  ...
}

public class CustomFilter : ActionFilterAttribute
{

    String CurrentAction {get; set;}

    void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
    {
        // TODO: Add your action filter's tasks here

      MyDBEntities storeDB = new MyDBEntities ();

      if(CurrentAction.Equals("Login"))
      {
           LoginDetail log = new LoginDetail ()
           {
              LoginTime= DateTime.Now,
              IP = filterContext.HttpContext.Request.UserHostAddress
           };
           storeDB.LoginDetails.Add(log);
      }
      else if(CurrentAction.Equals("Logout"))
      {
          LoginDetail log = new LoginDetail ()
          {
            LogoutTime= DateTime.Now,
            IP = filterContext.HttpContext.Request.UserHostAddress
          };
          storeDB.LoginDetails.Add(log);
      }

      storeDB.SaveChanges();
      this.OnActionExecuting(filterContext);
    }
}

A: A windows service or running your application at autostart would solve this.
Please take care of storing data, user session ending to safe handle storing it when the system gets shutdowned.
Please refer to the code here.
Create a windows service:
Or
Add your application to autostart


text:
Q: How to save condition to database I have database. there is table where is column. and column contains conditions > 10, < 10.
And I want to build procedure, that will create a select in loop.
How I can take condition from table and put it in SELECT * FROM TABLE WHERE @condition@?


text:
Q: How to decipher font encoding & install LaTeX font for use in MacWord? I want to know the font being used in my document. I saw on other posts that this can be determined using the following command:
   \showthefont

I also found LaTeX font encodings here: http://mirrors.ctan.org/macros/latex/base/encguide.pdf
When I compiled, this is what was given:
\T1/lmr/m/n/12

I understand 12 is referring to 12pt font size. However, I don't know how to interpret this output any further.
I want to know precisely what font is being used, because I am typesetting my references in Mac Word 2011 so I want to use the same font used elsewhere. This stems from difficulty in LaTeX formatting issues of the references section to meet my university's thesis requirements.

A: @Barbara & @David showed me to decipher the font.
`\expandafter\show\the\font`

and font was \T1/lmr/m/n/12=select font ec-lmr12
@ Christian Lindbig pointed me in the correct direction to install this for MacWord to find. It just took me awhile to actually execute it...
In the terminal:
`cd ~`
`cd ../../..`
`cd ./usr/local/texlive/2014/texmf-dist/fonts/opentype/public/lm`

The font I want: lmroman12-regular.otf
 `cp lmroman12-regular.otf ~`
 `mv lmroman12-regular.otf Desktop`

Double click the font, click install, and restart the computer. Now "Latin Modern Roman 12 regular" font is available to me in MacWord.


text:
Q: Keep the title in the first column instead of above both I'm using the following code:
\documentclass[twocolumn]{article}
\usepackage[landscape]{geometry}
\usepackage{lipsum, parskip}
\geometry{a4paper, twoside, left=1.5cm, right=1.5cm, marginparwidth=1.2cm, marginparsep=3mm, top=1cm, bottom=2cm}
\begin{document}
\title{Title\\
\large subtitle}
\date{2021}
\author{Author name}
\maketitle

\centering
\lipsum
\end{document}

which correctly renders to this:
However I'd like the title to be rendered above the first column only instead of above both, so that the second column may use the space that it would free. What would be a simple way to do that?

A: Don't use \maketitle but rather set the title(s) manually:

\documentclass[twocolumn]{article}

\usepackage[landscape]{geometry}
\usepackage{lipsum, parskip}
\geometry{
  paper=a4paper,
  twoside,
  hmargin=1.5cm,
  marginparwidth=1.2cm,
  marginparsep=3mm,
  top=1cm,
  bottom=2cm
}

\begin{document}

\begin{center}
  \LARGE % Title font size
  Title \par
  \large % Subtitle font size
  subtitle

  \vspace{1.5em}% Space between title and author

  \large % Author font size
  Author name

  \vspace{1em}% Space between author and date

  \large % Date font size
  \today
\end{center}

\lipsum

\end{document}

In the above document the center environment is used to set the title components, taken directly from \@maketitle regarding the formatting and spacing. Of course, you can adjust it to suit your needs.

A: You can patch \maketitle to do \@maketitle instead of
\twocolumn[\@maketitle]

but you also probably want that the title starts at the same level as the second column. So you also need to patch \@maketitle.
\documentclass[twocolumn]{article}
\usepackage[landscape]{geometry}
\usepackage{parskip}

\usepackage{etoolbox}

\usepackage{lipsum}

\geometry{
  a4paper,
  twoside,
  left=1.5cm,
  right=1.5cm,
  top=1cm,
  bottom=2cm,
  marginparwidth=1.2cm,
  marginparsep=3mm,
}

\makeatletter
\patchcmd{\maketitle}
 {\twocolumn[\@maketitle]}
 {\@maketitle}
 {}{}
\patchcmd{\@maketitle}
 {\null\vskip2em}
 {\hrule height0pt\vspace{-2\topsep}\vspace{-2\parskip}}
 {}{}
\makeatother

\begin{document}

\title{Title\\\large subtitle}
\date{2021}
\author{Author name}

\maketitle

\lipsum

\end{document}

A: Just use the code for printing the title (\@maketitle in the article class code).
% twocolprob.tex  SE 608946

\documentclass[twocolumn]{article}
\usepackage[landscape]{geometry}
\usepackage{lipsum, parskip}
\geometry{a4paper, twoside, left=1.5cm, right=1.5cm, marginparwidth=1.2cm, marginparsep=3mm, top=1cm, bottom=2cm}

%%%%% just print the title
\makeatletter
\let\onecolmaketitle\@maketitle
\makeatother
%%%%%
\begin{document}
\title{Title\\
\large subtitle}
\date{2021}
\author{Author name}
\onecolmaketitle
\centering  %%% to me this gives a strange look
\lipsum
\end{document}


text:
Q: Rotation of axes help? This is not a duplicate of my other question in regard to this.
I really am not understanding this rotation of axes stuff. If we want to graph a 45 degree shifted ellipse for example, we can think of it as in the XY plane as a normal ellipse but then when we convert the X's and Y's into equivalent forms in terms of x and y, the graph is graphed the way it was in the XY plane but now in the xy plane. It seems as if this would just give you the ellipse in the xy plane not shifted at all. Every X and Y is given a value in terms of x and y, so aren't these coordinates giving you the same exact thing?

A: Here is a picture of rotating an ellipse's axis:

Note that although it looks like $x = Y$ and $y = X$, this is not the case.  Notice that the coordinates $(x, y)$ are the rotated values of $(X, Y)$ through $\phi$ (which is $30^\circ$ for my picture):
$$
x = X\cos\left(\phi\right) - Y\sin\left(\phi\right) \\
y = X\sin\left(\phi\right) + Y\cos\left(\phi\right)
$$
...which would be $x  = \frac{\sqrt{3}X - Y}{2}$ and $y = \frac{X + \sqrt{3}Y}{2}$ for my picture ($\phi = 30^\circ$).


text:
Q: Draw three.js on canvas filled by raw WebGL I have a canvas which is filled by raw WebGL with primitives. A three.js library is supposed to draw stuff on the same canvas. Is this even possible? I get errors like:

WebGL: INVALID_OPERATION: uniformMatrix4fv: location is not from
  current program

In the past I used an overlay to achieve this. But the three.js stuff must be on the same canvas, because of future depth-tests and collision-detection. Is there a solution without migrating the raw WebGL stuff to three.js? Is this answer still up-to-date?


text:
Q: Classification: Calculating the significance of feature rankings? I know that classification performance can be tested for significance by permutation tests which permute the class labels. I wonder now if for ranked features (ie a ranking according to the features' relevance for the classification) a similar permutation test could be used to test this ranking for significance?
Thanks

A: If you'll repeat your training with multiple (independent!) training sets, then you'll have multiple realizations of the ranking. Then it's a much more standard problem, for which you can find references here at CV.
Regarding the single classification case, this isn't exactly what you asked for, but you can compare each weight with its null distribution produced by training with shuffled labels. See http://www.ncbi.nlm.nih.gov/pmc/articles/PMC3997040/
Having said that, you should ask yourself whether you are not over-interpreting classifier weights. Except for Naive Gaussian Bayes (in which the weights directly reflect the individual features' SNR as univariate measures would do), an individual feature's weight doesn't tell us much about the feature itself, since the weight can be understood only in the context of the all of the other features. The most evident case in which feature weight might be misleading is when a feature faithfully samples a noise source that masks signal in other features. A strong weight for this feature will reflect that it is subtracted from other features, not that it has any signal in it. See http://www.ncbi.nlm.nih.gov/pubmed/24239590
In my opinion, if you'd like to say something on individual features, use univariate methods.


text:
Q: Django get max date for each month in query I have a simple model with the fields date(DateTimeField) and value(IntegerField).
I would like the query this model for the value of the last day for each month (see example output)
date          value
2020-01-01    55
2020-01-02    12
2020-01-03    13
...
2020-01-31    34
...
2020-02-01    14
2020-02-02    54
2020-02-03    16
...
2020-02-28    23
...
2020-03-01    16
2020-03-02    23
2020-03-03    16
...
2020-03-31    7

Desired output:
date          value
2020-01-31    34
2020-02-28    23
2020-03-31    7

So far, I've managed to to this (but it involves querying the database a lot, so I'd prefer a less database intensive solution)
dates = MyModel.objects.annotate(
    month=TruncMonth('date')
).distinct()

for date in dates:
    end_value = MyModel.objects.filter(date__month=date['month'].month).latest('date')
    print(end_value)

A: You may try this:
MyModel.objects.filter(
    #prepare subquery which has max dates per month
    #and limit resultset only to those dates
    date__in = Subquery(
        MyModel.objects.annotate(
            truncated_to_month = TruncMonth('date') #used to group by truncated to month date
        ).values(
            'truncated_to_month'
        ).annotate(
            max_date_per_month = Max('date') #used to get max date per month i.e. per group
        ).values(
            'max_date_per_month' #only max date per month, so it may be used in __in lookup
        )
    )
).values(
    'date' #group by limited to max date per month
).annotate(
    max_value = Max('value') # and finally select max value per date
).values(
    'date','max_value'
)


text:
Q: Get domain from url (Ideal function)
Possible Duplicate:
how to get domain name from URL
PHP Getting Domain Name From Subdomain

As i figured out a lot from the examples from the google there are not so universal for getting the domain name from url because of:

*

*www

*subdomains

*second-level domain (co.uk)

Is there any solution, that can get universally domain.

A: I use the following regex in Ruby and it works for me:
/(https?:\/\/([-\w\.]+)+(:\d+)?(\/([-\w\/_\.]*(\?\S+)?)?)?)/

Example: http://rubular.com/r/wyR7yvKT6q
But what you mean under domain? The above regexp extracts domain correctly
http://my.subdomain.ko.uk
to
my.subdomain.ko.uk <-- this is domain

Or you can use:
.*([^\.]+)(com|net|org|info|coop|int|co\.uk|org\.uk|ac\.uk|uk|__and so on__)$
/^(?:www\.)?(.*?)\.(?:com|au\.uk|co\.in)$/


text:
Q: How to include a view in another view in cakephp I have an add.ctp file, which will enable the user to add new entries,
there is another view.ctp file which will list all the existing
entries from the database.
How would I include these existing entries within the add view page,
So that user should be able to view the existing entries at the bottom
of the page when he is making a new entry from add page?
Thanking you

A: You could extract the view code you want to use in both views into an element.

A: or load the view underneath through an ajax call when an entry is clicked.


text:
Q: Pandas - converting datamonth yyyymm to datetime yyyy-mm-dd I have a dataframe in pandas with some columns with dates in the following format

dates

202001

202002

I want to convert them to the following format

dates

2020-01-01

2020-02-01

Could anyone assist with converting the date format? Thanks

A: If need datetimes use to_datetime with format='%Y%m':
df['dates'] = pd.to_datetime(df['dates'], format='%Y%m')

A: You may use to_datetime here:
df["dates"] = pd.to_datetime(df["dates"] + '01', format='%Y%m%d', errors='ignore')

Note that your current text dates are year month only, so I concatenate 01 to the end of each one to form the first of the month, for each date.

A: Try this:
df['dates'] = df['dates'].astype(str)
df['dates'] = pd.to_datetime(df['dates'].str[:4] + ' ' + df['dates'].str[4:])
print(df)

Output:
       dates
0 2020-01-01
1 2020-02-01


text:
Q: Master don't receive the minon key Well, i installed salt-minion in some computers, but it just don't send any key to be acepted, i reinstall the salt-minion three times in each computer, and it doesn't work, somebody can help?
No minions matched the target. No command was sent, no jid was assigned.
ERROR: No return received


text:
Q: Mustache Template usage in Dart Fairly recent to web programming and all apologies for asking a basic question.
In the test.dart file, a template is created and populated as below
import 'dart:html';
// IMPORT MUSTACHE FOR TEMPLATES
import 'package:mustache/mustache.dart' as mustache;

function loadData()
{
 // some script .....
  output = template.renderString({
 'data_cell': [
     {'event_title': TitleOne,'event_desc' : Desc},]});
 }

In the test.html file, how can I insert the "output" in the below "data_cell" div.

Application

A: querySelector('div.data_cell').appendHtml(output);

or
var nodeValidator = new NodeValidatorBuilder()
    ..allowHtml5()                            // according to your requirements
    ..allowElement('a', attributes: ['href']) // - " -
    ..allowElement('img', attributes: ['src']); // - " -
querySelector('div.data_cell').append(new Element.html(output, validator: nodeValidator);


text:
Q: Oracle: find place in code where update was called The problem is: my procedure updates value in specific column and few miliseconds later this value is null. I try to find place where value from specific column is being changed to null.
Is it possible to check which procedure/trigger calls update on the column in Oracle DB?

A: Try this one:
dbms_output.put_line(dbms_utility.format_call_stack);

You can put this code in trigger or in procedure/function code where you think your field is changing a value.

A: You can create a trigger as below if i understood you correctly. Here I am checking if the new value of the column of your table is different than old value, then display the message that Updat occured on Column . You can extend the checking condition on all the columns of your table in when clause of trigger shown below.
CREATE OR REPLACE TRIGGER chk
 BEFORE INSERT ON Your_Table
 FOR EACH ROW
WHEN (
new.col1 <> old.col1
OR new.col1 is NULL
      )
 begin
   dbms_output.put_line('Updat occured on Column');
  end;
/


text:
Q: Canonical connection on $CP^n$ I have heard something along the lines of "There is a canonical $U(1)$ connection on $CP^n$" and I am trying to understand what that means.
First I suppose that the sentence refers to a line bundle over $CP^n$, possibly the tautological line bundle.
Second why is there a preferred connection?
I was thinking that $CP^n$ can be realised as the homogenous space $\frac{U(n+1)}{U(1)\times U(n)}$. Hence the Maurer-Cartan form on $U(n+1)$ descends to a unique $U(n+1)$-invariant connection form on $CP^n$ which however takes values in $U(1)\times U(n)$. I was thinking that one way to get a $U(1)$ connection would be to follow the prescription described in
https://math.stackexchange.com/questions/875705/a-construction-on-principal-bundles.
Namely one constructs the bundle $U(n+1) \times_{\rho} U(1)$ where the action $\rho: U(1)\times U(n) \rightarrow U(1)$ is simply projection onto the first factor followed ny $U(1)$ multiplication.
Would such a construction work? Is there a simpler way of thinking of the canonical connection on the tautological (?) line bundle over $CP^n$?

A: The standard action of $U(n+1)$ on $\mathbb C^{n+1}$ preserves the unit sphere $S^{2n+1}$ and commutes with the action of $U(1)$ (multiplication of vectors by complex unit scalars). The quotient by $U(1)$ is $\mathbb C P^n$ and $S^{2n+1}\to \mathbb C P^n$ is a principal $U(1)$ bundle, on which $U(n+1)$ acts by bundle automorphisms. Now the claim is that there is a unique $U(1)$ connection on $S^{2n+1}\to \mathbb C P^n$  which is $U(n+1)$-invariant.
Proof: since $U(n+1)$ acts transitivly on $S^{2n+1}$ it is enough to show that at some point  $x\in S^{2n+1}$ there exists a unique complement in $T_xS^{2n+1}$ to the tangent at $x$ of the $U(1)$-orbit through $x$  which is invariant under the stabilizer of $x$ in $U(n+1)$. Let the point be $x=(0,\ldots, 0, 1)$. Then $T_xS^{2n+1}=\mathbb C^n\oplus i\mathbb R$, the 2nd summand is the tangent space at $x$ to the $U(1)$ orbit through $x$, the stabilizer is $U(n)$,  acting on $T_xS^{2n+1}$ by the standard representation on the 1st summand and trivially on the 2nd. Since these are non-isomorphic irreducible $U(n)$-representations, it follows, by Schur lemma, that this is the unique $U(n)$-invariant decomposition of $T_xS^{2n+1}$.  Hence $\mathbb C^n\oplus 0$ is the unique $U(n)$ invariant complement in $T_xS^{2n+1}$ to $0\oplus i\mathbb R$. It follows that there is a unique $U(n+1)$-invariant $U(1)$-connection on the principal $U(1)$-bundle $S^{2n+1}\to \mathbb C P^n$. Its horizontal distribution is  the orthogonal complement of
the tangents to the $U(1)$-orbits.


text:
Q: Running FN Server on a Openshift Cluster without --privileged flag We are trying to deploy FN server in an Openshift Cluster without privileged security context, only enabling root mode (not privileged), but we are getting this error:
`
/usr/local/bin/preentry.sh: set: line 14: can't access tty; job control turned off
mount: permission denied (are you root?)
Could not mount /sys/kernel/security.
AppArmor detection and --privileged mode might break.
mount: permission denied (are you root?)
time="2022-12-09T12:03:59Z" level=info msg="Setting log level to" fields.level=DEBUG
time="2022-12-09T12:03:59Z" level=info msg="Registering data store provider 'sql'"
time="2022-12-09T12:03:59Z" level=debug msg="creating new datastore" db=sqlite3
time="2022-12-09T12:03:59Z" level=debug msg="mysql does not support sqlite3"
time="2022-12-09T12:03:59Z" level=debug msg="postgres does not support sqlite3"
time="2022-12-09T12:03:59Z" level=debug msg="mysql does not support sqlite3"
time="2022-12-09T12:03:59Z" level=debug msg="postgres does not support sqlite3"
time="2022-12-09T12:03:59Z" level=info msg="Connecting to DB" url="sqlite3:///app/data/fn.db"
time="2022-12-09T12:03:59Z" level=info msg="datastore dialed" datastore=sqlite3 max_idle_connections=256 url="sqlite3:///app/data/fn.db"
time="2022-12-09T12:03:59Z" level=debug msg="mysql does not support sqlite3"
time="2022-12-09T12:03:59Z" level=debug msg="postgres does not support sqlite3"
time="2022-12-09T12:03:59Z" level=info msg="agent starting cfg={MinDockerVersion:17.10.0-ce ContainerLabelTag: DockerNetworks: DockerLoadFile: DisableUnprivilegedContainers:false FreezeIdle:50ms HotPoll:200ms HotLauncherTimeout:1h0m0s HotPullTimeout:10m0s HotStartTimeout:5s DetachedHeadRoom:6m0s MaxResponseSize:0 MaxHdrResponseSize:0 MaxLogSize:1048576 MaxTotalCPU:0 MaxTotalMemory:0 MaxFsSize:0 MaxPIDs:50 MaxOpenFiles:0xc4201b5bf8 MaxLockedMemory:0xc4201b5c10 MaxPendingSignals:0xc4201b5c18 MaxMessageQueue:0xc4201b5c20 PreForkPoolSize:0 PreForkImage:busybox PreForkCmd:tail -f /dev/null PreForkUseOnce:0 PreForkNetworks: EnableNBResourceTracker:false MaxTmpFsInodes:0 DisableReadOnlyRootFs:false DisableDebugUserLogs:false IOFSEnableTmpfs:false EnableFDKDebugInfo:false IOFSAgentPath: IOFSMountRoot: IOFSOpts: ImageCleanMaxSize:0 ImageCleanExemptTags: ImageEnableVolume:false}"
time="2022-12-09T12:03:59Z" level=info msg="no docker auths from config files found (this is fine)" error="open /root/.dockercfg: no such file or directory"
time="2022-12-09T12:03:59Z" level=fatal msg="couldn't connect to docker daemon" error="Get http://unix.sock/_ping: dial unix /var/run/docker.sock: connect: no such file or directory"

`
Is there any way to deploy FN server without privileged mode?


text:
Q: chef installing node, npm and packages and running them I'm installing node and npm via the 'nodejs' cookbook and I'm including the recipe via
include_recipe "nodejs::npm"

I've installed the packages I want like so:
%w( dateformat aws2js optparse cloudwatch2graphite).each do |npm_package|
    nodejs_npm npm_package
end

and chef says that it's installed them successfully.
When I log onto the box and type npm list it simply returns empty no matter whether I'm as user root or user vagrant.
Why is the package list empty? Is it a user context issue?
Secondly how do I run a globally installed package such ascloudwatch2graphite.
When it's installed as a global package, do I just do
node cw2graphite.js

from any where to get it to run?
Bonus Points:
Just out of curiosity, what user does chef run as both on vagrant and on a box?

A: After poking around I realised what I was doing wrong.
with npm to do anything with a global package you have to use -g it's obvious in hindsight but I'm not much a node person so It's an easy mistake to make.
So to list global packages it's:
npm -g list

However whilst to run a script your supposed to do:
npm -g run <package-name> <package-script>

Nothing happened when I tried to use it to start cloudwatch2graphite.
That said, I was able to get it working by doing:
node `npm -g root`/<package-name>/<script-name>.js


text:
Q: Crash during 12.04 upgrade, "Broken pipe", cannot boot Now when I switch on the computer, only black screen with the following message shows up:
"Could not write byte: broken pipe"
.....
Starting network connection
Stopping network connection
(the above phrases repeat many times)
Also something like:
Stopping System V runlevel
I cannot type on the screen. It doesn't proceed onto anything. Just hanging there.
Please help! If there's anything I can do to enter and get my files.
Thank you!

A: It happened to me also. I'm not sure what was the source of this as I did an upgrade, installed some apps and changed themes and icons. Deleting configuration folders from home folder solved my problem, so you should give it a try.

*

*Press CTRL+ALT+F1 key combination.

*Log in using TTY.

*Delete those folders: .config, .cache, .dbus, .gfvs, .local with rm -R command.

Example:
rm -R /home/user/.config

I'm not sure if all listed folders should be deleted, so you can try one by one. If it solve your problem and you'll able to log in, be prepared for tons of Apport windows ;)

A: I had the sam problem which is caused by an error in var/lib/dpkg/status from a third party package. In this file the status of the update is saved and if there is an error somewhere the following packages are not installed.
Please follow the following steps which helped me (original source: http://forum.ubuntuusers.de/topic/dpkg-configure-a-schlaegt-fehl/ ) :

*

*boot normally, not recovery mode and click Str+Alt+F1 to start the terminal input.

*log in with your password and username

*type: sudo apt-get -f install

*you will get a message saying that there is an error in var/lib/dpkg/status and a line where the error is located.

*use the nano editor (sudo nano -w) to find the package around the line named in the error message and delete the package which causes the problem (more than one line). be careful and only delete the package which causes the problem!

*likewise delete the same package from the file /var/lib/dpkg/available
-run sudo apt-get -f install again and it will run through this time.

this solution is from http://forum.ubuntuusers.de/topic/dpkg-configure-a-schlaegt-fehl/


text:
Q: Sort a list of dict by key. If key is missing, assume a consecutive numbering I want so sort a list of dictionaries by the key "pos". However, if "pos" is missing in the dict, I want to keep the order of the item(s) and assume that "pos" is the item's 1-based index in the list.
This is working fine, as long as all list items are different:
L = [
    {   "id": "1" }, # assume pos: 1
    {   "id": "2" }, # assume pos: 2
    {   "id": "3" }, # assume pos: 3
    {   "id": "4" }, # assume pos: 4
    {   "id": "ZZZ" }, # assume pos: 5
    {   "id": "AAA" }, # assume pos: 6
    {   "id": "ABC", "pos": 3.2 },
    {   "id": "XYZ", "pos": 3.1 },
]

s = sorted(L,key=lambda i:i.get("pos",L.index(i)+1))
print(s)

Output:
[{'id': '1'}, {'id': '2'}, {'id': '3'}, {'id': 'XYZ', 'pos': 3.1}, {'id': 'ABC', 'pos': 3.2}, {'id': '4'}, {'id': 'ZZZ'}, {'id': 'AAA'}]

But it fails if I have multiple of the same items, because then list.index will return the first occurence, rather than the "assumed position".
L = [
    {   "id": "1" }, # assume pos: 1
    {   "id": "1" }, # assume pos: 2
    {   "id": "1" }, # assume pos: 3
    {   "id": "1" }, # assume pos: 4
    {   "id": "1" }, # assume pos: 5
    {   "id": "AAA" }, # assume pos: 6
    {   "id": "ABC", "pos": 3.2 },
    {   "id": "XYZ", "pos": 3.1 },
]

s = sorted(L,key=lambda i:i.get("pos",L.index(i)+1))
print(s)

Actual output:
[{'id': '1'}, {'id': '1'}, {'id': '1'}, {'id': '1'}, {'id': '1'}, {'id': 'XYZ', 'pos': 3.1}, {'id': 'ABC', 'pos': 3.2}, {'id': 'AAA'}]

Expected output:
[{'id': '1'}, {'id': '1'}, {'id': '1'}, {'id': 'XYZ', 'pos': 3.1}, {'id': 'ABC', 'pos': 3.2}, {'id': '1'}, {'id': '1'}, {'id': 'AAA'}]

How can the sorting be changed to return the expected output?
Note: the item IDs are not guaranteed to be in any order, that means 1,2,3,4,AAA,ABC,XYZ have been chosen arbitrarily.

A: Use enumerate:
L = [
    {"id": "1"},  # assume pos: 1
    {"id": "2"},  # assume pos: 2
    {"id": "3"},  # assume pos: 3
    {"id": "4"},  # assume pos: 4
    {"id": "ZZZ"},  # assume pos: 5
    {"id": "AAA"},  # assume pos: 6
    {"id": "ABC", "pos": 3.2},
    {"id": "XYZ", "pos": 3.1},
]

result = [e for _, e in sorted(enumerate(L, 1), key=lambda x: x[1].get("pos", x[0]))]

print(result)

Output
[{'id': '1'}, {'id': '2'}, {'id': '3'}, {'id': 'XYZ', 'pos': 3.1}, {'id': 'ABC', 'pos': 3.2}, {'id': '4'}, {'id': 'ZZZ'}, {'id': 'AAA'}]

For the duplicates example:
L = [
    {"id": "1"},  # assume pos: 1
    {"id": "1"},  # assume pos: 2
    {"id": "1"},  # assume pos: 3
    {"id": "1"},  # assume pos: 4
    {"id": "1"},  # assume pos: 5
    {"id": "AAA"},  # assume pos: 6
    {"id": "ABC", "pos": 3.2},
    {"id": "XYZ", "pos": 3.1},
]

result = [e for _, e in sorted(enumerate(L, 1), key=lambda x: x[1].get("pos", x[0]))]

print(result)

Output
[{'id': '1'}, {'id': '1'}, {'id': '1'}, {'id': 'XYZ', 'pos': 3.1}, {'id': 'ABC', 'pos': 3.2}, {'id': '1'}, {'id': '1'}, {'id': 'AAA'}]

A perhaps cleaner alternative is to use itertools.count:
from itertools import count

counter = count(1)

result = sorted(L, key=lambda x: x.get("pos", next(counter)))
print(result)

A: We can do something like this:
d = [
    {"id": "1"}, # assume pos: 1
    {"id": "1"}, # assume pos: 2
    {"id": "1"}, # assume pos: 3
    {"id": "1"}, # assume pos: 4
    {"id": "1"}, # assume pos: 5
    {"id": "AAA"}, # assume pos: 6
    {"id": "ABC", "pos": 3.2},
    {"id": "XYZ", "pos": 3.1},
]

def my_compare(x):
    if 'pos' in x[1]:
        return x[1]['pos']
    return x[0] + 1

sorted_d = [x[1] for x in sorted(enumerate(d), key=my_compare)]

expected_output = [
    {'id': '1'},
    {'id': '1'},
    {'id': '1'},
    {'id': 'XYZ','pos': 3.1},
    {'id': 'ABC','pos': 3.2},
    {'id': '1'},
    {'id': '1'},
    {'id': 'AAA'},
]
assert sorted_d == expected_output


text:
Q: Recycle App Pool Programmatically in IIS 10 / Windows Server 2019 I'm trying to create a function that will allow a user to reset/recycle an application pool on demand in order to reload updated IIS site settings, however I'm running into a permissions issue anytime I try to use a ServerManager function.
ServerManager serverManager = new ServerManager();
ApplicationPool appPool = serverManager.ApplicationPools[site_list.SelectedValue];
if (appPool != null) {
    if (appPool.State == ObjectState.Stopped) {
        appPool.Start();
    } else {
        appPool.Recycle();
    }
}

Any time I run the code, I get the following error:

Filename: redirection.config Error: Cannot read configuration file due
  to insufficient permissions
Description: An unhandled exception occurred during the execution of
  the current web request. Please review the stack trace for more
  information about the error and where it originated in the code.
Exception Details: System.UnauthorizedAccessException: Filename:
  redirection.config Error: Cannot read configuration file due to
  insufficient permissions
ASP.NET is not authorized to access the requested resource. Consider
  granting access rights to the resource to the ASP.NET request
  identity. ASP.NET has a base process identity (typically
  {MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6 and IIS 7, and
  the configured application pool identity on IIS 7.5) that is used if
  the application is not impersonating. If the application is
  impersonating via , the identity will be
  the anonymous user (typically IUSR_MACHINENAME) or the authenticated
  request user.
To grant ASP.NET access to a file, right-click the file in File
  Explorer, choose "Properties" and select the Security tab. Click "Add"
  to add the appropriate user or group. Highlight the ASP.NET account,
  and check the boxes for the desired access.

I've tried granting read permissions to the redirection.config file to any/all of the following users with no change:

*

*ASPNET

*NETWORK SERVICE

*IUSR

*IIS_IUSRS

Anyone happen to have any insight on how to recycle an AppPool through code?

A: I can get it work when I set application pool identity to LocalSystem and anonymous authentication->Edit->Use application pool identity.

I think if you don't want to use LocalSystem, then you have to grant special permission for C:\Windows\System32\inetsrv\config folder and your application root folder. It will also reduce the security of your computer.
Microsoft Process monitor could help you grant NTFS permission. You could add a filter for "process name=w3wp.exe" and "result=access denied".
https://learn.microsoft.com/en-us/sysinternals/downloads/procmon


text:
Q: Windows universal URI format exception I'm working on a windows universal app. I want to show the user an image. The image is located in a subfolder within my assets folder, in both the phone and the windows folder.
I'm trying to put the image in a variable in a class that is in the shared folder. I am continously getting uri exceptions.
My code looks like this:
Uri uri = new Uri("/Assets/Image/avatar_anonymous.png");
chat_profilepicture_Bitmap = new BitmapImage(uri);

I've tried different urls, with and without capitals, the entire path "C://blablabla", and many more. Nothing seems to be working. I have also tried: pack://application:,,,/ which was suggested by multiple stackoverflow threads. But no luck there.
I'm thinking the problem lies in the image being in another project, is there a way to get around this? Or if this isn't the problem, what am I doing wrong?

A: Try this
Uri uri = new Uri("ms-appx:///Assets/Image/avatar_anonymous.png");

Hope this helps

A: In Windows Universal App, You can use Image Resource with ms-appx or ms-appdata.

*

*ms-appx  means using resource in App Package

*ms-appdata menas using resource in floder of local, temp or roam.

So the uri can be written like this:
new Uri("ms-appx:///Assets/Image/avatar_anonymous.png", UriKind.Absolute);

or
new Uri("ms-appdata:///LocalFolderName/demo.png", UriKind.Absolute);


text:
Q: Get text from multiple classes in scrapy I want to crawl data from a website. I use this code
import scrapy

class KamusSetSpider(scrapy.Spider):
    name = "kamusset_spider"
    start_urls = ['http://kbbi.web.id/abadi']

    def parse(self, response):
        SET_SELECTOR = '.tur highlight'
        for brickset in response.css(SET_SELECTOR):
            yield {
                'name': brickset.css(SET_SELECTOR).extract_first(),
            }

and this is the inspect element:

I want to get every text in the red oval, like mengabadi, mengabadikan, etc. There are multiple class in the 'b' tag => tur highlight. But, I have not get any result.
What's the problem? How to solve it?
I have change my code become this:
def parse(self, response):
        for kamusset in response.css("div#d1"):
            text = kamusset.css("div.sub_17 b.tur.highlight::text").extract()
            print(dict(text=text))

but still not working. It return null.

A: Selector .tur highlight means - select elements highlight inside all elements with class tur.
To select elements with multiple classes use selector without whitespaces :
SET_SELECTOR = '.tur.highlight'

A: As far I understood your question, you want to extract text from the different place (tags) with different class names in single css_selector.
text = kamusset.css("div.sub_17::text, b.tur.highlight::text").extract()

This will work, surely

A: This will do!!
text : Selector(text=response.body).xpath('//b[@class="tur highlight"]/text()').extract()

Will return list with all occurrences.


text:
Q: how to kill command line process start with child_process nodejs how can i stop it, it keep running after i stop nodejs. I try process.kill() but not working
const process = require('child_process')
const child = process.exec('ping 8.8.8.8 -t')
setTimeout(()=>child.kill(2),10000)

after a few hour reading nodejs docs, i found this for who have same my problem
const process = require('child_process')
const child = process.execFile('ping 8.8.8.8',['-t'],{cwd:'your working direct'})
setTimeout(()=>child.kill(2),10000)//now kill() working

A: I modified your code as below to flush out the error:
const process = require('child_process')
const child = process.spawn('ping 8.8.8.8 -t') // instead of process.exec
setTimeout(() => {
    console.log(child.kill(2)) // --> false == failed
}, 10000);

child.on('error', (code, signal) => {
    console.log(`${code}`) // --> Error: spawn ping 8.8.8.8 -t ENOENT
});

The ping command requires an argument after the -t ( as per terminal: ping: option requires an argument -- t


text:
Q: Можно ли в Java рисовать на форме при помощи paint() с включенным setUndecorated()? При включении setUndecorated() на форме ничего нельзя отрисовать.
A: Это как? setUndecorated() выключает только стандартную рамку, свернуть, развернуть, закрыть, а рисуешь ты на фрейме.


text:
Q: Recover HDFS Data Files of Internal Hive Table after dropping table I accidentally dropped an Hive Internal Table, inturn all the files associated with the internal table ( xyz_table) got automatically deleted from HDFS location ( /hive/warehouse/abc_mes.db/xyz_table/ )
We are using Azure HDInsight Cluster with Azure File Storage ( AFS ) as storage layer.
Can someone advise on how to recover the files on HDFS ..I checked in trash, i could see very old files like 4 months old files there, but could not find any recent files under /home//.trash ...
Appreciate if someone can guide
Cheers

A: It's being long time after this question asked but I faced same issue and I want to share my experience.
First of all, I use Cloudera for HDFS-Hive-Hue. I dropped a table which associated  with HDFS location, and yes, I couldn't find files in /home/.Trash but in /user/admin/.Trash/Current/
It may help someone in the future.

A: For CDH, CDP platform, The dropped table if HDFS Trash is configured, will be stored in Trash directory of the user which dropped the file.
For example, for user abc, the HDFS Trash directory will be /user/abc/.Trash.
Under this directory,  there will be directory structure like Hive warehouse directory structure which you dropped.
For example, for table dropped from sample_db.test_table by user abc, the HDFS files will be under /user/abc/.Trash/Current/user/hive/warehouse/sample_db.db/test_table provided that Hive warehouse directory is /user/hive/warehouse.
For Azure File Storage, it depends if the Trash is configured somehow as it's based on object storage.


text:
Q: Hibernate session.update() vs update query? Hi if want to update some specific columns of a row so should i use an update query in hibernate or simply use the session.update() method of hibernate. Just came to know about
@org.hibernate.annotations.Entity(
        dynamicUpdate = true

annotation if set i can update specific columns. I haven't used this before so just want to know if there are any norms of using this or not. Just need your help on making a decision on this. Which approach will be better?

A: With dynamic session update off, Hibernate will cache all of possible queries for all entities. So Hibernate doesn't have to generate SQL each time it wants to update an entity.
When it's on, Hibernate will always generate SQL queries when requested, instead of caching it. So it's lighter for your database, but it becomes heavier for Hibernate.
When should you use Hibernate Dynamic Update ? If you have a huge table with tons of columns, caching all queries for all entities will cost much more memory than usual. So you could turn dynamic update on to improve performance. Also, if you are debugging, dynamic update will give you more readable queries because only modified column will appear in your update statement.
Should you use update queries or session update ? Update queries are less readable and harder to maintain (for instance if a field name has changed, you have to change all your queries whereas session update won't be impacted).


text:
Q: rq queue always empty I'm using django-rq in my project.
What I want to achieve:
I have a first view that loads a template where an image is acquired from webcam and saved on my pc. Then, the view calls a second view, where an asynchronous task to process the image is enqueued using rq. Finally, after a 20-second delay, a third view is called. In this latter view I'd like to retrieve the result of the asynchronous task.
The problem: the job object is correctly created, but the queue is always empty, so I cannot use queue.fetch_job(job_id). Reading here I managed to find the job in the FinishedJobRegistry, but I cannot access it, since the registry is not iterable.
from django_rq import job
import django_rq
from rq import Queue
from redis import Redis
from rq.registry import FinishedJobRegistry

redis_conn = Redis()
q = Queue('default',connection=redis_conn)
last_job_id = ''

def wait(request): #second view, starts the job
    template = loader.get_template('pepper/wait.html')
    job = q.enqueue(processImage)
    print(q.is_empty()) # this is always True!
    last_job_id = job.id # this is the expected job id
    return  HttpResponse(template.render({},request))

def ceremony(request): #third view, retrieves the result
    template = loader.get_template('pepper/ceremony.html')
    print(q.is_empty()) # True
    registry = FinishedJobRegistry('default', connection=redis_conn)
    finished_job_ids = registry.get_job_ids() #here I have the correct id (last_job_id)
    return HttpResponse(template.render({},request))

The question: how can I retrieve the result of the asynchronous job from the finished job registry? Or, better, how can I correctly enqueue the job?

A: I have found an other way to do it: I'm simply using a global list of jobs, that I'm modifying in the views. Anyway, I'd like to know the right way to do this...


text:
Q: How to make the toggle menu close on click and get me to the beginning of the section correctly? When I add the code below, the menu even closes when I click, but that doesn't get me to the starting point of the section. This takes me a few pixels down, unlike in my original code without adding the script.
script in question:
$('.navbar-nav>li>a').on('click', function(){
    $('.navbar-collapse').collapse('hide');
});

Could someone show me where I'm going wrong? How do I close the toggle menu in mobile by correctly clicking and descending to the beginning of the section and not a few pixels down. The correct behavior happens without this code that closes the menu on click, but would like to have a menu that closes automatically on click. Does anyone give a light?
MY ORIGINAL CODE WORKING: https://www.codeply.com/go/gD2F6iVFm0
PROBLEM CODE: https://www.codeply.com/go/eIKdPVCBih
Gif with the problem below - at the end of the click, I show where it takes me and then climb to the place I would like it to take me.
https://imgur.com/a/S2FZwJL#Sa3boQF

A: I have ran the code you have provided on Chrome 76 on MacOS, but I could not reproduce the issue. On both examples, upon adding the following snippet the website appears to be working correctly.
$('.navbar-nav>li>a').on('click', function(){
    $('.navbar-collapse').collapse('hide');
});

Are you sure the problem does not lie in the browser rendering the website differently or mistreating the script? Could you provide more details on your test environment?

A: Your problem is not related to closing the menu.
The issue is that the height of the navbar is different depending on the screen width. You have an offset of 60 pixels hardcoded into your scroll script. This works fine when the screen is desktop width, but it's not quite right on smaller screens.
To make sure it's always accurate, you can get the height of the navbar right before scrolling.
Here's an updated version of your scroll script:
$('a[href*="#"]:not([href="#"])').click(function() {
  var target = $(this.hash);
  var offset = $('.navbar').outerHeight();

  $('html, body').animate({
    scrollTop: target.offset().top - offset
  }, 900)
});

The offset variables replaces 60 and gets the height using .outerHeight() to make sure it's always accurate.


text:
Q: Webpage Download Time and export to CSV via batch file I am trying to set up a batch file to get webpage download time using curl command and export to CSV or text file.
I am using the following curl command:
curl http ://myurl.com -w %{time_total}\n -o NUL -s

The command above works when using it in cmd and will provide a response ex - 0.188000.
However, when I am using the command via a batch file and try to export using the following, it does not work. Instead of .1888000, I get {time_total}.
@echo on
ECHO.
totaltimeresponse
ECHO.
SET PATH=%PATH%;C:\software\curl
ECHO.
curl http ://myurl.com -w %{time_total}\n -o NUL -s >> total-time.txt
ECHO.

This is my first time working with curl and batch files, so I am not sure what is happening. I have researched and researched, but I still don't know what wrong I have made.
Any ideas or suggestions?

A: I don't have a Windows machine to test, but try this --should work.
@echo on
ECHO.
totaltimeresponse
ECHO.
SET PATH=%PATH%;c:\software\curl
ECHO.
curl http ://myurl.com -w %%{time_total}\n -o NUL -s >> total-time.txt
ECHO.


text:
Q: Why won't Highcharts accept UTC value from my JSON? I'm trying to get some JSON formatted data from a COSM feed into a simple chart, but am having trouble doing so. I'm not sure if I'm misunderstanding how the series array works (even after reviewing the documentation on it.
This is my code with experiments in it (I eventually want to get the JSON data streamed in through a loop, but for now I just manually tried to push a second data point).
$(document).ready(function(){
            var options = {
                    chart: {
                        renderTo: 'container',
                        type: 'line',
                        marginRight: 130,
                        marginBottom: 25
                    },
                    title: {
                        text: 'Temperature',
                        x: -20 //center
                    },
                    xAxis: {
                        //type: 'datetime',
                    },
                    yAxis: {
                        title: {
                            text: 'Temperature (°C)'
                        },
                        plotLines: [{
                            value: 0,
                            width: 1,
                            color: '#808080'
                        }]
                    },
                    tooltip: {
                        formatter: function() {
                                return ''+ this.series.name +'
'+
                                this.x +': '+ this.y +'°C';
                        }
                    },
                    legend: {
                        layout: 'vertical',
                        align: 'right',
                        verticalAlign: 'top',
                        x: -10,
                        y: 100,
                        borderWidth: 0
                    },
                    exporting: {
                        enabled: false
                    },
                    series: [{"name":"Temperature", "data":[]}]
            };
            $.getJSON('http://api.cosm.com/v2/feeds/79903.json?key=dNSiSvXZtR6QBUqbzll4CCgnngGSAKxIQVFSeXBneGpqWT0g', function(data)
            {
                var xval = data.datastreams[7].at;
                var yval = parseFloat(data.datastreams[7].current_value);
                alert(xval);
                alert(yval);
                var pointChart = new Array(xval, yval);
                options.series[0].data.push(pointChart);
                xval = data.datastreams[2].at;
                yval = parseFloat(data.datastreams[2].current_value);
                pointChart = [xval, yval];
                options.series[0].data.push(pointChart);
                //options.series[0].data.push(data.datastreams[7].at, 25);
                alert(options.series[0].data[0]);
                alert(options.series[0].data[1]);
            });
            var chart = new Highcharts.Chart(options);
        });

JSON looks like this:
{
   "version" : "1.0.0",
   "created" : "2012-10-12T05:01:53.231981Z",
   "status" : "live",
   "location" : {
   },
   "datastreams" : [{
         "max_value" : "100.0",
         "min_value" : "0.0",
         "at" : "2012-10-22T01:28:12.610947Z",
         "id" : "Battery_Level",
         "current_value" : "88"
      }, {
         "max_value" : "30431.0",
         "min_value" : "-26691.0",
         "at" : "2012-10-22T01:22:32.905001Z",
         "id" : "Heading",
         "current_value" : "95"
      }, {
         "max_value" : "64.9304",
         "min_value" : "21.6153",
         "at" : "2012-10-22T01:30:52.656318Z",
         "unit" : {
            "symbol" : "%"
         },
         "id" : "Humidity",
         "current_value" : "55.7556"
      }, {
         "max_value" : "32684.0",
         "min_value" : "0.0",
         "at" : "2012-10-22T01:30:52.656318Z",
         "id" : "Light_Level",
         "current_value" : "37"
      }, {
         "max_value" : "649994.0",
         "min_value" : "-139994.0",
         "at" : "2012-10-18T06:47:56.226880Z",
         "unit" : {
            "symbol" : "µT"
         },
         "id" : "Magnetic_X",
         "current_value" : "-24.90"
      }, {
         "max_value" : "99997.0",
         "min_value" : "-9.9006731e+24",
         "at" : "2012-10-18T06:47:56.226880Z",
         "unit" : {
            "symbol" : "µT"
         },
         "id" : "Magnetic_Y",
         "current_value" : "7.35"
      }, {
         "max_value" : "432.0",
         "min_value" : "-3950.0",
         "at" : "2012-10-18T06:47:56.226880Z",
         "unit" : {
            "symbol" : "µT"
         },
         "id" : "Magnetic_Z",
         "current_value" : "7.10"
      }, {
         "max_value" : "25.59",
         "min_value" : "11.1",
         "at" : "2012-10-22T01:30:52.656318Z",
         "unit" : {
            "symbol" : "°C"
         },
         "id" : "Temperature",
         "current_value" : "22.3800"
   ],
}

As I understand it, Highcharts accepts UTC formatted date/time values for the x-axis? Is the UTC coming in from my JSON feed not valid?

A: You have to convert your date and time values to a Unix timestamp, then Highcharts will accept it.
Date.UTC(2010, 0, 1)

Have a look at this tutorial on how to work with date objects in Javascript.


text:
Q: Swift - Search large array based on multiple conditions I have an array of 4K+ items, using UISearchBar and UISearchController to sort the list for matches. I would like to get sorted array by few criteria, but most importantly by the order user types first
Search controller has 3 scope buttons for

*

*category

*subCategory

*allCat

The items in the search array are using struct class to access the conditions:
struct Item {
    var title: String
    var category: String
    var subCategory: String
    var allCat: String
}

The standard method of filtering would be using something like this:
func filterContentForSearchText(_ searchText: String, scope: String = "All") {

    self.filteredItems = allItems.filter({( item : Item) -> Bool in

        let categoryMatch = (item.allCat == scope) || (item.category == scope)
        return categoryMatch && item.title.lowercased().contains(searchText.lowercased())
        //return categoryMatch && (item.title.lowercased().range(of:searchText.lowercased()) != nil)
    })

    tableView.reloadData()
}

Which is fine in case of few items, but if I have large array and when using the block above, plenty unrelated items with the string typed contained would be included.
I can use predicate to get better result using BEGINSWITH, but I am failing to meet the conditions for categories. I am pretty sure the code block below isn't effective and would appreciate for more economic advise. Another obstacle is that the array contains strings with multiple words. For example:
array = ["Apple", "Apple Freshly Picked", "Apple Green", "Pear", "Melon", "Pear Yellow",....]

So the result when user starts to type "Ap" should be

*

*Apple

*Apple Green

*Apple Freshly Picked

I kinda made it work without the conditions for search categories (struct) being met:
func filterContentForSearchText(_ searchText: String, scope: String = "All") {

    let words = searchText.components(separatedBy: " ")

    var word1 = ""
    var word2 = ""
    var word3 = ""

    var predicate = NSPredicate()
    var array = [Item]()

    if scope == "All" {

        if words.count == 1{
            word1 = (words[0])
            predicate = NSPredicate(format: "SELF BEGINSWITH[cd] %@ OR SELF LIKE[cd] %@", word1, word1)
        }
        else if words.count == 2{
            word1 = (words[0])
            word2 = (words[1])
            predicate = NSPredicate(format: "SELF BEGINSWITH[cd] %@ AND SELF CONTAINS[cd] %@", word1, word2)
        }
        else if words.count == 3{
            word1 = (words[0])
            word2 = (words[1])
            word3 = (words[2])
            predicate = NSPredicate(format: "SELF BEGINSWITH[cd] %@ AND SELF CONTAINS[cd] %@ AND SELF CONTAINS[cd] %@", word1, word2, word3)
        }

    } else {

        predicate = NSPredicate(format: "title BEGINSWITH[cd] %@ AND category == %@", searchText, scope)

        if words.count == 1{
            word1 = (words[0])
            predicate = NSPredicate(format: "SELF BEGINSWITH[cd] %@ OR SELF LIKE[cd] %@ AND category == %@", word1, word1, scope)
        }
        else if words.count == 2{
            word1 = (words[0])
            word2 = (words[1])
            predicate = NSPredicate(format: "SELF BEGINSWITH[cd] %@ AND SELF CONTAINS[cd] %@ AND category == %@", word1, word2, scope)
        }
        else if words.count == 3{
            word1 = (words[0])
            word2 = (words[1])
            word3 = (words[2])
            predicate = NSPredicate(format: "SELF BEGINSWITH[cd] %@ AND SELF CONTAINS[cd] %@ AND SELF CONTAINS[cd] %@ AND category == %@", word1, word2, word3, scope)
        }

    }

    array = (allItems as NSArray).filtered(using: predicate) as! [Item]
    self.filteredItems = array

    let lengthSort = NSSortDescriptor(key: "length", ascending: true)
    let sortedArr = (self.filteredItems as NSArray).sortedArray(using: [lengthSort])
    self.filteredItems = sortedArr as! [Item]

    self.tableView.reloadData()
}

How do I approach this logic satisfying the categories as well as the typing string match and length/range of the string (first word) please?
Thank you

A: I found the way. I combined .filter and .sort to get the result:
func filterContentForSearchText(_ searchText: String, scope: String = "All") {

    let options = NSString.CompareOptions.caseInsensitive

    if scope == "All"{

        print("filtering All")
        self.filteredItems = allItems
            .filter{$0.title.range(of: searchText, options: options) != nil && $0.allCat == scope}
            .sorted{ ($0.title.hasPrefix(searchText) ? 0 : 1) < ($1.title.hasPrefix(searchText) ? 0 : 1) }
    }
    else{

        print("filtering \(scope)")
        self.filteredItems = allItems
            .filter{$0.title.range(of: searchText, options: options) != nil && $0.category == scope}
            .sorted{ ($0.title.hasPrefix(searchText) ? 0 : 1) < ($1.title.hasPrefix(searchText) ? 0 : 1) }

    }
    tableView.reloadData()
}

Hope this helps somebody


text:
Q: Save/download ArcGIS Online feature layer as shapefile using Python script I would like to go through my feature layers in my ArcGIS Online account and download/save the feature layers as shapefiles to my computer. I've tried this tool and also this and others but with no success. Now I'm trying to load the feature layers from the catalog to TOC in ArcMap. It works fine, I can see them in the TOC and I can copy them manually using CopyFeatures tool, or by right-click and then data-export data. Because I have a lot of feature layers, I wrote a script that will iterate over the layers and save them as shp:
import arcpy
import os
destPath = r"C:\Users\data from AGOL"
mxd = arcpy.mapping.MapDocument(r"C:\Users\data from AGOL\Untitled.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
for lyr in arcpy.mapping.ListLayers(mxd, '', df):
    if lyr.isFeatureLayer == True:
       dest1 = os.path.join(destPath, str(lyr.name) + ".shp")
       arcpy.CopyFeatures_management(lyr,dest1)

This works fine for some feature layers but for others it fails with the error:
Traceback (most recent call last):
  File "C:/Users/PycharmProjects/untitled1/copyFeatures.py", line 15, in <module>
    arcpy.CopyFeatures_management(lyr, dest1)
  File "C:\Program Files (x86)\ArcGIS\Desktop10.2\arcpy\arcpy\management.py", line 2429, in CopyFeatures
    raise e
arcgisscripting.ExecuteError: ERROR 000210: Cannot create output C:\Users\data from AGOL\AOI_151213.shp
Failed to execute (CopyFeatures).

The following image show one of the problematic feature layer (AOI_151213) and one that is OK (AOI_2015):

The only difference I can think of is that the problematic one, contain some txt files, but I can save it manually and it's fine. This error rises only in the iteration process.
Is there a way to modify my code so that:
- I will be able to save the problematic feature layer as shp file
- OR at least to add a condition that will not terminate the script, but skip this error (and the following errors) - I'm not sure how to embed such a thing.

A: I suspect that the problem was that there were 2 layers with the same name, but I'm not sure. Anyway, I modified my script so it will ignore all errors, because it is enough for what I'm trying to accomplished. The script that worked for me:
import os
import arcpy
mxd = arcpy.mapping.MapDocument(r"D:\data from AGOL\Untitled.mxd")
df = arcpy.mapping.ListDataFrames(mxd)[0]
destPath = r"D:\data from AGOL"
for lyr in arcpy.mapping.ListLayers(mxd, '', df):
    if lyr.isFeatureLayer == True:
        d = lyr.name.encode('ascii', 'ignore')
        file_name = d + ".shp"
        dest1 = os.path.join(destPath, file_name)
        print file_name
        print type(file_name)
        print dest1
        try:
            arcpy.CopyFeatures_management(lyr, dest1)
        except:
            pass