text:
Q: Center of gravity of barplot in R Say you have a vector, and you make a barplot of it in R. How do you calculate the centroid / center of gravity of the barplot?
x<-cumsum(rnorm(50,1,2))
par(mfrow=c(1,2))
plot(x,type="l")
barplot(x)
par(mfrow=c(1,1))

There are plenty of answers on here about the center of gravity of a polygon, but I'm not sure which points I need to get the entire shape of the barplot, and not just the vector with the points (like in the left plot).

A: You can easily compute it using this function
getCentroid <- function(x, width = 1) {
  A  <- x * width                  # area of each bar
  xc <- seq(width/2, length(x), 1) # x coordinates of center of bars
  yc <- x/2                        # y coordinatey

  cx <- sum(xc * A) / sum(A)
  cy <- sum(yc * A) / sum(A)
  return(list(x = cx, y = cy))
}
points(getCentroid(x), col = 'red', pch = 19)

Notes: The default width of each bar is 1. The x coordinate of the centroid of two bars can be computed using the formula

The same applies to the y coordinate. This can be extended to a higher number of bars.

Since we do not have a perfect triangle, there will always be an error if we compare the centroids. Taking bars with the same height difference for example, like
x <- seq(0, 1, length.out = 1000)

(where the first bar has heigth 0) will always yield an error in the x coordinate of 1/6 (2000/3 compared to 666.83333) . The reason is the missing area due to the fact that we have no perfect triangle. This missing area equals 0.5 (Think about the height difference and multiply it by the bar width. Summing this over all bars and dividing it by 2 equals....).

A: Centroid of every bar is in its geometric center, so you can use approach for "A_system_of_particles".
M = Sum(Height[i])        for all i
cx = Sum(Height[i] * i) / M
cy = Sum(Height[i] * Height[i] / 2) / M


text:
Q: What is the intution behind the matrix inverse formula? I am learning about matrix inverses and my professor introduced the formula $\begin{bmatrix}a & b\\c & d\end{bmatrix}^{-1}=$ $ 1\over(ad-bc)$$\begin{bmatrix}d & -b\\-c & a\end{bmatrix}$ $,if\; and \; only \; if \; ad-bc\neq
0$. Can someone give me some intuition as to why this formula works?
I understand the intuition behind using Gauss-Jordan elimination to find the matrix by applying all of the steps of row reduction to the identity matrix, but this formula seems like magic.
Thank you!

A: Inverse of an invertible matrix is given by
$$A^{-1}={\frac {1}{\det(A)}} \mathrm{adj} (A)$$
Clearly, $\det(A) = ad-bc$ and we can find the adjugate matrix by applying transpose on the cofactor matrix of $A$. This results in the formula
$$A ^{-1} = {\frac {1}{ad-bc}} {\begin{bmatrix}\,\,\,d&\!\!-b\\-c&\,a\\\end{bmatrix}}$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to correctly combine xpath conditions I want to select a list of nodes that have class 'product-list-content':
//*[@class='product-list-content']

and contain text 'Sun 14 June':
//*[text()[contains(., 'Sun 14 June')]]

But when I combine those two conditions in a single Xpath expression:
//*[@class='product-list-content' and text()[contains(., 'Sun 14 June')]]

it doesn't work(tested in Chrome).
My question: Those two conditions select correct nodes and applied separately:
Why and operator doesn't work here. How to correctly combine those two conditions to select the nodes I need ?
Example node:
<div class="product-list-content ng-binding">Sun 14 June </div>

A: I made a mistake with @class='product-list-content'. When I replaced it with contains(@class,'product-list-content') it started working.
So the correct xpath is:
//*[contains(@class,'product-list-content') and contains(text(), 'Sun 14 June')]


text:
Q: How to update schema and data for a database deployed on kubernetes? I'm trying to understand how to manage a Postgres database deployed on a Kubernetes cluster.
So far, I can deploy a pod with the Postgres image. I'm also able to create persistent volume and persistent volume claims, but there is something that still I can't understand.
If I have a production database and at some point, I need to patch the database, what is the way to proceed?
Is there a way to execute a SQL instruction to update schema and data?

A: The easiest approach would be to connect to your database via port-forwarding, e.g.:
while true; do kubectl port-forward "$path" -n "$namespace" "$ports"; done

Better stop all downstream Pods that connect to this database. Then do what you need to do with a Postgres client of your choice.
More robustly, introduce a tool like Flyway or Liquibase for schema changes, which would get executed from inside the cluster and allow to version and track your DB changes.


text:
Q: Some part of your SQL statement is nested too deeply I have the following code
[WebGet]
        public Bid GetHighestBidInOpenAuctions(int auctionEventId)
        {
            var auctionEvent = CurrentDataSource.AuctionEvents.Where(x => x.Id == auctionEventId).FirstOrDefault();
            var auctionIds = CurrentDataSource.Auctions.Where(x => x.AuctionEventId == auctionEventId && x.Ends > DateTime.UtcNow).Select(x => x.Id).ToList();

            var bids = CurrentDataSource.Bids.Where(x => auctionIds.Any(t => t == x.AuctionId));

            // If the auction Event has not yet started or there are no bids then show auction with high pre-sale estimate.
            if (bids.Count() == 0 || auctionEvent.Starts > DateTime.UtcNow)
            {
                return null;
            }

            var highestBid = bids.Where(b => b.IsAutobid == false).OrderByDescending(b => b.Amount).FirstOrDefault();

            return highestBid;
        }

This line throws the below exception
if (bids.Count() == 0 || auctionEvent.Starts > DateTime.UtcNow)

Some part of your SQL statement is nested too deeply. Rewrite the query or break it up into smaller queries.

What's wrong?
EDIT
I have tried doing this
IQueryable<Bid> bids = CurrentDataSource.Bids.Where(b => 0 == 1);
            foreach(var auctionId in auctionIds)
            {
                int id = auctionId;
                bids = bids.Union(CurrentDataSource.Bids.Where(b => b.AuctionId == id));
            }

But I still get the same error.

A: Rather than using a subquery, try replacing the bid query with:
var bids = CurrentDataSource.Bids.Where(b => b.AuctionEventId == auctionEventId
                && b.Auction.AuctionEvent.Starts > DateTime.UtcNow
                && b.Auction.Ends > DateTime.UtcNow);

if (bids.Count() == 0
{
    return null;
}

A: It seems when you have too many things in your database then you will get this error (auctionIds in my case) because the generated sql will be too deeply nested.  To solve this I came up with this solution.  If anyone can do better then do.  I'm posting this because someone may have this error in the future and if they do, in the absence of a better solution this might help them.
 [WebGet]
        public Bid GetHighestBidInOpenAuctions(int auctionEventId)
        {
            /*
             * This method contains a hack that was put in under tight time constraints.  The query to
             * get bids for all open auctions used to fail when we had a large number of open auctions.
             * In this implementation we have fixed this by splitting the open auctions into groups of 20
             * and running the query on those 20 auctions and then combining the results.
            */

            const int auctionIdSegmentSize = 20;
            var auctionEvent = CurrentDataSource.AuctionEvents.Where(x => x.Id == auctionEventId).FirstOrDefault();
            var auctionIds = CurrentDataSource.Auctions.Where(x => x.AuctionEventId == auctionEventId && x.Ends > DateTime.UtcNow).Select(x => x.Id).ToList();

            int numberOfSegments = auctionIds.Count/auctionIdSegmentSize;
            if (auctionIds.Count % auctionIdSegmentSize != 0)
                numberOfSegments++;

            var bidsList = new List<IQueryable<Bid>>();
            for (int i = 0; i < numberOfSegments; i++)
            {
                int start = i*auctionIdSegmentSize;
                int end;
                if (i == numberOfSegments - 1)
                {
                    end = auctionIds.Count - 1;
                }
                else
                {
                    end = ((i + 1)*auctionIdSegmentSize) - 1;
                }

                var subList = auctionIds.GetRange(start, (end - start) + 1);
                bidsList.Add(CurrentDataSource.Bids.Where(b => subList.Any(id => id == b.AuctionId)));
            }

            // If the auction Event has not yet started or there are no bids then show auction with high pre-sale estimate.
            if (IsBidsCountZero(bidsList) || auctionEvent.Starts > DateTime.UtcNow)
            {
                return null;
            }

            var highestBid = FindHighestBid(bidsList);

            return highestBid;
        }

        private Bid FindHighestBid(List<IQueryable<Bid>> bidsList)
        {
            var bids = new List<Bid>();
            foreach (var list in bidsList)
            {
                bids.Add(list.Where(b => b.IsAutobid == false).OrderByDescending(b => b.Amount).FirstOrDefault());
            }

            bids.RemoveAll(b => b == null);

            if (bids.Count == 0)
                return null;

            bids.Sort(BidComparison);

            return bids[0];
        }

        private int BidComparison(Bid bid1, Bid bid2)
        {
            if (bid1.Amount < bid2.Amount)
                return 1;
            if (bid1.Amount > bid2.Amount)
                return -1;
            return 0;
        }

        private bool IsBidsCountZero(List<IQueryable<Bid>> bidsList)
        {
            int count = 0;
            foreach (var list in bidsList)
            {
                count += list.Count();
            }

            return count == 0;
        }

A: The problem is with auctionIds.Any(t => t == x.AuctionId) where EF cannot create a correct query. You can change it to:
var bids = CurrentDataSource.Bids.Where(x => auctionIds.Contains(x.AuctionId));

Where EF can convert auctionIds to a collection and pass to DB.


text:
Q: Autowiring a Feign client in my controller when spring launching throws exception I already tried solutions on this and this but no success so maybe I'm missing something else
here is my architecture
I have a ressource micro-service protected by Oauth2 which is implementing my business logic and a client micro-service with a thymleaf template that is consuming this ressource. Using Oauth2RestTemplate is fine now i m trying to use feign.
first here is my ressource project resume
Application.yml
spring.application.name: COMPONENTS

server:
  port: 0

eureka.client.service-url.defaultZone: xxxxxxxxxxxxxxxxxxxxxxxx

security.oauth2.resource.token-info-uri: xxxxxxxxxxxxxxxxxxxxxx
security.oauth2.client.client-id: xxxxxxxxxxxxxx
security.oauth2.client.client-secret: xxxxxxxxxxxxx

spring.jackson.date-format: com.fasterxml.jackson.databind.util.ISO8601DateFormat

spring:
  datasource:
    url: jdbc:mariadb://localhost:3306/pos_auth?createDatabaseIfNotExist=true
    username: root
    password: xxxxxxxx
    driver-class-name: org.mariadb.jdbc.Driver

And a simple Controller
@Controller
@RequestMapping(ApplicationController.API)
public class ApplicationController {

    public static final String API = "applications";

    @Autowired
    private ComponentsService componentsService;

    @GetMapping
    public ResponseEntity<List<Apps>> getApplicationsList() {
        return new ResponseEntity<List<Apps>>(componentsService.getAllApps(), HttpStatus.OK);
    }

}

Now here is My client important part of Feign client implementation
the main class
@SpringBootApplication
@EnableOAuth2Sso
@EnableEurekaClient
@EnableDiscoveryClient
@EnableWebSecurity
public class ClientApplication extends WebSecurityConfigurerAdapter{

    public static void main(String[] args) {
        SpringApplication.run(ClientApplication.class, args);
    }

        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                    .logout()
                    .logoutSuccessUrl("http://localhost:9999/uaa/exit");
            http.authorizeRequests().antMatchers("/graphics/**").permitAll().
                    and().authorizeRequests().anyRequest().authenticated();
        }

    @Bean
    @LoadBalanced
    OAuth2RestTemplate oauth2RestTemplate(OAuth2ClientContext oauth2ClientContext, OAuth2ProtectedResourceDetails details) {
        return new OAuth2RestTemplate(details, oauth2ClientContext);
    }

    @Profile("!cloud")
    @Bean
    RequestDumperFilter requestDumperFilter() {
        return new RequestDumperFilter();
    }

}

