问:
Simplify by trying to merge 2 functions into only one - issue of overlapping
I did an exclusive checkbox where I have 2 <input> with two <button> (also exclusive with black/white color) by <input>; below the HTML code snippet:

```<code><div id="PlayerVsComputer" class="checkbox">
  <label><input type="checkbox" class="game">
   <div class="btn-group" role="group">
    <button type="button" class="btn btn-inverse btn-xs">Player</button>
    <button type="button" class="btn btn-classic btn-xs">Computer</button>
   </div>
  </label>
 </div>
 <div id="Player1VsPlayer2" class="checkbox">
  <label><input type="checkbox" class="game">
   <div class="btn-group" role="group">
    <button type="button" class="btn btn-inverse btn-xs">Player 1</button>
    <button type="button" class="btn btn-classic btn-xs">Player 2</button>
   </div>
  </label>
 </div>
</code>```

Everything is working fine with the following functions (to invert color black/white for both PlayerVsComputer and Player1VsPlayer2 type of game).

When mouse is out of the area of button, I did :

```<code>   // Restore original state when mouseleave
   $('#PlayerVsComputer').mouseleave(restore1);
   // Restore original state when mouseleave
   $('#Player1VsPlayer2').mouseleave(restore2);

   // Restore default choice for player vs computer
   function restore1() {
     buttonsPlayerVsComputer.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       buttonsPlayerVsComputer.eq(0).removeClass('btn-classic').addClass('btn-inverse');
       buttonsPlayerVsComputer.eq(1).removeClass('btn-inverse').addClass('btn-classic');
   }
   });}

// Restore default choice for player1 vs player2
   function restore2() {
     buttonsPlayer1VsPlayer2.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       buttonsPlayer1VsPlayer2.eq(0).removeClass('btn-classic').addClass('btn-inverse');
       buttonsPlayer1VsPlayer2.eq(1).removeClass('btn-inverse').addClass('btn-classic');
   }});}

</code>```

and when mouse enters into
 :

```<code>    // Flip buttons player vs computer color when mouse is entering
    buttonsPlayerVsComputer.mouseenter(toggle1);
    // Flip buttons player vs computer color when mouse is entering
    buttonsPlayer1VsPlayer2.mouseenter(toggle2);

 function toggle1() {
     buttonsPlayerVsComputer.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       $(value).toggleClass('btn-inverse btn-classic');
     }
   });
   }

   function toggle2() {
     buttonsPlayer1VsPlayer2.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       $(value).toggleClass('btn-inverse btn-classic');
     }
   });
   }
</code>```

Now, I would like to simplify it and merge toggle1 and toggle2 functions into unique toogle function. I tried to do :

```<code>  // toggle black/white for both types of game
  function toggle() {
     var element = $(this);
     element.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       $(value).toggleClass('btn-inverse btn-classic');
     }
   });
   }
</code>```

Following the same way for doing a unique function restore from restore1 an restore2 functions, I did :

```<code>// Restore default choice for both types of game
   function restore() {
     var element = $(this);
     element.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       element.eq(0).removeClass('btn-classic').addClass('btn-inverse');
       element.eq(1).removeClass('btn-inverse').addClass('btn-classic');
     }
    });
   }
</code>```

Unfortunately, this simplification doesn't work, it causes overlapping between buttons,
 :

You can see the first solution which works (with toggle1, toggle2, restore1, and restore2):

Version working with two functions

You can see the other result with trying to use only 2 functions (toggle and restore) but it doesn't work :

Version not working with only one function toggle and restore

How can I fix this?

答: Add element as a parameter of a function because if this is outside of an event listener, this will not return the element, but window.

ContentLicense: CC BY-SA 4.0

Body:
I did an exclusive checkbox where I have 2 <input> with two <button> (also exclusive with black/white color) by <input>; below the HTML code snippet:

  <input type="checkbox" class="game">

    <button type="button" class="btn btn-inverse btn-xs">Player</button>
    <button type="button" class="btn btn-classic btn-xs">Computer</button>

  <input type="checkbox" class="game">

    <button type="button" class="btn btn-inverse btn-xs">Player 1</button>
    <button type="button" class="btn btn-classic btn-xs">Player 2</button>

Everything is working fine with the following functions (to invert color black/white for both PlayerVsComputer and Player1VsPlayer2 type of game).

When mouse is out of the area of button, I did :

   // Restore original state when mouseleave
   $('#PlayerVsComputer').mouseleave(restore1);
   // Restore original state when mouseleave
   $('#Player1VsPlayer2').mouseleave(restore2);

   // Restore default choice for player vs computer
   function restore1() {
     buttonsPlayerVsComputer.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       buttonsPlayerVsComputer.eq(0).removeClass('btn-classic').addClass('btn-inverse');
       buttonsPlayerVsComputer.eq(1).removeClass('btn-inverse').addClass('btn-classic');
   }
   });}

// Restore default choice for player1 vs player2
   function restore2() {
     buttonsPlayer1VsPlayer2.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       buttonsPlayer1VsPlayer2.eq(0).removeClass('btn-classic').addClass('btn-inverse');
       buttonsPlayer1VsPlayer2.eq(1).removeClass('btn-inverse').addClass('btn-classic');
   }});}

and when mouse enters into
 :

    // Flip buttons player vs computer color when mouse is entering
    buttonsPlayerVsComputer.mouseenter(toggle1);
    // Flip buttons player vs computer color when mouse is entering
    buttonsPlayer1VsPlayer2.mouseenter(toggle2);

 function toggle1() {
     buttonsPlayerVsComputer.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       $(value).toggleClass('btn-inverse btn-classic');
     }
   });
   }

   function toggle2() {
     buttonsPlayer1VsPlayer2.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       $(value).toggleClass('btn-inverse btn-classic');
     }
   });
   }

Now, I would like to simplify it and merge toggle1 and toggle2 functions into unique toogle function. I tried to do :

  // toggle black/white for both types of game
  function toggle() {
     var element = $(this);
     element.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       $(value).toggleClass('btn-inverse btn-classic');
     }
   });
   }

Following the same way for doing a unique function restore from restore1 an restore2 functions, I did :

// Restore default choice for both types of game
   function restore() {
     var element = $(this);
     element.each(function(index, value) {
     if (!$(value).prop('disabled')) {
       element.eq(0).removeClass('btn-classic').addClass('btn-inverse');
       element.eq(1).removeClass('btn-inverse').addClass('btn-classic');
     }
    });
   }

Unfortunately, this simplification doesn't work, it causes overlapping between buttons,
 :

You can see the first solution which works (with toggle1, toggle2, restore1, and restore2):

Version working with two functions

You can see the other result with trying to use only 2 functions (toggle and restore) but it doesn't work :

Version not working with only one function toggle and restore

How can I fix this?


来源: stackexchange

问:
How to insert elements from arrayList to a map, sorting by their name?
I have a Worker class with grade and name for each worker.
I need to write a method that will return me a sorted map by the workers name..
The sort is by a Comparator I build that calld workersComparator..
And there is a limit that I cant write the word Worker(The class) more then once..I need to work generic way..

The comparator is like this:

```<code>import java.util.Comparator;

public class workersComparator implements Comparator<Worker<?>>{

    @Override
    public int compare(Worker<?> worker1, Worker<?> worker2) {
        return worker1.getName().compareTo(worker2.getName());
    }
}
</code>```

and the method is like this:

```<code>public static Map<Integer,?> createMap(){

    TreeSet<Worker<?>> treeSet = new TreeSet<>(new workersComparator());
    for (int i = 0; i < workers.size(); i++) {
        treeSet.add(workers.get(i));
    }
    Map<Integer,?> workersMap = new TreeMap<>();
    int index = 1;
    int pointer = 0;
    while( pointer < treeSet.size() ){
        workersMap.put(index,treeSet.iterator().next());
        index++;
        pointer++;
    }
    return workersMap;
}
</code>```

答:
You can use TreeMap which sort values by key. You will not require any comparator. Please see following snippet.

```<code> Map<String, Worker> sortedWorkers = new TreeMap<String,Worker>();
    for(Worker worker:workers){
         sortedWorkers.put(worker.getName(),worker);
    }
</code>```

This will add worker into map in sorted order by workers name.

By sortedWorkers.values() will return all workers sorted by their name.

ContentLicense: CC BY-SA 3.0

Body:
I have a Worker class with grade and name for each worker.
I need to write a method that will return me a sorted map by the workers name..
The sort is by a Comparator I build that calld workersComparator..
And there is a limit that I cant write the word Worker(The class) more then once..I need to work generic way..

The comparator is like this:

import java.util.Comparator;

public class workersComparator implements Comparator<Worker<?>>{

    @Override
    public int compare(Worker<?> worker1, Worker<?> worker2) {
        return worker1.getName().compareTo(worker2.getName());
    }
}

and the method is like this:

public static Map<Integer,?> createMap(){

    TreeSet<Worker<?>> treeSet = new TreeSet<>(new workersComparator());
    for (int i = 0; i < workers.size(); i++) {
        treeSet.add(workers.get(i));
    }
    Map<Integer,?> workersMap = new TreeMap<>();
    int index = 1;
    int pointer = 0;
    while( pointer < treeSet.size() ){
        workersMap.put(index,treeSet.iterator().next());
        index++;
        pointer++;
    }
    return workersMap;
}

Body:
You can use TreeMap which sort values by key. You will not require any comparator. Please see following snippet.

 Map<String, Worker> sortedWorkers = new TreeMap<String,Worker>();
    for(Worker worker:workers){
         sortedWorkers.put(worker.getName(),worker);
    }

This will add worker into map in sorted order by workers name.

By sortedWorkers.values() will return all workers sorted by their name.


