text:
Q: How to remove an element from Arraylist by its type Say, I have an ArrayList:
List<Transaction> txList

I also have couple of transactions extending the base class - Transaction:
public class ATransaction extends Transaction {...}
public class BTransaction extends Transaction {...}
public class CTransaction extends Transaction {...}
... 10-12 more different kind of Transactions extends Transaction class

In some part of the code I am removing these transactions.
for (Object tx : transactions) {
    if (tx instanceof ATransaction) {
        CustomerSession.remove((ATransaction) t);
    } else if (tx instanceof BTransaction) {
        CustomerSession.remove((BTransaction) t);
    } else if ...
}

CustomerSession:
    public void remove(Transaction t) {
        Iterator itr = txList.iterator();

        while (itr.hasNext()) {
           //How to compare the type of iterator with that of the argument "t" passed in the remove method and do an - iterator remove - below when the condition is met
              itr.remove();
        }
    }

Thanks!

A: If you don't know the types, maybe this option with generics would be more suitable. The remove methods will look like this:
public void remove(Class<? extends Transaction> cls) {
    Iterator itr = transactions.iterator();

    while (itr.hasNext()) {
        if (itr.next().getClass().equals(cls)) {
            System.out.println("removing");
            itr.remove();
        }
    }
}

The signature Class<? extends Transaction> cls will ensure that you need to pass a class as parameter that extends Transaction and like ATransaction.
Find the code below:
public class ListStuff {

List<Transaction> transactions = new ArrayList<>();

public ListStuff() {
    //Add some data
    transactions.add(new ATransaction());
    transactions.add(new DTransaction());
    transactions.add(new ATransaction());
    transactions.add(new ATransaction());
    transactions.add(new CTransaction());
    transactions.add(new ATransaction());
    transactions.add(new BTransaction());
    transactions.add(new CTransaction());
    transactions.add(new BTransaction());
    transactions.add(new BTransaction());
    transactions.add(new CTransaction());
    transactions.add(new CTransaction());
    transactions.add(new DTransaction());

    remove(ATransaction.class); //This will remove all ATrasaction from the list
    remove(BTransaction.class); // This will remove all BTransaction from the list
    transactions.stream().forEach(System.out::println);
}

public void remove(Class<? extends Transaction> cls) {
    Iterator itr = transactions.iterator();

    while (itr.hasNext()) {
        if (itr.next().getClass().equals(cls)) {
            System.out.println("removing");
            itr.remove();
        }
    }
}

public abstract class  Transaction {

}

public class ATransaction extends Transaction{

    @Override
    public String toString() {
        return "A";
    }

}

public class BTransaction extends Transaction{
    @Override
    public String toString() {
        return "B";
    }
}

public class CTransaction extends Transaction{
    @Override
    public String toString() {
        return "C";
    }
}

public class DTransaction extends Transaction{
    @Override
    public String toString() {
        return "D";
    }
}
}

A: Also you can use the iterators:
    Iterator<Transaction> iterator = transactions.iterator();
    while(iterator.hasNext()) {
        Transaction tx = iterator.next();
        if (tx instanceof ATransaction) {
            iterator.remove();
        } else if (tx instanceof BTransaction) {
            iterator.remove();
        }
    }

EDIT:
If you want to organize the filtering classes, create a map and set true if exists.
first create constants:
Constants.ATransaction = "ATransaction ";
Constants.BTransaction = "BTransaction ";
...

update your classes, create a middle class:
public class MyTransaction extends Transaction {
    public String baseClassName;
    MyTransaction (String baseClassName) {
        super();
        baseClassName = baseClassName;
    }
}

public class ATransaction extends MyTransaction {
    ATransaction() {
        super(Constants.ATransaction);
    }
}
...

populate your map with the desired ones at build time:
Map<String, Boolean> transactionClasses = new HashMap<>();
transactionClasses.put(Constants.ATransaction, true);
transactionClasses.put(Constants.BTransaction, true);
...

then check them while iterating like this:
    Iterator<MyTransaction> iterator = transactions.iterator();
    while(iterator.hasNext()) {
        MyTransaction tx = iterator.next();
        if (transactionClasses.containsKey(tx.baseClassName)) {
            iterator.remove();
        }
    }

A: Based on the accepted answer in Determine if two Java objects are of the same class the answer depends on whether you seek the exact same class as t, or a derived class thereof.
public void remove(Transaction t) {
    Iterator itr = txList.iterator();

    while (itr.hasNext()) {
          //if(itr.next().getClass().equals( t.getClass())  /*if the current element should be of the exact same type as t */
          if(itr.next().getClass().isAssignableTo(t.getClass()))  /*if the current element is allowed to be a child element of t*/
              itr.remove();
    }
}

Please also notice that in the first part of your code, it is better to use the parent Transaction class in the enhanced for statement instead of Object as it enhances type safety, and that you do not have to down cast to the child type (e.g.,'ATransaction') when removing from the list:
for (Transaction tx : transactions) {
  if (tx instanceof ATransaction) {
      CustomerSession.remove(t);
  } else if (tx instanceof BTransaction) {
      CustomerSession.remove(t);
  } else if ...
}

or even do everything in a single if with several ||'s instead of the nested if-else


text:
Q: Where can I find good WordPress interview questions and answers? Can anyone help me to get good WordPress interview questions and answers.
Any link or Resource?
Please reply as I am unable to get it?

A: You can get ample of question and (great) answers here, https://stackoverflow.com/questions/tagged/wordpress?sort=frequent. See for yourself, how many can you answer.
Apart from this, I would add 2 questions:
What is wordpress? What can you not do with wordpress?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Remove "No main class detected" warning in SBT I have a multi-module SBT project. Some of the modules produce JARs with main classes and can be started with java -jar but most don't.
However when I run (or compile, or anything else) one of the modules (sbt foo/run) I get a warning per library module.
[warn] No main class detected

How can I remove those warnings?

A: This warning is considered a bug in sbt 0.13.7 and it will be removed in sbt 0.13.8.


text:
Q: Reading file with "gaps" in destination array I'm trying to find a way to read a file into an array with "gaps":
So the read data is in the byte array buffer at the positions buffer[0], buffer[2], .., buffer[2*i], without any significant speed loss.
More specifically I want to read it int-wise (i.e. b[0], b[4], ..., b[i * 4]).
Is that in any way possible (C#, C++) or should I look for another approach?
A bit more background:
I'm trying to speed up a hash algorithm (hashes the file blockwise, concats blockhashes, hashes it, and takes the resulting hash).
The idea is/was to take SSE3 and do 4 blocks in "parallel", which is why I need the data in that way, so I can easily load the data into the registers.
The (pinvokable) lib I wrote in C++ gives nice results (i.e. 4 times as fast), but reordering the data eats up the speed gains.
Currently I'm reading the file blockwise and then reorder the ints (C#):
unsafe {
    uint* b = (uint*)buffer.ToPointer() + chunkIndex;
    fixed(byte* blockPtr = chunk) {
        uint* blockIntPtr = (uint*)blockPtr;

        for(int i = 0; i < 9500 * 1024 / 4; i += 4) {
            *(b + 00) = blockIntPtr[i + 0];
            *(b + 04) = blockIntPtr[i + 1];
            *(b + 08) = blockIntPtr[i + 2];
            *(b + 12) = blockIntPtr[i + 3];
            b += 16;
        }
    }
}

chunk is a byte array and chunkIndex is an int, passed as methods parameters.
buffer is a uint32_t* pointer which is allocated by my C++ code.
The problem with this is that it takes too long. Calling the above code 4 times takes around 90ms while the hashing takes 3ms.
The big discrepancy strikes me as a bit odd, but it produces correct hashes.

A: in c++ I would do something like:
uint* b = (uint*)buffer;
 for(int i = 0; i < 9500 * 1024; i ++) {
       //read 4 ints
            *(b+i+0)  = blockIntPtr[i + 0];
            *(b+i+1)  = blockIntPtr[i + 1];
            *(b+i+2)  = blockIntPtr[i + 2];
            *(b+i+3)  = blockIntPtr[i + 3];
      //skip next 12 ints
            b += 16;
   }


text:
Q: pyral accessing customfield .attributes values from CA Agile Central I'm super new in development in general. I'm currently building a webapp that get data from Rally/CA Agile Central and put them in a neat table.
My code:
response = rally.get('UserStory', fetch = True, query=query_criteria)
response_defect = rally.get('Defect', fetch = True, query=query_criteria)

story_list = []
if not response.errors:
    for story in response:
        #print (story.details())
        a_story={}
        #a_story['State'] = story.State.Name #if story.State else "Backlog"
        a_story['State']=story.BusOpsKanban if story.BusOpsKanban else "unassigned"
        #a_story['Status']=Story.Status if story.Status else "unassigned"
        a_story['id'] = story.FormattedID
        a_story['name'] = story.Name
        a_story['Opened']=(datetime.strptime(story.CreationDate, '%Y-%m-%dT%H:%M:%S.%fZ').strftime('%Y-%d-%b'))
        a_story['Requester']= story.Owner.Name if story.Owner else "unassigned"
        a_story['Blocked']= story.Blocked
        a_story['Service']=story.c_ServiceNowID

My issue is to get access to the value of the linkid of my customfield (c_ServiceNowID).
When I run a Dict = I see that I have LinkID attributes but when I type
story.c_ServiceNowID.LinkID, I receive an error message telling me there is no such attributes.... How do I access this value using python ?
Thank you

A: According to the documentation at http://pyral.readthedocs.io/en/latest/overview.html#custom-fields, pyral allows you to reference the field without the c_ prefix

Most Artifact types in Rally can be augmented with custom fields. As of Rally WSAPI v2.0, the ElementName for a custom field is prefixed with 'c_'. The pyral toolkit allows you to reference these fields without having to use the 'c_' prefix. For example, if your custom field has a DisplayName of 'Burnt Offerings Index' you can use the String of 'BurntOfferingsIndex' in a fetch clause or a query clause or refer to the field directly on an artifact as artifact.BurntOfferingsIndex.

A: I think what you have should work, unless the ServiceNowID is empty.  In that case there will not be a LinkID or DisplayString available on the ServiceNowID object.
If you update your code to check to make sure the Attribute is there, does it work?
if hasattr(story.c_ServiceNowID, 'LinkID'):
  a_story['Service']=story.c_ServiceNowID.DisplayString
  a_story['Link']=story.c_ServiceNowID.LinkID


text:
Q: How to find out if a tile is being covered by a polygon? Given a (intersecting) polygon, I'd like find out which tiles are being covered by the polygon.
Example:

Details:

*

*Tiles are square, 1 unit wide/high

*The grid begins in (0,0)

*The corners of the polygon can have floating point coordinates (i.e. 3.433, 5.234)

*In general, an edge of the polygon might be as long as 1000 - 10000 tiles

I tried to iterate over all tiles and check whether they are in the polygon, however as I have to iterate over 10000² tiles it takes a quite a long time.
I'm interested in a solution which allows me to quickly answer "Is tile (x,y) covered by the polygon?" without recomputing everything from scratch for each question.
Any solution/approach/pseudo-code/hint which leads me to a correct solution will be accepted.

A: It seems that you want to do polygon rasterization, where your "pixels" are your grid elements.
An approach I would try (as chances are you will find ready-to-use algorithms to do that), is to use an in-memory rasterizer (e.g. Cairo), adjusting the filtering (and of course the coordinates of your polygons so they are expressed in grid units).
You could alternatively roll your own using existing algorithms.
For instance:

*

*split the polygon into its convex parts

*draw each polygon's outline (more precise: each convex part's outline) with Bresenham's line algorithm

