问:
Maven Shade Plugin and DataNucleus issue
I'm trying to execute a working code out of my eclipse IDE and I'm facing strange errors I can't deal with.
Trying to sum up my problems :

Executing my code with eclipse : Everything's fine.

Capturing the command line thrown by eclipse to run my app, and copying it into a shell : Everything's fine.

Now, the command line generated by eclipse to run my app is something like java -cp lots-of-jars -Dvm.params myPackage.MyMainClass app-params.

My objective is to execute my App with Oozie as a Java Action, so I need to build an uber jar to reduce lots-of-jars to myapp.jar.

To do so, I configured the maven shade plugin like this :

```<code>         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.4.2</version>
            <configuration>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <filters>
                            <filter>
                                <artifact>*:*</artifact>
                                <excludes>
                                    <exclude>META-INF/*.SF</exclude>
                                    <exclude>META-INF/*.DSA</exclude>
                                    <exclude>META-INF/*.RSA</exclude>
                                </excludes>
                            </filter>
                        </filters>
                        <transformers>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                <resource>reference.conf</resource>
                            </transformer>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>es.mycompany.bigdata.OozieAction</mainClass>
                            </transformer>

<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.PluginXmlResourceTransformer" />
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>
</code>```

I had to add some transformers because of some errors I was facing starting my app (can't create FsShell Spring object, can't start SparkContext..)
By the way, my app purpose is to download some azure blobs, put then into HDFS, transform them with Spark to finally add then to a Hive table.
I developed the app in Java (including the spark part) and used Spring to do so.

Now, my last new problem occurs when I'm trying to create a HiveContext (my spark context is ok, as my app works if I omit the hive part) :

```<code>@Bean
@Lazy
@Scope("singleton")
public SQLContext getSQLContext(@Autowired JavaSparkContext sparkContext) {
    return new HiveContext(sparkContext);
}
</code>```

The error thrown is :

```<code>2017-04-02 20:20:18 WARN  Persistence:106 - Error creating validator of type org.datanucleus.properties.CorePropertyValidator
ClassLoaderResolver for class "" gave error on creation : {1}
org.datanucleus.exceptions.NucleusUserException: ClassLoaderResolver for class "" gave error on creation : {1}
...
Caused by: org.datanucleus.exceptions.NucleusUserException: Persistence process has been specified to use a ClassLoaderResolver of name "datanucleus" yet this has not been found by the DataNucleus plugin mechanism. Please check your CLASSPATH and plugin specification.
        at org.datanucleus.NucleusContext.<init>(NucleusContext.java:283)
        at org.datanucleus.NucleusContext.<init>(NucleusContext.java:247)
        at org.datanucleus.NucleusContext.<init>(NucleusContext.java:225)
        at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.<init>(JDOPersistenceManagerFactory.java:416)
        at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.createPersistenceManagerFactory(JDOPersistenceManagerFactory.java:301)
        at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.getPersistenceManagerFactory(JDOPersistenceManagerFactory.java:202)
        ... 93 more
2017-04-02 20:20:18 WARN  ExtendedAnnotationApplicationContext:550 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getOozieJavaAction': Unsatisfied dependency expressed through field 'sqlContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSQLContext' defined in es.mediaset.technology.bigdata.config.FlatJsonToCsvAppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.spark.sql.SQLContext]: Factory method 'getSQLContext' threw exception; nested exception is java.lang.RuntimeException: org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient
</code>```

As my code correctly runs in eclipse, and out of eclipse with such a command

```<code>/usr/java/jdk1.8.0_121/bin/java -Dmode=responsive -Dspark.master=local[*] -Dfile.encoding=UTF-8 -classpath /home/cloudera/workspace-sts/oozie-eventhub-retriever/target/classes:/home/cloudera/workspace-sts/java-framework/target/classes:/home/cloudera/.m2/repository/com/microsoft/azure/azure-storage/5.0.0/azure-storage-5.0.0.jar:<...>:/etc/hive/conf.dist es.mycompany.technology.bigdata.OozieAction json2hive
</code>```

I suppose my shade configuration is wrong. But I can't understand why, and I can't see what's I'm doing wrong...

Thanks

答:
The following Stackoverflow Q/A answers this question : Apache spark Hive, executable JAR with maven shade   </p>

<p>For those who don't understand how to "merge" all the plugin.xml files from datanucleus, you can take this one : plugin.xml and paste it in your resource folder. </p>

Body:
I'm trying to execute a working code out of my eclipse IDE and I'm facing strange errors I can't deal with.
Trying to sum up my problems :

Executing my code with eclipse : Everything's fine.

Capturing the command line thrown by eclipse to run my app, and copying it into a shell : Everything's fine.

Now, the command line generated by eclipse to run my app is something like java -cp lots-of-jars -Dvm.params myPackage.MyMainClass app-params.

My objective is to execute my App with Oozie as a Java Action, so I need to build an uber jar to reduce lots-of-jars to myapp.jar.

