问:
T-SQL CONTAINS with search condition from subquery
I have a table containing search values and wish to use CONTAINS to search another table with those values.  The table to search contains email data.

```<code>SEARCHTABLE
ID     VALUE
1      '*domain1.com'
2      '*domain2.co.uk'

EMAILTABLE

ID     SENDER                 BODY
1      'fred@domain1.com'     'body text of email'
2      'frank@domain1.com'    'body text of email'
3      'bob@domain3.net'      'body text of email'
</code>```

is there a way to build a query searching the EMAILTABLE with the values in the SEARCHTABLE in a subquery i.e. the equivalent of :

```<code>SELECT * FROM EMAILTABLE where CONTAINS (sender, '*domain.com OR *domain2.co.uk'
</code>```

I'd be grateful for any assistance with this.

答:
Try like this :</p>

```<code>SELECT EMAILTABLE.*
FROM EMAILTABLE
INNER JOIN SEARCHTABLE ON  EMAILTABLE.SENDER LIKE '%'+REPLACE(SEARCHTABLE.Value,'*','')+'%'
</code>```

Body:
I have a table containing search values and wish to use CONTAINS to search another table with those values.  The table to search contains email data.

SEARCHTABLE
ID     VALUE
1      '*domain1.com'
2      '*domain2.co.uk'

EMAILTABLE

ID     SENDER                 BODY
1      'fred@domain1.com'     'body text of email'
2      'frank@domain1.com'    'body text of email'
3      'bob@domain3.net'      'body text of email'

is there a way to build a query searching the EMAILTABLE with the values in the SEARCHTABLE in a subquery i.e. the equivalent of :