问:
How to convert Dataset to a Scala Iterable?
Is there a way to convert a org.apache.spark.sql.Dataset to a scala.collection.Iterable?  It seems like this should be simple enough.</p>

答:
In Scala 2.11 you can do the following:</p>

```<code>import scala.collection.JavaConverters._

dataset.toLocalIterator.asScala.toIterable
</code>```

Body:
In Scala 2.11 you can do the following:

import scala.collection.JavaConverters._

dataset.toLocalIterator.asScala.toIterable


问:
Start service in Android
I want to call a service when a certain activity starts. So, here's the Service class:

```<code>public class UpdaterServiceManager extends Service {

    private final int UPDATE_INTERVAL = 60 * 1000;
    private Timer timer = new Timer();
    private static final int NOTIFICATION_EX = 1;
    private NotificationManager notificationManager;

    public UpdaterServiceManager() {}

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // Code to execute when the service is first created
    }

    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startid) {
        notificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        int icon = android.R.drawable.stat_notify_sync;
        CharSequence tickerText = "Hello";
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);
        Context context = getApplicationContext();
        CharSequence contentTitle = "My notification";
        CharSequence contentText = "Hello World!";
        Intent notificationIntent = new Intent(this, Main.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);
        notification.setLatestEventInfo(context, contentTitle, contentText,
                contentIntent);
        notificationManager.notify(NOTIFICATION_EX, notification);
        Toast.makeText(this, "Started!", Toast.LENGTH_LONG);
        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                // Check if there are updates here and notify if true
            }
        }, 0, UPDATE_INTERVAL);
        return START_STICKY;
    }

    private void stopService() {
        if (timer != null) timer.cancel();
    }
}
</code>```

And here is how I call it:

```<code>Intent serviceIntent = new Intent();
serviceIntent.setAction("cidadaos.cidade.data.UpdaterServiceManager");
startService(serviceIntent);
</code>```

The problem is that nothing happens. The above code block is called at the end of the activity's onCreate. I already debugged and no exception is thrown.

Any idea?

答:
Probably you don't have the service in your manifest, or it does not have an <intent-filter> that matches your action. Examining LogCat (via adb logcat, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.

More likely, you should start the service via:

```<code>startService(new Intent(this, UpdaterServiceManager.class));
</code>```

Title: Start service in Android

Body:
I want to call a service when a certain activity starts. So, here's the Service class:

public class UpdaterServiceManager extends Service {

    private final int UPDATE_INTERVAL = 60 * 1000;
    private Timer timer = new Timer();
    private static final int NOTIFICATION_EX = 1;
    private NotificationManager notificationManager;

    public UpdaterServiceManager() {}

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // Code to execute when the service is first created
    }

    @Override
    public void onDestroy() {
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startid) {
        notificationManager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        int icon = android.R.drawable.stat_notify_sync;
        CharSequence tickerText = "Hello";
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);
        Context context = getApplicationContext();
        CharSequence contentTitle = "My notification";
        CharSequence contentText = "Hello World!";
        Intent notificationIntent = new Intent(this, Main.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                notificationIntent, 0);
        notification.setLatestEventInfo(context, contentTitle, contentText,
                contentIntent);
        notificationManager.notify(NOTIFICATION_EX, notification);
        Toast.makeText(this, "Started!", Toast.LENGTH_LONG);
        timer.scheduleAtFixedRate(new TimerTask() {

            @Override
            public void run() {
                // Check if there are updates here and notify if true
            }
        }, 0, UPDATE_INTERVAL);
        return START_STICKY;
    }

    private void stopService() {
        if (timer != null) timer.cancel();
    }
}

And here is how I call it:

Intent serviceIntent = new Intent();
serviceIntent.setAction("cidadaos.cidade.data.UpdaterServiceManager");
startService(serviceIntent);

The problem is that nothing happens. The above code block is called at the end of the activity's onCreate. I already debugged and no exception is thrown.

Any idea?

Body:
Probably you don't have the service in your manifest, or it does not have an <intent-filter> that matches your action. Examining LogCat (via adb logcat, DDMS, or the DDMS perspective in Eclipse) should turn up some warnings that may help.

More likely, you should start the service via:

startService(new Intent(this, UpdaterServiceManager.class));

ContentLicense: CC BY-SA 2.5


问:
SQL query to check all records of employee
I wanted to check all employees and location. One location is having multiple employees. So my condition is i want all locations where all employee status is inactive.

Like eg emp table is

```<code>EmpId loc status
123  ABC active
124 ABC active
125  ABC inactive
234  PQR inactive
</code>```

Result should be

```<code>Empid loc status
234 PQR inactive
</code>```

答:
How about this one?

```<code>SELECT DISTINCT loc, status
  FROM my_table
 WHERE loc NOT IN (SELECT DISTINCT loc WHERE status = 'active);
</code>```

This will give you all locations which are not active.

Body:
I wanted to check all employees and location. One location is having multiple employees. So my condition is i want all locations where all employee status is inactive.

Like eg emp table is

EmpId loc status
123  ABC active
124 ABC active
125  ABC inactive
234  PQR inactive

Result should be

Empid loc status
234 PQR inactive

Body:
How about this one?

SELECT DISTINCT loc, status
  FROM my_table
 WHERE loc NOT IN (SELECT DISTINCT loc WHERE status = 'active);

This will give you all locations which are not active.


问:
Automata regular Expression
I have this homework question.

```<code>Which pair of regular expressions are equivalent?
a) (ab)* and a*b*
b) r(rr)* and (rr)*r
c) r+ and r*r
d) (b) and (c)
</code>```

I have been told that the answer is (d). I think (b) and (c) should also be answers. Can someone clarify this for me?

答:
The first thing you should try is writing out a few simple strings in each language. If you find one that's in the language of one RE but not the other, you can check to make sure and, if so, you're done. Here's what that looks like for these:

```<code>(a)
 - (ab)*: e, ab, abab, ababab, ...
 - a*b* : e, a, b, aa, ab, bb, ...
 guess: a is in L(a*b*) but not (ab)*.
 check: (ab)* only generates strings with the same number of a's as b's.
 L((ab)*) != L(a*b*)

(b)
 - r(rr)*: r, rrr, rrrrr, rrrrrrr, ...
 - (rr)*r: r, rrr, rrrrr, rrrrrrr, ...
 guess: these look the same.
 proof: the first generates all and only strings of r's of odd length.
        the second generates all and only strings of r's of odd length.
        these languages are the same.
        alternatives:
        - derive DFAs L and R and show DFAs for L \ R and R \ L accept
          the empty language.

(c)
 - r+ : r, rr, rrr, rrrr, ...
 - r*r: r, rr, rrr, rrrr, ...
 guess: these look the same.
 proof: the first generates all and only non-empty strings of r's.
        the second generates all and only non-empty strings of r's.
        these languages are the same.
        alternatives:
        - derive DFAs L and R and show DFAs for L \ R and R \ L accept
          the empty language
</code>```

Based on the above, the most correct answer would appear to be (d).

Title: Automata regular Expression

Body:
I have this homework question.

Which pair of regular expressions are equivalent?
a) (ab)* and a*b*
b) r(rr)* and (rr)*r
c) r+ and r*r
d) (b) and (c)

I have been told that the answer is (d). I think (b) and (c) should also be answers. Can someone clarify this for me?

Body:
The first thing you should try is writing out a few simple strings in each language. If you find one that's in the language of one RE but not the other, you can check to make sure and, if so, you're done. Here's what that looks like for these:

(a)
 - (ab)*: e, ab, abab, ababab, ...
 - a*b* : e, a, b, aa, ab, bb, ...
 guess: a is in L(a*b*) but not (ab)*.
 check: (ab)* only generates strings with the same number of a's as b's.
 L((ab)*) != L(a*b*)

(b)
 - r(rr)*: r, rrr, rrrrr, rrrrrrr, ...
 - (rr)*r: r, rrr, rrrrr, rrrrrrr, ...
 guess: these look the same.
 proof: the first generates all and only strings of r's of odd length.
        the second generates all and only strings of r's of odd length.
        these languages are the same.
        alternatives:
        - derive DFAs L and R and show DFAs for L \ R and R \ L accept
          the empty language.

(c)
 - r+ : r, rr, rrr, rrrr, ...
 - r*r: r, rr, rrr, rrrr, ...
 guess: these look the same.
 proof: the first generates all and only non-empty strings of r's.
        the second generates all and only non-empty strings of r's.
        these languages are the same.
        alternatives:
        - derive DFAs L and R and show DFAs for L \ R and R \ L accept
          the empty language

Based on the above, the most correct answer would appear to be (d).


问:
Collections comparator with null at the end
I have some User objects that can have name and email, I want them sorted by name , then by email, but firstly show users that have not null names. I was trying like so:

```<code> Collections.sort(usersList, new Comparator<User>() {
            @Override
            public int compare(User obj1, User obj2) {
                int res = 0;

               //to make sure null names at the end

                if (obj1.getFullName() == null && obj2.getFullName()  == null)
                    res = 0;

                if (obj1.getFullName()  == null)
                    res = 1;

                if (obj2.getFullName() == null)
                    res = -1;

                //logic for name sorting then email sorting

                if (obj1.getFullName() != null  && obj2.getFullName() != null)
                    res = obj1.getFullName().compareTo(obj2.getFullName());

                if (res == 0)
                    res = obj1.getEmail().compareTo(obj2.getEmail());

                return res;
            }
        });
</code>```

As result  I get names first but sorted by email not by name.

答:
This can be easily done with Java-8's Comparator utilities:

```<code>List<User> users = Arrays.asList(new User("pete", "pete@email"), new User(null, null), new User("alex", null), new User(null, "email"));

Collections.sort(users, Comparator.comparing(User::getName, Comparator.nullsLast(Comparator.naturalOrder()))
                       .thenComparing(Comparator.comparing(User::getEmail, Comparator.nullsLast(Comparator.naturalOrder()))));

System.out.println(users);
</code>```

Output:

```<code>[
    User{name='alex', email='null'},
    User{name='pete', email='pete@email'},
    User{name='null', email='email'},
    User{name='null', email='null'}
]
</code>```

Body:
I have some User objects that can have name and email, I want them sorted by name , then by email, but firstly show users that have not null names. I was trying like so:

 Collections.sort(usersList, new Comparator<User>() {
            @Override
            public int compare(User obj1, User obj2) {
                int res = 0;

               //to make sure null names at the end

                if (obj1.getFullName() == null && obj2.getFullName()  == null)
                    res = 0;

                if (obj1.getFullName()  == null)
                    res = 1;

                if (obj2.getFullName() == null)
                    res = -1;

                //logic for name sorting then email sorting

                if (obj1.getFullName() != null  && obj2.getFullName() != null)
                    res = obj1.getFullName().compareTo(obj2.getFullName());

                if (res == 0)
                    res = obj1.getEmail().compareTo(obj2.getEmail());

                return res;
            }
        });

As result  I get names first but sorted by email not by name.

Body:
This can be easily done with Java-8's Comparator utilities:

List<User> users = Arrays.asList(new User("pete", "pete@email"), new User(null, null), new User("alex", null), new User(null, "email"));

Collections.sort(users, Comparator.comparing(User::getName, Comparator.nullsLast(Comparator.naturalOrder()))
                       .thenComparing(Comparator.comparing(User::getEmail, Comparator.nullsLast(Comparator.naturalOrder()))));

System.out.println(users);

Output:

[
    User{name='alex', email='null'},
    User{name='pete', email='pete@email'},
    User{name='null', email='email'},
    User{name='null', email='null'}
]


问:
How to resize RMarkdown page to fit a big plot (non-rescaled igraph)
I need to fit a big igraph plot in an RMarkdown document, but a lot of the nodes and labels overlap (in a way similar to the image below).

I figured using the 'rescale=FALSE' argument could work, but then the problem is that the plot size is bigger than the page size, regardless of the fig.height, fig.width options.

Below you can see a reproducible example (save as .Rmd and Knit):

```<code>---
output: pdf_document
---

# How to resize page to fit plot?
```{r pressure, echo=FALSE, fig.height=20, fig.width=20, message=FALSE, warning=FALSE}
library(igraph)
st <- make_star(500)
set.seed(100)
plot(st, vertex.size=10, vertex.label=NA, rescale=FALSE)
```
</code>```

There is a way to adjust the page size to a non-rescaled igraph?

答:
You can adjust the page size by adding the classoption in the YAML.

But you can also play around with the fig size and the xlim() and ylim() to adjust the figure inside the page as answered here.

```<code>---
output:
  pdf_document:
documentclass: article
classoption:
  - a1paper
---

# How to resize page to fit plot?
```{r pressure, echo=FALSE, fig.height=30, fig.width=40, message=FALSE, warning=FALSE}
library(igraph)
st <- make_star(500)
set.seed(100)
plot(st, vertex.size=10, ylim=c(3,5), xlim = c(-7, 15),vertex.label=NA, rescale=FALSE)
```
</code>```

Body:
I need to fit a big igraph plot in an RMarkdown document, but a lot of the nodes and labels overlap (in a way similar to the image below).

I figured using the 'rescale=FALSE' argument could work, but then the problem is that the plot size is bigger than the page size, regardless of the fig.height, fig.width options.

Below you can see a reproducible example (save as .Rmd and Knit):

---
output: pdf_document
---

# How to resize page to fit plot?
```{r pressure, echo=FALSE, fig.height=20, fig.width=20, message=FALSE, warning=FALSE}
library(igraph)
st <- make_star(500)
set.seed(100)
plot(st, vertex.size=10, vertex.label=NA, rescale=FALSE)
```

There is a way to adjust the page size to a non-rescaled igraph?

Body:
You can adjust the page size by adding the classoption in the YAML.

But you can also play around with the fig size and the xlim() and ylim() to adjust the figure inside the page as answered here.

---
output:
  pdf_document:
documentclass: article
classoption:
  - a1paper
---

# How to resize page to fit plot?
```{r pressure, echo=FALSE, fig.height=30, fig.width=40, message=FALSE, warning=FALSE}
library(igraph)
st <- make_star(500)
set.seed(100)
plot(st, vertex.size=10, ylim=c(3,5), xlim = c(-7, 15),vertex.label=NA, rescale=FALSE)
```


问:
how to get shared value proportion by each row in r
```<code>type<-c("111","111","111","222","222","222","222","333","333","333","444","444","444")

location<-c("aaa","bbb","ccc","aaa","bbb","ddd","eee","aaa","ccc","ddd","ccc","ddd","fff")

datafr1 <- data.frame(type,location)
</code>```