To do so, I configured the maven shade plugin like this :

         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>2.4.2</version>
            <configuration>
            </configuration>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals>
                        <goal>shade</goal>
                    </goals>
                    <configuration>
                        <filters>
                            <filter>
                                <artifact>*:*</artifact>
                                <excludes>
                                    <exclude>META-INF/*.SF</exclude>
                                    <exclude>META-INF/*.DSA</exclude>
                                    <exclude>META-INF/*.RSA</exclude>
                                </excludes>
                            </filter>
                        </filters>
                        <transformers>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                <resource>reference.conf</resource>
                            </transformer>
                            <transformer
                                implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                <mainClass>es.mycompany.bigdata.OozieAction</mainClass>
                            </transformer>

<transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
<transformer implementation="org.apache.maven.plugins.shade.resource.PluginXmlResourceTransformer" />
                        </transformers>
                    </configuration>
                </execution>
            </executions>
        </plugin>

I had to add some transformers because of some errors I was facing starting my app (can't create FsShell Spring object, can't start SparkContext..)
By the way, my app purpose is to download some azure blobs, put then into HDFS, transform them with Spark to finally add then to a Hive table.
I developed the app in Java (including the spark part) and used Spring to do so.

Now, my last new problem occurs when I'm trying to create a HiveContext (my spark context is ok, as my app works if I omit the hive part) :

@Bean
@Lazy
@Scope("singleton")
public SQLContext getSQLContext(@Autowired JavaSparkContext sparkContext) {
    return new HiveContext(sparkContext);
}

The error thrown is :

2017-04-02 20:20:18 WARN  Persistence:106 - Error creating validator of type org.datanucleus.properties.CorePropertyValidator
ClassLoaderResolver for class "" gave error on creation : {1}
org.datanucleus.exceptions.NucleusUserException: ClassLoaderResolver for class "" gave error on creation : {1}
...
Caused by: org.datanucleus.exceptions.NucleusUserException: Persistence process has been specified to use a ClassLoaderResolver of name "datanucleus" yet this has not been found by the DataNucleus plugin mechanism. Please check your CLASSPATH and plugin specification.
        at org.datanucleus.NucleusContext.<init>(NucleusContext.java:283)
        at org.datanucleus.NucleusContext.<init>(NucleusContext.java:247)
        at org.datanucleus.NucleusContext.<init>(NucleusContext.java:225)
        at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.<init>(JDOPersistenceManagerFactory.java:416)
        at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.createPersistenceManagerFactory(JDOPersistenceManagerFactory.java:301)
        at org.datanucleus.api.jdo.JDOPersistenceManagerFactory.getPersistenceManagerFactory(JDOPersistenceManagerFactory.java:202)
        ... 93 more
2017-04-02 20:20:18 WARN  ExtendedAnnotationApplicationContext:550 - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'getOozieJavaAction': Unsatisfied dependency expressed through field 'sqlContext'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'getSQLContext' defined in es.mediaset.technology.bigdata.config.FlatJsonToCsvAppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.spark.sql.SQLContext]: Factory method 'getSQLContext' threw exception; nested exception is java.lang.RuntimeException: org.apache.hadoop.hive.ql.metadata.HiveException: java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

As my code correctly runs in eclipse, and out of eclipse with such a command

/usr/java/jdk1.8.0_121/bin/java -Dmode=responsive -Dspark.master=local[*] -Dfile.encoding=UTF-8 -classpath /home/cloudera/workspace-sts/oozie-eventhub-retriever/target/classes:/home/cloudera/workspace-sts/java-framework/target/classes:/home/cloudera/.m2/repository/com/microsoft/azure/azure-storage/5.0.0/azure-storage-5.0.0.jar:<...>:/etc/hive/conf.dist es.mycompany.technology.bigdata.OozieAction json2hive

I suppose my shade configuration is wrong. But I can't understand why, and I can't see what's I'm doing wrong...

Thanks

Body:
The following Stackoverflow Q/A answers this question : Apache spark Hive, executable JAR with maven shade

For those who don't understand how to "merge" all the plugin.xml files from datanucleus, you can take this one : plugin.xml and paste it in your resource folder.


来源: stackexchange

问:
How do I read from a named file?
I'm trying to copy all the lines from an input file to another file:

```<code>#!/bin/bash
in=$1
file="current_line.txt"
let count=0
echo $count
while read LINE
do
        (( count++ ))
        echo $count
        echo $LINE > $file
done
</code>```

Why doesn't the read command get its input from the file I gave as argument to the script?

答:
```<code>#!/bin/bash

in=$1
file="current_line.txt"
count=0
echo $count

while read -r LINE
do
        echo $LINE >> $file
        count=$((count + 1))
        echo $count

done < "$in"
</code>```

Supply the input file at the end of the done in the way described above.

ContentLicense: CC BY-SA 3.0

Title: How do I read from a named file?

Body:
I'm trying to copy all the lines from an input file to another file:

#!/bin/bash
in=$1
file="current_line.txt"
let count=0
echo $count
while read LINE
do
        (( count++ ))
        echo $count
        echo $LINE > $file
done

Why doesn't the read command get its input from the file I gave as argument to the script?

Body:
#!/bin/bash

in=$1
file="current_line.txt"
count=0
echo $count

while read -r LINE
do
        echo $LINE >> $file
        count=$((count + 1))
        echo $count

done < "$in"

Supply the input file at the end of the done in the way described above.


问:
MongoDB setup with node.js: Error: failed to connect to [localhost:27017]
I am getting the error:
"failed to connect to [localhost:27017]" while trying to follow this tutorial.

I've been attempting to do several other node.js tutorials with mongoDB over the past few days, and each one runs into similar problems.
The other solutions I've found surrounding this all involve people not having the server running when trying to connect. I have mongod running in a terminal window, can view the info in the browser at localhost, and have added and viewed records to the database through the mongo shell. All of that appears to be working. The breakage seems to be in connecting any of the node.js projects to the database, but being pretty new to this, I am not even sure where to begin troubleshooting.

RESOLVED: very stupid mistake on my part. The file suggested by Neil below (view here was instrumental in helping me to troubleshoot and find the problem, though.

needed to change the line

```<code>mongoose.connect('mongodb://localhost/MyApp');
</code>```

to

```<code>mongoose.connect('mongodb://127.0.0.1:27017/test');
</code>```

in the server.js file.

Additional note: for reasons I don't quite understand, specifying the address as 127.0.0.1: works, but localhost: does not.

答:
just start mongo server
or run on mongo.exe and type

mongod

then

mongo

Body:
I am getting the error:
"failed to connect to [localhost:27017]" while trying to follow this tutorial.

I've been attempting to do several other node.js tutorials with mongoDB over the past few days, and each one runs into similar problems.
The other solutions I've found surrounding this all involve people not having the server running when trying to connect. I have mongod running in a terminal window, can view the info in the browser at localhost, and have added and viewed records to the database through the mongo shell. All of that appears to be working. The breakage seems to be in connecting any of the node.js projects to the database, but being pretty new to this, I am not even sure where to begin troubleshooting.

RESOLVED: very stupid mistake on my part. The file suggested by Neil below (view here was instrumental in helping me to troubleshoot and find the problem, though.

needed to change the line

mongoose.connect('mongodb://localhost/MyApp');

to

mongoose.connect('mongodb://127.0.0.1:27017/test');

in the server.js file.

Additional note: for reasons I don't quite understand, specifying the address as 127.0.0.1: works, but localhost: does not.


问:
How to REGEX and .htaccess rewrite url
I have this url and I need to grab the tags and rewrite the url

http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=1&tag=Social%20Media&limit=20&IncludeBlogs=1

So, in the example above to something more like this http://beantownbride.com/?s=Social+Media

Here is what I have so far for my .htaccess file

```<code>RewriteRule ^http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=(*.)&tag=(*.) http://beantownbride.com/?s=$2
</code>```

but it only works for the first tag
(if it works at all)

the whole .htaccess file

```<code>RewriteEngine On
# BEGIN WordPress

#MT to WP
# Convert old archives
RewriteRule ^/archives/([0-9]*)\.php$ /$1/ [R=301,L]
RewriteRule ^/archives/([0-9]*)\.html$ /$1/ [R=301,L]
RewriteRule ^/archives/([0-9]*)\.shtml$ /$1/ [R=301,L]
RewriteRule ^/archives/([0-9][0-9][0-9][0-9]/[0-9][0-9]/.*)\.php$ /$1/ [R=301,L]
RewriteRule ^/archives/old/([0-9]*)\.php$ /$1/ [R=301,L]
RewriteRule ^/archives/cat_(.+)\.php$ /category/$1/ [R=301,L]
RewriteRule ^/archives/cat_(.+)\.html$ /category/$1/ [R=301,L]
RewriteRule ^/archives/cat_(.+)\.shtml$ /category/$1/ [R=301,L]
RewriteRule ^/archives/?$ /archive/ [R=301,L]
RewriteCond %{REQUEST_URI} !^/archives/[0-9][0-9][0-9][0-9]/[0-9][0-9]/?.*$ [NC]
RewriteCond %{REQUEST_URI} !^/archives/[0-9][0-9][0-9][0-9][0-9][0-9]\.?.*$ [NC]
RewriteCond %{REQUEST_URI} !^/archives/tag/.*$ [NC]
RewriteCond %{REQUEST_URI} !^/archives/author/.*$ [NC]
RewriteRule ^/archives/(.*)$ /category/$1 [R=301,L]
RewriteRule ^/archives/(.*)$ /$1 [R=301,L]

# Change underscores hyphens
RewriteRule ^/category/([^_]*)_([^_]*)_([^_]*)_(.*)$ /category/$1-$2-$3-$4/ [R=301,L]
RewriteRule ^/category/([^_]*)_([^_]*)_(.*)$ /category/$1-$2-$3/ [R=301,L]
RewriteRule ^/category/([^_]*)_(.*)$ /category/$1-$2/ [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9])/([^_/]*)_([^_/]*)_([^_/]*)_(.*)/(.+)$ /$1/$2-$3-$4-$5/$6 [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9])/([^_/]*)_([^_/]*)_(.*)/(.+)$ /$1/$2-$3-$4/$5 [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9])/([^_/]*)_(.*)/(.+)$ /$1/$2-$3/$4 [R=301,L]

# Change to wordpress feeds
RewriteRule ^/atom$ /wp-atom.php [R=301,L]
RewriteRule ^/atom\.xml$ /wp-atom.php [R=301,L]
RewriteRule ^/index\.atom$ /wp-atom.php [R=301,L]
RewriteRule ^/index\.rdf$ /wp-rdf.php [R=301,L]
RewriteRule ^/index\.xml$ /wp-rss2.php [R=301,L]
RewriteRule ^/rss\.xml$ /wp-rss.php [R=301,L]
Redirect permanent /rss.xml /feed/

RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9]/.*)\.atom$ /$1/feed/ [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9]/.*)\.atom/$ /$1/feed/ [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9]/.*)\.xml$ /$1/feed/ [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9]/.*)\.xml/$ /$1/feed/ [R=301,L]

Redirect permanent /about.html /about
Redirect permanent /advertise.html /advertise
Redirect permanent /contact.html /contact
Redirect permanent /welcome-about/ /about/
Redirect permanent /welcome-about/welcome-to-my-blog.html /about/
Redirect permanent /real-wedding /real-weddings

RewriteRule ^/events/(.*)$ /?s=events

#http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=1&tag=Social%20Media&limit=20&IncludeBlogs=1
#RewriteRule ^/darkroom/mt/mt-search.cgi?blog_id=1&tag=(*.)&limit
#http://beantownbride.com/?s=test+tag+blah

#RewriteRule ^http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=(.*)&tag=(.*)$ http://beantownbride.com/?s=$2
RewriteRule ^http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=(.*)&tag=(.*)$ http://beantownbride.com/?s=$2

<IfModule mod_rewrite.c>
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
</code>```

答:
I think you're missing the $ end tag for your Regular Expression. Try the next line instead:

```<code>RewriteRule ^http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=(*.)&tag=(*.)$ http://beantownbride.com/?s=$2
</code>```

also, check this article for additional rules and options:

http://www.workingwith.me.uk/articles/scripting/mod_rewrite

ContentLicense: CC BY-SA 2.5

Title: How to REGEX and .htaccess rewrite url

Body:
I have this url and I need to grab the tags and rewrite the url

http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=1&tag=Social%20Media&limit=20&IncludeBlogs=1

So, in the example above to something more like this http://beantownbride.com/?s=Social+Media

Here is what I have so far for my .htaccess file

RewriteRule ^http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=(*.)&tag=(*.) http://beantownbride.com/?s=$2

but it only works for the first tag
(if it works at all)

the whole .htaccess file

RewriteEngine On
# BEGIN WordPress

#MT to WP
# Convert old archives
RewriteRule ^/archives/([0-9]*)\.php$ /$1/ [R=301,L]
RewriteRule ^/archives/([0-9]*)\.html$ /$1/ [R=301,L]
RewriteRule ^/archives/([0-9]*)\.shtml$ /$1/ [R=301,L]
RewriteRule ^/archives/([0-9][0-9][0-9][0-9]/[0-9][0-9]/.*)\.php$ /$1/ [R=301,L]
RewriteRule ^/archives/old/([0-9]*)\.php$ /$1/ [R=301,L]
RewriteRule ^/archives/cat_(.+)\.php$ /category/$1/ [R=301,L]
RewriteRule ^/archives/cat_(.+)\.html$ /category/$1/ [R=301,L]
RewriteRule ^/archives/cat_(.+)\.shtml$ /category/$1/ [R=301,L]
RewriteRule ^/archives/?$ /archive/ [R=301,L]
RewriteCond %{REQUEST_URI} !^/archives/[0-9][0-9][0-9][0-9]/[0-9][0-9]/?.*$ [NC]
RewriteCond %{REQUEST_URI} !^/archives/[0-9][0-9][0-9][0-9][0-9][0-9]\.?.*$ [NC]
RewriteCond %{REQUEST_URI} !^/archives/tag/.*$ [NC]
RewriteCond %{REQUEST_URI} !^/archives/author/.*$ [NC]
RewriteRule ^/archives/(.*)$ /category/$1 [R=301,L]
RewriteRule ^/archives/(.*)$ /$1 [R=301,L]

# Change underscores hyphens
RewriteRule ^/category/([^_]*)_([^_]*)_([^_]*)_(.*)$ /category/$1-$2-$3-$4/ [R=301,L]
RewriteRule ^/category/([^_]*)_([^_]*)_(.*)$ /category/$1-$2-$3/ [R=301,L]
RewriteRule ^/category/([^_]*)_(.*)$ /category/$1-$2/ [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9])/([^_/]*)_([^_/]*)_([^_/]*)_(.*)/(.+)$ /$1/$2-$3-$4-$5/$6 [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9])/([^_/]*)_([^_/]*)_(.*)/(.+)$ /$1/$2-$3-$4/$5 [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9])/([^_/]*)_(.*)/(.+)$ /$1/$2-$3/$4 [R=301,L]

# Change to wordpress feeds
RewriteRule ^/atom$ /wp-atom.php [R=301,L]
RewriteRule ^/atom\.xml$ /wp-atom.php [R=301,L]
RewriteRule ^/index\.atom$ /wp-atom.php [R=301,L]
RewriteRule ^/index\.rdf$ /wp-rdf.php [R=301,L]
RewriteRule ^/index\.xml$ /wp-rss2.php [R=301,L]
RewriteRule ^/rss\.xml$ /wp-rss.php [R=301,L]
Redirect permanent /rss.xml /feed/

RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9]/.*)\.atom$ /$1/feed/ [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9]/.*)\.atom/$ /$1/feed/ [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9]/.*)\.xml$ /$1/feed/ [R=301,L]
RewriteRule ^/([0-9][0-9][0-9][0-9]/[0-9][0-9]/.*)\.xml/$ /$1/feed/ [R=301,L]

Redirect permanent /about.html /about
Redirect permanent /advertise.html /advertise
Redirect permanent /contact.html /contact
Redirect permanent /welcome-about/ /about/
Redirect permanent /welcome-about/welcome-to-my-blog.html /about/
Redirect permanent /real-wedding /real-weddings

RewriteRule ^/events/(.*)$ /?s=events

#http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=1&tag=Social%20Media&limit=20&IncludeBlogs=1
#RewriteRule ^/darkroom/mt/mt-search.cgi?blog_id=1&tag=(*.)&limit
#http://beantownbride.com/?s=test+tag+blah

#RewriteRule ^http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=(.*)&tag=(.*)$ http://beantownbride.com/?s=$2
RewriteRule ^http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=(.*)&tag=(.*)$ http://beantownbride.com/?s=$2

<IfModule mod_rewrite.c>
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

Body:
I think you're missing the $ end tag for your Regular Expression. Try the next line instead:

RewriteRule ^http://beantownbride.com/darkroom/mt/mt-search.cgi?blog_id=(*.)&tag=(*.)$ http://beantownbride.com/?s=$2

also, check this article for additional rules and options:

http://www.workingwith.me.uk/articles/scripting/mod_rewrite


问:
Protractor Drag and Drop In SVG Element
I am facing the problem in drag and drop the element to one editor page and editor page is SVG element. I am using this code, but it is not working</p>

```<code>var dragAndDrop = require('html-dnd').code;
var dragDataType=element(By.id('{"name":"Filter","type":"Filter","icon":"filter_list","iconHex":""}'));
var dropDataType= element(By.id('___content'));
var offsetX = 1;
var offsetY = 1;
var offsetX = 300;
var offsetY = 250;
browser.executeScript(dragAndDrop, dragDataType, dropDataType, offsetX,offsetY);
</code>```

答:
I have implemented drag and drop like this:

```<code> xxxx.protorype.dragNDrop= function(){
  var offsetx = <offsetValueX>;
  var offsety = <offsetValueY>;
  this.getDropIndex(dragElement, function (dropIndex) {
    var dropElement = element(<locator>).get(dropIndex);
    dropElement.getLocation().then(function (location) {
      offsetx = Math.round(offsetx + location.x);
      browser.actions().mouseMove(dragElement)
        .mouseDown()
        .mouseMove(dropElement)
        .mouseMove(dropElement, {x: offsetx, y: offsety})
        .mouseUp().perform();
    });
    browser.waitForAngular();
    expect(element(<your locator>).getAttribute()).toBe(dragElement.getAttribute());
  });
  };

  xxxx.prototype.getDropIndex = function (elementHolder, callback) {
  browser.waitForAngular();
  elementHolder.getText().then(function (elementName) {
  var index;
    if (callback) {
      callback(index);
    }
  });
};
</code>```

Here it is done using the browser.actions(), since there is not in build function. I have used like this.

Title: Protractor Drag and Drop In SVG Element

Body:
I am facing the problem in drag and drop the element to one editor page and editor page is SVG element. I am using this code, but it is not working

var dragAndDrop = require('html-dnd').code;
var dragDataType=element(By.id('{"name":"Filter","type":"Filter","icon":"filter_list","iconHex":""}'));
var dropDataType= element(By.id('___content'));
var offsetX = 1;
var offsetY = 1;
var offsetX = 300;
var offsetY = 250;
browser.executeScript(dragAndDrop, dragDataType, dropDataType, offsetX,offsetY);

Body:
I have implemented drag and drop like this:

 xxxx.protorype.dragNDrop= function(){
  var offsetx = <offsetValueX>;
  var offsety = <offsetValueY>;
  this.getDropIndex(dragElement, function (dropIndex) {
    var dropElement = element(<locator>).get(dropIndex);
    dropElement.getLocation().then(function (location) {
      offsetx = Math.round(offsetx + location.x);
      browser.actions().mouseMove(dragElement)
        .mouseDown()
        .mouseMove(dropElement)
        .mouseMove(dropElement, {x: offsetx, y: offsety})
        .mouseUp().perform();
    });
    browser.waitForAngular();
    expect(element(<your locator>).getAttribute()).toBe(dragElement.getAttribute());
  });
  };

  xxxx.prototype.getDropIndex = function (elementHolder, callback) {
  browser.waitForAngular();
  elementHolder.getText().then(function (elementName) {
  var index;
    if (callback) {
      callback(index);
    }
  });
};

Here it is done using the browser.actions(), since there is not in build function. I have used like this.


问:
How can I call particular array value of array in php?
I'm getting below output as an array.

```<code>$array =
        Array
    (
        [12] => Array
            (
                [1] => Array
                    (
                        [14] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Avaya Implementation  Services
                                        [service_id] => 14
                                        [ser_type_id] => 1
                                        [service_desc] =>Avaya Implementation Servic
                                    )

                            )

                    )

            )

    );
</code>```

I want to print only service_desc array value. and I don't want call like $array[12][1][14][0]['service_desc'];

How can I call particular service_desc array value of the array?

答:
As you mentioned that you don't want to call it as $array[12][1][14][0]['service_desc'] you can use extract function which will create variables from your array,

```<code>extract($array[12][1][14][0]);
echo $service_desc;
</code>```

And then you can use your particular key such as service_desc as variable.

Body:
I'm getting below output as an array.

$array =
        Array
    (
        [12] => Array
            (
                [1] => Array
                    (
                        [14] => Array
                            (
                                [0] => Array
                                    (
                                        [name] => Avaya Implementation  Services
                                        [service_id] => 14
                                        [ser_type_id] => 1
                                        [service_desc] =>Avaya Implementation Servic
                                    )

                            )

                    )

            )

    );

I want to print only service_desc array value. and I don't want call like $array[12][1][14][0]['service_desc'];

How can I call particular service_desc array value of the array?

Body:
As you mentioned that you don't want to call it as $array[12][1][14][0]['service_desc'] you can use extract function which will create variables from your array,

extract($array[12][1][14][0]);
echo $service_desc;

And then you can use your particular key such as service_desc as variable.


问:
Creating a program to replace multiple values within a string
I posted a question yesterday and shot myself in the foot by accepting an answer that I believed to work, only to find at the end of my project that it had failed, I am truly sorry for this!

To put my program a little bit more clear, I am creating an application using google maps API within android studio, and have been given a database of information such as Latitude, Longitude and areas to link.

this would require a lot of copying and pasting (and I mean a lot!) in order to complete, so I wanted to make a program that basically replaces multiple strings in a single line.
This is the line to be changed:

googleMap.addMarker(new MarkerOptions().position(new LatLng(LATNUMBER1, LONGNUMBER2)).title("A place"));

Basically, I have a lot of latitude & longtitude & placenames to add into this line, and make duplicates. To do this, I have created 3 listBoxes, each one containing longitude, latitude and place names in order of which they are to be added.

This is the code I currently have:

```<code>string path = Environment.CurrentDirectory + "/" + "latlong.txt";

private void button1_Click(object sender, EventArgs e)
{
    if (!File.Exists(path))
    {
        File.CreateText(path);
        MessageBox.Show("File has been created.");
    }
}

private void button2_Click(object sender, EventArgs e)
{
    using (StreamWriter stwr = new StreamWriter(path))
    {
        for (int i = 0; i < listBox1.Items.Count; i++)
        {
            stwr.WriteLine("googleMap.addMarker(new MarkerOptions().position(new LatLng(" + listBox1.Items[i] + ", " + "ii" + ")).title(" + "bbb" + "));");
        }
        stwr.Close();
        string text = File.ReadAllText("latlong.txt");
        for (int ii = 0; ii < listBox2.Items.Count; ii++)
        {

            text = text.Replace("ii", Convert.ToString(listBox2.Items[ii]));
        }
        File.WriteAllText("latlong.txt", text);
    }
}
</code>```

however, the code here:

```<code>listBox1.Items[i] + ", " + "ii"
</code>```

causes my second set of values to break after the first 10
The first set of values seems to be changing accordingly.

I hope this is clear, would anyone possibly have a solution to this?

答:
```<code>for (int i = 0; i < listBox1.Items.Count; i++)
{
    for (int j = 0; j < listBox2.Items.Count; j++)
    {
        stwr.WriteLine($"googleMap.addMarker(new MarkerOptions().position(new LatLng({ listBox1.Items[i] }, { listBox2.Items[j] })).title(\"A place\"));");
    }
}
</code>```

If i understood your problem correctly, this should work.

Edit: Solution that worked

```<code>for (int i = 0; i < listBox1.Items.Count; i++)
{
    stwr.WriteLine($"googleMap.addMarker(new MarkerOptions().position(new LatLng({ listBox1.Items[i] }, { listBox2.Items[i] })).title(\"A place\"));");
}
</code>```

Body:
I posted a question yesterday and shot myself in the foot by accepting an answer that I believed to work, only to find at the end of my project that it had failed, I am truly sorry for this!

To put my program a little bit more clear, I am creating an application using google maps API within android studio, and have been given a database of information such as Latitude, Longitude and areas to link.

this would require a lot of copying and pasting (and I mean a lot!) in order to complete, so I wanted to make a program that basically replaces multiple strings in a single line.
This is the line to be changed:

googleMap.addMarker(new MarkerOptions().position(new LatLng(LATNUMBER1, LONGNUMBER2)).title("A place"));

Basically, I have a lot of latitude & longtitude & placenames to add into this line, and make duplicates. To do this, I have created 3 listBoxes, each one containing longitude, latitude and place names in order of which they are to be added.

This is the code I currently have:

string path = Environment.CurrentDirectory + "/" + "latlong.txt";

private void button1_Click(object sender, EventArgs e)
{
    if (!File.Exists(path))
    {
        File.CreateText(path);
        MessageBox.Show("File has been created.");
    }
}

private void button2_Click(object sender, EventArgs e)
{
    using (StreamWriter stwr = new StreamWriter(path))
    {
        for (int i = 0; i < listBox1.Items.Count; i++)
        {
            stwr.WriteLine("googleMap.addMarker(new MarkerOptions().position(new LatLng(" + listBox1.Items[i] + ", " + "ii" + ")).title(" + "bbb" + "));");
        }
        stwr.Close();
        string text = File.ReadAllText("latlong.txt");
        for (int ii = 0; ii < listBox2.Items.Count; ii++)
        {

            text = text.Replace("ii", Convert.ToString(listBox2.Items[ii]));
        }
        File.WriteAllText("latlong.txt", text);
    }
}

however, the code here:

listBox1.Items[i] + ", " + "ii"

causes my second set of values to break after the first 10
The first set of values seems to be changing accordingly.

I hope this is clear, would anyone possibly have a solution to this?

Body:
for (int i = 0; i < listBox1.Items.Count; i++)
{
    for (int j = 0; j < listBox2.Items.Count; j++)
    {
        stwr.WriteLine($"googleMap.addMarker(new MarkerOptions().position(new LatLng({ listBox1.Items[i] }, { listBox2.Items[j] })).title(\"A place\"));");
    }
}

If i understood your problem correctly, this should work.

Edit: Solution that worked

for (int i = 0; i < listBox1.Items.Count; i++)
{
    stwr.WriteLine($"googleMap.addMarker(new MarkerOptions().position(new LatLng({ listBox1.Items[i] }, { listBox2.Items[i] })).title(\"A place\"));");
}


问:
Graph in SSRS only shows a couple of week's data
I'm making a graph in SSRS which will highlight the sales for each week from a specific week, and from 52 week up to that date.

For this I have created the following data set in SSRS:

```<code>WITH SET LAST52WEEKS AS
    {
        STRTOMEMBER("[Dim Date].[Week].&[2017]&[1]&[1]&[4]").Lag(52):
        STRTOMEMBER("[Dim Date].[Week].&[2017]&[1]&[1]&[4]")
    }
Select {[Measures].[Quantity]} ON 0,
{Last52Weeks} ON 1
FROM (
    Select {
        [Dim Store2].[Store Key].&[1024]
        } on columns
    from [DSV_FactStoreSales 1]
    )
</code>```

which works as intended, and have an output for week 13 through 4 with each week having a weekly sales Quantity>400 (except for one week with Quantity (null).

However, when I add this data as the Y-axis in a graph in SSRS along with Weeks attribute as the X-axis, only four rows are returned. The rows returned are for the weeks

1,19,3,40

All other values are blank in the graph. Does anyone have any idea as to why this may occur?

Regards,

Cenderze

EDIT updated x-axis from using Interval value = 1

When I changed the Interval value under Horizontal Axis Properties I now get the following values for the x-axis:

1, 13, 14,[...],19, 2, 20, 21, 22, 23, [...], 29, 3, 30, 31, 32,[...],39, 4, 41, 42,[...], 53

where I have bolded the results which seem odd. Im guessing these values are the quarters? I am however using Weeks as my Grouping variable.

EDIT

Following Mike Honey I figured that:

```<code>WITH SET LAST52WEEKS AS
    {STRTOMEMBER("[Dim Date].[Date].&[1]&[2017-01-29]").Parent.Lag(52)
    :
    STRTOMEMBER("[Dim Date].[Date].&[1]&[2017-01-29]").parent}
Select {[Measures].[Quantity]} ON 0,
{Last52Weeks} ON 1
FROM (
    Select {
        [Dim Store2].[Store Key].&[1024]
    } on columns
from [DSV_FactStoreSales 1])
</code>```

ought to work, but it simply returned that Quantity was (null). Why isn't this equivalent to the other Query I wrote, but based off of Date rather than week?

EDIT

I also noted that the graph I am creating has week 52 to the utmost right, whereas it is supposed to have week 4 at the utmost right.

EDIT

EDIT

Edited the Query to become:

```<code>WITH SET LAST52WEEKS AS
{STRTOMEMBER("[Dim Date].[Hierarchy].&[2017 W4]").Lag(52):STRTOMEMBER("[Dim Date].[Hierarchy].&[2017 W4]")}
Select {[Measures].[Quantity]} ON 0,
{(Last52Weeks,[Dim Store2].[Store Name].Allmembers)} ON 1
from [DSV_FactStoreSales 1]
</code>```

where Hierarchy is an Attribute Hierarchy with the values 2010 W1,...., 2018 W52.

But this yields me an output:

```<code>2016 W40    Store1  300
2016 W40    Store2  400
...
2017 W39    Store1  400
</code>```

where I would expect the output to be:

```<code>2016 W4 Store1  300
2016 W4 Store2  400
...
2017 W4 Store1  400
</code>```

Any ideas? It is just an hierarchy with one attribute, Week Name (I've tried the Query with both using [Dim Date].[Hierarchy].[Week Name].&[2017 W4] and [Dim date].[Hierarchy].&[2017 W4], both with the same output.

EDIT (very close now!)

答:
There are two issues I can see with your current chart. One is that your week numbers are being treated as text, which is why the ordering has sequences like 19, 2, 20. The other is that it isn't distinguishing where the week numbers for one year ends and another year starts.

I'm not familiar with mdx. I'm hoping you're able to make a simple dataset that is purely a list of sales with dates. For my solution, I used an Oracle query like:

```<code>SELECT date SALEDATE, ID FROM sales
WHERE date BETWEEN '28-MAR-2016' AND '28-JAN-2017'
</code>```

With a new chart, use [Count(ID)] for the values. It then needs two category groups, first one for the year and then one for the week number. You can use expressions to get these from a date field. For the first category group, set Group on: and Label as

```<code>=DatePart(DateInterval.Year, Fields!SALEDATE.Value)
</code>```

and for the second, set Group on: and Label as

```<code>=DatePart(DateInterval.WeekOfYear, Fields!SALEDATE.Value)
</code>```

To then hide the columns with under 400 sales, right-click the second category group (the weeks one) and add a filter: [Count(ID)] (integer) > 400.

 400">

Even if your dataset is different from the raw data approach I'm using, hopefully this will steer you in the right direction.

Body:
I'm making a graph in SSRS which will highlight the sales for each week from a specific week, and from 52 week up to that date.

For this I have created the following data set in SSRS:

WITH SET LAST52WEEKS AS
    {
        STRTOMEMBER("[Dim Date].[Week].&[2017]&[1]&[1]&[4]").Lag(52):
        STRTOMEMBER("[Dim Date].[Week].&[2017]&[1]&[1]&[4]")
    }
Select {[Measures].[Quantity]} ON 0,
{Last52Weeks} ON 1
FROM (
    Select {
        [Dim Store2].[Store Key].&[1024]
        } on columns
    from [DSV_FactStoreSales 1]
    )

which works as intended, and have an output for week 13 through 4 with each week having a weekly sales Quantity>400 (except for one week with Quantity (null).

However, when I add this data as the Y-axis in a graph in SSRS along with Weeks attribute as the X-axis, only four rows are returned. The rows returned are for the weeks

1,19,3,40

All other values are blank in the graph. Does anyone have any idea as to why this may occur?

Regards,

Cenderze

EDIT updated x-axis from using Interval value = 1

When I changed the Interval value under Horizontal Axis Properties I now get the following values for the x-axis:

1, 13, 14,[...],19, 2, 20, 21, 22, 23, [...], 29, 3, 30, 31, 32,[...],39, 4, 41, 42,[...], 53

where I have bolded the results which seem odd. Im guessing these values are the quarters? I am however using Weeks as my Grouping variable.

EDIT

Following Mike Honey I figured that:

WITH SET LAST52WEEKS AS
    {STRTOMEMBER("[Dim Date].[Date].&[1]&[2017-01-29]").Parent.Lag(52)
    :
    STRTOMEMBER("[Dim Date].[Date].&[1]&[2017-01-29]").parent}
Select {[Measures].[Quantity]} ON 0,
{Last52Weeks} ON 1
FROM (
    Select {
        [Dim Store2].[Store Key].&[1024]
    } on columns
from [DSV_FactStoreSales 1])

ought to work, but it simply returned that Quantity was (null). Why isn't this equivalent to the other Query I wrote, but based off of Date rather than week?

EDIT

I also noted that the graph I am creating has week 52 to the utmost right, whereas it is supposed to have week 4 at the utmost right.

EDIT

EDIT

Edited the Query to become:

WITH SET LAST52WEEKS AS
{STRTOMEMBER("[Dim Date].[Hierarchy].&[2017 W4]").Lag(52):STRTOMEMBER("[Dim Date].[Hierarchy].&[2017 W4]")}
Select {[Measures].[Quantity]} ON 0,
{(Last52Weeks,[Dim Store2].[Store Name].Allmembers)} ON 1
from [DSV_FactStoreSales 1]

where Hierarchy is an Attribute Hierarchy with the values 2010 W1,...., 2018 W52.

But this yields me an output:

2016 W40    Store1  300
2016 W40    Store2  400
...
2017 W39    Store1  400

where I would expect the output to be:

2016 W4 Store1  300
2016 W4 Store2  400
...
2017 W4 Store1  400

Any ideas? It is just an hierarchy with one attribute, Week Name (I've tried the Query with both using [Dim Date].[Hierarchy].[Week Name].&[2017 W4] and [Dim date].[Hierarchy].&[2017 W4], both with the same output.

EDIT (very close now!)

Body:
There are two issues I can see with your current chart. One is that your week numbers are being treated as text, which is why the ordering has sequences like 19, 2, 20. The other is that it isn't distinguishing where the week numbers for one year ends and another year starts.

I'm not familiar with mdx. I'm hoping you're able to make a simple dataset that is purely a list of sales with dates. For my solution, I used an Oracle query like:

SELECT date SALEDATE, ID FROM sales
WHERE date BETWEEN '28-MAR-2016' AND '28-JAN-2017'

With a new chart, use [Count(ID)] for the values. It then needs two category groups, first one for the year and then one for the week number. You can use expressions to get these from a date field. For the first category group, set Group on: and Label as

=DatePart(DateInterval.Year, Fields!SALEDATE.Value)

and for the second, set Group on: and Label as

=DatePart(DateInterval.WeekOfYear, Fields!SALEDATE.Value)

To then hide the columns with under 400 sales, right-click the second category group (the weeks one) and add a filter: [Count(ID)] (integer) > 400.

Even if your dataset is different from the raw data approach I'm using, hopefully this will steer you in the right direction.


问:
Flask-login does not login
I am making a text based browser game but I have a problem with my login script.
Nothing happens when I login, it doesn't even redirect.

Here is my code:

from flask import Flask,render_template,redirect,request,url_for,session
from flask_login import LoginManager, current_user, login_user, login_required
# this contains the configuration and the database connection
from config import users, stats, register_user
from werkzeug.security import check_password_hash
# load the user model
from user import User

version = 2.00
app = Flask(__name__)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
app.config['SECRET_KEY'] = "lkajdghdadkglajkgah"

#the user loader callback
@login_manager.user_loader
def load_user(user_id):
    u = users.find_one({"_id": user_id})
    if not u:
        return None
    return User(u['_id'])

@app.route('/')
def main():
    if current_user.is_authenticated:
        return redirect("/game/", code=302)
    else:
        return redirect("/login/", code=302)

@app.route('/login/', methods=['GET','POST'])
def login():
    if current_user.is_authenticated:
        return redirect("/game/", code=302)

    # when the form is filled in
    if request.method == 'POST':
        try:
            # login user
            if request.form['logSubmit'] == 'logSubmit':
                username = request.form['logUser']
                password = request.form['logPassword']
                result = users.find_one({"user": username})

                if result and check_password_hash(result['password_hash'], password):
                    resid = result['_id']
                    print(resid)
                    user_obj = User(resid)
                    login_user(user_obj)
                    return redirect(request.args.get("next") or url_for("game"))

        except KeyError:
            # register the user
            if request.form['regSubmit'] == 'regSubmit':
                username = request.form['regUser']
                password = request.form['regPassword']
                address = request.form['regAddress']
                register_user(username=username,password=password,address=address)
                print(address)
                return redirect("/login/", code=302)

    return render_template('out.html')

@app.route('/game/')
@login_required
def game():
    return render_template('game.html')

@app.route('/logout')
def logout():
    logout_user()
    return redirect("/login/", code=302)
```

<p>and here is my user class:</p>

<pre class="lang-python prettyprint-override"><code>class User():

    def __init__(self,id):
        self.id = id
        self.email = None
        print (str(id)+" has logged in.")

    #def getStats(self):
        #get the statistics of the user from the database
        #return "your getStats() is still under construction"
    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.id)
</code>```

I'm looking for a couple hours now for the solution and I have a read the whole documentation of flask-login but I can't figure it out.

Please help me.

EDIT: I removed the old code and added the new code but it still doesn't work.

答:
i am going to give you code of my working login which makes use of Flask-login and Flask-WTF.

The View Function:

```<code>@app.route("/login", methods=["GET","POST"])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.get_by_username(form.username.data)
        if user is not None:
            login_user(user, form.remember_me.data)
            flash("logged in successfully as {}".format(user.username))
            return redirect(request.args.get('next') or url_for('index'))
        flash("Incorrect username or password")
    return render_template("login.html", form=form)
</code>```

The Login Form:

```<code>from flask_wtf import FlaskForm
from wtforms.fields import StringField, PasswordField, BooleanField,           SubmitField
from wtforms.validators import DataRequired, url, Length, Email, Regexp,     EqualTo, ValidationError

from models import User
class LoginForm(FlaskForm):
    username = StringField('Your Username: ', validators=[DataRequired()])
    password = PasswordField('password', validators=[DataRequired()])
    remember_me = BooleanField("Keep me logged in")
    submit = SubmitField('Log In')
</code>```

The User Model:

```<code>class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)
    password_hash = db.Column(db.String(80))
</code>```

You can implement that code in your own and see if it solves your problem

Title: Flask-login does not login

Body:
I am making a text based browser game but I have a problem with my login script.
Nothing happens when I login, it doesn't even redirect.

Here is my code:

from flask import Flask,render_template,redirect,request,url_for,session
from flask_login import LoginManager, current_user, login_user, login_required
# this contains the configuration and the database connection
from config import users, stats, register_user
from werkzeug.security import check_password_hash
# load the user model
from user import User

version = 2.00
app = Flask(__name__)
login_manager = LoginManager()
login_manager.init_app(app)
login_manager.login_view = 'login'
app.config['SECRET_KEY'] = "lkajdghdadkglajkgah"

#the user loader callback
@login_manager.user_loader
def load_user(user_id):
    u = users.find_one({"_id": user_id})
    if not u:
        return None
    return User(u['_id'])

@app.route('/')
def main():
    if current_user.is_authenticated:
        return redirect("/game/", code=302)
    else:
        return redirect("/login/", code=302)

@app.route('/login/', methods=['GET','POST'])
def login():
    if current_user.is_authenticated:
        return redirect("/game/", code=302)

    # when the form is filled in
    if request.method == 'POST':
        try:
            # login user
            if request.form['logSubmit'] == 'logSubmit':
                username = request.form['logUser']
                password = request.form['logPassword']
                result = users.find_one({"user": username})

                if result and check_password_hash(result['password_hash'], password):
                    resid = result['_id']
                    print(resid)
                    user_obj = User(resid)
                    login_user(user_obj)
                    return redirect(request.args.get("next") or url_for("game"))

        except KeyError:
            # register the user
            if request.form['regSubmit'] == 'regSubmit':
                username = request.form['regUser']
                password = request.form['regPassword']
                address = request.form['regAddress']
                register_user(username=username,password=password,address=address)
                print(address)
                return redirect("/login/", code=302)

    return render_template('out.html')

@app.route('/game/')
@login_required
def game():
    return render_template('game.html')

@app.route('/logout')
def logout():
    logout_user()
    return redirect("/login/", code=302)

and here is my user class:

class User():

    def __init__(self,id):
        self.id = id
        self.email = None
        print (str(id)+" has logged in.")

    #def getStats(self):
        #get the statistics of the user from the database
        #return "your getStats() is still under construction"
    @property
    def is_authenticated(self):
        return True

    @property
    def is_active(self):
        return True

    @property
    def is_anonymous(self):
        return False

    def get_id(self):
        return str(self.id)

I'm looking for a couple hours now for the solution and I have a read the whole documentation of flask-login but I can't figure it out.

Please help me.

EDIT: I removed the old code and added the new code but it still doesn't work.

Body:
i am going to give you code of my working login which makes use of Flask-login and Flask-WTF.

The View Function:

@app.route("/login", methods=["GET","POST"])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        user = User.get_by_username(form.username.data)
        if user is not None:
            login_user(user, form.remember_me.data)
            flash("logged in successfully as {}".format(user.username))
            return redirect(request.args.get('next') or url_for('index'))
        flash("Incorrect username or password")
    return render_template("login.html", form=form)

The Login Form:

from flask_wtf import FlaskForm
from wtforms.fields import StringField, PasswordField, BooleanField,           SubmitField
from wtforms.validators import DataRequired, url, Length, Email, Regexp,     EqualTo, ValidationError

from models import User
class LoginForm(FlaskForm):
    username = StringField('Your Username: ', validators=[DataRequired()])
    password = PasswordField('password', validators=[DataRequired()])
    remember_me = BooleanField("Keep me logged in")
    submit = SubmitField('Log In')

The User Model:

class User(db.Model, UserMixin):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)
    password_hash = db.Column(db.String(80))

You can implement that code in your own and see if it solves your problem


问:
TextBox_TextChanged Event not firing in c#
The DOB_TextChanged event not firing.My code is,

Aspx code

```<code><asp:TemplateField HeaderText="DOB">
<EditItemTemplate>
  <asp:TextBox ID="DOB" CssClass="datepick" runat="server" AutoPostBack="true"
               OnTextChanged="DOB_TextChanged"></asp:TextBox>
</EditItemTemplate>
 </asp:TemplateField>
</code>```

code behind,

```<code>protected void DOB_TextChanged(object sender, EventArgs e)
{
    //mycode
}
</code>```

am i did anything wrong??

答: You have to check one thing..Go to aspx  (Design) page. Select the button. and click F4(Properties). There you have to go Event area. Here, Check if the TextChanged event is given correctly, like in the server page.

Body:
The DOB_TextChanged event not firing.My code is,

Aspx code

<asp:TemplateField HeaderText="DOB">
<EditItemTemplate>
  <asp:TextBox ID="DOB" CssClass="datepick" runat="server" AutoPostBack="true"
               OnTextChanged="DOB_TextChanged"></asp:TextBox>
</EditItemTemplate>
 </asp:TemplateField>

code behind,

protected void DOB_TextChanged(object sender, EventArgs e)
{
    //mycode
}

am i did anything wrong??


问:
Div content to be stretched equal to table width

<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

My First Bootstrap Page

Resize this responsive page to see the effect!

Last Payment

                                                View All

                                            Property/ Agreement ID
                                            Property/ Agreement Name
                                            Project ID
                                            Project Name
                                            Check Date
                                            Check Amount
                                            Invoice

```

How to stretch the div tag to be equal to table's width. Please see the screenshot. Currently there is white space showing at the end

Please check the updated code. I see it showing the white space at the end of header lable when we move the horizontal bar. Please test this code on w3c school site.

答:
Give percentage value for width attribute.</p>

```<code>.example { width:50%; background:green;}<div class="example">HAVE FUN!</div>
</code>```

Body:
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

My First Bootstrap Page

Resize this responsive page to see the effect!

Last Payment

                                                View All

                                            Property/ Agreement ID
                                            Property/ Agreement Name
                                            Project ID
                                            Project Name
                                            Check Date
                                            Check Amount
                                            Invoice

How to stretch the div tag to be equal to table's width. Please see the screenshot. Currently there is white space showing at the end

Please check the updated code. I see it showing the white space at the end of header lable when we move the horizontal bar. Please test this code on w3c school site.

Body:
Give percentage value for width attribute.

.example { width:50%; background:green;}<div class="example">HAVE FUN!</div>


问:
AngularJS invoking function whose name is constructed as a string
I have a situation in which there are main functions named as:

```<code>Add_<Element_Type>_Page()
</code>```

where Element_Type is received as a parameter.

I can see two options to handle the invocation of the correct function:

Write a relatively long switch construct covering all possible values of Element_Type, or

Use some existing mechanism/trick (I'm not aware of) through which I can build a string using the received Element_Type and invoke a function whose name is contained in that string.

Needless to say, all the functions that can be invoked this way have exactly the same signature as far as parameters is concerned.

Obviously, Option 2 would be the best (easy to maintain and very general as no changes are needed whenever a new type of pages is added).

Is this possible to achieve within AngularJS framework?

Thanks in advance.

答:
Create an attribute with name func-name and pass your dynamic string value which is your function name to that attribute and within your directive you can do something like this.</p>

```<code>scope: {
 funcName: '@'
},
controller: function() {
 $scope[$scope.funcName]();
}
</code>```

Body:
I have a situation in which there are main functions named as:

Add_<Element_Type>_Page()

where Element_Type is received as a parameter.

I can see two options to handle the invocation of the correct function:

Write a relatively long switch construct covering all possible values of Element_Type, or

Use some existing mechanism/trick (I'm not aware of) through which I can build a string using the received Element_Type and invoke a function whose name is contained in that string.

Needless to say, all the functions that can be invoked this way have exactly the same signature as far as parameters is concerned.

Obviously, Option 2 would be the best (easy to maintain and very general as no changes are needed whenever a new type of pages is added).

Is this possible to achieve within AngularJS framework?

Thanks in advance.

Body:
Create an attribute with name func-name and pass your dynamic string value which is your function name to that attribute and within your directive you can do something like this.

scope: {
 funcName: '@'
},
controller: function() {
 $scope[$scope.funcName]();
}


问:
How to uncheck radio button in jquery using label
I have 3 buttons wrapped with labels of radio buttons, so basically control on radio is managed by those 3.

```<code><input type="radio" name="block_image_checkbox" id="block_image_checkbox_1" value="a">
  <label for="block_image_checkbox_1">
  <div id="block_image_1" class="block_image block_image_hover">
    <div class="block_image_overlay">
            <img src="img/1-1.png" alt="" id="image"/>
    </div>
  </div>
  </label>
  <input type="radio" name="block_image_checkbox" id="block_image_checkbox_2" value="b">
  <label for="block_image_checkbox_2">
    <div id="block_image_2" class="block_image block_image_hover">
      <div class="block_image_overlay">
            <img src="img/2-1.png" alt="" id="image"/>
      </div>
    </div>
  </label>
</code>```

I use jquery to handle clicks on my buttons changing their view. My click handler is below.

```<code>$("#block_image_1").click(function() {
    if(!$('.block_image_overlay').hasClass('block_image_overlay_active')){
        $(this).children('.block_image_overlay').toggleClass('block_image_overlay_active');
        $('.block_image').removeClass('block_image_hover');
    }
    else {
        if($(this).children('.block_image_overlay').hasClass('block_image_overlay_active')){
            $(this).children('.block_image_overlay').toggleClass('block_image_overlay_active');
            $('.block_image').addClass('block_image_hover');
            $('#block_image_checkbox_1').prop('checked', false);
        }
        else{
            $('.block_image_overlay_active').toggleClass('block_image_overlay_active');
            $(this).children('.block_image_overlay').toggleClass('block_image_overlay_active');
        }
    }
});
</code>```

I want to uncheck radio button if I click on its label when it's checked. But it does not work. I think because when I try to uncheck it, it may get checked again. But is there any solution for this situation without using another button?

答:
I just found a way to solve this in a way that isn't provided here yet.
You can use DIVs instead of LABELs and attach JS to it that mimics a label, like this:

HTML:

```<code><input type="radio" name="rooms" id="rooms_1" value="1">
<div class="radio-label" data-for="rooms_1">1</div>
</code>```

JS:

```<code>$('.filter-option').on('click', '.radio-label', function() {
    var forId = $(this).data('for');
    if (!$('#'+forId).prop('checked')) {
        $('#'+forId).prop('checked', true);
    } else {
        $('#'+forId).prop('checked', false);
    }
});
</code>```

Here is a fiddle of it: https://jsfiddle.net/yzbvcbo3/2/

Body:
I have 3 buttons wrapped with labels of radio buttons, so basically control on radio is managed by those 3.

<input type="radio" name="block_image_checkbox" id="block_image_checkbox_1" value="a">

  <input type="radio" name="block_image_checkbox" id="block_image_checkbox_2" value="b">

I use jquery to handle clicks on my buttons changing their view. My click handler is below.

$("#block_image_1").click(function() {
    if(!$('.block_image_overlay').hasClass('block_image_overlay_active')){
        $(this).children('.block_image_overlay').toggleClass('block_image_overlay_active');
        $('.block_image').removeClass('block_image_hover');
    }
    else {
        if($(this).children('.block_image_overlay').hasClass('block_image_overlay_active')){
            $(this).children('.block_image_overlay').toggleClass('block_image_overlay_active');
            $('.block_image').addClass('block_image_hover');
            $('#block_image_checkbox_1').prop('checked', false);
        }
        else{
            $('.block_image_overlay_active').toggleClass('block_image_overlay_active');
            $(this).children('.block_image_overlay').toggleClass('block_image_overlay_active');
        }
    }
});

I want to uncheck radio button if I click on its label when it's checked. But it does not work. I think because when I try to uncheck it, it may get checked again. But is there any solution for this situation without using another button?

Body:
I just found a way to solve this in a way that isn't provided here yet.
You can use DIVs instead of LABELs and attach JS to it that mimics a label, like this:

HTML:

<input type="radio" name="rooms" id="rooms_1" value="1">
<div class="radio-label" data-for="rooms_1">1</div>

JS:

$('.filter-option').on('click', '.radio-label', function() {
    var forId = $(this).data('for');
    if (!$('#'+forId).prop('checked')) {
        $('#'+forId).prop('checked', true);
    } else {
        $('#'+forId).prop('checked', false);
    }
});

Here is a fiddle of it: https://jsfiddle.net/yzbvcbo3/2/


问:
differences between HDFS and ZooKeeper?
While reading ZooKeeper's documentation, it seems to me that HDFS relies on pretty much the same mechanisms of distribution/replication (broadly speeking) as ZooKeeper. I hear some echo from one to another, but I still can't distinguish things clearly and striclty.

I understand ZooKeeper is a Cluster Management / Sync tool, while HDFS is a Distributed File Management System, but could ZK be needed on an HDFS cluster for example?

答:
Yes, the factor is distributed processing and high availability on a hadoop cluster with a zookeper's quorum

For ex. Hadoop Namenode fail over process.

Hadoop high availability is designed around Active Namenode & Standby Namenode for fail over process. At any point of time, you should not have two masters ( active Namenodes) at same time.

Zookeper resolves cluster address to an active namenode.

Title: differences between HDFS and ZooKeeper?


问:
Facebook dynamic Open Graph tags for image gallery
I have a Javascript image gallery and wanted to be able to share individual images on FB but found out that the Open Graph tags need to be static for FB to scrape, changing them on the fly with JS does not work.

I found this post Generating Facebook Open Graph meta tags dynamically and added some Javascript redirections.

Basically when a user clicks on my static FB Share button, title, description, image and redirect parameters are send to the page and the OG tags written. Than I do a JS self.location to the actual https://www.facebook.com/sharer/sharer.php?u=&t=

Once the image is posted on FB and the users clicks on the image they are taken back to the same page with another redirect pulled from the redirect parameter.

Everything works except that the image does not show up in the FB sharer dialog. Once posted on FB it shows fine though. Also in the Open Graph Object Debugger the image shows up fine, but not in the sharer dialog. Any Idea why?

I was also wondering about my dynamic OG template with the redirects, is there anything that could be improved? What about security etc?

```<code><?php

    // https://stackoverflow.com/questions/8431694/generating-facebook-open-graph-meta-tags-dynamically

    $params = array();
    if ( count($_GET) > 0) {
        $params = $_GET;
    } else {
        $params = $_POST;
    }

    // defaults
    if ( $params['locale'] == "" ) $params['locale'] = "en_US";
    if ( $params['type'] == "" ) $params['type'] = "article";

    if ( $params['title'] == "" ) $params['title'] = "My Awsome Website";
    if ( $params['description'] == "" ) $params['description'] = "The default description of my website";
    if ( $params['image'] == "" ) $params['image'] = "http://www.mywebsite.com/logo.png";
    if ( $params['redirect'] == "" ) $params['redirect'] = "http://www.mywebsite.com/";

    $query_str =    'locale='       . $params['locale'] .
                    '&type='        . $params['type'] .
                    '&title='       . $params['title'] .
                    '&description=' . $params['description'] .
                    '&image='       . $params['image'] .
                    '&redirect='    . $params['redirect'];

    $fb_param_u = urlencode( 'http://www.mywebsite.com/share/facebook/?' . $query_str );
    $fb_param_t = rawurlencode( strip_tags( $params['title'] ) );

?>

<!DOCTYPE html>
<html lang="en-US" prefix="og: http://ogp.me/ns#">

    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <!-- Open Graph meta tags -->
        <meta property="og:site_name" content="My Website"/>
        <meta property="og:locale" content="<?php echo $params['locale']; ?>"/>
        <meta property="og:type" content="<?php echo $params['type']; ?>"/>

        <meta property="og:url" content="http://www.mywebsite.com/share/facebook/?<?= $query_str ?>" />

        <meta property="og:title" content="<?php echo $params['title']; ?>"/>
        <meta property="og:description" content="<?php echo $params['description']; ?>"/>
        <meta property="og:image" content="<?php echo $params['image']; ?>"/>

        <script type="text/javascript">
            var matches = document.referrer.match(/^https?\:\/\/([^\/?#]+)(?:[\/?#]|$)/i);
            var domain_referrer = matches && matches[1];

            // when clicking through on FB share button
            if (domain_referrer == 'www.mywebsite.com') {
                self.location = "https://www.facebook.com/sharer/sharer.php?u=<?= $fb_param_u ?>&t=<?= $fb_param_t ?>";
            } else {
            // redirect incomming links from FB
                self.location = '<?php echo $params["redirect"]; ?>';
            }
        </script>
    </head>

    <body>
        <div style="/*display:none*/">
            <img src="<?= $params['image'] ?>" />
        </div>
    </body>