SELECT * FROM EMAILTABLE where CONTAINS (sender, '*domain.com OR *domain2.co.uk'

I'd be grateful for any assistance with this.

Body:
Try like this :

SELECT EMAILTABLE.*
FROM EMAILTABLE
INNER JOIN SEARCHTABLE ON  EMAILTABLE.SENDER LIKE '%'+REPLACE(SEARCHTABLE.Value,'*','')+'%'


来源: stackexchange

问:
How to Output a Double Value with all the Decimal Places in Debugger or Console
I wish to extract double value completely when I am debugging an application, so that I can use it to construct a test case to feed into my geometry algorithm.

How to extract the double value out-- down to very last decimal places allowed by the double datatypes in C#-- and output it in either debugger windows, or using Console.WriteLine command?

Edit: My problem is that the algorithm that takes the double value as input will only fail if I insist of input the whole double value, right down to the very last digit. And since I want to reproduce it in a test case, that's why I would need such a full representation of the double value.

答:
Instead of trying to output a binary number as a decimal number to a very large number of decimal places and do an exact comparison, instead do a comparison with an epsilon value that is your acceptable error and set epsilon to be very small. E.g.</p>

```<code> double epsilon = Math.Abs(actual - expected);
 Assert.That(epsilon, Is.LessThan(0.000000000001);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Instead of trying to output a binary number as a decimal number to a very large number of decimal places and do an exact comparison, instead do a comparison with an epsilon value that is your acceptable error and set epsilon to be very small. E.g.

 double epsilon = Math.Abs(actual - expected);
 Assert.That(epsilon, Is.LessThan(0.000000000001);


问:
the best way to postpone callback till event
What would you suggest in case we need to postpone a callback in some circumstances and call it later, when an event occurs?
There are currently several queuing modules but I have not found one, which meet requirements as this one. I mean one don't run tasks out of queue till they are done. You run them when there is a suitable parameter value or the callback. For example,     </p>

```<code><html>
<body>
<input type="text" id="id1">
<input type="text" id="id2">
<script type="text/javascript">
    document.getElementById("id1")
        .addEventListener("keydown", function (e) {
            if (e.keyCode === 13) {
                upper(e.target.value);
            }
        });

    document.getElementById("id2")
        .addEventListener("keydown", function (e) {
            if (e.keyCode === 13) {
                delayed(e.target.value);
            }
        });

    function upper(x){
        if (parseInt(x) == x) {
            next_level(x, function(y){
                alert(y);
            });
        } else {
                alert('not int');
        }
    }

    function next_level(x, callback){
        y = Math.random() * 10;
        if (y < x){
            callback(y);
        } else {
            // postpone callback till y comes from id2
            // put it into a queue
        }
    }

    function delayed(y){
        // take 1st element/callback from the queue
        // call it with y
        // if queue is empty, do nothing
    }
</script>
</body>
</html>
</code>```

答:
Please check my jsFiddle. It is similar to amcdrmtt's answer ut i tried to explain in the code what happen.

```<code>function next_level(x, callback){
  y = Math.random() * 10;
  if (y < x){
    callback(y);
  } else {
    // postpone callback till y comes from id2
    // put it into a queue
    addToQueue(callback);
  }
}
// queue for callback methods
var queue = [];

// remember the callback for later
function addToQueue(func){
   queue.push(func); // add a method that calls func with the original arguments
    outputDiv.innerHTML += "<div>callback added to queue. queue length:" + queue.length + "</div>";
}
// call the last callback with a new value y
function delayed(y){
   // if queue is empty, do nothing
   if (queue.length === 0) {
    return;
   }
  // take 1st element/callback from the queue
  var firstCallback = queue.shift(); // also remove it from the queue
  // call it with y

  firstCallback(y);
}
</code>```

https://jsfiddle.net/7pfzvL0d/4/

ContentLicense: CC BY-SA 3.0

Body:
What would you suggest in case we need to postpone a callback in some circumstances and call it later, when an event occurs?
There are currently several queuing modules but I have not found one, which meet requirements as this one. I mean one don't run tasks out of queue till they are done. You run them when there is a suitable parameter value or the callback. For example,

<input type="text" id="id1">
<input type="text" id="id2">

Body:
Please check my jsFiddle. It is similar to amcdrmtt's answer ut i tried to explain in the code what happen.

function next_level(x, callback){
  y = Math.random() * 10;
  if (y < x){
    callback(y);
  } else {
    // postpone callback till y comes from id2
    // put it into a queue
    addToQueue(callback);
  }
}
// queue for callback methods
var queue = [];

// remember the callback for later
function addToQueue(func){
   queue.push(func); // add a method that calls func with the original arguments
    outputDiv.innerHTML += "<div>callback added to queue. queue length:" + queue.length + "</div>";
}
// call the last callback with a new value y
function delayed(y){
   // if queue is empty, do nothing
   if (queue.length === 0) {
    return;
   }
  // take 1st element/callback from the queue
  var firstCallback = queue.shift(); // also remove it from the queue
  // call it with y

  firstCallback(y);
}

https://jsfiddle.net/7pfzvL0d/4/


问:
Prove that 5^n = o(n!)
Please help me providing a direction on how to prove this. I can prove by randomly finding value of n that makes n! greater than 5^n. But can someone help me prove mathematically.</p>

答:
```<code>5^n = o(n!) <=> if n close to ∞ limit 5^n/n! close to 0
</code>```

prove:

```<code>set An = 5^n/n!, when n > 10, An = 5^n/n! < 1/(n-5)!
for An > 0 and limit 1/(n-5)! close to 0, then 0 <= limit An <= limit 1/(n-5)! <= 0
so limit 5^n/n! close to 0, and 5^n = o(n!)
</code>```

Title: Prove that 5^n = o(n!)

Body:
5^n = o(n!) <=> if n close to ∞ limit 5^n/n! close to 0

prove:

set An = 5^n/n!, when n > 10, An = 5^n/n! < 1/(n-5)!
for An > 0 and limit 1/(n-5)! close to 0, then 0 <= limit An <= limit 1/(n-5)! <= 0
so limit 5^n/n! close to 0, and 5^n = o(n!)


问:
how to implement observable int in wpf ViewModel?
In my mvvm ViewModel I have such field

```<code>public int Delta { get; private set; }
</code>```

However when I update it like that:

```<code>Delta = newValue;
</code>```

UI is not refreshed.

I was thinking that databinding will do that for me. For example I can declare collection as ObservableCollection and then databinding will work.

However there are no ObservableInt, how to say View that it need to be refreshed then?

Probably I should raise some event "notify property changed" or something?

答:
While we're at it with improving the answer, some of the other new additions of c# 6.0 and 7.0 help make it ever more compact:

```<code>public class Prop<T> : INotifyPropertyChanged
{
    private T _value;

    public T Value
    {
        get => _value;
        set { _value = value; NotifyPropertyChanged(nameof(Value)); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    internal void NotifyPropertyChanged(string propertyName) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
</code>```

This way, you aren't using any "embedded values" (i.e - the property's name) and are keeping the code refactor-safe.

And there's also no need for redundant code blocks due to c# 6.0 and 7.0's new Expression body features

Body:
In my mvvm ViewModel I have such field

public int Delta { get; private set; }

However when I update it like that:

Delta = newValue;

UI is not refreshed.

I was thinking that databinding will do that for me. For example I can declare collection as ObservableCollection and then databinding will work.

However there are no ObservableInt, how to say View that it need to be refreshed then?

Probably I should raise some event "notify property changed" or something?

Body:
While we're at it with improving the answer, some of the other new additions of c# 6.0 and 7.0 help make it ever more compact:

public class Prop<T> : INotifyPropertyChanged
{
    private T _value;

    public T Value
    {
        get => _value;
        set { _value = value; NotifyPropertyChanged(nameof(Value)); }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    internal void NotifyPropertyChanged(string propertyName) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

This way, you aren't using any "embedded values" (i.e - the property's name) and are keeping the code refactor-safe.

And there's also no need for redundant code blocks due to c# 6.0 and 7.0's new Expression body features

ContentLicense: CC BY-SA 4.0


问:
How can I format a number into a currency value without php?
I have a value in my mySQL database 13148.70. I want to convert it into a currency format:

```<code>$data = $db->query('SELECT *, ROUND((price), 2) AS price FROM data')->fetchAll(PDO::FETCH_ASSOC);
</code>```

The result is:

```<code>13148.70
</code>```

But I would need 13 148,70 €

答:
You can use the function money-format in php :money-format

The nearest you can do in mysql would be this :

```<code>SELECT *, REPLACE(REPLACE(CONCAT(FORMAT(price, 2)," €"), ",", " "),".",",") AS price FROM data
</code>```

Body:
I have a value in my mySQL database 13148.70. I want to convert it into a currency format:

$data = $db->query('SELECT *, ROUND((price), 2) AS price FROM data')->fetchAll(PDO::FETCH_ASSOC);

The result is:

13148.70

But I would need 13 148,70 €

Body:
You can use the function money-format in php :money-format

The nearest you can do in mysql would be this :

SELECT *, REPLACE(REPLACE(CONCAT(FORMAT(price, 2)," €"), ",", " "),".",",") AS price FROM data


问:
Connect to multiple database elixir
In Rails , we can connect to multiple database on fly as,

```<code>ActiveRecord::Base.establish_connection(
  database: "db_name", username: "postgres")
</code>```

But in Elixir - Phoenix framework, how to do the same process.

答:
use Mix.Config

config :my_app, MyApp.OneRepo,
  adapter: Ecto.Adapters.MySQL,
  database: "legacy_db",
  username: "username",
  password: "password",
  hostname: "something.com"

config :my_app, MyApp.TwoRepo,
  adapter: Ecto.Adapters.Postgres,
  username: "username",
  password: "password",
  database: "some_db_two",
  hostname: "example.com"

config :my_app, ecto_repos: [MyApp.OneRepo, MyApp.TwoRepo]
```

<p>lib/my_app.ex
Supervise the Repos.</p>

<pre class="lang-rb prettyprint-override"><code>defmodule Databases do
  use Application

  def start(_type, _args) do
    import Supervisor.Spec, warn: false

    children = [
      supervisor(MyApp.OneRepo, []), # <-- our addition
      supervisor(MyApp.TwoRepo, [])     # <-- our addition
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end
</code>```

and finally
lib/repos.ex

defmodule MyApp.OneRepo do
 use Ecto.Repo, otp_app: :my_app
end

defmodule MyApp.TwoRepo do
 use Ecto.Repo, otp_app: :my_app
end
```

<p>example</p>

<pre class="lang-rb prettyprint-override"><code>iex> import Ecto.Query

 iex> some_table= MyApp.OneRepo.get_by(SomeTable, %{username: "Alpha"})

iex> other_table= MyApp.TwoRepo.all from ot in OtherTable,
             where: ot.user_id == ^user.id
</code>```

Title: Connect to multiple database elixir

Body:
In Rails , we can connect to multiple database on fly as,

ActiveRecord::Base.establish_connection(
  database: "db_name", username: "postgres")

But in Elixir - Phoenix framework, how to do the same process.

Body:
use Mix.Config

config :my_app, MyApp.OneRepo,
  adapter: Ecto.Adapters.MySQL,
  database: "legacy_db",
  username: "username",
  password: "password",
  hostname: "something.com"

config :my_app, MyApp.TwoRepo,
  adapter: Ecto.Adapters.Postgres,
  username: "username",
  password: "password",
  database: "some_db_two",
  hostname: "example.com"

config :my_app, ecto_repos: [MyApp.OneRepo, MyApp.TwoRepo]

lib/my_app.ex
Supervise the Repos.

defmodule Databases do
  use Application

  def start(_type, _args) do
    import Supervisor.Spec, warn: false

    children = [
      supervisor(MyApp.OneRepo, []), # <-- our addition
      supervisor(MyApp.TwoRepo, [])     # <-- our addition
    ]

    opts = [strategy: :one_for_one, name: MyApp.Supervisor]
    Supervisor.start_link(children, opts)
  end
end

and finally
lib/repos.ex

defmodule MyApp.OneRepo do
 use Ecto.Repo, otp_app: :my_app
end

defmodule MyApp.TwoRepo do
 use Ecto.Repo, otp_app: :my_app
end

example

iex> import Ecto.Query

 iex> some_table= MyApp.OneRepo.get_by(SomeTable, %{username: "Alpha"})

iex> other_table= MyApp.TwoRepo.all from ot in OtherTable,
             where: ot.user_id == ^user.id


答:
Syntax

```<code>number_format(number,decimals,decimalpoint,separator)
</code>```

So in your case:

```<code>$data = number_format($data, 2, ",", " ");
</code>```

More information: number_format

Title: How can I format a number into a currency value without php?

Body:
Syntax

number_format(number,decimals,decimalpoint,separator)

So in your case:

$data = number_format($data, 2, ",", " ");

More information: number_format


问:
How to Inherit from IdentityUserLogin And IdentityUserRole asp.net mvc
I have a two classes they are names tblUserProfile and tblUserRole I want to add multiple property to my own class that i mentioned.in fact , tblUserProfile use tblUserProfile:IdentityUserLogin and tblUserRole use tblAccessRole : IdentityUserRole but when I did add-migration it did give me this error EntityType  has no key defined. Define the key for this EntityType
after that I add key attribute then EF did show me Column names in each table must be unique. Column name 'RoleId' in table 'tblAccessRoles' is specified more than once. please tell me how can i solve it.

```<code>   public class tblUserProfile : IdentityUserLogin
    {
        public int UserID { get; set; }
        public string NameFamily { get; set; }

    }

  public class tblAccessRole : IdentityUserRole
    {

        public int RoleID { get; set; }
        public string  Section { get; set; }
        public bool IsSave { get; set; }
    }
</code>```

答:
remove UserID from tblUserProfile and RoleID from tblAccessRole and

In Your DbContext add :

```<code>  protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

      modelBuilder.Entity<tblUserProfile>()//IdentityUserLogin
            .HasKey(l => new { l.LoginProvider, l.ProviderKey, l.UserId })
            .ToTable("tblUserProfile");// Database Table Nam

            modelBuilder.Entity<tblAccessRole>()//IdentityUserRole
            .HasKey(r => new { r.UserId, r.RoleId })
                .ToTable("tblAccessRole");// Database Table Name
    }
</code>```

Body:
I have a two classes they are names tblUserProfile and tblUserRole I want to add multiple property to my own class that i mentioned.in fact , tblUserProfile use tblUserProfile:IdentityUserLogin and tblUserRole use tblAccessRole : IdentityUserRole but when I did add-migration it did give me this error EntityType  has no key defined. Define the key for this EntityType
after that I add key attribute then EF did show me Column names in each table must be unique. Column name 'RoleId' in table 'tblAccessRoles' is specified more than once. please tell me how can i solve it.

   public class tblUserProfile : IdentityUserLogin
    {
        public int UserID { get; set; }
        public string NameFamily { get; set; }

    }

  public class tblAccessRole : IdentityUserRole
    {

        public int RoleID { get; set; }
        public string  Section { get; set; }
        public bool IsSave { get; set; }
    }

Body:
remove UserID from tblUserProfile and RoleID from tblAccessRole and

In Your DbContext add :

  protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

      modelBuilder.Entity<tblUserProfile>()//IdentityUserLogin
            .HasKey(l => new { l.LoginProvider, l.ProviderKey, l.UserId })
            .ToTable("tblUserProfile");// Database Table Nam

            modelBuilder.Entity<tblAccessRole>()//IdentityUserRole
            .HasKey(r => new { r.UserId, r.RoleId })
                .ToTable("tblAccessRole");// Database Table Name
    }


问:
What is the better way of including a header file? #include<> followed by #include"" or the otherwise?

Possible Duplicates:

  what is the difference between #include <filename> and #include “filename”

  C/C++ include file order/best practices

In what order should the include statements in a header file and source file come in C++? #include <> followed by #include "" or the otherwise?

Also, should the header file of a source file precede all include statements in source file?

答: There is no better or worse, they server different purposes. #ncude "" is supposed to be used for files in your project or direct dependencies that are not system wide installed. Where #include <> are for inludes that (eg under Linux) are located in your /usr/include or simialr folder, also called system libraries.


问:
Return an array of Interfaces or extended interfaces
Not sure if the title resembles correctly my question, but I am open to suggestions.

I have the following method which returns either array of IListItem or array of other interfaces that extend that interface.

```<code>import { SPHttpClient, SPHttpClientResponse } from "@microsoft/sp-http";
import { IWebPartContext } from "@microsoft/sp-webpart-base";
import { IListItem} from "./models/IListItem";
import { IFactory } from "./IFactory";
import { INewsListItem } from "./models/INewsListItem";
import { IDirectoryListItem } from "./models/IDirectoryListItem";
import { IAnnouncementListItem } from "./models/IAnnouncementListItem";

export class ListItemFactory implements IFactory {
    private _listItems: IListItem[];
    public getItems(requester: SPHttpClient, siteUrl: string, listName: string): Promise<IListItem[]> {
        switch(listName) {
            case "GenericList":
                let items: IListItem[];
                // tslint:disable-next-line:max-line-length
                return requester.get(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=Title,Id,Modified,Created,Author/Title,Editor/Title&$expand=Author,Editor`,
                SPHttpClient.configurations.v1,
                {
                    headers: {
                        "Accept": "application/json;odata=nometadata",
                        "odata-version": ""
                    }
                })
                .then((response: SPHttpClientResponse): Promise<{ value: IListItem[] }> => {
                    return response.json();
                })
                .then((json: { value: IListItem[] }) => {
                    console.log(JSON.stringify(json.value));
                    return items=json.value.map((v,i)=>(
                        {
                            //key: v.id,
                            id: v.Id,
                            title: v.Title,
                            created: v.Created,
                            createdby: v.Author.Title,
                            modified: v.Modified,
                            modifiedby: v.Editor.Title
                        }
                    ));
                });
            case "News":
                let newsitems: INewsListItem[];
                // tslint:disable-next-line:max-line-length
                return requester.get(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=Title,Id,Modified,Created,Created By,Modified By,newsheader,newsbody,expiryDate`,
                SPHttpClient.configurations.v1,
                {
                    headers: {
                        "Accept": "application/json;odata=nometadata",
                        "odata-version": ""
                    }
                })
                .then((response: SPHttpClientResponse): Promise<{ value: INewsListItem[] }> => {
                    return response.json();
                })
                .then((json: { value: INewsListItem[] }) => {
                    return items=json.value.map((v,i)=>(
                        {
                            id: v.Id,
                            title: v.Title,
                            created: v.Created,
                            createdby: v.Author.Title,
                            modified: v.Modified,
                            modifiedby: v.Editor.Title,
                            newsheader: v.newsheader,
                            newsbody: v.newsbody,
                            expiryDate: v.expiryDate
                        }
                    ));
                });
            case "Announcements":
                let announcementitems: IAnnouncementListItem[];
                return requester.get(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=Title,Id`,
                SPHttpClient.configurations.v1,
                {
                    headers: {
                        "Accept": "application/json;odata=nometadata",
                        "odata-version": ""
                    }
                })
                .then((response: SPHttpClientResponse): Promise<{ value: IAnnouncementListItem[] }> => {
                    return response.json();
                })
                .then((json: { value: IAnnouncementListItem[] }) => {
                    return items=json.value.map((v,i)=>(
                        {
                            id: v.Id,
                            title: v.Title,
                            created: v.Created,
                            createdby: v.Author.Title,
                            modified: v.Modified,
                            modifiedby: v.Editor.Title,
                            announcementBody: v.announcementBody,
                            expiryDate: v.expiryDate
                        }
                    ));
                });
            case "Directory":
                let directoryitems: IDirectoryListItem[];
                return requester.get(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=Title,Id`,
                SPHttpClient.configurations.v1,
                {
                    headers: {
                        "Accept": "application/json;odata=nometadata",
                        "odata-version": ""
                    }
                })
                .then((response: SPHttpClientResponse): Promise<{ value: IDirectoryListItem[] }> => {
                    return response.json();
                })
                .then((json: { value: IDirectoryListItem[] }) => {
                    return items=json.value.map((v,i)=>(
                        {
                            id: v.Id,
                            title: v.Title,
                            created: v.Created,
                            createdby: v.Author.Title,
                            modified: v.Modified,
                            modifiedby: v.Editor.Title,
                            firstName: v.firstName,
                            lastName: v.lastName,
                            mobileNumber: v.mobileNumber,
                            internalNumber: v.internalNumber
                        }
                    ));
                });
            default:
                return null;
        }
      }
}
</code>```

Interfaces are here:

```<code>export  interface IListItem {
    [key: string]: any;
    id: string;
    title: string;
    modified: Date;
    created: Date;
    modifiedby: string;
    createdby: string;
}

import {IListItem} from "./IListItem";

export interface  INewsListItem extends IListItem {
    newsheader: string;
    newsbody: string;
    expiryDate: Date;
}

import {IListItem} from "./IListItem";

export interface  IAnnouncementListItem extends IListItem {
    announcementBody: string;
    expiryDate: Date;
}

import {IListItem} from "./IListItem";

export interface IDirectoryListItem extends IListItem {
        firstName: string;
        lastName: string;
        mobileNumber: string;
        internalNumber: string;
}
</code>```

And the consumer method from the TSX component is:

```<code> // read items using factory method pattern and sets state accordingly
  private readItemsAndSetStatus(): void {
    this.setState({
      status: "Loading all items..."
    });

    const factory: ListItemFactory = new ListItemFactory();
    factory.getItems(this.props.spHttpClient, this.props.siteUrl, this.props.listName)
    .then((items: IListItem[]) => {
      const keyPart: string = this.props.listName === "GenericList" ? "" : this.props.listName;
        // the explicit specification of the type argument `keyof {}` is bad and
        // it should not be required.
        this.setState<keyof {}>({
          status: `Successfully loaded ${items.length} items`,
          ["Details" + keyPart + "ListItemState"] : {
            items
          },
          columns: buildColumns(items)
        });
    });
  }
</code>```

I paste below the entire TSX just for reference

```<code>//#region Imports
import * as React from "react";
import styles from "./FactoryMethod.module.scss";
import  { IFactoryMethodProps } from "./IFactoryMethodProps";
import {
  IDetailsListItemState,
  IDetailsNewsListItemState,
  IDetailsDirectoryListItemState,
  IDetailsAnnouncementListItemState,
  IFactoryMethodState
} from "./IFactoryMethodState";
import { IListItem } from "./models/IListItem";
import { IAnnouncementListItem } from "./models/IAnnouncementListItem";
import { INewsListItem } from "./models/INewsListItem";
import { IDirectoryListItem } from "./models/IDirectoryListItem";
import { escape } from "@microsoft/sp-lodash-subset";
import { SPHttpClient, SPHttpClientResponse } from "@microsoft/sp-http";
import { ListItemFactory} from "./ListItemFactory";
import { TextField } from "office-ui-fabric-react/lib/TextField";
import {
  DetailsList,
  DetailsListLayoutMode,
  Selection,
  buildColumns,
  IColumn
} from "office-ui-fabric-react/lib/DetailsList";
import { MarqueeSelection } from "office-ui-fabric-react/lib/MarqueeSelection";
import { autobind } from "office-ui-fabric-react/lib/Utilities";
import PropTypes from "prop-types";
//#endregion

export default class FactoryMethod extends React.Component<IFactoryMethodProps, IFactoryMethodState> {
  constructor(props: IFactoryMethodProps, state: any) {
    super(props);
    this.setInitialState();
  }

  // lifecycle help here: https://staminaloops.github.io/undefinedisnotafunction/understanding-react/

  //#region Mouting events lifecycle

  // the data returned from render is neither a string nor a DOM node.
  // it's a lightweight description of what the DOM should look like.
  // inspects this.state and this.props and create the markup.
  // when your data changes, the render method is called again.
  // react diff the return value from the previous call to render with
  // the new one, and generate a minimal set of changes to be applied to the DOM.
  public render(): React.ReactElement<IFactoryMethodProps> {
    switch(this.props.listName) {
        case "GenericList":
          // tslint:disable-next-line:max-line-length
          return <this.ListMarqueeSelection items={this.state.DetailsListItemState.items} columns={this.state.columns} />;
        case "News":
          // tslint:disable-next-line:max-line-length
          return <this.ListMarqueeSelection items={this.state.DetailsNewsListItemState.items} columns={this.state.columns}/>;
        case "Announcements":
          // tslint:disable-next-line:max-line-length
          return <this.ListMarqueeSelection items={this.state.DetailsAnnouncementListItemState.items} columns={this.state.columns}/>;
        case "Directory":
          // tslint:disable-next-line:max-line-length
          return <this.ListMarqueeSelection items={this.state.DetailsDirectoryListItemState.items} columns={this.state.columns}/>;
        default:
          return null;
    }
  }

   // invoked once, only on the client (not on the server), immediately AFTER the initial rendering occurs.
   public componentDidMount(): void {
    // you can access any refs to your children
    // (e.g., to access the underlying DOM representation - ReactDOM.findDOMNode).
    // the componentDidMount() method of child components is invoked before that of parent components.
    // if you want to integrate with other JavaScript frameworks,
    // set timers using setTimeout or setInterval,
    // or send AJAX requests, perform those operations in this method.
    this._configureWebPart = this._configureWebPart.bind(this);
    this.readItemsAndSetStatus();
  }

  //#endregion

  //#region Props changes lifecycle events (after a property changes from parent component)
  public componentWillReceiveProps(nextProps: IFactoryMethodProps): void {
    if(nextProps.listName !== this.props.listName) {
      this.readItemsAndSetStatus();
    }
  }

  //#endregion

  //#region private methods
  private _configureWebPart(): void {
    this.props.configureStartCallback();
  }

  public setInitialState(): void {
    this.state = {
      type: "ListItem",
      status: this.listNotConfigured(this.props)
        ? "Please configure list in Web Part properties"
        : "Ready",
      columns:[],
      DetailsListItemState:{
        items:[]
      },
      DetailsNewsListItemState:{
        items:[]
      },
      DetailsDirectoryListItemState:{
        items:[]
      },
      DetailsAnnouncementListItemState:{
        items:[]
      },
    };
  }

  // reusable inline component
  private ListMarqueeSelection = (itemState: {columns: IColumn[], items: IListItem[] }) => (
      <div>
          <DetailsList
            items={ itemState.items }
            columns={ itemState.columns }
            setKey="set"
            layoutMode={ DetailsListLayoutMode.fixedColumns }
            selectionPreservedOnEmptyClick={ true }
            compact={ true }>
          </DetailsList>
      </div>
  )

  // read items using factory method pattern and sets state accordingly
  private readItemsAndSetStatus(): void {
    this.setState({
      status: "Loading all items..."
    });

    const factory: ListItemFactory = new ListItemFactory();
    factory.getItems(this.props.spHttpClient, this.props.siteUrl, this.props.listName)
    .then((items: IListItem[]) => {
      const keyPart: string = this.props.listName === "GenericList" ? "" : this.props.listName;
        // the explicit specification of the type argument `keyof {}` is bad and
        // it should not be required.
        this.setState<keyof {}>({
          status: `Successfully loaded ${items.length} items`,
          ["Details" + keyPart + "ListItemState"] : {
            items
          },
          columns: buildColumns(items)
        });
    });
  }

  private listNotConfigured(props: IFactoryMethodProps): boolean {
    return props.listName === undefined ||
      props.listName === null ||
      props.listName.length === 0;
  }

  //#endregion
}
</code>```

the problem is that its always returnin array of listitems, therefore the react component is only displaying the columns of IListItem, but not display columns of the other interfaces

Update 1:

Trying to do a cast in the  THEN, will result in a duplicate warning for the variable myItems.

答:
It's a problem because your Promise is returning IListItem[].

If you change the return type of the promise in the getItems method in the factory to any[]. Then do the same to the return type in the 'then' of the getItems method call in the consumer. Then do another switch on the listName in the consumer to cast to the required type there it should work

You can cast using this because you have the list name available in the consumer;

var myItems = null;
switch(listName) {
    case "GenericList":
        myItems = items as IListItem[];
    case "News":
        myItems = items as INewsListItem[];
    case "Announcements":
        myItems = items as IAnnouncementListItem[];
    case "Directory":
        myItems = items as IDirectoryListItem[];
}

and then use myItems when you build the columns instead of items

Body:
Not sure if the title resembles correctly my question, but I am open to suggestions.

I have the following method which returns either array of IListItem or array of other interfaces that extend that interface.

import { SPHttpClient, SPHttpClientResponse } from "@microsoft/sp-http";
import { IWebPartContext } from "@microsoft/sp-webpart-base";
import { IListItem} from "./models/IListItem";
import { IFactory } from "./IFactory";
import { INewsListItem } from "./models/INewsListItem";
import { IDirectoryListItem } from "./models/IDirectoryListItem";
import { IAnnouncementListItem } from "./models/IAnnouncementListItem";

export class ListItemFactory implements IFactory {
    private _listItems: IListItem[];
    public getItems(requester: SPHttpClient, siteUrl: string, listName: string): Promise<IListItem[]> {
        switch(listName) {
            case "GenericList":
                let items: IListItem[];
                // tslint:disable-next-line:max-line-length
                return requester.get(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=Title,Id,Modified,Created,Author/Title,Editor/Title&$expand=Author,Editor`,
                SPHttpClient.configurations.v1,
                {
                    headers: {
                        "Accept": "application/json;odata=nometadata",
                        "odata-version": ""
                    }
                })
                .then((response: SPHttpClientResponse): Promise<{ value: IListItem[] }> => {
                    return response.json();
                })
                .then((json: { value: IListItem[] }) => {
                    console.log(JSON.stringify(json.value));
                    return items=json.value.map((v,i)=>(
                        {
                            //key: v.id,
                            id: v.Id,
                            title: v.Title,
                            created: v.Created,
                            createdby: v.Author.Title,
                            modified: v.Modified,
                            modifiedby: v.Editor.Title
                        }
                    ));
                });
            case "News":
                let newsitems: INewsListItem[];
                // tslint:disable-next-line:max-line-length
                return requester.get(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=Title,Id,Modified,Created,Created By,Modified By,newsheader,newsbody,expiryDate`,
                SPHttpClient.configurations.v1,
                {
                    headers: {
                        "Accept": "application/json;odata=nometadata",
                        "odata-version": ""
                    }
                })
                .then((response: SPHttpClientResponse): Promise<{ value: INewsListItem[] }> => {
                    return response.json();
                })
                .then((json: { value: INewsListItem[] }) => {
                    return items=json.value.map((v,i)=>(
                        {
                            id: v.Id,
                            title: v.Title,
                            created: v.Created,
                            createdby: v.Author.Title,
                            modified: v.Modified,
                            modifiedby: v.Editor.Title,
                            newsheader: v.newsheader,
                            newsbody: v.newsbody,
                            expiryDate: v.expiryDate
                        }
                    ));
                });
            case "Announcements":
                let announcementitems: IAnnouncementListItem[];
                return requester.get(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=Title,Id`,
                SPHttpClient.configurations.v1,
                {
                    headers: {
                        "Accept": "application/json;odata=nometadata",
                        "odata-version": ""
                    }
                })
                .then((response: SPHttpClientResponse): Promise<{ value: IAnnouncementListItem[] }> => {
                    return response.json();
                })
                .then((json: { value: IAnnouncementListItem[] }) => {
                    return items=json.value.map((v,i)=>(
                        {
                            id: v.Id,
                            title: v.Title,
                            created: v.Created,
                            createdby: v.Author.Title,
                            modified: v.Modified,
                            modifiedby: v.Editor.Title,
                            announcementBody: v.announcementBody,
                            expiryDate: v.expiryDate
                        }
                    ));
                });
            case "Directory":
                let directoryitems: IDirectoryListItem[];
                return requester.get(`${siteUrl}/_api/web/lists/getbytitle('${listName}')/items?$select=Title,Id`,
                SPHttpClient.configurations.v1,
                {
                    headers: {
                        "Accept": "application/json;odata=nometadata",
                        "odata-version": ""
                    }
                })
                .then((response: SPHttpClientResponse): Promise<{ value: IDirectoryListItem[] }> => {
                    return response.json();
                })
                .then((json: { value: IDirectoryListItem[] }) => {
                    return items=json.value.map((v,i)=>(
                        {
                            id: v.Id,
                            title: v.Title,
                            created: v.Created,
                            createdby: v.Author.Title,
                            modified: v.Modified,
                            modifiedby: v.Editor.Title,
                            firstName: v.firstName,
                            lastName: v.lastName,
                            mobileNumber: v.mobileNumber,
                            internalNumber: v.internalNumber
                        }
                    ));
                });
            default:
                return null;
        }
      }
}