I want the result like this.(don't need to be a format like this.)

```<code>           222     333    444
111      0.66%    0.66%   0.33%
</code>```

and 222, 333, 444 too.
Find the shared values and then get proportion of intersection.

Can you help me?!!

答:
I'm only using data.table for the rbindlist at the end. You could replace this with a do.call on rbind or something similar if you don't want to use data.table.

```<code>typevals <- unique(datafr1$type)

funky <- function(typeval) {
  uniqueloc <- unique(datafr1[type == typeval,]$location)
  props <- sapply(typevals,
                  function(x) {
                    length(intersect(uniqueloc, datafr1[type == x,]$location))/length(uniqueloc)
                  })
  props <- round(props, 2)
  df <- data.frame(t(props))
  names(df) <- typevals
  df <- cbind(data.frame(type = typeval), df)
}
rbindlist(lapply(typevals, funky))
#    type  111  222  333  444
# 1:  111 1.00 0.67 0.67 0.33
# 2:  222 0.50 1.00 0.50 0.25
# 3:  333 0.67 0.67 1.00 0.67
# 4:  444 0.33 0.33 0.67 1.00
</code>```

Body:
type<-c("111","111","111","222","222","222","222","333","333","333","444","444","444")

location<-c("aaa","bbb","ccc","aaa","bbb","ddd","eee","aaa","ccc","ddd","ccc","ddd","fff")

datafr1 <- data.frame(type,location)

I want the result like this.(don't need to be a format like this.)

           222     333    444
111      0.66%    0.66%   0.33%

and 222, 333, 444 too.
Find the shared values and then get proportion of intersection.

Can you help me?!!

Body:
I'm only using data.table for the rbindlist at the end. You could replace this with a do.call on rbind or something similar if you don't want to use data.table.

typevals <- unique(datafr1$type)

funky <- function(typeval) {
  uniqueloc <- unique(datafr1[type == typeval,]$location)
  props <- sapply(typevals,
                  function(x) {
                    length(intersect(uniqueloc, datafr1[type == x,]$location))/length(uniqueloc)
                  })
  props <- round(props, 2)
  df <- data.frame(t(props))
  names(df) <- typevals
  df <- cbind(data.frame(type = typeval), df)
}
rbindlist(lapply(typevals, funky))
#    type  111  222  333  444
# 1:  111 1.00 0.67 0.67 0.33
# 2:  222 0.50 1.00 0.50 0.25
# 3:  333 0.67 0.67 1.00 0.67
# 4:  444 0.33 0.33 0.67 1.00


问:
What HTML That Doesn't Show HTML Tags?
Few days ago, I visited a site, and for no reason I tried to view its source code. And surprisingly, it doesn't contain regular HTML tags such as h1, h2, p, etc.

it only contains code like this :

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">

  <script>
  window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date;
  if (window.PerformanceObserver) {
    var observer = new PerformanceObserver(function(list) {
      const entries = list.getEntries();
      for (var i=0; i<entries.length; i++) {
        var entry = entries[i];
        // `name` will be either 'first-paint' or 'first-contentful-paint'.
        var metricName = entry.name;
        var time = Math.round(entry.startTime + entry.duration);

        ga('send', {
          hitType: 'timing',
          timingCategory: 'Performance Metrics',
          timingVar: metricName,
          timingValue: time,
        });
      }
    });
    observer.observe({entryTypes: ['paint']});
  }
  </script>

    <!-- Open search -->
      <link type="application/opensearchdescription+xml" rel="search"
              href="./assets/opensearch-id.xml"/>

  <script>dataLayer = [];</script>
  <!-- Google Tag Manager -->
  <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
  new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
  'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer','GTM-WJZQSJF');</script>
  <!-- End Google Tag Manager -->
<link href="***/assets/bundle.f4eb17af99f6bcda6c58794466a0abd3.css" rel="stylesheet"></head>
<body>
  <!-- Google Tag Manager (noscript) -->
  <noscript><iframe src="https://www.googletagmanager.com/ns.html?id=GTM-WJZQSJF"
  height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
  <!-- End Google Tag Manager (noscript) -->

  <div id="main"></div>
  <script async src='https://www.google-analytics.com/analytics.js'></script>

  <!-- Facebook Pixel Code -->
  <script>
    !function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?
            n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;
      n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;
      t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,
            document,'script','https://connect.facebook.net/en_US/fbevents.js');
  </script>
  <!-- DO NOT MODIFY -->
  <!-- End Facebook Pixel Code -->

  <!-- Criteo One Tag Code -->
  <script type="text/javascript" src="//*******" async="true"></script>
  <script>window.criteo_q = window.criteo_q || [];</script>
  <!-- End Criteo Code -->

  <script>!function(e){function c(a){if(b[a])return b[a].exports;var d=b[a]={i:a,l:!1,exports:{}};return e[a].call(d.exports,d,d.exports,c),d.l=!0,d.exports}var a=window.webpackJsonp;window.webpackJsonp=function(b,f,n){for(var r,t,o,i=0,u=[];i<b.length;i++)t=b[i],d[t]&&u.push(d[t][0]),d[t]=0;for(r in f)Object.prototype.hasOwnProperty.call(f,r)&&(e[r]=f[r]);for(a&&a(b,f,n);u.length;)u.shift()();if(n)for(i=0;i<n.length;i++)o=c(c.s=n[i]);return o};var b={},d={74:0};c.e=function(e){function a(){r.onerror=r.onload=null,clearTimeout(t);var c=d[e];0!==c&&(c&&c[1](new Error("Loading chunk "+e+" failed.")),d[e]=void 0)}var b=d[e];if(0===b)return new Promise(function(e){e()});if(b)return b[2];var f=new Promise(function(c,a){b=d[e]=[c,a]});b[2]=f;var n=document.getElementsByTagName("head")[0],r=document.createElement("script");r.type="text/javascript",r.charset="utf-8",r.async=!0,r.timeout=12e4,c.nc&&r.setAttribute("nonce",c.nc),r.src=c.p+""+({61:"vendor",62:"bundle",63:"icons",64:"short_url"}[e]||e)+".bundle."+{0:"c38a1529c3b99c325cbb",1:"36418a346d47b7489609",2:"ef74eff3789cd571abc8",3:"40b845bf76f300f55de4",4:"8a6a439aa451d3d927b0",5:"72986b428e8cbd866607",6:"c6c9571f8e2fe5d212bb",7:"aae34ad175b103ef7e4e",8:"242c59a9d553de716c60",9:"ef6bbc1570fb8834ab36",10:"4bbc0a828f9c224773d1",11:"ddb3f50d8864e9408fc1",12:"6c1497f53303248323d7",13:"afeda231b24bbc8194de",14:"a87b72a437d706639baf",15:"09604bb7d99977b19574",16:"2a88b519fe8a5231bed8",17:"8752912c6b561ea445e5",18:"1bc4d82776cf99767789",19:"a2333c0fb5928e5c8294",20:"5b3a12ea7ea8144d0b40",21:"84073184bb3f2047b2a7",22:"20b45cf24e9ba43bfeb9",23:"cd0ea9678da108d1f4ce",24:"cd3c35192890404fa9f8",25:"5eb5420abef187dc2df6",26:"18f747b4b8c098ff19f7",27:"669314a53c5cfe3c73d6",28:"ebcb097c69b716623654",29:"ac9eccdcdb242cc2aef8",30:"5e109d633d36dcbba47f",31:"5a7027b9dfa01f78bf70",32:"61e7dceb5b3a30078d83",33:"4fee29baa1d2816fdae7",34:"cc8761150451212c4a22",35:"b17ad377b0cb1ef37461",36:"66899702ab02bf7a6339",37:"bf88a5c916c22b7dd322",38:"0f8294f2a9a2e2e1ffeb",39:"dc558711f648a8ae4fc6",40:"aa5362b270c5e5c12cb8",41:"53574e3109dc0721b45b",42:"e7d39f00425207d8b5b0",43:"b1cdc408800853db7b1a",44:"90e7fdfc599c75ed6c00",45:"33db36c7330b10227972",46:"830b163b775b656e3a92",47:"03bfb3bbdd79ee0e0442",48:"e0548b8051ef72fb0e4f",49:"a14357c795d7bc1913cd",50:"ed0bec3efe20b2dc2da1",51:"76f7f508111c9d32ea1e",52:"ce6f96656a3b08a5f978",53:"dbce6a5f7c10fc5bda8b",54:"00e18ead99250bf63f01",55:"04d3bb1b65d42a9fdaf4",56:"1a12a992adc0cc13f856",57:"5fe4d3c577315f8f99a2",58:"bcd10412dcbab2259da4",59:"c8db0c00ea4034701abc",60:"d33e9ca4f6d41e01d92c",61:"8ee65c855117c2ea0d78",62:"7d31cc04d88c6681ce75",63:"d2dcedabc8faa5a71473",64:"e66827895350ae2fac63",65:"230b7a8a1670edc8e52c",66:"33b35d4cbdffc7271758",67:"6a55b5d11720b6d975ad",68:"7d28f6e0272beec18917",69:"91c610b55fa27ae0d91c",70:"4c240b9a04ec67a27235",71:"54531e628f75037462bd",72:"f6a6e9ff0ab728eabca1",73:"3d7f47216be8efeca29b"}[e]+".js";var t=setTimeout(a,12e4);return r.onerror=r.onload=a,n.appendChild(r),f},c.m=e,c.c=b,c.d=function(e,a,b){c.o(e,a)||Object.defineProperty(e,a,{configurable:!1,enumerable:!0,get:b})},c.n=function(e){var a=e&&e.__esModule?function(){return e.default}:function(){return e};return c.d(a,"a",a),a},c.o=function(e,c){return Object.prototype.hasOwnProperty.call(e,c)},c.p="https://cdngarenanow-a.akamaihd.net/shopee/shopee-pcmall-live-id/assets/",c.oe=function(e){throw e}}([]);
</script>
<script type="text/javascript" src="https://***/vendor.8ee65c855117c2ea0d78.js"></script><script type="text/javascript" src="https://***/assets/icons.d2dcedabc8faa5a71473.js"></script><script type="text/javascript" src="https://***/assets/bundle.7d31cc04d88c6681ce75.js"></script><script type="text/javascript" src="https://***/assets/short_url.e66827895350ae2fac63.js"></script></body>
</html>
</code>```

what programming language / technique is this? it shows all the content on my browser, but the html tags remains invisible. any idea what it is?

答:
That's some straight up Javascript you're seeing there, and the code running will be generating all the necessary tags client side (hence why viewing the source doesn't show them).

Try right-clicking on an element and using "Inspect". That should open the browser's dev tools and show the HTML code the Javascript is generating.

Title: What HTML That Doesn't Show HTML Tags?

Body:
Few days ago, I visited a site, and for no reason I tried to view its source code. And surprisingly, it doesn't contain regular HTML tags such as h1, h2, p, etc.

it only contains code like this :

<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">

      <link type="application/opensearchdescription+xml" rel="search"
              href="./assets/opensearch-id.xml"/>

<link href="***/assets/bundle.f4eb17af99f6bcda6c58794466a0abd3.css" rel="stylesheet">

what programming language / technique is this? it shows all the content on my browser, but the html tags remains invisible. any idea what it is?


问:
Csharp equivalent of signed char const
I have the following line in C++

```<code> signed char const ix((delta_x > 0) - (delta_x < 0));
</code>```

I would be really glad,if someone can write the above line in CSharp.

Thanks in Advance!

答:
The following code

```<code>    bool a = true;
    bool b = false;
    bool c = a - b;
</code>```

Leads to this error in C#:

```<code> Operator '-' cannot be applied to operands of type 'bool' and 'bool'
</code>```

Which totally makes sense. Subtraction of booleans is not intuitive.

Your term does work in C++, but it's still bad practice imho.

This is what you probably want in C#:

```<code>    bool a = delta_x > 0;
    bool b = delta_x < 0;
    sbyte c = (sbyte) ((a ? 1 : 0) - (b ? 1 : 0));
</code>```

You should also you use a clearer expression in C++, implicit conversion at this point is not readable and easily understandable.

Title: Csharp equivalent of signed char const

Body:
I have the following line in C++

 signed char const ix((delta_x > 0) - (delta_x < 0));

I would be really glad,if someone can write the above line in CSharp.

Thanks in Advance!

Body:
The following code

    bool a = true;
    bool b = false;
    bool c = a - b;

Leads to this error in C#:

 Operator '-' cannot be applied to operands of type 'bool' and 'bool'

Which totally makes sense. Subtraction of booleans is not intuitive.

Your term does work in C++, but it's still bad practice imho.

This is what you probably want in C#:

    bool a = delta_x > 0;
    bool b = delta_x < 0;
    sbyte c = (sbyte) ((a ? 1 : 0) - (b ? 1 : 0));

You should also you use a clearer expression in C++, implicit conversion at this point is not readable and easily understandable.


问:
Enterprise Cobol 5.2 Debugger Linenumbers exceeded
I have the "wonderful" task of maintaining a legacy program that I didn't write. The Cobol program runs in a z/OS 2.2 environment and is compiled with IBM Enterprise Cobol 5.2. For debugging I would like to compile the program with the option CBL LIST, TEST (EJPD, SOURCE). Unfortunately, my source code has more than 999999 lines, so there is an error when compiling.
Is there a way to circumvent the limitation of the number of lines or is there only a way to split the program?

答:
The 999999 limit on number of lines has been present since at least VS COBOL II, released in the mid-1980s. It's also present in Enterprise COBOL 6.3, the latest version prior to the compiler as of this update.

Perhaps someone is having you on, presenting you with uncompilable source.  This is a compiler limit, and as @SaggingRufus has indicated, the solution would be to break the program up into multiple modules.

I would contend that a million+ lines of source code is incomprehensible.

Other mechanisms available to you include evaluating the code, looking for statements that span multiple lines for no good reason...

```<code>MOVE
A
TO
B
</code>```

...is just silly.

As an aside, maintaining code you didn't write is part of the job.  It used to be normal to put the new employees through a period of maintaining the existing code base to get them familiar with shop standards, etc.

Body:
The 999999 limit on number of lines has been present since at least VS COBOL II, released in the mid-1980s. It's also present in Enterprise COBOL 6.3, the latest version prior to the compiler as of this update.

Perhaps someone is having you on, presenting you with uncompilable source.  This is a compiler limit, and as @SaggingRufus has indicated, the solution would be to break the program up into multiple modules.

I would contend that a million+ lines of source code is incomprehensible.

Other mechanisms available to you include evaluating the code, looking for statements that span multiple lines for no good reason...

MOVE
A
TO
B

...is just silly.

As an aside, maintaining code you didn't write is part of the job.  It used to be normal to put the new employees through a period of maintaining the existing code base to get them familiar with shop standards, etc.


问:
Pandas: display groupby aggregate statistic with data
Data Snippet

I am trying to add a new column to my data frame that displays the average purchase amount per user. The data frame is called trainDf and the below line of code produces the average by user. I'm trying to learn how to add it as a column to display similar  to the above image.

AveragePurchaseAmountUser = trainDf.groupby(by='User_ID')['Purchase_Amount'].mean()
```