</html>
</code>```

答:
Try this </p>

```<code><?php

$params = array();
if(count($_GET) > 0) {
    $params = $_GET;
} else {
    $params = $_POST;
}
// defaults
if($params['type'] == "") $params['type'] = "restaurant";
if($params['locale'] == "") $params['locale'] = "en_US";
if($params['title'] == "") $params['title'] = "default title";
if($params['image'] == "") $params['image'] = "thumb";
if($params['description'] == "") $params['description'] = "default description";

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# MY_APP_NAME_SPACE: http://ogp.me/ns/fb/MY_APP_NAME_SPACE#">
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <!-- Open Graph meta tags -->
        <meta property="fb:app_id" content="MY_APP_ID" />
        <meta property="og:site_name" content="meta site name"/>
        <meta property="og:url" content="http://URL/index.php?type=<?php echo $params['type']; ?>&locale=<?php echo $params['locale']; ?>&title=<?php echo $params['title']; ?>&image=<?php echo $params['image']; ?>&description=<?php echo $params['description']; ?>"/>
        <meta property="og:type" content="MY_APP_NAME_SPACE:<?php echo $params['type']; ?>"/>
        <meta property="og:locale" content="<?php echo $params['locale']; ?>"/>
        <meta property="og:title" content="<?php echo $params['title']; ?>"/>
        <meta property="og:image" content="http://URL/img/<?php echo $params['image']; ?>.png"/>
        <meta property="og:description" content="<?php echo $params['description']; ?>"/>

    </head>