A feign configuration
@Configuration
@EnableFeignClients
@ImportAutoConfiguration({RibbonAutoConfiguration.class, FeignRibbonClientAutoConfiguration.class, FeignAutoConfiguration.class})
public class FeignConfig {

}

My desired behaviour in the client controller when index is called
@Controller
public class MessageController {

    @Autowired
    OAuth2RestTemplate restTemplate;

    @Autowired
    private AppClientFeign appClientFeign;

    @RequestMapping("/")
    String home(Model model) {
        model.addAttribute("applications", appClientFeign.getApps());
        System.out.println(appClientFeign.getApps());
        return "index";
    }

}

finally my feign client
@FeignClient("COMPONENTS")
public interface AppClientFeign {
    @RequestMapping(method = RequestMethod.GET, value = "/applications")
    List<App> getApps();
}

while running the  client I m getting the following exception

Field appClientFeign in demo.MessageController required a bean of type
'org.springframework.cloud.netflix.feign.FeignContext' that could not
be found.

*

*Bean method 'feignContext' not loaded because @ConditionalOnClass did not find required class 'feign.Feign'

A: the explanation:
knowing that spring cloud have Feign by default not adding the feign starter dependency will not trigger any compilation time issue (as using javax jpa that should be injected by a starter project Data JPA) in my case I forgot to add the starter to the project pom, spring  search for an implemntation or a comfiguration that he can't found.
the solution
adding the  starter feign dependency
<dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

A: For Spring Boot version above 2.0.0.M4 use
         <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
         </dependency>


text:
Q: R: how to apply a function to some columns into groups of data? I appreciate your help to apply a function to a data frame grouping by some columns. I suppose I have to use some dplyr function or lapply or do.call but I was not able to do that.
I have the following data frame:
dfFull <- data.frame(Cen = c("Cen01", "Cen01", "Cen01", "Cen01",
                             "Cen01", "Cen01", "Cen01", "Cen01",
                             "Cen02", "Cen02", "Cen02", "Cen02",
                             "Cen02", "Cen02", "Cen02", "Cen02"),
                     Model = c("Mod01", "Mod01", "Mod01", "Mod01",
                               "Mod02", "Mod02", "Mod02", "Mod02",
                               "Mod01", "Mod01", "Mod01", "Mod01",
                               "Mod02", "Mod02", "Mod02", "Mod02"),
                     Indiv = c(1,2,3,4,1,2,3,4,1,2,3,4,1,2,3,4),
                     PF = c(1,1,2,2,1,1,2,2,1,1,2,2,1,1,2,2),
                     Obj1 = c(0.0,0.02,0.01,0.03,0.01,
                              0.0,0.02,0.0,0.15,0.03,
                              0.02,0.08,0.1,0.06,0.02,0.09),
                     Obj2 = c(0.8,0.62,0.85,0.7,0.92,
                              0.26,0.85,0.93,0.03,0.84,
                              0.94,0.84,0.05,0.63,0.83,0.92))

I have to call a function (from emoa package):

*

*dominated_hypervolume(matrix_points, refp) that calculates the hypervolume for matrix_point using a pre-defined refp.

*refp is a vector (RP <- c(1.0,1.0)) used for every calculation.

The problem relies on matrix_points:

*

*matrix_points is a matrix that is transposed compared to my data frame.

*I need this hypervolume calculated using Obj1 and Obj2 of all Indiv grouped by Cen, Mod and PF columns.

Using small data, I know dominated_hypervolume will do the work since I would be able to provide the proper data.
I know it is wrong, but I was trying to do something like:
dfFull <- dfFull %>%
  group_by(Cen, Model, PF) %>%
  do.call(HV =dominated_hypervolume(data.matrix(t(dfFull[,5:6]), RP)))

What I expect at the end is the below. HV value is just a example, not the calculated. It is not a problem to repeat the HV value for the lines of the individuals used in its calculation.
Cen     Model   PF   Indiv    Obj1   Obj2    HV
Cen01   Mod01    1     1      0.0    0.8     0.77
Cen01   Mod01    1     2      0.02   0.62    0.77
Cen01   Mod01    2     3      0.01   0.85    0.74
Cen01   Mod01    2     4      0.03   0.70    0.74
Cen01   Mod02    1     1      0.01   0.92    0.81
Cen01   Mod02    1     2      0.0    0.26    0.81
Cen01   Mod02    2     3      0.02   0.85    0.69
Cen01   Mod02    2     4      0.0    0.93    0.69
Cen02   Mod01    1     1      0.15   0.03    0.88
Cen02   Mod01    1     2      0.03   0.84    0.88
Cen02   Mod01    2     3      0.02   0.94    0.86
Cen02   Mod01    2     4      0.08   0.84    0.86
Cen02   Mod02    1     1      0.1    0.05    0.76
Cen02   Mod02    1     2      0.06   0.63    0.76
Cen02   Mod02    2     3      0.02   0.83    0.64
Cen02   Mod02    2     4      0.09   0.92    0.64

Thanks for your help.

A: library(tidyverse)
library(emoa)

RP <- c(1.0,1.0)

dfFull %>%
  nest(-Cen, -Model, -PF) %>%
  mutate(HV = map_dbl(data, ~dominated_hypervolume(t(data.frame(.x$Obj1, .x$Obj2)), RP))) %>%
  unnest()

#      Cen Model PF     HV Indiv Obj1 Obj2
# 1  Cen01 Mod01  1 0.3764     1 0.00 0.80
# 2  Cen01 Mod01  1 0.3764     2 0.02 0.62
# 3  Cen01 Mod01  2 0.2940     3 0.01 0.85
# 4  Cen01 Mod01  2 0.2940     4 0.03 0.70
# 5  Cen01 Mod02  1 0.7400     1 0.01 0.92
# 6  Cen01 Mod02  1 0.7400     2 0.00 0.26
# 7  Cen01 Mod02  2 0.1484     3 0.02 0.85
# 8  Cen01 Mod02  2 0.1484     4 0.00 0.93
# 9  Cen02 Mod01  1 0.8437     1 0.15 0.03
# 10 Cen02 Mod01  1 0.8437     2 0.03 0.84
# 11 Cen02 Mod01  2 0.1508     3 0.02 0.94
# 12 Cen02 Mod01  2 0.1508     4 0.08 0.84
# 13 Cen02 Mod02  1 0.8698     1 0.10 0.05
# 14 Cen02 Mod02  1 0.8698     2 0.06 0.63
# 15 Cen02 Mod02  2 0.1666     3 0.02 0.83
# 16 Cen02 Mod02  2 0.1666     4 0.09 0.92

A: Consider by (object-oriented wrapper of tapply for grouping) to pass grouped subets to run needed defined method, then casted into data.frame():
grpcols <- c("Cen", "Model", "PF")

df_list <- by(dfFull, dfFull[grpcols], function(sub)
  data.frame(Cen = sub$Cen[[1]],
             Model = sub$Model[[1]],
             PF = sub$PF[[1]],
             HV = dominated_hypervolume(t(sub[,5:6]), RP))
  )

And then process the list of data frames:
# BASE PROCESSING
final_df <- do.call(rbind, df_list)
final_df <- with(final_df, final_df[order(Cen, Model, PF),])
row.names(final_df) <- NULL

final_df <- merge(dfFull, final_df[c(grpcols, "HV")], by=c("Cen", "Model", "PF"))
final_df
#      Cen Model PF Indiv Obj1 Obj2     HV
# 1  Cen01 Mod01  1     1 0.00 0.80 0.3764
# 2  Cen01 Mod01  1     2 0.02 0.62 0.3764
# 3  Cen01 Mod01  2     3 0.01 0.85 0.2940
# 4  Cen01 Mod01  2     4 0.03 0.70 0.2940
# 5  Cen01 Mod02  1     1 0.01 0.92 0.7400
# 6  Cen01 Mod02  1     2 0.00 0.26 0.7400
# 7  Cen01 Mod02  2     3 0.02 0.85 0.1484
# 8  Cen01 Mod02  2     4 0.00 0.93 0.1484
# 9  Cen02 Mod01  1     1 0.15 0.03 0.8437
# 10 Cen02 Mod01  1     2 0.03 0.84 0.8437
# 11 Cen02 Mod01  2     3 0.02 0.94 0.1508
# 12 Cen02 Mod01  2     4 0.08 0.84 0.1508
# 13 Cen02 Mod02  1     1 0.10 0.05 0.8698
# 14 Cen02 Mod02  1     2 0.06 0.63 0.8698
# 15 Cen02 Mod02  2     3 0.02 0.83 0.1666
# 16 Cen02 Mod02  2     4 0.09 0.92 0.1666

Or with dplyr handling still using the base::by() output where do.call, order, merge becomes bind_rows, arrange, inner_join respectively:
# DPLYR PROCESSING
attributes(df_list) <- NULL

final_df <- bind_rows(df_list) %>%
  arrange(Cen, Model, PF) %>%
  inner_join(dfFull, by=c("Cen", "Model", "PF"))

final_df
#      Cen Model PF     HV Indiv Obj1 Obj2
# 1  Cen01 Mod01  1 0.3764     1 0.00 0.80
# 2  Cen01 Mod01  1 0.3764     2 0.02 0.62
# 3  Cen01 Mod01  2 0.2940     3 0.01 0.85
# 4  Cen01 Mod01  2 0.2940     4 0.03 0.70
# 5  Cen01 Mod02  1 0.7400     1 0.01 0.92
# 6  Cen01 Mod02  1 0.7400     2 0.00 0.26
# 7  Cen01 Mod02  2 0.1484     3 0.02 0.85
# 8  Cen01 Mod02  2 0.1484     4 0.00 0.93
# 9  Cen02 Mod01  1 0.8437     1 0.15 0.03
# 10 Cen02 Mod01  1 0.8437     2 0.03 0.84
# 11 Cen02 Mod01  2 0.1508     3 0.02 0.94
# 12 Cen02 Mod01  2 0.1508     4 0.08 0.84
# 13 Cen02 Mod02  1 0.8698     1 0.10 0.05
# 14 Cen02 Mod02  1 0.8698     2 0.06 0.63
# 15 Cen02 Mod02  2 0.1666     3 0.02 0.83
# 16 Cen02 Mod02  2 0.1666     4 0.09 0.92