Thank you in advance!

答:
I would use merge

avg_df = trainDf.groupby(by='User_ID')['Purchase_Amount'].mean().reset_index().rename(columns={'Purchase_Amount': 'Avg'})
trainDf = trainDf.merge(avg_df, on='User_ID')
```

Body:
Data Snippet

I am trying to add a new column to my data frame that displays the average purchase amount per user. The data frame is called trainDf and the below line of code produces the average by user. I'm trying to learn how to add it as a column to display similar  to the above image.

AveragePurchaseAmountUser = trainDf.groupby(by='User_ID')['Purchase_Amount'].mean()

Thank you in advance!


问:
What is/how does the "search" command work?
Put briefly, can I use the 'search' command to search through file contents? If so, how?

I am trying to find an easier way to search through file contents in Linux Mint than having to type

```<code>grep -rnw . -e 'my search text'
</code>```

I just noticed there is a 'search' command

```<code>$ which search
/usr/local/bin/search
</code>```

However, when I look at its help text; I am presented with this:

```<code>usage: search [arguments] [options]
arguments:
     for text
     in directory
</code>```

I am unable to make sense of this, any arguments I try passing in seem to inevitably lead me to the same text.

There is also no man page entry, I tried that as well.

I have tried e.g.

```<code>$ search "my search text" .
$ search . "test"
$ search . . . .
</code>```

Lacking a way to get this to work, I may opt for an alias. Sadly though, 'search' is already taken..

答:
Holy smokes. I never thought you may need to interpret a manual so literally;

```<code>$ search for text in directory
find: ‘directory’: No such file or directory
</code>```

It still doesn't completely make me sure how to use it exactly, though; I am puzzled on whether it supports regex/wildcards, etc.

I do get good results for simple case-insensitive text with

```<code>~/mytargetfolder/ $ search for singlewordspacesdontwork in .
</code>```

However, it breaks as soon as there is a space, escaping it with ", \  or ' is not working.

Given my experienced, I'd recommend steering clear of this command.

I'd also like to recommend not giving answers on StackOverflow, or asking questions like these, since I seem to be having a case of the downvotes as of just now?

Body:
Put briefly, can I use the 'search' command to search through file contents? If so, how?

I am trying to find an easier way to search through file contents in Linux Mint than having to type

grep -rnw . -e 'my search text'

I just noticed there is a 'search' command

$ which search
/usr/local/bin/search

However, when I look at its help text; I am presented with this:

usage: search [arguments] [options]
arguments:
     for text
     in directory

I am unable to make sense of this, any arguments I try passing in seem to inevitably lead me to the same text.

There is also no man page entry, I tried that as well.

I have tried e.g.

$ search "my search text" .
$ search . "test"
$ search . . . .

Lacking a way to get this to work, I may opt for an alias. Sadly though, 'search' is already taken..

Body:
Holy smokes. I never thought you may need to interpret a manual so literally;

$ search for text in directory
find: ‘directory’: No such file or directory

It still doesn't completely make me sure how to use it exactly, though; I am puzzled on whether it supports regex/wildcards, etc.

I do get good results for simple case-insensitive text with

~/mytargetfolder/ $ search for singlewordspacesdontwork in .

However, it breaks as soon as there is a space, escaping it with ", \  or ' is not working.

Given my experienced, I'd recommend steering clear of this command.

I'd also like to recommend not giving answers on StackOverflow, or asking questions like these, since I seem to be having a case of the downvotes as of just now?


问:
Rails Nested Singular Resource Routing
I have a simple User model with a singular nested Profile resource so in my routes.rb I have:

```<code>resources :users do
  resource :profile, :only => [:edit, :update, :show]
end
</code>```

This generates the expected routes:

```<code>edit_user_profile GET    /users/:user_id/profile/edit(.:format)  {:action=>"edit", :controller=>"profiles"}
     user_profile GET    /users/:user_id/profile(.:format)       {:action=>"show", :controller=>"profiles"}
     user_profile PUT    /users/:user_id/profile(.:format)       {:action=>"update", :controller=>"profiles"}
</code>```

I've created a simple controller update method that updates the model and then redirects upon successful update:

```<code>def update
  @profile = Profile.find_by_user_id(params[:user_id])
  @user = User.find_by_id(params[:user_id])

  respond_to do |format|
    if @profile.update_attributes(params[:profile])
      format.html { redirect_to( user_profile_path(@user, @profile), :notice => 'Profile was successfully updated.') }
    else
      # ...
    end
  end
end
</code>```

The problem is that once the form is submitted, the form redirects to mydomain.com/users/4/profile.22 where 22 happens to be the id of the profile.  Clearly this confuses the controllers since the routing interprets the '22' as the format.

My question is, how do I get this to redirect to mydomain.com/users/4/profile instead?  I've tried the following variations on the redirect_to statement to no effect, they all result in the same incorrect url:

```<code>redirect_to( user_profile_path(@user), ... )
redirect_to( user_profile_path(@user, @profile), ... )
redirect_to([@user, @profile], ... )
redirect_to( @profile, ... )
</code>```

What's more, using 'user_profile_path(@user)' elsewhere produces the correct url.

Any ideas?  Oh, and I'm using Rails 3.0.0 and Ruby 1.9.2 if that helps.

答:
After looking around, it appears that the form generating the update had an incorrect url.  If anyone is seeing this issue, it's because I had my form set up as:

```<code>form_for [@user, @profile] do |f| ...
</code>```

This caused the form action to have the incorrect url (of the offending form above).  Instead, I used

```<code>form_for @profile, :url => user_profile_path(@user) do |f| ...
</code>```

and everything seemed to work.

Title: Rails Nested Singular Resource Routing

Body:
I have a simple User model with a singular nested Profile resource so in my routes.rb I have:

resources :users do
  resource :profile, :only => [:edit, :update, :show]
end

This generates the expected routes:

edit_user_profile GET    /users/:user_id/profile/edit(.:format)  {:action=>"edit", :controller=>"profiles"}
     user_profile GET    /users/:user_id/profile(.:format)       {:action=>"show", :controller=>"profiles"}
     user_profile PUT    /users/:user_id/profile(.:format)       {:action=>"update", :controller=>"profiles"}

I've created a simple controller update method that updates the model and then redirects upon successful update:

def update
  @profile = Profile.find_by_user_id(params[:user_id])
  @user = User.find_by_id(params[:user_id])

  respond_to do |format|
    if @profile.update_attributes(params[:profile])
      format.html { redirect_to( user_profile_path(@user, @profile), :notice => 'Profile was successfully updated.') }
    else
      # ...
    end
  end
end

The problem is that once the form is submitted, the form redirects to mydomain.com/users/4/profile.22 where 22 happens to be the id of the profile.  Clearly this confuses the controllers since the routing interprets the '22' as the format.

My question is, how do I get this to redirect to mydomain.com/users/4/profile instead?  I've tried the following variations on the redirect_to statement to no effect, they all result in the same incorrect url:

redirect_to( user_profile_path(@user), ... )
redirect_to( user_profile_path(@user, @profile), ... )
redirect_to([@user, @profile], ... )
redirect_to( @profile, ... )

What's more, using 'user_profile_path(@user)' elsewhere produces the correct url.

Any ideas?  Oh, and I'm using Rails 3.0.0 and Ruby 1.9.2 if that helps.

Body:
After looking around, it appears that the form generating the update had an incorrect url.  If anyone is seeing this issue, it's because I had my form set up as:

form_for [@user, @profile] do |f| ...

This caused the form action to have the incorrect url (of the offending form above).  Instead, I used

form_for @profile, :url => user_profile_path(@user) do |f| ...

and everything seemed to work.


问:
excel vba: use dynamically built string to define array of arrays (for .TextToColumns)
EDIT: The marked solution is correct. My problem was that I was incrementing the values I was using in the FieldInfo parameter of .TextToColumns rather than using absolute positions of splits
For Example:
1, 3, 2, 5 instead of 1, 4, 6, 11

ORIGINAL:

I am building a tool that will various record types (that come in as one column, many rows) and split them into columns (depending on certain values in the lines of data).

The data could look like this:

```<code>062017000JohnDoe   777E
</code>```

It may be specified as (recordtype 2 chars; YYYY; three zeroes filler; Name; Filler Spaces; ID)

The delimiters are predefined based on the record type (defined by user) and subtype (often defined by the first 1 or 2 numbers in the data, depending on the record type).

I am using the .TextToColumns function like so:

```<code>DataToParse.TextToColumns Destination:=DataToParse, DataType:=xlFixedWidth, _
FieldInfo:=FieldInfoString, TrailingMinusNumbers:=True
</code>```

Earlier in the code, I build the string

```<code>FieldInfoString = "Array(Array(0,1), Array(5,1), Array(12,1))"
</code>```

I build the string using concatenation, adding ", Array(x , 1)" for each delimiter (looping through a variable length list of x's).

The 'FieldInfoString' variable is throwing an error. What should go in the FieldInfo parameter is:

```<code>FieldInfo:=Array(Array(0,1), Array(5,1), Array(12,1))
</code>```

The string is dynamically created for many different file types. Is there a way to use this string to define the arrays for use in .TextToColumns?

I also tried altering my approach and dynamically building the array:

```<code>Dim FieldInfoArray()