Interfaces are here:

export  interface IListItem {
    [key: string]: any;
    id: string;
    title: string;
    modified: Date;
    created: Date;
    modifiedby: string;
    createdby: string;
}

import {IListItem} from "./IListItem";

export interface  INewsListItem extends IListItem {
    newsheader: string;
    newsbody: string;
    expiryDate: Date;
}

import {IListItem} from "./IListItem";

export interface  IAnnouncementListItem extends IListItem {
    announcementBody: string;
    expiryDate: Date;
}

import {IListItem} from "./IListItem";

export interface IDirectoryListItem extends IListItem {
        firstName: string;
        lastName: string;
        mobileNumber: string;
        internalNumber: string;
}

And the consumer method from the TSX component is:

 // read items using factory method pattern and sets state accordingly
  private readItemsAndSetStatus(): void {
    this.setState({
      status: "Loading all items..."
    });

    const factory: ListItemFactory = new ListItemFactory();
    factory.getItems(this.props.spHttpClient, this.props.siteUrl, this.props.listName)
    .then((items: IListItem[]) => {
      const keyPart: string = this.props.listName === "GenericList" ? "" : this.props.listName;
        // the explicit specification of the type argument `keyof {}` is bad and
        // it should not be required.
        this.setState<keyof {}>({
          status: `Successfully loaded ${items.length} items`,
          ["Details" + keyPart + "ListItemState"] : {
            items
          },
          columns: buildColumns(items)
        });
    });
  }