text:
Q: Dynamic variable in $in mongoose I have following variables. (I am using this query in mongoose, node )
var splitDates=currentDate.split('-');//2019-12-09
currentDate=splitDates[0]+splitDates[1]+splitDates[2] //returns 20191209
previousDate= splitDates[0]+splitDates[1]+splitDates[2]-1;

I want it in the mongoDB query:
{ batchRef: { $in: [/20191209/, /20191210/] } }, // this is static values and works.
{ batchRef: { $in: ['/'+previousDate+'/','/'+currentDate+'/'] } }, // this doesnt work!

am I missing something?
any help would be appreciated.

A: This looks like a javascript date transformation question.
You can use the following code to get a string array for a given  date and previous date to be used in $in query.
const inputDateString = "2019-12-09";

const currentDate = new Date(inputDateString);
const previousDate = new Date(inputDateString);
previousDate.setDate(currentDate.getDate() - 1);

let inArray = [];

inArray.push(inputDateString.split("-").join(""));
inArray.push(
  previousDate
    .toISOString()
    .slice(0, 10)
    .split("-")
    .join("")
);

console.log(inArray);

inArray will have these 2 items:
[ '20191209', '20191208' ]

Now we can use this in the query like this:
  { batchRef: { $in: inArray } }

Please not that I assumed that inputDateString is always in this format with 10 characters, like 2019-01-31  or 2019-01-01


text:
Q: Sort highest match in excel How can in Excel sort multiple collumns with data?
Column B = Subscribe date
Column A = Subscribe name
I have multiple columns with a lot of doubles names (A) and different subscribe dates(B)
How can this be sorted that all names are sorted, but the highest subscribe date is flagged as HIGHEST in column C. In this way you can see directly wich is the highest date.

A: Update
Here's a bit of magic using an array formula. This type of formula require you to press Ctrl+Shift+Enter, when entering the formula into a cell (notice the {}-brackets surrounding the formula in the screenshot when doing this). In other words - type in the formula, and the press Ctrl+Shift+Enter instead of just Enter.
Use the following formula in column C to mark the highest dates within a group in column A:
=IF($B2=MAX(IF($A$2:$A$100=$A2;$B$2:$B$100; 0));"HIGHEST";"")

The result being:

Note that the formula only handles the first 100 rows. You can change this easily if needed, though. E.g.:
=IF($B2=MAX(IF($A$2:$A$65000=$A2;$B$2:$B$65000; 0));"HIGHEST";"")

This formula will handle the first 65.000 rows.
Download example file here (download link valid until aug 24 2009).

Original answer
You could put the following formula in the C column:
=IF($B2=MAX($B:$B);"HIGHEST";"")

The result being:

