text:
Q: slf4j logging syntax I've got 3 developers on a project who have different styles when writing to logs.  Which of these variations is best?
LOG.info("error = {}", errmsg);
LOG.info("error = ", errmsg);
LOG.info("error = " + errmsg);

A: This is the best (jcabi-log on top of SLF4J):
Logger.info(this, "error=%s", errmsg);

It's a short alternative to:
private static Logger LOG = Logger.getLogger(Foo.class);
LOG.info(String.format("error=%s", errmsg));

First, it's convenient to let one utility class to take care about loggers instantiation. Second, it's very convenient to use String.format() for text formatting, because you always see the whole string and can easily translate it.

A: An alteration of the first form is the best
log.info("error={}", errmsg);

As others have said, the second example has to be a mistake as there is no format token to insert errmsg into "error = ", unless errmsg is a Throwable and info level logging is enabled. Then the logger will print a stracktrace.
For many years I preferred the string concatenation, the third form. I found it easier to read months or years later when I go back to read the code.
However, as Tomasz Nurkiewicz answered, the first form LOG.info("error={}", errmsg); is the best. The reason, though, isn't that String.format() is faster than String concatenation. It isn't. See Is it better practice to use String.format over string Concatenation in Java?.
The reason the first form performs better is that if the info level logging is disabled, then the logging framework doesn't have to call  errmsg.toString()  and it doesn't have to execute String.format() at all. The only case where errmsg.toString() has no performance cost is if errmsg is a String.
I also would suggest no whitespace around the = as many log aggregators like Splunk will automatically index error=errmsg into a field and value pair. Also, if this truly is an error, then I would write it to the error() level, not info(). And most likely there is a Throwable exception somewhere before this code that should go into the Throwable parameter.
And, logger, while it is probably declared as final, is a mutable object, so, it should be in lower case. See Should a "static final Logger" be declared in UPPER-CASE?.
which means the answer really should be
log.info("error={}", errMsg, exception);

A: LOG.info("error = {}", errmsg);

Correct and best.
LOG.info("error = ", errmsg);

This is most likely wrong. Unless errmsg is an exception, it will never be logged.
LOG.info("error = " + errmsg);

This one is not performing as good as first. You'll run String concatenation every time you hit this line while in first case variable replacement occurs only if statement will actually be logged.
Some time ago I blogged about different logging syntaxes in slf4j.

A: Below is the exact copy paste from actual slf4j javadoc. Its worth visiting here :http://www.slf4j.org/api/org/slf4j/Logger.html
import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;

 public class Wombat {

   final static Logger logger = LoggerFactory.getLogger(Wombat.class);
   Integer t;
   Integer oldT;

   public void setTemperature(Integer temperature) {
     oldT = t;
     t = temperature;
     logger.debug("Temperature set to {}. Old temperature was {}.", t, oldT);
     if(temperature.intValue() > 50) {
       logger.info("Temperature has risen above 50 degrees.");
     }
   }
 }


text:
Q: Finding and replacing text in c# I need to add functionality in my program so that any file imported it will find the text within the "" of the addTestingPageContentText method as seen below. The two values on each line will then be added to a datagridview which has 2 columns so first text in first column then second in the 2nd column. How would i go about Finding the "sometext" ?
    addTestingPageContentText("Sometext", "Sometext");
    addTestingPageContentText("Sometext2", "Sometext2");
... continues n number of times.

A: Neither fast nor efficient, but it's easier to understand for those new to regular expressions:
while (!endOfFile)
{
    //get the next line of the file
    string line = file.readLine();

    EDIT: //Trim WhiteSpaces at start
    line = line.Trim();
    //check for your string
    if (line.StartsWith("addTestingPageContentText"))
    {
        int start1;
        int start2;
        //get the first something by finding a "
        for (start1 = 0; start1 < line.Length; start1++)
        {
            if (line.Substring(start1, 1) == '"'.ToString())
            {
                start1++;
                break;
            }
        }
        //get the end of the first something
        for (start2 = start1; start2 < line.Length; start2++)
        {
            if (line.Substring(start2, 1) == '"'.ToString())
            {
              start2--;
              break;
            }
        }
        string sometext1 = line.Substring(start1, start2 - start1);
        //get the second something by finding a "
        for (start1 = start2 + 2; start1 < line.Length; start1++)
        {
            if (line.Substring(start1, 1) == '"'.ToString())
            {
                start1++;
                break;
            }
        }
        //get the end of the second something
        for (start2 = start1; start2 < line.Length; start2++)
        {
            if (line.Substring(start2, 1) == '"'.ToString())
            {
                start2--;
                break;
            }
        }
        string sometext2 = line.Substring(start1, start2 - start1);
    }
}

However I would seriously recommend going through some of the great tutorials out there on the internet. This is quite a good one

A: The expression "\"[^"]*\"" would find each...

redpajama_set_name: RedPajamaStackExchange


text:
Q: negative fitted value for positive original value auto.arima I am trying to forecast a time series using auto. arima. My command is,
auto.arima(X, stationary = F, ic = "aic", stepwise = T, trace = T, test = "adf", allowdrift = F, allowmean = T, lambda = BoxCox.lambda(prd.xts, method = "loglik"), biasadj = T);

My original time series has 36 observations (monthly for 3 years). When plotting the fitted vs original values, I found the fitted value to be a negative one. Please find below the original and fitted:
X:
 [1]  5200  4420  5297  6815  8385  8000  5700  6610  5810  5680  4100  4750  2205  4748  5170  8050  8900  7050  6810
[20]  7030  5890  7160  6405  5370  5360  7649  7730  9090 10174  7775

Fitted:
 [1]  4932.4310  4935.5587  4003.1725  5045.8954  6690.9964  8315.6047  7920.8435  5495.5020  6474.9251  5616.1591
[11]  5473.4794  3585.5492  4409.2808  -716.4241  4406.8788  4901.2397  7972.2124  8841.2718  6937.2260  6685.7413
[21]  6916.3253  5703.4412  7052.0103  6257.4684  5128.3367  5117.0722  7559.2477  7642.8563  9034.6446 10133.6204

Looking at these two closely, we can observe, 14th element in original series is: 4748 & in fitted (ARIMA modelled) is -716.4241.
I am a novice in Time series forecasting. The best model auto.arima spits out is arima(0,1,0) with an AIC of 964.095.
My questions:
1) Is the model correct? Is it alright, if the fitted value is negative?
2) Would it be reasonable to have just 36 observations to do a monthly forecasting?
Any help would be much appreciated.

A: ARIMA assumes normally distributed innovations, and it can definitely go below zero. (If you take differences, you will often end up with negative values.)
In your specific case, I suspect that your X is not identified as monthly data, i.e., that it has a frequency of 12. Once we do that and create a seasonplot, seasonality is rather evident:
library(forecast)
foo <- c(5200, 4420, 5297, 6815, 8385, 8000, 5700, 6610, 5810, 5680,
4100, 4750, 2205, 4748, 5170, 8050, 8900, 7050, 6810, 7030, 5890,
7160, 6405, 5370, 5360, 7649, 7730, 9090, 10174, 7775)

X <- ts(foo,frequency=12)
seasonplot(X)

Now auto.arima() fits a seasonal model, and neither fits nor forecasts are negative:
model <- auto.arima(X)
plot(forecast(model,h=12))
lines(fitted(model),col="red")