*fill the holes (which should be easy since you are working with convex polygons)
For step 2, if you want to cover all pixels, see this SO question.


text:
Q: kfd: error getting iommu info I got this error during boot process.
[15.757121] kfd kfd: error getting iommu info. is the iommu enabled?
[15.757182] kfd kfd: Error initializing iommuv2 for device (1002:1318)
[15.757245] Creating topology SYSFS entries
[15.757376] kfd kfd: device (1002:1318) NOT added due to errors

How can I fix it?

A: Bad BIOS UEFI tables are a common problem, which yield a non funtional iommu.
If on X86 or AMD64 try:
Edit the file /etc/default/grub:
Change the line
GRUB_CMDLINE_LINUX=""

To:
GRUB_CMDLINE_LINUX="iommu=pt"

Run:
sudo update-grub

Reboot.

In many cases the "pass through" function of the kernel will provide iommu funtionality also the BIOS is foobar. The HSA software stack will run on a system with a working iommu funtionality without tiggering the iommu error message.

A: Found this from a Google Search:
UEFI boot was a red herring. The real problem was that you need a kfd.rules file in /etc/udev/rules.d. The file must say:
KERNEL=="kfd", GROUP="video", MODE="0660"

You may also need to set proper selinux policy
restorecon /etc/udev/rules.d/kfd.rules

Installing mainline 3.19 in Ubuntu 14.10 created this file during package installation (we think?), but Ubuntu 15.04 does not create this file by default. You must do it by hand. Then the HSA software stack works!
Problem solved.

A: I got this error (between others) using a linux embedded udoo bolt device that was using a cloned HD (using dd) from another identical device.
The problem was solved updating disks information on /etc/fstab with the correct UUID.
Using blkid / fdisk -l on the new device the UUID of all disks can be found and used to update /etc/fstab.

A: If you have this error following an AMD GPU error, add amd_iommu=on to GRUB_CMDLINE_LINUX as well.


text:
Q: selecting random rows with normal distribution based on a column in SQL Server 2012 FULL DETAILS:
let me explain more clear. this is a table including about 100 question. every question has a BooKRange property that shows from which part of the book, this question hast fetched with values 1,2,3,4. and there is another property called Level that shows level of the difficulty of the question with values 1,2,3,4,5. now i need to randomly select 20 question that have to include all four Book Ranges and all five levels with a normal distribution.
please consider that i need to select distinct rows.
thank you very much.
edit: added the table
CREATE TABLE [dbo].[Question] (
    [QuesID]    INT            IDENTITY (1, 1) NOT NULL,
    [BookRange] NVARCHAR (50)  NULL,
    [Level]     NVARCHAR (50)  NULL,
    PRIMARY KEY CLUSTERED ([QuesID] ASC)
);

A: Select distinct id from table where level=1 order by rand() limit 5 union Select distinct id from table where level=2 order by rand() limit 5 union Select distinct id from table where level=3 order by rand() limit 5 union Select distinct id from table where level=4 order by rand() limit 5

A: Since you havent provided any table schema, Assuming we have a table dbo.Number with One column with values from 1 - 30 you could do something like this ...
;With NthGroups
AS
 (
  SELECT  * , NTILE(4) OVER (ORDER BY Nums) Np
  FROM dbo.Number
 ),
Top25Perc
AS
 (
 SELECT TOP 5 * FROM NthGroups
 WHERE NP = 1
 ORDER BY NEWID()
 UNION ALL
  SELECT TOP 5 * FROM NthGroups
  WHERE NP = 2
  ORDER BY NEWID()
 UNION ALL
  SELECT TOP 5 * FROM NthGroups
  WHERE NP = 3
  ORDER BY NEWID()
  UNION ALL
  SELECT TOP 5 * FROM NthGroups
  WHERE NP = 4
  ORDER BY NEWID()
 )
 SELECT * FROM Top25Perc

Update
Just read your comment in other answer and you have mentioned you have a column Range with values (1,2,3,4) , this makes query even simpler , you can do something like this
;With
RandTop5
AS
 (
 SELECT TOP 5 * FROM TableName
 WHERE [Range] = 1
 ORDER BY NEWID()
 UNION ALL
  SELECT TOP 5 * FROM TableName
  WHERE [Range] = 2
  ORDER BY NEWID()
 UNION ALL
  SELECT TOP 5 * FROM TableName
  WHERE [Range] = 3
  ORDER BY NEWID()
  UNION ALL
  SELECT TOP 5 * FROM TableName
  WHERE [Range] = 4
  ORDER BY NEWID()
 )
 SELECT * FROM RandTop5

A: You can do this query (assuming a uniform distribution) without doing a union.  You just need to specify the ordering correctly.
If you want to select 5 questions from each of the levels, then you can do so by assigning a sequential number to the questions in each level.  If these are assigned randomly, then you should meet the requirement of randomness for the levels:
with q as (
      select q.*,
             row_number() over (partition by [range] order by newid()) as seqnum
      from Question q
     )
select *
from q
where seqnum <= 5;

If you want to ensure that these is exactly one question for each level and range, but want the questions random, then do:
with q as (
      select q.*,
             row_number() over (partition by [range], [level] order by newid()) as seqnum
      from Question q
     )
select *
from q
where seqnum = 1;

By the way, range and level are reserved words in SQL Server.  In general, it is good practice to avoid using reserved words for the names of things like tables, columns, stored procedures, and so on.


text:
Q: How can I map the F4 key's default functionality to trigger a key sequence rather than open Launchpad? (Mountain Lion) I will use the touchpad gesture to open Launchpad. I don't use Launchpad much.
I'd like to map the F4-key (which opens Launchpad) to send the Keystroke Command + Ctrl + Shift + 4 so I can use the OSX screenshot feature with it.
BetterTouchTool does not allow me to do it because it does not recognize when I press this key. I can get BTT to recognize F4 (i.e. hold fn then press F4) but this is not ideal: I need the top row to mostly function the way they already do while also not requiring pressing fn to take a screenshot.

A: This is more or less exactly what I wanted.
http://kevingessner.com/software/functionflip/
Works perfectly and no BTT is needed for setting the keyboard shortcut (Do it through Keyboard -> Keyboard Shortcuts in System Prefs)

A: Using KeyRemap4MacBook, you could also add this to
private.xml:
<autogen>__KeyToKey__ KeyCode::LAUNCHPAD, ModifierFlag::NONE, KeyCode::KEY_4, ModifierFlag::CONTROL_L | ModifierFlag::SHIFT_L | ModifierFlag::COMMAND_L</autogen>
See the source for the key code constants and predefined settings.


text:
Q: iText Vertical Alignment in Text inside a Canvas isn't working I'm trying to set my text which is inside a canvas to get vertically aligned with VerticalAlignment.BOTTOM property value, but whatever I put doesn't change the visual result.
retangulo = New iText.Kernel.Geom.Rectangle(122, AlturaPag - 208, 235, 27)
PdfCanvas = New iText.Kernel.Pdf.Canvas.PdfCanvas(page).SetLineWidth(1).Rectangle(retangulo).Stroke()
canvas = New iText.Layout.Canvas(PdfCanvas, retangulo)
texto = (New iText.Layout.Element.Text(Npagador).SetFontSize(11).SetBold)

' VerticalAlingment = BOTTOM \/
paragrafo = (New iText.Layout.Element.Paragraph().Add(texto).SetTextAlignment(TextAlignment.LEFT).SetVerticalAlignment(VerticalAlignment.BOTTOM))
canvas.Add(paragrafo)

A: You are trying to align the contents of the paragraph to the bottom of the paragraph itself, and the paragraph when laying itself out simply uses the minimal necessary height, so whatever alignment (bottom or top) you set, the result it just the same simply because paragraph packs itself to the minimal height.
To make sure setVerticalAlignment has an effect, you need to give the paragraph more vertical space by setting its height. Here is an example where I set paragraph height to match the height of the canvas you add it to, since it's the only element in the canvas. I also set the margins of the paragraph to zero so that you don't get additional spacing around the text.
The code is in Java but you will be able to convert it back to VB.NET as easily as I converted your code to Java:
Paragraph p = new Paragraph().add("Test").setTextAlignment(TextAlignment.LEFT)
        .setVerticalAlignment(VerticalAlignment.BOTTOM).setHeight(retangulo.getHeight());
p.setMargin(0);


text:
Q: Passing a function as an argument to FUN in lapply I'm designing a package which fits a model that involves basis expansions of columns of a matrix. I want the expansion to be user defined, so that any expansion is possible such as splines::bs, splines::ns, stats::poly. The same expansion is to be applied to every column of a matrix. I've tried some combinations of eval and substitute but cannot get it to work in nested functions.
What I'm trying to do

set.seed(123)
(mat <- replicate(4, rnorm(10)))
#>              [,1]       [,2]       [,3]        [,4]
#>  [1,] -0.56047565  1.2240818 -1.0678237  0.42646422
#>  [2,] -0.23017749  0.3598138 -0.2179749 -0.29507148
#>  [3,]  1.55870831  0.4007715 -1.0260044  0.89512566
#>  [4,]  0.07050839  0.1106827 -0.7288912  0.87813349
#>  [5,]  0.12928774 -0.5558411 -0.6250393  0.82158108
#>  [6,]  1.71506499  1.7869131 -1.6866933  0.68864025
#>  [7,]  0.46091621  0.4978505  0.8377870  0.55391765
#>  [8,] -1.26506123 -1.9666172  0.1533731 -0.06191171
#>  [9,] -0.68685285  0.7013559 -1.1381369 -0.30596266
#> [10,] -0.44566197 -0.4727914  1.2538149 -0.38047100

fit <- function(x, expr = splines::bs(i, df = 5)) {

  nvars <- ncol(x)
  x <- scale(x, center = TRUE, scale = FALSE)

  design <- design_mat(x = x, expr = expr, nvars = nvars)

  # then fit some model on design

}

design_mat <- function(x, expr, nvars) {

  lapply(seq_len(nvars), function(j) expr(x[, j]))

}

fit(x = mat)
#> Error in splines::bs(i, df = 5): object 'i' not found

What I've tried

set.seed(123)
mat <- replicate(4, rnorm(10))

fit <- function(x, expr = splines::bs(i, df = 5)) {
  sexpr <- substitute(expr)
  sexpr[[2]] <- substitute(x[,j])

  lapply(seq_len(ncol(x)), function(j) eval(sexpr))

}