A: Select all the data first (if there's a lot, go the the first cell and press Ctrl-Shift-Down to quickly select the whole list). From the menus choose Data -> Sort. This will give you the option of which column to sort by first (column A in your case) and second (column B).
(EDIT: The instructions below assume that you want the highest date flagged for each unique name. For the highest overall, see Bernhof's answer.)
If you sort this way, then the latest date is just the last one for that particular name. You can show the flag using this formula in C1:
=IF(A1<>A2,"HIGHEST","")

Then just select the cell containing the formula, and use your mouse to drag the small handle (in the bottom right-hand corner of the cell) down to copy the formula do the other cells in column C.


text:
Q: What is the simplest way to implement transparent objects in sharpdx? I am currently trying to implement semi-transparent polygons in sharpdx.
At the moment I am using GraphicsDevice and BasicEffect to draw my objects.
// Setup the vertices
game.GraphicsDevice.SetVertexBuffer(myModel.vertices);
game.GraphicsDevice.SetVertexInputLayout(myModel.inputLayout);

// Apply the basic effect technique and draw the object
basicEffect.CurrentTechnique.Passes[0].Apply();
game.GraphicsDevice.Draw(PrimitiveType.TriangleList, myModel.vertices.ElementCount);

This is working fine for normal objects, however I would like to make some of the objects partially transparent. I've set the alpha value of these object's colors to 50, however they are still being rendered as opaque. What do I need to do to achieve this effect?

A: Transparency in Sharpdx requires alpha blending value 0..1 for float colors. The comment Nico Schertler provided above solved the question and can be regarded as answer.
Without Alpha mode, there are two options, that you can use in the HLSL shader file

*

*In the Pixel shader, use the clip() function, dependent on the input color. You could define your transparent black and not show any black triangles. Like so:
float4 PS( PS_IN input ) : SV_Target
{
  clip(input.color[3] < 0.1f ? -1:1 );
  return input.color;
}
ref: https://learn.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-clip
See the effect:

*

*modify the Vertex Shader to project these vertices to (0,0,0), dependent on the input color. You could define your transparent black and not show any black triangles. Like so:
PS_IN VS( VS_IN input)
   {
    PS_IN output = (PS_IN)0;
    if ((input.color[0]!=0)||(input.color[1]!=0)||(input.color[2]!=0))
    {
      output.position = mul(worldViewProj,input.position);
    }
    output.color = input.color;
    return output;
   }
See below the effect on the edges of my HeightField mesh, on the left is the unchanged version..

NOTE: The latter solution gives sharper edges, but it only works when (0,0,0) is behind the object.


text:
Q: Explicit path in the unitary group of a $C^*$-algebra For $G$ a discrete group, there is a canonical inclusion $g\mapsto u_g$ of $G$ into the unitary group of the reduced $C^*$-algebra $C^*_r(G)$. Denote by $[u_g]$ the class of $u_g$ in the (topological) $K$-theory group $K_1(C^*_r(G))$. It is well-known that, if $g$ is a commutator in $G$, then $[u_g]=0$ in $K_1(C^*_r(G))$: indeed the $2\times 2$ matrix $u_g\oplus 1$ is connected to the identity in the unitary group of $M_2(C^*_r(G))$.
Now, let $G$ be the free group on two generators $a,b$, and let $g$ be the commutator of $a$ and $b$. I recently bumped into this nice paper by Haagerup, Dykema and Rordam:
http://arxiv.org/pdf/funct-an/9608001.pdf
At the top of page 3, they mention as a consequence of their main result, that $u_g$ is connected to $1$ already in the unitary group of $C^*_r(G)$. Partly out of curiosity, I was wondering whether an explicit path of unitaries between $u_g$ and $1$ had been written down somewhere.

A: Here are some thoughts about a construction of an explicit path. Unfortunately, I could not carry it over, so take it as a long comment. I'd be glad if somebody is able to complete it, or maybe to get some useful hint!
Any skew-symmetric unitary element $J$ of a $C^*$  algebra $A$  can be connected to the identity in the unitary group of $A$ by the path $\exp(tJ)=\cos(t)I+\sin(t)J$, for $0\le t\le \pi/4$. This suggests to consider a factorization of $U:=u_g$ as a product of two  skew-symmetric unitary operators $J$ and $K$ on $\ell_2(G) $ (this can be done in many ways, indeed):
$$J\in B(\ell_2(G)),\quad K\in B(\ell_2(G))\, ,$$
$$J^*=J^{-1}=-J,\quad K^*=K^{-1}=-K\, ,$$
$$U=JK\,\quad  (\,\mathit{so\, that}\quad K=-JU)\, .$$
Then $u(t):=\exp(tJ)\exp(tK)=\cos(t)^2I+\sin(t)\cos(t)J(I-U)+\sin(t)^2U$ for $0\le t\le \pi/4$ is a path in the unitary group of $B(\ell_2(G))$ connecting $I$ to $U$. So, if we can choose the above factorization in such a way that we also have $J(I-U)\in C^*_{\mathrm {r}}(G)$, the whole path $u(t)$ would be in the reduced algebra for all $t$. Of course, $J \in C^*_{\mathrm {r}}(G)$ would do it, but this doesn't quite seem to be needed, as $I-U$ is not invertible.
I've thus tried the simplest Ansatz for $J$, namely $Jf(x):=\alpha(x)f(\sigma(x))$, for all $f\in \ell_2(G)$ and $x\in G$, with  a convenient $\alpha\in\ell_\infty(G)$ and a  $\sigma:G\to G$ bijective. However, it seems the last requirement, $J(I-U)\in C^*_{\mathrm {r}}(G)$ can't be fulfilled in this case. A slightly more general form, $Jf(x):=\alpha(x)f(\sigma(x))+\beta(x)f(\tau(x))$ seems more promising (yet there could be some good reason why the whole approach is hopeless, though).


text:
Q: Can't authenticate user using React and Spring Security i am trying to login to my app via front written in React. The method which is responsible for form login. Button invoke this method:
handleSubmit = event => {
        event.preventDefault();
        PostData('perform_login', this.state).then((result) => {
          let responseJSON = result;
      console.log(responseJSON);
    });
  }

And this is a Data with username and password
export function PostData(type, userData) {

  let BaseUrl = 'http://localhost:8080/';

  return new Promise((resolve, reject) => {
    fetch(BaseUrl + type, {
      method: 'POST',
      body: JSON.stringify(userData)
    })
    .then((response) => response.json())
    .then((responseJson) => {
      resolve(responseJson);
    })
    .catch((error) => {
      reject(error);
    });
  });
}

I am trying to log in to backend, spring config looks like that:
@Override
  protected void configure(final HttpSecurity http) throws Exception {
    http
          .cors()
        .and()
          .csrf().disable()
          .exceptionHandling().authenticationEntryPoint(restAuthenticationEntryPoint)
        .and()
          .authorizeRequests()
          .antMatchers("/login*", "/success*").anonymous()
          .antMatchers("/auth/**", "/signup/**", "/css/*", "/webjars/**","/js/*","/image/*").permitAll()
          .anyRequest().authenticated()
        .and()
          .formLogin()
          .successHandler(mySuccessHandler)
          .failureHandler(myFailureHandler)
          .loginProcessingUrl("perform_login")
          .usernameParameter("username")
          .passwordParameter("password")
          .successForwardUrl("/tasks")
        .and()
          .logout()
          .logoutUrl("/logout")
          .logoutSuccessUrl("/logout-success").permitAll()
        .and()
          .apply(new SpringSocialConfigurer());
  }

Important line in this file i think is the loginProcessingUrl("perform_login") which i used to verify my username and password from react.
While i do something like that in CURL is working fine:
curl -i -X POST -d username=admin -d password=admin http://localhost:8080/perform_login

But if i want authenticate by Postman or React it doesn't work, please about help/hints
Regards


text:
Q: Xcode4 corruption of nib files I have a rather strange problem that I can't quite get to the bottom of just yet, and I want to document it here because I haven't seen this problem discussed anywhere else.
I have a iPhone app that I was developing under Xcode3. This was working perfectly and I had done some ad-hoc distribution that also worked perfectly on devices.
Then I upgraded to Xcode4 and the next time I did an ad-hoc distribution my app crashed on startup. Needless to say that it worked in the simulator and in devices hooked up to my development machine. The crash logs were none too helpful, they indicated a crash in main.m, in the standard call to UIApplication. I, of course, had never changed that file. After much digging and piecing together I discovered the problem.
Xcode thought that the file type of my *.xib files was text.xml instead of file.xib and so was only copying these files to the app bundle instead of compiling them. The app was then crashing on startup because it couldn't find the MainWindow.nib file.
By tracing back through my subversion checkins I found that the file types, as recorded in the project.pbxproj file within xcodeproj, changed in the first checkin after the Xcode4 upgrade. I have no idea as to how or why that happened. Nor I can see through the UI how I would influence that setting and I didn't even open some of the xib's that changed. (To fix my problem I modified the pbxproj file in a text editor).
So, does any-one have any insight as to how or why this could have happened?

A: I'm running into the same problem with my existing xcode3 projects that I have migrated to xcode4.
I tried @jaylinn's solution, but I too found the file already had lastKnownReference.
I have been able to resolve this by deleting the .xib files from the project (Remove Reference Only) and then re-adding them to the project.  It's a bit of a pain, but it works.
Hope that helps.
-Mike

A: Here's what fixed it for us. The XIB was identified as an "explictFileType" which does not appear to be recognized in Xcode 4.
Look for a line like this in your project file (open with a text editor) ...
C9B10BEA11D9084800F10866 /* Record.xib */ = {isa = PBXFileReference; explicitFileType = file.xib; path = Record.xib; sourceTree = ""; };
And change it to this ...
C9B10BEA11D9084800F10866 /* Record.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = Record.xib; sourceTree = ""; };


text:
Q: Typescript Angular 2 How do I return JSON data from a service to a component? I'm getting an error Type 'void' is not assignable to type 'Image[]' for the following code.
How do I return the json data in image.service.ts so that  app.component.ts is getting an array of Image[] types?
app.component.ts
  images: Image[];

  getImages() {
     this.images = this._imageService.getImageData();
   }

image.service.ts
  getImageData() {
    this._http.get('app/test.json').subscribe(res => {
      return res.json();
    })
  }

app/test.json
[{"id":"1","imageid":"1","imageurl":"http://imageur"}]

A: Normally, we subscribe() to the Observable returned by http.get() like in this answer.  An alternative is to return an empty array, and then push items onto that array when the data comes back from the (web) server.  Be sure to not assign this.images to a new array, otherwise the component will still be referencing the original empty array.
image.service.ts
export class ImageService {
   images = [];
   getImageData() {
       this._http.get('app/test.json').subscribe(res => {
         this.images.push(...res.json());
         // don't do this:   this.images = res.json()
       });
       return this.images;
   }
}

Plunker
Note that ... is an ES2015 feature.


text:
Q: How could we execute a program with "dynamic arguments" (loop) ? DYNAMIC ARG CONSTRUCTOR IN SHELL How could we execute a program with "dynamic arguments" (loop) ?
I would like to add an argument as per user interest/input. I can do it by several if conditions, But it is not practical. Arg1, Arg3, and Arg4 might be needed for a program (eg: docker run ) but Arg2 and Arg5 are not.
For example:
docker run -d --name $CONTAINER_NAME \
               --hostname $MY_PROFILE \  ## if $hostname_req=1
               --user $USER \
               -v $MYAPP_DL:/home/$USER/Downloads \  ## if $dwnldfolder_req=1
               --net-alias=${MY_NEW_DNS_NAME} \   ## if $dns_req=1
               --label "appname=$MYAPP" \  ## if $label_req=1
               --label "profile=$DOMAIN_CODE" \
               --label "purpose=$PURPOSE" \
               --label "maintainer=$DEV_ID" \
               $DOCKER_IMAGE_TAG

We can use function and loop but how will substitute to Program ( docker run ) arguments?
    ## NOT ACTUAL CODE :: ILLUSTRATING PLAN1

    if [$label_req==1]
    argument_aray+=('--label "appname=$MYAPP"')
    if [$dns_req==1]
    argument_aray+=('-net-alias=${MY_NEW_DNS_NAME} ')
    ...
    ...
    if [$hostname_req==1]
    argument_aray+=('-hostname $MY_PROFILE')

    docker run <<argument_aray>>

I couldn't find any dynamic argument constructor for the shell. Please suggest if anyone has any idea how can achieve this


text:
Q: What defines 'partial' coverage in Intellij code coverage tests? I am running Java unit tests with code coverage in IntelliJ IDEA with 'tracing' (using the default Intellij coverage tool)). I have one if-statement that always reports 'partial coverage' even though both branches are used:

Other if-statements are green where both paths are tested, and I've tried extracting a variable with the result of the method call. Can anyone explain why line this is reported as partial instead of complete?

A: Partial coverage would occur, if you have compound conditions and not all of the terms are executed. e.g.
if (isEmptyString(location) && isEmptyString(name)) {
    return false;
}

If isEmptyString(location) returns false in all test cases, isEmptyString(name) is never executed. Hence "partial coverage".
This is not the case in your code, therefore I would suppose that this is a bug in the coverage tool.


text:
Q: How do I use HttpBuilder with a partial path in the URL? In my Grails app, I have a config property which includes a partial URL path, like this:
http://apis.mycompany.com/my-api/v1/
I want to invoke endpoints using this URL with HttpBuilder:
class MyApiService {
    @Value('${myApiUrl}')
    String myApiUrl

    def http

    @PostConstruct()
    init() {
        http = HttpBuilder.configure {
            request.uri = myApiUrl
        }
    }

    def getData() {
        http.get() {
            // This doesn't work!!
            request.uri.path = 'resource/data'
        }
    }
}

The request.uri.path erases the existing path segment:
java.lang.RuntimeException: java.net.URISyntaxException: Relative path in absolute URI: http://apis.mycompany.comresource/data

I was able to work around this:
request.raw = "${myApiUrl}resource/data"

...but I can't get Ersatz to work with raw in my Spock test:
def setup() {
    ersatz = new ErsatzServer()
    service.myApiUrl = ersatz.httpUrl + '/'
}

void "getData() - should call the endpoint"() {
    given:
    def jsonData = '[{"person": "Someone"}]'

    ersatz.expectations {
        get("/resource/data") {
            called 1
            responder {
                content jsonData, 'application/json;chartset=UTF-8'
            }
        }
    }

    when:
    def result = service.getData()

    then:
    result == jsonData
}

The URL being assigned to raw is: http://localhost:-1/resources/data
This results in an exception:
java.lang.IllegalArgumentException: protocol = http host = null

    at sun.net.spi.DefaultProxySelector.select(DefaultProxySelector.java:176)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1132)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1032)
    at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:966)
    at groovyx.net.http.JavaHttpBuilder$Action.lambda$execute$2(JavaHttpBuilder.java:147)
    at groovyx.net.http.JavaHttpBuilder$ThreadLocalAuth.with(JavaHttpBuilder.java:331)
    at groovyx.net.http.JavaHttpBuilder$Action.execute(JavaHttpBuilder.java:122)
    at groovyx.net.http.JavaHttpBuilder.createAndExecute(JavaHttpBuilder.java:374)
    at groovyx.net.http.JavaHttpBuilder.doGet(JavaHttpBuilder.java:381)
    at groovyx.net.http.HttpObjectConfigImpl.nullInterceptor(HttpObjectConfigImpl.java:47)
    at groovyx.net.http.HttpBuilder.get(HttpBuilder.java:346)
    at groovyx.net.http.HttpBuilder.get(HttpBuilder.java:1297)
    at com.mycompany.MyApiService.getData(...)
    at com.mycompany.MyApiServiceSpec.getData(...)

Is this a bug in HttpBuilder, or am I doing it wrong? Help appreciated!
Update:
I thought Ersatz would start when constructed, but it turns out I was wrong. Calling start() before using the URL fixed the -1 port number:
def setup() {
    ersatz = new ErsatzServer()
    ersatz.start()
    service.myApiUrl = ersatz.httpUrl + '/'
}

Now, the builder is getting a seemingly valid URL:
http://localhost:52180/resources/data
...but the Ersatz server gives a message that the expectation is not matched.
java.lang.AssertionError: Expectations for Expectations (ErsatzRequest): <GET>, "/resources/data" were not met.. Expression: (com.stehno.ersatz.impl.ErsatzRequest -> com.stehno.ersatz.impl.ErsatzRequest) r.verify()

    at com.stehno.ersatz.impl.ExpectationsImpl.verify_closure2(ExpectationsImpl.groovy:365)
    at com.stehno.ersatz.impl.ExpectationsImpl.verify(ExpectationsImpl.groovy:364)
    at com.stehno.ersatz.ErsatzServer.verify(ErsatzServer.groovy:522)
    at com.mycompany.MyApiServiceSpec.cleanup(...)

The Ersatz docs indicate that the unmatched request should be printed out, but it only prints the above stack trace (and an HttpNotFoundException).

A: For me it works to just append the path instead of assigning it:
request.uri.path += 'resource/data'


text:
Q: How to route an IP Whitelist to one VM and all other to a second VM on proxmox? Is it possible on linux to have a whitelist of IP's that are allowed to reach a specific VM on the internal NAT? eg (public ip (proxmox) --> My VM for whitelisted IP's (192.168.0.1)), and if the traffic is not on the whitelist just route it to 192.168.0.2 ?
The problem is that a certain service is suffering from attacks, so I want users to register on a website before they can connect to the real deal. (and if anyone tries, they will connect to a dummy server on 192.168.0.2 which will catch all the attacks and display a message for users they need to register before connecting)
(if anyone needs visualization to make it easier, because maybe my storywriting skills aren't that good, here is a link: http://i.imgur.com/BCCkhmm.png)

Additional question: Is it somehow possible for packets with a certain signature (for example QUERY packets) to be always allowed for any ip, even non whitelisted (redirect this traffic where whitelisted traffic goes)?

A: You can selectively DNAT based on source IP address.
for example:
ipset destroy whitelist # this may error the first time
ipset create whitelist hash:ip hashsize 32768
ipset -A whitelist <ip_address1>
ipset -A whitelist <ip_address2>
iptables -t nat -A PREROUTING -p tcp --dport 80 -m set --match-set whitelist -j DNAT --to 192.168.0.1
iptables -t nat -A PREROUTING -p tcp --dport 80 -m set ! --match-set whitelist -j DNAT --to 192.168.0.2

You may still need other rules for -t filter -A FORWARD to allow the connections across, and ip_forward needs to be enabled, which it should already be on proxmox.


text:
Q: Shuffling Songs from Multiple Playlists on iPhone I'd like to play songs from multiple playlists on my iPhone and iCloud. I use iTunes Match which clearly introduces some limitations.
The closest I've come is to create a Smart Playlist, with the rules stating to include songs from specified other playlists.
However, since iCloud does not sync smart playlists that reference other playlists, it does not make it to my iPhone. I can only listen to it from iTunes on my Mac.
Is there any other route to achieving this, without manually sweeping the songs whenever I make a change to one of the referenced playlists?

A: Since I got the Tumbleweed badge for this, I'll respond with what I did.

*

*Cleared all the star ratings from my entire music library.

*In each of my "genre" playlists, assigned every song a rating of 5-stars

*Created a smart playlist that includes every song with 5 stars. This playlist will sync over iCloud to my iDevices for listening.

*Created a second smart playlist that lists every song in my "genre" playlists that doesn't have 5 stars. This playlist is for maintenance and is only available on my Mac.

This works as long as I do the following:

*

*Continue adding songs that I like to my "genre" playlists.

*Every once in a while, check the second smart playlist, and give a 5-star rating to any songs in it. It will then be empty, and the songs will automatically be added to my listening playlist.


text:
Q: remove_filter( 'the_content', 'wpautop' ); only for certain post types I want to try and remove automatic <p> tag and <br> tag addition for my custom post type.
It looks like
remove_filter( 'the_content', 'wpautop' );

will do this, but how would I make the change only for my chosen post type I've tried writing a function for this, but it doesn't seem to work:
function remove_tags() {
    global $post_type;

    if ( 'client' == $post_type ) {
        remove_filter( 'the_content', 'wpautop' );
    }
}

A: remove_filter('the_content','wpautop');

//decide when you want to apply the auto paragraph

add_filter('the_content','my_custom_formatting');

function my_custom_formatting($content){
if(get_post_type()=='my_custom_post') //if it does not work, you may want to pass the current post object to get_post_type
    return $content;//no autop
else
 return wpautop($content);
}

found this code on stackoverflow - looks to do the trick.

A: Hook into the_content before the wpautop filter has been called, check the post type, and remove the wpautop filter, which is added in wp-includes/default-filters.php with the default priority 10:
add_filter( 'the_content', 'wpse_82860_remove_autop_for_posttype', 0 );

function wpse_82860_remove_autop_for_posttype( $content )
{
    # edit the post type here
    'post' === get_post_type() && remove_filter( 'the_content', 'wpautop' );
    return $content;
}


text:
Q: Relationship between $\theta$ functions and number fields. I'm trying to have a clear picture of the relationship of theta functions and $L$-functions, and the geometric objects they relate to.
Firstly, I know that $\theta$-functions arise as sections of line bundles on abelian varieties. So if you take a lattice $\Lambda$ in $V=\mathbb{C}^g$ and a polarization $H$ (i.e a hermitian form on $V$ such that $E=Im(H)$ is definite positive and integral on $\Lambda$) you get an abelian variety $X=V/\Lambda$ and a class of line bundles $L(H, \bullet)$. If you specify a quasi-character of $H$, then you get a well definied line bundle $L$ on $X$ whose 1st chern class is $E$. So far this is clear.
From the data of $\Lambda$ alone, you get a family of $\theta$ functions, which correspond to all sections of all the line bundles on $X$. Basically $\theta$-functions are paramterized by a lattice, a polarization and a quasi-character. You can also parametrize them by an element in the Siegel half space, a polarization and a quasi-character.
Now on the other hand $L$-functions arise as Mellin Transform of $\theta$-functions (up to Euler/Gamma-factors). For instance the Riemann Zeta function satsifies $$\pi^{-s/2}\Gamma(s/2)\zeta(s)=Mel(\theta(it)-1, s)$$
with $\theta(z)=\sum_{m\in \mathbb{Z}}e^{i\pi m^2z}$ the Jacobi theta function.
Of course the term $it$ in $Mel(\theta(it)-1, s)$ makes me think that $it$ lives in $\mathbb{H}$ the upper half plane, but I don't think that should be relevant because the variable $t$ is the one integrated in the Mellin transform so it's not a fixed parameter that I could interpret as corresponding to some lattice.
So my (rather blurry) question is : what is the relationship between the "abelian variety" picture of theta functions, and the zeta functions of number field arrising as Mellin transforms of the same $\theta$-functions.
The naive picture I have in mind (which is probably not true) is the following.
If you take $k$ a number field, its ring of integer gives you via the canonnical embedding a lattice $\Lambda$ in some vector space $\mathbb{C}^g$ (obvisouly there are some problems already, as the dimension of $\mathbb{R}^{s+t}$ has no reason to be even in general). The abelian variety $X=\mathbb{C}^g/\Lambda$ has a polarization (coming from the trace on the number field ?) and thus a line bundle, unique up to translation which has a section defined by a $\theta$ function, such that $\zeta_k$ is essentially the Mellin transform of that $\theta$-function.
Now what is wrong with that picture? How far is it from what actually happens? And what is the real picture?
I've seen $\theta$-functions in the context of $L$-functions, parametrized by all sorts of parameters, e.g Neukirch writes $$\theta_\Gamma(a,b,z)=\sum_{g\in \Gamma}N(a+g)e^{i\pi((a+g)z, a+g)+2i\pi(b,g)}$$
in this case can I interpret $\theta_\Gamma(a,b,z)$ as a section on some line bundle on $\mathbb{C}^d/\Gamma$ ?
I feel like those $(a,b)$ should be some $(H,\alpha)$ for some "natural" $(H,\alpha)$, am I completely mistaken here?


text:
Q: How can I change/add params on a store On a sencha-touch, here's is my store declaration
Ext.regStore('newsStore',  {
    model: 'News',
    autoLoad: true,
    proxy: {
        type: 'ajax',
        url: '../news/list.form?format=json',
        reader: {
            type: 'json',
            root: ''
        }
    },
});

How can I modify params? I tried
params:{ format: 'json'}

But its doesn't work!

A: For dynamically setting extra parameters:
If you want to set single parameter at a time, you can use following
var proxy= myStore.getProxy();
proxy.setExtraParam('param1', 'value 1' );
proxy.setExtraParam('param2' , 'value 2' );
myStore.load();

If you want to set multiple parameters at a time, you can use following
proxy.setExtraParams({
     'param1':'value 1',
     'param2':'value 2'
});

A: You could try using extraParams:
Ext.regStore('newsStore',  {
    model: 'News',
    autoLoad: true,
    proxy: {
        type: 'ajax',
        url: '../news/list.form',
        reader: {
            type: 'json',
            root: ''
        },
        extraParams: {
            format: 'json'
        }
    },
});

A: Store declaration
new Ext.data.Store({
model:'prj.models.ContactInfo',
storeId:'contactInfoId',
proxy:{
    type:'ajax',
    url:'/GetContactInfoByID',
    reader:{
        type:'json'
    },
    extraParams:{
        format:'json'
    },
    listeners:{
        exception:function(proxy, response, orientation){
            console.error('Failure Notification', response.responseText);
            Ext.Msg.alert('Loading failed', response.statusText);
        }
    }
}
});

Adding params to proxy and read ajax store
prj.stores.contactInfoId.getProxy().extraParams.partyID = options.partyID;
prj.stores.contactInfoId.getProxy().extraParams.eventName = options.eventName;
prj.stores.contactInfoId.read();

Hope this helps.

A: I suggest you a more elegant solution, the Sencha way to do that:
//Take your store
var store = Ext.StoreMgr.get('YOUR_STORE_ID');

//Apply the params
Ext.apply(store.getProxy().extraParams, {
    partyID: options.partyID,
    eventName: options.eventName
});

//Reload your store
store.contactInfoId.read();

Hope this helps.


text:
Q: ANTLR: Lexer RULE does not match I want to match the following text:
test.define_shared_constant(:testConst, "12", false)
With this grammar it matches correctly:
grammar test;

statement: shared_constant_defioniton | method_call;
KEY: ':' ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'?'|'!'|'|'|'-'|'()')+;
expr: STRING;
STRING: '"' (~'"')* ('"' | NEWLINE) | '\'' (~'\'')* ('\'' | NEWLINE);
NEWLINE: '\r'? '\n' | '\r';
BOOLEAN: 'true' | 'false';
ID: ('a'..'z'|'A'..'Z'|'!') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'!'|'?')*;
WS : [ \t\n\r]+ -> channel(HIDDEN);
DEF_SHARED_CONSTANT: 'define_shared_constant';

shared_constant_defioniton
  : ID('.define_shared_constant' '(' KEY ',' expr ',' (BOOLEAN) ')')
;

method_call
  : ID '.' ID? '('expr*(',' expr)*')'
;

With this grammar it does not match. It matches to method_call which is not even correct.
 shared_constant_defioniton
  : ID('.' DEF_SHARED_CONSTANT '(' KEY ',' expr ',' (BOOLEAN) ')')
;

It is interpreting 'define_shared_constant' as ID. So I have to specify that ID should not contain 'define_'. But how can I do that?

A: ID: ('a'..'z'|'A'..'Z'|'!') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'!'|'?')*;
WS : [ \t\n\r]+ -> channel(HIDDEN);
DEF_SHARED_CONSTANT: 'define_shared_constant';

Here both ID and DEF_SHARED_CONSTANT could match the input define_shared_constant. In cases like this where multiple rules could match and would produce a match of the same length, the rule that's defined first wins. So defined_shared_constant is recognized as an ID token because ID is defined first.
To get the behaviour you want, you should move the definition of DEF_SHARED_CONSTANT before the definition of ID. If you don't define a named lexer rule for it at all and instead use 'define_shared_constant' directly in the parser rule, that also works because implicitly defined lexer rules act as if they had been defined at the beginning of the file.

A: This worked according to ANTLR specification. But running it as an IntelliJ Language plugin did not. I had use a predicated and the final solution looks like this:
ID: { getText().indexOf("define") == 0}? ('a'..'z'|'A'..'Z'|'!') ('a'..'z'|'A'..'Z'|'0'..'9'|'_'|'!'|'?')*;


text:
Q: Efficiently compute Minkowski sum of a 2D Region and a Disc of radius r? Given a 2D Mathematica Region, e.g. A = Region[RegionDifference[Disk[{0, 0}, 2], Disk[{2, 0}, 1]]], how can I grow the region by an arbitrary radius r?
For example, automatically compute the region outlined in black for r = 1/2 in
Show[A, Graphics[{Circle[{0, 0}, 2.5, {.55, 5.8}],
   Circle[{2, 0}, .5, {1.72, 4.5}],
   Circle[{1.75, .98}, .5, {5, 7}],
   Circle[{1.75, -.98}, .5, {5.9, 7.55}],
   Red, Point[{1.73, .98}]}]]

In CGAL, the operation of computing the Minkowski sum P⊕Br of a polygon P with a disc Br of radius r centered at the origin is widely known as offsetting the polygon P by a radius r.
A typical example is
 or .
I'd like to end with a Region because of the many built-in functions that Mathematica provides. This is similar to Dilation of a BinaryImage, but for my purposes a Region is better than a BinaryImage. This post suggested trying Clipper, but I'd like to remain in Mathematica.

A: OP and reply the comment.
reg1 = Disk[{0, 0}, 1/2];
reg2 =
 ImplicitRegion[u^2 + v^2 <= 4 && 3 + u^2 + v^2 >= 4 u, {u, v}];
 sol =
  Resolve[Exists[{x, y, u, v},
   Element[{x, y}, reg1] &&
    Element[{u, v}, reg2], (p == x + u && q == y + v)],
  Reals]; RegionPlot[List @@ sol, {p, -4, 4}, {q, -4, 4},
 PlotPoints -> 80, BoundaryStyle -> Red]

reg1 = Disk[{0, 0}, {3, 2}];
reg2 =
 ImplicitRegion[u^2 + v^2 <= 4 && 3 + u^2 + v^2 >= 4 u, {u, v}];
sol =
  Resolve[Exists[{x, y, u, v},
   Element[{x, y}, reg1] &&
    Element[{u, v}, reg2], (p == x + u && q == y + v)], Reals];
RegionPlot[List @@ sol, {p, -8, 8}, {q, -8, 8}, PlotPoints -> 80,
 BoundaryStyle -> Red]

Edit
For two  simple regions some times it work. (for example elliptical disk and rectangle)
reg = ParametricRegion[{{x, y} + {u, v}, {x, y} ∈
      Disk[{0, 0}, {3, 2}] && Abs[u] + Abs[v] <= 1}, {x, y, u, v}];
RegionPlot[DiscretizeRegion[reg], BoundaryStyle -> Green,
 PlotStyle -> Gray, Frame -> False, AspectRatio -> Automatic]

reg1 = Disk[{0, 0}, {3, 2}];
reg2 = ImplicitRegion[Abs[u] + Abs[v] <= 1, {u, v}];
sol = Resolve[
  Exists[{x, y, u, v},
   Element[{x, y}, reg1] &&
    Element[{u, v}, reg2], (p == x + u && q == y + v)], Reals]
RegionPlot[List @@ sol // Evaluate, {p, -4, 4}, {q, -4, 4}]

Original
A simple example.
ParametricRegion[{{x, y} + {u, v},
   x^2 + y^2 <= 1 && Abs[u] + Abs[v] <= 1}, {x, y, u, v}] // Region

Or
reg = ImplicitRegion[
   x^2 + y^2 <= 1 && Abs[u] + Abs[v] <= 1, {x, y, u, v}];
sol = Resolve[
  Exists[{x, y, u, v},
   Element[{x, y, u, v}, reg], (p == x + u && q == y + v)], Reals]
RegionPlot[List @@ sol // Evaluate, {p, -2, 2}, {q, -2, 2}]

For simple region, we can also use
reg = Circle[{0, 0}, 3];
d = SignedRegionDistance[reg, {x, y}];
Show[RegionPlot[d <= 1, {x, -4, 4}, {y, -4, 4}], Graphics[reg]]

A: One approach is to decompose your region into a collection of convex regions, find the Minkowski sum of each, then union the result.
The Minkowski sum of two convex polygonal regions is a call to ConvexHullMesh after replacing each vertex of one region with all offset vertices of the other.
A = BoundaryDiscretizeRegion[RegionDifference[Disk[{0, 0}, 2], Disk[{2, 0}, 1]]];
cpts = CirclePoints[0.5, 100];

decompcoords = PolygonCoordinates /@ PolygonDecomposition[A, "Convex"];

offsetcoords = Table[Join @@ Outer[Plus, dc, cpts, 1], {dc, decompcoords}];

RegionUnion @@ ConvexHullMesh /@ offsetcoords

A: Minkovski sum is not substantial here. In fact, the $\frac 1 2$-neighborhood of RegionDifference[Disk[{0, 0}, 2], Disk[{2, 0}, 1]] is required. Following the documentation, this can be done as follows. First, we define
d = RegionDistance[DiscretizeRegion[RegionDifference[Disk[{0, 0}, 2], Disk[{2, 0}, 1]]], {x, y}];

The above does not work without DiscretizeRegion for me.
Then,
RegionPlot[d <= 1/2, {x, -3, 3}, {y, -3, 3}]

Addition. I'd like to explain why the similar approaches from that  post do not work here.
We start from
RegionMember[RegionDifference[Disk[{0, 0}, 2], Disk[{2, 0}, 1]], {x, y}]

(x | y) \[Element] Reals && x^2 + y^2 <= 4 && 3 + x^2 + y^2 > 4 x

Next,
r = 1/2; ms = Resolve[Exists[{x, y, s, t}, a == x + s && b == y + t &&
x^2 + y^2 <= 4 &&  3 + x^2 + y^2 > 4 x && (s - x)^2 + (t - y)^2 <= r^2], Reals];
LeafCount[ms]

99435

We see ms is too complicated and big  to work with. This also explains the necessity of DiscretizeRegion in the above.


text:
Q: posting XML request in java How do I post an XML request to a URL using HTTP POST and retrieve the response?
Update Sorry, my question was not clear I guess. I want to know how to post an XML request to an URL using either HttpClient or URLConnection and get the response as a POST parameter and display it in a webpage.

A: This example post an xml file, it depends on Jakarta HttpClient API (jakarta.apache.org)
import java.io.File;
import java.io.FileInputStream;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;

/**
 * This is a sample application that demonstrates
 * how to use the Jakarta HttpClient API.
 *
 * This application sends an XML document
 * to a remote web server using HTTP POST
 *
 * @author Sean C. Sullivan
 * @author Ortwin Glück
 * @author Oleg Kalnichevski
 */
public class PostXML {

    /**
     *
     * Usage:
     * java PostXML http://mywebserver:80/ c:\foo.xml
     *
     * @param args command line arguments
     * Argument 0 is a URL to a web server
     * Argument 1 is a local filename
     *
     */
    public static void main(String[] args) throws Exception {

        if (args.length != 2) {
            System.out.println(
                "Usage: java -classpath <classpath> [-Dorg.apache.commons."+
                "logging.simplelog.defaultlog=<loglevel>]" +
                " PostXML <url> <filename>]");

            System.out.println("<classpath> - must contain the "+
                "commons-httpclient.jar and commons-logging.jar");

            System.out.println("<loglevel> - one of error, "+
                    "warn, info, debug, trace");

            System.out.println("<url> - the URL to post the file to");
            System.out.println("<filename> - file to post to the URL");
            System.out.println();
            System.exit(1);
        }

        // Get target URL
        String strURL = args[0];

        // Get file to be posted
        String strXMLFilename = args[1];
        File input = new File(strXMLFilename);

        // Prepare HTTP post
        PostMethod post = new PostMethod(strURL);

        // Request content will be retrieved directly
        // from the input stream
        // Per default, the request content needs to be buffered
        // in order to determine its length.
        // Request body buffering can be avoided when
        // content length is explicitly specified
        post.setRequestEntity(new InputStreamRequestEntity(
                new FileInputStream(input), input.length()));

        // Specify content type and encoding
        // If content encoding is not explicitly specified
        // ISO-8859-1 is assumed
        post.setRequestHeader(
                "Content-type", "text/xml; charset=ISO-8859-1");

        // Get HTTP client
        HttpClient httpclient = new HttpClient();

        // Execute request
        try {

            int result = httpclient.executeMethod(post);

            // Display status code
            System.out.println("Response status code: " + result);

            // Display response
            System.out.println("Response body: ");
            System.out.println(post.getResponseBodyAsString());

        } finally {
            // Release current connection to the connection pool
            // once you are done
            post.releaseConnection();
        }
    }
}

A: Use InputStreamEntity. I used httpclient 4.2.1.
For example:
HttpPost httppost = new HttpPost(url);
InputStream inputStream=new ByteArrayInputStream(xmlString.getBytes());//init your own inputstream
InputStreamEntity inputStreamEntity=new InputStreamEntity(inputStream,xmlString.getBytes());
httppost.setEntity(inputStreamEntity);

A: Warning this code is 5+ years old.  I did some modfying for this post and never tested it.
Hopefully it helps.
Post XML (data) to a server and downlod the resp:
 public int uploadToServer(String data) throws Exception {
      OutputStream os;
      URL url = new URL("someUrl");

      HttpURLConnection httpConn= (HttpURLConnection) url.openConnection();
      os = httpConn.getOutputStream();

      BufferedWriter osw = new BufferedWriter(new OutputStreamWriter(os));

      osw.write(data);
      osw.flush();
      osw.close();

      return httpConn.getResponseCode();
 }

 public String downloadFromServer() throws MalformedURLException, IOException {
      String returnString = null;
      StringBuffer sb = null;
      BufferedInputStream in;

      //set up httpConn code not included same as previous

      in = new BufferedInputStream(httpConn.getInputStream());
      int x = 0;
      sb = new StringBuffer();

      while ((x = in.read()) != -1) {
           sb.append((char) x);
      }

      in.close();
      in = null;

      if (httpConn != null) {
          httpConn.disconnect();
      }

      return sb.toString();
  }

Somewhere else.....
int respCode = uploadToServer(someXmlData);
if (respCode == 200) {
    String respData = downloadFromServer();
}

A: Here's an example how to do it with java.net.URLConnection:
String url = "http://example.com";
String charset = "UTF-8";
String param1 = URLEncoder.encode("param1", charset);
String param2 = URLEncoder.encode("param2", charset);
String query = String.format("param1=%s&param2=%s", param1, param2);

URLConnection urlConnection = new URL(url).openConnection();
urlConnection.setUseCaches(false);
urlConnection.setDoOutput(true); // Triggers POST.
urlConnection.setRequestProperty("accept-charset", charset);
urlConnection.setRequestProperty("content-type", "application/x-www-form-urlencoded");

OutputStreamWriter writer = null;
try {
    writer = new OutputStreamWriter(urlConnection.getOutputStream(), charset);
    writer.write(query); // Write POST query string (if any needed).
} finally {
    if (writer != null) try { writer.close(); } catch (IOException logOrIgnore) {}
}

InputStream result = urlConnection.getInputStream();
// Now do your thing with the result.
// Write it into a String and put as request attribute
// or maybe to OutputStream of response as being a Servlet behind `jsp:include`.


text:
Q: Passing default answers to apt-get package install questions? I'm trying to write a configuration script for new servers, and one of the first steps is to install a series of required packages, such as MySQL, phpMyAdmin, etc. using apt-get install However, when dpkg tries to configure them it asks you for a few options, such as MySQL root password, phpMyAdmin passwords, what server to use, etc.
Since I will likely be passing this script on to co-workers who are unlikely to read the prompts, and my desire to simply start it and walk away, I'd like to know how to pass in a series of "default" answers/values for it to use. This might include usernames/passwords/other dynamic values passed on command line.
--
I realize that having passwords in a script is a security issue, but I'm willing to ignore it, particularly in the more general sense of installing packages that an answer to this would imply.

A: Use debconf's configuration preseeding.
Do a test install to get the values that you want:
root@test1:~# apt-get install mysql-server

..and set the root password when prompted during the install.
Then you can check what the debconf settings look like for what you just installed (you may need to install debconf-utils):
root@test1:~# debconf-get-selections | grep mysql-server
mysql-server-5.5        mysql-server/root_password_again        password
mysql-server-5.5        mysql-server/root_password      password
mysql-server-5.5        mysql-server/error_setting_password     error
mysql-server-5.5        mysql-server-5.5/postrm_remove_databases        boolean false
mysql-server-5.5        mysql-server-5.5/start_on_boot  boolean true
mysql-server-5.5        mysql-server-5.5/nis_warning    note
mysql-server-5.5        mysql-server-5.5/really_downgrade       boolean false
mysql-server-5.5        mysql-server/password_mismatch  error
mysql-server-5.5        mysql-server/no_upgrade_when_using_ndb  error

There's some noise there, but the important part is the password settings.
Then, for a fresh install, you can avoid the prompts completely by setting the password beforehand:
root@test2:~# echo "mysql-server-5.5 mysql-server/root_password_again password Som3Passw0rd" | debconf-set-selections
root@test2:~# echo "mysql-server-5.5 mysql-server/root_password password Som3Passw0rd" | debconf-set-selections
root@test2:~# apt-get install mysql-server

No prompts at all during that install.

A: The debconf package contains debconf-show:
debconf-show package

A: export DEBIAN_FRONTEND=noninteractive
apt-get -q -y install _packages_


text:
Q: has inconsistent name: expected , but metadata has when install from url by pipenv I am trying to install a package directly from github by
pipenv install -e git+https://github.com/cikay/public_repo.git@main#egg=public_repo
command but got\n
has inconsistent name: expected 'public-repo', but metadata has 'main'.
If I specify egg=main it works. What is wrong? Why I cannot specify any name I would like?

A: The package name should be specified in the setup function.
setup(name="package_name")


text:
Q: Is there any way to revoke access from modules after a particular time? We want to make the modules readonly. After clicking on the parent menus, all the submenus should also be readonly.
Tried fields_view_get() but there are too many forms to write the method for!
So is there any other way to do it. We are disabling the modules forever based on a particular date.
Please help.

A: The algorithm that you can follow to achieve this will depend on what kind of access do your users have to your server. If they do not have access to the Settings menu, then what you can do is have a cron job run every X minutes that validates their subscription for your modules.
If the cron job finds that the their subscription is invalid and you want to make some menus unclickable or some views read only you can run the following query against the database to find out what views does a particular module create:
select * from ir_model_data where module = 'your_module_name';
The ir_model_data model actually contains all the keys for data your module contains. All the menus, views, groups etc you created using XML files (or not) are there.
Once you get all the records in your cursor you can cr.fetchall() and then loop on the return value. Each record will have a model and an res_id. When you see that you have a menu or a view that interests you you can set its active field to false to completely hide the view or menu.
When you loop on your results and find a field (that is a record that has model='ir.model.fields', you can set the readonly field to True so that this field is readonly. You can do this for every field.
As you can understand this approach is not bullet proof. If your users have access to the settings (ie. admin rights) then you must not use Odoo's cron jobs and rather configure a cron job to be run from your Operating System to invoke an external Python script that will do the process described above.
Also, if you set the views/menus/fields readonly, they might be rendered as readonly on the web browser, but there is nothing stopping an end user for crafting a rpc request and sending inappropriate json data.
If the users have SSH access to your server there is not much you can do.


text:
Q: Add link to allow editing profile from Meta Here's what happened to me just now:

(It took me an embarrassingly long time looking for an edit option on my meta profile to get to this step though)

So, I realize that it makes sense that we don't have separate profile information for site Meta accounts. And it also makes sense that we do have separate settings options for Meta (there are meta-only tags, people might be less interested in the questions and not want to receive email updates, etc.) But, instead of having the functionality change based on which site you're on, perhaps we could just make it so that you can edit your main-site profile from Meta? Or maybe keep them different, but make it a smaller difference: after clicking the "Edit profile and settings" horizontal tab on Meta, the vertical tab that you start out on is "Preferences" rather than "Edit Profile" by default, and if you click on "Edit Profile" you're automatically taken back to the main site page for that.


text:
Q: BOSH doesn't recognize deleted VM I'm working with BOSH on Openstack. I called bosh -n deploy to have BOSH update an existing deployment. The update required some slave machines to be brought down. As far as I can tell on the Openstack Horizon Web GUI and through command line calls to the Openstack tenancy I'm working on the VMs that should have been brought down have been. However, BOSH seems to think all but one have been brought down.
Is there a way to go into my MicroBOSH VM to edit an entry somewhere that will fix this error?
I can't be positive that the error is completely due to BOSH because the Openstack cloud that I'm working on is going to be completely rebuilt soon and therefore there could be any number of things happening behind the scenes that I don't know about. As such I just want to be able to stop BOSH from complaining about a VM that it can't delete (because it's already gone).

A: Running bosh cck should take care of it.


text:
Q: Accessing Attribute table in ArcMap on Mac computer? I'm using ArcGIS for Desktop on a Mac computer via Parallels.
How do I access the Attribute Table?

*

*I cannot right-click on the layer

*I keep getting Layer properties...

A: Test these options, though I am not sure they will work with Parallels in ArcGIS: http://www.wikihow.com/Right-Click-on-a-Mac
If none of these work, you can still open the attribute table by a keyboard shortcut (select the Layer and press Ctrl + T ):
http://help.arcgis.com/en/arcgisdesktop/10.0/help/index.html#//005s00000006000000


text:
Q: Property 'click' does not exist on type 'string' item[i].click(); should click the element but its not and displaying error "Property 'click' does not exist on type 'string'" can someone please help me why click() is not working. Code:
var ls = element.all(by.xpath("//*[@id='ui-id-1']/li"));
ls.getText().then(function(items) {

  for (var i = 0; i <= items.length; i++) {

    if (items[i] == "Algeria") {
      console.log(items[i]);
      items[i].click();

      browser.sleep(5000);
    }
  }

});

A: As @Tyler pointed out in the comments that a string does not have click() method. What you need is to click the li element.
To perform the click action, in the above snippet substitute items[i].click() with
ls[i].click()
Hope this helps :)


text:
Q: BigQuery cannot return data that execute on cloud function This function has been working normally, but when the latest was deployed to Cloud function, the value that returns from function is always empty and none error.
But if I run it in my local computer,it returns right value.
I don't know what is wrong. Help me please.
exports.fnGetCurrentLocationVehicle = function (sql) {

    let options = {

        query: sql,

        useLegacySql: false,

        useQueryCache: true

    }

    const {BigQuery} = require('@google-cloud/bigquery');

    const bq = new BigQuery({projectId: projectId,});

    return bq.query(options).then(function (data) {

           console.log({

                "fnGetCurrentLocationVehicle": options

            });

            var rows = data[0];

            return rows;

        })

        .catch(err => {

            if (err && err.name === 'PartialFailureError') {

                if (err.errors && err.errors.length > 0) {

                    console.log('Insert errors:');

                    err.errors.forEach(err => console.error(err));

                }

            } else {

                oErr = 'ERROR:' + err;

                console.error('ERROR:', oErr);

            }

            throw err;

        });};


text:
Q: When to "release" after setting a property/instance variable? We have a property declared:
@property (retain) MyClass *myProperty;

What is the difference between this one from Apple example Code:
MyClass *aux = [[MyClass alloc] init];
myProperty = aux;
[aux release];

and this one:
myProperty = [[MyClass alloc] init];

Edited:
The original code posted should have been this one:
MyClass *aux = [[MyClass alloc] init];
self.myProperty = aux;
[aux release];

It was an error of mine, but since many answers have covered the topic I have leave the original code.

A: This is generally the right way to set a property to a new value you've created.
MyClass *aux = [[MyClass alloc] init]; // new value retain count 1
self.myProperty = aux; // new value retain count 2; IMPORTANT: old value retain count decremented
[aux release]; // new value retain count 1, correct since it's retained by self

This is acceptable in the init method.
myProperty = [[MyClass alloc] init]; // new value retain count 1; there was no old value since the object just init'ed

The code you posted is wrong.
MyClass *aux = [[MyClass alloc] init]; // new value retain count 1
myProperty = aux; // new value retain count 1
[aux release]; // new value retain count 0!! deallocated; myProperty points to invalid memory

The following code is subtly wrong.
self.myProperty = [[MyClass alloc] init]; // new value retain count 1 for alloc + 1 for assigned to retain property
[self.myProperty release]; // normally new value retain count 1, correct

However you might get into trouble if the accessors are written in a funny way, and the getter doesn't return the same object you passed into the setter. Perhaps it returns some sort of proxy object, for example. Then you would not be releasing the same object you alloc'ed.

A: self.myProperty = [[MyClass alloc] init];  // this will leak
myProperty = [[MyClass alloc] init];  // this will NOT leak

The first line leaks because it is using the property setter to assign a new object and the property has a memory model of retain.  So, in addition to the alloc in the assignment, you get a retain from the property's setter.
However, the second line will not leak as it is not using the property's setter but the private variable behind it.  Generally speaking, you want to use the setter everywhere except in init.
Because property setters increase the retain count (for retain / copy memory models), it's not uncommon to see an autorelease in property assignments like:
self.myProperty = [[[MyClass alloc] init] autorelease];  // Yeah, no leak now

If you want to really wrap your head around it, an overridden setter might look something like this:
- (void) setMyProperty:(MyClass*)newMyProperty
{
   MyClass *oldValue = _myProperty;
   // replace retain with copy if you want copy to be memory model
   _myProperty = [newMyProperty retain];
   [oldValue release];  // release last in case newMyProperty == oldValue

   [...] // super cool setter behavior here
}

A: Firs of all, just to clarify a little bit what declaring a property means I will explain it a little.
When you declare a property, you are actually declaring two methods, a getter and a setter for that particular class attribute. When you declare a property as retain you are actually saying that when you set that property through the setter method, it will be retained. That basically means that its retain count will be incremented.
In order to set the class attribute using the property declared, you can either use dot syntax, e.g. self.myProperty or the setter method, e.g. -(void)setMyProperty:(MyClass*)newMyClass,
So, in your code, even though you are declaring a property, you are not making use of it because you are not using any of the methods stated above.
Now,
MyClass *aux = [[MyClass alloc] init];
myProperty = aux;
[aux release];

*

*You alloc a MyClass object, now that object has retain count of 1.

*You assign it to your class attribute (w/o using the property) so the retain count is still 1.

*You release that object so its retain count is 0 and it gets released.

myProperty = [[MyClass alloc] init];

*

*You alloc a MyClass object (it has retain count of 1) and assign it your class attribute myProperty.

So, to sum up, in the first case you create and object in memory and then you dispose it, whereas in the second one you are creating it but it never gets disposed.

A: In first case myProperty have retainCount 0.
In second case myProperty have retainCount 1.
If you will use self.myProperty = aux in first case then retainCount of aux and myProperty will be 1.


text:
Q: Log odds ratio as dependent variable in regression I have data with binary outputs of success/failure as the result of undergoing a high and low temperature treatment after being subjected to treatments involving combinations of several other variables. In other words, I have a series of contingency tables across a set of variables. I am interested in whether the comparative effect of the temperature treatment changes across the series of other variables, and whether or not it stays approximately the same.
Based on this, I think it makes sense to model the log odds ratio of the outcomes of the two temperature treatments for each combination of other explanatory variables. Based on some sources I've found and looking at the data, the log odds ratio seems to be approximately normally distributed, and it seems like this would work well under a regression modeling approach.
However, I have not seen many examples of regression analyses that include the log odds ratio as a dependent variable. Is there any reason for this? Is there a better approach that would allow me to answer this set of questions with my data?
Hope this makes sense, and thanks!


text:
Q: Stripe: add a one off payment to a subscription Is it possible in Stripe to add a one off payment to a subscription, without creating a dedicated plan?
For example, if I had an apple subscription business where we charge £4 per month to receive a bag of apples, and wanted to offer users the chance to add a couple of bananas in January.
Except, as well as bananas you could add almost any number of any other type of fruit, then the following month go straight back to being signed up for your bag of apples.
I could charge the card the difference, but with the subscription going out on a set day each month and it might make for a messy bank statement. I'm using Laravel with Cashier at the moment.

A: You can use the invoice item object for this purpose. The invoice item can be added to a subscription and would be payed during the next subscription billing cycle.
Alternatively you can also just create a charge a la carte. This would have nothing to do with the subscription directly, and simply charged the card for the purchase.
Invoice Item:
https://stripe.com/docs/api#create_invoiceitem
Charge:
https://stripe.com/docs/api#create_charge


text:
Q: How to implement a SelectList Looking for an example showing how to implement a SelectList control on a Visualforce page using an extension class.
I am able to display the selectList, but I am not sure how to save the value to the object, and then display it back on a detail page.
I used this page (https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_compref_selectList.htm) as a reference to get this far.
This is the extension class for my Opportunity_New visualforce page for creating a new Oppotunity. This is used to pre-populate some fields on the record.
public with sharing class OpportunityNewExtension
{
    Public Opportunity opp {get; set;}
    Public Opportunity oppy;

     public OpportunityNewExtension(ApexPages.StandardController sc)
    {
        Id id = ApexPages.currentPage().getParameters().get('id');
        oppy=(opportunity)sc.getRecord();

        Map<String,String> m = ApexPages.currentPage().getParameters();
        Account acc = [select id,
                              name,
                              CEI_Customer_Number__c,
                              Sales_Account_Manager__c,
                              Customer_Service_Rep__c
                       from Account
                       where ID=:(Id) m.get('accid')];

        //system.debug(acc);

        // default in values for a new record
        oppy.AccountId = acc.id;
        oppy.cei_Customer_Number__c = acc.cei_Customer_Number__c;
        oppy.Sales_Account_Manager__c = acc.Sales_Account_Manager__c;
        oppy.Customer_Service_Rep__c = acc.Customer_Service_Rep__c;
        oppy.CloseDate = Date.today() + 300 ;
        oppy.StageName = 'Quoting';
        oppy.Probability = 0;

        //system.debug(Oppy);
    }

    public PageReference save()
    {
        //oppy.U_O_M__c =  'TEST VALUE 001';
        opp=oppy;

        Upsert opp;
        return new PageReference('/' + opp.id);
    }
}

This is the second extension class I want to add to the visualforce page.
public class Lookups
{
    public string unitOfMeasure{get;set;}

    ApexPages.StandardController sc;

    public Lookups(ApexPages.StandardController sc)
    {
        this.sc = sc;
    }

    public PageReference test()
    {
        return null;
    }

    public List<SelectOption> getItems()
    {
        List<SelectOption> options = new List<SelectOption>();

        options.add(new SelectOption('FT','FT'));
        options.add(new SelectOption('IN','IN'));
        options.add(new SelectOption('KG','KG'));
        options.add(new SelectOption('LBS','LBS'));
        options.add(new SelectOption('M','M'));
        options.add(new SelectOption('MIMP','MIMP'));
        options.add(new SelectOption('MM','MM'));

        return options;
    }

    public String getUnitOfMeasure()
    {
        return unitOfMeasure;
    }

    public void setUnitOfMeasure(String unitOfMeasure)
    {
        this.unitOfMeasure= unitOfMeasure;
    }
}

This is my visualforce page
<apex:page standardController="Opportunity" extensions="OpportunityNewExtension,Lookups" >
    <apex:sectionHeader title="{!$ObjectType.Opportunity.label} Edit" subtitle="New {!$ObjectType.Opportunity.name}"/>
    <apex:form >
    <apex:pageBlock title="{!$ObjectType.Opportunity.label} Edit" mode="edit">
        <apex:pageBlockButtons >
            <apex:commandButton action="{!save}" value="Save"/>
            <apex:commandButton action="{!cancel}" value="Cancel" immediate="true"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection showHeader="true" title="Account" columns="2">
            <apex:outputField value="{!Opportunity.AccountId}"/>
         <apex:outputField value="{!Opportunity.Sales_Account_Manager__c}"/>
         <apex:outputField value="{!Opportunity.cei_Customer_Number__c}"/>
         <apex:outputField value="{!Opportunity.Customer_Service_Rep__c}"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection showHeader="true" title="Opportunity" columns="2">
            <apex:outputField value="{!Opportunity.ForecastCategoryName}"/>
            <apex:outputField value="{!Opportunity.StageName}"/>
            <apex:outputField value="{!Opportunity.Probability}"/>
            <apex:outputField value="{!Opportunity.Status__c}"/>
            <apex:pageBlockSectionItem />
            <apex:outputField value="{!Opportunity.CloseDate}"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection showHeader="true" title="Opportunity - Sales" columns="1">
            <apex:inputField value="{!Opportunity.Name}"/>
            <apex:inputField value="{!Opportunity.Class__c}"/>
            <apex:inputField value="{!Opportunity.Type}"/>
            <apex:inputField value="{!Opportunity.PD_Engineer__c}"/>
            <apex:pageBlockSectionItem />
            <apex:inputField value="{!Opportunity.Division__c}"/>
            <apex:inputField value="{!Opportunity.Market_Group__c}"/>
            <apex:inputField value="{!Opportunity.Market__c}"/>
            <apex:inputField value="{!Opportunity.Submarket__c}"/>
            <apex:pageBlockSectionItem />
            <apex:inputField value="{!Opportunity.TotalOpportunityQuantity}"/>
            <apex:inputField value="{!Opportunity.Unit_of_Measure__c}"/>
            <apex:inputField value="{!Opportunity.Amount}"/>

            <apex:outputField value="{!Opportunity.U_O_M__c}"/>

            <apex:selectList value="{!unitOfMeasure}" multiselect="false" Size="1" rendered="true">
                <apex:selectOptions value="{!items}"/>
            </apex:selectList>

            <apex:pageBlockSectionItem />
            <apex:inputField value="{!Opportunity.Commercialization_Date_Orig_Est__c}"/>
            <apex:inputField value="{!Opportunity.Commercialization_Date_Curr_Est__c}"/>
            <apex:inputField value="{!Opportunity.Est_12_Mo_Revenue_at_Commercialization__c}"/>
            <apex:inputField value="{!Opportunity.Est_Margin__c}"/>
            <apex:inputField value="{!Opportunity.Est_12_Mo_Margin_Improvement__c}"/>
            <apex:pageBlockSectionItem />
            <apex:inputField value="{!Opportunity.Outcome_Status__c}"/>
            <apex:inputField value="{!Opportunity.Outcome_Status_Reason__c}"/>
        </apex:pageBlockSection>
        <apex:pageBlockSection showHeader="false" title="Description Information" columns="2">
        </apex:pageBlockSection>
        <apex:pageBlockSection showHeader="false" title="Additional Information" columns="2">
        </apex:pageBlockSection>
        <apex:pageBlockSection showHeader="false" title="System Information" columns="2">
        </apex:pageBlockSection>
        <apex:pageBlockSection showHeader="false" columns="2">
        </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>
</apex:page>

A: Create one Apex class and use this class as controller with visualforce page and create new buttton that will call to Save method and save the record. In this example I have used Account object to save the value. Once it is saved you can display in any page. hope this helps.
Controller
public Class ClassName{
  public string str{get;set;}
  public pagereference Save(){
   //Here set the str value with object`s field.
   //like you  want to create new account with selected value.
   Account act = new Account(name=str);
  insert act;
  return null;
 }
}

your VF Page:
<apex:page  controller="ClassName">

Congratulations

    This is your new Page: OptionPicker

  <apex:form >
    <apex:selectList id="recent" size="1" >
      <apex:actionSupport event="onchange" action="{!changeRt}" reRender="recentmodify">
    </apex:actionSupport>
      <apex:selectoption itemLabel="option1" itemValue="card">
    </apex:selectoption>
      <apex:selectoption itemLabel="option2" itemValue="check">
    </apex:selectoption>
      <apex:selectoption itemLabel="option3" itemValue="Scholarship">
    </apex:selectoption>
  </apex:selectList>
    <apex:commandbutton value="Save selected value!" action="{!Save}"/>
  </apex:form>
</apex:page>


text:
Q: JDA guild.getMembers() no longer getting all members, since few days ago This is my code that Ive used for a long time, since before the recent JDA changes in I think July
for (Member member : guild.getMembers()) {
 // code
}

This no longer works, and it only cycles through about 4 members before stopping. Is there anything new I need to add to this since the patch? I commented out the entire loop body and just put a system.println member.getEffectiveName() and it just prints 4 names every time, when there are about 80 people in the discord.

A: You will need to cache members to loop through them.
When using methods such as getMember() or getMemberById() unless its the owner of guild or the bot itself its null.
When using createLight() or createDefault() for building a JDA Member Caching and Member Chunking is disabled by default.
Things like User class can't be null, as it is provided by discord
For more info on caching all members read this


text:
Q: GStreamer Win x64 -- is dshowvideosrc missing? I have GStreamer 1.12.1 Win64 msi installed (full install), but I cannot find dshowvideosrc element.
C:\lib\gstreamer\1.0\x86_64\bin>gst-inspect-1.0.exe dshowvideosrc
No such element or plugin 'dshowvideosrc'

I would like to capture video from a DirectShow video device, but I cannot specify the exact device if I use autovideosrc (which uses something to connect to DirectShow under the hood).

A: I think dshowvideosrc was never ported to gstreamer-1.0. I think ksvideosrc was kind of meant as a replacement for video device access.