' Here there is code to define DelimitersToParse - which ends up being a 1 column by x rows
' group of numbers that will be the first value in the arrays > i.e. Array(___, 1)

ReDim Preserve FieldInfoArray(DelimitersToParse.Rows.Count)
</code>```

The first entry is (0,1)

```<code>FieldInfoArray(0) = Array(0,1)

        i = 1
        For Each ParsedDelimiter In DelimitersToParse.Cells
            FieldInfoArray(i) = Array(ParsedDelimiter.Value, 1)
            i = i + 1
        Next ParsedDelimiter

DataToParse.TextToColumns Destination:=DataToParse, DataType:=xlFixedWidth, _
        FieldInfo:=FieldInfoArray, TrailingMinusNumbers:=True
</code>```

The array approach doesn't throw an error, and the data is split, but not by any of the delimiters that I defined. I'm not sure how to audit FieldInfoArray to see what is going on.

EDIT: have attempted @jochen 's answer, auditing my array. still having issues - the 77777 should be placed in one column but is split as 777 | 77

答:
Completely edited after comment/edit:

Your Building approach is alright. You can loop to build an 0-based array with arrays using variables as you did above.

Enter a stopin the line before your TextToColumnsto have a look at the values and structure of your array. Using some test values and a simple structure it worked perfectly with me:

```<code>Sub test()
Dim Arr()
Dim v1 As Integer, v2 As Integer
ReDim Arr(0 To 4)

    v1 = 2: v2 = 6
    Arr(0) = Array(0, 2)
    Arr(1) = Array(v1, 1)
    Arr(2) = Array(v2, 2)
    Arr(3) = Array(9, 2)
    Arr(4) = Array(19, 2)

    Range("A2").TextToColumns Destination:=Range("A2"), DataType:=xlFixedWidth, _
        FieldInfo:=Arr, _
        TrailingMinusNumbers:=True

End Sub
</code>```

EDIT:

As you are still encountering problems (now your code splits but not on the right positions as I understand) I give you another example.

In my example-sheet I have a Range called Data with Data in the structure of your provided example-data (062017000JohnDoe   777E). I have another Rangecalled Delimiters with a matrix of widths and types (I prefer to use Text in some cases, especially if I dont want to loose 0's and blanks. My Delimiter matrix (5 rows, 2 columns) looks like:

```<code>0     2
2     1
6     2
9     2
19    2
</code>```

Then I use the following single-line-code to split Data into Columns:

```<code>    Range("Data").TextToColumns Destination:=Range("Data"), DataType:=xlFixedWidth, _
        FieldInfo:=Range("Delimiters").Value2, _
        TrailingMinusNumbers:=True
</code>```

Body:
EDIT: The marked solution is correct. My problem was that I was incrementing the values I was using in the FieldInfo parameter of .TextToColumns rather than using absolute positions of splits
For Example:
1, 3, 2, 5 instead of 1, 4, 6, 11

ORIGINAL:

I am building a tool that will various record types (that come in as one column, many rows) and split them into columns (depending on certain values in the lines of data).

The data could look like this:

062017000JohnDoe   777E

It may be specified as (recordtype 2 chars; YYYY; three zeroes filler; Name; Filler Spaces; ID)

The delimiters are predefined based on the record type (defined by user) and subtype (often defined by the first 1 or 2 numbers in the data, depending on the record type).

I am using the .TextToColumns function like so:

DataToParse.TextToColumns Destination:=DataToParse, DataType:=xlFixedWidth, _
FieldInfo:=FieldInfoString, TrailingMinusNumbers:=True

Earlier in the code, I build the string

FieldInfoString = "Array(Array(0,1), Array(5,1), Array(12,1))"

I build the string using concatenation, adding ", Array(x , 1)" for each delimiter (looping through a variable length list of x's).

The 'FieldInfoString' variable is throwing an error. What should go in the FieldInfo parameter is:

FieldInfo:=Array(Array(0,1), Array(5,1), Array(12,1))

The string is dynamically created for many different file types. Is there a way to use this string to define the arrays for use in .TextToColumns?

I also tried altering my approach and dynamically building the array:

Dim FieldInfoArray()

' Here there is code to define DelimitersToParse - which ends up being a 1 column by x rows
' group of numbers that will be the first value in the arrays > i.e. Array(___, 1)

ReDim Preserve FieldInfoArray(DelimitersToParse.Rows.Count)

The first entry is (0,1)

FieldInfoArray(0) = Array(0,1)

        i = 1
        For Each ParsedDelimiter In DelimitersToParse.Cells
            FieldInfoArray(i) = Array(ParsedDelimiter.Value, 1)
            i = i + 1
        Next ParsedDelimiter

DataToParse.TextToColumns Destination:=DataToParse, DataType:=xlFixedWidth, _
        FieldInfo:=FieldInfoArray, TrailingMinusNumbers:=True

The array approach doesn't throw an error, and the data is split, but not by any of the delimiters that I defined. I'm not sure how to audit FieldInfoArray to see what is going on.

EDIT: have attempted @jochen 's answer, auditing my array. still having issues - the 77777 should be placed in one column but is split as 777 | 77

Body:
Completely edited after comment/edit:

Your Building approach is alright. You can loop to build an 0-based array with arrays using variables as you did above.

Enter a stopin the line before your TextToColumnsto have a look at the values and structure of your array. Using some test values and a simple structure it worked perfectly with me:

Sub test()
Dim Arr()
Dim v1 As Integer, v2 As Integer
ReDim Arr(0 To 4)

    v1 = 2: v2 = 6
    Arr(0) = Array(0, 2)
    Arr(1) = Array(v1, 1)
    Arr(2) = Array(v2, 2)
    Arr(3) = Array(9, 2)
    Arr(4) = Array(19, 2)

    Range("A2").TextToColumns Destination:=Range("A2"), DataType:=xlFixedWidth, _
        FieldInfo:=Arr, _
        TrailingMinusNumbers:=True

End Sub

EDIT:

As you are still encountering problems (now your code splits but not on the right positions as I understand) I give you another example.

In my example-sheet I have a Range called Data with Data in the structure of your provided example-data (062017000JohnDoe   777E). I have another Rangecalled Delimiters with a matrix of widths and types (I prefer to use Text in some cases, especially if I dont want to loose 0's and blanks. My Delimiter matrix (5 rows, 2 columns) looks like:

0     2
2     1
6     2
9     2
19    2

Then I use the following single-line-code to split Data into Columns:

    Range("Data").TextToColumns Destination:=Range("Data"), DataType:=xlFixedWidth, _
        FieldInfo:=Range("Delimiters").Value2, _
        TrailingMinusNumbers:=True


问:
Is it possible to replace org.apache.axis2.wso2 artifacts with org.apache.axis2 artifacts?
folks!

I need to update artifacts in a project that is running on wso2 server.
There were used wso2 specific artifacts like org.apache.axis2.wso2 or org.apache.ws.commons.axiom.wso2.

If I want to replace these wso2 specific artifacts with more up-to-date regular org.apache.axis2 artifacts could it lead to errors or I can use non specific artifacts freely?

答:
WSO2 creates its own versions of such 3rd party libraries in 2 cases.

When the original jar is not OSGi

When WSO2 needs to add new fixes and improvement which are not
there is the original jar

In either case, changing a jar to its original version can break the server.

On the other hand, new versions of those 3rd party jars can have API (signature) changes too. So it can also break the server.

So the bottom line is it won't be possible to do such jar upgrades without internal code changes.


问:
Real projects on .Net Core
I need to write essay about .Net Core and about real projects written on it.
But i can not find any examples of such projects.
Can you tell me some examples of real .Net Core projects?

Or they do not exist yet?

答:
Whilst I agree that this is not the correct forum for such a question, a quick and simple Google search suggests that https://www.ageofascent.com/ is built on .Net Core to some degree.

Additionally, although not quite what you're looking for, .Net Core is supported in lots of Windows Docker containers running Windows Server Core, due to it's lightweight nature.

A bit of research goes a long way. Good luck with the essay.

Title: Real projects on .Net Core


问:
How to write into Rspec output log file from rspec test case?
I have Rspec test cases but I want write some data from variables into Rspec output file for further processing, so how to write into output file generated by --out rspec_results.html

答:
In your spec_helper.rb file write down this code

```<code>RSpec.configure do |config|
  config.example_status_persistence_file_path = 'spec/examples.txt'