</html>
</code>```

Body:
I have a Javascript image gallery and wanted to be able to share individual images on FB but found out that the Open Graph tags need to be static for FB to scrape, changing them on the fly with JS does not work.

I found this post Generating Facebook Open Graph meta tags dynamically and added some Javascript redirections.

Basically when a user clicks on my static FB Share button, title, description, image and redirect parameters are send to the page and the OG tags written. Than I do a JS self.location to the actual https://www.facebook.com/sharer/sharer.php?u=&t=

Once the image is posted on FB and the users clicks on the image they are taken back to the same page with another redirect pulled from the redirect parameter.

Everything works except that the image does not show up in the FB sharer dialog. Once posted on FB it shows fine though. Also in the Open Graph Object Debugger the image shows up fine, but not in the sharer dialog. Any Idea why?

I was also wondering about my dynamic OG template with the redirects, is there anything that could be improved? What about security etc?

<?php

    // https://stackoverflow.com/questions/8431694/generating-facebook-open-graph-meta-tags-dynamically

    $params = array();
    if ( count($_GET) > 0) {
        $params = $_GET;
    } else {
        $params = $_POST;
    }

    // defaults
    if ( $params['locale'] == "" ) $params['locale'] = "en_US";
    if ( $params['type'] == "" ) $params['type'] = "article";

    if ( $params['title'] == "" ) $params['title'] = "My Awsome Website";
    if ( $params['description'] == "" ) $params['description'] = "The default description of my website";
    if ( $params['image'] == "" ) $params['image'] = "http://www.mywebsite.com/logo.png";
    if ( $params['redirect'] == "" ) $params['redirect'] = "http://www.mywebsite.com/";

    $query_str =    'locale='       . $params['locale'] .
                    '&type='        . $params['type'] .
                    '&title='       . $params['title'] .
                    '&description=' . $params['description'] .
                    '&image='       . $params['image'] .
                    '&redirect='    . $params['redirect'];

    $fb_param_u = urlencode( 'http://www.mywebsite.com/share/facebook/?' . $query_str );
    $fb_param_t = rawurlencode( strip_tags( $params['title'] ) );

?>

<!DOCTYPE html>

        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <meta property="og:site_name" content="My Website"/>
        <meta property="og:locale" content="<?php echo $params['locale']; ?>"/>
        <meta property="og:type" content="<?php echo $params['type']; ?>"/>

        <meta property="og:url" content="http://www.mywebsite.com/share/facebook/?<?= $query_str ?>" />

        <meta property="og:title" content="<?php echo $params['title']; ?>"/>
        <meta property="og:description" content="<?php echo $params['description']; ?>"/>
        <meta property="og:image" content="<?php echo $params['image']; ?>"/>

            <img src="<?= $params['image'] ?>" />

Body:
Try this

<?php

$params = array();
if(count($_GET) > 0) {
    $params = $_GET;
} else {
    $params = $_POST;
}
// defaults
if($params['type'] == "") $params['type'] = "restaurant";
if($params['locale'] == "") $params['locale'] = "en_US";
if($params['title'] == "") $params['title'] = "default title";
if($params['image'] == "") $params['image'] = "thumb";
if($params['description'] == "") $params['description'] = "default description";

?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
    <head prefix="og: http://ogp.me/ns# fb: http://ogp.me/ns/fb# MY_APP_NAME_SPACE: http://ogp.me/ns/fb/MY_APP_NAME_SPACE#">
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

        <!-- Open Graph meta tags -->
        <meta property="fb:app_id" content="MY_APP_ID" />
        <meta property="og:site_name" content="meta site name"/>
        <meta property="og:url" content="http://URL/index.php?type=<?php echo $params['type']; ?>&locale=<?php echo $params['locale']; ?>&title=<?php echo $params['title']; ?>&image=<?php echo $params['image']; ?>&description=<?php echo $params['description']; ?>"/>
        <meta property="og:type" content="MY_APP_NAME_SPACE:<?php echo $params['type']; ?>"/>
        <meta property="og:locale" content="<?php echo $params['locale']; ?>"/>
        <meta property="og:title" content="<?php echo $params['title']; ?>"/>
        <meta property="og:image" content="http://URL/img/<?php echo $params['image']; ?>.png"/>
        <meta property="og:description" content="<?php echo $params['description']; ?>"/>

    </head>
</html>


问:
Locating data volumes in Docker Desktop (Windows)
I'm trying to learn docker at the moment and I'm getting confused about where data volumes actually exist.

I'm using Docker Desktop for Windows. (Windows 10)

In the docs they say that running docker inspect on the object will give you the source:https://docs.docker.com/engine/tutorials/dockervolumes/#locating-a-volume

```<code>$ docker inspect web

