text:
Q: Download zip using jszip in Sharepoint Hi I am looking for solutions insanely for almost 2 days.I have sharepoint library where multiple word docs uploaded.Using javascript JSZip I like to pass sharepoint file urls into it.Is this possible ?
I am getting each file server relative URL by ecmascript.Now I would like to do something like this:
  function create_zip() {
    debugger
        var zip = new JSZip();
        zip.add("http://myspsite/shareddoc/a/test.docx", "\n"); //this is hardcoded for testing??here I have file url
        //zip.add("hello2.txt", "Hello Second World\n");
        content = zip.generate();
        location.href = "data:application/zip;base64," + content;
    }

Any pointers or how I proceed from here?
Thanxs.

A: It´s insanely but interesting. Could works. Creating a button and calling the library and the script, I´m sure of that.
or, try this: http://techtrainingnotes.blogspot.com.ar/2010/05/sharepoint-2010-windows-explorer-view.html
This is more simple.


text:
Q: MySQL to group a column's values to a single cell value I have a query that return data with 10 columns and in which only one column value is unique for every row and all the other column values will be repeated for few rows each.
Eg:
Column 1 | Column 2 | column 3 | column 4 | column 5 | Column 6
          Sony     |    Xperia   |   stack      |   ask        | question   |    XYZ
          Sony     |    Xperia   |   stack      |   ask        | question   |    ABC
          Sony     |    Xperia   |   stack      |   ask        | question   |    123
          Nexus   |   Android  |   stack      |   ask        | question   |    POI
          Nexus   |   Android  |   stack      |   ask        | question   |    KILL
I want the result to be as -
Eg: Column 1 | Column 2 | column 3 | column 4 | column 5 | Column 6
          Sony     |    Xperia   |   stack      |   ask        | question   |    XYZ, ABC, 123
          Nexus   |   Android  |   stack      |   ask        | question   |    POI, KILL
Can you guys please help me in achieving this through mysql query ?? Just a hint of the possibilities would do.
I got the values in sorted order so that the "to be grouped" rows will always come consecutively.
Thanks in advance. :)

A: You do this using aggregation and group_concat():
select column1, column2, column3, column4, column5, group_concat(column6) as column6
from query q
group by column1, column2, column3, column4, column5;

redpajama_set_name: RedPajamaStackExchange


text:
Q: C# RSS feed reader with thread, feeds are written to listView multiple times I have a RSS news reader which reads a rss feed and writes the news with links in a ListView.
when I'm executing my program I'm starting a new thread like this:
    Thread myThread = new Thread(getNews);
    myThread.Start();

My method to read the feed looks like this:
    public void getNews()
    {
        //Creates a XmlTextReader which reads from the url entered in input field
        rssReader = new XmlTextReader(txtUrl.Text);

        //Creates an xml doc to save the content of the entered path
        rssDoc = new XmlDocument();

        //Loads the xml content from the reader into a XmlDocument
        rssDoc.Load(rssReader);

        //Make a loop to search for the <rss> tag
        for (int i = 0; i < rssDoc.ChildNodes.Count; i++)
        {
            //If the childenode is the rss tag
            if (rssDoc.ChildNodes[i].Name == "rss")
            {
                //the <rss> tag is found, and we know where it is
                nodeRss = rssDoc.ChildNodes[i];
            }
        }

        //Make a loop to search for the <channel> tag
        for (int i = 0; i < nodeRss.ChildNodes.Count; i++)
        {
            //If the childnode is the channel tag
            if (nodeRss.ChildNodes[i].Name == "channel")
            {
                //The channel tag is found and we know where it is
                nodeChannel = nodeRss.ChildNodes[i];
            }
        }

        //Make a loop to search for the <item> tag
        for (int i = 0; i < nodeChannel.ChildNodes.Count; i++)
        {
            //If the childnode is the item tag
            if (nodeChannel.ChildNodes[i].Name == "item")
            {
                //the item tag is found, and we know where it is
                nodeItem = nodeChannel.ChildNodes[i];

                //Creates a new row in the LstView which contains information from inside the nodes
                rowNews = new ListViewItem();
                rowNews.Text = nodeItem["title"].InnerText;
                rowNews.SubItems.Add(nodeItem["link"].InnerText);

                if (this.lstView.InvokeRequired)
                {
                    AddItemCallback d = new AddItemCallback(getNews);
                    this.Invoke(d);
                }
                else
                {
                    lstView.Items.Add(rowNews);
                }
            }

        }

My problem is, after I started to run my code in a new thread and use the delegate to check if the listView requres an invoked all the news feeds are written in my listView mulitple times. if I run method without starting a new thread and using the delegate its only written once, why is that? It's probably a very simple question but just can't seeme to figure out why
Thanks in advance, code examples are appreciated :)

A: If invoke is required, you're calling the getNews method again. Instead of using this code:
if (this.lstView.InvokeRequired)
{
     AddItemCallback d = new AddItemCallback(getNews); // STOP CALLING getNews
     this.Invoke(d);
}

You need to call another method to update your UI. It's a giant loop.

A: You put your invocation check in the wrong place - thus your getNews function is being called many many more times than you intended.
at the very top of getNews try this:
if (this.lstView.InvokeRequired) {
AddItemCallback d = new AddItemCallback(getNews);
this.Invoke(d);
return;
}

Then replace the if statement at the end with lstView.Items.Add(rowNews);
Of course, doing it this way effectively marshalls your getNews to the UI thread.  What you really need is to build a collection of ListViewItems and pass that collection to an Updater method.. and in THAT method you check if invokation is required.


text:
Q: Posting Supergroup Messages with Python-Telegram-Bot I have been sending Telegram messages to a chat using the code below. It worked fine but the group has been upgraded to a "Supergoup" and it has stopped working. It just gives a "Chat cannot be found" error.
I have the new ID and found a suggestion that I needed to add the bot as admin for the group. Neither of these has fixed the problem.
Does anyone know what the issue is?
bot = telegram.Bot(token='xxxxxxxxxxxxxxxxxxxxxxxxxxx')

def post(message):
    msg = dedent(f'''\
        On subject {subject}: {message}
        ''')
    bot.send_message('-1111111111', text=msg)


text:
Q: Got wrong size of dimensions after using "dataloader" Encountering a problem when trying to use "dataloader" to segment my dataset .
I used gray picture which displays pixel as ( 2294 * 1914). First, using "transforms",
then got tensor.size( ) = ( 1, 2294, 1914) .
But after using "dataloader", the returning .size( )
got ( 8, 1, 2294, 1914, 3) ,
which should be ( 8, 1, 2294, 1914) .
The last dimension "3 " copied every pixel three-times, and i have no idea where the problem is .
Any help will be appreciated !
import torch
import numpy as np
from torchvision import transforms
import torchvision
import torch.utils.data
from PIL import Image

training_transforms = transforms.Compose([
    transforms.Lambda(lambda image: torch.from_numpy(np.array(image)   \
    .astype(np.float32)).unsqueeze(0)),
    transforms.Lambda(lambda image: image / 65535)
])

training_dataset_path = r"D:\user\Desktop\bcResearch\root"
train_dataset = torchvision.datasets.ImageFolder(root =                \
training_dataset_path, transform = training_transforms)
train_loader = torch.utils.data.DataLoader                             \
(dataset = train_dataset, batch_size = 8, shuffle = False)

img = Image.open                                                       \
(r"D:\user\Desktop\bcResearch\root\2\Subroot1_Sub1_subroot3_IM1.tiff")
img = training_transforms(img)
print(img.size())

for i, j in train_loader:
    print(i.size())
    print(i)
    break

#end

Result is in the link here. (I have insufficient permissions to paste the picture directly. )

A: The question requires a bit of edit:
It shows return size ( 8, 1, 2294, 1914, 3) instead of ( 5, 1, 2294, 1914, 3) where batch_size=8.
Regarding the question,

The last dimension "3 " copied every pixel three-times, and i have no
idea where the problem is .

torchvision.datasets.ImageFolder returns (sample, target) where target is the class_index of the target class.
So, according to the returned size, 3 is for the number of target classes and sample size = (8, 1, 2294, 1914).
See reference.

A: Thanks to my old friend, i already found the answer to problem caused by not adding transforms.Grayscale() in the transform.Compose([]).


text:
Q: Iterator for columns of matrix: copying matrix column to std::vector? Trying to return an std::vector from a designated column in a matrix. This is the code I have so far:
template <typename T>
vector<T> ExtractMatrixColAsVector(NumericMatrix x, NumericVector column){
  vector<T> values = as<vector<T> >(NumericVector(x(_,as<int>(column))));
  return values;
}

I was wondering whether there was a better way of doing this if I wanted to convert the whole matrix into separate vectors? Is there an iterator for this purpose or some syntactic sugar that returns a vector of that column automatically?
Thanks for any help.

A: You could use a quick for loop to convert the whole matrix.
// [[Rcpp::export]]
vector< vector<double> > ExtractMatrixAsVectors(NumericMatrix x){
  vector< vector<double> > values(x.nrow());
  for(int i=0; i<values.size(); i++) values[i] = as< vector<double> >(NumericVector(x(_,i)));
  return values;
}

Also, I don't see too much point in using a template.  The output of a numeric matrix column will always be a double precision float.


text:
Q: Material Components Web and Webpack 2 not including path I want to use MDC in my .vue files but my build always failed because MDC does not use relative path or at least the ~
my config looks like this: https://www.hastebin.com/pezukobuba.coffeescript
that's a snippet from laravel-mix's webpack config.
I've spent hours searching and copying other's configuration but none of them really works. I tried googling already and ran out of ideas.
Is there anyway I could use MDC using webpack 2 / laravel-mix ?


text:
Q: Show that $\ln(\sin(-20)+21)>3$ by hand Hi I hope this problem is new :
Show that :
$$\ln(\sin(-20)+21)>3$$
I have tried the power series of $\ln(x)$ and $\sin(x)$ without success because it's becomes hard by hand .
You can also find the inequality due to Michael Rozenberg wich states for $x\geq 1$ :
$$\ln(x)\leq (x-1)\left(\frac{2}{x^2+x}\right)^{\frac{1}{3}}$$
But unfortunately it's an upper bound not a lower bound so maybe we can play with it .
Edit :
We have :
$$k=\sin(-20)+21$$
Then it seems we have for $5\leq x\leq k$ :
$$\left(\frac{2x}{2+x}\left(1-b\right)+b\frac{\left(x-1\right)}{\sqrt{x}}\right)<\ln(x)$$
Where $b=0.484092$
I used the lower bound
Use Jensen's inequality to show $\frac{2x}{2+x} < \log(1+x) < \frac{2x+x^2}{2+2x}$ for $x>0$
And another well-know upper bound for the logarithm .
Question :
How to show it by hand (without a calculator) ?