text:
Q: Suggestion for labeling my plots I have several figures like the one in the below:
logdata001 = {{2., 0.961973}, {3., Around[1.0615567283096428`, 0.0829973108613199]}, {4., Around[1.6148368066515686`, 0.19646949168300437`]}, {4.9542, Around[1.9799984788912215`, 0.22744045238090516`]}, {5.97728, Around[3.0256586135432313`, 0.4441779651996193]}, {6.96578, Around[4.751870201707909, 0.5186565213910944]}, {7.96578, Around[8.353662042037488, 1.0279834833435684`]}, {8.96578, Around[13.333103260464355`, 1.3421587275991116`]}}

logdata002 = {{2., 1.36736}, {3., 1.50511}, {4., 1.67348}, {4.9542, 2.25512}, {5.97728, 3.0625}, {6.96578, 4.38542}, {7.96578, 7.34536}, {8.96578, 12.6508}}

ListLinePlot[{logdata002, logdata001}, IntervalMarkers -> "Fences", Frame -> True,
PlotMarkers -> {Graphics[{Disk[], {Thick, Circle[]}}], 0.04}, LabelStyle -> {22, GrayLevel[0]},
PlotStyle -> {{RGBColor[0.368417, 0.506779, 0.709798], Thick}, {RGBColor[0.922526, 0.385626, 0.209179], Thick}}, ImageSize -> Large, BaseStyle -> {FontFamily -> "Latin Modern Math"},
PlotLegends -> Placed[PointLegend[{Style["Theory",
FontFamily -> "Latin Modern Roman 10"],
Style["Experiment", FontFamily -> "Latin Modern Roman 10"]},
LegendFunction -> "Frame"], Scaled[{0.2, 0.77}]],
FrameLabel -> {Style["City", FontFamily -> "Latin Modern Roman 10"],
Style["Crimes", FontFamily -> "Latin Modern Roman 10"]}, FrameTicks -> {{{2, 4, 6, 8, 10, 12, 14},
None}, {{{2, 4}, {3, 8}, {4, 16}, {5, 31}, {6, 63}, {7, 125}, {8,
  250}, {9, 500}}, None}}]

I want to label these figures as (A), (B), and ... . What is the best way to do this and how?

A: I am leaving this on top because I like it the most
Edit 2:
text0 = "Some poor souls trying to keep the referees happy";
text1 = "Figure (A)";
text2 = "Figure (B)";
text3 = "Figure (C)";
Grid[{{Style[text0, FontSize -> Scaled[0.02],
    FontFamily -> "League Gothic"],
   SpanFromLeft}, {Style[text1, FontSize -> Scaled[0.02],
    FontFamily -> "Alegreya SC"],
   Style[text2, FontSize -> Scaled[0.04],
    FontFamily -> "Herculanum"]}, {plot,
   plot}, {Style[text3, FontSize -> Scaled[0.05],
    FontFamily -> "Felipa"], SpanFromLeft}, {plot, SpanFromLeft}},
 ItemSize -> Scaled[0.5]]

Edit 3: in the comments it was requested to place Figure A in the bottom and to the left, while keeping the rest aligned. The following
Labeled[ListLinePlot[{logdata002, logdata001},
  IntervalMarkers -> "Fences",
  Frame -> True,
  PlotMarkers -> {Graphics[{Disk[], {Thick, Circle[]}}], 0.04},
  LabelStyle -> {22, GrayLevel[0]},
  PlotStyle -> {{RGBColor[0.368417, 0.506779, 0.709798],
     Thick}, {RGBColor[0.922526, 0.385626, 0.209179], Thick}},
  ImageSize -> Large,
  BaseStyle -> {FontFamily -> "Latin Modern Math"},
  PlotLegends ->
   Placed[PointLegend[{Style["Theory",
       FontFamily -> "Latin Modern Roman 10"],
      Style["Experiment", FontFamily -> "Latin Modern Roman 10"]},
     LegendFunction -> "Frame"], Scaled[{0.2, 0.77}]],
  FrameLabel -> {Style["City", FontFamily -> "Latin Modern Roman 10"],
     Style["Crimes", FontFamily -> "Latin Modern Roman 10"]},
  FrameTicks -> {{{2, 4, 6, 8, 10, 12, 14},
     None}, {{{2, 4}, {3, 8}, {4, 16}, {5, 31}, {6, 63}, {7, 125}, {8,
        250}, {9, 500}}, None}}],
 Grid[{{Style["Figure A", FontSize -> Scaled[0.02],
     FontFamily -> "League Gothic"]}}], {{Left, Bottom}}]

Orignal
text = "some words";
Grid[{{plot}, {Style[text, FontSize -> Scaled[0.05],
    FontFamily -> "Helvetica"]}}, ItemSize -> Scaled[0.5]]

where in the above plot=ListLinePlot[....]
Edit 1: another possible way is
Column[{plot,
  Style[text, FontSize -> Scaled[0.05], FontFamily -> "Helvetica"]},
 ItemSize -> Scaled[0.5]]


text:
Q: How we can apply pandas groupby to get expected output? Col1    Col2   Col3   Result

2        70     1      15
2        71     2      15
2        72     3      15
3        80     4      16
3        81     5      16
3        82     6      16
3        2      15     16
3        3      16     16

I am new to pandas, can anyone explain how get last column result to add my existing data frame?

A: Use Series.map with DataFrame.drop_duplicates for all unique rows by col2 values:
df['Res'] = df['Col1'].map(df.drop_duplicates('col2').set_index('Col2')['Col3'])
print (df)
   Col1  Col2  Col3  Result  Res
0     2    70     1      15   15
1     2    71     2      15   15
2     2    72     3      15   15
3     3    80     4      16   16
4     3    81     5      16   16
5     3    82     6      16   16
6     3     2    15      16   16
7     3     3    16      16   16

A: Another option is merge:
df.merge(df[['Col2','Col3']].rename(columns={'Col2':'Col1', 'Col3':'Res'}),
         on='Col1', how='left')

Output:
   Col1  Col2  Col3  Result  Res
0     2    70     1      15   15
1     2    71     2      15   15
2     2    72     3      15   15
3     3    80     4      16   16
4     3    81     5      16   16
5     3    82     6      16   16
6     3     2    15      16   16
7     3     3    16      16   16


text:
Q: Como guardar una imagen generada por html2canvas a mi base de datos Mysql Me gustaría guardar una imagen generada con html2canvas en mi phpmyadmin, pero sin tener que descargar la imagen.
Alguien sabe como se podría hacer eso?
Me sería de mucha ayuda.


text:
Q: Google Maps API - Nearby Search requests - PlaceID I am calling the following API from Google Maps:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={latitude},{longitude}&radius={radius}&type={type}&keyword={keyword}&key={api_key}
and even tried:
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={latitude},{longitude}&**fields=place_id**,formatted_address,geometry,name&radius={radius}&type={type}&keyword={keyword}&key={api_key}
at the end I got the result of places but the place_id is null, which would give more detailed information about this place...but always null.
Any experience?
Thanks in advance,Csaba


text:
Q: How can I build a transparent shape with colored background I need this:

the white must be transparent
if I use this shape:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle"
>
<size android:height="32dp"
    android:width="16dp"/>
<solid android:color="@android:color/transparent"
    />
<corners android:topLeftRadius="16dp"
    android:bottomLeftRadius="16dp"
/>

inside of
    <ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/yyy"
    android:background="@color/colorPrimary"/>

I get a blue rectangle (because the color under the transparent shape is blue)
How can I get the shape transparent so I will see the color behind the ImageView?

A: Write code into your color:
<color name="transparent">#10000000</color>

and also use <solid android:color="@color/transparent">


text:
Q: inequality involving eigendecomposition Let $A \in \mathbb{R}^{n \times n}$ be an Hermitian matrix. This means the eigenvalues $\lambda_{i}, i = 1, ..., n$ are real and the eigenvectors $v_i, i = 1 ... n$ are orthogonal on each other. We assume that alle eigenvalues are simple and we assume the eigenvalues are in increasing order (so $\lambda_1 < \lambda_2< ...< \lambda_n$), we define $V := [v_1 ... v_n]$ and $\Lambda = diag(\lambda_1, ..., \lambda_n)$ and we note $V_m = [v_1 ... v_m]$ and $\Lambda_m = diag(\lambda_1, ..., \lambda$. This means we can write $A = V \Lambda V^*$
In the paper I'm reading they state the following:
$$\min_{u \in span{V_m}^\bot, \left \| u \right  \| = 1} u^* A u \geq \min_{u \in span{V_m}^\bot, \left \| u \right  \| = 1  }u^* \left( V_m \Lambda_m V_m^* + \lambda_{m+1} (I - V_m V_m^*)\right) u$$
I don't know how to use the fact that $u \in span{V_m}^\bot$.
Can anyone help me?

A: I hope you agree that the RHS is $\lambda_{m+1}$, since the first term is zero and the second term is $\lambda_{m+1}$ (since $I-V_{m}V_{m}^{\top}$ is projection onto $V_{m}^{\perp}$ and $u\in\text{span}V_{m}^{\perp}$). Also assume that $u=\Sigma_{i=m+1}^{n}\alpha_{i}v_{i}$. For the LHS:

Sorry, the very last equality should read "=RHS"


text:
Q: GRAILS: HQL - Order by with IF (ISNULL) I'm wondering how to format this query. I have a table with three dates, where some can be nulls. The three fields are createdDate, downDate, and fixDate. I need to query and get the latest entry depending on the date. Ex, if fixDate is not null, then it orders by the fixDate, if it is null then I need to order by downDate. If downDate is null, then I order by createdDate.
Via mySQL, I get the correct results using:
SELECT * FROM history WHERE equipment_id=88 ORDER BY IF(ISNULL(fix_date), IF(ISNULL(down_date), created_date, down_date), fix_date) DESC;

I am trying to put this into my grails project and using HQL and tried (also tried other variations of this):
History.executeQuery("SELECT FROM History WHERE equipment=:eqpt ORDER BY " +
"IF(ISNULL(fixDate), IF(ISNULL(downDate), createdDate, downDate), fixDate) DESC", [eqpt:equipment])

Also tried:
   History.executeQuery("SELECT FROM History WHERE equipment=:eqpt ORDER BY " +
    "IF(COALESCE(fixDate,downDate,createdDate) DESC", [eqpt:equipment])

ERROR I get is:
nexpected token: FROM near line 1, column 8 [SELECT FROM com...History WHERE equipment=:eqpt ORDER BY IF(COALESCE(fixDate, downDate, createdDate) DESC]

I appreciate any help, if there is a createCriteria solution as well that would be fine. Thanks.

A: I've never tried it, but the Hibernate documentation says that coalesce() is supported in the 'where' clause. If it is also available in the 'select' clause, you could select the coalesced date, and then order by it, as the documentation also states that

"The list returned by a query can be ordered by any property of a
  returned class or components"

So, perhaps something like:
 select h.prop1, h.prop2, coalesce(h.fixDate, h.downDate, h.createdDate) as orderDate from history h where ..... order by orderDate


text:
Q: can I pop 2 times with stack? (java) Im writing a program with the help of a stack. I have to decode inputs. for example the word 'he-llo', becomes 'hllo', but I get 'hello'. the '-' should have the effect of deleting the character which comes before it and it self.
I know that I have to use pop (which I have implemented my self), but I have problems with using it twice in a row. Because I've actually already printed the 'e' in the first if statement. I'm really clueless on how to fix this, am I printing it wrong? or should I adapt my pop code?
//my pop code
public char pop() {
    if(!this.empty()){
        if(top > 0){
            temp = arr[top - 1];
            arr[top -1] = 0;
            top = top -1;
        }
        return temp;
    }else{
        return 0;
    }

    //handling the charachters of the input
    if(Character.isLetter(ch) || Character.isDigit(ch)){
         Stack.push(ch);
         System.out.println(myStack.peek());
    }
    if(Stack.peek() == '-'){
         myStack.pop();
         myStack.pop();
         System.out.println(Stack.peek());
    }
}

A: your question is about using pop twice in a row--yes, that should work as long as top represents at least two objects on the stack
the semantics of Stack is slightly wrong for pop if your implementation is using an array.  the top of stack (top) is supposed to be the object you see; your pop is using top - 1.  secondly, there is no need to set the popped objects to 0, the push method should overwrite the value if the Stack is correctly implemented.
the empty test is not correctly used given the above; empty should test for top < 0 and return true if so, otherwise false.  stack[0] is a legitimate element.  perhaps a bit of review of stacks and their implementation and operations is in order?


text:
Q: Get SonarQube analysis results in JavaConsole is it possible to get the results of a SonarQube analysis displayed in the JavaConsole?
For example, I installed SonarQube in Java/Maven. I can analyze my program and it uploads the results to localhost:9000. But can I get the number of "code-smells" or "bugs" in my console from the project when it got uploaded to localhost:9000?
I tried smth with
HttpGet httpGet = new HttpGet("http://localhost:9000/api/issues/search?pageSize=500&componentKeys=CODE_SMELLS");
But it seems like it does not work?
I tried to use the web/API but I don't understand the documentation. For example
web_api/api/measures
I don't know how to actually use it in the code I can not find an example or which method or so I have to use, to use the API.
Can someone maybe provide some example code or pseudocode for Java how I could retrieve results from the analysis?
I am fairly new to SonarQube and how to work with an API. So sorry about that.
I am using the newest SonarQube free edition, maven and IntelliJ

A: If you've installed the sonarlint plugin you get the lint tab next to console and terminal. Ctrl+Alt+s or Ctrl+Shift+s on your project at root and that will produce the results

A: On http://localhost:9000/api/webservices/list I could find all possible services and parameters.
This helped me a lot, for example:
http://localhost:9000/api/issues/search?componentKeys=myProjectKey&facets=types&facetMode=count


text:
Q: How to create table in database for entity, using Spring JPA and Maven? How to generate table in the Postgres database for the entity below? I'm using maven build.
Entity:
@Entity
@Table(name = "EMPLOYEE")
public class Employee {
   @Id @GeneratedValue
   @Column(name = "id")
   private int id;
}

properties:
spring.jpa.properties.hibernate.cache.use_second_level_cache=true
spring.jpa.properties.hibernate.cache.region.factory_class=org.hibernate.cache.ehcache.EhCacheRegionFactory
spring.datasource.url=jdbc:postgresql://localhost:5433/con_db
spring.datasource.username=postgres
spring.datasource.password=root
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.default_schema=as2
spring.jpa.hibernate.naming.physical-strategy=com.ds.entity.strategy.EntityNamingStrategy
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.h2.console.enabled=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE

A: Try to use hibernate default_schema to public instead of as2 like this: spring.jpa.properties.hibernate.default_schema=public then run your project.

A: you have to run the spring boot app to build your database structure in the postgres database, there is no relation of maven with that. Thanks @Spartan for your help here.


text:
Q: SqsListner not listening to messages I have below application.properties for connection:
cloud.aws.credentials.instanceProfile=true
cloud.aws.credentials.useDefaultAwsCredentialsChain=true
cloud.aws.region.static=us-east-2
cloud.aws.stack.auto=false

I have written listener with SqsListner and running my application with below dependencies
 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-aws-messaging</artifactId>
            <version>1.2.4.RELEASE</version>
        </dependency>
 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
            <version>1.4.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-aws-messaging</artifactId>
            <version>2.1.2.RELEASE</version>
        </dependency>

But somehow my listener is not listening to messages (I am doing this in the existing code base).
I tried creating a separate spring boot application with only the listener in it, which is working fine. But the same thing is not working when added to existing code
and Listener code is as below:
@SqsListener(value = "test-queue",deletionPolicy = ON_SUCCESS)
public void receiveMessage(String message,
    @Header(X_REQUEST_ID) String xRequestId,
    @Header(X_SESSION_ID) String xSessionId) {
    LOGGER.info("message received is: {}", message);

    }
}

A: By mistake I had overriden AmazonSQSAsync bean
public AmazonSQSAsync amazonSQSClient() {
        return new AmazonSQSAsyncClient();
    }

which caused ignoring the aws properties I added. And hence SqsListner was not working as there is no way to explicitly specify aws properties including credentials to SqsListner. I removed the manual bean creation part and it started working smoothly as Bean is automatically created now and picking up the correct properties.


text:
Q: how to get nested undeclared variables in python jinja2 I have an xml template and I'm loadind data into it using jinja2 template engine. I'm trying to validate that all the variables in the template are supplied:
from jinja2 import Environment, PackageLoader, meta
tmp = JinjaEnvironment().from_string(TEMPLATE)
parsed_content = tmp.environment.parse(TEMPLATE)
for key in meta.find_undeclared_variables(parsed_content):
    if key not in data:
        print 'Missing ', key

The problem is that the find_undeclared_variables method does not return nested variables.
For example if my data is {'main': {'age': 22, 'height': 6}, 'size': 10}
then that method returns ['main', 'size']
but what I need is ['main.age', 'main'height', 'size']

The goal is to validate that all variable are substituted. Any ideas?

A: I found the package that helps with that: jinja2schema
from jinja2schema import infer, model
def test(self):
    for key, val in infer(TEMPLATE).items():
        assert key in self.data, 'Missing {}'.format(key)

        if type(val) == model.List:
            for subkey in val.item.keys():
                assert subkey in self.data[key][0], 'Missing {}.{}'.format(key, subkey)

        elif type(val) == model.Dictionary:
            for subkey in val.keys():
                assert subkey in self.data[key], 'Missing {}.{}'.format(key, subkey)


text:
Q: Enter on a file, modify the rows and overwrite the file. With a .bat file I am doing some modifications on a text file; however the program is adding lines instead of modifying them.
As i am new to it, can you help or guide me?
Here is my code:
setlocal enabledelayedexpansion
for /f "delims=" %%a in (economic_changes.txt) do (
   SET s='%%a
   SET s=!s:;= !
   SET s=!s:- =-;;!
   SET s=!s: -=-!
   SET s=!s:-;;-=-;-!
   SET s=!s:-=%!
   SET s=!s:_= %!
   SET s=!s:;=';'%!
   SET s=!s:;'';'=;;%!

   echo !s!
) >>  "%userprofile%\desktop\Economic_Folder\economic_changes.txt"

A: Since the same file cannot be read and written at the same time, create a temporary file to store the changed lines into.
Several of the modifications have a SPACE character at the end. Using quotes makes it clear where those occur. Perhaps you want those. I do not know.
Then, of course, delete the temporary file once completed.
setlocal enabledelayedexpansion

SET "TMPFILE=%TEMP%\file_converter_%RANDOM%.tmp"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")

for /f "delims=" %%a in (economic_changes.txt) do (
   SET "s='%%a "
   SET "s=!s:;= ! "
   SET "s=!s:- =-;;! "
   SET "s=!s: -=-! "
   SET "s=!s:-;;-=-;-! "
   SET "s=!s:-=%!"
   SET "s=!s:_= %!"
   SET "s=!s:;=';'%!"
   SET "s=!s:;'';'=;;%!"

   echo>>"%TMPFILE% !s!
)

COPY /Y "%TMPFILE%" "%USERPROFILE%\Desktop\Economic_Folder\economic_changes.txt"
IF EXIST "%TMPFILE%" (DEL "%TMPFILE%")

A: Here's a "dirty" trick:
@echo off
setlocal enabledelayedexpansion

set _FILE="%userprofile%\desktop\Economic_Folder\economic_changes.txt"
for /f %%a in ('type %_FILE% ^&^& echo.^>NUL 2^>%_FILE%') do (
    SET s='%%a
    SET s=!s:;= !
    SET s=!s:- =-;;!
    SET s=!s: -=-!
    SET s=!s:-;;-=-;-!
    SET s=!s:-=%!
    SET s=!s:_= %!
    SET s=!s:;=';'%!
    SET s=!s:;'';'=;;%!

    echo !s!
) >> %_FILE%

The "algorithm":

*

*type the file contents to be consumed by the for loop

*Empty it (thanks to [SO]: How to create empty text file from a batch file?)

*Append everything in (your original code)


text:
Q: unset $_POST doesn't works Here is my code
http://pastebin.com/DtK8MMtU
when user pressing 'Next turn' button, $_POST["turnOver"] is getting set. Then script goes into this section
 if (isset($_POST["turnOver"])) {
                $_SESSION["state"] = 0;
                unset($_SESSION["rolls"] );
                unset($_SESSION["bet"]);
                unset($_SESSION["nextTurn"]);
                $_SESSION["turnNumber"]++;
                unset($_POST["turnOver"]);
 }

By this row unset($_POST["turnOver"]); i want this block executes only once after user pressed 'Next turn' button, but this executed every time user refreshed page (i saw this by $_SESSION["turnNumber"] value, its increasing all the time i refresh page). Also, here is  $_POST var_dump from xdebug:
array (size=1)
  'turnOver' => string ''... (length=9)

It means it is set?

A: If the user is refreshing the page they will be sending the turnOver POST value each time. Unsetting post will only affect the rest of that page.
Best thing to do is set a session value and set that the first time that turnOver is sent then check against that.

A: You said

I saw this by $_SESSION["turnNumber"] value, its increasing all the time i refresh page

This is a normal beauvoir since you execute
$_SESSION["turnNumber"]++;

which will keep adding 1 at each refresh. Further more before the line
unset($_POST["turnOver"]);

Your $_POST["turnOver"] is actually set so if you try a var_dump before the unset() command you will see it as set.


text:
Q: Rails 4 Remove Migration ID from Migration Index How do I remove a migration ID listing with "** NO FILE **" in rake db:migrate:status?  For example:
 Status   Migration ID    Migration Name
--------------------------------------------------
   up     20131017204224  Create users
   up     20131218005823  ********** NO FILE **********
   up     20131218011334  ********** NO FILE **********

I'm not understanding why it would still keep an old migration file when I manually removed it myself as I was playing around with how migrations work.  Is this for record keeping?  But what use is it when I don't have a name associated with it?
I tried using db:migrate:down command for those files but it says file missing. I have no clue what to do here.
Can someone explain how to remove this listing and maybe some insight on why this might happen.

A: You need to delete that numbers from your schema_migrations table in the database.

A: You deleted the file but the ID is still in the schema table.
Just Log into mysql
 SELECT * FROM schema_migrations; *- take note of the version_id*

Then
DELETE FROM schema_migrations WHERE VERSION = version_id;

Then logout and verify
rake db:migrate:status

A: You can also delete it using SQL, but through the rails console.
sql = "DELETE FROM schema_migrations WHERE VERSION = 'version_id'"
ActiveRecord::Base.connection.exec_query(sql)


text:
Q: Google Apps Script doesn't recognize "Host" header in HTTP POST request? I'm trying to query ArcGIS Rest API from Google Apps script. Building the request in Postman works perfectly fine, but when I get the code into apps script, I'm having trouble that I cant seem to figure out. Here's the code:
function callEsri () {
  var url = "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trailheads/FeatureServer/0/query"
  var params =
      {
  "async": true,
  "crossDomain": true,
  "url": "https://services3.arcgis.com/GVgbJbqm8hXASVYi/arcgis/rest/services/Trailheads/FeatureServer/0/query",
  "method": "POST",
  "headers": {
    "Content-Type": "application/x-www-form-urlencoded",
    "User-Agent": "PostmanRuntime/7.20.1",
    "Accept": "*/*",
    "Cache-Control": "no-cache",
    "Postman-Token": "[TOKEN]",
    "Host": "services3.arcgis.com",
    "Accept-Encoding": "gzip, deflate",
    "Content-Length": "125",
    "Connection": "keep-alive",
    "cache-control": "no-cache"
  },
  "data": {
    "f": "json",
    "where": "CITY_JUR LIKE '%Los Angeles%'",
    "outSr": "4326",
    "outFields": "TRL_NAME,ELEV_FT,CITY_JUR,PARK_NAME,FID"
  }
}
  var response = UrlFetchApp.fetch(url, params);
  var json = response.getContentText();
  var data = JSON.parse(json);
  Logger.log(data);
}

The Error I am getting is: Execution failed: Attribute provided with invalid value: Header:Host (line 28, file "Code")
Any reason why Google is not recognizing this and is there a way to fix this? Any help/advice is greatly appreciated.

A: As @TheMaster has already noted in the comments. You are already specifying the Host in the url.
Also you can take a look at the official documentation of URLFetchApp.
And in case you want more information in the head here you have the mozilla documentation on that header and also the RFC specifying the Host header.


text:
Q: Custom Looping of Wordpress Posts I have been working on a Wordpress theme from few days.
I want to achieve modern like layout in my theme's frontpage.
But I am having no clue that how to achieve it.
Now my wordpress theme loops the post in this manner

What I want to achieve in the above code is

Can anyone suggest a possible solution with this custom looping for a frontpage.

A: Hi I believe this should work

    <?php $count  = 1; ?>
    <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
       <?php if $count = 1; ?>

        <?php else : ?>
                <article class="post<?php echo $count; ?>">

        <?php endif; ?>
    <?php $count++; endwhile; endif; ?>


text:
Q: Can I overload the implicit type conversions in Groovy? Say I have a function
def method1(MyClass2 mc2) {...}

and I call it with an object of type MyClass1.  Is there a way that I can specify how to implicitly convert from MyClass1 to MyClass2, so that the method call will work without having to explicitly say method1(mc1 as MyClass2)?

A: If MyClass1 doesn't implement/extend MyClass2, there isn't anything that I'm aware of that'll do the "as MyClass2" conversion without the old standby Java method overloading.  Explicitly overloading the method with the signature including MyClass1:
def method1(MyClass1 mc1) {
    method1(mc1 as MyClass2)
}

The other, more groovy, alternative is to not explicitly type method1 so that it doesn't demand that you have an instance of MyClass2:
def method1(mc) {
    // do stuff and let mc walk/talk/quack like MyClass2
    // or even do the "as MyClass2" in this method if you need it for something further down.
}


text:
Q: What is $A^{31}+B^{35}$ If $AB=B$ and $BA=A$ then $A^{31}+B^{35}$ is?
(A)$A^2+B^2$
(B)$A+B$
(C)$A^4+B^4$
(D)$A^3+B^3$
My work
$AB=B \rightarrow ABB^{-1}=BB^{-1}$
So, $A=I$
Similarly $B=I$
All option seem valid to me :O

A: You are given $AB = B$ so that $ABA = BA$. You are also given $BA = A$ so that $A^2 = A$.
From here $A^{31} = A$ is a friendly exercise.
For that matter, so is $B^{35} = B$.
Happy holidays.


text:
Q: Jquery fade right to left I have the following jquery:
jQuery.fn.slideFadeToggle = function(speed, easing, callback) {
  return this.animate({
    opacity: 'toggle',
    width: 'toggle'
  }, speed, easing, callback);
};

$(document).ready(function() {
  $("#container_content_quick").hide();
  $("#header").click(function() {
    $("#container_content_quick").slideFadeToggle();
    return true;
  });
});

Basically fades in #container_content_quick from left to right.
I wonder if its possible to fade right to left?

A: If your element is anchored to the left then the left side will stay in place and the right side will appear to move towards it. If you element is anchored to the right, then the opposite is true. You could achieve this most easily with floats, I would guess.


text:
Q: Excel formula working on local but not on remote server I am facing one very strange issue. User uploads a blank template in our system (with some formulas), service imports some data into the workbook and these formulas are triggered. I am facing a strange issue with 1 template, the formula is not working correctly (on the windows remote server) but if I copy the same workbook over to my local computer, the formula is calculating correctly. (Please note that excel automatic calculation is on)
In the remote server, if I hit calculate sheet manually nothing happens. But if I click on the cell and press enter, correct value is displayed.
I am not sure how this is possible that it works on 1 server but not on the other. Any hints on what could be the issue?
Sample formula which is not working:-
=IF(C$13<DATE(2021,7,31),IFERROR(Q53/G53,0),SUMIFS('foo Waterfall'!$W:$W,'foo Waterfall'!$D:$D,'bar Waterfall'!B53)+IFERROR(SUMPRODUCT(('foo Threshold'!$J$6:$L$53),('foo Threshold'!$J$4:$L$4<='bar Waterfall'!$C$13)*('foo Threshold'!$C$6:$C$53='bar Waterfall'!$C53)*('foo Threshold'!$B$6:$B$53='bar Waterfall'!$B53)),0))


text:
Q: How to setup optional parameters in mod_rewrite I am in a new project and I'm designing the URL structure,
the thing is I want URLs look like this:
/category-23/keyword/5/
Where the normal page is:
/search.php?q=keyword&cat=23&page=5
So my question is, cat and page fields, must be optional, I mean if I go to /keyword it should be
/search.php?q=keyword (page 1)
and if I go to
/category/keyword should be:
/search.php?q=keyword&cat=category&p=1
and also if I go to
/keyword/5/ it must be: /search.php?q=keyword&p=5
Now I have my .htaccess like this:
RewriteEngine On
RewriteBase /
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteCond %{SCRIPT_FILENAME} !-d
RewriteRule ^(.*)/(.*)/(.*)$ search.php?q=$2&cat=$1&page=$3 [L]

I cannot make it working and the CSS / image files don't load.
I'd thank a lot who could give me a solution.

A: You can do this with four rules, one for each case:
RewriteRule ^([^/]+)$ search.php?q=$1
RewriteRule ^([^/]+)/([0-9]+)$ search.php?q=$2&p=$1
RewriteRule ^([^/]+)/([^/]+)$ search.php?q=$2&cat=$1&p=1
RewriteRule ^([^/]+)/([^/]+)/([0-9]+)$ search.php?q=$2&cat=$1&p=$3

And with this rule in front of the other rules, any request that can be mapped onto existing files will be passed through:
RewriteCond %{SCRIPT_FILENAME} !-f
RewriteRule ^ - [L]

Now your last issue, that externally linked resources cannot be found, is due to that you're probably using relative URL paths like css/style.css or ./css/style.css. These relative references are resolved from the base URL path that is the URL path of the URL of the document the references are used in. So in case /category/keyword is requested, a relative reference like css/style.css is resolved to /category/keyword/css/style.css and not /css/style.css. Using the absolute URL path /css/style.css makes it independent from the actual base URL path

A: While i know this was answered succinctly by @Gumbo a few months back, I ran into a similar issue recently... and didn't want to include full/absolute paths in my app, to keep it dynamic and not having a bunch APP_PATH (php) vars all over the place... so I just added a base[href] html tag with the

like so...
<base href="http://<?php echo $_SERVER[HTTP_HOST];?><?php echo APP_PATH;?>"/>

Hoping that helps others... and this is not trying to discount @Gumbo's reply in the least... they're right-e-o on :).

A: Shouldn't it be
RewriteCond %{SCRIPT_FILENAME} -f
RewriteRule ^ - [L]

in @Gumbo's answer above? Works with me like that. If it is a file (like CSS), let it pass through.


text:
Q: Can a struct become deallocated? I've declared a struct in my header file like this:
typedef struct {
NSString *department;
NSString *departmentId;
}  Department;

Department currentDepartment;

This struct is in a fairly simple class.  I assign the struct values in viewDidLoad. Just before leaving viewDidLoad, I see the struct values are still there. After the user clicks a segment control, I reassign the struct values.  Before assigning values, I see the two struct values are 0x0.  I do have NSZombieEnabled, which is printing out this when I mouse over the struct while the app is running and one of my breakpoints have been hit:
MyApp[25722:207] *** -[CFString _cfTypeID]: message sent to deallocated instance 0xfc0e90

I'm not creating an instance of the struct or deallocating it.  How can it be getting deallocated?

A: No, structs can be freed, but not unless you do that yourself somewhere in your code. What's being deallocated in this case is a string, as can be seen from the error message. Check the objects you're using when you set the department and departmentId members.
In fact, you need to be extra careful about memory management in general when you assign objects to struct members. In this case, you may need to send a -retain message to the strings, or change the way you're creating them so that you use alloc/init... or copy rather than stringWith... or other methods.

A: I strongly advise against putting objects in structs if at all possible. Structs are just dumb collections of data and cannot manage their members' memory like objects can with accessors. This means client code will have to take on the responsibilty of retaining and releasing the structs members whenever it deals with them and making sure they are released before the strict goes out of scope — it's not really that easy. You'd be better off creating a lightweight object.


text:
Q: I/O - Manipulation of C Strings I'd like to iterate through a string (entered by the user), returning the inputted string with an added space after each character (i.e. "Hello" --> "H e l l o ".
If I preset the value for str (i.e. char str[] = "Hello";) then the desired result is printed ("H e l l o "), but not so with user input (i.e. If the user inputs "Hello" the output is "H"). How does one successfully extract and manipulate a C string based on user input?
#include <stdio.h>
#include <string.h>

int main()
{
    char str[] = "";
    printf("\nEnter a string: ");
    scanf("%s", &str);

    printf("\nYou typed: %s \n", str);

    int i = 0;
    char newstr[150] = "";

    for (i = 0; i < strlen(str); i++)
    {
        newstr[2*i] = str[i];
        newstr[2*i+1] = ' ';
    }

    newstr[2 * strlen(str)] = '\0';

    printf("\nExpanded String: ");
    printf("%s", newstr);

    return 0;
}

A: Here:
char str[] = "";

the size of str is inferred from the initializer, which is in this case one byte large. Thus str cannot hold a string larger than one byte, and since the zero-terminator is one byte large, there is no more space for a payload. A fix is to specify a size:
char str[1024] = "";

Now str has enough space for a kilobyte of data, or 1023 characters in addition to the terminator. The size is deliberately chosen to be much larger than the input you expect.
In addition to this, it would be a good idea to prevent scanf from writing past the end of the buffer by including the size in the format string. That is
scanf("%1023s", str); // now scanf will not read more than 1023 bytes plus sentinel.

...and in turn, it would be a good idea to increase the size of newstr accordingly (to twice that of str), i.e.
char newstr[2047]; // 2 * 1023 + terminator

...or, you know, make str smaller, depending on how long a string you want to support.
Thanks to Cool Guy for catching the superfluous & and newstr size implications.

A: "How does one successfully extract and manipulate a C string based on user input?"
You can use getchar() instead.
For example, you can store the user input in an array first. Then the problem becomes the same as if you did your 'char str[] = "Hello":
int index = 0
while((temp1 = getchar())!= '\n'){
    str[index++] = temp1;
}

A: the following code
-complies cleanly
-checks and handles errors
-does the job
-doesn't use unneeded memory
 (well actually) the logic could be a loop
 that reads one char, outputs char, outputs space
 or something similar if a trailing space is a problem
 then the input buffer could be a single character

#include <stdio.h>
#include <stdlib.h> // exit, EXIT_FAILURE
#include <string.h>

int main()
{
    // char str[] = "";
    // there actually has to be room for the string
    char str[100] = {'\0'};

    printf("\nEnter a string: ");
    if( 1 != scanf("%s", str) ) // arrays degenerate to pointer so no extra '&' needed
    { // then scanf failed
        perror( "scanf failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    printf("\nYou typed: %s \n", str);

    // there is no need to keep the modified string in memory
    // when all that will be done is print it
    int i = 0; // loop counter

    printf("\nExpanded String: ");

    for (i = 0; i < strlen(str); i++)
    {
        printf("%c", str[i]);

        if( i < (strlen(str)-1) )
        { // then another char will follow
            printf( " " );
        }

        else
        {
            printf( "\n" );
        } // end if
    } // end for

    return 0;
} // end function: main


text:
Q: Disable SSL/TLS Renegotiation In Tomcat This is regarding the SSL/TLS Renegotiation issue. We are using Tomcat 7.0.47 as our web server for our application.
I tried many different ways to disable the renegotiation, but couldn't succeed.
We enabled SSL as follows in Server.xml file:
<Connector SSLEnabled="true"
           clientAuth="false"
           compressableMimeType="text/html,text/plain,text/xml,text/css,text/javascript,image/png,image/gif,image/jpeg,application/json"
           compression="on"
           compressionMinSize="2048"
           connectionTimeout="15000"
           debug="0"
           disableUploadTimeout="true"
           enableLookups="false"
           keyAlias="SomeAlias"
           keystoreFile="C:\.keystore"
           keystorePass="SomePassword"
           maxHttpHeaderSize="20480"
           maxSpareThreads="100"
           maxThreads="400"
           minSpareThreads="25"
           port="8443"
           protocol="HTTP/1.1"
           allowUnsafeLegacyRenegotiation=false
           scheme="https"
           secure="true"
           sslProtocol="TLS"
           tomcatAuthentication="false"/>

Here, I tried setting the option allowUnsafeLegacyRenegotiation=false but server is not able to start with this setting.

A: Unfortunately, the current JSSE implementation from Oracle doesn't provide any solution to your problem. But you can run an old Java (Java 6 update 19/20/21) as it explained in the JSSE Reference Guide table 7, since these versions called "phase 1 Fix" allowed to completely remove renegotiation support.
Considering that the old Java versions had other problems and you probably don't want to run them, the most secure is to only allow the newest renegotiations (RFC 5746). For this, as explained in JSSE Reference Guide table 9, set these two system properties to false : allowLegacyHelloMessages , allowUnsafeRenegotiation.
And remove allowUnsafeLegacyRenegotiation connector attribute which is no more usefull.


text: Q: Package babel error - bbding.sty not found I am a new user to ubuntu. I installed latex as I had it before (I was a windows user). This document was perfectly fine in windows, no error. And now I tried to open the same document in ubuntu and there appears some error. I have no idea why and how to fix it. And I don't think the problem is in the "usepackage{bm}", because if I delete it, the red line appears in the other line. Thank you for your advices.


text:
Q: Is is possible to develop an app to record phone conversations for iPhone? Is it possible to develop an app to handle an incoming phone call for iPhone? I mean, I'm thinking to develop an app to record phone conversation for both outgoing and incoming calls.
If it is an outgoing call, can user make a standard phone call and the voice conversation be recorded?
If it is an incoming call, can app be opened/activated when there is an incoming call and the user talk while the conversation is recorded?
(There is a Core Telephone Framework:
 but I don't know if it would help.)
Can anyone advise?

A: Ignoring legal implications, it is not possible over their provider's network.
(ex: Verizon)

This article goes into a little more detail.


text:
Q: Problem when waking the computer from sleep mode I have a HP Pavilion dv6-2188la and when it wakes from sleep the monitor flashes (screen flickers), and every time it flashes (2 seconds) it returns me to the beginning of the password field making it almost impossible input the password.
Does anyone knows what causes this problem?
More info: Intel Core i5-430M processor, Nvidia GeForce G 105M, 500GB HDD, 4GB RAM.

A: What version of Windows are you using?  If you have the install disc, you may want to reinstall...  Or, possibly, it's the screen resolution settings.  If you can log in and try to adjust these, then induce the flicker, see if that helps.


text:
Q: IDE for Corona SDK for Mac
I am Just started with Corona SDK and could not find any IDE with proper Corona SDK. Can any one list out the IDE for the Corona SDK for Mac.

A:
The Corona SDK IDE's are

*

*sublime text. source1

*coronaprojectmanager source2

*Lua Glider source3

*ZeroBrane Studio source4

A: Lua Glider is the best, Am using it since a year am master in that and can help you in that please ask if want any help.

A: I would highly recommend sublime text 2 due to the fact that Corona Labs now officially supports it. Plus just yesterday, Corona updated and has this cool snippets that allow sample code to be added via a GUI.
Check it out: http://coronalabs.com/blog/2013/12/11/corona-editor-is-now-1-0/

A: Check out Visual Studio Code – a free text editor from Microsoft
https://code.visualstudio.com/

*

*It runs on OS X
While the full Visual Studio IDE is a Windows-based tool, Visual Studio Code has a native version for OS X. If you're comfortable with the IDE in Windows, you'll feel right at home when working in OS X.

*It supports Corona SDK
Code highlighting is part of the standard Visual Studio Code editor, and an optional extension called Corona Tools brings Corona's documentation to the editor. Installing the extension gives you keyboard shortcuts to either open or search Corona Labs' documentation. While this is currently a new extension with limited functionality, feel free to reach out to the developer, Tobiah Zarlez, to request additional features.


text:
Q: VS2017: multiple asp.net core projects debug We are migrating our project www.SampleProject.com from VS2013 into VS2017, also considering upgrade into ASP.NET Core. Project has following structure:

*

*some class library projects (BLL and DAL)

*API (WebAPI2 project)

*UI (asp.net project with NG 1.4 used)

During debug:

*

*Primary start-up project is UI, starting on localhost:52000

*Second start-up project is API, starting on localhost:52000/API/

Such configuration allows us to debug both projects simultaneously, which is handy.
Also, this separation allows us to deploy API as separate REST API service (api.SampleProject.com) and also use API internally for UI (app.SampleProject.com/api)
In production environment, 'internal API' is configured in IIS as nested application in UI project.
However, this is not working with ASP.NET Core and VS2017.
Is there any known way how to debug two ASP.NET Core projects on same port (as described above)?
Thanks a lot


text:
Q: Web scraping using python for multiple pages I have a beautifulsoup parser to get all content of html. How do i scrape the web  when it hs multiple pages. like,
myurl  = "https://www.mybanktracker.com/ABC-Bank/Reviews"
the url has 20 off pages like
https://www.mybanktracker.com/ABC-Bank/Reviews/pages/1
https://www.mybanktracker.com/ABC-Bank/Reviews/pages/2 and so on.
How do i extract all the pages infro into one? or any other easier way to do so?

A: I've been examining the series of pages that begin with https://www.mybanktracker.com/TD-Bank/Reviews. The formatting of the top of first page appears to differ somewhat from that of the second and subsequent pages. I will therefore assume that you are arranging to parse all of the pages in such a way as to capture information below the heading 'Latest  Reviews'.
I suggest that you process pages in a while loop. It's likely that the number of pages of reviews differs from one bank to another. Rather than trying to recover the number of pages you could just keep requesting pages until you get an empty page. (I've found that a request for 'page 52' in this series yields a page with no reviews.) Here is some pseudo-code.
URL = https://www.mybanktracker.com/TD-Bank/Reviews
pageNumber = 1
while True:
    fetch, parse and store information from one page
    if no reviews found in page then break
    pageNumber += 1
    URL = https://www.mybanktracker.com/TD-Bank/Reviews/page/pageNumber


text:
Q: Problem with QVariant/QTreeWidgetItem/iterator on qt4.4.3 In my qt app I have this object, filled before setting up my QTreeWidget's content:
QList<QTreeWidgetItem*> items;

I fill the QList by this way:
QVariant qv; // I need this for "attaching" to the item my linuxPackage object
qv.setValue(linuxPackage);
packRow->setData(1, Qt::UserRole,qv); // packRow is my own object inherited from QTreeWidgetItem, I "put" the QVariant into it
items.append(packRow); // then I put my item into the QList

at the end of the work, my QList has almost 1000 items.
I need to iterate over them and for each item I need to get the "linuxPackage" data by this (tested and working) way:
Pkg linuxPackage = this->data(1,Qt::UserRole).value<Pkg>(); // Pkg is my own class for the linuxPackage object

So, I've been trying to extract needed data by this manner:
QList<QTreeWidgetItem*>::iterator iter;
for (iter = items.begin(); iter != items.end(); ++iter){
    Pkg pack = iter->data(1,Qt::UserRole).value<Pkg>();
}

But nothing works, I can not even get the program compiling. Help! :D

A: Perhaps:
(*iter)->data(1,Qt::UserRole).value<Pkg>();

BTW, an easier way of doing this with Qt4:
foreach (const QTreeWidgetItem *item, items) {
    Pkg pack = item->data(1,Qt::UserRole).value<Pkg>();
}

at the very least, you should use const_iterators =)
QList<QTreeWidgetItem*>::const_iterator iter;
for (iter = items.constBegin(); iter != items.constEnd(); ++iter){
    ...
}


text:
Q: how to get specific field in serialiser with related_name by Django rest i have model named ContactPhone and in the model link to Lead model with field lead_id and ralated_name phones
class ContactPhone(models.Model):
    phone_number = PhoneNumberField(blank=True, default='')
    phone_type = models.CharField(
        max_length=100,
        blank=True,
        choices=ContactPhoneInterface.phone_number_types,
        default=PhoneNumbers.mobile.name
    )
    contact_id = models.ForeignKey(
        Contact,
        on_delete=models.CASCADE,
        null=True,
        related_name='phones_c'
    )
    lead_id = models.ForeignKey(
        Lead,
        on_delete=models.CASCADE,
        null=True,
        related_name='phones'
    )

by this serilizer class i got id of ContactPhone table, but i need got phone_number field in ContactPhone.
class LeadListSerializer(serializers.ModelSerializer):

    class Meta:
        model = Lead
        fields = (
            'id',
            'full_name',
            'responsible_id',
            'phones',
            'emails',
        )

tried different options to solve this problem but it doesn't help. In the screenshot you can see response of this moment, id of ContactPhone

A: If you want to return a list of specific fields from a related model you can use a serializers.SlugRelatedField
class LeadListSerializer(serializers.ModelSerializer):

    phones = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='phone_number'
    )

    class Meta:
        model = Lead
        fields = (
            'id',
            'full_name',
            'responsible_id',
            'phones',
            'emails',
        )

EDIT: The ContactPhone.phone_number field is not serializable
One option is to set the __str__ method of the ContactPhone model to return the phone number and use a StringRelatedField
class ContactPhone(models.Model):
    ...

    def __str__(self):
        return str(self.phone_number)

class LeadListSerializer(serializers.ModelSerializer):

    phones = serializers.StringRelatedField(
        many=True,
        read_only=True,
    )

    class Meta:
        model = Lead
        fields = (
            'id',
            'full_name',
            'responsible_id',
            'phones',
            'emails',
        )

Or adding a property that returns the string of phone_number to the ContactPhone model and using that in a SlugRelatedField is potential option
class ContactPhone(models.Model):
    ...

    @property
    def phone_number_str(self):
        return str(self.phone_number)

class LeadListSerializer(serializers.ModelSerializer):

    phones = serializers.SlugRelatedField(
        many=True,
        read_only=True,
        slug_field='phone_number_str'
    )

    class Meta:
        model = Lead
        fields = (
            'id',
            'full_name',
            'responsible_id',
            'phones',
            'emails',
        )


text:
Q: Error 'Cannot recognize current file path' occurred when using syncfusion When trying to open an existing docx file by using suncfusion ,

WordDocument document = new WordDocument(filename.docx);

"Cannot recognize current file path" error occurred.
Stack Trace: at Syncfusion.DocIO.DLS.WordDocument.WordDocumentType(String fileName, String password)
But I don't want a password to open this document.

A: You should give full path instead of providing the file name alone. Please refer below code:
WordDocument document = new WordDocument(@"D:\XXX\FileName.docx");

Also ensure that the file exists in corresponding path.


text:
Q: Loading a texture using OpenGL I am trying to load a texture via OpenGL for a 2d platformer and the code seems to be crashing on this exact part, but the lack of knowledge in C++ or openGL seems to be my problem, pls help!
bool Texture::LoadTextureFromFile( std::string path )
{
    //Texture loading success
    bool textureLoaded = false;

    //Generate and set current image ID
    GLuint imgID = 0;
    glGenTextures( 1, &imgID );
    glBindTexture(GL_TEXTURE_2D ,imgID );

    //Load image
    GLboolean success = glLoadTextures( path.c_str() );

    //Image loaded successfully
    if( success == GL_TRUE )
    {
        //Convert image to RGBA
        // success = ilConvertImage( IL_RGBA, IL_UNSIGNED_BYTE );
        if( success == GL_TRUE )
        {
            //Create texture from file pixels
            textureLoaded = LoadTextureFromPixels32
            ( (GLuint*)glGetDoublev, (GLuint*)glGetIntegerv( GL_TEXTURE_WIDTH ), GLuint*(glGetIntegerv( GL_TEXTURE_HEIGHT )) );
        }

        //Delete file from memory
        glDeleteTextures( 1, &imgID );
    }

    //Report error
    if( !textureLoaded )
    {
        printf( "Unable to load %s\n", path.c_str() );
    }

    return textureLoaded;
}

A: There are a few possible issues.
Firstly, where do you get glLoadTextures() from? And what does it do? That's not part of the OpenGL specification. It's not clear to me what it does. It's possible that this function does the entire texture loading for you, and the code below just screws things up.
Next, your first parameter to LoadTextureFromPixels32() is glGetDoubleV. You're passing it a pointer to the function glGetDoubleV, which is definitely NOT right. I assume that parameter expects a pointer to the loaded image data.
Finally, your code deletes the texture you just created with glDeleteTextures(). That makes no sense. Your texture object's ID is stored in imgID, which is a local variable. You're deleting it so the texture's gone.
The normal procedure for creating a texture is:

*

*Load the texture data (using something like SDL_image, or another image loading library)

*Create the texture object using glGenTextures(); NOTE: This is your handle to the texture; you MUST store this for future use

*Bind it glBindTexture()

*Load in the image data glTexture2D()

That's it.


text:
Q: Is there a single word that defines time is on your part/side/favor? These past few days I have had this kind of "luck": every time I'm not ready for something, it has ended up being cancelled. For instance, a surprise quiz came up for which I was not at all prepared, but by some "luck" there was a sudden suspension of class.
Just out of curiosity, I want to know if there's a single word to describe this kind of luck in which time is in your favor.

A: You might consider serendipity.  NOAD says:

serendipity (n.): the occurrence and development of events by chance in a happy or beneficial way

Alternatively, you could also say these are fortuitous events.  Macmillan defines fortuitous as:

fortuitous (adj.): happening by chance, especially in a way that is lucky or convenient

These words aren't restricted to incidents when "time is in your favor," as was mentioned in your original question, but having especially good timing through sheer blind luck could be one way to experience serendipity.

A: Deus ex machina. Try this. It means, an unexpected power or event saving a seemingly hopeless situation, (especially as a contrived plot device in a play or novel).


text:
Q: How to prove contrapositive of this statement on compact metric spaces I read the following:

Given $E$ and $F$ as metric spaces and $\hat{E}$ and $\hat{F}$ as their completion, any uniformly continuous function $\phi : E \rightarrow F$ admits a unique uniformly continuous extension $\hat{\phi}: \hat{E} \rightarrow \hat{F}$. Furthermore, if $\hat{E}$ is compact and $\phi$ is surjective, then $\hat{\phi}$ is surjective.

I would like to ask, is there a proof for this statement that uses the contrapositive ? i.e.

$\hat{\phi}$ is not surjective $\implies$ $\hat{E}$ is not compact or ${\phi}$ is not surjective

To show $[\hat{\phi}$ is not surjective $\implies$ $\phi$ is not surjective $]$ is one part, but how about the other part of the statement, i.e. that if $\hat{\phi}$ is not surjective, it can be that $\phi$ is surjective but $\hat{E}$ is not compact ?

A: Your contrapositive has the form $p\to(q\lor r)$. The usual way to prove such an implication is to prove $(p\land\neg q)\to r$ or $(p\land\neg r)\to q$. In this case that means proving either that if $\widehat\varphi$ is not surjective and $\varphi$ is, then $\widehat E$ is not compact, or that if $\widehat\varphi$ is not surjective and $\widehat E$ is compact, then $\varphi$ is not surjective. The first of these possibilities looks a bit more promising, so let's start there.
If $\widehat\varphi$ is not surjective, fix $y\in\widehat F\setminus\widehat\varphi[\widehat E]$, and let $\langle y_n:n\in\Bbb N\rangle$ be a sequence in $F$ converging to $y$. If $\varphi$ is surjective, there is a sequence $\sigma=\langle x_n:n\in\Bbb N\rangle$ in $E$ such that $\varphi(x_n)=y_n$ for each $n\in\Bbb N$. If some subsequence of $\sigma$ converged to some $p\in\widehat E$, we would have $\widehat\varphi(p)=y$, which is impossible, so $\sigma$ has no convergent subsequence in $\widehat E$, and therefore $\widehat E$ is not compact.
What about the other possibility? As before, if $\widehat\varphi$ is not surjective, fix $y\in\widehat F\setminus\widehat\varphi[\widehat E]$, and let $\langle y_n:n\in\Bbb N\rangle$ be a sequence in $F$ converging to $y$. If $\widehat E$ is compact, then $\widehat\varphi[\widehat E]$ is compact and hence closed in $\widehat F$, so $\widehat F\setminus\widehat\varphi[\widehat E]$ is an open nbhd of $y$, and there is an $m\in\Bbb N$ such that $y_n\in\widehat F\setminus\widehat\varphi[\widehat E]$ whenever $n\ge m$. And each $y_n\in F$, so in fact $y_n\in F\setminus\widehat\varphi[\widehat E]\subseteq F\setminus\varphi[E]$ whenever $n\ge m$, and $\varphi$ is therefore not surjective.
So in this case both of the natural alternatives for proving the contrapositive in question turn out to be pretty straightforward.


text:
Q: Passing string from child tab activity to parent tab I have an  activity name "Tabs". It launches 4 different tabs , each with its own activities. It uses :
th = (TabHost) findViewById(R.id.tabhost);
    th.setup(this.getLocalActivityManager());
    TabSpec specs = th.newTabSpec("Tag1");
    Intent tabSelection = new Intent (this, ProfileSettings.class);

    tabSelection.putExtras(gotSettings);
    specs.setContent(tabSelection);
    specs.setIndicator("Settings",
            getResources().getDrawable(R.drawable.ic_menu_friendslist));
    th.addTab(specs);

    specs = th.newTabSpec("Tag2");
    tabSelection = new Intent (this,InternationalRoamingService.class);
    specs.setContent(tabSelection);
    specs.setIndicator("IRS", getResources().getDrawable(R.drawable.ic_menu_mapmode));
    th.addTab(specs);

    specs = th.newTabSpec("Tag3");
    tabSelection = new Intent (this,Call.class);
    specs.setContent(tabSelection);
    specs.setIndicator("Call", getResources().getDrawable(R.drawable.call));
    th.addTab(specs);

    specs = th.newTabSpec("Tag4");
    tabSelection = new Intent (this,WebSMS.class);
    specs.setContent(tabSelection);
    specs.setIndicator("SMS", getResources().getDrawable(R.drawable.ic_menu_start_conversation));
    th.addTab(specs);

I have no problems in passing the bundle "gotSettings" from the parent to the child. But how do I update the value of the bundle from the child activity OR pass a value from the child to the parent?

A: There is two way for you :

*

*You can use StartActivityForResult ,This is an example for it : http://www.vogella.com/articles/AndroidIntent/article.html#usingintents_sub

*Another way is using a static parameter, you change it in your child activity and then use it in your parent activity. For example : Add this line in your child activity with 'ChildActivity' Class name public static int myValue; then set a parameter to it myValue=25; and use it in your parent activity : myChildValue=ChildActivity.myValue;


text:
Q: typedef'ing an enum does not make the enum-values visible I have a class in which I have an enumeration, defined like this:
class X
   {
   public:
      enum Direction {DIR_LEFT, DIR_RIGHT};
   };

Now I want this enumeration to be reused in another class, like this:
class Y
   {
   public:
      typedef X::Direction Direction;
   };

As expected, using Y::Direction works correctly, e.g.:
void myFunction (Y::Direction dir)
{
}

But the values within the enumeration does not seem to be 'copied' together with the typedef.  If I write the following, I get compilation errors:
myFunction (Y::DIR_LEFT);

Instead, I have to refer to the original place of the enumeration again, like this:
myFunction (X::DIR_LEFT);

Which defeats my purpose of typdefing the enumeration.
The only solution I see is to move the enumeration out of class X, and putting it in another class (e.g. MyEnums), so it can be reused by X and Y (although they should still use MyEnums::DIR_LEFT and MyEnums::DIR_RIGHT), but at least the code does not depend on class X anymore.
Why are the enumeration values itself no exposed via the typedef?
Are there any other patterns to manage enumerations in different classes?

A: Unfortunately C++ doesn't introduce a new scope with an enum although C++0x is improving things.
Practically this means that you can't typedef an enum and get the enumerated values as well.
What you can do is use a nested struct with the name you want for the enum and typedef THAT.
class X
{
public:
    struct Direction { enum EnumType {LEFT, RIGHT}; };
};

class Y
{
public:
    typedef X::Direction Direction;
};

Now you can do:
myFunction (Y::Direction::LEFT);
The purpose of the nested struct is to create a "fake" scope to holld both the enum name and its values.

A: Here is my understanding of how enums work in C++. (Or at least my observed behaviour of enums in Microsoft Visual C++.)
The enum keyword does not create a scope the same way that classes do.
The full name then for your enum 'Direction', is X::Direction. The values within that enum are still part of the class scope, so they are X::DIR_LEFT and X::DIR_RIGHT.
When you typedef the enum in another class, this does not change the scope of the values of the enum.
I suggest you put the enum inside a namespace in a header file if you want to share it in multiple locations.

A: If you want the enum values to be members of both classes, the
solution is to define a separate class with the enum, and
inherit from it, e.g.:
class MyEnums
{
protected:
    ~MyEnums() {} //  Prevent delete through pointer to this class
public:
    enum Direction
    {
        DIR_LEFT,
        DIR_RIGHT
    };
};

class X : public MyEnums
{
    // ...
};

class Y : public MyEnums
{
    // ...
};

Users will see X::Direction, X::DIR_LEFT and Y::Direction,
Y::DIR_LEFT.  Of course, they'll still be able to pass
a Y::DIR_LEFT to a function expecting an X::Direction; to
prevent that, make MyEnums a template, with the derived class as
the template argument.

A: Anything shared by more than one class should be factored outside of the classes and perhaps into a parent class.
direction.hpp:
#ifndef DIRECTION_HPP
enum Direction {DIR_LEFT, DIR_RIGHT};
#endif

x.hpp:
#ifndef X_HPP
#include "direction.hpp"

class X
{
  Direction dir;
};
#endif // X_HPP

y.hpp
#ifndef Y_HPP
#include "direction.hpp"

class Y
{
  Direction dir;
};
#endif // Y_HPP

A: If the original declaration:

    class X
    {
    public:
      enum Direction {DIR_LEFT, DIR_RIGHT};
    };

is embedded in a large legacy code-base, then we might want a solution that does not change any existing uses of X::Direction. In that case, the rather ugly:

    class Y
    {
    public:
       typedef enum X::Direction Direction;
       static const enum X::Direction DIR_LEFT = X:DIR_LEFT;
       static const enum X::Direction DIR_RIGHT = X:DIR_RIGHT;
    }

works...
Definitely not recommended for new code, however!


text:
Q: How to convert a JSONObject to a String Array or ArrayList in android I'm going to get the values of a JSONObject and put it in a String Array or ArrayList. the Problem is that I have a JSONObject not a JSONArray, and I can't change the Webservice.
This is my JSONObject:
{"THR":"تهران",
"MHD":"مشهد",
"KIH":"کیش",
"IFN":"اصفهان",
"SYZ":"شیراز",
"TBZ":"تبریز",
"ABD":"آبادان"}
And this is my code:
    ProgressBar progressbar = (ProgressBar) findViewById(R.id.progressbar);
    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

    progressbar.setVisibility(View.VISIBLE);
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Toast.makeText(getApplicationContext(), "Response", Toast.LENGTH_SHORT).show();
            progressbar.setVisibility(View.GONE);

            try {
                JSONArray array = new JSONArray(response);
                Toast.makeText(getApplicationContext(), "Try", Toast.LENGTH_LONG).show();
            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Catch", Toast.LENGTH_LONG).show();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
            progressbar.setVisibility(View.GONE);
        }
    });

    queue.add(stringRequest);

when I debug my code, it goes to CATCH!!!
It doesn't go to TRY, anyway!
I want something like this:
String[] strArray = {"تهران","مشهد","کیش","اصفهان","شیراز","تبریز","آبادان"};

How can I get it?

A: public static void main(String[] args) {
//building your jsonObject(took only the 1st four ;P )
        JSONObject objJsonObject = new JSONObject();
        objJsonObject.put("THR", "تهران");
        objJsonObject.put("MHD", "مشهد");
        objJsonObject.put("KIH", "کیش");
        objJsonObject.put("IFN", "اصفهان");
        String [] strArray= new String[objJsonObject.length()];
        int i = 0;
//adding your required data into a array
        for (String key: objJsonObject.keySet()) {
            strArray[i] = objJsonObject.getString(key);
            i++;
        }
//printing your data
        for (int j = 0; j < strArray.length; j++) {
            System.out.println(strArray[j]);
        }
}

hope this helps....

A: added changes to your code
ProgressBar progressbar = (ProgressBar) findViewById(R.id.progressbar);
    RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
    ArrayList<String> answersStringArray= new ArrayList<String>(); // define string array

progressbar.setVisibility(View.VISIBLE);
    StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            Toast.makeText(getApplicationContext(), "Response", Toast.LENGTH_SHORT).show();
            progressbar.setVisibility(View.GONE);

            try {
                JJSONObject jsonObject = new JSONObject(response); //cast responce to jsonObject
                Iterator<?> keys = jsonObject.keys(); // get the keys of the jsonObject
                while( keys.hasNext() ) {//iterrate over them
                    String key = (String)keys.next();
                    answersStringArray.add(jsonObject.optString(key));}// add the string to our array of stings

          } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Catch", Toast.LENGTH_LONG).show();
            }

        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_SHORT).show();
            progressbar.setVisibility(View.GONE);
        }
    });

    queue.add(stringRequest);


text:
Q: Regex find instance of dash, but not dash I am sooo close. I am trying code a regex expression for Notepad++ to replace a dash with a space, ignoring dashes already with a pre/post space. I realize I could search/replace " - " with "foobarfoo" then search for "-" replacing for " " then converting "foobarfoo" back to " - ", but damnit - I'm trying to learn regex!
Here's my problem:

Adapter - BNC Male to BNC-Female, Right Angle

to

Adapter - BNC Male to BNC Female, Right Angle

(note the disappearing dash in "BNC Female")
The closest I am getting is using this:
/(?:[^( )])\-(?:[^( )])/g
but that results with it finding the single letter ahead, the dash, and the single letter following:

Adapter - BNC Male to BNC-Female, Right Angle

WHY is it selecting the pre/post characters? Is this not:
(?:[^( )])  find anything except a space (as a noncapturing group)...
\-      ... that follows with a dash ...
(?:[^( )])  ... and is followed by anything except a space(as a noncapturing group)
I get even closer is I replace the first term with (?=[^( )]) but if I change the third term to (?![^( )]) I'm back to where I started - just selecting the dash in between the two spaces. GRRRR.
More samples here at http://regexr.com/444i2

A: The most readable option for Notepad++ is an alternation based regex with a conditional replacement pattern:
Find What: (\s-\s)|-
Replace With: (?1$1: )
The (\s-\s)|- pattern either captures into Group 1 a whitespace, - and a whitespace, or just matches -. If Group 1 matches, its value is pasted back where it was (=this match is skipped), else the - in other contexts is replaced with a space.
See a demo below:

Another option is using nested lookarounds:
Find What: -(?<!\s-(?!=\s))
Replace With:   (a space)
The pattern matches:

*

*- - a hyphen

*(?<!\s-(?!=\s)) - this negative lookbehind fails the match if its pattern matches the following pattern immediately to the left of the current location (that is, right after -):

*

*\s - a whitespace

*- - a hyphen (this is necessary to make sure we get to the same place where the lookbehind was triggered)

*(?!=\s) - the next char is a whitespace (this is a lookahead, it is not possible to make it a simple \s as we cannot let the lookbehind move its pattern position matching, i.e. we can't let it try \s-\s before and including - (it would result in a true result).

A: To ignore dashes already with a pre/post space you could use positive lookarounds to assert that what is on the left and on the right are a non whitespace character \S
In the replacement use a space.
(?<=\S)-(?=\S)
Regex demo

A: Use \w(-)\w to replace all hyphens surrounded by alphabetic characters, digits and underscores, or [^ ](-)[^ ] to replace all hyphens surrounded by non-space characters.
Both work fine in my Notepad++ version with all of your examples.


text:
Q: How do I stop a Google Cloud's AutoML (now VertexAI) batch prediction job using the web GUI? I started a batch prediction job in AutoML (now VertexAI) for a small csv in one of my buckets, using a classification model, then I noticed the csv had an error but was unable to find a way to cancel the job using the web GUI, it just says "running" but I see no "stop" or "cancel" button.
Fortunately, it was done after 20 minutes, but I need to know how to stop a job since I will require predictions for way bigger files and can't risk having to wait until the job ends by itself. It was kind of desperating being able to watch the log throwing error after error and not being able to stop the job. I tried to delete the job but it said it can't be deleted while its running.
I found a related question, but it was not answered, the job just finished itself after a couple of days. I can't risk that.
How do I force "batch prediction" to stop?
I will greatly appreciate any help.

A: Unfortunately the cancel/stop feature is not yet available in the Vertex AI UI. As per How do I force "batch prediction" to stop?, the OP sent a feedback. You can ask if there was a public issue tracker created for this so you can monitor the progress of the feature request there.
But there is a workaround for this, just send a request projects.locations.batchPredictionJobs.cancel via REST.
To do this you can send a request via curl. In this example the model and endpoint are located in us-central1 thus the location defined in the request.
Just supply your project-id and the batch-prediction-id on the request. To get the batch-prediction-id you can get it via UI:
Get batch-prediction-id via UI:

*

*Open "Batch Predictions" tab in the Vertex AI UI

*Click on the job you want to cancel

*Job information will be displayed and the 1st entry will contain the Job ID

To cancel the job send a cancel request via curl. If requests is successful, the response body is empty.
curl -X POST -H "Content-Type: application/json" \
-H "Authorization: Bearer "$(gcloud auth application-default print-access-token) \
https://us-central1-aiplatform.googleapis.com/v1/projects/your-project-id/locations/us-central1/batchPredictionJobs/batch-prediction-job-id:cancel

Check in Vertex AI UI if the job was canceled.


text:
Q: Loop through time values in a raster brick in R I have raster bricks of temperature and rainfall consisting of one layer for each month of the year.  The raster brick looks like this:
> tmx
class      : RasterBrick
dimensions : 3875, 8017, 31065875, 240  (nrow, ncol, ncell, nlayers)
resolution : 0.04490319, 0.04490319  (x, y)
extent     : -180.0393, 179.9495, -90.04088, 83.95898  (xmin, xmax, ymin, ymax)
crs        : +proj=longlat +datum=WGS84 +ellps=WGS84 +towgs84=0,0,0
source     : /scratch/bntjoa002/chelsa_cmip5_ts/tasmax/CHELSAcmip5ts_tasmax_ACCESS1-3_rcp8                                      5_2070-2089.nc
names      : X2070.01.15, X2070.02.15, X2070.03.15, X2070.04.15, X2070.05.15, X2070.06.15,                                       X2070.07.15, X2070.08.15, X2070.09.15, X2070.10.15, X2070.11.15, X2070.12.15, X2071.01.15                                      , X2071.02.15, X2071.03.15, ...
Date       : 2070-01-15, 2089-12-15 (min, max)
varname    : air_temperature

I have been using the following code to get the average monthly values for a specified period (e.g. resulting in 12 averaged layers, one for each month, over a X year period):
new_tmx <- subset(tmx, which(getZ(tmx) >= as.Date("2070-01-15") & getZ(tmx) <= as.Date("2089-12-15")))
indices <- format(as.Date(names(new_tmx), format = "X%Y.%m.%d"), format = "%m")
indices <- as.numeric(indices)
Monthlytmx<- stackApply(new_tmx, indices, fun = mean)

I do this separately for the maximum temperature, minimum temperature, and precipitation bricks.
What I need now is to do the same process, but instead to output one raster layer for each year consisting of the averaged values for one-year periods (i.e. for 2070, 2071, 2072...).
I've only done very simple loops in R, and I'm not sure how to deal with the time/date function in this example?

A: I think what you need to do is create a new index from the year in the date - you can use the "format" function on a date to get the year out:
> indices = format(getZ(tmx),"%Y")
> indices
  [1] "2070" "2070" "2070" "2070" "2070" "2070" "2070" "2070" "2070" "2070"
 [11] "2070" "2070" "2071" "2071" "2071" "2071" "2071" "2071" "2071" "2071"
 [21] "2071" "2071" "2071" "2071" "2072" "2072" "2072" "2072" "2072" "2072"
...

then stackApply with that:
> Yearlytmx<- stackApply(new_tmx, indices, fun = mean)
> Yearlytmx
class      : RasterBrick
dimensions : 3, 4, 12, 20  (nrow, ncol, ncell, nlayers)
resolution : 0.25, 0.3333333  (x, y)
extent     : 0, 1, 0, 1  (xmin, xmax, ymin, ymax)
crs        : NA
source     : memory
names      : index_2070, index_2071, index_2072, index_2073, index_2074, index_2075, index_2076, index_2077, index_2078, index_2079, index_2080, index_2081, index_2082, index_2083, index_2084, ...
min values :  0.2871428,  0.3901444,  0.3483226,  0.2906245,  0.2947116,  0.3599598,  0.3503530,  0.3295298,  0.4077774,  0.3867792,  0.3916475,  0.3714683,  0.3746881,  0.3817867,  0.3694289, ...
max values :  0.6998091,  0.6197922,  0.6100803,  0.5943091,  0.6323317,  0.6812757,  0.7028588,  0.6113572,  0.5682294,  0.6368843,  0.6010818,  0.6163263,  0.6534441,  0.5922601,  0.5980651, ...

That brick now has 20 layers, which should be one for each year.
You can then add the year as a Z to the data:
> Yearlytmx = setZ(Yearlytmx,unique(indices),"Year")

Or use the "names", which have an "index_" attached to them:
> names(Yearlytmx)
 [1] "index_2070" "index_2071" "index_2072" "index_2073" "index_2074"
 [6] "index_2075" "index_2076" "index_2077" "index_2078" "index_2079"
[11] "index_2080" "index_2081" "index_2082" "index_2083" "index_2084"
[16] "index_2085" "index_2086" "index_2087" "index_2088" "index_2089"


text:
Q: SendGrid (PHP library) with attachments I have a simple SendGrid API setup but I am wondering how I can include attachments in the email that gets sent. I am passing the attachment URL into the $_POST variable so can return the full path but unsure where to include it in my setup.
//
$i = 1; foreach ($cart as $download) {

    $file . $i = $download['download'];
    $file_encoded . $i = base64_encode(file_get_contents($file));
    $attachment . $i = new SendGrid\Attachment();
    $attachment . $i->setContent($file_encoded);
    $attachment . $i->setType("application/zip");
    $attachment . $i->setDisposition("attachment");
    $attachment . $i->setFilename("test.zip");
    $mail->addAttachment($attachment . $i);

    i++;

}

// Set email confirmation settings
$email_subject = 'New order from ' . $user_details['first-name-billing'] . ' ' . $user_details['last-name-billing'] . ' via www.***.com';
$email_admin = '******@***.com'; // Client
$email_customer = $user_details['email'];

ob_start();
    require_once './email-confirmation.php';
    $email_body = ob_get_contents();
ob_end_clean();

// Send to confirmation to admin
if ($email_admin) {
    send_email($email_admin, $email_admin, $email_subject, $email_body);
}

// Send confirmation to customer
if ($email_customer) {
    send_email($email_admin, $email_customer, $email_subject, $email_body);
}

// SendGrid init
function send_email($from_email, $to_email, $subject, $body) {
    global $sgAPIKey;
    $from = new SendGrid\Email(null, $from_email);
    $to = new SendGrid\Email(null, $to_email);
    $content = new SendGrid\Content("text/html", $body);
    $mail = new SendGrid\Mail($from, $subject, $to, $content);
    $sg = new \SendGrid($sgAPIKey);
    $response = $sg->client->mail()->send()->post($mail);
}

A: Use the SendGrid\Attachment class. A complete example can be found in the documentation:
$filename = basename($url);
$file_encoded = base64_encode(file_get_contents($url));
$attachment = new SendGrid\Attachment();
$attachment->setType("application/text");
$attachment->setContent($file_encoded);
$attachment->setDisposition("attachment");
$attachment->setFilename($filename);
$mail->addAttachment($attachment);

A: $textMessageModel = new TextMessage;
$leadActivityModel = new LeadRecordActivity;
$leadsModel = new Leads;
$sentEmailModel = new SentEmail;
$userDetailsModel = new UserDetails;
$to = $request->input('to');
$filename = $request->input('filename');
$contentFile = $request->input('fileContent');
$from = $request->input('from');
$content = $request->input('content');
$subject = $request->input('subject');
$leadId = $leadsModel->fetchLeadEmailByUserIdData($to);
$fromName = $userDetailsModel->fetchUserDetails(Session::get('user_id'))->full_name;

$email = new \SendGrid\Mail\Mail();
$email->setFrom($from, $fromName);
$email->setSubject($subject);
$email->addTo($to, "");
$email->addContent(
        "text/html", $content
);

    // $file_encoded = (''.$contentFile.'');

    foreach( $filename as $index => $code ) {
        $email->addAttachment(
            ''.$contentFile[$index].'',
            "application/json",
            $filename[$index],
            "attachment"
        );
 }

$sendgrid = new \SendGrid(env('SENDGRID_API_KEY'));
try {
        $response = $sendgrid->send($email);
} catch (Exception $e) {

}


text:
Q: Can I specify in a SQLite query that a column have ANY value? I'm trying to design a feature where the user can specify what data they get back from a query. Below are the search options to the end user.

*

*Players with a contract (non-null contractId)

*Players without a contract (null contractId)

*All Players (null or non-null contractId)

I'd like to make a function that can take a String and plug it into a query to return the desired data set.
public ArrayList<Player> getPlayers(String contractFilter) {
    String query = "... WHERE player.ContractId is " + contractFilter;
}

With this design, I can pass in contractFilter = "null" or contractFilter = "not null".  Is there something I can pass in for the 3rd condition (null OR non-null)? Something like contractFilter = "any"?

A: IMHO, the best solution is to simply not include the column in your WHERE clause. If you use something like SQLiteQueryBuilder, just skip that appendWhere() call when the condition is "any".
You can try to hack around this:

*

*Use column_name IS NULL OR column_name IS NOT NULL

*Use column_name LIKE '%'
However, there is a decent chance that these will perform worse. Ideally, SQLite's query planner will detect the "any" case and optimize it away, but I would not assume that to be the case.


text:
Q: Exporting OpenLayers.Layer.WMS to GeoJSON / KML I'm looking the way to exporting an especific region of a WMS layer to some XML format (GeoJSON, GML, KML) using OpenLayers and Geoserver. I've found how to export features objects with OpenLayers.Format.GeoJSON.write(), but this method only allow converting feature objects or geometry objects.
An example of my idea: I'm viewing a map of a certain country with a couple of WMS layers with some data. Then I zoom to a particular state of that country and I want to export what I'm viewing to GeoJSON or KML for use that in a desktop GIS application (like QGIS).
Does anyone know how to do this?
Thanks.

A: You can do the following:

*

*Get the bounding box of the area that you are requesting
layer.getExtent().toBBOX()

*Build a WFS request using the BBOX here a simple request. As output format choose json

A: In this thread there is an interesting answer about getting a KML representation with WMS. The only problem that I've found is that Qgis has problems with a KML with multiple geometries.


text:
Q: React firestore increment gives type error I want to increase a value of a number field in my firestore database when a button clicked. I've setup the onClick button, but when I click it gives me this error:

TypeError: Cannot read property 'increment' of undefined

I can't find what I did wrong.
Here is my code:
import React,{useState,useEffect, useRef, useContext} from 'react'
import UserContext from  './UserContext.js';
import fire from '../config/Fire';
import copper from '../img/coppernew.jpg'
function useTimes(){
  const user = useContext(UserContext)
  const [kullanici,setTimes] = useState([])
  useEffect(()=>{
    fire
      .firestore()
      .collection('kullanici')
      .doc(user)
      .onSnapshot((doc)=>{
          const newTimes = doc.data()
          setTimes(newTimes)
      })
  },[])

  return kullanici
}

function upgradecopper(){
  var userUid = fire.auth().currentUser.uid;
  console.log(userUid);
  var db = fire.firestore();
  var copperincrease =  db.collection("kullanici").doc(userUid);
  copperincrease.update({
    copper:fire.firestore.FieldValue.increment(1)
  });
}
const Mine = () => {
    const kullanici =useTimes()
    return(

<button onClick={()=>upgradecopper()}>Upgrade Copper Mine</button>(LVL: {kullanici.copper})

Account: {kullanici.email}

      )
    }

export default Mine

My Fire.js
import firebase from 'firebase/app';
import 'firebase/firestore'
import 'firebase/auth';

const config = {
    (there is my api info)
};
const fire = firebase.initializeApp(config);
export default fire;

New Fire.js file:
import firebase from 'firebase';
import 'firebase/app';
import 'firebase/firestore'
import 'firebase/auth';

const config = { /* COPY THE ACTUAL CONFIG FROM FIREBASE CONSOLE */
    (there is my api info)
};
const fire = firebase.initializeApp(config);
export default fire;

A: You're exporting the FirebaseApp instance. But increment is declared on the FieldValue constant.
So you'll need to also import firebase into the main file, and then use firebase.firestore.FieldValue.increment(1) as shown here.


text:
Q: Properly Abstract OId in MongoDB with MongoDB-CSharp I'm trying to use MongoDB with my POCOs. Using mongodb-csharp library (http://github.com/samus/mongodb-csharp), I've got everything working, but I have to have my Ids set to OIds which requires me to reference the mongodb-csharp library from within my entities assembly. This doesn't seem right. I've searched online but I can't seem to find anyone who is abstracting out the OId so it could be easily replaced. Does someone have some guidance on this?
Thanks,
Dan

A: I agree that this isn't right, but if you want to use Oids, then this is what has to happen.  I'm one of devs on the mongodb-csharp driver, and I personally never use Oids.  I will always use Guids.  While it takes more space, I believe it is worth that for transportability between different data stores (I use MSSQL for transactional processing) as well as keeping my dependencies transparent.


text:
Q: Predefined type 'System.ValueTuple`2' is not defined or imported I have a .NET solution file with about 20 C# projects. All of them are targeting .NET Framework 4.6.2. Within a couple of projects, I can easily write var t = ("hello", "world"); and the compiler is happy. But within some projects of the same solution, the compilation fails with Predefined type System.ValueTuple`2 is not defined or imported for the exact same piece of code.
I've already checked the following things:

*

*There is no mscorlib.dll anywhere in the solution or project directories.

*bin and obj have been deleted several times.

*Problem can be reproduced on a colleagues computer.

*Not a single project is using the NuGet package System.ValueTuple.

*I did a text search across all *.csproj files for ValueTuple without any match.

I know that there are dozens of articles related to this error. But most of them are just saying: install the NuGet package or update your .NET Framework version. Unfortunately, none of them seems to cover the problem I'm encountering. Rather than installing or upgrading anything, I'd like to understand the behavior.

A: I finally found the culprit: there is one project targeting .NET Standard 2.0. Every .NET Framework project referencing the .NET Standard project automatically gets a reference to System.ValueTuple.dll from the GAC (in my case, this is .NET Framework 4.7.2).
Each project without referencing the .NET Standard project does not have the reference. Therefore, the snippet var t = ("hello", "world"); cannot be used.


text:
Q: Oauth2 server on aws elastic beanstalk I am working on a spring boot app using spring security to set up an oauth2 server for use with Amazon Alexa using the authorization code grant flow. As it's a POC, it's using an in memory client and some in memory users. I've set up a working example locally and tested this with Postman.
I've thrown the packaged jar into elastic beanstalk and have it hosted over https using a self signed certificate. When testing with both Alexa and Postman, I'm brought to the login screen and the allow/deny screens, followed by a failure. For alexa, I'm simply shown that account linking failed. For postman, the generated token just contains the message "Could+not+make+access+token+request".
I've checked the network calls that occur for the alexa app and I can confirm that my authorization endpoint redirects with a code and the state that was passed by alexa, but never reaches the token endpoint. However, manually passing this code to the token endpoint provides me a valid token.
This is the first time I'm using every one of these technologies (other than spring boot) so any help would be vastly appreciated here.
Edit
So I went ahead and served the endpoints over regular http and I still encountered the same problem using Postman. So I'm pretty confident the issue has anything to do with ssl.

A: So, I ended up building a dummy client application to go test my Auth server.
I used this guide to create this client application using the spring security
framework.
I ended up getting a sun.security.provider.certpath.SunCertPathBuilderException exception, which was caused by the JVM not trusting my self signed certificate. I added my site's certificate using this SO answer. From there, my local client application was working.
In terms of my end goal, I would need to obtain a trusted certificate for my auth server. I found this out here.

*Note that the account linking URL must be a HTTPS URL on port 443, with a certificate from an Amazon approved CA authority (https://mozillacaprogram.secure.force.com/CA/IncludedCACertificateReport).

The provided link on approved CA's seems to have been moved unfortunately.


text:
Q: According to Standards Recommendations How many properties are allowed in class Here some example of code
class A {
    public $attribute1;
    public $attribute2;
    public $attribute3;
    ........
    public $attributeN;
}

I need to know how many properties I can have in the class.
What say about this PSR or phpmd or something else standard?
With bud example I can have "how many I want", but I need to write it with PSR and phpmd.
I am searching this but still can not find.
Thanks  for help.

A: Like arkascha said, there is no technical limit for this.
Classes are implemented using hash tables and access to its properties (or fields) is designed to work efficiently at constant time for millions of properties.
See this page: https://en.wikipedia.org/wiki/Hash_table
PHPMD is a tool for analyzing source code.
The rules described in its Rules page including its Code Size Rules are just its default configuration.
In other words, you can modify it to whatever you want to match your own policy.
For example, if a company has a policy that the maximum number of fields should be 100,
look for the "TooManyFields" rule and modify it like this:
<properties>
    <property name="maxfields" description="The field count reporting threshold " value="100"/>
</properties>

Another company can modify the maximum limit to 50 thousand fields, like this:
<properties>
    <property name="maxfields" description="The field count reporting threshold " value="50000"/>
</properties>

You can even create your own rules.
In conclusion, the rules described there are not for everyone to follow.
They are just default configuration.
Any company and any development team can modify the configuration to match their own policies.

A: If you plan to have attributes in such way, you definitely do it wrong.
public $attribute1;
public $attribute2;
public $attribute3;
........
public $attributeN;

You probably need several arrays, with all that values.


text:
Q: PIL 1.1.7 and python 3.x
Possible Duplicate:
Image library for Python 3

How can I use PIL 1.1.7 in python 3.x, it says it needs an 2.4 ver. of python, but I have seen it being used ( just never got around to ask how it was done).
The version I saw was that somehow the PIL 1.1.7 was defined and then later used in python 3.x code.
Thanks for any help beforehand!

A: See here for some unofficial PIL downloads. Works for me.


text:
Q: Computational method for finding edge states? I am actually interested to learn how to calculate edge states  in 1D topological systems using computational methods,
Q. can anyone tell me which method is best suited and easy to calculate edge spectrums and winding numbers especially for interacting systems?
and I was also going through one paper and I have found following graph for 1 D system

The above figure shows the edge spectrum for finite chain of length L=64 where y-axis show energy
Q. can anyone tell me which method is used here to obtain edge spectrum like above?