"Mounts": [
    {
        "Name": "fac362...80535",
        "Source": "/var/lib/docker/volumes/fac362...80535/_data",
        "Destination": "/webapp",
        "Driver": "local",
        "Mode": "",
        "RW": true,
        "Propagation": ""
    }
]
</code>```

however I don't see this, I get the following:

```<code>$ docker inspect blog_postgres-data
[
    {
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/blog_postgres-data/_data",
        "Name": "blog_postgres-data",
        "Options": {},
        "Scope": "local"
    }
]
</code>```

Can anyone help me? I just want to know where my data volume actually exists is it on my host machine? If so how can i get the path to it?

答:
Each container has its own filesystem which is independent from the host filesystem. If you run your container with the -v flag you can mount volumes so that the host and container see the same data (as in docker run -v hostFolder:containerFolder).

The first output you printed describes such a mounted volume (hence mounts) where /var/lib/docker/volumes/fac362...80535/_data (host) is mounted to /webapp (container).

I assume you did not use -v hence the folder is not mounted and only accessible in the container filesystem which you can find in /var/lib/docker/volumes/blog_postgres-data/_data. This data will be deleted if you remove the container (docker -rm) so it might be a good idea to mount the folder.

As to the question where you can access this data from windows. As far as I know, docker for windows uses the bash subsystem in Windows 10. I would try to run bash for windows10 and go to that folder or find out how to access the linux folders from windows 10. Check this page for a FAQ on the linux subsystem in windows 10.

Update: You can also use docker cp to copy files between host and container.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to learn docker at the moment and I'm getting confused about where data volumes actually exist.

I'm using Docker Desktop for Windows. (Windows 10)

In the docs they say that running docker inspect on the object will give you the source:https://docs.docker.com/engine/tutorials/dockervolumes/#locating-a-volume

$ docker inspect web

"Mounts": [
    {
        "Name": "fac362...80535",
        "Source": "/var/lib/docker/volumes/fac362...80535/_data",
        "Destination": "/webapp",
        "Driver": "local",
        "Mode": "",
        "RW": true,
        "Propagation": ""
    }
]

however I don't see this, I get the following:

$ docker inspect blog_postgres-data
[
    {
        "Driver": "local",
        "Labels": null,
        "Mountpoint": "/var/lib/docker/volumes/blog_postgres-data/_data",
        "Name": "blog_postgres-data",
        "Options": {},
        "Scope": "local"
    }
]

Can anyone help me? I just want to know where my data volume actually exists is it on my host machine? If so how can i get the path to it?


问:
MYSQL where x in all
I am running a query like this

```<code>SELECT .......  WHERE column_name IN (1,2,3)
</code>```

How can I use the same query and say

```<code>SELECT ........WHERE column_name IN (*)
</code>```

and select all rows?

Edit: The reason I need to do this is because of a bad database design and bad coding in general, for now I need to hack it. If I don't pass the query 1,2,3 .. I need to pass it something so it will return me all records. Is there a way to do it without changing the query? If you don't think this is possible then you should say that it is not possible in your answer.

答: ... IN (SELECT DISTINCT column_name FROM table) ...

Title: MYSQL where x in all

Body:
I am running a query like this

SELECT .......  WHERE column_name IN (1,2,3)

How can I use the same query and say

SELECT ........WHERE column_name IN (*)

and select all rows?

Edit: The reason I need to do this is because of a bad database design and bad coding in general, for now I need to hack it. If I don't pass the query 1,2,3 .. I need to pass it something so it will return me all records. Is there a way to do it without changing the query? If you don't think this is possible then you should say that it is not possible in your answer.


问:
SQL Querying Help/IF Conditional Statement
So I am creating a booking table. I have two drop down lists called Date and Time and the data for these is being retrieved from a table called "DateTime" with a field called Date with a load of dates in it and same with time.

This booking system is booking time and a date with a Doctor. I'm lost at this point in terms of how do I get times to only appear for a doctor that the user wants to choose an appointment with to avoid double bookings. If a user has booked 9:15am on a certain date, I don't want that time to appear for another user for that date and doctor.

UPDATE Once a user has selected their date time and doctor, this is stored in a table called Booking. So i was originally going to delete that time and date out of that DateTime but this will then  not appear for another doctor if selected.

HELP PLEASE. :'(

答:
At least you should share your own table design.

I think there will be two table.

One Master table (booking master table)
--date
--time
--isactive

Another one

doctor booking table

--date
--time
--doctorid
--patientid
--isActive (0,1)-- 0 in cae of cancel

So in GUI I select Doctor and Date,I pass this doctorid and date to my proc

It fetch me date,time etc from proc.which help me to populate calender.
I populate calender for each doctorid and date.
So I have written this on doctor and date change both.

Now while creating Calendar,if I get already book flag then I will show this time,but it will be disable.

My query will be like this

```<code>select bm.date,bm.time
,case when db.date=dbm.date then 1 else 0 end isBookedDate
from BookingMaster BM
left join DoctorBookingMapping DBM
on bm.date=dbm.date
where dbm.isactive=1
and db.isactive=1
and dbm.doctorid=@Doctorid
and db.date=@Date
</code>```

Body:
At least you should share your own table design.

I think there will be two table.

One Master table (booking master table)
--date
--time
--isactive

Another one

doctor booking table

--date
--time
--doctorid
--patientid
--isActive (0,1)-- 0 in cae of cancel

So in GUI I select Doctor and Date,I pass this doctorid and date to my proc

It fetch me date,time etc from proc.which help me to populate calender.
I populate calender for each doctorid and date.
So I have written this on doctor and date change both.

Now while creating Calendar,if I get already book flag then I will show this time,but it will be disable.

My query will be like this

select bm.date,bm.time
,case when db.date=dbm.date then 1 else 0 end isBookedDate
from BookingMaster BM
left join DoctorBookingMapping DBM
on bm.date=dbm.date
where dbm.isactive=1
and db.isactive=1
and dbm.doctorid=@Doctorid
and db.date=@Date


问:
Edit code of page on Wordpress
I want to edit the HTML code of my Wordpress page. Exactly, I want to create a page, not posts, in my Wordpress page, where I want expose my CV and insert my photo which will changes when I pass the mouse above of it.

I tried to search something about this and i found this. In this reference, the writer speaks about the code modification, but isn't my particular case.

When I try to edit the code in the Wordpress page, I can't use some codes. For example: ,
 ...

I want to use something like this:

```<code><div class="authorimage">
   <a href="https://www.codesyntax.com/eu/bloga/author/lfernandez">
       <img class="mainimage" src="https://www.codesyntax.com/lfernandez.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
       <img class="hoverimage" src="https://www.codesyntax.com/lfernandezhover.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
   </a>