result <- fit(x = mat)
lapply(result, head)
#> [[1]]
#>                 1            2          3           4         5
#> [1,] 0.2869090697 0.6076093707 0.10273054 0.000000000 0.0000000
#> [2,] 0.0415525644 0.6427602520 0.31195968 0.003727506 0.0000000
#> [3,] 0.0000000000 0.0003743454 0.01981069 0.247406189 0.7324088
#> [4,] 0.0001816776 0.4352403899 0.51334496 0.051232973 0.0000000
#> [5,] 0.0000000000 0.3905258786 0.53866977 0.070804348 0.0000000
#> [6,] 0.0000000000 0.0000000000 0.00000000 0.000000000 1.0000000
#>
#> [[2]]
#>                 1          2         3          4         5
#> [1,] 0.0000000000 0.02198301 0.3045954 0.49460707 0.1788145
#> [2,] 0.0011185047 0.35509930 0.6295682 0.01421403 0.0000000
#> [3,] 0.0003890728 0.32724596 0.6499248 0.02244016 0.0000000
#> [4,] 0.0246803968 0.50883712 0.4664825 0.00000000 0.0000000
#> [5,] 0.2872342378 0.53361187 0.1461208 0.00000000 0.0000000
#> [6,] 0.0000000000 0.00000000 0.0000000 0.00000000 1.0000000
#>
#> [[3]]
#>               1         2          3           4 5
#> [1,] 0.35168337 0.5649939 0.08306911 0.000000000 0
#> [2,] 0.00000000 0.3231237 0.55125784 0.125618496 0
#> [3,] 0.30267559 0.5962519 0.10107251 0.000000000 0
#> [4,] 0.07651472 0.6370926 0.28014756 0.006245077 0
#> [5,] 0.03869768 0.5949041 0.35104880 0.015349416 0
#> [6,] 0.00000000 0.0000000 0.00000000 0.000000000 0
#>
#> [[4]]
#>               1            2           3         4         5
#> [1,] 0.02100644 2.785920e-01 0.530958302 0.1694432 0.0000000
#> [2,] 0.55111536 5.535714e-02 0.001433639 0.0000000 0.0000000
#> [3,] 0.00000000 0.000000e+00 0.000000000 0.0000000 1.0000000
#> [4,] 0.00000000 1.946324e-05 0.004217654 0.2228812 0.7728817
#> [5,] 0.00000000 1.578049e-03 0.068681551 0.6628659 0.2668745
#> [6,] 0.00000000 3.492500e-02 0.350034463 0.6150405 0.0000000

A: Ooh, you're close. You just need the expression to be a function.
fit <- function(x, expr = function(i) splines::bs(i, df = 5)) {
  nvars <- ncol(x)
  x <- scale(x, center = TRUE, scale = FALSE)
  design <- design_mat(x = x, expr = expr, nvars = nvars)
  # then fit some model on design
}

A: Here's another solution that uses non-standard evaluation to change the call splines::bs(x, df = 6). The basic idea relies on using the rlang package to change the abstract syntax tree captured from the user. Here's the solution; the details appear below:
fit <- function(expr = splines::bs(x, df = 6)) {
    sexpr <- rlang::enexpr(expr)
    new_expr <- call2(sexpr[[1]],
                      call2(`[`, sexpr[[2]],
                            call2(seq_len,
                                  call2(nrow,
                                        sexpr[[2]])),
                            sym("i")),
                      splice(as.list(sexpr)[-c(1:2)]))

    seq_col <- call2(seq_len, call2(ncol, sexpr[[2]]))
    design <- lapply(eval(seq_col), function(i) eval(new_expr))

    # then fit some model on design
}

Details
The expression supplied by the user

splines::bs(x, df = 6)

The expression you would like to derive

splines::bs(x[,i], df = 6)

We will use the function rlang::call2 to create a function call that will then be evaluated using base::eval.
1. Capture the expression from the user
This is straightforward: sexpr <- rlang::enexpr(expr). Now we can extract the function as the first slot of the list-like object sexpr, and the other slots correspond to the arguments passed to this function.
2. Create x[,i]
We first need to rewrite this in prefix form: `[`(x, seq_len(nrow(x)), i). We now see that we have three nested functions. We can create the first call nrow(x) as follows: call2(nrow, sym("x")). But recall that the symbol sym("x") can also be extracted from the second slot of sexpr, which gives call2(nrow, sexpr[[2]]). Continuing this way, we can get x[,i] as follows:
call2(`[`,
      sexpr[[2]],
      call2(seq_len,
            call2(nrow,
                  sexpr[[2]])),
      sym("i"))

3. Create splines::bs(x[,i], df = 6)
This is tricky, because we need to keep track of the extra arguments. For this, we can use the function rlang::splice. If we let foo be the expression created in step 2 above, we can write
`call2(sexpr[[1]], foo, splice(as.list(sexpr)[-c(1:2)]))`

Note that we dropped the first and second slots from sexpr, which correspond to the function and the matrix x, respectively.
4. Create seq_len(ncol(x))
We're pretty good at this now: call2(seq_len, call2(ncol, sexpr[[2]]))
5. Put it all together and evaluate
This is the last line lapply(eval(seq_col), function(i) eval(new_expr))


text:
Q: View collective data from all tables using a single query I have 20 tables and want to see the data of all tables with one query. Is there any way I could do this?
The tables, join/converge on 2 columns. Also, is it possible to view the collective data directly on XAMPP?

A: It's completely based on how your tables connected to each other and you need a little knowledge to utilize your mysql server to do that for you.
In practice let's say you have a table for customers and a table for products and a relation between them indicating which customer bought which product (which also a table in this case):
Customers (id, username, password, fullname, email)
Products (id, name, sku, price)
Customers_Products (customer_id, product_id, created_at)
And we want to get a list of all products sold from May:
SELECT c.fullname, p.name, p.sku, p.created_at FROM Products AS p INNER JOIN Customers_Products AS cp ON p.id=cp.product_id INNER JOIN Customers as c ON c.id=cp.customer_id WHERE created_at > '2015-05-01 00:00:00';
I wrote this example to show you that doing this is completely depends on your requirements which can be very simple like selecting data from just one table to very complicated like joining multiple tables while filtering, grouping and ordering them.
For your next question. Yes It's possible you can see what's on your tables from phpMyAdmin but usually this is not a good solution since a user in phpMyAdmin can see the plumbing part of your system. The other way that most people use is to write some code to acquire the data and show them to the user.


text:
Q: Is there a construct like Java initializing blocks in C++? I read in some articles that there is something called Initializing blocks in java ; where we can perform some initializing assignments When the Class is loaded or an instance is created.

Apart from methods and constructors, Initialization Blocks are the third place in a Java Program where operations can be performed.

class InitDemo
{
     static int y;
     int x;
 {
   y = 10;
   x =  0;
 }
}

I am asking if there is such paradigme in C++ ?
Thank you.