A: Let's approximate $\sin(-20)$ using a Taylor series centered near $-20$. Since $\pi \approx 3.14$, we have $-6.5\pi \approx -20.41$, so this is what we'll use as the center of the approximation. Note that $\sin(-6.5\pi) = -1$ and $\cos(-6.5\pi) = 0$. So we have
$$\sin(x) = \sum_{k=0}^{\infty} (-1)^k \frac{\sin(-6.5\pi)}{(2k)!} \cdot (x + 6.5\pi)^{2k} = \sum_{k=0}^{\infty} \frac{(-1)^{k+1}}{(2k)!} (x + 6.5\pi)^{2k}.$$
We'll use the quadratic approximation:
$$\sin(x) = -1 + \frac{1}{2} \cdot (x + 6.5\pi)^2 + O((x + 6.5\pi)^4).$$
Since $3.14159 < \pi < 3.14160$, we have $0.42 < -20 + 6.5\pi < 0.421$. We compute
$$\sin(-6.5\pi + 0.42) \approx -1 + \frac{1}{2} \cdot 0.42^2 = -0.9118$$
and
$$\sin(-6.5\pi + 0.421) \approx -1 + \frac{1}{2} \cdot 0.421^2 = -0.9113795.$$
By Taylor's theorem, these approximations have error bounded above by $0.421^4/4! < 0.002$. So
$$-0.914 < \sin(-6.5\pi + 0.42) < \sin(-20) < \sin(-6.5\pi + 0.421) < -0.909.$$
Thus,
$$20.086 < \sin(-20) + 21 < 20.091.$$
At this point, we could try to approximate the natural logarithm, but its Taylor series converges rather slowly, so it's more efficient to bound $e^3$. We have $e < 2.7183$, so
$$e^3 < 2.7183^3 = 20.08593... < 20.086 < \sin(-20) + 21.$$
Thus $3 < \ln(\sin(-20) + 21)$.

A: Some thoughts:
Fact 1: $\sin 20 < \frac{21}{23}$.
Using Fact 1, it suffices to prove that
$\ln (21 - \frac{21}{23}) > 3$
or $\frac{462}{23} > \mathrm{e}^3$ which is true.

Proof of Fact 1:
The desired inequality is written as
$$\cos \frac{13\pi - 40}{2}  < \frac{21}{23}.$$
Using $\cos 2x = 1 - 2\sin^2 x$, it suffices to prove that
$$\sin \frac{13\pi - 40}{4} > \frac{1}{\sqrt{23}}.$$
Using $\sin y \ge y - \frac{1}{6}y^3$ for all $y \ge 0$, it suffices to prove that
$$\frac{13\pi - 40}{4} - \frac16 \left(\frac{13\pi - 40}{4}\right)^3
> \frac{1}{\sqrt{23}}$$
which is true.


text:
Q: WebAppInitializer cannot be cast to javax.servlet.ServletContainerInitializer I'm facing the following stacktrace when running mvn tomcat7:run:
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/blog-demo]]
    at java.util.concurrent.FutureTask.report(FutureTask.java:122)
    at java.util.concurrent.FutureTask.get(FutureTask.java:188)
    at org.apache.catalina.core.ContainerBase.startInternal(ContainerBase.java:1123)
    at org.apache.catalina.core.StandardHost.startInternal(StandardHost.java:800)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1559)
    at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1549)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:744)
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Tomcat].StandardHost[localhost].StandardContext[/blog-demo]]
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:154)
    ... 6 more
Caused by: java.lang.ClassCastException: com.replaceme.WebAppInitializer cannot be cast to javax.servlet.ServletContainerInitializer
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializer(ContextConfig.java:1670)
    at org.apache.catalina.startup.ContextConfig.getServletContainerInitializers(ContextConfig.java:1652)
    at org.apache.catalina.startup.ContextConfig.processServletContainerInitializers(ContextConfig.java:1562)
    at org.apache.catalina.startup.ContextConfig.webConfig(ContextConfig.java:1270)
    at org.apache.catalina.startup.ContextConfig.configureStart(ContextConfig.java:878)
    at org.apache.catalina.startup.ContextConfig.lifecycleEvent(ContextConfig.java:376)
    at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
    at org.apache.catalina.util.LifecycleBase.fireLifecycleEvent(LifecycleBase.java:90)
    at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5322)
    at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
    ... 6 more

This is my WebAppInitializer class:
public class WebAppInitializer extends AbstractSecurityWebApplicationInitializer {
    @Override
    public void beforeSpringSecurityFilterChain(ServletContext servletContext) {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

        ConfigurableEnvironment env = rootContext.getEnvironment();
        env.setDefaultProfiles("production", env.getProperty("user.name"));

        rootContext.scan("com.replaceme.config");

        servletContext.addListener(new ContextLoaderListener(rootContext));

        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }
}