end
</code>```

Body:
In your spec_helper.rb file write down this code

RSpec.configure do |config|
  config.example_status_persistence_file_path = 'spec/examples.txt'
end


问:
PHP MESSAGE Issue
SOLVED

The freaking error was having "inc" in the from address. CHANGED $from = "messageform@courtesycareinc.com"; to $from = "messageform@courtesycare.com"; and it worked.

I can't get this working. On another site I had, I used a similar method, but with a database and it works. When I use it this way without a database, for some reason it won't work. I can't get a message to send out.

```<code><?php
if (isset($_POST['send'])) {
 $name = $_REQUEST['name'];
 $email = $_REQUEST['email'];
 $phone = $_REQUEST['phone'];
 $subject = $_REQUEST['subject'];
 $message = $_REQUEST['message'];
 $semail = "yanikem@gmail.com";

 $name = htmlspecialchars($name, ENT_QUOTES);
 $email = htmlspecialchars($email, ENT_QUOTES);
 $phone = htmlspecialchars($phone, ENT_QUOTES);
 $subject = htmlspecialchars($subject, ENT_QUOTES);
 $message = htmlspecialchars($message, ENT_QUOTES);

 $from = "messageform@courtesycareinc.com";
 $headers = "From: $from";
 $message .= "Courtesy Care, Inc. Contact\n\n";
 $message .= "The following information was collected from Courtesy Care, Inc.'s Contact Form.\n\n";
 $message .= "<table><tr><td>Name: </td><td>".$name."</td></tr><tr><td>Email: </td><td>".$email."</td></tr><tr><td>Phone: </td><td>".$phone."</td></tr><tr><td>Subject: </td><td>".$subject."</td></tr><tr><td>Message: </td><td>".$message."</td></tr></table>";

 mail($semail, "Courtesy Care, Inc.", $message, $headers);

 header ('Location: contactusdone.php?say=msent');
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
 <table style="text-align:left; width: 500px; left:45px; position:relative; padding:2px; border:1px solid #1A1A1A">
 <tr>
  <td colspan="2" style="vertical-align:top; text-align:center; border:1px solid #1A1A1A; background-color:#A52A2A; color:#FFFFFF;">MESSAGE FORM</td>
 </tr>
 <tr>
 <td colspan="2"><center>The form below can be used to send a detailed message to <strong>courtesycare@comcast.net</strong>.<br /><br /></center></td>
 </tr>
    <tr>
        <td width="80" align="right" valign="top">Name: </td>
        <td width="302" align="left" valign="top"><input name="name" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td align="right" valign="top">Email: </td>
        <td align="left" valign="top"><input name="email" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td align="right" valign="top">Phone: </td>
        <td align="left" valign="top"><input name="phone" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td align="right" valign="top">Subject: </td>
        <td align="left" valign="top"><input name="subject" type="text" style="width:98%" /></td>
    </tr>
    <tr>
        <td align="right" valign="top">Message: </td>
        <td align="left" valign="top"><textarea name="message" style="width:98%; height:150px;"></textarea></td>
    </tr>
    <tr>
  <td colspan="2" align="right"><input type="reset" value="Clear Fields"> <input type="submit" name="send" value="Send" /></td>
    </tr>
    </table>
</form>
</code>```

答:
Are you sure the message is actually sending? Or, if it's sent, it's not getting dumped as spam?

PHP's mail() function essentially lies to you. If it returns true, that doesn't mean the mail got to the person it's addressed to, it just means that's it's been accepted into the mail system. Think of it as the difference between dropping a letter into a mailbox and the letter actually getting delivered - there's still plenty of ways for the postal system to shred the thing before it goes anywhere. All mail() will guarantee is that you dropped it into the mailbox.

Title: PHP MESSAGE Issue

Body:
SOLVED

The freaking error was having "inc" in the from address. CHANGED $from = "messageform@courtesycareinc.com"; to $from = "messageform@courtesycare.com"; and it worked.

I can't get this working. On another site I had, I used a similar method, but with a database and it works. When I use it this way without a database, for some reason it won't work. I can't get a message to send out.

<?php
if (isset($_POST['send'])) {
 $name = $_REQUEST['name'];
 $email = $_REQUEST['email'];
 $phone = $_REQUEST['phone'];
 $subject = $_REQUEST['subject'];
 $message = $_REQUEST['message'];
 $semail = "yanikem@gmail.com";

 $name = htmlspecialchars($name, ENT_QUOTES);
 $email = htmlspecialchars($email, ENT_QUOTES);
 $phone = htmlspecialchars($phone, ENT_QUOTES);
 $subject = htmlspecialchars($subject, ENT_QUOTES);
 $message = htmlspecialchars($message, ENT_QUOTES);

 $from = "messageform@courtesycareinc.com";
 $headers = "From: $from";
 $message .= "Courtesy Care, Inc. Contact\n\n";
 $message .= "The following information was collected from Courtesy Care, Inc.'s Contact Form.\n\n";
 $message .= "

Name: 	".$name."

Email: 	".$email."

Phone: 	".$phone."

Subject: 	".$subject."

Message: 	".$message."

";

 mail($semail, "Courtesy Care, Inc.", $message, $headers);

 header ('Location: contactusdone.php?say=msent');
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

  MESSAGE FORM

 The form below can be used to send a detailed message to courtesycare@comcast.net.

        Name:
        <input name="name" type="text" style="width:98%" />

        Email:
        <input name="email" type="text" style="width:98%" />

        Phone:
        <input name="phone" type="text" style="width:98%" />

        Subject:
        <input name="subject" type="text" style="width:98%" />

        Message:
        <textarea name="message" style="width:98%; height:150px;"></textarea>

  <input type="reset" value="Clear Fields"> <input type="submit" name="send" value="Send" />

</form>


问:
translate service in MatPaginator
I based myself on the following implementation:
How to use MatPaginatorIntl?

He tried to add TranslateService within my implied MatPaginatorIntl, it shows me the following error. This code is part of jhipster and I have added this implementation within the shared forlder.

Error:

```<code>Uncaught Error: Can't resolve all parameters for SharedPaginatorIntl: (?).
at syntaxError (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:1917:34)
at CompileMetadataResolver._getDependenciesMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:15984:35)
at CompileMetadataResolver._getTypeMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:15852:26)
at CompileMetadataResolver._getInjectableMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:15838:21)
at CompileMetadataResolver.getProviderMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:16129:40)
at eval (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:16058:49)
at Array.forEach (<anonymous>)
at CompileMetadataResolver._getProvidersMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:16018:19)
at CompileMetadataResolver.getNgModuleMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:15673:50)
at CompileMetadataResolver.getNgModuleSummary (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:15526:52)
</code>```

Shared folder structure

index.ts

```<code>export * from './constants/pagination.constants';
export * from './alert/alert.component';
export * from './alert/alert-error.component';
export * from './auth/csrf.service';
export * from './auth/state-storage.service';
export * from './auth/account.service';
export * from './auth/auth-oauth2.service';
export * from './auth/principal.service';
export * from './auth/has-any-authority.directive';
export * from './auth/user-route-access-service';
export * from './language/language.constants';
export * from './language/language.helper';
export * from './language/find-language-from-key.pipe';
export * from './tracker/tracker.service';
export * from './login/login.component';
export * from './login/login.service';
export * from './login/login-modal.service';
export * from './user/account.model';
export * from './user/user.model';
export * from './user/user.service';
export * from './model/response-wrapper.model';
export * from './model/request-util';
export * from './model/base-entity';
export * from './shared-libs.module';
export * from './shared-common.module';
export * from './shared.module';
export * from './own/shared-bce-table.component';
export * from './own/shared-table-query-service';
export * from './own/shared-data-source';
export * from './own/shared-paginator-intl';
</code>```

shared.module.ts

```<code>import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { DatePipe } from '@angular/common';
import {TranslateModule} from '@ngx-translate/core';

import {
BuildingcSharedLibsModule,
BuildingcSharedCommonModule,
CSRFService,
AuthServerProvider,
AccountService,
UserService,
StateStorageService,
LoginService,
LoginModalService,
Principal,
JhiTrackerService,
HasAnyAuthorityDirective,
JhiLoginModalComponent,
} from './';

@NgModule({
imports: [
    BuildingcSharedLibsModule,
    BuildingcSharedCommonModule,
    TranslateModule
],
declarations: [
    JhiLoginModalComponent,
    HasAnyAuthorityDirective
],
providers: [
    LoginService,
    LoginModalService,
    AccountService,
    StateStorageService,
    Principal,
    CSRFService,
    JhiTrackerService,
    AuthServerProvider,
    UserService,
    DatePipe,
    TranslateModule
],
entryComponents: [JhiLoginModalComponent],
exports: [
    BuildingcSharedCommonModule,
    JhiLoginModalComponent,
    HasAnyAuthorityDirective,
    DatePipe
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]

})
export class BuildingcSharedModule {}
</code>```

My implementation:

```<code> import {MatPaginator, MatPaginatorIntl} from '@angular/material';
 import {Component} from '@angular/core';
 import {TranslateService} from '@ngx-translate/core';