A: It needs to be pointed out that there are two different forms of initialization blocks in Java.  The bare {...} block, without the keyword static, is just a bit of compiler swizzling -- the text in the block is appended to the front of any constructors that are defined -- no separate code segment is generated.  A block that begins static {..., on the other hand, is a static initialization block and a (semi-)proper procedure in its own right (named, not surprisingly, "static").
The static block is executed only once, immediately (with a few caveats) after the class is loaded.  The non-static initializer is (by virtue of being copied into the constructors) executed every time a constructor is executed, and hence is generally inappropriate for static init.

A: In a nutshell, C++ does not have a direct equivalent for this Java construct.
To get similar behaviour, you would have to set x and y from InitDemo's constructors (which you can also do in Java).


text:
Q: How to redirect to previous URL after Facebook Passport without sessions I'm trying to redirect back to the link in the referer header, but the request on the facebook callback doesn't contain a referer header.
app.get(
    // referer present
    '/login/facebook',
    passport.authenticate('facebook', { scope: ['email'], session: false }),
);

app.get(
    // referer not present
    '/login/facebook/return',
    passport.authenticate('facebook', { failureRedirect: config.CLIENT_URI, session: false }),
    (req, res) => {
        const { secret, expiresIn } = config.jwt;
        const id = Array.isArray(req.user) ? req.user[0].id : req.user.id;

        // Redirect to client
        const token = jwt.sign({ id }, secret, { expiresIn });

        if (req.headers.referer) {
            res.redirect(`${req.headers.referer}?token=${token}`);
        } else {
            res.redirect(`${config.CLIENT_URI}?token=${token}`);
        }
    },
);

How do I redirect back to the referer? I don't want to use sessions.


text:
Q: How to pass values from one action to another without redirecting to that action I would like to know how I can pass values from one action to another action without redirecting to that controller.
For example, I want to pass values from my "Index" action to my "reservation_step_2" action without having to redirect to that page but instead to my "reservation_step_1" page.
 [HttpPost]
    public ActionResult Index(string locationId, string dt1, string dt2, string PickUpTime, string DropOffTime)
    {
        string loc = locationId;
        string PUT = PickUpTime;
        string DOT = DropOffTime;
        DateTime d_in = DateTime.ParseExact(dt2.Trim(), "dd/M/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
        DateTime d_out = DateTime.ParseExact(dt1.Trim(), "dd/M/yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);

        return RedirectToAction("reservation_step_1", "Home", new { d_out = d_out, d_in = d_in, loc = loc, PU_time = PUT, DO_time = DOT});
    }

I would like to pass d_out, d_in, PU_time and DO_time to "reservation_step_2" but pass loc to "reservation_step_1" and redirect to "reservation_step_1"
How can I go about doing this?


text:
Q: Regex for match sequence digits in Amazon Redshift I am write a regex that matches sequence increasing numbers in string. It works fine in test, but does not works in Amazon Redshift.
Can anyone help me out here
Regex:
^(?:[^1]*)1(?:[^2]*)2(?:[^3]*)3(?:.*)$

For example it match strings (correct):
123
1331213
12222211323
17397462453
1abcd2abcd3abcd

https://regex101.com/r/zkUMxG/1/
When I use it in Amazon, get error:
Error running query: Invalid preceding regular expression prior to repetition operator. The error occurred while parsing the regular expression fragment: '(?>>>HERE>>>:[^1]*)1(?'. DETAIL: ----------------------------------------------- error: Invalid preceding regular expression prior to repetition operator. The error occurred while parsing the regular expression fragment: '(?>>>HERE>>>:[^1]*)1(?'. code: 8002 context: T_regexp_init query: 19124520 location: funcs_expr.cpp:185 process: query1_107_19124520 [pid=15061] -----------------------------------------------

A: Amazon Redshift regex is POSIX-based (proof). POSIX Basic Regular Expressions don't support non-capturing groups that your ^(?:[^1]*)1(?:[^2]*)2(?:[^3]*)3(?:.*)$ expression contains: there are four (?:...) patterns.
Remove the groups altogher as you do not plan on using them:
^[^1]*1[^2]*2[^3]*3.*$


text:
Q: jtextarea does not pop out import net.htmlparser.jericho.*;

@SuppressWarnings({ "serial", "unused" })
public class RenderToText extends JDialog {

    static JTextArea _resultArea = new JTextArea(100, 100);
    JScrollPane scrollingArea = new JScrollPane(_resultArea);
    private final static String newline = "\n";
    int filename = 100;
    String[] fileName = new String[filename];

    public RenderToText(){
        for (int i = 0; i < filename; i++) {
         String fileName = "abc"+i+".txt";
            // A File object to represent the filename
            File f = new File(fileName);
            f.delete();
        }

        _resultArea.setEditable(false);
        //Starting to write files
        try{
        FileReader fr = new FileReader(
                "C:\\Users\\user\\fypworkspace\\FYP\\Link\\abc.txt");
        BufferedReader textReader = new BufferedReader(fr);

        // for each URL, process the URL and render the HTML file
        int numberofURL = 100;
        String[] URL = new String[numberofURL];
        int a;

        // For each URL, assign one text file to store the contents

        // for each URL, extract the URL contents

        for (a = 0; a < numberofURL; a++) {
            for (int i = 0; i < numberofURL; i++) {

                URL[a] = textReader.readLine();
                try{
                try {
                    try {
                        // Render the text from the HTML file
                        String sourceUrlString = URL[a];

                        System.out.println("Using argument of \""
                                    + sourceUrlString + '"');

                        if (sourceUrlString.indexOf(':') == -1)
                            sourceUrlString = "file:" + sourceUrlString;
                        Source source = new Source(new URL(sourceUrlString));
                        String renderedText = source.getRenderer()
                                .toString();
                        _resultArea.append("\nSimple rendering of the HTML document:\n" + newline);
                        System.out.println(renderedText+ newline);

                        // Write the rendered text to a text file

                        String filename = ("abc" + i + ".txt");
                        Writer output = null;
                        String text = renderedText;
                        File file = new File(filename);
                        output = new BufferedWriter(new FileWriter(file));
                        output.write(text);
                        output.close();
                        System.out.println("Your file has been written"+ newline);

                        // Count the number of words available in the
                        // rendered text.

                        BufferedReader br = new BufferedReader(
                                new FileReader(
                                        "C:\\Users\\user\\fypworkspace\\FYP\\abc"
                                                + i + ".txt"));
                        String line = "", str = "";
                        int count = 0;
                        while ((line = br.readLine()) != null) {
                            str += line + " ";

                        }
                        StringTokenizer st = new StringTokenizer(str);
                        while (st.hasMoreTokens()) {
                            String s = st.nextToken();
                            count++;
                        }
                        _resultArea.append("File has " + count + " words."+ newline);
                    } catch (UnknownServiceException ex) {
                        System.out.println("The following url cannot be processed"+ newline);

                    }

                    System.out.println("\n");
                    System.out.println("\n");
                    System.out.println("\n");
                } catch (NullPointerException ex) {
                    System.out.println("End of URL");
                    System.exit(0);
                }
            }catch(IOException ex){
                System.out.println("The following url cannot be processed due to the need to login");
            }
            }
        }

    }catch (IOException e1) {
    }
    JPanel content = new JPanel();
    content.setLayout(new BorderLayout());
    content.add(scrollingArea, BorderLayout.CENTER);

    this.setContentPane(content);
    this.setTitle("TextAreaDemo B");

    this.pack();
    }

    public static void main(String[] args) throws IOException {
        JDialog win = new RenderToText();
        win.setVisible(true);

    }
    }

This code extract the contents of a website. I have use append on the output, however the jtextarea does not come out. It cant run, but it CANT transfer the output to the jtextarea. What do i missing ?

A: You are running two loops
for (a = 0; a < numberofURL; a++)
    for (int i = 0; i < numberofURL; i++)

with 100 steps each. Thus you're reading 10000 URLs from your input file. If there are not enough of them readline will return null and thus you'll exceptions (see also comment from extraneon). Get rid of the useless second loop.
Besides the errors in reading the files your textarea should display the output (and it does in my test). Therefore it seems that it lies within your read loop and the exception handling therein.
Note: please also consider the other comments from extraneon.

A: Agree with comment about static JTextArea. If you want to shere content you can use the same Document in two JTextAreas added in different places.


text:
Q: How can I get Xamarin account? I'm new to Xamarin .. I found that there is an account called Xamarin account.
Visual Studio 2017 -> Tools Menu -> Xamarin Account.
However, I don't follow how can I get such Xamarin Account .. so do you have any suggestions about how to get or create Xamarin Account ?

A: There are no Xamarin accounts anymore.
Xamarin used to be an independent company until Microsoft acquired it in 2016. When it was an independent company, you had to use your Xamarin account to pay for your Xamarin license.
Today, Xamarin is free and included in Visual Studio 2017.
Edit: The Xamarin Component Store has been deprecated and is now obsolete.


text:
Q: To check status of Tomcat server in Linux I need to know whether Tomcat 7.0.2.3 is on or not.
I got an error page that shows this message:
HTTP Status 404 - /cas/login

type Status report

 message /cas/login

description The requested resource (/cas/login) is not available.
 Apache Tomcat/7.0.23

I need to check the status and start the service of Tomcat in Linux. I have tried:
#/bin/startup.sh
#rctomcat7 start

But all these are not working.

A: Like others have pointed out, if you are receiving an HTTP standard response code of 404 then it means that Tomcat is up.
But to answer your question, you can try
 #rctomcat7 status

A: I have used below script. This script check tomcat post and process is running up or not,if not then start the tomcat.
Tomcat Start script
if netstat -tulpen | grep 18880 && ps -ef | grep tomcat | grep java

then

    echo "Tomcat Running"

else

    echo "Tomcat Stopped"

    /bin/sh /tomcat/bin/startup.sh

fi


text:
Q: How to change windows theme (or at least the background) using the command line or scripts I am trying to make it so that the theme (or at least the background) changes when I switch desktop view. I have found some answers but most if not all are about old versions of windows and do not work for windows 10. The scripting tool I am using is AHK. Thank you in advance.

A: Its possible to change the background using this command:
reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v Wallpaper /t REG_SZ /d  wallpaper_path /f

Changing the theme is not that direct, you might want to run the following command. What it does is that it will show you a dialog where you can pick the theme you want. (It may also reset your theme to default)
rundll32.exe %SystemRoot%\system32\shell32.dll,Control_RunDLL %SystemRoot%\system32\desk.cpl desk,@Themes /Action:OpenTheme /file:"C:\Windows\Resources\Themes\aero.theme"

A: It's although possible to change the theme using this command:
call <path-to-your-theme>

You close the opened window using this command:
taskkill /IM ApplicationFrameHost.exe

A: I came across this question while looking to do the same thing for my company's computer image. The command below worked well for me, keep in mind that the taskkill part would kill all settings windows
C:\PATH\TO\THEME\FILE.theme & timeout /t 03 /nobreak > NUL & taskkill /f /im systemsettings.exe
This will launch the theme file which will apply the theme but also open the Setting app/window, but then it will wait for the timeout (set to 3 seconds in the command above) then kill the Settings app/window. Tested on Windows 10 Enterprise x64 v1909. Also depending on the performance of the computers you might be able to lower the timeout from 3 seconds.
Martin's answer didnt work for me, but after some reading it believe its because of changes made with either v1809 or v1903


text:
Q: Intercambiar los valores de la primera columna con la ultima columna Al imprimir mi código me sale todo lo contrario a lo que quiero, en vez de imprimirme el intercambio de columnas me imprime un intercambio de filas.
Solo quieron que me intercambie los valores de la primera columna con la última columna, ya me vi muchos tutoriales y aún no lo resuelvo.
import Vectores.Modulos;
public class Problema8 {
    @SuppressWarnings("empty-statement")
    public static void main(String[] args) {
       //definimos una matriz
       int matriz[][];
       int Filas,Columnas;
       // Lectura de filas y columnas de la matriz
       Filas =  Modulos.LeerEntero("Ingrese el tamaño de fila de la matriz : ");
       Columnas = Modulos.LeerEntero("Ingrese el tamaño de columna de la matriz");
       //creamos la matriz
       matriz= new int[Filas][Columnas];
       //lectura de los datos del vector
       for(int i=0; i<Filas; i++){
           for(int j=0; j<Columnas ; j++){
              matriz[i][j] = Modulos.LeerEntero("Ingrese valor para la matriz["+i+"]["+j+"] :");
           }
       }
       //generar una cadena con los datos de la matriz
       String cadena="";
       for(int i=0;i<Filas;i++){
           for(int j=0;j<Columnas;j++){
               cadena =  cadena + "    "+matriz[i][j];
           }
           cadena=cadena+"\n";
       }
       //Intercambio de columnas
       int auxiliar;
       for(int i=0;i<matriz[0].length;i++){
           auxiliar=matriz[0][i];
           matriz[0][i]=matriz[1][i];
           matriz[1][i]=auxiliar;
       }
       String cadenas="";
       for(int i=0;i<Filas;i++){
           for(int j=0;j<Columnas;j++){
                cadenas=cadenas+"  "+matriz[i][j];
            }
            cadenas=cadenas+"\n";
        }

       //Imprimimos las matriz
       Modulos.Imprimir("Los datos de la matriz son : \n"+cadena+"\n\n Matriz intercambiada : \n "+cadenas);
    }
}

A: Este problema me llevo a pensar un poco pero lo tengo solucionado, para que entiendas un poco mas, te voy a explicar el proceso de como intercambiar las columnas, pero antes te muestro como serian ejemplo probados:

Matriz original:
   1   2   3
   4   5   6
   7   8   9
   10   11   12
   13   14   15

Matriz modificada:
   3   2   1
   6   5   4
   9   8   7
   12   11   10
   15   14   13

Como vez se intercambian las columnas 1 y 3 (0,2), El código es bastante sencillo:
Se recorren las filas de la matriz, y se crea un numero auxiliar que seria la posición i de fila y la columna 0 (obtenemos el primer lugar en la matriz), luego se intercambia la fila actual matriz[i][0] por la columna que queremos intercambiar, como la fila es la misma se utiliza i para la fila y columna que es el parámetro que pasamos de la columna que elegimos cambiar, luego la columna matriz[i][columna] (la columna que queremos cambiar) la pasamos a la variable auxiliar que era matriz[i][0]
En otras palabras si tuviéramos una matriz 3x3 (se comienza a contar desde el 0) cambiamos la columna [i][0] por [i][2], y como la variable i va incrementando se van cambiando todos los valores.
for (int i = 0; i < matriz.length; i++) {
    int aux = matriz[i][0];
    matriz[i][0] = matriz[i][columna];
    matriz[i][columna] = aux;
}

Esa es la explicación del intercambio, acá te dejo mi clase que utilicé para crear esto, es diferente a la tuya porque me gusta separar todo por pequeños métodos. También he utilizado una clase que no es mía, para la entrada por teclado ya que el Scanner siempre trae problemas, se llama Parser y la podes encontrar en el siguiente enlace: https://github.com/darrensun/OJ-Solutions/blob/master/src/com/darrensun/spoj/facefrnd/Main.java
(Si te funciona el Scanner y anda todo bien para ti, pues mejor)
De todos modos el métodos de intercambio ya te lo enseñe.
import java.io.IOException;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        int[][] matriz;
        int filas, columnas;

        filas = scannerInt("Ingrese la cantidad de filas de la matriz: ");
        columnas = scannerInt("Ingrese la cantidad de columnas de la matriz: ");

        matriz = new int[filas][columnas];

        fillArray(matriz); // LLENAR ARRAY

        String original = arrayToString(matriz);

        // INTERCAMBIAMOS COLUMNAS
        intercambiarXcon0(matriz, columnas-1);

        print("Matriz original: " + "\n" + original + "\n" + "Matriz modificada: " + "\n" + arrayToString(matriz));
    }

    /**
     * Intercambia la posicion de 'x' columna por la columna 0.
     * El valor de la columna pasada por parametro empieza a contar
     * desde el numero 0, en una matriz 3x3 el valor de la columa a pasar es 2,
     * esto es porque del 0 al 2 hay 3 numeros. (0, 1, 2) -> 3
     *
     * @param matriz
     * @param columna
     */
    public void intercambiarXcon0(int[][] matriz, int columna) {
        for (int i = 0; i < matriz.length; i++) {
            int aux = matriz[i][0];
            matriz[i][0] = matriz[i][columna];
            matriz[i][columna] = aux;
        }

    }

    private void fillArray(int[][] array) {
        for (int i = 0; i < array.length; i++) { // FILAS
            for (int j = 0; j < array[0].length; j++) { // COLUMNAS
                array[i][j] = scannerInt("Ingresar valor en la posición ["+i+"]["+j+"] : ");
            }
        }
    }

    private StringBuilder cadena = new StringBuilder();

    private String arrayToString(int[][] array) {
        cadena.setLength(0);

        for (int i = 0; i < array.length; i++) { // FILAS
            for (int j = 0; j < array[0].length; j++) { // COLUMNAS
                cadena.append("   " + array[i][j]);
            }
            cadena.append("\n");
        }

        return cadena.toString();
    }

    public int scannerInt(String text) {
        System.out.println(text);

        Parser parser = new Parser(System.in);

        int number = 0;

        try {
            number = parser.nextInt();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(number);

        return number;
    }

    public void print(String text) {
        System.out.println(text);
    }

}

Y otro ejemplo pero de una matriz cuadrada: (rows = columns)

Matriz original:
   1   2   3
   4   5   6
   7   8   9

Matriz modificada:
   3   2   1
   6   5   4
   9   8   7

Edit:
Con respecto a lo ultimo preguntado en los comentarios, crea un método que retorne un entero que contenga la suma de todos los números pares de la matriz,
/**
 * Obtiene la suma de todos los numeros pares que
 * conforman una matriz bidimensional.
 *
 * @param array
 * @return
 */
private int getSumaPares(int[][] array) {
    int result = 0;
    for (int i = 0; i < array.length; i++) { // FILAS
        for (int j = 0; j < array[0].length; j++) { // COLUMNAS
            if(array[i][j] % 2 == 0) {
                result += array[i][j]; // si es par sumo al resultado
            }
        }
    }
    return result;
}

Ahora en vez de intercambiar los valores de la primer columna con la segunda, simplemente remplace los números, si es lo que necesitas.
En el método de intercambiar X por 0:
/**
 * Intercambia la posicion de 'x' columna por la columna 0.
 * El valor de la columna pasada por parametro empieza a contar
 * desde el numero 0, en una matriz 3x3 el valor de la columa a pasar es 2,
 * esto es porque del 0 al 2 hay 3 numeros. (0, 1, 2) -> 3
 *
 * @param matriz
 * @param columna
 */
private void intercambiarXcon0(int[][] matriz, int columna) {
    int numero = getSumaPares(matriz);

    for (int i = 0; i < matriz.length; i++) {
        matriz[i][0] = numero; // remplazo por la suma de todos
        matriz[i][columna] = numero; // los numeros pares que tenia la matriz.
    }

}

A: algo asi mira bro :
digamos que esta es la matriz que acabo de ingresar
4    - 6 -    8
2  -   7  -   9
4    - 2    - 2
las suma de los pares de toda la matriz seria 28
entonces el resultado de la suma lo remplazo en toda la primera y ultima fila
28-6- 28
28- 7- 28
28- 2 -28

A: Ingresar números enteros a una matriz cuadrada de tamaño N e intercambiar los elementos de la última columna con la última fila.


text:
Q: Replace bullets with dashes in a Word document I'm trying to replace the bullets of a list in a word document with dashes, basically only the "rendered icon" to be replaced, i.e.
Replace bullets from the below list:

*

*this is a list item

*this is another list item

*yet another item
with dashes:

— this is a list item
— this is another list item
— yet another item

I'm going to do this using ActiveX in Delphi, but VB code would also do, thank you!

A: Is this what you are trying?
Option Explicit

'~~> Select the relevant range before running this code
Sub Sample()
    With ListGalleries(wdBulletGallery).ListTemplates(1).ListLevels(1)
        .NumberFormat = ChrW(61485)
        .TrailingCharacter = wdTrailingTab
        .NumberStyle = wdListNumberStyleBullet
        .NumberPosition = InchesToPoints(0.25)
        .Alignment = wdListLevelAlignLeft
        .TextPosition = InchesToPoints(0.5)
        .ResetOnHigher = 0
        .StartAt = 1
        .Font.Name = "Symbol"
        .LinkedStyle = ""
    End With
    ListGalleries(wdBulletGallery).ListTemplates(1).Name = ""

    Selection.Range.ListFormat.ApplyListTemplateWithLevel ListTemplate:= _
    ListGalleries(wdBulletGallery).ListTemplates(1), ContinuePreviousList:= _
    False, ApplyTo:=wdListApplyToSelection, DefaultListBehavior:= _
    wdWord10ListBehavior
End Sub

SNAPSHOT

A: Within Delphi code:
uses ..., ComObj;

const
  wdListNumberStyleBullet = 23;
var
  vMSWord                      : variant;
    Doc                          : Variant;
  oListTemplate                : Variant;
  oListLevel                   : Variant;
  iLoopTemplates, iMaxTemplates: Integer;
  iLoopLevels, iMaxLevels      : Integer;
begin
  try
    vMSWord         := GetActiveOleObject('Word.Application');
    vMSWord.Visible := True;
    Doc             := vMSWord.ActiveDocument;
    iMaxTemplates   := Doc.ListTemplates.Count;
    for iLoopTemplates := 1 to iMaxTemplates do
    begin
      oListTemplate := Doc.ListTemplates.Item(iLoopTemplates);
      iMaxLevels    := oListTemplate.ListLevels.Count;
      for iLoopLevels := 1 to iMaxLevels do
      begin
        oListLevel := oListTemplate.ListLevels.Item(iLoopLevels);
        if      (oListLevel.NumberStyle  = wdListNumberStyleBullet)
            and (oListLevel.NumberFormat = UTF8String(#61623))
            and (oListLevel.Font.Name    = 'Symbol') then
//        if (oListLevel.NumberStyle = wdListNumberStyleBullet) then
        begin
          oListLevel.NumberFormat := UTF8String('-');
          oListLevel.Font.Name    := 'Arial';
        end;
      end;
    end;
  except
    ShowMessage('Open a Word document before running this method');
  end;

The current IF is checking if it's really a •bullet wih a •
If you don't need this check, comment this line (if...) and uncomment the next one...

A: A macro which does the job...
Dim oListTemplate As ListTemplate
Dim oListLevel As ListLevel

For Each oListTemplate In ActiveDocument.ListTemplates
    For Each oListLevel In oListTemplate.ListLevels
        If oListLevel.NumberStyle = wdListNumberStyleBullet Then
            With oListLevel
                .NumberFormat = "-"
                .Font.Name = "Arial"
            End With
        End If
    Next oListLevel
Next oListTemplate


text:
Q: ListView do banco de dados Android - Fecha aplicação com erro Estou implementando um cadastro com SQLite3 no Android e até aqui tudo bem, o problema está na chamada da Activity de listagem de dados quando o cadastro é realizado com sucesso, ao fazer a chamada a Activity a aplicação é fechada com erro.
Segue código:
DevedorActivity
package br.com.savemoney.mastercontas;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import br.com.savemoney.database.DatabaseHelper;

public class DevedorActivity extends Activity {

  private DatabaseHelper helper;
  private EditText edtNomeDevedor, edtTelefoneDevedor, edtEmailDevedor;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.devedor);

    edtNomeDevedor = (EditText) findViewById(R.id.edtNomeDevedor);
    edtTelefoneDevedor = (EditText) findViewById(R.id.edtTelefoneDevedor);
    edtEmailDevedor = (EditText) findViewById(R.id.edtEmailDevedor);

    helper = new DatabaseHelper(this);
  }

  public void cadastrarDevedor(View view) {
    SQLiteDatabase db = helper.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put("nome", edtNomeDevedor.getText().toString());
    values.put("telefone", edtTelefoneDevedor.getText().toString());
    values.put("email", edtEmailDevedor.getText().toString());

    long resultado = db.insert("devedor", null, values);
    if(resultado != -1) {
        Toast.makeText(getBaseContext(), R.string.cadastro_devedor_sucesso, Toast.LENGTH_LONG).show();
        startActivity(new Intent(this, ListaDevedoresActivity.class));
    } else {
        Toast.makeText(getBaseContext(), R.string.cadastro_devedor_erro, Toast.LENGTH_LONG).show();
    }
  }

  @Override
  protected void onDestroy() {
    helper.close();
    super.onDestroy();
  }
}

ListarDevedoresActivity
package br.com.savemoney.mastercontas;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;
import br.com.savemoney.database.DatabaseHelper;

public class ListaDevedoresActivity extends Activity {

  private DatabaseHelper helper;
  private SQLiteDatabase db;
  private SimpleCursorAdapter adapter;
  ListView listViewDevedores;

  private static final String[] campos = new String[] {"_id", "nome"};

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.lista_devedores);

    helper = new DatabaseHelper(this);

    listViewDevedores = (ListView) findViewById(R.id.listDevedores);

    listarDevedores();
  }

  public void listarDevedores(){
    //executa consulta geral de todos os registros cadastrados no banco de dados
    Cursor devedores = db.query("agenda", campos, null, null, null, null, null);

    if (devedores.getCount() > 0){
        //cria cursor que será exibido na tela, nele serão exibidos
        //todos os contatos cadastrados
        adapter = new SimpleCursorAdapter(this, R.layout.item_devedor, devedores, campos, new int[] { R.id.txtIdDevedor, R.id.txtNomeDevedor});

        //relaciona o dataSource ao próprio listview
        listViewDevedores.setAdapter(adapter);
    }else{
        Toast.makeText(this, "Nenhum registro encontrado", Toast.LENGTH_SHORT).show();
    }
  }

  @Override
  protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();

    //fecha a conexão com o Banco de dados
    db.close();
   }
}