I've added a text file in src/main/resources/META-INF/services called javax.servlet.ServletContainerInitializer which contains the class identifier com.replaceme.WebAppInitializer.
And here are my maven dependencies:
[INFO] +- org.hibernate:hibernate-core:jar:4.3.5.Final:compile
[INFO] |  +- org.jboss.logging:jboss-logging:jar:3.1.3.GA:compile
[INFO] |  +- org.jboss.logging:jboss-logging-annotations:jar:1.2.0.Beta1:compile
[INFO] |  +- org.jboss.spec.javax.transaction:jboss-transaction-api_1.2_spec:jar:1.0.0.Final:compile
[INFO] |  +- dom4j:dom4j:jar:1.6.1:compile
[INFO] |  |  \- xml-apis:xml-apis:jar:1.0.b2:compile
[INFO] |  +- org.hibernate.common:hibernate-commons-annotations:jar:4.0.4.Final:compile
[INFO] |  |  +- (org.jboss.logging:jboss-logging:jar:3.1.3.GA:compile - omitted for duplicate)
[INFO] |  |  \- (org.jboss.logging:jboss-logging-annotations:jar:1.2.0.Beta1:compile - omitted for duplicate)
[INFO] |  +- org.hibernate.javax.persistence:hibernate-jpa-2.1-api:jar:1.0.0.Final:compile
[INFO] |  +- org.javassist:javassist:jar:3.18.1-GA:compile
[INFO] |  +- antlr:antlr:jar:2.7.7:compile
[INFO] |  \- org.jboss:jandex:jar:1.1.0.Final:compile
[INFO] +- org.hibernate:hibernate-validator:jar:5.1.0.Final:compile
[INFO] |  +- javax.validation:validation-api:jar:1.1.0.Final:compile
[INFO] |  +- (org.jboss.logging:jboss-logging:jar:3.1.3.GA:compile - omitted for duplicate)
[INFO] |  \- com.fasterxml:classmate:jar:1.0.0:compile
[INFO] +- ch.qos.logback:logback-classic:jar:1.0.13:runtime
[INFO] |  +- ch.qos.logback:logback-core:jar:1.0.13:runtime
[INFO] |  \- (org.slf4j:slf4j-api:jar:1.7.5:runtime - omitted for duplicate)
[INFO] +- org.slf4j:slf4j-api:jar:1.7.5:compile
[INFO] +- org.slf4j:jcl-over-slf4j:jar:1.7.5:compile
[INFO] |  \- (org.slf4j:slf4j-api:jar:1.7.5:compile - omitted for duplicate)
[INFO] +- org.codehaus.janino:janino:jar:2.6.1:compile
[INFO] |  \- org.codehaus.janino:commons-compiler:jar:2.6.1:compile
[INFO] +- org.springframework:spring-context:jar:4.0.3.RELEASE:compile
[INFO] |  +- org.springframework:spring-aop:jar:4.0.3.RELEASE:compile
[INFO] |  |  +- (aopalliance:aopalliance:jar:1.0:compile - omitted for duplicate)
[INFO] |  |  +- (org.springframework:spring-beans:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  |  \- (org.springframework:spring-core:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  +- org.springframework:spring-beans:jar:4.0.3.RELEASE:compile
[INFO] |  |  \- (org.springframework:spring-core:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  +- org.springframework:spring-core:jar:4.0.3.RELEASE:compile
[INFO] |  \- org.springframework:spring-expression:jar:4.0.3.RELEASE:compile
[INFO] |     \- (org.springframework:spring-core:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] +- org.springframework:spring-jdbc:jar:4.0.3.RELEASE:compile
[INFO] |  +- (org.springframework:spring-beans:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  +- (org.springframework:spring-core:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  \- org.springframework:spring-tx:jar:4.0.3.RELEASE:compile
[INFO] |     +- (org.springframework:spring-beans:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |     \- (org.springframework:spring-core:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] +- org.springframework:spring-orm:jar:4.0.3.RELEASE:compile
[INFO] |  +- (org.springframework:spring-beans:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  +- (org.springframework:spring-core:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  +- (org.springframework:spring-jdbc:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  \- (org.springframework:spring-tx:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] +- org.springframework:spring-webmvc:jar:4.0.3.RELEASE:compile
[INFO] |  +- (org.springframework:spring-beans:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  +- (org.springframework:spring-context:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  +- (org.springframework:spring-core:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  +- (org.springframework:spring-expression:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |  \- org.springframework:spring-web:jar:4.0.3.RELEASE:compile
[INFO] |     +- (org.springframework:spring-aop:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |     +- (org.springframework:spring-beans:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |     +- (org.springframework:spring-context:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] |     \- (org.springframework:spring-core:jar:4.0.3.RELEASE:compile - omitted for duplicate)
[INFO] +- org.springframework.security:spring-security-config:jar:3.2.3.RELEASE:compile
[INFO] |  +- aopalliance:aopalliance:jar:1.0:compile
[INFO] |  +- org.springframework.security:spring-security-core:jar:3.2.3.RELEASE:compile
[INFO] |  |  +- (aopalliance:aopalliance:jar:1.0:compile - omitted for duplicate)
[INFO] |  |  +- (org.springframework:spring-aop:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  |  +- (org.springframework:spring-beans:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  |  +- (org.springframework:spring-context:jar:4.0.3.RELEASE:compile - version managed from 3.2.8.RELEASE; omitted for duplicate)
[INFO] |  |  +- (org.springframework:spring-core:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  |  \- (org.springframework:spring-expression:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  +- (org.springframework:spring-aop:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  +- (org.springframework:spring-beans:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  +- (org.springframework:spring-context:jar:4.0.3.RELEASE:compile - version managed from 3.2.8.RELEASE; omitted for duplicate)
[INFO] |  \- (org.springframework:spring-core:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] +- org.springframework.security:spring-security-web:jar:3.2.3.RELEASE:compile
[INFO] |  +- (aopalliance:aopalliance:jar:1.0:compile - omitted for duplicate)
[INFO] |  +- (org.springframework.security:spring-security-core:jar:3.2.3.RELEASE:compile - omitted for duplicate)
[INFO] |  +- (org.springframework:spring-beans:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  +- (org.springframework:spring-context:jar:4.0.3.RELEASE:compile - version managed from 3.2.8.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-core:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  +- (org.springframework:spring-expression:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  \- (org.springframework:spring-web:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] +- org.springframework.data:spring-data-jpa:jar:1.5.2.RELEASE:compile
[INFO] |  +- org.springframework.data:spring-data-commons:jar:1.7.2.RELEASE:compile
[INFO] |  |  +- (org.springframework:spring-core:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  |  +- (org.springframework:spring-beans:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  |  +- (org.slf4j:slf4j-api:jar:1.7.5:compile - version managed from 1.7.6; omitted for duplicate)
[INFO] |  |  \- (org.slf4j:jcl-over-slf4j:jar:1.7.5:runtime - version managed from 1.7.6; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-orm:jar:4.0.3.RELEASE:compile - version managed from 3.2.8.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-context:jar:4.0.3.RELEASE:compile - version managed from 3.2.8.RELEASE; omitted for duplicate)
[INFO] |  +- (org.springframework:spring-aop:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  +- (org.springframework:spring-tx:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  +- (org.springframework:spring-beans:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  +- (org.springframework:spring-core:jar:3.2.8.RELEASE:compile - omitted for conflict with 4.0.3.RELEASE)
[INFO] |  +- org.aspectj:aspectjrt:jar:1.7.4:compile
[INFO] |  +- (org.slf4j:slf4j-api:jar:1.7.5:compile - version managed from 1.7.6; omitted for duplicate)
[INFO] |  \- (org.slf4j:jcl-over-slf4j:jar:1.7.5:runtime - version managed from 1.7.6; omitted for duplicate)
[INFO] +- javax.servlet:javax.servlet-api:jar:3.1.0:provided
[INFO] +- org.thymeleaf:thymeleaf:jar:2.1.2.RELEASE:compile
[INFO] |  +- ognl:ognl:jar:3.0.6:compile
[INFO] |  +- (org.javassist:javassist:jar:3.16.1-GA:compile - omitted for conflict with 3.18.1-GA)
[INFO] |  \- (org.slf4j:slf4j-api:jar:1.7.5:compile - version managed from 1.6.1; omitted for duplicate)
[INFO] +- org.thymeleaf:thymeleaf-spring4:jar:2.1.2.RELEASE:compile
[INFO] |  +- (org.thymeleaf:thymeleaf:jar:2.1.2.RELEASE:compile - omitted for duplicate)
[INFO] |  \- (org.slf4j:slf4j-api:jar:1.7.5:compile - version managed from 1.6.1; omitted for duplicate)
[INFO] +- cglib:cglib:jar:3.1:compile
[INFO] |  \- org.ow2.asm:asm:jar:4.2:compile

EDIT: It won't work with the following class as well:
public class WebAppInitializer implements WebApplicationInitializer {
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

        ConfigurableEnvironment env = rootContext.getEnvironment();
        env.setDefaultProfiles("production", env.getProperty("user.name"));

        rootContext.scan("com.replaceme.config");

        servletContext.addListener(new ContextLoaderListener(rootContext));

        ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
        servlet.setLoadOnStartup(1);
        servlet.addMapping("/");
    }
}

A: Class com.replaceme.WebAppInitializer which extends Class AbstractSecurityWebApplicationInitializer is not a subtype of Class javax.servlet.ServletContainerInitializer. So, You are not allowed to type cast an object of one type to an object of another type. To simply say you are trying to convert a dog to a donkey, that's why ClassCastException is thrown. Casting can't be done between object types which are not in the same inheritance tree

A: A WebApplicationInitializer (from Spring) is not a ServletContainerInitializer (from the Servlet specs). So just remove the file javax.servlet.ServletContainerInitializer from the services folder. Your WebAppInitializer will automatically be detected by Spring (see here)


text:
Q: Download a file to heroku process it and send as an attachment I'm trying to do the following:

*

*Download a pdf file from S3 to my heroku.

*Process the pdf.

*Email the pdf as an attachment.

Is it possible? If yes, could you please give me a tip how?
I'm running Django and pdf is about 1MB.
This is my processing part:
from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.colors import HexColor
import os, sys
import requests
from io import BytesIO

URL = "https://domainname.com/sample.pdf"
response=requests.get(URL)
p = BytesIO(response.content)
p.seek(0, os.SEEK_END)

def watermark_product(watermark_text, input_file_path, output_file_path):

    c = canvas.Canvas("watermark.pdf")
    c.setFont("Helvetica", 24)
    c.setFillGray(0.5,0.5)
    c.saveState()
    c.translate(500,100)
    c.rotate(45)
    c.drawCentredString(0, 300, watermark_text)
    c.restoreState()
    c.save()

    input_file = PdfFileReader(input_file_path)
    output_writer = PdfFileWriter()
    total_pages = input_file.getNumPages()

    for single_page in range(total_pages):
        page = input_file.getPage(single_page)
        watermark = PdfFileReader("watermark.pdf")
        page.mergePage(watermark.getPage(0))
        output_writer.addPage(page)

    with open(output_file_path, "wb") as outputStream:
        output_writer.write(outputStream)
    os.remove("watermark.pdf")

watermark_product('testtesatd', p, 'w1.pdf')

EDIT:
I've managed to keep the pdf file in memory.


text:
Q: python unicode string matching I have a list of words converted into  a list of unciode strings but i am not able to match the end strings of a particular word from a list of strings as for example:
list which contains of strings of which it needs to be removed.For example
उपलब्धियां is the word when converted to unicode is u'\u0909\u092a\u0932\u092c\u094d\u0927\u093f\u092f\u093e\u0902'
list which contains of strings which if found at the end of a word in unicode needs to be removed
r3_bad= [u"0900", u"0901", u"0902",u"0903"];
in this case is u0902 is at the end from the bad string list so to be removed.
i tried
if re.search(r'u$[0-3]',word[-1]) :

it does not returns true
i don't know why.
please help thanks in advance.

A: Why RegEx? I think you need something like plain string comparison:
s = u'\u0909\u092a\u0932\u092c\u094d\u0927\u093f\u092f\u093e\u0902'
r3_bad= [u'\u0900',u'\u0901',u'\u0902',u'\u0903']

print s # output: उपलब्धियां
if s[-1] in r3_bad: print s[:-1] # output: उपलब्धिया


text:
Q: Gooey Animation for Pager Indicator inside Item Decoration Can some please teach me how to make a gooey pager indicator for on-boarding please?
I really am just curious on how these animations are done.
I am thinking of something like this Here.
Its the example under the . The image might not show it but the circle below combines into one forming a rounded rectangle by a gooey effect before the indicator circle slides to the next circle. After the circle has slide to the correct position, the formed rounded rectangle goes back to its original circular form.
Can someone give me an idea how this could be achieved? Thank you very much in advance.

A: This is what you need https://github.com/chenupt/SpringIndicator. I've used this once on a project before. The documentation is kind of straight forward.


text:
Q: What is/are the difference(s) between the two following variables? (Except their names) char *s1 = "";
char *s2 = NULL;
What is the difference?

A: One is pointing to the first element of an array of a single char element, the element being the string null-terminator character '\0'.
The other variable is initialized point to NULL which means it doesn't point anywhere, really.

Slightly simplified, the definition
char *s1 = "";

is kind of equivalent to
char private_array[1] = { '\0' };
char *s1 = &private_array[0];

It might seem confusing to have both a string null terminator, and a generic null pointer, but it will clear itself out with more experience.
Also note that in C all literal strings (even "") are not modifiable, they are in essence read only. That's why it's recommended to always use const char * to point to literal strings.

A: There's a very big differnce using "" leaves '\0', whereas NULL leaves the pointer as ((void *)0).
This can be tested via dereferencing the pointer like:
NOTE: Dereferencing the pointer means accessing its inner values or elements, which is done using * unary operator or [] operator in C/C++.
""
#include <stdio.h>

int main(void){
    char *s1 = "";
    printf("%d", *s1);
    return 0;
}

I'm printing the integer representation of *s1 because '\0' can't be seen on the terminal.
Ouput:
0

And program returned 0 which means "" ends with '\0'.
NULL
#include <stdio.h>

int main(void){
    char *s2 = NULL;
    printf("%d", *s2);
    return 0;
}

The above program printed nothing on stdout, but it returned 139, which means program crashed before it exited (segmentation fault), as it was an undefined behavior.
You can try it online.

A: The first one points to a 0-byte and can be dereferenced but the second one points to 0 and cannot be dereferenced

A: *

*The first one points to a 0-byte, the second one (char *s2 = NULL;) points to 0

*The first one can be dereferenced, not the second one

Key:
The First One: char *s1 = "";
The Second One: char *s2 = NULL;


text:
Q: Text transformed incorrectly after JSoup transform I use JSoup to parse HTML. I have a text string of:
   &ap

After parsed using:
Jsoup.parseBodyFragment("&ap");

It is transformed to a wired character: ≈
The character is actually from an URL:
 http://mycompany.com?param=1&app=100

Notice that the &ap part of URL is always replaced with the wired character hence the URL becomes:
http://mycompany.com?param=1≈p=100

I think this might be something to do with HTML encoding.
Can someone let me know how to fix this?

A: Could you provide more information how to reproduce that?
I tried it with this code:
public static void main(String[] args) throws MalformedURLException, IOException {
    Document doc = Jsoup.parseBodyFragment("\n
http://mycompany.com?param=1&app=100
");

    System.out.println(doc.toString());
    System.out.println();
    System.out.println(doc.getElementsByAttribute("href"));
}

It prints:

http://mycompany.com?param=1&app=100

And there the & got translated into &amp.


text:
Q: How to change clicked item glyphicon am binding list of products from database in my page with icon,
initially am showing glyphicon off for all items , when i click list item am changing clicked item glyphicon to ok,
but if i select any other item in list first item glyphicon changing to ok , i want to change icon of clicked item
my code is
view

                                    {{prod.PRODCTNAME}}

js
 $scope.getModules = function (event) {
        var prodID = event.target.id;
        var productElement = angular.element(document.querySelector('#iProduct'));
        productElement.toggleClass('glyphicon glyphicon-off ChangeButtonColorOrangeRed').toggleClass('glyphicon glyphicon-ok ChangeButtonColorGreen');
        var moduleDiv = angular.element(document.querySelector('#divModule'));
        moduleDiv.toggleClass('divProductsHide').toggleClass('divProductsShow');
        productService.getModules(prodID).then(function (d) {
            $scope.modules = d.data;
        }, function (error) {
            alert('Error!');
        });

    };

css


text:
Q: Howto create a partial mock using mockto-flex? Is it posible to create a partial mock using mockito-flex?

A: Mockito-flex does not support partial mocks at this point. However you can make your mock object call original functions.
given(someone.something(any())).will(callOriginal());
You could add a convenience function that makes your mock call originals for all public functions and properties.


text:
Q: LocationManager providerDisabled() I want to know if a Certain Provider is Disabled will the LocationManager stop listening to the location changes for that provider ? If not then how can i manually stop listening for updates for that provider. Thanks In Advance

A: give this a whirl
 myLocationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
 myListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        Log.i("LocationListener", "Logging Change");
    }

  }

myLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
            5000, 1, myListener);

myLocationManager.removeUpdates(myListener);

A: Your location listeners will not stop until you call myLocationManager.removeUpdates(myListener);. Check my answer to a different question [here] to know what else you need to do for connection status updates1.


text:
Q: How to compile ADF and JSF Utils and create the JAR files? I would like to compile the ADF and JSF Utils and make a jar file containing the two so that I can make use of it in my ADF Applications.
Please let me know if you have done this before (couldn't find a step by step tutorial).
Thank you,
Mike


text:
Q: Problems with Arduino remotely controlling an outlet This is a project that will be turned in, in 8 hours! We are stuck with this problem and thought of this place as a kind of last resort.
I'm trying to turn on/off a remotely controlled outlet with an Arduino.
We get inconsistencies when doing so. Sometimes when it goes into the if statement that "should be ON" but instead turns the power off of the outlet and vice versa.
Code:
// on off remote control
int off = 12;
int on = 13;

void setup() {

  pinMode(off, OUTPUT);      // sets the digital pin as output
  pinMode(on, OUTPUT);

}
void loop() {

  // ..first we getting response from server if remote control should be on/off,
  // working fine so not really relevant to problem.

  // then we determine if outlet should be ON or OFF:
  response.toCharArray(responseCharArray,100);
    if(strstr( responseCharArray, "active") && strstr( responseCharArray, "1")) {
      // This should turn ON the outlet.
      digitalWrite(on, HIGH);
      delay(250);
      digitalWrite(on, LOW);
      Serial.println("should be ON");
    }
    else if(strstr( responseCharArray, "active") && strstr( responseCharArray, "0")) {
      // This should turn OFF the outlet.
      digitalWrite(off, HIGH);
      delay(250);
      digitalWrite(off, LOW);
      Serial.println("should be OFF");
    }

}

Picture of the wiring:

Question:
What could be missing here? Since it randomly turns it on/off while entering same if statement.

A: There is too little information here.
Notice that your code will trigger (turn on) if responseCharArray contains something like e.g. "retroactively from 1941", or turn off for something like "active for 37 seconds".
In other words, that string-matching is not very precise, but it's hard to know what it should be since I don't know anything about the format of the response.
Perhaps it should at least be
if(strstr(responseCharArray, "active=1") != NULL)

or something, to at least lock the 1 to the active part.
In the logging that you do, print out the value of responseCharArray too. This will let you analyze whether or no the decision-making made sense.
Also, as always, triple-check your wiring and watch for e.g. back-feeding.


text:
Q: Upload file from vue.js to flask backend via Websocket I am looking for a minimal reproductible example on how to upload a file from Vue.js to flask backend  via websocket and saving it there. Preferably with the possibility to upload bigger files (few hundred MB)
the template:
    <template>
  <div>
  <form id='upload-form'>
    <input
      id='file-field'
      name='file'
      type='file' @change="onFileChange">
  </form>
      <button @click="uploadFile">Upload</button>
    </div>
</template>

Vue script:
export default {
  name: "UploadFile",
  data () {
    return {
      file: ''
    }
  },
  methods: {
    onFileChange (e) {
      var files = e.target.files || e.dataTransfer.files;
      if (!files.length) {
        return
      }
      this.file = files;
    },

    uploadFile: function (e) {
      console.log('File upload clicked')
      this.$socket.emit('upload-file', this.file)
    }
  }
}

Flask:
# need to save file etc.
@socketio.on('upload-file')
def save_file(data):
    print("Data received")
    print(data)

Right now there is an error in flak on receiving the upload-file-event. The error appears regardless of the file size:

message handler error
Traceback (most recent call last):   File
"~ib/python3.8/site-packages/engineio/server.py", line 549, in
_trigger_event
return self.handlersevent   File "~lib/python3.8/site-packages/socketio/server.py", line 730, in
_handle_eio_message
if pkt.add_attachment(data):   File "~lib/python3.8/site-packages/socketio/packet.py", line 118, in
add_attachment
raise ValueError('Unexpected binary attachment') ValueError: Unexpected binary attachment


text:
Q: Java MongoDB bulk insert from stream I'm trying to insert a few million documents into MongoDB in one operation. Using MongoCollection.insertMany does not work for me because it takes a List as input and my data does not fit in memory.
Is it possible to insert documents from a stream instead?

A: you need to use Bulk Insert operations from your stream. please read:
Bulk Insert
try to execute() the bulk after a reasonable number of documents (inside your consumer lambda) because after all there is a limit to the size of the request Mongo can handle.


text:
Q: C# - Convert String/Null to decimal I have a method and argument as a string or null. So I am trying to convert the arguments into decimal.. I am trying to use decimal.Parse to convert string to decimal.
If the argument has a null value don't want to convert as a decimal..
public void abcd(string price)
{
    decimal result = string.IsNullOrEmpty(price) ? null : decimal.Parse(price);
    //error - cannot convert null as decimal
    //I tried few other options also.
    decimal result = price is null ? 0 : decimal.Parse(price);
    // error - VAlue cannot be null

    //have other logic here
}

abcd("123");
abcd(null);

A: If you want a null to represent the absence of value, you can use a nullable variable:
decimal? result = string.IsNullOrEmpty(price) ? null : decimal.Parse(price);

This is a better option than representing a lack of data by a zero as proposed by others.
You may have to check if result is null before using it for certain purposes. However, the usual operations are supported:
See Math operations with null

A: string i = null;

decimal result;
decimal.TryParse(i, out result);
Console.WriteLine(result.ToString()); // 0

A: You can set 0 when the string is null or empty.
Please follow the below answer.
public void abcd(string price)
{
    decimal result = string.IsNullOrEmpty(price) ? 0: decimal.Parse(price);
}

A: Try -
public static void abcd(string price)
{
    decimal result = string.IsNullOrEmpty(price) ? 0 : decimal.Parse(price);
    decimal result2 = price is null ? 0 : decimal.Parse(price);

    //have other logic here
}


text:
Q: Cannot persist cookies when using RTK Query I'm creating a pet project with React with Redux on the front end and Node.js with express on the back end. It's the first time I use Redux and RTK Queries, and I'm confused about cookies not being saved.
I tried both variants with RTK Query, and neither worked for me.
const baseQuery = fetchBaseQuery({
  baseUrl,
  credentials: "include",
});

and
signIn: builder.mutation<User, SignInPayload>({
  query(body) {
    return {
      url: "/auth/jwt",
      method: "POST",
      body,
      credentials: "include",
    };
  },
}),

If I reach the same endpoint using axios and {withCredentials: true}, everything works fine, and cookies are persisted.
I attach my Request/Response Headers below.


text:
Q: Can I convert OpenID Stack Overflow login into standard login? My Stack Overflow account is using an OpenID to login. Can I convert this to a normal Stack Overflow account? Any suggestions?

A: There is no such thing as a "normal stackoverflow account". Stack Exchange does offer its own OpenIDs, and you can add one of those to your account if you want. Go to your profile page, and click "my logins" at the top:

Choose "add more logins…", and at the bottom of that page click the link under "To create a new Stack Exchange account, click here". Once you've added the Stack Exchange OpenID to your account you can optionally remove your other OpenID, through the same "my logins" dialog


text:
Q: Add attachment to email with SendGrid using rails I've created a hello_world method which sends an email with Sendgrid. I am trying to include an attachment. I've found the following line in another stackoverflow answer: mail.attachments['test.txt'] = File.read("#{Rails.root}/public/test.txt")
This however generates the following error:
Completed 500 Internal Server Error in 17ms (ActiveRecord: 3.4ms)

TypeError - no implicit conversion of String into Integer:
  app/controllers/messages_controller.rb:32:in `hello_world'
  app/controllers/messages_controller.rb:65:in `create'

Mailing code in controller:
  def hello_world(company, message)
    from = Email.new(email: "test+#{current_user.auth_token}@example.com")
    to = Email.new(email: 'hello@pim.gg')

    subject = 'TEST from dev'
      content = Content.new(type: 'text/plain', value: "#{company.email} #{current_user} #{current_user.first_name} #{current_user.last_name} #{message.text}")

    mail = SendGrid::Mail.new(from, subject, to, content)
    mail.attachments['test.txt'] = File.read("#{Rails.root}/public/test.txt")

    sg = SendGrid::API.new(api_key: ENV['SENDGRID_API_KEY'])
    response = sg.client.mail._('send').post(request_body: mail.to_json)
    puts response.status_code
    puts response.body
    puts response.headers
  end

A: According to documentation of sendgrid-ruby gem adding-attachments should be like this:
attachment = SendGrid::Attachment.new
attachment.content = Base64.strict_encode64(File.open(fpath, 'rb').read)
attachment.type = 'application/vnd.openxmlformatsofficedocument.spreadsheetml.sheet'
attachment.filename = fname
attachment.disposition = 'attachment'
attachment.content_id = 'Reports Sheet'
mail.add_attachment(attachment)


text:
Q: How to go around "Incorrect namespace usage(s)" in static tests I have a simple CRUD module for Magento 2.
When I run the static tests I get the following error/warning.

"Incorrect namespace usage(s) found in file..... <Vendor>_<Module>".

The issue is caused by this line in my file
$resultPage->setActiveMenu('<Vendor>_<Module>::<menu_item_name_here>');

I also tried this approach:
const ADMIN_MENU = '<Vendor>_<Module>::<menu_item_name_here>';

...

$resultPage->setActiveMenu(self::ADMIN_MENU);

But I get the same result.
For core modules, this does not happen even if they have the same approach.
How can I get the static tests to shut up?
Ideally, I would like a clean solution, but I can go with "hiding the dirt under the rug".
Alternative: How can I set the active menu without upsetting the static tests?
Any clean approach would do.


text:
Q: unable to find links in laravel for pagination i get a json response like this  note i am using GuzzleHttp to call my API
$response =  $response->getBody()->getContents();
$output = (json_decode($response));
dd(output)

{#232 ▼
  +"current_page": 1
  +"data": array:2 [▼
    0 => {#230 ▼
      +"id": 1
      +"test_col": "Test one"
    }
    1 => {#237 ▼
      +"id": 3
      +"test_col": "Test three"
    }
  ]
  +"first_page_url": "http://api/api/test?page=1"
  +"from": 1
  +"last_page": 8
  +"last_page_url": "http://api/api/test?page=8"
  +"next_page_url": "http://api/api/test?page=2"
  +"path": "http://api/api/test"
  +"per_page": 2
  +"prev_page_url": null
  +"to": 2
  +"total": 15
}

and now when i go to my front end and do this
 {{$outputs->links()}}

to get the pagination links it shows me an error

ErrorException (E_ERROR) Call to undefined method stdClass::links()

and on my API side i am doing this
      $results = DB::table('test_table')->paginate(2);
        return ($results);

A: The object from the response ($output) can not have any methods. The response already has links (first_page_url, last_page_url, next_page_url). If you need to HTML rendered links then you can try to create instance of LengthAwarePaginator
$pagination = new LengthAwarePaginator($outputs->data, $outputs->total, $outputs->per_page, $outputs->current_page);
echo $pagination->links();

(not tested)


text:
Q: python Regular expression file = open("demo.txt","r")
text = file.read()

def find(info):
    match = re.findall(r"info+\w+\d+",text)
    if match:
        print(match)
    else:
        print("Not found!")

my question is, how to apply 'info' in the function,
have no idea how to do it.
Any help would be greatly appreciated

A: I think this is what you're after:
file = open("demo.txt","r")
text = file.read()

def find(info,text):
    match = re.findall(info + "+\w+\d+",text)
    if match:
        print(match)
    else:
        print("Not found!")

# This is how you call the function
find("whatever info is supposed to be",text)

A: Review your Python syntax a bit.
# beware "file" is a python keyword so you might want to use a different name
file = open("demo.txt","r")
# your text is called "text" so that is the argument to use in the function call
text = file.read()

# define the function:

def find(info):
    # your variable is called "info" in the function so call findall on "info"
    match = re.findall(r"info+\w+\d+",info)
    if match:
        print(match)
    else:
        print("Not found!")

# call the function on "text" since that is the name of the local variable you created with file.read()::
find(text)


text:
Q: Load the content of a template after pressing a button How can I can load a search results template only after the search button has been pressed?
Here is a sample of my code:
app.js
(function() {
    var app = angular.module('app', ['app-directives']);

  app.controller('AppController', function() {
    this.buttonClick = function() {
      alert('Test');
    };
  });
})();

directives.js
(function(){
    var app = angular.module('app-directives', []);

    app.directive('searchForm', function() {
       return {
         retrict: 'E',
         templateUrl: '/partials/search-form.html'
       };
    });

    app.directive('searchResults', function() {
       return {
         retrict: 'E',
         templateUrl: '/partials/search-results.html'
       };
    });
})();

search-form.html
<input type="text" id="query" />
<button onclick="buttonClick">Search</button>

page-content.html
<section id="mainContent">
    <search-form></search-form>
    <search-results></search-results>
</section>

A: If you'd like to just show and hide a content, why not try with ng-show or ng-hide?
Example
<search-results ng-show="buttonPressed"></search-results>
OR
<search-results ng-hide="buttonNotPressed"></search-results>

Unless by 'load' you mean getting the template from a file?


text:
Q: Why i am getting Yahoo OAuth 2.0 error (401) Unauthorized? I am implementing Yahoo OAuth 2.0 given in the guide -https://developer.yahoo.com/oauth2/guide/
I am successful in getting the Access Code given in step 4 but in step 5 which says 'Exchange refresh token for new access token' my code is failing with error - 'The remote server returned an error: (401) Unauthorized.'
My application is placed in http://www.example.com/TutorialCode/YahooOAuth2.0/yahoooauth2.aspx and it gets the Access Token.
Now i am requesting the new access token from the refresh token in another page - http://www.example.com/TutorialCode/YahooOAuth2.0/newaccesstoken.aspx
that is the refresh token i copy and paste from previous page to this page and click button to get new access token but it is failing. My code is -
HTML
<asp:TextBox placeholder="Refresh Token" ID="refreshTokenTextBox" runat="server"></asp:TextBox>
<asp:Button ID="newAccessTokenButton" runat="server" Text="Get New Access Token" OnClick="newAccessTokenButton_Click" />

C#
 protected void newAccessTokenButton_Click(object sender, EventArgs e)
{
    string consumerKey = "xxxx";
    string consumerSecret = "myconsumerkey";

    string returnUrl = "http://www.example.com/TutorialCode/YahooOAuth2.0/newaccesstoken.aspx";
    //string encodedReturnUrl = System.Web.HttpUtility.UrlEncode(returnUrl);

    /*Exchange authorization code for Access Token by sending Post Request*/
    Uri address = new Uri("https://api.login.yahoo.com/oauth2/get_token");

    // Create the web request
    HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

    // Set type to POST
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    byte[] headerByte = System.Text.Encoding.UTF8.GetBytes(consumerKey + ":" + consumerSecret);
    string headerString = System.Convert.ToBase64String(headerByte);
    request.Headers["Authorization"] = "Basic " + headerString;

    // Create the data we want to send
    StringBuilder data = new StringBuilder();
    data.Append("client_id=" + consumerKey);
    data.Append("&client_secret=" + consumerSecret);
    data.Append("&redirect_uri=" + returnUrl);
    data.Append("&refresh_token =" + refreshTokenTextBox.Text.Trim());
    data.Append("&grant_type=refresh_token");

    // Create a byte array of the data we want to send
    byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());

    // Set the content length in the request headers
    request.ContentLength = byteData.Length;

    // Write data
    using (Stream postStream = request.GetRequestStream())
    {
        postStream.Write(byteData, 0, byteData.Length);
    }

    // Get response
    string responseFromServer = "";
    try
    {
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            // Get the response stream
            StreamReader reader = new StreamReader(response.GetResponseStream());
            responseFromServer = reader.ReadToEnd();
            //ShowNewReceivedData(responseFromServer);
            newDataDiv.InnerHtml = responseFromServer;
        }
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message+"
"+ex.ToString());
    }
}

Can somebody help me in getting the root cause of the problem?
Thanks

A: You need to URL encode the parameter values in the request. They may contain characters like & or = that would break the form encoding.
Other than that you may want to swap the legacy POST approach for a more recent, easier approach, as described in the answer in HTTP request with post
You can check your parameters with a curl command:
curl -u "${consumerKey}:${consumerSecret}" -d "grant_type=refresh_token&redirect_uri=${returnUrl}&refresh_token=${refreshToken}" https://api.login.yahoo.com/oauth2/get_token


text:
Q: ZXing QR code size The QRCodeWriter.encode method provides a width and height parameter that are the preferred size in pixels.  I have one URL, when encoded, produces a QR Code sized precisely to the dimensions passed in.  However, a different URL, albeit somewhat longer, produces a QR code that is 12% larger than the dimensions specified.  Is there a way to force the QR code to fit within a certain size limit?

A: QR codes are just encoding (with error correction), which means that, as the input grows, the output has to grow proportionately.
If you want your QRs of the same size then you must limit the input, maybe using tinyurl?


text:
Q: Displaying SMS message once received in Android I am trying to write a simple android program that listens to SMS messages, and once a message is received, it displays it in a toast.
Below is my Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.zaidalmahmoud.expenseless">

    <uses-permission android:name="android.permission.RECEIVE_SMS" />
    <uses-permission android:name="android.permission.READ_SMS" />
    <uses-permission android:name="android.permission.SEND_SMS"/>

    <application

        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Below is my SMS Listener:
public class SmsListener extends BroadcastReceiver {

    private String msgBody;
    private SharedPreferences preferences;

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){

            Toast.makeText(context,"message received:",Toast.LENGTH_SHORT).show();

            Bundle bundle = intent.getExtras();           //---get the SMS message passed in---
            SmsMessage[] msgs = null;
            String msg_from;
            if (bundle != null){
                //---retrieve the SMS message received---
                try{
                    Object[] pdus = (Object[]) bundle.get("pdus");
                    msgs = new SmsMessage[pdus.length];
                    for(int i=0; i<msgs.length; i++){
                        msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
                        msg_from = msgs[i].getOriginatingAddress();
                        msgBody = msgs[i].getMessageBody();
                    }

                    Toast.makeText(context,"message is:"+msgBody,Toast.LENGTH_SHORT).show();
                }catch(Exception e){
                    Log.d("Exception caught",e.getMessage());
                }
            }
        }
    }
}

and below is my activity:
public class MainActivity extends AppCompatActivity{

    SmsListener smsListener;

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

        smsListener= new SmsListener();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("android.provider.Telephony.SMS_RECEIVED");
        registerReceiver(smsListener, intentFilter);

    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();

        // Unregister the SMS receiver
        unregisterReceiver(smsListener);
    }

}

Surprisingly, I am getting no output at all (no Toast message) once the SMS is received. Can someone help? Thank you.

A: You are not declaring your receiver in Manifest file, because of it will not listen anything.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.zaidalmahmoud.expenseless">

<uses-permission android:name="android.permission.RECEIVE_SMS" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.SEND_SMS"/>

<application

    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

 <receiver android:name=".SmsListener"/>

</application>


text:
Q: Bad characters in Return Oriented Programming I am writing a rop chain for a vulnerable program (stack overflow, with NX and ASLR turned on).
I follow the execution of my gadgets by watching the stack pointer on gdb peda. It works well except when it encounters a gadget mov[eax], edx; ret. This gadget gets executed, but after there is a push ebx that follows, even if I didn't put any gadget like that in my ROP chain. And in the end my exploit doesn't work.
I have tried with different registers this instruction and there is always the push ebx that follows and I don't know why.
Would someone have an idea ?

A: Program is not always vulnerable under NX and ASLR enabled conditions.
In the most of time, you can't find enough gadget to produce your ROP exploit.
Maybe you could take a look of ROPgadget.
This tool could help you to find useful gadget to assemble ROP exploit.


text:
Q: create a grayscale image with an array of values I have a single dimensional array with 8 values. I want to create a grayscale image with those values. The image consist of a square with provided width and length. inside that square i want to produce circles with array values. The values from the array will be the radius of the circles. I need a grayscale image of that circle. Any help???

A: You can use ImageMagick for this, either directly from the commandline or from C/C++, Perl, Python, PHP etc.
Start with convert to get a white square 100pixels by 100pixels.
convert -size 100x100 xc:white circles.jpg

Change colour or file extension as you wish, e.g.
convert -size 200x200 xc:black circles.gif

Now add two circles with centre 50,50
convert -size 100x100 xc:white \
    -draw "circle 50,50,60,50" \
    -draw "circle 50,50,70,50" \
    circles.jpg

The \ is just a line continuation.
Back at my desk now.... so, here is a command:
#!/bin/bash
convert -size 400x400 xc:white  -fill transparent \
   -stroke gray90  -draw "circle 200,200,260,200" \
   -stroke gray80  -draw "circle 200,200,280,200" \
   -stroke gray70  -draw "circle 200,200,300,200" \
   -stroke gray60  -draw "circle 200,200,320,200" \
   -stroke gray50  -draw "circle 200,200,340,200" \
   -stroke gray40  -draw "circle 200,200,360,200" \
   -stroke gray30  -draw "circle 200,200,380,200" \
   -stroke gray20  -draw "circle 200,200,400,200" \
    circles.jpg

and the result:

Maybe you can execute it in Java with:
Runtime.exec(...)


text:
Q: Layout issues when working with TabController, NavigationController and NavigationView (SwiftUI) together I am working on the iOS legacy codebase with some SwiftUI views built. Everything looks good when app gets launched, but the Tab Bar title will be missing when navigate to another screen (either ViewController or SwiftUI view). It happens when navigate at the first time, the tab bar title will keep missing even though pops back.
This is how the tab bar looks after launching at the first time.
This is how the tab bar looks after navigating the other screens.
One more issue that I am facing is the navigation bar will be duplicate when navigate to a ViewController from SwiftUI view. The top one will be the nav bar from SwiftUI with a back button, the duplicate one will be from ViewController below the first one without the back button. What I expect is either the one from SwiftUI view with nav bar title, or the one from ViewController with the back button.
The top one is from SwiftUI view
Does anyone have some ideas how to fix them? Thank you!


text:
Q: libGDX - Button is set to down even if outside of bounds I'm am trying to properly setup button clicks for my UI. I want my buttons to respond right after clicking them instead of releasing by using ClickListeners touchDown method.
I've created a class which creates and displays a table with text input:
public class InputBox {

    public static float OFFSET = 20;

    private Table table;

    private TextField inputField;

    private TextButton okButton;
    private TextButton closeButton;

    private String saveText;

    private TextButtonStyle style;

    private Skin skin;

    public InputBox(Skin skin, float x, float y, float width, float height, boolean visible) {

        this.skin = skin;

        table = new Table();

        // Creating a new style as suggested.
        style = new TextButtonStyle();
        style.up = skin.getDrawable("button_normal_up");
        style.down = skin.getDrawable("button_normal_down");
        style.font = skin.getFont("default");

        inputField = new TextField("", skin);

        okButton = new TextButton("Ok", style);
        okButton.addListener(new ClickListener() {

            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

                if (button != Buttons.LEFT) {

                    return false;
                }
                Game.resources.getSound("click_2").play();
                table.setVisible(false);

                if (inputField.getText().equals("")) {

                    saveText = null;
                    return false;
                }

                saveText = inputField.getText();
                return true;
            }

        });

        closeButton = new TextButton("Close", style);
        closeButton.addListener(new ClickListener() {

            @Override
            public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

                if (button != Buttons.LEFT) {

                    return false;
                }
                Game.resources.getSound("click_2").play();

                saveText = null;

                table.setVisible(false);

                return true;
            }
        });

        table.setVisible(visible);

        table.setX(x);
        table.setY(y);

        table.setWidth(width);
        table.setHeight(height);

        table.add(inputField).colspan(2).center().width(width - OFFSET).expand().padRight(2);
        table.row();
        table.add(okButton).width(width / 2 - OFFSET / 2).right();
        table.add(closeButton).width(width / 2 - OFFSET / 2).left();
        table.pad(5);
    }

    public void setUnclicked() {

        style.down = skin.getDrawable("button_normal_up");

        // I think these two lines ar uneeded.
        okButton.setStyle(style);
        closeButton.setStyle(style);
    }

    public void setClicked() {

        style.down = skin.getDrawable("button_normal_down");

        // Same here.
        okButton.setStyle(style);
        closeButton.setStyle(style);
    }

    public void setText(String text) {

        inputField.setText(text);
    }

    public String getSaveTextOnce() {

        String temp = saveText;

        saveText = null;

        return temp;
    }

    public void setBackground(Drawable background) {

        table.setBackground(background);
    }

    public boolean isVisible() {

        return table.isVisible();
    }

    public void setVisible(boolean visible) {

        table.setVisible(visible);
    }

    public Table getTable() {

        return table;
    }
}

The table is being set to visible after clicking a different button:
// Save map button.
saveMap = new ImageButton(new ImageButtonStyle());
saveMap.getStyle().imageUp = uiSkin.getDrawable("save");
saveMap.getStyle().up = uiSkin.getDrawable("button_flat_up");
saveMap.getStyle().down = uiSkin.getDrawable("button_flat_down");

saveMap.addListener(new ClickListener() {

    public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

        if (button != Buttons.LEFT) {

            return false;
        }

        Game.resources.getSound("click_2").play();

        if (saveBox.isVisible()) {

            saveBox.setVisible(false);
            saveBox.setUnclicked();
            return false;
        }
        saveBox.setVisible(true);
        saveBox.setClicked();

        return true;
    }
});

The entire class for the saveMap button: http://pastebin.com/62ZGfcch
However, if I close the table by clicking the "ok" or "close" button and click and hold the mouse over the show table button, the table reappears with last clicked button being held down.
This video illustrates whats happening:
https://www.youtube.com/watch?v=Jf3WzU8G4dE&feature=youtu.be
If I move the mouse while holding it down, the last clicked button on the table resets to its normal state.

A: First i would recommend you to rather use a TextButtonStyle instance for setting the style of the buttons rather than a Skin instance.
You could somehow get the TextButton's references to the saveMap.addListener anonymous inner class. Then you could manualy set the style of the Ok and Cancel TextButton's, something like this:
public boolean touchDown(InputEvent event, float x, float y, int pointer, int button) {

    Game.resources.getSound("click_2").play();

    if (saveBox.isVisible()) {

        saveBox.setVisible(false);
        okButtonReference.setStyle(unclickedTextButtonStyle) // Not-clicked TextButtonStyle as parameter

        cancelButtonReference.setStyle(unclickedTextButtonStyle) // Not clicked TextButtonStyle as parameter.
        return false;
    }
    saveBox.setVisible(true);

    return true;
}

By forcing the TextButton to change it's TextButtonStyle by calling setStyle() you can be confident that the button will change.
Also i noticed that you are not calling the debug() method on the Table object. This is not necessary but it is advisable:
    table.add(inputField).colspan(2).center().width(width - OFFSET).expand().padRight(2);
    table.row();
    table.add(okButton).width(width / 2 - OFFSET / 2).right();
    table.add(closeButton).width(width / 2 - OFFSET / 2).left();
    table.pad(5);
    table.debug();

A: After more fiddling I found out that the way I setup my games InputProcessor was causing this issue. I did not handle the touchUp event properly.
Game.inputs.addProcessor(new InputProcessor() {

    ...

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {

        releasedButton = -1;

        if (UI.isOver()) {

            return false;
        }
        if (button == Buttons.LEFT) {

            releasedButton = Buttons.LEFT;
        }
        if (button == Buttons.RIGHT) {

            releasedButton = Buttons.RIGHT;
        }
        return true; // <--- setting this to false fixes the issue
    }
});


text:
Q: How to merge to a branch that is behind in network in Gitlab? I am quite new with Gitlab and I'm having an issue for merging in Eclipse.
We're working as a team, and we all have development branches that we are trying to merge into a single one. Unfortunately, when I did my merge, I have done a stupid mistake. Instead of merging my development branch to the main one, I have merged the main one into my development branch.
I have reversed the commit/merge on gitlab, but now as I try to merge back my development branch into the main one on Eclipse, it seems like I am 9 commits ahead of this branch (described as the arrows on Eclipse here: ), so the potential merge would basically replace everything by my code, when I should actually have merge conflicts to solve.
I am not quite sure how to merge properly so that I get back these merge conflicts.
Here is a screenshot of my network:

The ['1'] commit in the network on the left branch (my branch) corresponds to the merge from Week6AllIssues to my dev branch (the wrong merge). The last commit on this left branch is me reversing the commit.
Thanks a lot for your help !

A: If you're not using the remote branch with anyone else, the following series of steps might help.
First, remove the superfluous commits from the local branch. It can be achieved with git reset --hard <the commit before you merged master into your branch> command (see this link on how to do this with Eclipse).
Now make the remote branch match your local branch. You can do this with git push --force command. In Eclipse, this command corresponds to configure push - enable "force update" option.
Now the superfluous commits are gone.


text:
Q: How to build war from maven nonstandard structure project? I work on a project with some directory structure in my company. Now I have to convert project to Maven project. It's web app based on companies framework.
Project is exported to war file,
Here is structure of project:

web-app-name
    - WebContent
        - css
        - html
        - images
        - modules
        - WEB-INF
           - classes
           - config
           - data
           - lib
           - src
              - src_core
              - src_util
              - ... other src_
              - propertis.file

I can't use standard Maven structure.
So far I build pom.xml file and make project to work.
Dependencies are downloaded from private server and that works fine.
Problem is file structure. I try to override default maven paths, but no go.
When i export war file there is no css, html, images files ... There is just WEB-INF directory:

WEB-INF
  - classes
  - lib
META-INF

Is there a way to get all directories in war file that are under WebContent with some exceptions, or I can forget to convert project to Maven?
Pom file without dependencies:
...
<properties>
  <dborr.base.dir>${basedir}</dborr.base.dir>
</properties>
<build>
  <sourceDirectory>${dborr.base.dir}\coll_dborr\WebContent</sourceDirectory>
      <plugins>
  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
      <source>1.7</source>
      <target>1.7</target>
      <compilerVersion>1.7</compilerVersion>
    </configuration>
  </plugin>
  <plugin>
     <groupId>org.apache.maven.plugins</groupId>
     <artifactId>maven-war-plugin</artifactId>
      <version>2.6</version>
      <configuration>
         <warSourceDirectory>${dborr.base.dir}/coll_dborr/WebContent</warSourceDirectory>
       <webResources>
          <resource>
            <directory>${dborr.base.dir}/coll_dborr/WebContent/css</directory>
          </resource>
       </webResources>
      </configuration>
   </plugin>
</plugins>
</build>

Another question is there a way to include all source files to .classpath from pom.xml file?

A: Your solution should work, see Apache Maven WAR Plugin:

warSourceDirectory:
Single directory for extra files to include in the WAR. This is where you place your JSP files.
- Type: java.io.File
- Required: Yes
- Default: ${basedir}/src/main/webapp

But your path ${dborr.base.dir}\coll_dborr\WebContentis not right, it should be ${basedir}\web-app-name\WebContent.
Your sourceDirectory seems also not right, because it has to be the path to your sources not to your webapp resources.
Maybe you have also to remove webResources, because its already included in warSourceDirectory?


text:
Q: Fool python that it is called from tty The question is somewhat opposite to the Fool python's os.isatty from a bash script. I need python script to think that its stdin is attached to the tty.
In particular, I need to use some script, that changes its behavior depending on sys.stdin.isatty(). But when python is called in a bash loop, stdin.isatty() returns false
cat 'file.txt' | while read ENTRY
do
python -c "import sys; print sys.stdin.isatty()"
done

So is there a way to maybe wrap that call, so python will think that it is called from the tty.

A: In your case you could just try to redirect the input of the Python script alone:
cat 'file.txt' | while read ENTRY
do
  python -c "import sys; print sys.stdin.isatty()" < /dev/tty
done


text:
Q: handle large data set in R I  have   two large data sets , first data set is numeric , contains 60759 objects and 15 features the he second one is categorical contains 60759 objects and 9 features  ,I am trying to calculate Euclidean  distance   for numerical data set    and simple matching for categorical data set.  but i  could not  calculate them because of the size of data.
does any one has idea how can we handle large data in R

A: You can use Microsoft R Open with RevoScaleR library.
RevoScaleR library is designed to handle large amount of data by breaking into smaller chunks.
Look up here:
https://learn.microsoft.com/en-us/r-server/r/concept-what-is-revoscaler
https://learn.microsoft.com/en-us/r-server/r-client/what-is-microsoft-r-client

A: you can try the paralleldDist package C++ and multithread
https://cran.r-project.org/web/packages/parallelDist/parallelDist.pdf
parDist(x, method = "euclidean")


text:
Q: How do I reset ImageView memory in Android? My app is a question and answer type thing. So I load specific string into an activity and that activity display it. My problem is that when I change to a new question for example q1 -> q2, it will load a another string and also picture. But this picture stay in the memory after I change it to s2 -> s3 and thus leading to run out of memory. How do I reset the ImageView so it doesn't stay in the memory?
I'm pretty new to android.
The code is roughly like this.
    public void getdata(){
        imageView.setImageResource(0);
        switch (data){
            case 1;
            row1.setText(qt1r1);
            row2.setText(qt1r2);
            imageView.setImageResource(R.drawable.q1);
            break;
            case 2;
            row1.setText(qt2r1);
            row2.setText(qt2r2);
            imageView.setImageResource(R.drawable.q2);
            break;
        }

    }

A: It's depend on your resources resolutions.Here is a good library.You can fix your problem like this
Glide.with(fragment)
.load(R.drawable.resource_id)
.into(imageView);

For assets, you can construct an asset uri:
Glide.with(fragment)
.load(Uri.parse("file:///android_asset/assetName"))
.into(imageView);

Here is a library


text:
Q: Maven resource filtering - Explicitly specify which files require property injection Does the Maven resources plugin allow a flexible way to exclude certain files during the injection of Maven profile properties?

*

*I don't want to exclude the files from assembly, just from the injection phase.

The project I'm working on defines unique Maven Profiles (and corresponding properties) in Settings.xml for each deployment environment. When the project is built the following steps occur

*

*The projects POM defines the resources folder as the target to apply resource filtering

*The resources folder contains .XML and .PROPERTIES files

*During mvn:deploy Maven injects Profile properties into the .PROPERTIES file as expected

*Maven also injects Profile properties into .XML files. This is not desired behavior (these files contain placeholders which allow the project to flexible inject values during deploy of the application)

The resource plugin provides configuration options to define include and exclude options however choosing the exclude option will also exclude the specified file from the assembly folder which is not desired.
Is it possibly to tell Maven which files should have placeholders replaced?

A: You are probably using the filters mechanism, for which you can decide whether to apply it to a certain folder and which filter should be applied to that folder.
Given the following sample POM:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.sample</groupId>
    <artifactId>resources-example</artifactId>
    <version>1.0-SNAPSHOT</version>

    <build>
        <filters>
            <filter>src/main/filters/filter.properties</filter>
        </filters>

        <resources>
            <!-- configuring an additional resources folder: conf -->
            <resource>
                <directory>${project.basedir}/src/main/conf</directory>
                <filtering>true</filtering>
                <excludes>
                    <exclude>*.txt</exclude>
                </excludes>
                <includes>
                    <include>*.properties</include>
                </includes>
                <targetPath>${project.basedir}/target</targetPath>
            </resource>
        </resources>
    </build>
</project>

Note the filters section within the build section. Here we are telling Maven where how filter is, providing placeholders replacement.
Note then the <filtering>true</filtering> addition to a new resource configured afterwards and related includes/excludes patterns. As such, Maven will filter only the *.properties files of this folder.
Now, src/main/conf can contain a conf.properties file with the following content:
## add some properties here
property.example=@property.value1@
property.example2=${property.value2}

(Note the ant and maven style placeholders.)
While the src/main/filters (you need to create this folder) contains the filter.properties file with the following content:
property.value1=filtered-value1
property.value2=filtered-value2

Running the build you will get the conf.properties file in the target directory with the following content:
property.example=filtered-value1
property.example2=filtered-value2

Now, if your filter (file name) is a property injected by a profile, you can then inject different filters depending on the environment and only targeting certain files.


text:
Q: Nested Query Elastic Search Currently I am trying to search/filter a nested Document in Elastic Search Spring Data.
The Current Document Structure is:
{
  "id": 1,
  "customername": "Cust@123",
  "policydetails": {
    "address": {
      "city": "Irvine",
      "state": "CA",
      "address2": "23994384, Out OF World",
      "post_code": "92617"
    },
    "policy_data": [
      {
        "id": 1,
        "status": true,
        "issue": "Variation Issue"
      },
      {
        "id": 32,
        "status": false,
        "issue": "NoiseIssue"
      }
    ]
  }
}

Now we need to filter out the policy_data which has Noise Issue and If there is no Policy Data which has Noise Issue the policy_data will be null inside the parent document.
I have tried to use this Query
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "customername": "Cust@345"
          }
        },
        {
          "nested": {
            "path": "policiesDetails.policy_data",
            "query": {
              "bool": {
                "must": {
                  "terms": {
                    "policiesDetails.policy_data.issue": [
                      "Noise Issue"
                    ]
                  }
                }
              }
            }
          }
        }
      ]
    }
  }
}

This works Fine to filter nested Document. But If the Nested Document does not has the match it removes the entire document from the view.
What i want is if nested filter does not match:-
{
  "id": 1,
  "customername": "Cust@123",
  "policydetails": {
    "address": {
      "city": "Irvine",
      "state": "CA",
      "address2": "23994384, Out OF World",
      "post_code": "92617"
    },
    "policy_data": null
  }

A: If any nested document is not found then parent document will not be returned.
You can use should clause for policy_data. If nested document is found it will be returned under inner_hits otherwise parent document will be returned
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "customername": "Cust@345"
          }
        }
      ],
      "should": [
        {
          "nested": {
            "path": "policydetails.policy_data",
            "inner_hits": {},  --> to return matched policy_data
            "query": {
              "bool": {
                "must": {
                  "terms": {
                    "policydetails.policy_data.issue": [
                      "Noise Issue"
                    ]
                  }
                }
              }
            }
          }
        }
      ]
    }
  },
  "_source": ["id","customername","policydetails.address"] --> selected fields
}

Result:
{
  "_index" : "index116",
  "_type" : "_doc",
  "_id" : "f1SxGHoB5tcHqHDtAkTC",
  "_score" : 0.2876821,
  "_source" : {
    "policydetails" : {
      "address" : {
        "city" : "Irvine",
        "address2" : "23994384, Out OF World",
        "post_code" : "92617",
        "state" : "CA"
      }
    },
    "id" : 1,
    "customername" : "Cust@123"
  },
  "inner_hits" : {
    "policydetails.policy_data" : {
      "hits" : {
        "total" : {
          "value" : 0,
          "relation" : "eq"
        },
        "max_score" : null,
        "hits" : [ ]  -->  nested query result , matched document returned
      }
    }
  }
}


text:
Q: java.lang.ClassNotFoundException: net.ucanaccess.jdbc.UcanaccessDriver I'm doing a registration form which contains username,password,email and country.
whenever I submit the data , following  error is showing up :
java.lang.ClassNotFoundException: net.ucanaccess.jdbc.UcanaccessDriver
Following is my code:
register.java:
import java.io.IOException;

import java.io.PrintWriter;

import java.sql.*;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 @WebServlet("/servregister")
    public class Register extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse
    response) throws ServletException, IOException {

    doPost(request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    response.setContentType("text/html");

    PrintWriter out=response.getWriter();

    String n = request.getParameter("username");
    String u = request.getParameter("password");
    String em = request.getParameter("usermail");
    String c = request.getParameter("usercountry");

    try{
        Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
        Connection conn=DriverManager.getConnection(
                "jdbc:ucanaccess://C:/Users/e48265/Documents/Database2.accdb");
        System.out.println("connection made...");

        PreparedStatement ps=conn.prepareStatement("insert into Register values(?,?,?,?)");

        ps.setString(1, n);
        ps.setString(2, u);
        ps.setString(3, em);
        ps.setString(4, c);

        int i=ps.executeUpdate();
        if(i>0){
            out.print("user successfully registered");
        }
    }catch(SQLException e){
        e.printStackTrace();
    }catch(ClassNotFoundException ce){
            ce.printStackTrace();
        }

    out.close();

}

}

I've added all 5 jar files of ucanaccess in eclipse and  in web appication's WebContent - WEB-INF - lib folder. Can anyone solve this?


text:
Q: Assertion for a test step is not being recognized by groovy script when run on Jenkins I have a "Property Content" JsonPath Existence Match assertion for a Test Step in a test case. Its a REST service and have assertion as following:
$.recommendedFood[0].calories
I have the following code def assertsize = testStep.getAssertionList().size()
This works fine when i print out running the groovy script on SOAP UI ( locally)log.info (testStep.getAssertionList().size()) output is 1
But the same when run on Jenkins, the size is printed as 0( no change in the script, but it doesnt recognize the test step.
Also i see error 23:41:42,500 ERROR [TestAssertionRegistry] Missing assertion for type [JsonPath Existence Match]
I tried solutions : SoapUI Testrunner giving error about TestAssertionRegistry
https://community.smartbear.com/t5/API-Functional-Security-Testing/Maven-Soapui-Plugin-with-json-assertions-does-not-work-well-in/td-p/106777
but could not solve the issue. Any solutions or fixes for that?


text:
Q: On cyclic right $R/I$-modules for two sided ideal $I$ of $R$ Let $R$ be a ring such that every cyclic right $R$ module is either injective or projective and let $I$ be a two sided ideal of $R$ . Then why is every cyclic right $R/I$-module either injective  or projective ? And if $R/I$ is injective , then why is every cyclic right $R/I$-module injective ? This is Lemma 1 in http://www.ams.org/journals/proc/1975-053-01/S0002-9939-1975-0382349-X/S0002-9939-1975-0382349-X.pdf
, and there it is said that the fact is clear from the paper http://www.ams.org/journals/proc/1968-019-06/S0002-9939-1968-0231857-7/S0002-9939-1968-0231857-7.pdf
; but I couldn't find anything in that paper to deduce this facts . Please help . Thanks in advance

A: A cyclic $R/I$-module is a cyclic $R$-module on which $I$ acts as zero. If $M$ is an $R/I$-module that is injective (or projective) as an $R$-module then it is injective (or projective) as an $R/I$-module, since every injective map $M\to X$ of $R/I$-modules is an injective map of $R$-modules, and therefore splits.
If $R/I$ is injective as an $R/I$-module and $P$ is a cyclic $R/I$-module that is projective, then the natural surjection $R/I\to P$ splits, and so $P$ is also an injective $R/I$-module.
The reference to Osofsky's paper is not relevant for this, but for the second part of Lemma 1, that you didn't reproduce.


text:
Q: Array/Object strange behavior Following Javascript:
WORKING
            //Going to set on local storage on an iPhone
            window.localStorage.setItem("emailaddress", "test@test.de");
            //Loading local storage
            var storage = window.localStorage.getItem("emailaddress");
            alert(storage); //test@test.de
            var servicename = "test";
            window.plugins.keychain.getForKey(storage, servicename);

NOT WORKING
            //Going to set on local storage on an iPhone
            window.localStorage.setItem("emailaddress", "test@test.de" + ":1");
            //Loading local storage
            var storage = window.localStorage.getItem("emailaddress");
            var array = new Array();
            var array = storage.split(":");
            var emailaddress = array[0];
            alert(emailaddress); //test@test.de
            var servicename = "test";
            window.plugins.keychain.getForKey(emailaddress, servicename);

Why? Actually I need the second one because I want to store more than with the emailaddress, e.g emailaddress/state/timestamp....


text:
Q: Rails Controller - Return and then perform complex action (without worker) I want to create an API endpoint in my app that takes data and performs a complex, time-consuming operation with it, but only after returning that the data has been received.
As in, I'd love to be able to do something like this:
def action
  render json: { data_received: params[:whatever].present? }
  perform_calculations( params[:whatever] )
end

Unfortunately, as I understand it, Ruby/Rails is synchronous, and requires that a controller action end in a render/redirect/head statement of some sort.
Ordinarily, I'd think of accomplishing this with a background worker, like so:
 def action
   DelayedJobActionPerformer.perform_later(params[:whatever])
   render { data_received: params[:whatever].present? }
 end

But a worker costs (on Heroku) a fair amount of monthly money for a beginning app like this, and I'm looking for alternatives. Is there any alternative to background workers you can think of to return from the action and then perform the behavior?
I'm thinking of maybe creating a separate Node app or something that can start an action and then respond, but that's feeling ridiculous. I guess the architecture in my mind would involve a main Rails app which performs most of the behavior, and a lightweight Node app that acts as the API endpoint, which can receive a request, respond that it's been received, and then send on the data to be performed by that first Rails app, or another. But it feels excessive, and also like just kicking the problem down the road.
At any rate, whether or not I end up having to buy a worker or few, I'd love to know if this sort of thing is feasible, and whether using an external API as a quasi-worker makes sense (particularly given the general movement towards breaking up application concerns).

A: Not really...
Well you can spawn a new thread:
thread = Thread.new { perform_calculations( params[:whatever] ) }

And not call thread.join, but that is highly unreliable, because that thread will be killed if the main thread terminates.
I don't know how things with cron jobs are in Heroku, but another option is to have a table with pending jobs where you save params[:whatever] and have a rake task that is triggered with cron periodically to check and perform any pending tasks. This solution is a (really) basic worker implementation.

A: Heard about sucker_punch, you can give it a try. This will run in single webprocess but the downside is that if the web processes is restarted and there are jobs that haven't yet been processed, they will be lost. So not recommended for critical background tasks.


text:
Q: Django--HELP. django not creating sqlite database file as expected New to django
following tutorial 1. also looked up all related questions on stack overflow.  thought it was a absolute path issue...but absolute path seems to be correct. below is settings.py. any ideas?
MANAGERS = ADMINS

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql',    'sqlite3' or 'oracle'.
        'NAME': 'Users/Leerix/cars/carfilter/database/temp.db',                      #     Or path to database file if using sqlite3.
        'USER': '',                      # Not used with sqlite3.
        'PASSWORD': '',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used     with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }

Below is the error i'm getting.  Been at this for several hours and cannot find the bug.  any help is greatly appreciated. Thx
python manage.py syncdb
Traceback (most recent call last):
  File "manage.py", line 9, in <module>
    execute_from_command_line(sys.argv)
  File "/Library/Python/2.5/site-packages/django/core/management/__init__.py", line 420,  in execute_from_command_line
    utility.execute()
  File "/Library/Python/2.5/site-packages/django/core/management/__init__.py", line 359, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 196, in   run_from_argv
    self.execute(*args, **options.__dict__)
  File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 232, in execute
    output = self.handle(*args, **options)
  File "/Library/Python/2.5/site-packages/django/core/management/base.py", line 371, in   handle
    return self.handle_noargs(**options)
  File "/Library/Python/2.5/site-packages/django/core/management/commands/syncdb.py", line 57, in handle_noargs
    cursor = connection.cursor()
  File "/Library/Python/2.5/site-packages/django/db/backends/__init__.py", line 306, in  cursor
        cursor = self.make_debug_cursor(self._cursor())
      File "/Library/Python/2.5/site-packages/django/db/backends/sqlite3/base.py", line 259, in _cursor
        self.connection = Database.connect(**kwargs)
sqlite3.OperationalError: unable to open database file

A: Perhaps you meant to use an absolute path (one starting with /) instead of a relative path.

A: Delete the database file at that location. Also, the path starting with Users isn't absolute (is it?) make sure if you're on windows that it starts with a drive letter. (C:\)


text:
Q: getting the operations (a.k.a methods or functions) in a soap web service from the wsdl with .net core mvc I need a way to find the operations in a SOAP web service using the WSDL of the web service.

A: You may use a public wsdl url such as http://www.thomas-bayer.com/axis2/services/BLZService?wsdl or https://www.lb.lt/webservices/ExchangeRates/ExchangeRates.asmx?WSDL for testing. The solution is as follows: 1) get the contents of the wsdl url. 2) Parse the wsdl xml for the operations. The code is as follows.
public string[] GetOperations(string wsdlURL)
{

    //string httpResponseMessage;
    List<string> sList = new List<string>();
    string[] s = { };
    string result = GetWSDLContent(wsdlURL);
    XmlDocument doc = new XmlDocument();
        doc.LoadXml(result);

    var nsmgr = new XmlNamespaceManager(doc.NameTable);
    nsmgr.AddNamespace("wsdl", "http://schemas.xmlsoap.org/wsdl/");
    var nl = doc.SelectNodes("//wsdl:portType/wsdl:operation", nsmgr);
    for (var i=0; i<nl.Count; i++ )
    {
        sList.Add(nl[i].Attributes["name"].Value.ToString());
    }
    s = sList.ToArray();
    return s;
}
public string GetWSDLContent(string wsdlURL)
{
    HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(wsdlURL);
    myRequest.Method = "GET";
    WebResponse myResponse = myRequest.GetResponse();
    StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
    string result = sr.ReadToEnd();
    sr.Close();
    myResponse.Close();
    return result;
}