</div>
</code>```

But in the published page the following appears:

```<code> <img class="mainimage" src="https://www.codesyntax.com/lfernandez.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
 <img class="hoverimage" src="https://www.codesyntax.com/lfernandezhover.jpg" alt="Luistxo Fernandez" title="Luistxo Fernandez">
</code>```

I need use this code for my purpose. what can i do to fix this problem?

Thanks for all.

答:
Please refer below link, this should work,

http://www.inmotionhosting.com/support/edu/wordpress/wordpress-introduction/adding-html-wordpress

Title: Edit code of page on Wordpress

Body:
I want to edit the HTML code of my Wordpress page. Exactly, I want to create a page, not posts, in my Wordpress page, where I want expose my CV and insert my photo which will changes when I pass the mouse above of it.

I tried to search something about this and i found this. In this reference, the writer speaks about the code modification, but isn't my particular case.

When I try to edit the code in the Wordpress page, I can't use some codes. For example: ,
 ...

I want to use something like this:

But in the published page the following appears:

I need use this code for my purpose. what can i do to fix this problem?

Thanks for all.


问:
Android Google map circle
I have a map with many markers for places. I want to draw an overlay around all map with a black transparent color, and a circle around those markers which is fully transparent to show them. Like the attached picture.

I know how to add an overlay view, but I don't know how to add the middle circle while keeping the overlay colored.

If I use Circle then only the circle is colored, and not rest of map.

I also tried to draw something like this but yea won't work ^^.

```<code>        int d = 500; // diameter
        Bitmap bm = Bitmap.createBitmap(d, d, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bm);
        Paint p = new Paint();
        p.setColor(getResources().getColor(R.color.colorAccent));
        c.drawCircle(d / 2, d / 2, d / 2, p);

        // generate BitmapDescriptor from circle Bitmap
        BitmapDescriptor bmD = BitmapDescriptorFactory.fromBitmap(bm);

        // mapView is the GoogleMap
        googleMap.addGroundOverlay(new GroundOverlayOptions().
                image(bmD).
                position(latLng, RADIUS_CIRCLE * 2, RADIUS_CIRCLE * 2).
                transparency(0.4f));