LogCat
Aqui, peguei só a parte de erro... Vejam se conseguem ver alguma coisa!
> 06-19 14:21:08.579: E/AndroidRuntime(1971): FATAL EXCEPTION: main
> 06-19 14:21:08.579: E/AndroidRuntime(1971): Process:
> br.com.savemoney.mastercontas, PID: 1971 06-19 14:21:08.579:
> E/AndroidRuntime(1971): java.lang.RuntimeException: Unable to start
> activity
> ComponentInfo{br.com.savemoney.mastercontas/br.com.savemoney.mastercontas.ListaDevedoresActivity}:
> java.lang.NullPointerException 06-19 14:21:08.579:
> E/AndroidRuntime(1971):   at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
> 06-19 14:21:08.579: E/AndroidRuntime(1971):   at
> android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
> 06-19 14:21:08.579: E/AndroidRuntime(1971):   at
> android.app.ActivityThread.access$800(ActivityThread.java:135) 06-19
> 14:21:08.579: E/AndroidRuntime(1971):     at
> android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
> 06-19 14:21:08.579: E/AndroidRuntime(1971):   at
> android.os.Handler.dispatchMessage(Handler.java:102) 06-19
> 14:21:08.579: E/AndroidRuntime(1971):     at
> android.os.Looper.loop(Looper.java:136) 06-19 14:21:08.579:
> E/AndroidRuntime(1971):   at
> android.app.ActivityThread.main(ActivityThread.java:5017) 06-19
> 14:21:08.579: E/AndroidRuntime(1971):     at
> java.lang.reflect.Method.invokeNative(Native Method) 06-19
> 14:21:08.579: E/AndroidRuntime(1971):     at
> java.lang.reflect.Method.invoke(Method.java:515) 06-19 14:21:08.579:
> E/AndroidRuntime(1971):   at
> com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
> 06-19 14:21:08.579: E/AndroidRuntime(1971):   at
> com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595) 06-19
> 14:21:08.579: E/AndroidRuntime(1971):     at
> dalvik.system.NativeStart.main(Native Method) 06-19 14:21:08.579:
> E/AndroidRuntime(1971): Caused by: java.lang.NullPointerException
> 06-19 14:21:08.579: E/AndroidRuntime(1971):   at
> br.com.savemoney.mastercontas.ListaDevedoresActivity.listarDevedores(ListaDevedoresActivity.java:35)
> 06-19 14:21:08.579: E/AndroidRuntime(1971):   at
> br.com.savemoney.mastercontas.ListaDevedoresActivity.onCreate(ListaDevedoresActivity.java:30)
> 06-19 14:21:08.579: E/AndroidRuntime(1971):   at
> android.app.Activity.performCreate(Activity.java:5231) 06-19
> 14:21:08.579: E/AndroidRuntime(1971):     at
> android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
> 06-19 14:21:08.579: E/AndroidRuntime(1971):   at
> android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
> 06-19 14:21:08.579: E/AndroidRuntime(1971):   ... 11 more