I paste below the entire TSX just for reference

//#region Imports
import * as React from "react";
import styles from "./FactoryMethod.module.scss";
import  { IFactoryMethodProps } from "./IFactoryMethodProps";
import {
  IDetailsListItemState,
  IDetailsNewsListItemState,
  IDetailsDirectoryListItemState,
  IDetailsAnnouncementListItemState,
  IFactoryMethodState
} from "./IFactoryMethodState";
import { IListItem } from "./models/IListItem";
import { IAnnouncementListItem } from "./models/IAnnouncementListItem";
import { INewsListItem } from "./models/INewsListItem";
import { IDirectoryListItem } from "./models/IDirectoryListItem";
import { escape } from "@microsoft/sp-lodash-subset";
import { SPHttpClient, SPHttpClientResponse } from "@microsoft/sp-http";
import { ListItemFactory} from "./ListItemFactory";
import { TextField } from "office-ui-fabric-react/lib/TextField";
import {
  DetailsList,
  DetailsListLayoutMode,
  Selection,
  buildColumns,
  IColumn
} from "office-ui-fabric-react/lib/DetailsList";
import { MarqueeSelection } from "office-ui-fabric-react/lib/MarqueeSelection";
import { autobind } from "office-ui-fabric-react/lib/Utilities";
import PropTypes from "prop-types";
//#endregion

export default class FactoryMethod extends React.Component<IFactoryMethodProps, IFactoryMethodState> {
  constructor(props: IFactoryMethodProps, state: any) {
    super(props);
    this.setInitialState();
  }

  // lifecycle help here: https://staminaloops.github.io/undefinedisnotafunction/understanding-react/

  //#region Mouting events lifecycle

  // the data returned from render is neither a string nor a DOM node.
  // it's a lightweight description of what the DOM should look like.
  // inspects this.state and this.props and create the markup.
  // when your data changes, the render method is called again.
  // react diff the return value from the previous call to render with
  // the new one, and generate a minimal set of changes to be applied to the DOM.
  public render(): React.ReactElement<IFactoryMethodProps> {
    switch(this.props.listName) {
        case "GenericList":
          // tslint:disable-next-line:max-line-length
          return <this.ListMarqueeSelection items={this.state.DetailsListItemState.items} columns={this.state.columns} />;
        case "News":
          // tslint:disable-next-line:max-line-length
          return <this.ListMarqueeSelection items={this.state.DetailsNewsListItemState.items} columns={this.state.columns}/>;
        case "Announcements":
          // tslint:disable-next-line:max-line-length
          return <this.ListMarqueeSelection items={this.state.DetailsAnnouncementListItemState.items} columns={this.state.columns}/>;
        case "Directory":
          // tslint:disable-next-line:max-line-length
          return <this.ListMarqueeSelection items={this.state.DetailsDirectoryListItemState.items} columns={this.state.columns}/>;
        default:
          return null;
    }
  }

   // invoked once, only on the client (not on the server), immediately AFTER the initial rendering occurs.
   public componentDidMount(): void {
    // you can access any refs to your children
    // (e.g., to access the underlying DOM representation - ReactDOM.findDOMNode).
    // the componentDidMount() method of child components is invoked before that of parent components.
    // if you want to integrate with other JavaScript frameworks,
    // set timers using setTimeout or setInterval,
    // or send AJAX requests, perform those operations in this method.
    this._configureWebPart = this._configureWebPart.bind(this);
    this.readItemsAndSetStatus();
  }

  //#endregion

  //#region Props changes lifecycle events (after a property changes from parent component)
  public componentWillReceiveProps(nextProps: IFactoryMethodProps): void {
    if(nextProps.listName !== this.props.listName) {
      this.readItemsAndSetStatus();
    }
  }

  //#endregion

  //#region private methods
  private _configureWebPart(): void {
    this.props.configureStartCallback();
  }

  public setInitialState(): void {
    this.state = {
      type: "ListItem",
      status: this.listNotConfigured(this.props)
        ? "Please configure list in Web Part properties"
        : "Ready",
      columns:[],
      DetailsListItemState:{
        items:[]
      },
      DetailsNewsListItemState:{
        items:[]
      },
      DetailsDirectoryListItemState:{
        items:[]
      },
      DetailsAnnouncementListItemState:{
        items:[]
      },
    };
  }

  // reusable inline component
  private ListMarqueeSelection = (itemState: {columns: IColumn[], items: IListItem[] }) => (

          <DetailsList
            items={ itemState.items }
            columns={ itemState.columns }
            setKey="set"
            layoutMode={ DetailsListLayoutMode.fixedColumns }
            selectionPreservedOnEmptyClick={ true }
            compact={ true }>
          </DetailsList>

  )

  // read items using factory method pattern and sets state accordingly
  private readItemsAndSetStatus(): void {
    this.setState({
      status: "Loading all items..."
    });

    const factory: ListItemFactory = new ListItemFactory();
    factory.getItems(this.props.spHttpClient, this.props.siteUrl, this.props.listName)
    .then((items: IListItem[]) => {
      const keyPart: string = this.props.listName === "GenericList" ? "" : this.props.listName;
        // the explicit specification of the type argument `keyof {}` is bad and
        // it should not be required.
        this.setState<keyof {}>({
          status: `Successfully loaded ${items.length} items`,
          ["Details" + keyPart + "ListItemState"] : {
            items
          },
          columns: buildColumns(items)
        });
    });
  }

  private listNotConfigured(props: IFactoryMethodProps): boolean {
    return props.listName === undefined ||
      props.listName === null ||
      props.listName.length === 0;
  }

  //#endregion
}

the problem is that its always returnin array of listitems, therefore the react component is only displaying the columns of IListItem, but not display columns of the other interfaces

Update 1:

Trying to do a cast in the  THEN, will result in a duplicate warning for the variable myItems.


问:
Angular 2 Reactive Form nested group passed null on reset throw error
I have this form group:

```<code>Id: [null],
Nominativo: [null, [Validators.required, Validators.maxLength(100)]],
Area: fb.group({
    Id: [null]
})
</code>```

When i try to reset the form with this model:

```<code>Id: 1,
Nominativo: 'Test'
Area: null
</code>```

the area null value throw exception "TypeError: Cannot read property 'Id' of null". My expected result is all Area value become null. I can avoid this problem? My server response with all nested model null when they are all null

答:
I suggest to do something like this:

area.model.ts

```<code>export class Area {
 id: string;
}
</code>```

data.model.ts

```<code>export class DataModel {
 id: string;
 nominativo: string;
 area: Area;
}
</code>```

form.model.ts

```<code>export class FormModel {
 id: string;
 nominativo: string;
 area?: Area;
}
</code>```

data-model.service.ts

```<code>@Injectable()
export class DataModelService {
  toFormModel(dataModel: DataModel): FormModel {
    const form: FormModel = new FormModel();
    form.id = dataModel.id;
    form.nominativo = dataModel.nominativo;
    if (dataModel.area) {
      form.area = dataModel.area;
    }
    return form;
 }
}
</code>```

form.component.ts

```<code>constructor(dataModelService: DataModelService,
            dataApi: dataApiService,
            fb: FormBuilder) {
  this.form = this.fb.group({
    id: '',
    nominativo: '',
    area: this.fb.group({
      id: ''
    })
  });

  this.dataApi.getData()
    .map((data: DataModel) => this.dataModelService.toFormModel(data))
    .subscribe((formData) => {
       this.form.patchValue(formData);
    });
}
</code>```

Body:
I have this form group:

Id: [null],
Nominativo: [null, [Validators.required, Validators.maxLength(100)]],
Area: fb.group({
    Id: [null]
})

When i try to reset the form with this model:

Id: 1,
Nominativo: 'Test'
Area: null

the area null value throw exception "TypeError: Cannot read property 'Id' of null". My expected result is all Area value become null. I can avoid this problem? My server response with all nested model null when they are all null

Body:
I suggest to do something like this:

area.model.ts

export class Area {
 id: string;
}

data.model.ts

export class DataModel {
 id: string;
 nominativo: string;
 area: Area;
}

form.model.ts

export class FormModel {
 id: string;
 nominativo: string;
 area?: Area;
}

data-model.service.ts