</code>```

I am confused and not sure how to work it out. Any help will be appreciated. Thanks.

答:
Please check Antonio's answer in the comments. I have tested that and works for me.
user1892172 answer but i didn't test it, but seems correct also.
Thanks.</p>

Title: Android Google map circle

Body:
I have a map with many markers for places. I want to draw an overlay around all map with a black transparent color, and a circle around those markers which is fully transparent to show them. Like the attached picture.

I know how to add an overlay view, but I don't know how to add the middle circle while keeping the overlay colored.

If I use Circle then only the circle is colored, and not rest of map.

I also tried to draw something like this but yea won't work ^^.

        int d = 500; // diameter
        Bitmap bm = Bitmap.createBitmap(d, d, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bm);
        Paint p = new Paint();
        p.setColor(getResources().getColor(R.color.colorAccent));
        c.drawCircle(d / 2, d / 2, d / 2, p);

        // generate BitmapDescriptor from circle Bitmap
        BitmapDescriptor bmD = BitmapDescriptorFactory.fromBitmap(bm);

        // mapView is the GoogleMap
        googleMap.addGroundOverlay(new GroundOverlayOptions().
                image(bmD).
                position(latLng, RADIUS_CIRCLE * 2, RADIUS_CIRCLE * 2).
                transparency(0.4f));

I am confused and not sure how to work it out. Any help will be appreciated. Thanks.


问:
Refresh UI language on the fly
I'm following this guide to localize my app. I don't want to get system language so I don't use ILocalize interface and dependecy services. I have these 3 resx files for English, Spanish and French languages:

AppResources.es.resx

AppResources.fr.resx

AppResources.resx (English)

This is my TestPage.xaml code using TranslateExtension class from guide:

```<code><?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:t="clr-namespace:LanguageTest.Resources;assembly=LanguageTest.Resources"
             x:Class="LanguageTest.TestPage">
    <Label Text="{t:Translate TestText}" VerticalOptions="Center" HorizontalOptions="Center" />