Alguém consegue ver onde está o erro? De já obrigado.

A: É um NullPointerException, ou seja, existe uma variável com valor nulo.
A melhor forma de resolver erros em tempo de execução, como é o caso do NullPointerException, é debugando o código.
Procure na pilha do erro referências aos seus arquivos fonte e a linhas que originou o erro.
Por exemplo:
ExemploActivity:96.
Coloque um ponto de parada antes da linha indicada (96), rode o debug e inspecione os valores de suas variáveis, passo a passo.
Não vale a pena ficar pressupondo o que aconteceu, é mais fácil partir logo para a ação.
DICA: No onCreate, em vez de recuperar somente à referencia dos seus componentes visuais (findViewById), trate também os seus valores.
Exemplo:
EditText edtNomeDevedor = (EditText) edtNomeDevedor = (EditText) findViewById(R.id.edtNomeDevedor);
String nomeDevedor = edtNomeDevedor.getText().toString() == null ? "": edtNomeDevedor.getText().toString();

Dessa forma você trata o valor, que pode estar vindo nulo, já na criação da sua atividade (Activity).
Boa sorte!


text:
Q: Get Twitter profile photo I'm trying to create an interface of tweets with a special hashtag , and i want to add a profile photo picture in tweets , is there any way to get the  twitter profile photo using twitter4j ?

A: Go through the following code.
Assume that the Twitter object is mytTwitter
*get the user from the twitter object

User user = mytTwitter.showUser(mytTwitter.getid());

*get the profile image URL

URL url = user.getProfileImageURL();

*create Image icon

ImageIcon img = new ImageIcon(url);

*set the JLabel icon to be the ImageIcon

Jlabel1.setIcon(img);

A: Yes you can. You must get a status and then:
status.getUser().getProfileImageURL(); //returns a string which is profile image url

For detailed usage:
getProfileImageURL()
twitter4j Javadoc


text:
Q: Dynamically generate textbox to match sum I'm trying to generate Dynamic Text Box
Starting with two textboxes.

if the value is less than the value in the first textbox then generate another textbox dynamically and let the user enter more values.
    This has to be done till the sum of the values of all the text boxes from the second to the last one generated becomes equal to the value of first textbox.

Of course other things need to be generated with the textboxes as well like lables etc. and positioned correctly so i thought of using a grid and generate the grid dynamically but above that i'm lost.
Any Help?
Thanks

i used a scrollviewer with the following code
<ScrollViewer Margin="8,8,8,14.417" Grid.Row="4" Grid.ColumnSpan="5" VerticalScrollBarVisibility="Hidden">
    <Grid Margin="8" Grid.Row="4" Grid.ColumnSpan="4" x:Name="amtGrid">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" MinWidth="103"/>
            <ColumnDefinition Width="Auto" MinWidth="324"/>
            <ColumnDefinition Width="Auto" MinWidth="218"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ComboBox x:Name="crdrnextrows" Margin="32.367,8,8,7.423" SelectedIndex="1" />
        <ComboBox Background="#FFC6C3C6" Margin="8" x:Name="comboboxCr" GotKeyboardFocus="comboboxCr_GotKeyboardFocus" Grid.Column="1"/>
        <TextBox Background="#FFC6C3C6" Foreground="White" IsEnabled="True" Margin="7.973,8,8,8" x:Name="txtBoxam1" Grid.Column="2" LostFocus="txtBoxam1_LostFocus"/>
        <TextBox Background="#FFC6C3C6" Foreground="White" IsEnabled="True" Margin="8,8,33.972,8" x:Name="txtBoxamt2" Grid.Column="3" LostFocus="textBox4_LostFocus"/>
    </Grid>
</ScrollViewer>

There is another textbox above that with similar code but without the scroll viewer, now what i was thinking was to dynamically create instances of the grid shown in the scrollviewer as many times as need to make them equal.
Is it possible to create new instances of the same grid and add them to the scollviewer dynamically with code?
Thanks

A: Looking at the additional information that you gave and given the complexity of the object you are wanting to create, a UserControl would probably be the best fit. This code is an example using a DoubleClick to show how to add the UserControl to your ScrollViewer.  You will need to expose properties in the UserControl in order to get the information from your TextBoxes otherwise the Code should be simular to my earlier answer.
i.e:
UserControl Xaml
<UserControl x:Class="WpfApplication1.UserControl1"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d"
             d:DesignHeight="70" d:DesignWidth="985">
    <Grid Margin="8" Grid.Row="4" Grid.ColumnSpan="4" x:Name="amtGrid" Height="40">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" MinWidth="103"/>
            <ColumnDefinition Width="Auto" MinWidth="324"/>
            <ColumnDefinition Width="Auto" MinWidth="218"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <ComboBox x:Name="crdrnextrows" Margin="32.367,8,8,7.423" SelectedIndex="1" />
        <ComboBox Background="#FFC6C3C6" Margin="8" x:Name="comboboxCr" GotKeyboardFocus="comboboxCr_GotKeyboardFocus" Grid.Column="1"/>
        <TextBox Background="#FFC6C3C6" Foreground="White" IsEnabled="True" Margin="7.973,8,8,8" x:Name="txtBoxam1" Grid.Column="2" LostFocus="txtBoxam1_LostFocus"/>
        <TextBox Background="#FFC6C3C6" Foreground="White" IsEnabled="True" Margin="8,8,33.972,8" x:Name="txtBoxamt2" Grid.Column="3" LostFocus="txtBoxamt2_LostFocus"/>
    </Grid>
</UserControl>

Window Xaml
<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="123" Width="1098" xmlns:my="clr-namespace:WpfApplication1" MouseDoubleClick="Window_MouseDoubleClick">

    <ScrollViewer VerticalScrollBarVisibility="Auto">
        <StackPanel Name="stackPanel1" VerticalAlignment="top" HorizontalAlignment="Left" >
            <my:UserControl1 x:Name="userControl11" Width="1077" />
        </StackPanel>
    </ScrollViewer>

</Window>

Main Window Code
public partial class MainWindow : Window
{

    public MainWindow()
    {
        InitializeComponent();
    }

    private void Window_MouseDoubleClick(object sender, MouseButtonEventArgs e)
    {
        UserControl1 newUserControl = new UserControl1();
        newUserControl.Width = userControl11.Width;
        newUserControl.Height = userControl11.Height;
        stackPanel1.Children.Add(newUserControl);
    }

}

Here is a basic idea, I am using a StackPanel to hold the TextBox's you may want to use a DockPanel to hold your labels and etc and add that to the StackPanel.
Xaml
<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <StackPanel Name="myContainer">
            <TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" KeyDown="textBox1_KeyDown" />
            <TextBox Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" KeyDown="textBox2_KeyDown"/>
        </StackPanel>
    </Grid>
</Window>

Code
public partial class MainWindow : Window
{
    Collection<Control> myControls = new Collection<Control>();

    public MainWindow()
    {
        InitializeComponent();
        myControls.Add(textBox2);
    }

    private void textBox2_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            int temp;
            int sum;
            sum = 0;
            foreach (TextBox tb in myControls)
            {
                if (int.TryParse(tb.Text, out temp))
                {
                    sum += temp;
                }
            }
            int test = 0;
            if (int.TryParse(textBox1.Text, out test))
            {
                if (sum < test)
                {
                    TextBox newtb = new TextBox();
                    newtb.Width = ((TextBox)sender).Width;
                    newtb.Height = ((TextBox)sender).Height;
                    newtb.Margin = new Thickness(((TextBox)sender).Margin.Left, ((TextBox)sender).Margin.Top , ((TextBox)sender).Margin.Right , ((TextBox)sender).Margin.Bottom);
                    newtb.HorizontalAlignment = ((TextBox)sender).HorizontalAlignment;
                    newtb.KeyDown += new KeyEventHandler(textBox2_KeyDown);
                    myContainer.Children.Add(newtb);
                    myControls.Add(newtb);
                    newtb.Focus();
                }
                else
                    this.Background = Brushes.LightBlue;
            }
        }
    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Enter)
        {
            textBox2.Focus();
        }
    }
}