@Injectable()
export class DataModelService {
  toFormModel(dataModel: DataModel): FormModel {
    const form: FormModel = new FormModel();
    form.id = dataModel.id;
    form.nominativo = dataModel.nominativo;
    if (dataModel.area) {
      form.area = dataModel.area;
    }
    return form;
 }
}

form.component.ts

constructor(dataModelService: DataModelService,
            dataApi: dataApiService,
            fb: FormBuilder) {
  this.form = this.fb.group({
    id: '',
    nominativo: '',
    area: this.fb.group({
      id: ''
    })
  });

  this.dataApi.getData()
    .map((data: DataModel) => this.dataModelService.toFormModel(data))
    .subscribe((formData) => {
       this.form.patchValue(formData);
    });
}


问:
deploying jsf jpa web application in weblogic 12.1.1
i am developping a web application using Maven , JSF 2.2 ,JSTL 1.2.1 , JPA 2.1 , Spring 4.2.9, Hibernate-jpa-api-2.1
i can deploy my application in Tomcat and run it without problems , but i want deploy in weblogic 12.1.1 as well but i got some problems starting my app server :

nested exception is java.lang.NoSuchMethodError : javax.persistance.Table.indexes()[Ljavax/persistence/Index;
  ....
  org.springframework.beans.factory.BeanCreationException : Error creatin bean with name 'myEmf' defined in class path resource [jpaConfig.xml]
  ....
  Error javax.entreprise.resource.webcontainer.jsf.application

i have created a weblogic.xml in my deployed war like this :

<prefer-application-packages>
   <package-name>javax.faces.*</package-name>
   <package-name>com.sun.faces.*</package-name>
   <package-name>com.bea.faces.*</package-name>
   </prefer-application-packages>

   <prefer-application-resources>
   <resource-name>javax.faces.*</resource-name>
   <resource-name>com.sun.faces.*</resource-name>
   <resource-name>com.bea.faces.*</resource-name>

<resource-name>META-INF/services/javax.servlet.ServletContainerInitializer</resource-name>
</prefer-application-resources>```

答:
The error message "java.lang.NoSuchMethodError" indicates a library collision with the JPA 2.0 Library of Weblogic. Since you are packing your own library for that, try adding "javax.persistence.*" to the weblogic.xml

Option 2: Add the JPA 2.1 Support to weblogic classpath

In your domain/bin/setDomainEnv (.cmd for windows, .sh for unix) add a PRE_CLASSPATH Variable. On a windows System this would look like this:

```<code>set PRE_CLASSPATH=C:/weblogic_12130/oracle_common/modules/javax.persistence_2.1.jar;C:/weblogic_12130/wlserver/modules/com.oracle.weblogic.jpa21support_1.0.0.0_2-1.jar
</code>```

Body:
The error message "java.lang.NoSuchMethodError" indicates a library collision with the JPA 2.0 Library of Weblogic. Since you are packing your own library for that, try adding "javax.persistence.*" to the weblogic.xml

Option 2: Add the JPA 2.1 Support to weblogic classpath

In your domain/bin/setDomainEnv (.cmd for windows, .sh for unix) add a PRE_CLASSPATH Variable. On a windows System this would look like this:

set PRE_CLASSPATH=C:/weblogic_12130/oracle_common/modules/javax.persistence_2.1.jar;C:/weblogic_12130/wlserver/modules/com.oracle.weblogic.jpa21support_1.0.0.0_2-1.jar


问:
Get excel cell address in Python 2 using openpyxl
I have the following scenario:

Read the excel file of column A for all active rows

Run if else statement: if column A == 'registered', do nothing and just read the next row. Else, get cell address (not value) and do some actions

For example, here is my "sample.xlsx":

[row 1] A1=registered B1=user1

[row 2] A2=registered B2=user2

[row 3] A3=null B3=user3

my code should ignore row1 and row2 and proceed with row 3. In row 3, I should get "A3" and do some actions.

```<code>from openpyxl import load_workbook
book = load_workbook(filename='sample.xlsx')
sheet = book.active
first_column = sheet['A']

for x in xrange(len(first_column)):
    status = first_column[x].value

    if status == 'registered':
      #enter code to just proceed with the next row

    else:
      #enter code to get the column cell range and do some actions

book.save('sample.xlsx')
</code>```

I got stucked with the scenario 2, I am a newbie in python, I have a code in java using FileScanner but I need it in Python 2. Appreciate your help.

UPDATE:
I already have an answer below but just wondering if there are any other method??

答:
Have a look

```<code>import openpyxl

wb = openpyxl.load_workbook('sample.xlsx')
ws = wb.active

for row in ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row)):
   for cell in row:
     if cell.value != "registered":
        print cell.column
        print cell.row
        ## further processing here #######
</code>```

No need to write logic for explicit row iteration this for loop will take care of that.

Hope it will help you :)

Body:
I have the following scenario:

Read the excel file of column A for all active rows

Run if else statement: if column A == 'registered', do nothing and just read the next row. Else, get cell address (not value) and do some actions

For example, here is my "sample.xlsx":

[row 1] A1=registered B1=user1

[row 2] A2=registered B2=user2

[row 3] A3=null B3=user3

my code should ignore row1 and row2 and proceed with row 3. In row 3, I should get "A3" and do some actions.

from openpyxl import load_workbook
book = load_workbook(filename='sample.xlsx')
sheet = book.active
first_column = sheet['A']

for x in xrange(len(first_column)):
    status = first_column[x].value

    if status == 'registered':
      #enter code to just proceed with the next row

    else:
      #enter code to get the column cell range and do some actions

book.save('sample.xlsx')

I got stucked with the scenario 2, I am a newbie in python, I have a code in java using FileScanner but I need it in Python 2. Appreciate your help.

UPDATE:
I already have an answer below but just wondering if there are any other method??

Body:
Have a look

import openpyxl

wb = openpyxl.load_workbook('sample.xlsx')
ws = wb.active

for row in ws.iter_rows('A{}:A{}'.format(ws.min_row,ws.max_row)):
   for cell in row:
     if cell.value != "registered":
        print cell.column
        print cell.row
        ## further processing here #######

No need to write logic for explicit row iteration this for loop will take care of that.

Hope it will help you :)


问:
Partially used on the application
Is it possible to use Angular not for all the application but only for some parts ?

I use Express for the server side and few pages are already made. Should I rebuild them or can I use Angular for only some parts ?

答:
If you want to build only some page in angular, do it something like this:

Add angular script in header.

define your body like this:

```<code><body ng-app="myApp">
</body>
</code>```

Define module like this:

```<code><script>
var app = angular.module("myApp", []);
</script>
</code>```

Now on those pages where you want to use angular define a ng-controller at the very first div like this:

```<code><div ng-controller="myCtrl">
</div>
</code>```

and now define your controller like this:

```<code><script>
 app.controller("myCtrl", function($scope) {
     //here you can define all your logic for page.
 });
</script>
</code>```

Title: Partially used on the application

Body:
If you want to build only some page in angular, do it something like this:

Add angular script in header.

define your body like this:

<body ng-app="myApp">
</body>

Define module like this:

<script>
var app = angular.module("myApp", []);
</script>

Now on those pages where you want to use angular define a ng-controller at the very first div like this:

<div ng-controller="myCtrl">
</div>

and now define your controller like this:

<script>
 app.controller("myCtrl", function($scope) {
     //here you can define all your logic for page.
 });
</script>


问:
Unable to install ffmpeg on CircleCi 2.0
I have Ruby on Rails project which uses CircleCi to run tests. In the past I was using CircleCi 1.0 but now I migrated to CircleCi 2.0. I have problem with installing ffmpeg. CircleCi 2.0 uses Ubuntu 14.04. I install ffmpeg like this:

```<code># ffmpeg installation
sudo add-apt-repository ppa:mc3man/trusty-media -y
sudo apt-get update
sudo apt-get install ffmpeg
</code>```

and my circle.yml config file looks like this:

```<code>version: 2
environment:
  TZ: "/usr/share/zoneinfo/America/Los_Angeles"

jobs:
  build:
    parallelism: 2
    working_directory: ~/circleci-survey-builder
    docker:
      - image: circleci/ruby:2.4.1-node
        environment:
          PGHOST: 127.0.0.1
          PGUSER: ubuntu
          RAILS_ENV: test
      - image: circleci/postgres:9.6-alpine
        environment:
          POSTGRES_USER: ubuntu
          POSTGRES_DB: circle_test
          POSTGRES_PASSWORD: ''
    steps:
      - checkout

      - run:
          name: 'Install CircleCI dependencies'
          command: bash deploy/circle-dependencies.sh

      - type: cache-restore
        key: dashboard-{{ checksum "Gemfile.lock" }}

      - run:
          name: 'Install gems'
          command: bundle install --path vendor/bundle

      - type: cache-save
        key: dashboard-{{ checksum "Gemfile.lock" }}
        paths:
          - vendor/bundle

      - run:
          name: 'Install postgresql-client'
          command: sudo apt install postgresql-client

      - run:
          name: 'Create database.yml'
          command: mv config/database.ci.yml config/database.yml

      - run:
          name: Set up SurveyBuilder database
          command: bundle exec rake db:structure:load --trace

      - run:
          name: 'Run tests'
          command: |
            bundle exec rspec spec
</code>```

It returns following error when I run build on CircleCi:

```<code>#!/bin/bash -eo pipefail
bash deploy/circle-dependencies.sh

Fetching: bundler-1.16.0.gem (100%)
Successfully installed bundler-1.16.0
1 gem installed
sudo: add-apt-repository: command not found

Ign http://deb.debian.org jessie InRelease

Get:1 http://deb.debian.org jessie-updates InRelease [145 kB]