</ContentPage>
</code>```

With this code I initilize language settings:

```<code>public App ()
{
    // I can change among "en", "es" and "fr"
    AppResources.Culture = new CultureInfo("es");
    this.MainPage = new NavigationPage(new TestPage());
}
</code>```

I this case the texts are displayed in Spanish. But I want to change the language after the pages are displayed (for example, using a LanguageSettingsPage the user can change the language while the app is running).

```<code>public App ()
{
    AppResources.Culture = new CultureInfo("es");
    this.MainPage = new NavigationPage(new TestPage());
    AppResources.Culture = new CultureInfo("fr");
    // At this point the texts are diplayed in Spanish, not in French
}
</code>```

How can I refresh de page to display French texts without doing new TestPage() again?

答:
If you are simply popping the page, the resources will not be evaluated again. You are simply being displayed the previous page on your nav stack (still in the memory).

You need to push a new page for new resource texts to be loaded.

Title: Refresh UI language on the fly

Body:
I'm following this guide to localize my app. I don't want to get system language so I don't use ILocalize interface and dependecy services. I have these 3 resx files for English, Spanish and French languages:

AppResources.es.resx

AppResources.fr.resx

AppResources.resx (English)

This is my TestPage.xaml code using TranslateExtension class from guide:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:t="clr-namespace:LanguageTest.Resources;assembly=LanguageTest.Resources"
             x:Class="LanguageTest.TestPage">

</ContentPage>

With this code I initilize language settings:

public App ()
{
    // I can change among "en", "es" and "fr"
    AppResources.Culture = new CultureInfo("es");
    this.MainPage = new NavigationPage(new TestPage());
}

I this case the texts are displayed in Spanish. But I want to change the language after the pages are displayed (for example, using a LanguageSettingsPage the user can change the language while the app is running).

public App ()
{
    AppResources.Culture = new CultureInfo("es");
    this.MainPage = new NavigationPage(new TestPage());
    AppResources.Culture = new CultureInfo("fr");
    // At this point the texts are diplayed in Spanish, not in French
}

How can I refresh de page to display French texts without doing new TestPage() again?


问:
php exec,imagemagick convert pdf to jpg return errors
I've wrote a simple php file  convert_pdf_to_single_continuous_long_image.php, and it's content is:

```<code>$shell = '/usr/local/Cellar/imagemagick/7.0.5-4/bin/convert /Users/Bruce/www/pdf_files/sample.pdf -quality 500 -units pixelspercentimeter -density 500 -fill white -alpha remove -append /Users/Bruce/www/pdf_files/sample.png 2>&1';
@exec($shell,$output,$return_var);
var_dump($output);
</code>```

if i ran the command below,it works!

bash-3.2# php convert_pdf_to_single_continuous_long_image.php

but if I ran it through browser, it failed and returns

```<code>array (size=1)
0 => string 'convert: no images defined
/Users/Bruce/www/pdf_files/sample.png' @
error/convert.c/ConvertImageCommand/3254.' (length=110)
who am I--->_www
</code>```

enter image description here

both my nginx user and group are "_www", is that nginx no permission to read the pdf file? but the permission of the directory "/Users/Bruce/www/pdf_files" which contains the pdf file is：

```<code>drwxrwxrwx    8 Bruce  staff       272  4  3 16:43 pdf_files
</code>```

I've google and find some similar questions, and some answer said that is because I didn't install ghostscript, but I do install it, And I put it's path to system PATH:
enter image description here

And I also remove the ghostscript and then reinstall it by "brew istall ghostscript"

nginx:

```<code>bash-3.2# ps aux | grep nginx
nobody             299   0.0  0.0  2503496   1116   ??  S    11:44下午
0:06.26 nginx: worker process
nobody             298   0.0  0.0  2503624   1740   ??  S    11:44下午
0:03.38 nginx: worker process
nobody             296   0.0  0.0  2503496   1128   ??  S    11:44下午
0:06.27 nginx: worker process
nobody             294   0.0  0.0  2503624   1896   ??  S    11:44下午
0:02.97 nginx: worker process
root                68   0.0  0.0  2503496   4860   ??  Ss   11:44下午
0:00.02 nginx: master process /usr/local/opt/nginx/bin/nginx -g daemon off;

bash-3.2# ps aux | grep php-fpm
_www             45743   0.0  0.1  2560356   9992   ??  S     1:48下午
0:00.22 /usr/local/opt/php70/sbin/php-fpm --fpm-config
/usr/local/etc/php/7.0/php-fpm.conf
_www             45720   0.0  0.1  2560356  10288   ??  S     1:47下午
0:00.49 /usr/local/opt/php70/sbin/php-fpm --fpm-config
/usr/local/etc/php/7.0/php-fpm.conf
_www               309   0.0  0.1  2560356  10540   ??  S    11:44下午
0:01.94 /usr/local/opt/php70/sbin/php-fpm --fpm-config
/usr/local/etc/php/7.0/php-fpm.conf
root               107   0.0  0.0  2517076   7356   ??  Ss   11:44下午
0:01.80 /usr/local/opt/php70/sbin/php-fpm --fpm-config
/usr/local/etc/php/7.0/php-fpm.conf
</code>```

I'm sorry the Chinese word "下午" means p.m.

I've tried to set the user and group of php-fpm to root:wheel, but failed, it tells me that I can't ran php-fpm as root.

So I really don't know what's going on, I guess the problem is about permission.Hope someone can help me. Thank you very much!

答:
A couple of issues...

Issue 1

You appear to be using homebrew on a Mac. homebrew puts symbolic links in /usr/local/bin pointing to the various versions of applications in the Cellar. The idea is that you use:

```<code>/usr/local/bin/convert
</code>```

and not

```<code>/usr/local/Cellar/imagemagick/7.0.5-4/bin/convert
</code>```

so that when you upgrade a package, you don't have to change all the version numbers.

Issue 2

When you checked the PATH, I think you did so as yourself, rather than checking the path of the user _www.

Body:
I've wrote a simple php file  convert_pdf_to_single_continuous_long_image.php, and it's content is:

$shell = '/usr/local/Cellar/imagemagick/7.0.5-4/bin/convert /Users/Bruce/www/pdf_files/sample.pdf -quality 500 -units pixelspercentimeter -density 500 -fill white -alpha remove -append /Users/Bruce/www/pdf_files/sample.png 2>&1';
@exec($shell,$output,$return_var);
var_dump($output);

if i ran the command below,it works!

bash-3.2# php convert_pdf_to_single_continuous_long_image.php

but if I ran it through browser, it failed and returns

array (size=1)
0 => string 'convert: no images defined
/Users/Bruce/www/pdf_files/sample.png' @
error/convert.c/ConvertImageCommand/3254.' (length=110)
who am I--->_www

enter image description here

both my nginx user and group are "_www", is that nginx no permission to read the pdf file? but the permission of the directory "/Users/Bruce/www/pdf_files" which contains the pdf file is：

drwxrwxrwx    8 Bruce  staff       272  4  3 16:43 pdf_files

I've google and find some similar questions, and some answer said that is because I didn't install ghostscript, but I do install it, And I put it's path to system PATH:
enter image description here

And I also remove the ghostscript and then reinstall it by "brew istall ghostscript"

nginx:

bash-3.2# ps aux | grep nginx
nobody             299   0.0  0.0  2503496   1116   ??  S    11:44下午
0:06.26 nginx: worker process
nobody             298   0.0  0.0  2503624   1740   ??  S    11:44下午
0:03.38 nginx: worker process
nobody             296   0.0  0.0  2503496   1128   ??  S    11:44下午
0:06.27 nginx: worker process
nobody             294   0.0  0.0  2503624   1896   ??  S    11:44下午
0:02.97 nginx: worker process
root                68   0.0  0.0  2503496   4860   ??  Ss   11:44下午
0:00.02 nginx: master process /usr/local/opt/nginx/bin/nginx -g daemon off;

bash-3.2# ps aux | grep php-fpm
_www             45743   0.0  0.1  2560356   9992   ??  S     1:48下午
0:00.22 /usr/local/opt/php70/sbin/php-fpm --fpm-config
/usr/local/etc/php/7.0/php-fpm.conf
_www             45720   0.0  0.1  2560356  10288   ??  S     1:47下午
0:00.49 /usr/local/opt/php70/sbin/php-fpm --fpm-config
/usr/local/etc/php/7.0/php-fpm.conf
_www               309   0.0  0.1  2560356  10540   ??  S    11:44下午
0:01.94 /usr/local/opt/php70/sbin/php-fpm --fpm-config
/usr/local/etc/php/7.0/php-fpm.conf
root               107   0.0  0.0  2517076   7356   ??  Ss   11:44下午
0:01.80 /usr/local/opt/php70/sbin/php-fpm --fpm-config
/usr/local/etc/php/7.0/php-fpm.conf

I'm sorry the Chinese word "下午" means p.m.

I've tried to set the user and group of php-fpm to root:wheel, but failed, it tells me that I can't ran php-fpm as root.

So I really don't know what's going on, I guess the problem is about permission.Hope someone can help me. Thank you very much!

Body:
A couple of issues...

Issue 1

You appear to be using homebrew on a Mac. homebrew puts symbolic links in /usr/local/bin pointing to the various versions of applications in the Cellar. The idea is that you use:

/usr/local/bin/convert

and not

/usr/local/Cellar/imagemagick/7.0.5-4/bin/convert

so that when you upgrade a package, you don't have to change all the version numbers.

Issue 2

When you checked the PATH, I think you did so as yourself, rather than checking the path of the user _www.