A: Pass the collection to the item.  Then in the set add to the collection as necessary.
 public class dynamicInts
 {
     private int dInt;
     private ObservableCollection<DynamicInt> dynamicInts

     public int DInt
     {
         get { return dInt; }
         set
         {
             value = dInt;
             int sumInt;
             foreach (DynamicInt di in dynamicInts) sumInt += di.Dint)
             if (sumInt < 2*dynamicInts) dynamicInts.add(newdynamicInts ...


text:
Q: Iconfont / webfont not showing in iPhone safari browser The glyphs in my iconfont, a custom web font in the navigation in my footer, are not showing when viewed on an iPhone. It is iOS 6.1.4
Any idea why this is happening and how to fix it?
Here is a screenshot of the icons in the footer not appearing:

Here is a link to the page where this is happening

A: The problem is that IOS provides partial support for font-feature-settings CSS property but you can use ligatures in iOS Safari adding text-rendering: optimizeLegibility. The following link (http://clagnut.com/sandbox/opentype/ligatures) shows a text using the font Magenta with Common & Discretionary Ligatures ON and other text with Common & Discretionary Ligatures OFF.
If you access this link from an iOS device you will see that both texts are equal. This means that iOS does not support ligatures only with font-feature-settings and that is why the gyphs in your typography do not work on iOS.
To make it work in iOS, you'll have to add text-rendering: optimizeLegibility to your css. A good reference may be "Tomorrow's web type today: The fine flourish of the ligature". But, you should read "Is it safe to use the CSS rule "text-rendering: optimizelegibility;" on all text?".
You will find an example of your font working in iOS in the following link:
http://jsfiddle.net/poselab/TQjgC/
text-rendering: optimizeLegibility;

A screenshot of this jsfiddle from an iPhone:

A: Delete if((Modernizr.prefixed("fontFeatureSettings")) in noLigatures.js. The icons will show in iOS6.


text:
Q: put empty string instead of null in JSON string I want to put an empty string in my JSON file rather than null value. Is it possible to do quickly with any C# utility or any other way
{
   "typeOfPerson":"",
   "personDetails":{
      "dateOfBirth":"12/20/2019"
   }
}

I have below C# code to get the above JSON:
public class person
    {
    public string typeOfPerson { get; set; }
    public List<PersonDetails> personDetails { get; set; } = new List<PersonDetails>();

}

I have below C# code to get above JSON

public void test()
{
    Person person = new Person();
    person.personDetails = new PersonDetails() { dateOfBirth = "12/20/2019" };

    string JSONresult = JsonConvert.SerializeObject(person);
    string jsonFormatted = JValue.Parse(JSONresult).ToString(Formatting.Indented);
}

above class creates this JSON:
{
   "typeOfPerson":null,
   "personDetails":{
      "dateOfBirth":"12/20/2019"
   }
}

This creates the JSON with null value in typeofperson. Is it possible to get empty string instead of null value? I can always initialize typeofperson="", but I have a huge JSON file and it has lot of empty strings . Any utility that can put ""  instead of null in JSONREsult string.
any help is highly appreciated.

A: public class person {
public string typeOfPerson { get; set; } = "";
public List<PersonDetails> personDetails { get; set; } = new List<PersonDetails>();

}
you can try it like this.


text:
Q: Cannot modify association 'User#tracks' because it goes through more than one other association I created a Playlist association so Users can add a track to a playlist if they chose. That works, the problem is, a user now cannot upload a track the normal way through belongs_to :user
Something in my association broke the relationships and I can't figure out what it is, here's all of the relevent code from my models:
class User < ActiveRecord::Base
require 'soundcloud'
acts_as_voter
belongs_to :gallery
has_many :tracks

has_many :active_relationships, class_name:  "Relationship",
                              foreign_key: "follower_id",
                              dependent:   :destroy

has_many :passive_relationships, class_name:  "Relationship",
                               foreign_key: "followed_id",
                               dependent:   :destroy

has_many :following, through: :active_relationships, source: :followed
has_many :followers, through: :passive_relationships, source: :follower

has_many :playlists
has_many :tracks, through: :playlists
end

--
class Playlist < ActiveRecord::Base
belongs_to :user
has_many :playlist_tracks
has_many :tracks, through: :playlist_tracks
end

--
class PlaylistTrack < ActiveRecord::Base
belongs_to :playlist
belongs_to :track
end

--
class Track < ActiveRecord::Base
acts_as_votable
belongs_to :user

has_many :playlist_tracks

has_many :playlists, through: :playlist_tracks

mount_uploader :track, TrackUploader

validates :title, presence: true
validates :description, presence: true
validates :track, presence: true
validates_length_of :title, :minimum => 2, :too_short => "please enter at least %d character"
validates_length_of :description, :minimum => 10, :too_short => "please enter at least %d characters"

def self.search(query)
# where(:title, query) -> This would return an exact match of the query
where("title || description like ?", "%#{query}%")
end
end

Please let me know if I should clarify anything about the issue, thanks.
EDIT:
ERROR: Cannot modify association 'User#tracks' because it goes through more than one other association.
The error points to the create action in the tracks_controller.rb
class TracksController < ApplicationController
skip_before_filter  :verify_authenticity_token
def show
    @track = Track.find_by(id: params[:id])
end

def new
    @user = User.find(params[:user_id])
    @track = Track.new
end

def create
    @user = current_user
    @track = @user.tracks.create(track_params)

    if @track.save
        redirect_to user_path(current_user)
    else
        redirect_to :back
        flash[:alert] = 'There was an error processing your request'
    end
end

def upvote
  @track = Track.find_by(id: params[:id])
  @track.upvote_by current_user

  render json: @track
end

def unvote
  @track = Track.find_by(id: params[:id])
  @track.unliked_by current_user

  render json: @track
end

 def likes
    @user = User.find_by(id: params[:id])
    @likes = @user.find_voted_items

    render json: @likes
 end

 private

 def track_params
   params.require(:track).permit(:track, :user_id, :title, :description, :artist)
 end

 end

UPDATE: When I remove like 7 in the user model it doesn't give me an error but that track does not save...


text:
Q: How to monitor incoming http requests How can I monitor incoming HTTP requests to port 80? I have set up web hosting on my local machine using DynDNS and Nginx. I wanted to know how many request are made on my server every day.
Currently I'm using this command:
netstat -an | grep 80

A: I've been using tcpflow to check incoming requests at aws instances, maybe there's a way to aggregate requests daywise.
STEP 1 - installation
# yum install --nogpgcheck http://pkgs.repoforge.org/tcpflow/tcpflow-0.21-1.2.el6.rf.x86_64.rpm

STEP 2 - track GET/POST requests at port 80
# tcpflow -p -c -i eth0 port 80 | grep -oE '(GET|POST|HEAD) .* HTTP/1.[01]|Host: .*'

Reference
https://github.com/simsong/tcpflow

A: Do you have log files turned on for your server? If you do, I'd recommend installing AwStats and running your log files with it to get accurate reporting.
If you want to just monitor all incoming/outgoing traffic, you can use WireShark.

A: You may use tcpdump.
# tcpdump filter for HTTP GET
sudo tcpdump -s 0 -A 'tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x47455420'

# tcpdump filter for HTTP POST
sudo tcpdump -s 0 -A 'tcp dst port 80 and (tcp[((tcp[12:1] & 0xf0) >> 2):4] = 0x504f5354)'

For a solution using tshark see:
https://serverfault.com/questions/84750/monitoring-http-traffic-using-tcpdump

A: You can also tail the log file:
tail -f /path/to/access_log

The -f parameter will cause tail to continually update the screen as new entries are written to the log.

A: Run this
while true
do
echo -----`date '+%r'` -----:
netstat -ant | grep :8080 | awk '{print $6}' | sort | uniq -c | sort -n
echo httpd processes: [`ps aux | grep httpd | wc -l`]
echo .
sleep 2
done

It will monitor traffic on 8080 port every 2 seconds


text:
Q: Why am I experiencing an infinite loop here? My code never stops asking for input so I think I must've made an infinite loop, but I can't find where the error is. I've also noticed that when inserting the input line by line, it prints the result of one loop after inserting the first line of the second loop, which seems incorrect to me. Please help me debug. (For further context, the code is supposed to receive a number we'll call n, and then scan 3n more lines, which are basically n bundles of 3 similar lines. The 2nd and 3rd lines are two words with the same num of characters, and the 1st line is that num. The output is whether or not these words are anagrams.)
#include <stdio.h>

int main() {
    int n, l;

    scanf("%d\n", &n);

    for (int i = 1; i <= n; i++) {
        scanf("%d\n", &l);
        char A[l], B[l];

        for (int j = 0; j < l; j++) {
            scanf("%c", &A[j]);
            scanf("\n");
        }
        for (int j = 0; j < l; j++) {
            scanf("%c", &B[j]);
            scanf("\n");
        }

        for (int k = 0; k < l; k++) {
            int result = 0;
            for (int j = 0; j < l; j++) {
                if (A[k] == B[j]) {
                    result = 1;
                }
            }
            if (!result) {
                printf("\nNO\n");
                return 0;
            }
        }

        printf("\nYES\n");
    }
}

Example:
input:
2
6
listen
silent
4
Evil
live

output:
YES
NO

A: It's because you are asking for input over and over and over again,
Not sure what you are trying to achieve, but start by removing the extra scanfs
try this,
#include <stdio.h>

int main() {
    int n, l;

    scanf("%d\n", &n);

    for (int i = 1; i <= n; i++) {
        char A[l], B[l];

        for (int k = 0; k < l; k++) {
            int result = 0;
            for (int j = 0; j < l; j++) {
                if (A[k] == B[j]) {
                    result = 1;
                }
            }
            if (!result) {
                printf("\nNO\n");
                return 0;
            }
        }

        printf("\nYES\n");
    }
}

A: Your scanf calls wait for an extra \n which requires more input to enter.
To fix this, remove the \n from your scanf calls. Also remove the extra calls when you enter  A and B:
I have added some debug code to demonstrate where you are in your program execution while you enter your input.
#include <stdio.h>

int main() {
    int n, l;
    int res;

    res=scanf("%d", &n);

printf ("res=%d, n=%d\n", res, n);

    for (int i = 1; i <= n; i++) {
        res = scanf("%d", &l);

printf ("res=%d, l=%d\n", res, l);

//        char A[l], B[l];
        char A[l+1], B[l+1];

        for (int j = 0; j < l; j++) {
            scanf(" %c", &A[j]);
        }

printf ("A done\n");

        for (int j = 0; j < l; j++) {
            scanf(" %c", &B[j]);
        }

printf ("B done\n");

A[l] = 0; B[l] = 0;
printf ("A=\"%s\" - B=\"%s\"\n", A, B);
...

Now your input should work properly.
But your code also contains another error.
You will treat "12344" and "11234" as correct match wchich is wrong.
To fix this you need to remove each matching character from B:
        for (int k = 0; k < l; k++) {
            int result = 0;

// We compare A[k] with the remaining characters in B only
            for (int j = k; j < l; j++) {
                if (A[k] == B[j]) {
                    result = 1;
                    B[j] = B[k]; // Replace matching character with non-matching character we checked earlier.
                    break;
                }
            }
            if (!result) {
                printf("\nNO\n");
                return 0;
            }
        }

        printf("\nYES\n");

This code stops as soon as the first match is found and removed that character from B.
The entries in B are rearranged to keep the unused entries at the end.
The full code looks like this:
#include <stdio.h>

int main() {
    int n, l;
    int res;

    res=scanf("%d", &n);

printf ("res=%d, n=%d\n", res, n);

    for (int i = 1; i <= n; i++) {
        res = scanf("%d", &l);

printf ("res=%d, l=%d\n", res, l);

//        char A[l], B[l];
        char A[l+1], B[l+1];

        for (int j = 0; j < l; j++) {
            scanf(" %c", &A[j]);
        }

printf ("A done\n");

        for (int j = 0; j < l; j++) {
            scanf(" %c", &B[j]);
        }

printf ("B done\n");

A[l] = 0; B[l] = 0;
printf ("A=\"%s\" - B=\"%s\"\n", A, B);

        for (int k = 0; k < l; k++) {
            int result = 0;
            for (int j = k; j < l; j++) {
                if (A[k] == B[j]) {
                    result = 1;
                    B[j] = B[k];
                    break;
                }
            }
            if (!result) {
                printf("\nNO\n");
                return 0;
            }
        }

        printf("\nYES\n");
    }
}

output:
~/stackoverflow$ ./test
4
res=1, n=4
2
res=1, l=2
12
A done
21
B done
A="12" - B="21"

YES
6
res=1, l=6
liver1
A done
evil1r
B done
A="liver1" - B="evil1r"

YES
3
res=1, l=3
111
A done
111
B done
A="111" - B="111"

YES
4
res=1, l=4
abcd
A done
dcbb
B done
A="abcd" - B="dcbb"

NO


text:
Q: Не отображаются рисунки в JSP (Spring MVC resource mapping) У меня упорно не хотят отображаться рисунки в jsp, хотя в конфигурационном файле прописано

<resources mapping="/resources/**" location="/resources/">

Сервлет прописан вот так
<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

Но все ссылки на /resources/image.jpg не отображают результат
A: Проблема решилась прописыванием абсолютного пути к рисункам. Что-то вроде http://localhost:8080/abc/resources/trava.jpg. Наверное, я где-то затупила... Всем спасибо.
A: Если рисунок отобразился, значит, вы неверно написали путь в первый раз. Как вариант можно попробовать /abc/resources/trava.jpg, т.к. путь абсолютный, а корень localhost


text:
Q: Zend Framework - get front controller from bootstrap? I'm trying to implement routes into my bootstrap file with this code ;
protected function _initRoutes()
{
    $router = $this->getResource('frontController')->getRouter();

    $router->addRoute(
        'profil',
        new Zend_Controller_Router_Route
        (
            'profil/:username',
            array
            (
                'controller' => 'users',
                'action'    => 'profil'
            )
        )
    );
}

but it doesn't work since I get 'Call to a member function getRouter() on a non-object in...' error.
How can I get the controller from bootstrap ?

A: I believe that your problem is that where you are calling
$this->getResource('frontController')->getRouter()

the FrontController resource has not yet been initialized.
I called the same method in this fashion (which won't work in Zend Framework 2.0 but works for now):
Zend_Controller_Front::getInstance()->getRouter();

Alternatively you can make certain that your front controller is initialized like this:
$this->bootstrap('FrontController');

$front =  $this->getResource('FrontController');

A: You could try:
$front  = Zend_Controller_Front::getInstance();
$router = $front->getRouter();

And if you run into any issues these are most likely your culprits:
require_once 'Zend/Controller/Front.php';
require_once 'Zend/Controller/Router/Route.php';


text:
Q: How do I suppress CosmosDB "default" info in resultsets? I want to suppress the CosmosDB information in the following resultset, how can that be done?
 {
            "id": null,
            "_rid": null,
            "_self": null,
            "_ts": 0,
            "_etag": null,
            "topLevelCategory": "Shorts,Skirt"
 },

This is an extract of course but I dont want to show the ID etc as they serve no purpose in this result but I cannot figure out how to suppress that info.
I expect the following
 {
            "topLevelCategory": "Shorts,Skirt"
 },

Query looks as follows
 $"SELECT DISTINCT locales.categories[0] AS topLevelCategory " +
                                                 $"FROM c JOIN locales in c.locales " +
                                                 $"WHERE locales.country = '{apiInputObject.Locale}' " +
                                                 $"AND locales.language = '{apiInputObject.Language}'";

Interesting thing is if I cast the  result as a JOBJECT I dont get the system data, I only get it if I createDOcumentQuery as DOcument, so a workaround would be as follows
IQueryable<JObject> queryResultSet = client.CreateDocumentQuery<JObject>(UriFactory.CreateDocumentCollectionUri(databaseName, databaseCollection), parsedQueryObject.SqlStatement, queryOptions);

but that has other async issues but the above does not show the system generate IDs but the below one does
 var query = client.CreateDocumentQuery<Document>(UriFactory.CreateDocumentCollectionUri(databaseName, databaseCollection), parsedQueryObject.SqlStatement, queryOptions).AsDocumentQuery();
                        var result = await query.ExecuteNextAsync<Document>();

A: These are system-generated properties of items in Cosmos DB.

Surely,you could filter them in the sql: select c.topLevelCategory from c, don't mention them or use select * from c. Filtering  in sql is the best method, better than secondary processing of result set.

Update Answer:
Your situation is executing the exact same query the JOBJECT does not show the system data but the Document does.
My explanation as below:
Document Class is a self-contained base class of Document DB .NET package.It has these generate properties:

SDK will try to map the result data one by one to the entity class which you defined in the CreateDocumentQuery<T>.
So actually,you already find the solution.You could define your custom pojo to receive the result data. Just contain the properties you want in that pojo inside like:
class Pojo : Document
    {
        public string id { get; set; }
        public string name { get; set; }
    }

That would have both business implications and no more redundant fields.Hope i'm clear on this.


text:
Q: get texts from array at indexes where 2D tensor's values are above or equal to thresholds in tensorflow2 I have tensorflow tensor with probabilites like this:
>>> valid_4_preds
array([[0.9817431 , 0.01259811, 0.50729334, 0.00053732, 0.6966804 ,
        0.00488825],
       [0.9851129 , 0.01246135, 0.38177294, 0.00378728, 0.8398497 ,
        0.68413687],
       [0.00061161, 0.00005008, 0.00017785, 0.0000152 , 0.00017121,
        0.00002404],
       [0.9991425 , 0.23962161, 0.98579687, 0.01727398, 0.9354003 ,
        0.3325037 ]], dtype=float32)

I now need to map the above probabilties with different thresholds to classes(or a tensor with texts) and get them.
>>> # printing classes
>>> classes
<tf.Tensor: shape=(6,), dtype=string, numpy=
array([b'class_1', b'class_2', b'class_3', b'class_4', b'class_5',
       b'class_6'], dtype=object)>
>>> # converting to bools
>>> true_falses = tf.math.greater_equal(valid_4_preds, tf.constant([0.5, 0.40, 0.20, 0.80, 0.5, 0.4]))
>>> true_falses
<tf.Tensor: shape=(4, 6), dtype=bool, numpy=
array([[ True, False,  True, False,  True, False],
       [ True, False,  True, False,  True,  True],
       [False, False, False, False, False, False],
       [ True, False,  True, False,  True, False]])>

now, I am trying to get the texts at indices where true_falses has Trues(this is my expected output), like this:
>>> <some-tensorflow-operations>
<tf.Tensor: shape=(4, 6), dtype=bool, numpy=
array([['class_1', 'class_3', 'class_5'],
       ['class_1', 'class_3', 'class_5', 'class_6'],
       [],
       ['class_1', 'class_3', 'class_5']])>

Here's what I have tried:

*

*tf.boolean_mask seems to solve the purpose, but the mask it takes in, strictly has to be 1D array.

*tf.where can be used to get the indexes, output of which after reshaping to single dimension can be passed to tf.gather to get the respective classes like this:

>>> tf.gather(classes, tf.reshape(tf.where(true_falses[0] == True), shape=(-1,)))
<tf.Tensor: shape=(3,), dtype=string, numpy=array([b'class_1', b'class_3', b'class_5'], dtype=object)>

But, I haven't been able to figure out how to do this on 2D arrays.
this logic will go in a signature for serving via tensorflow-serving, so operations strictly only needs to be of tensorflow. How do I do this on 2D tensors or arrays? more efficient and quicker operations would be appreciated.

A: tf.ragged.boolean_mask?
import tensorflow as tf

classes = tf.constant([b'class_1', b'class_2', b'class_3', b'class_4', b'class_5', b'class_6'])
true_falses = tf.constant([
    [ True, False,  True, False,  True, False],
    [ True, False,  True, False,  True,  True],
    [False, False, False, False, False, False],
    [ True, False,  True, False,  True, False]]
)

tf.ragged.boolean_mask(
    data=tf.tile(tf.expand_dims(classes, 0), [tf.shape(true_falses)[0], 1]),
    mask=true_falses
)
# <tf.RaggedTensor [[b'class_1', b'class_3', b'class_5'], [b'class_1', b'class_3', b'class_5', b'class_6'], [], [b'class_1', b'class_3', b'class_5']]>


text:
Q: Linux - How to stop users from moving folders We have a situation where users in a factory are regularly moving folders from a shared samba drive, which in turn causes issues for the software running on the machines
For example, we have a root folder which is shared with all factory pc's
/usr/factory

and within that folder we have
/usr/factory/proc1
/usr/factory/proc2
/usr/factory/proc3
/usr/factory/proc4

And all of those proc folders contain sub-folders with the actual production data required for machines
In some cases, users are "accidentally" clicking and dragging folders away from their expected location. Since the software they use needs to be able to read and write back to the folders, we can't just remove all access. Additionally, since they access multiple folders, mapping directly to the folders isn't preferred either.
Any ideas?

A: In order to change the permissions type: chown -R root:root /usr/factory
where root:root is the argument to give permissions only to the root user.


text:
Q: Output current week number within month PHP I have a PHP script to identify the current month and current week within that month.
For today, it should output 501 (i.e. 5th week of the 1st month), however right now it outputs 101.
Can someone explain why this is the case and how I can resolve? I feel I'm missing something obvious.
<?php
date_default_timezone_set("Europe/London");

function weekOfMonthFunction($date) {
    $firstOfMonth = date("Y-m-01", strtotime($date));
    return intval(date("W", strtotime($date))) - intval(date("W", strtotime($firstOfMonth)));
}

$week = weekOfMonthFunction($date2);
$week = $week + 1;
$month = date("m");
$week_month = $week.$month;

echo $week_month;

A: <?php
date_default_timezone_set("Europe/London");

function weekOfMonth() {
    $now = time();
    $week = date('W', $now);
    $firstWeekOfMonth = date('W', strtotime(date('Y-m-01', $now)));
    return 1 + ($week < $firstWeekOfMonth ? $week : $week - $firstWeekOfMonth);
}

$week = weekOfMonth();
$week_month = $week . date("m");

echo $week_month;

501

Try it online!

A: You've fixed the date to Y-m-01 instead of Y-m-d from the parameter date.
How about this alternative?
function weekOfMonthFunction($date) {
    list($d, $m) = explode('-', date("d-m", strtotime($date)));
    return intval(ceil($d/7).str_pad($m, 1, '0', STR_PAD_LEFT));
}

echo weekOfMonthFunction('2021-01-25'); //Give 401
echo weekOfMonthFunction('2020-01-29'); //Gives 501

Explanation:
Date of month divided by 7 rounded up to get week number prepended to month number with a padded 0