10% [1 InRelease 13.8 kB/145 kB 10%] [Waiting for headers] [Connecting to securHit http://deb.debian.org jessie Release.gpg

Hit http://deb.debian.org jessie Release

Get:2 http://deb.debian.org jessie-updates/main amd64 Packages [23.2 kB]

Get:3 http://deb.debian.org jessie/main amd64 Packages [9063 kB]

Get:4 http://security.debian.org jessie/updates InRelease [63.1 kB]

Get:5 http://security.debian.org jessie/updates/main amd64 Packages [610 kB]

100% [3 Packages 9063 kB]100% [3 Packages 9063 kB]Fetched 9904 kB in 1s (8178 kB/s)

Reading package lists... 1%
Reading package lists... 61%
Reading package lists... Done

Reading package lists... 1%
Reading package lists... Done

Building dependency tree... 0%
Building dependency tree

Reading state information... Done

Package ffmpeg is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'ffmpeg' has no installation candidate
Exited with code 100
</code>```

How can I fix that?

答:
Since the system is now Debian 8.0 (jessie) and not Ubuntu 14.04. You need to enable backports</p>

```<code>sudo sh -c 'echo "deb http://ftp.debian.org/debian jessie-backports main" >> /etc/apt/sources.list'
apt update
apt install -y ffmpeg
</code>```

Body:
I have Ruby on Rails project which uses CircleCi to run tests. In the past I was using CircleCi 1.0 but now I migrated to CircleCi 2.0. I have problem with installing ffmpeg. CircleCi 2.0 uses Ubuntu 14.04. I install ffmpeg like this:

# ffmpeg installation
sudo add-apt-repository ppa:mc3man/trusty-media -y
sudo apt-get update
sudo apt-get install ffmpeg

and my circle.yml config file looks like this:

version: 2
environment:
  TZ: "/usr/share/zoneinfo/America/Los_Angeles"

jobs:
  build:
    parallelism: 2
    working_directory: ~/circleci-survey-builder
    docker:
      - image: circleci/ruby:2.4.1-node
        environment:
          PGHOST: 127.0.0.1
          PGUSER: ubuntu
          RAILS_ENV: test
      - image: circleci/postgres:9.6-alpine
        environment:
          POSTGRES_USER: ubuntu
          POSTGRES_DB: circle_test
          POSTGRES_PASSWORD: ''
    steps:
      - checkout

      - run:
          name: 'Install CircleCI dependencies'
          command: bash deploy/circle-dependencies.sh

      - type: cache-restore
        key: dashboard-{{ checksum "Gemfile.lock" }}

      - run:
          name: 'Install gems'
          command: bundle install --path vendor/bundle

      - type: cache-save
        key: dashboard-{{ checksum "Gemfile.lock" }}
        paths:
          - vendor/bundle

      - run:
          name: 'Install postgresql-client'
          command: sudo apt install postgresql-client

      - run:
          name: 'Create database.yml'
          command: mv config/database.ci.yml config/database.yml

      - run:
          name: Set up SurveyBuilder database
          command: bundle exec rake db:structure:load --trace

      - run:
          name: 'Run tests'
          command: |
            bundle exec rspec spec

It returns following error when I run build on CircleCi:

#!/bin/bash -eo pipefail
bash deploy/circle-dependencies.sh

Fetching: bundler-1.16.0.gem (100%)
Successfully installed bundler-1.16.0
1 gem installed
sudo: add-apt-repository: command not found

Ign http://deb.debian.org jessie InRelease

Get:1 http://deb.debian.org jessie-updates InRelease [145 kB]

10% [1 InRelease 13.8 kB/145 kB 10%] [Waiting for headers] [Connecting to securHit http://deb.debian.org jessie Release.gpg

Hit http://deb.debian.org jessie Release

Get:2 http://deb.debian.org jessie-updates/main amd64 Packages [23.2 kB]

Get:3 http://deb.debian.org jessie/main amd64 Packages [9063 kB]

Get:4 http://security.debian.org jessie/updates InRelease [63.1 kB]

Get:5 http://security.debian.org jessie/updates/main amd64 Packages [610 kB]

100% [3 Packages 9063 kB]100% [3 Packages 9063 kB]Fetched 9904 kB in 1s (8178 kB/s)

Reading package lists... 1%
Reading package lists... 61%
Reading package lists... Done

Reading package lists... 1%
Reading package lists... Done

Building dependency tree... 0%
Building dependency tree

Reading state information... Done

Package ffmpeg is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'ffmpeg' has no installation candidate
Exited with code 100

How can I fix that?

Body:
Since the system is now Debian 8.0 (jessie) and not Ubuntu 14.04. You need to enable backports

sudo sh -c 'echo "deb http://ftp.debian.org/debian jessie-backports main" >> /etc/apt/sources.list'
apt update
apt install -y ffmpeg


问:
dates with "and" at the last date freemarker
I have a list of dates seperated by comas. but I want an "and" before the last date.
I want it to look like this:

date, date, date and (last)date.

my code:

```<code><#list MySequence as x>${x}<#sep>,</#list>
</code>```

cant figure how to find the last date and add the "and" to it

thanks

答:
You could decide based on the current index:

```<code><#list MySequence as x>${x}<#sep><#if x?index == MySequence?size - 2> and <#else>, </#if></#list>
</code>```

It's not very terse... so if you will do this often, create a macro for it.

Body:
I have a list of dates seperated by comas. but I want an "and" before the last date.
I want it to look like this:

date, date, date and (last)date.

my code:

<#list MySequence as x>${x}<#sep>,</#list>

cant figure how to find the last date and add the "and" to it

thanks

Body:
You could decide based on the current index:

<#list MySequence as x>${x}<#sep><#if x?index == MySequence?size - 2> and <#else>, </#if></#list>

It's not very terse... so if you will do this often, create a macro for it.


问:
Disable/enable an input with jQuery?
```<code>$input.disabled = true;
</code>```

or

```<code>$input.disabled = "disabled";
</code>```

Which is the standard way? And, conversely, how do you enable a disabled input?

答:
I used @gnarf answer and added it as function

```<code>   $.fn.disabled = function (isDisabled) {
     if (isDisabled) {
       this.attr('disabled', 'disabled');
     } else {
       this.removeAttr('disabled');
     }
   };
</code>```

Then use like this

```<code>$('#myElement').disable(true);
</code>```

Title: Disable/enable an input with jQuery?

Body:
$input.disabled = true;

or

$input.disabled = "disabled";

Which is the standard way? And, conversely, how do you enable a disabled input?

Body:
I used @gnarf answer and added it as function

   $.fn.disabled = function (isDisabled) {
     if (isDisabled) {
       this.attr('disabled', 'disabled');
     } else {
       this.removeAttr('disabled');
     }
   };

Then use like this

$('#myElement').disable(true);


问:
Common children, but different root: possible to avoid re-render and re-mount in children?
Our current app has each screen implement a AppLayout component, that takes a body and a header prop.

While the body prop is often very different, the (quite complex) header has a lot of repeating content between the various screens. At times just the title text is changing.

Currently, going from one route to another rerenders the entire screen, a quite wasteful operation given the similar content. Is there a way of avoid re-rendering and re-mounting of common sub-components between two screens?

Example of routing setup

This shows how a lot is seemingly repeated in the trees.

```<code><Route
  exact
  path='/user'
  component={()=> {
      return (<AppLayout
          header={<AppHeader heading="Users"/>}
          main={<UserList/>} />);
  } />
<Route
  exact
  path='/user/new'
  component={()=>{
      return (<AppLayout
          header={<AppHeader heading="Create user"/>}
          main={<UserAccountAdd />} />);
  } />
<Route
  exact
  path='/user/:userId'
  component={({ match }) =>
      return (<AppLayout
          header={<AppHeader heading="User profile"/>}
          main={<UserAccountInfo userId={match.params.userId}/>}
          />)
  } />
</code>```

The AppHeader component basically looks like

```<code>connected(div)
    ReallyExpensiveFoo
    ReallyExpensiveBar
    <p>{this.props.title}</p>
</code>```

Basically I would like to have seen that the
 tag of header that renders the heading title should remount.

答: React Router has a good SideBar example on their site that is quite relevant. Basically it injects pairwise Routes at different parts in the hierarchy, so they update independently to routing changes.

Body:
Our current app has each screen implement a AppLayout component, that takes a body and a header prop.

While the body prop is often very different, the (quite complex) header has a lot of repeating content between the various screens. At times just the title text is changing.

Currently, going from one route to another rerenders the entire screen, a quite wasteful operation given the similar content. Is there a way of avoid re-rendering and re-mounting of common sub-components between two screens?

Example of routing setup

This shows how a lot is seemingly repeated in the trees.

<Route
  exact
  path='/user'
  component={()=> {
      return (<AppLayout
          header={<AppHeader heading="Users"/>}
          main={<UserList/>} />);
  } />
<Route
  exact
  path='/user/new'
  component={()=>{
      return (<AppLayout
          header={<AppHeader heading="Create user"/>}
          main={<UserAccountAdd />} />);
  } />
<Route
  exact
  path='/user/:userId'
  component={({ match }) =>
      return (<AppLayout
          header={<AppHeader heading="User profile"/>}
          main={<UserAccountInfo userId={match.params.userId}/>}
          />)
  } />

The AppHeader component basically looks like

connected(div)
    ReallyExpensiveFoo
    ReallyExpensiveBar

{this.props.title}

Basically I would like to have seen that the
 tag of header that renders the heading title should remount.


答: Just follow the project's existing conventions, if it has any for #include directives.  If it doesn't, it doesn't really matter what you do as long as you're consistent.

Title: What is the better way of including a header file? #include<> followed by #include"" or the otherwise?

Body:
Possible Duplicates:

  what is the difference between #include <filename> and #include “filename”

  C/C++ include file order/best practices

In what order should the include statements in a header file and source file come in C++? #include <> followed by #include "" or the otherwise?

Also, should the header file of a source file precede all include statements in source file?


问:
Rails query all records whose all associated record has nil or some specific value in some specific fields
I have two models with a has_many and belongs_to relations:

```<code>class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end
</code>```

How do I find all those Parents whose all children have nil value in some specific field.

答:
'All children have a condition' is generally much harder!  I'm sure there's some way to do it with a complicated joins, but the easier ruby way is to do something like the following:</p>

```<code>parents = []
Parent.includes(:children).find_each do |parent|
  parents.push(parent) if parent.children.collect{|child| child.field.nil?}.reduce(:&)
end
</code>```

Body:
I have two models with a has_many and belongs_to relations:

class Parent < ActiveRecord::Base
  has_many :children
end

class Child < ActiveRecord::Base
  belongs_to :parent
end

How do I find all those Parents whose all children have nil value in some specific field.

Body:
'All children have a condition' is generally much harder!  I'm sure there's some way to do it with a complicated joins, but the easier ruby way is to do something like the following:

parents = []
Parent.includes(:children).find_each do |parent|
  parents.push(parent) if parent.children.collect{|child| child.field.nil?}.reduce(:&)
end


问:
Bootstrap 3 mobile menu 100% height
Whats the best method for getting 100% height for collapse bootstrap menu (mobile).

.navbar-collapse { max-height: 100% !important; min-height: 100% !important; height: 100%;}

is not really working here

答:
None of the previous answers worked for me. My .navbar-collapse has position: fixed; but I assume this is also the case for the original question.

The key to solve this was to have the child element of .navbar-collapse to have height: 100vh.

Note: I'm using Bootstrap 4, so collapse.in is now collapse.show.

HTML code:

```<code><div id="main-nav" class="collapse navbar-collapse">
    <ul class="nav navbar-nav">
        ...
    </ul>
</div>
</code>```

(S)CSS:

```<code>.navbar-collapse {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
}
.navbar-collapse.collapse.show {
    height: 100vh;
}
.navbar-nav {
    height: 100vh;
}
</code>```

Title: Bootstrap 3 mobile menu 100% height

Body:
None of the previous answers worked for me. My .navbar-collapse has position: fixed; but I assume this is also the case for the original question.

The key to solve this was to have the child element of .navbar-collapse to have height: 100vh.

Note: I'm using Bootstrap 4, so collapse.in is now collapse.show.

HTML code:

<div id="main-nav" class="collapse navbar-collapse">
    <ul class="nav navbar-nav">
        ...
    </ul>
</div>

(S)CSS:

.navbar-collapse {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
}
.navbar-collapse.collapse.show {
    height: 100vh;
}
.navbar-nav {
    height: 100vh;
}


答:
We can use rank and as it is needed by each column, we loop through the columns (apply with MARGIN=2)

```<code>apply(df, 2, rank)
</code>```

Title: Order a space matrix by index

Body:
I have matrix space some locations 1, 2, 3, and 4

df<-matrix(data=c(0.00, 4.69, 12.63, 2.99, 4.69, 0.00, 17.30, 5.15, 12.63, 17.30, 0.00, 13.72, 2.99, 5.15, 13.72, 0.00), ncol=4)
colnames(df)<-c(seq(1:4))
rownames(df)<-c(seq(1:4))
df

#    1     2     3     4
#1  0.00  4.69 12.63  2.99
#2  4.69  0.00 17.30  5.15
#3 12.63 17.30  0.00 13.72
#4  2.99  5.15 13.72  0.00

and I would like to order this matrix in descending order by rank of each space row, so get

#       1     2     3     4
#1      1     2     2     2
#2      3     1     4     3
#3      4     4     1     4
#4      2     3     3     1

Any suggestions on how I could achieve this? Thanks.

Body:
We can use rank and as it is needed by each column, we loop through the columns (apply with MARGIN=2)

apply(df, 2, rank)


问:
String to hexadecimal conversion - Python - ValueError: Invalid conversion specification
I need to split a four digit string to two hexadecimal numbers.

Eg: string = "ABCD"
expected output = 0xAB 0xCD

I tried these statements:

```<code>>>data = "0000"
>>[byte1, byte2] = [data[:2], data[2:]]
>>byteInt = int(byte1,16)
>>byteHex = format(byteInt,'0#4x')
>>print byteHex
</code>```

I am getting the error, "ValueError: Invalid conversion specification" at the line "byteHex = format(byteInt,'0#4x')"

答:
The leading zero in the format specification is not needed since you have not specified any alignment:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]

fill is conditioned on alignment:

```<code>>>> byteHex = format(byteInt,'#4x')
>>> byteHex
' 0x0'
</code>```

To use the optional fill in the format specification, you should specify an alignment:

```<code>>>> byteHex = format(byteInt,'0>#4x') # left align
>>> byteHex
'0x00'
</code>```

Body:
I need to split a four digit string to two hexadecimal numbers.

Eg: string = "ABCD"
expected output = 0xAB 0xCD

I tried these statements:

>>data = "0000"
>>[byte1, byte2] = [data[:2], data[2:]]
>>byteInt = int(byte1,16)
>>byteHex = format(byteInt,'0#4x')
>>print byteHex

I am getting the error, "ValueError: Invalid conversion specification" at the line "byteHex = format(byteInt,'0#4x')"

Body:
The leading zero in the format specification is not needed since you have not specified any alignment:

format_spec ::=  [[fill]align][sign][#][0][width][,][.precision][type]

fill is conditioned on alignment:

>>> byteHex = format(byteInt,'#4x')
>>> byteHex
' 0x0'

To use the optional fill in the format specification, you should specify an alignment:

>>> byteHex = format(byteInt,'0>#4x') # left align
>>> byteHex
'0x00'


问:
Double iteration to a list python 3
```<code>for x in range(0,img_row):
    for y in range(0,img_col):
       img_lst.append([img[x,y][0],img[x,y][1],img[x,y][2]])
return img_lst
</code>```

How do I use list Comprehension here?

```<code>img_lst = [img[x,y][0], img[x,y][1], img[x,y][2] y for y in range(0,img_col) for x in range(0, img_row)]
</code>```

I tried this but it is giving my invalid syntax and when I remove "y" in the beginning it gives me that Y is not defined

the whole function:

```<code>def cvimg_to_list(img):
    img_row = img.shape[0]
    img_col = img.shape[1]
    img_lst=[]

    img_lst = [img[x,y][0], img[x,y][1], img[x,y][2] y for y in range(0,img_col) for x in range(0, img_row)]
    return img_lst
</code>```

答:
To convert nested loops with a list.append() call to a list comprehension, all you have to do is move everything between the .append(...) parentheses to the front, remove the : colons after the for loops, and finally add [...] around the result:

```<code>[
[img[x,y][0],img[x,y][1],img[x,y][2]]
for x in range(0,img_row)
    for y in range(0,img_col)
]
</code>```

Note that the order of the for loops does not change!

This can then be put onto one line; I added some whitespace for readability and simplified the range() calls:

```<code>[[img[x, y][0], img[x, y][1], img[x, y][2]]
 for x in range(img_row) for y in range(img_col)]
</code>```

Because you build a new list with the first 3 values from img[x, y], you can also use slicing:

```<code>[img[x, y][:3] for x in range(img_row) for y in range(img_col)]
</code>```

You made three mistakes in your attempt; you swapped the order of the for loops, you added in an extra, stray y, and you dropped the ] closing bracket for the list object you produce each iteration.

Title: Double iteration to a list python 3

Body:
for x in range(0,img_row):
    for y in range(0,img_col):
       img_lst.append([img[x,y][0],img[x,y][1],img[x,y][2]])
return img_lst

How do I use list Comprehension here?

img_lst = [img[x,y][0], img[x,y][1], img[x,y][2] y for y in range(0,img_col) for x in range(0, img_row)]

I tried this but it is giving my invalid syntax and when I remove "y" in the beginning it gives me that Y is not defined

the whole function:

def cvimg_to_list(img):
    img_row = img.shape[0]
    img_col = img.shape[1]
    img_lst=[]

    img_lst = [img[x,y][0], img[x,y][1], img[x,y][2] y for y in range(0,img_col) for x in range(0, img_row)]
    return img_lst

Body:
To convert nested loops with a list.append() call to a list comprehension, all you have to do is move everything between the .append(...) parentheses to the front, remove the : colons after the for loops, and finally add [...] around the result:

[
[img[x,y][0],img[x,y][1],img[x,y][2]]
for x in range(0,img_row)
    for y in range(0,img_col)
]

Note that the order of the for loops does not change!

This can then be put onto one line; I added some whitespace for readability and simplified the range() calls:

[[img[x, y][0], img[x, y][1], img[x, y][2]]
 for x in range(img_row) for y in range(img_col)]

Because you build a new list with the first 3 values from img[x, y], you can also use slicing:

[img[x, y][:3] for x in range(img_row) for y in range(img_col)]

You made three mistakes in your attempt; you swapped the order of the for loops, you added in an extra, stray y, and you dropped the ] closing bracket for the list object you produce each iteration.


问:
How to remove XmlRootElement wrapper while marshalling in JAXB
Lets say I have the following POJO class, which I want to marshal using JAXB

```<code>@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
Class Employee {
  private String firstName;
  private String lastName;
  private int age;
}
</code>```

Now I am marshaling an instance of Employee class using following code snippet

```<code>JAXBContext jc = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
OutputStream os = new FileOutputStream("C:\\employee.xml")
marshaller.marshal(employee, os);
</code>```

The generated XML looks like

```<code><Employee>
  <firstName>Mark</firstName>
  <lastName>Smith</lastName>
  <age>30</age>
</Employee>
</code>```

Question : I don't want the default Employee tag around employee data.
i.e.

I want output as following

```<code> <firstName>Mark</firstName>
  <lastName>Smith</lastName>
  <age>30</age>
</code>```

How to achieve this?

答:
Not sure what are you asking. XML document must contain root element.
You can change it using QName (example below), but it must exist.</p>

```<code>JAXBContext jc = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
QName qName = new QName("", "whatever");
JAXBElement<Employee> newRootEmployee = new JAXBElement<Employee>(qName, Employee.class, employee);
OutputStream os = new FileOutputStream("C:\\employee.xml")
marshaller.marshal(newRootEmployee , os);
</code>```

Body:
Lets say I have the following POJO class, which I want to marshal using JAXB

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
Class Employee {
  private String firstName;
  private String lastName;
  private int age;
}

Now I am marshaling an instance of Employee class using following code snippet

JAXBContext jc = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
OutputStream os = new FileOutputStream("C:\\employee.xml")
marshaller.marshal(employee, os);

The generated XML looks like

<Employee>
  <firstName>Mark</firstName>
  <lastName>Smith</lastName>
  <age>30</age>
</Employee>

Question : I don't want the default Employee tag around employee data.
i.e.

I want output as following

 <firstName>Mark</firstName>
  <lastName>Smith</lastName>
  <age>30</age>

How to achieve this?

Body:
Not sure what are you asking. XML document must contain root element.
You can change it using QName (example below), but it must exist.

JAXBContext jc = JAXBContext.newInstance(Employee.class);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
QName qName = new QName("", "whatever");
JAXBElement<Employee> newRootEmployee = new JAXBElement<Employee>(qName, Employee.class, employee);
OutputStream os = new FileOutputStream("C:\\employee.xml")
marshaller.marshal(newRootEmployee , os);


问:
How to write scala code not like java code?
During an interview, the tech lead said my scala code was just like java code, but using scala api and he wanted me to improve on that.

I am a 3-year java developer and I began scala coding by following the MOOC on Coursera.

Can anyone tell me what is the problem and how can I improve it, please?

I got the job because of my Java acknowledge but the job is based on scala and the coding style is one thing to fix during the trial period.

```<code>object Extraction {

// IntelliJ use .idea/modules as current working directory
  val FilePathPre = "../../src/main/resources/"
  val UserIdFile = "lookup_user.csv"
  val ProductIdFile = "lookup_product.csv"
  val RatingFile = "agg_ratings.csv"

  def readFile(file: String): Iterator[((String, String), String, String)] = {
val Splitter = ","
Source.fromInputStream(this.getClass.getResourceAsStream(file)).getLines()
      .map(_.split(Splitter))
      .filter(_.size >= 4) // in case line is not valid
      .map(x => ((x(0), x(1)), x(2), x(3))) // (userId, ItemId), rating, time
  }

  def filePrinter(fileName: String, lines: mutable.Map[String, Int]) = {
val file = new File(fileName)
val bw = new BufferedWriter(new FileWriter(file))
lines.toArray.sortWith((a, b) => a._2 < b._2)
     .map(x => x._1 + "," + x._2.toString + "\n")
     .foreach(bw.write)
bw.close()
  }

  def aggFilePrinter(fileName: String, lines: mutable.Map[(Int, Int), Float]) = {
val file = new File(fileName)
val bw = new BufferedWriter(new FileWriter(file))
lines.foreach(x => {
     val line = x._1._1.toString + "," + x._1._2.toString + "," + (math.round(x._2 * 100.0) / 100.0).toFloat + "\n"
     bw.write(line)
   })
bw.close()
  }

  /**
* * une pénalité multiplicative de 0.95 est appliquée au rating
*   pour chaque jour d'écart avec le timestamp maximal de input.csv
*
* @param nowTime maximal timestamp at input.csv
* @param pastTime    current rating time
* @param rating  original rating
* @return final rating multiplied by 0.95 for every day interval from the maximal timestamp
*/
  def finalRating(nowTime: String, pastTime: String, rating: String): Float = {
val now =
  LocalDateTime.ofInstant(Instant.ofEpochMilli(nowTime.toLong), ZoneId.systemDefault())
val past =
  LocalDateTime.ofInstant(Instant.ofEpochMilli(pastTime.toLong), ZoneId.systemDefault())
val diff = ChronoUnit.DAYS.between(past, now)
(math.pow(0.95, diff) * rating.toFloat).toFloat
  }

  /**
*
* @param file file to extract
*/
  def fileDispatcher(file: String) = {

    /**
  * get idIndice or increment to idIndice and put it to id map
  * @param id  id in String
  * @param idIndice id in Int
  * @param idMap userIdMap or productIdMap
  * @return (indice for id, max idIndice)
  */
def getIndice(id: String, idIndice: Int, idMap: mutable.Map[String, Int]): (Int, Int) = {
  idMap.get(id) match {
    case Some(i) => (i, idIndice)
    case None => {
      val indice = idIndice + 1
      idMap += (id -> indice)
      (indice, indice)
    }
  }
}

// 1. scan the file the find the max time
val maxTime = readFile(file).reduce((a, b) => if(a._3 > b._3) a else b)._3

// 2. apply rating condition, calculate rating and return only valid rating lines
val validLines = readFile(file).map(x => (x._1, finalRating(maxTime.toString, x._3, x._2))).filter(_._2 > 0.01)

// 3. loop file lines, sum ratings by (userId, productId), and combine id_String and id_Int
val userIdMap = mutable.Map[String, Int]() // (userId, userIdAsInt)
val productIdMap = mutable.Map[String, Int]() // (productId, productIdAsInt)
val userProductRatingMap = mutable.Map[(Int, Int), Float]() // (userIdAsInt, productIdAsInt, ratingSum)

var userIdIndice = -1
var productIdIndice = -1

validLines.foreach(x => {
  val userIdString = x._1._1
  val userId = getIndice(userIdString, userIdIndice, userIdMap)
  userIdIndice = userId._2

  val productIdString = x._1._2
  val productId = getIndice(productIdString, productIdIndice, productIdMap)
  productIdIndice = productId._2

  val key = (userId._1, productId._1)
  userProductRatingMap.get(key) match {
    case Some(i) => userProductRatingMap += (key -> (i + x._2))
    case None => userProductRatingMap += (key -> x._2)
  }
})

filePrinter(FilePathPre + UserIdFile, userIdMap)
filePrinter(FilePathPre + ProductIdFile, productIdMap)
aggFilePrinter(FilePathPre + RatingFile, userProductRatingMap)
  }
}
</code>```

答:
Apart of javish code you have also code style issues, suggest to read https://docs.scala-lang.org/style/ at the start (this is not an ultimate guide, but for start is ok). Avoid to use ._1 on tuples, use match { case (a, b, c) => ... } instead.

The main issue is that you use mutable structures, so in scala every structure is immutable by default and it should stay like that unless you have a strong reason to have it mutable. It is more about functional programming which from one perspective tries to avoid mutability and side effects, you can google for this topic more.

So remove mutable. from your code and replace foreach with eg. foldLeft to get newly created immutable.Map on each iteration instead of modifying existing one.

Body:
During an interview, the tech lead said my scala code was just like java code, but using scala api and he wanted me to improve on that.

I am a 3-year java developer and I began scala coding by following the MOOC on Coursera.

Can anyone tell me what is the problem and how can I improve it, please?

I got the job because of my Java acknowledge but the job is based on scala and the coding style is one thing to fix during the trial period.

object Extraction {

// IntelliJ use .idea/modules as current working directory
  val FilePathPre = "../../src/main/resources/"
  val UserIdFile = "lookup_user.csv"
  val ProductIdFile = "lookup_product.csv"
  val RatingFile = "agg_ratings.csv"

  def readFile(file: String): Iterator[((String, String), String, String)] = {
val Splitter = ","
Source.fromInputStream(this.getClass.getResourceAsStream(file)).getLines()
      .map(_.split(Splitter))
      .filter(_.size >= 4) // in case line is not valid
      .map(x => ((x(0), x(1)), x(2), x(3))) // (userId, ItemId), rating, time
  }

  def filePrinter(fileName: String, lines: mutable.Map[String, Int]) = {
val file = new File(fileName)
val bw = new BufferedWriter(new FileWriter(file))
lines.toArray.sortWith((a, b) => a._2  x._1 + "," + x._2.toString + "\n")
     .foreach(bw.write)
bw.close()
  }

  def aggFilePrinter(fileName: String, lines: mutable.Map[(Int, Int), Float]) = {
val file = new File(fileName)
val bw = new BufferedWriter(new FileWriter(file))
lines.foreach(x => {
     val line = x._1._1.toString + "," + x._1._2.toString + "," + (math.round(x._2 * 100.0) / 100.0).toFloat + "\n"
     bw.write(line)
   })
bw.close()
  }

  /**
* * une pénalité multiplicative de 0.95 est appliquée au rating
*   pour chaque jour d'écart avec le timestamp maximal de input.csv
*
* @param nowTime maximal timestamp at input.csv
* @param pastTime    current rating time
* @param rating  original rating
* @return final rating multiplied by 0.95 for every day interval from the maximal timestamp
*/
  def finalRating(nowTime: String, pastTime: String, rating: String): Float = {
val now =
  LocalDateTime.ofInstant(Instant.ofEpochMilli(nowTime.toLong), ZoneId.systemDefault())
val past =
  LocalDateTime.ofInstant(Instant.ofEpochMilli(pastTime.toLong), ZoneId.systemDefault())
val diff = ChronoUnit.DAYS.between(past, now)
(math.pow(0.95, diff) * rating.toFloat).toFloat
  }

  /**
*
* @param file file to extract
*/
  def fileDispatcher(file: String) = {

    /**
  * get idIndice or increment to idIndice and put it to id map
  * @param id  id in String
  * @param idIndice id in Int
  * @param idMap userIdMap or productIdMap
  * @return (indice for id, max idIndice)
  */
def getIndice(id: String, idIndice: Int, idMap: mutable.Map[String, Int]): (Int, Int) = {
  idMap.get(id) match {
    case Some(i) => (i, idIndice)
    case None => {
      val indice = idIndice + 1
      idMap += (id -> indice)
      (indice, indice)
    }
  }
}

// 1. scan the file the find the max time
val maxTime = readFile(file).reduce((a, b) => if(a._3 > b._3) a else b)._3

// 2. apply rating condition, calculate rating and return only valid rating lines
val validLines = readFile(file).map(x => (x._1, finalRating(maxTime.toString, x._3, x._2))).filter(_._2 > 0.01)

// 3. loop file lines, sum ratings by (userId, productId), and combine id_String and id_Int
val userIdMap = mutable.Map[String, Int]() // (userId, userIdAsInt)
val productIdMap = mutable.Map[String, Int]() // (productId, productIdAsInt)
val userProductRatingMap = mutable.Map[(Int, Int), Float]() // (userIdAsInt, productIdAsInt, ratingSum)

var userIdIndice = -1
var productIdIndice = -1

validLines.foreach(x => {
  val userIdString = x._1._1
  val userId = getIndice(userIdString, userIdIndice, userIdMap)
  userIdIndice = userId._2

  val productIdString = x._1._2
  val productId = getIndice(productIdString, productIdIndice, productIdMap)
  productIdIndice = productId._2

  val key = (userId._1, productId._1)
  userProductRatingMap.get(key) match {
    case Some(i) => userProductRatingMap += (key -> (i + x._2))
    case None => userProductRatingMap += (key -> x._2)
  }
})

filePrinter(FilePathPre + UserIdFile, userIdMap)
filePrinter(FilePathPre + ProductIdFile, productIdMap)
aggFilePrinter(FilePathPre + RatingFile, userProductRatingMap)
  }
}


问:
Why are the properties of Google_Service_Drive files only returning null?
I want to list all files in a folder shared with my Service Account. I'm trying to figure out what files have a 'parent' attribute set to the folder ID or folder name. However, all the objects that I output show "NULL" for nearly all fields. I've searched through the Google Drive API v3 and I can't even find the listFiles() function in it. Additionally, the documentation recommends using the Files.list function for outputting a list of files but when I use the Files.list function, I get an error as if the method doesn't exist. So I went back to using listFiles()... My code looks like this:

```<code>public function getTitlesAndIDs($folderID)
{

    // $capabilities = new \Google_Service_Drive_DriveFileCapabilities();
    // $capabilities->canListChildren = true;
    $files = $this->driveService->files->listFiles();

    var_dump($files);
}
</code>```

Trying to add capabilities just returns NULL as well. When I run listFiles() I get output like this:

```<code>["files"]=>
  array(100) {
    [0]=>
    object(Google_Service_Drive_DriveFile)#77 (65) {
      ["collection_key":protected]=>
      string(6) "spaces"
      ["appProperties"]=>
      NULL
      ["capabilitiesType":protected]=>
      string(42) "Google_Service_Drive_DriveFileCapabilities"
      ["capabilitiesDataType":protected]=>
      string(0) ""
      ["contentHintsType":protected]=>
      string(42) "Google_Service_Drive_DriveFileContentHints"
      ["contentHintsDataType":protected]=>
      string(0) ""
      ["createdTime"]=>
      NULL
      ["description"]=>
      NULL
      ["explicitlyTrashed"]=>
      NULL
      ["fileExtension"]=>
      NULL
      ["folderColorRgb"]=>
...
</code>```

Why are the values all coming back as NULL and how do I fix this so I can search by parent folders? Is there a php equivalent to the Files.list function?
Thanks in advance.

答: In addition to what @DalmTo said, one important thing to explicitly point out: you received NULL for nearly all fields because you didn't supply a list of fields, 'fields' as optional parameter.

Body:
I want to list all files in a folder shared with my Service Account. I'm trying to figure out what files have a 'parent' attribute set to the folder ID or folder name. However, all the objects that I output show "NULL" for nearly all fields. I've searched through the Google Drive API v3 and I can't even find the listFiles() function in it. Additionally, the documentation recommends using the Files.list function for outputting a list of files but when I use the Files.list function, I get an error as if the method doesn't exist. So I went back to using listFiles()... My code looks like this:

public function getTitlesAndIDs($folderID)
{

    // $capabilities = new \Google_Service_Drive_DriveFileCapabilities();
    // $capabilities->canListChildren = true;
    $files = $this->driveService->files->listFiles();

    var_dump($files);
}

Trying to add capabilities just returns NULL as well. When I run listFiles() I get output like this:

["files"]=>
  array(100) {
    [0]=>
    object(Google_Service_Drive_DriveFile)#77 (65) {
      ["collection_key":protected]=>
      string(6) "spaces"
      ["appProperties"]=>
      NULL
      ["capabilitiesType":protected]=>
      string(42) "Google_Service_Drive_DriveFileCapabilities"
      ["capabilitiesDataType":protected]=>
      string(0) ""
      ["contentHintsType":protected]=>
      string(42) "Google_Service_Drive_DriveFileContentHints"
      ["contentHintsDataType":protected]=>
      string(0) ""
      ["createdTime"]=>
      NULL
      ["description"]=>
      NULL
      ["explicitlyTrashed"]=>
      NULL
      ["fileExtension"]=>
      NULL
      ["folderColorRgb"]=>
...

Why are the values all coming back as NULL and how do I fix this so I can search by parent folders? Is there a php equivalent to the Files.list function?
Thanks in advance.