export class SharedPaginatorIntl extends MatPaginatorIntl {

itemsPerPageLabel = 'Total por página';
nextPageLabel     = 'Siguiente Página';
previousPageLabel = 'Anterior Página';

constructor(private translateService: TranslateService) {
    super();
}

getRangeLabel = function (page, pageSize, length) {
    if (length === 0 || pageSize === 0) {
        return '0 de ' + length;
    }
    length = Math.max(length, 0);
    const startIndex = page * pageSize;
    // If the start index exceeds the list length, do not try and fix the end index to the end.
    const endIndex = startIndex < length ?
        Math.min(startIndex + pageSize, length) :
        startIndex + pageSize;
    return startIndex + 1 + ' - ' + endIndex + ' de ' + length;
};
}
</code>```

答:
You have to annotate your custom PaginatorIntl with

```<code>@Injectable()
</code>```

to be able to use the Angular-DI.

so in your case it would be:

```<code>@Injectable()
export class SharedPaginatorIntl extends MatPaginatorIntl {
...
</code>```

Title: translate service in MatPaginator

Body:
I based myself on the following implementation:
How to use MatPaginatorIntl?

He tried to add TranslateService within my implied MatPaginatorIntl, it shows me the following error. This code is part of jhipster and I have added this implementation within the shared forlder.

Error:

Uncaught Error: Can't resolve all parameters for SharedPaginatorIntl: (?).
at syntaxError (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:1917:34)
at CompileMetadataResolver._getDependenciesMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:15984:35)
at CompileMetadataResolver._getTypeMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:15852:26)
at CompileMetadataResolver._getInjectableMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:15838:21)
at CompileMetadataResolver.getProviderMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:16129:40)
at eval (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:16058:49)
at Array.forEach (<anonymous>)
at CompileMetadataResolver._getProvidersMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:16018:19)
at CompileMetadataResolver.getNgModuleMetadata (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:15673:50)
at CompileMetadataResolver.getNgModuleSummary (eval at ./node_modules/@angular/compiler/@angular/compiler.es5.js (vendor.bundle.js:135), <anonymous>:15526:52)

Shared folder structure

index.ts

export * from './constants/pagination.constants';
export * from './alert/alert.component';
export * from './alert/alert-error.component';
export * from './auth/csrf.service';
export * from './auth/state-storage.service';
export * from './auth/account.service';
export * from './auth/auth-oauth2.service';
export * from './auth/principal.service';
export * from './auth/has-any-authority.directive';
export * from './auth/user-route-access-service';
export * from './language/language.constants';
export * from './language/language.helper';
export * from './language/find-language-from-key.pipe';
export * from './tracker/tracker.service';
export * from './login/login.component';
export * from './login/login.service';
export * from './login/login-modal.service';
export * from './user/account.model';
export * from './user/user.model';
export * from './user/user.service';
export * from './model/response-wrapper.model';
export * from './model/request-util';
export * from './model/base-entity';
export * from './shared-libs.module';
export * from './shared-common.module';
export * from './shared.module';
export * from './own/shared-bce-table.component';
export * from './own/shared-table-query-service';
export * from './own/shared-data-source';
export * from './own/shared-paginator-intl';

shared.module.ts

import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { DatePipe } from '@angular/common';
import {TranslateModule} from '@ngx-translate/core';

import {
BuildingcSharedLibsModule,
BuildingcSharedCommonModule,
CSRFService,
AuthServerProvider,
AccountService,
UserService,
StateStorageService,
LoginService,
LoginModalService,
Principal,
JhiTrackerService,
HasAnyAuthorityDirective,
JhiLoginModalComponent,
} from './';

@NgModule({
imports: [
    BuildingcSharedLibsModule,
    BuildingcSharedCommonModule,
    TranslateModule
],
declarations: [
    JhiLoginModalComponent,
    HasAnyAuthorityDirective
],
providers: [
    LoginService,
    LoginModalService,
    AccountService,
    StateStorageService,
    Principal,
    CSRFService,
    JhiTrackerService,
    AuthServerProvider,
    UserService,
    DatePipe,
    TranslateModule
],
entryComponents: [JhiLoginModalComponent],
exports: [
    BuildingcSharedCommonModule,
    JhiLoginModalComponent,
    HasAnyAuthorityDirective,
    DatePipe
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]

})
export class BuildingcSharedModule {}

My implementation:

 import {MatPaginator, MatPaginatorIntl} from '@angular/material';
 import {Component} from '@angular/core';
 import {TranslateService} from '@ngx-translate/core';

export class SharedPaginatorIntl extends MatPaginatorIntl {

itemsPerPageLabel = 'Total por página';
nextPageLabel     = 'Siguiente Página';
previousPageLabel = 'Anterior Página';

constructor(private translateService: TranslateService) {
    super();
}

getRangeLabel = function (page, pageSize, length) {
    if (length === 0 || pageSize === 0) {
        return '0 de ' + length;
    }
    length = Math.max(length, 0);
    const startIndex = page * pageSize;
    // If the start index exceeds the list length, do not try and fix the end index to the end.
    const endIndex = startIndex < length ?
        Math.min(startIndex + pageSize, length) :
        startIndex + pageSize;
    return startIndex + 1 + ' - ' + endIndex + ' de ' + length;
};
}

Body:
You have to annotate your custom PaginatorIntl with

@Injectable()

to be able to use the Angular-DI.

so in your case it would be:

@Injectable()
export class SharedPaginatorIntl extends MatPaginatorIntl {
...


问:
HTML Table not full width td
For some reason I can not get the td with 100% inside the table and align the text as center.

How can I make the  full width, so it full the 600px of the table obove?

JSFIDDLE: https://jsfiddle.net/61s1cdyo/1/

CODE:

```<code><table class="table-bestelling-content" cellpadding="0" cellspacing="0" border="0" width="100%" style="background-color:#ffffff">
  <tr class="details">
      <td align="center">
      <table  class="table-bestelling-content" cellpadding="0" cellspacing="0" border="0" width="100%" style="background-color:#ffffff; max-width: 600px; display: block;">
        <tr align="center" class="header">
              <td class="order-details">
                    <h1 style="text-align: left; display: table-cell; padding: 10px 0px;">ORDER DETAILS</h1>
                </td>
        </tr>
      </table>
    </td>
  </tr>
</table>
</code>```

答:
Assuming you want to keep the max-width: 600px, you need to remove the display: block from the inner table to make it act like a table.

```<code><table class="table-bestelling-content" cellpadding="0" cellspacing="0" border="0" width="100%" style="background-color:#ffffff">
  <tr class="details">
      <td align="center">
      <table  class="table-bestelling-content" cellpadding="0" cellspacing="0" border="0" width="100%" style="background-color:#ffffff; max-width: 600px;">
        <tr align="center" class="header">
              <td class="order-details">
                    <h1 style="text-align: left; display: table-cell; padding: 10px 0px;">ORDER DETAILS</h1>
                </td>
        </tr>
      </table>
    </td>
  </tr>
</table>
</code>```

Here's a Fiddle

Title: HTML Table not full width td

Body:
For some reason I can not get the td with 100% inside the table and align the text as center.

How can I make the  full width, so it full the 600px of the table obove?

JSFIDDLE: https://jsfiddle.net/61s1cdyo/1/

CODE:

ORDER DETAILS

Body:
Assuming you want to keep the max-width: 600px, you need to remove the display: block from the inner table to make it act like a table.

<table class="table-bestelling-content" cellpadding="0" cellspacing="0" border="0" width="100%" style="background-color:#ffffff">
  <tr class="details">
      <td align="center">
      <table  class="table-bestelling-content" cellpadding="0" cellspacing="0" border="0" width="100%" style="background-color:#ffffff; max-width: 600px;">
        <tr align="center" class="header">
              <td class="order-details">
                    <h1 style="text-align: left; display: table-cell; padding: 10px 0px;">ORDER DETAILS</h1>
                </td>
        </tr>
      </table>
    </td>
  </tr>
</table>

Here's a Fiddle


问:
Is it possible to make use of a dependency CDI with wildfly?
I'm used to Spring framework dependency injection and stuff, so I'm really green with JBoss. I might be wanting to do something that is not possible.

In our company we started with a prototype that has all the dependency injection on it. We have one class declared this way:

```<code>@ApplicationScoped
public class MessageHandlerImpl implements MessageHandler {
    ...
}
</code>```

and I inject it on another class like this:

```<code>@ApplicationScoped
public class MessageReceiverImpl implements MessageReceiver {

    @Inject
    MessageHandler messageHandler;
    ...

}
</code>```

The prototype was accepted and now we are organizing this project isolating some common code on a core project.

Those injections were working fine until we separated it. More details about this problem was asked on this question: Ambiguous dependency with only one @ApplicationScoped class

I'm taking a step back and considering that maybe what I'm doing is not possible with wildfly-swarm or the whole concept that I'm trying is wrong.

What I would like to do is to have all the CDI done on my core project and only use it with an @Inject annotation on my dependent project. So in my dependent project I would have something like:

```<code>@ApplicationScoped
public class WSClient {

    @Inject
    MessageReceiver messageReceiver;

    ...

}
</code>```

Well, that doesn't work because I get an Ambiguous dependency as you can see on the question I linked. I'm wondering if what I should be doing is use a Producer or something like that. Can anyone enlighten me on a valid approach for this, or maybe an alternative?

答:
Producers are used when you want to instantiate a type in a certain, possibly varying, way and then just hand it over to CDI saying "Hey, if someone injects this type, give him this instance" (very simplified version of course). From what you described, you should be good enough with plain injection and bean creation, I don't see a need for producer.

From both of your questions I can gleam that the injection in fact even works, but there are some ambiguities. By that I mean that one injection point has several possible candidates. Only in your case they are identical which means the class must have been loaded twice somehow, somewhere - keep digging in that direction.

From the architecture point of view, with CDI it is perfectly ok (and I would say common) to extract your core as a CDI library which is then used by other parts of your project. Just make sure all of your archives are considered "bean archives". The easiest way to achieve that is to make sure you include beans.xml in them.

Body:
I'm used to Spring framework dependency injection and stuff, so I'm really green with JBoss. I might be wanting to do something that is not possible.

In our company we started with a prototype that has all the dependency injection on it. We have one class declared this way:

@ApplicationScoped
public class MessageHandlerImpl implements MessageHandler {
    ...
}

and I inject it on another class like this:

@ApplicationScoped
public class MessageReceiverImpl implements MessageReceiver {

    @Inject
    MessageHandler messageHandler;
    ...

}

The prototype was accepted and now we are organizing this project isolating some common code on a core project.

Those injections were working fine until we separated it. More details about this problem was asked on this question: Ambiguous dependency with only one @ApplicationScoped class

I'm taking a step back and considering that maybe what I'm doing is not possible with wildfly-swarm or the whole concept that I'm trying is wrong.

What I would like to do is to have all the CDI done on my core project and only use it with an @Inject annotation on my dependent project. So in my dependent project I would have something like:

@ApplicationScoped
public class WSClient {

    @Inject
    MessageReceiver messageReceiver;

    ...

}

Well, that doesn't work because I get an Ambiguous dependency as you can see on the question I linked. I'm wondering if what I should be doing is use a Producer or something like that. Can anyone enlighten me on a valid approach for this, or maybe an alternative?