问:
Combining two functions in LISP to atomize list and then find max?
So, id like to take in a list of numbers, atomize it (to remove nested integers), then find the max value.  I have two functions written that accomplish this individually, but can't figure out how to combine them in LISP so I can make one call and have them both run. Any help would be appreciated.  </p>

```<code>:Atomize function to remove nests
:(atomify ‘( a (b c) (e (f (g h) i)) j)->(a b c e f g h i j)

(defun atomify (numbers)
  (cond ((null numbers) nil)
        ((atom (car numbers))
         (cons (car numbers)
               (atomify (cdr numbers))))
        (t
         (append (atomify (car numbers))
                 (atomify (cdr numbers))))))

:Max value of a list of integers function

(defun large_atom (numbers)
  (if (null numbers)
      0
      (max (first numbers)
           (large_atom (rest numbers)))))
</code>```

答:
Here is another way to solve the problem: rather than flattening the list, this walks down it recursively.  This is very explicit about what the structure of the list must be: a good list is a non-null proper list each of whose elements is either an integer or a good list.

The problem with this approach is that it's not tail recursive so it will necessarily fail on very large structures (and even if it was tail recursive CL does not promise to deal with tail recursion.

```<code>(defun greatest-integer (good-list)
  ;; a good list is one of:
  ;; - a cons of a good list and either a good list or ()
  ;; - a cons of an integer and either a good list or ()
  ;; In particular it can't be () and it can't be an improper list
  ;;
  (destructuring-bind (a . b) good-list
    ;; a can be an integer or a good list, b can be null or a good list
    (etypecase b
      (null
       (etypecase a
         (integer a)
         (cons (greatest-integer a))))
      (cons
       (max (etypecase a
              (integer a)
              (cons (greatest-integer a)))
            (greatest-integer b))))))
</code>```

Body:
So, id like to take in a list of numbers, atomize it (to remove nested integers), then find the max value.  I have two functions written that accomplish this individually, but can't figure out how to combine them in LISP so I can make one call and have them both run. Any help would be appreciated.

:Atomize function to remove nests
:(atomify ‘( a (b c) (e (f (g h) i)) j)->(a b c e f g h i j)

(defun atomify (numbers)
  (cond ((null numbers) nil)
        ((atom (car numbers))
         (cons (car numbers)
               (atomify (cdr numbers))))
        (t
         (append (atomify (car numbers))
                 (atomify (cdr numbers))))))

:Max value of a list of integers function

(defun large_atom (numbers)
  (if (null numbers)
      0
      (max (first numbers)
           (large_atom (rest numbers)))))

Body:
Here is another way to solve the problem: rather than flattening the list, this walks down it recursively.  This is very explicit about what the structure of the list must be: a good list is a non-null proper list each of whose elements is either an integer or a good list.

The problem with this approach is that it's not tail recursive so it will necessarily fail on very large structures (and even if it was tail recursive CL does not promise to deal with tail recursion.

(defun greatest-integer (good-list)
  ;; a good list is one of:
  ;; - a cons of a good list and either a good list or ()
  ;; - a cons of an integer and either a good list or ()
  ;; In particular it can't be () and it can't be an improper list
  ;;
  (destructuring-bind (a . b) good-list
    ;; a can be an integer or a good list, b can be null or a good list
    (etypecase b
      (null
       (etypecase a
         (integer a)
         (cons (greatest-integer a))))
      (cons
       (max (etypecase a
              (integer a)
              (cons (greatest-integer a)))
            (greatest-integer b))))))


来源: stackexchange

问:
Casting Generic to int
So in school we are making a project for graphic. I have this interface:

```<code>package rasterdata;

import java.util.Optional;

public interface RasterImage<PixelType> {
    Optional<PixelType> getPixel(int c, int r);
    RasterImage<PixelType> withPixel(int c, int r, PixelType value);
    RasterImage<PixelType> cleared(PixelType pixel);
    int getWidth();
    int getHeight();
}
</code>```

And this is the class which extends the interface and its getPixel() method:

```<code>public class RasterImageBuffered<PixelType> implements RasterImage<PixelType> {
private final BufferedImage img;
private final Function<PixelType, Integer> toInteger;
private final Function<Integer, PixelType> toPixelType;
public RasterImageBuffered(final BufferedImage img,
                           final Function<PixelType, Integer> toInteger,
                           final Function<Integer, PixelType> toPixelType) {
    this.img = img;
    this.toInteger = toInteger;
    this.toPixelType = toPixelType;
}

@Override
public Optional<PixelType> getPixel(final int c, final int r) {
    if (c < 0 || c >= img.getWidth() ||
            r < 0 || r >= img.getHeight())
        return Optional.empty();
    return Optional.of(toPixelType.apply(img.getRGB(c, r)));
}
</code>```

Now, what I am trying to do is to implement a seed fill algorithm. To do that I need to compare the color of the pixel in Canvas (color) with the color which I will use to fill the polygon (fillColor).

This is the seedfill class:

```<code>public class SeedFill<PixelType> {

public RasterImage fill(final RasterImage<PixelType> img, final int x, final int y, PixelType borderColor, PixelType fillColor) {

    RasterImage<PixelType> result = img;

    PixelType color = (PixelType) img.getPixel(x,y);

        //this condition throws an error
        if((color & 0xffffff) == (fillColor & 0xffffff)){

        result = result.withPixel(x,y, fillColor);

        fill(img, x+1, y, borderColor, fillColor,bcgColor);
        fill(img, x-1, y, borderColor, fillColor,bcgColor);
        fill(img, x, y+1, borderColor, fillColor,bcgColor);
        fill(img, x, y-1, borderColor, fillColor,bcgColor);

    }

        return result;

    }

}
</code>```

The problem is that when I want to compare the colors, error saying that I cant compare PixelType with int pops out. However casting It to int throws another error saying that I cant cast PixelType to int. Is there any way of comparing those two values?

答:
Not easy to answer as you don't advertise your PixelType class.

However:

PixelType color = (PixelType) img.getPixel(x,y);

This cast is wrong.

At the very least, you want to invoke img.getPixel(x,y).get(), othwerise you're casting an Optional<PixelType> as PixelType.

Secondly, depending on whether or not you have an appropriate getter in your PixelType class that returns int, you will want to use that when using bitwise operations with an hexadecimal literal.

ContentLicense: CC BY-SA 3.0

Title: Casting Generic to int

Body:
So in school we are making a project for graphic. I have this interface:

package rasterdata;

import java.util.Optional;

public interface RasterImage<PixelType> {
    Optional<PixelType> getPixel(int c, int r);
    RasterImage<PixelType> withPixel(int c, int r, PixelType value);
    RasterImage<PixelType> cleared(PixelType pixel);
    int getWidth();
    int getHeight();
}

And this is the class which extends the interface and its getPixel() method:

public class RasterImageBuffered<PixelType> implements RasterImage<PixelType> {
private final BufferedImage img;
private final Function<PixelType, Integer> toInteger;
private final Function<Integer, PixelType> toPixelType;
public RasterImageBuffered(final BufferedImage img,
                           final Function<PixelType, Integer> toInteger,
                           final Function<Integer, PixelType> toPixelType) {
    this.img = img;
    this.toInteger = toInteger;
    this.toPixelType = toPixelType;
}

@Override
public Optional<PixelType> getPixel(final int c, final int r) {
    if (c < 0 || c >= img.getWidth() ||
            r < 0 || r >= img.getHeight())
        return Optional.empty();
    return Optional.of(toPixelType.apply(img.getRGB(c, r)));
}

Now, what I am trying to do is to implement a seed fill algorithm. To do that I need to compare the color of the pixel in Canvas (color) with the color which I will use to fill the polygon (fillColor).

This is the seedfill class:

public class SeedFill<PixelType> {

public RasterImage fill(final RasterImage<PixelType> img, final int x, final int y, PixelType borderColor, PixelType fillColor) {

    RasterImage<PixelType> result = img;

    PixelType color = (PixelType) img.getPixel(x,y);

        //this condition throws an error
        if((color & 0xffffff) == (fillColor & 0xffffff)){

        result = result.withPixel(x,y, fillColor);

        fill(img, x+1, y, borderColor, fillColor,bcgColor);
        fill(img, x-1, y, borderColor, fillColor,bcgColor);
        fill(img, x, y+1, borderColor, fillColor,bcgColor);
        fill(img, x, y-1, borderColor, fillColor,bcgColor);

    }

        return result;

    }

}

The problem is that when I want to compare the colors, error saying that I cant compare PixelType with int pops out. However casting It to int throws another error saying that I cant cast PixelType to int. Is there any way of comparing those two values?


问:
Gradle Project Sync Failed Android Studio 3.0 (JDK 9.0.1)
I tried all solutions to fix it, but nothing has succeeded. (Turned gradle to "offline work", deleted .gradle files, invalidated and restarted. I also removed the jdk-android studio completely and installed again.)

Here is the problem's screenshot:
Android Studio 3.0 Gradle Sync Problem

Here is my java version

and here is the system/log file:

答:
I think add build tools and sdk version 23 or 24
and if you select to use 23 build tools and sdk version, add dependency like this

compile 'com.android.support:appcompat-v7:23.1.1'

Note:
Wherever its written 26, replace with 23, only if you choose to 23 build tools and sdk version
If there is still any problem you can ask.


问:
active menu item - asp.net mvc3 master page
I've been scanning around trying to find an appropriate solution for assigning "active/current" class to menu items from the master page.  The line is split down the middle with regards of whether to do this client vs server side.

Truthfully I'm new to both JavaScript and MVC so i don't have an opinion. I would prefer to do this in the "cleanest" and most appropriate way.

I have the following jQuery code to assign the "active" class to the
 item...the only problem is the "index" or default view menu item will always be assigned the active class, because the URL is always a substring of the other menu links:

```<code>(default) index = localhost/
link 1 = localhost/home/link1
link 2 = localhost/home/link1

$(function () {
 var str = location.href.toLowerCase();
  $('#nav ul li a').each(function() {
   if (str.indexOf(this.href.toLowerCase()) > -1) {
    $(this).parent().attr("class","active"); //hightlight parent tab
   }
});
</code>```

Is there a better way of doing this, guys?  Would someone at least help me get the client-side version bulletproof? So that the "index" or default link is always "active"? Is there a way of assigning a fake extension to the index method?  like instead of just the base URL it would be localhost/home/dashboard so that it wouldn't be a substring of every link?

Truthfully, i don't really follow the methods of doing this server-side, which is why I'm trying to do it client side with jQuery...any help would be appreciated.

答:
What I usually do is assign a class to the body tag that's based on the path parts. So like, if you do a String.Replace on the path to turn /blogs/posts/1 to class="blogs posts 1".

Then, you can assign CSS rules to handle that.  For example, if you have a menu item for "blogs", you can just do a rule like

```<code>BODY.blogs li.blogs { /* your style */}
</code>```

or if you want a particular style if your on a post only vice if you're on the blog root page

```<code>BODY.blogs.posts li.blogs {/* your style */}
</code>```

Body:
I've been scanning around trying to find an appropriate solution for assigning "active/current" class to menu items from the master page.  The line is split down the middle with regards of whether to do this client vs server side.

Truthfully I'm new to both JavaScript and MVC so i don't have an opinion. I would prefer to do this in the "cleanest" and most appropriate way.

I have the following jQuery code to assign the "active" class to the
 item...the only problem is the "index" or default view menu item will always be assigned the active class, because the URL is always a substring of the other menu links:

(default) index = localhost/
link 1 = localhost/home/link1
link 2 = localhost/home/link1

$(function () {
 var str = location.href.toLowerCase();
  $('#nav ul li a').each(function() {
   if (str.indexOf(this.href.toLowerCase()) > -1) {
    $(this).parent().attr("class","active"); //hightlight parent tab
   }
});

Is there a better way of doing this, guys?  Would someone at least help me get the client-side version bulletproof? So that the "index" or default link is always "active"? Is there a way of assigning a fake extension to the index method?  like instead of just the base URL it would be localhost/home/dashboard so that it wouldn't be a substring of every link?

Truthfully, i don't really follow the methods of doing this server-side, which is why I'm trying to do it client side with jQuery...any help would be appreciated.

Body:
What I usually do is assign a class to the body tag that's based on the path parts. So like, if you do a String.Replace on the path to turn /blogs/posts/1 to class="blogs posts 1".

Then, you can assign CSS rules to handle that.  For example, if you have a menu item for "blogs", you can just do a rule like

BODY.blogs li.blogs { /* your style */}

or if you want a particular style if your on a post only vice if you're on the blog root page

BODY.blogs.posts li.blogs {/* your style */}

ContentLicense: CC BY-SA 2.5


问:
The Redux Form validation is not working
I am new in react. Now if I am trying to put value in input fields, but not being able to do that showing blocked. Also no validation happening. Any suggestion will be appreciated. Please feel free to ask if you need any more information.

package.js file

```<code>"dependencies": {
    "axios": "^0.17.1",
    "react": "^16.0.0",
    "react-bootstrap": "^0.31.5",
    "react-dom": "^16.0.0",
    "react-redux": "^5.0.6",
    "react-router-dom": "^4.2.2",
    "redux": "^3.7.2",
    "redux-form": "^7.1.2",
    "redux-thunk": "^2.2.0"
  }
</code>```

reducer/index.js

```<code>import {combineReducers} from 'redux';
import {reducer as formReducer} from 'redux-form';
const rootReducer = combineReducers({
    form: formReducer
});

export default rootReducer;
</code>```

root/index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import {BrowserRouter, Route} from 'react-router-dom';
import reduxThunk from 'redux-thunk';

import reducers from './reducers';

import App from './components/app';
import Header from './components/main/header';
import Footer from './components/main/footer';
import Dashboard from './components/main/dashboard';
import Signin from './components/auth/signin';
import Signup from './components/auth/signup';
import About from './components/main/about';
import Contact from './components/main/contact';
import { reducer } from 'redux-form';

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);

ReactDOM.render(
        <Provider store={createStoreWithMiddleware(reducer)}>
            <BrowserRouter>
                <div className="container">
                    <Header />
                    <Route path="/" component={App} />
                    <Route exact path="/" component={Dashboard} />
                    <Route path="/signin" component={Signin} />
                    <Route path="/signup" component={Signup} />
                    <Route path="/about" component={About} />
                    <Route path="/contact" component={Contact} />
                    <Footer />
                </div>
            </BrowserRouter>
        </Provider>
,document.getElementById('root')
);
</code>```

components/signin.js

```<code>import React, {Component} from 'react';
import {Field, reduxForm} from 'redux-form';

class Signin extends Component{

    renderCommonInputField(field){
        return(
            <div className="form-group">
                <label>{field.label}</label>
                <input
                    className="form-control"
                    type={field.type}
                    placeholder={field.placeholder}
                    {...field.input}
                />
            </div>
        );
    }

    onFormSubmit(values){
        console.log('test');

        event.preventDefault();
    }
    render(){
        const {handleSubmit} = this.props;
        return(
            <div>
                <form onSubmit={handleSubmit(this.onFormSubmit.bind(this))}>
                    <Field
                        label="Enter your email"
                        name="email"
                        type="text"
                        placeholder="enter email ex@..example@empl.com"
                        component={this.renderCommonInputField}
                    />
                    <Field
                        label="Enter your password"
                        name="password"
                        type="password"
                        placeholder="enter your password"
                        component={this.renderCommonInputField}
                    />
                    <button type="submit" className="btn btn-default">Submit</button>
                </form>
            </div>
        );
    }
}
function validate(values){
    const errors = {}
    if(!values.email){
        errors.email = "Email is required"
    }
    if(!values.password){
        errors.password = "Password is required"
    }
    return errors;
}
export default reduxForm({
    form: 'signinform',
    validate
})(Signin);
</code>```

答:
UPDATED:

Your problems is a little mistake when calling createStoreWithMiddleware on index.js. The param should be reducers and not reducer.

Replace: <Provider store={createStoreWithMiddleware(reducer)}>.

By: <Provider store={createStoreWithMiddleware(reducers)}>

Body:
I am new in react. Now if I am trying to put value in input fields, but not being able to do that showing blocked. Also no validation happening. Any suggestion will be appreciated. Please feel free to ask if you need any more information.

package.js file

"dependencies": {
    "axios": "^0.17.1",
    "react": "^16.0.0",
    "react-bootstrap": "^0.31.5",
    "react-dom": "^16.0.0",
    "react-redux": "^5.0.6",
    "react-router-dom": "^4.2.2",
    "redux": "^3.7.2",
    "redux-form": "^7.1.2",
    "redux-thunk": "^2.2.0"
  }

reducer/index.js

import {combineReducers} from 'redux';
import {reducer as formReducer} from 'redux-form';
const rootReducer = combineReducers({
    form: formReducer
});

export default rootReducer;

root/index.js

import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import {createStore, applyMiddleware} from 'redux';
import {BrowserRouter, Route} from 'react-router-dom';
import reduxThunk from 'redux-thunk';

import reducers from './reducers';

import App from './components/app';
import Header from './components/main/header';
import Footer from './components/main/footer';
import Dashboard from './components/main/dashboard';
import Signin from './components/auth/signin';
import Signup from './components/auth/signup';
import About from './components/main/about';
import Contact from './components/main/contact';
import { reducer } from 'redux-form';

const createStoreWithMiddleware = applyMiddleware(reduxThunk)(createStore);

ReactDOM.render(
        <Provider store={createStoreWithMiddleware(reducer)}>
            <BrowserRouter>

                    <Route path="/" component={App} />
                    <Route exact path="/" component={Dashboard} />
                    <Route path="/signin" component={Signin} />
                    <Route path="/signup" component={Signup} />
                    <Route path="/about" component={About} />
                    <Route path="/contact" component={Contact} />

            </BrowserRouter>
        </Provider>
,document.getElementById('root')
);

components/signin.js

import React, {Component} from 'react';
import {Field, reduxForm} from 'redux-form';

class Signin extends Component{

    renderCommonInputField(field){
        return(

                {field.label}
                <input
                    className="form-control"
                    type={field.type}
                    placeholder={field.placeholder}
                    {...field.input}
                />

        );
    }

    onFormSubmit(values){
        console.log('test');

        event.preventDefault();
    }
    render(){
        const {handleSubmit} = this.props;
        return(

                <form onSubmit={handleSubmit(this.onFormSubmit.bind(this))}>
                    <Field
                        label="Enter your email"
                        name="email"
                        type="text"
                        placeholder="enter email ex@..example@empl.com"
                        component={this.renderCommonInputField}
                    />
                    <Field
                        label="Enter your password"
                        name="password"
                        type="password"
                        placeholder="enter your password"
                        component={this.renderCommonInputField}
                    />
                    <button type="submit" className="btn btn-default">Submit</button>
                </form>

        );
    }
}
function validate(values){
    const errors = {}
    if(!values.email){
        errors.email = "Email is required"
    }
    if(!values.password){
        errors.password = "Password is required"
    }
    return errors;
}
export default reduxForm({
    form: 'signinform',
    validate
})(Signin);


问:
React SVG, issue with combining SVG's
If I want to combine multiple SVG parts into a single component, the issue is that every React component has to return a single parent element.

```<code>class ComponentA extends Component {
  render() {
    return (

      <svg>
        <Part1 />
        <Part2 />

      </svg>
    )
  }
}

class Part1 extends Component {
  render() {
    return (
      <defs>
        <linearGradient...>
        <etc...>
      </defs>
      <g>
        <path...>
        <text...>
      </g>
)
  }
}

class Part2 extends Component {
  render() {
    return (
      <defs>
        <linearGradient...>
        <etc...>
      </defs>
      <g>
        <circle...>
        <path...>
        <path...>
      </g>
)
  }
}
</code>```

As we can see, in order to combine multiple SVG components into one component, we have to return both defs and g tags, and possibly also title and maybe others. This breaks the React rule that every component needs to return only one parent element. How do we solve this?

答:
Use React 16 or wrap defs and g with svg tag, like this:

```<code>class Part1 extends Component {
  render() {
    return (
     <svg>
      <defs>
        <linearGradient...>
        <etc...>
      </defs>
      <g>
        <path...>
        <text...>
      </g>
    </svg>
    )
  }
}
</code>```

Title: React SVG, issue with combining SVG's

Body:
If I want to combine multiple SVG parts into a single component, the issue is that every React component has to return a single parent element.

class ComponentA extends Component {
  render() {
    return (

      <svg>
        <Part1 />
        <Part2 />

      </svg>
    )
  }
}

class Part1 extends Component {
  render() {
    return (
      <defs>
        <linearGradient...>
        <etc...>
      </defs>
      <g>
        <path...>
        <text...>
      </g>
)
  }
}

class Part2 extends Component {
  render() {
    return (
      <defs>
        <linearGradient...>
        <etc...>
      </defs>
      <g>
        <circle...>
        <path...>
        <path...>
      </g>
)
  }
}

As we can see, in order to combine multiple SVG components into one component, we have to return both defs and g tags, and possibly also title and maybe others. This breaks the React rule that every component needs to return only one parent element. How do we solve this?

Body:
Use React 16 or wrap defs and g with svg tag, like this:

class Part1 extends Component {
  render() {
    return (
     <svg>
      <defs>
        <linearGradient...>
        <etc...>
      </defs>
      <g>
        <path...>
        <text...>
      </g>
    </svg>
    )
  }
}


问:
How to list Docker mounted volumes from within the container
I want to list all container directories that are mounted volumes.

I.e. to be able to get similar info I get from

```<code>docker inspect --format "{{ .Volumes }}" <self>
</code>```

But from within the container and without having docker installed in there.

I tried cat /proc/mounts, but I couldn't find a proper filter for it.

答:
(EDIT - this may no longer work on Mac) <s>If your Docker host is OS X, the mounted volumes will be type osxfs (or fuse.osxfs). You can run a

mount | grep osxfs | awk '{print $3}'

and get a list of all the mounted volumes.</s>

If your Docker host is Linux (at least Ubuntu 14+, maybe others), the volumes appear to all be on /dev, but not on a device that is in your container's /dev filesystem. The volumes will be alongside /etc/resolv.conf, /etc/hostname, and /etc/hosts. If you do a mount | grep ^/dev to start, then filter out any of the files in ls /dev/*, then filter out the three files listed above, you should be left with host volumes.

mount | grep ^/dev/ | grep -v /etc | awk '{print $3}'

My guess is the specifics may vary from Linux to Linux. Not ideal, but at least possible to figure out.

ContentLicense: CC BY-SA 4.0

Body:
I want to list all container directories that are mounted volumes.

I.e. to be able to get similar info I get from

docker inspect --format "{{ .Volumes }}" <self>

But from within the container and without having docker installed in there.

I tried cat /proc/mounts, but I couldn't find a proper filter for it.


问:
Write a function that takes 1 parameter: a string, s. It must return an integer denoting the length of the longest magical sub-sequence in s?
Consider a string s, consisting of one or more of the following letters: a, e, i, o, and u.

We define a magical subsequence of s to be a sequence of letters derived from s that contains all five vowels in order. This means a magical subsequence will have one or more a's followed by one or more e's followed by one or more i's followed by one or more o's followed by one or more u's. For example, if s = "aeeiooua", then "aeiou" and "aeeioou" are magical subsequences but "aeio" and "aeeioua" are not.

Write a function to find length of longest magical subsequence with parameter string s.

```<code>Input Format
String s composed of English vowels (i.e., a, e, i, o, and u).

Output Format
Count denoting the length of the longest magical subsequence in s.

    Sample Input 1
    aeiaaioooaauuaeiou

Sample Output 1
10

Explanation 1
In the table below, the component characters of the longest magical subsequence are red:
a   e   i   a   a   i   o   o   o   a   a   u   u   a   e   i   o   u

Sample Input 2
aeiaaioooaa

Sample Output 2
0

Explanation 2
String s does not contain the letter u, so it is not possible to construct a magical subsequence

I
</code>```

So the java code of this problem goes like this .

```<code>import java.util.Arrays; import java.util.Scanner;
public class LongestMegicalSubsequence {
static int longestMegicalSubsequence(String s, char[] c) {

    // exit conditions
    if (s.length() == 0 || c.length == 0) {
        return 0;
    }

    if (s.length() < c.length) {
        return 0;
    }

    if (s.length() == c.length) {
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != c[i]) {
                return 0;
            }
        }
        return s.length();
    }

    if (s.charAt(0) < c[0]) {
        // ignore, go ahead with next item
        return longestMegicalSubsequence(s.substring(1), c);
    } else if (s.charAt(0) == c[0]) {

        return Math.max(Math.max(
                (1 + longestMegicalSubsequence(s.substring(1),
                        Arrays.copyOfRange(c, 1, c.length))),
                (1 + longestMegicalSubsequence(s.substring(1), c))),
                (longestMegicalSubsequence(s.substring(1), c)));
    } else {
        return longestMegicalSubsequence(s.substring(1), c);
    }
}

public static void main(String...s) {

    char[] chars = { 'a', 'e', 'i', 'o', 'u' };
    System.out.print("PLEASE ENTER THE STRING");
    Scanner sc =new Scanner(System.in);

    String str = sc.next();

    System.out.println(longestMegicalSubsequence(str, chars));

}
}
</code>```

I was just thinking to do this problem in python .

But couldn't think of a pythonic  way to do it . I mean I convert each line of logic in python code but that is not my motive . Can you people suggest me a way to do it in python .

答:
Here is a python version.

```<code>def f(input):
    pattern='aeiou'
    total=0
    c=0
    for x in input:
        if x==pattern[c]:
            c+=1
            if c==5:
                total += 5
                c=0
    return total
</code>```

Text :

```<code>In [12]: f('aeiaaioooaauuaeiou')
10
</code>```

Or, more arithmetic:

```<code>def f(input):
    pattern='aeiou'
    c=0
    for x in input:
        c += (x==pattern[c%5])
    print(c//5*5)
</code>```

Body:
Consider a string s, consisting of one or more of the following letters: a, e, i, o, and u.

We define a magical subsequence of s to be a sequence of letters derived from s that contains all five vowels in order. This means a magical subsequence will have one or more a's followed by one or more e's followed by one or more i's followed by one or more o's followed by one or more u's. For example, if s = "aeeiooua", then "aeiou" and "aeeioou" are magical subsequences but "aeio" and "aeeioua" are not.

Write a function to find length of longest magical subsequence with parameter string s.

Input Format
String s composed of English vowels (i.e., a, e, i, o, and u).

Output Format
Count denoting the length of the longest magical subsequence in s.

    Sample Input 1
    aeiaaioooaauuaeiou

Sample Output 1
10

Explanation 1
In the table below, the component characters of the longest magical subsequence are red:
a   e   i   a   a   i   o   o   o   a   a   u   u   a   e   i   o   u

Sample Input 2
aeiaaioooaa

Sample Output 2
0

Explanation 2
String s does not contain the letter u, so it is not possible to construct a magical subsequence

I

So the java code of this problem goes like this .

import java.util.Arrays; import java.util.Scanner;
public class LongestMegicalSubsequence {
static int longestMegicalSubsequence(String s, char[] c) {

    // exit conditions
    if (s.length() == 0 || c.length == 0) {
        return 0;
    }

    if (s.length() < c.length) {
        return 0;
    }

    if (s.length() == c.length) {
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) != c[i]) {
                return 0;
            }
        }
        return s.length();
    }

    if (s.charAt(0) < c[0]) {
        // ignore, go ahead with next item
        return longestMegicalSubsequence(s.substring(1), c);
    } else if (s.charAt(0) == c[0]) {

        return Math.max(Math.max(
                (1 + longestMegicalSubsequence(s.substring(1),
                        Arrays.copyOfRange(c, 1, c.length))),
                (1 + longestMegicalSubsequence(s.substring(1), c))),
                (longestMegicalSubsequence(s.substring(1), c)));
    } else {
        return longestMegicalSubsequence(s.substring(1), c);
    }
}

public static void main(String...s) {

    char[] chars = { 'a', 'e', 'i', 'o', 'u' };
    System.out.print("PLEASE ENTER THE STRING");
    Scanner sc =new Scanner(System.in);

    String str = sc.next();

    System.out.println(longestMegicalSubsequence(str, chars));

}
}

I was just thinking to do this problem in python .

But couldn't think of a pythonic  way to do it . I mean I convert each line of logic in python code but that is not my motive . Can you people suggest me a way to do it in python .

Body:
Here is a python version.

def f(input):
    pattern='aeiou'
    total=0
    c=0
    for x in input:
        if x==pattern[c]:
            c+=1
            if c==5:
                total += 5
                c=0
    return total

Text :

In [12]: f('aeiaaioooaauuaeiou')
10

Or, more arithmetic:

def f(input):
    pattern='aeiou'
    c=0
    for x in input:
        c += (x==pattern[c%5])
    print(c//5*5)


问:
iPad viewport issue between portrait and landscape
I have a web page that comes up on an ipad. I added this meta for the viewport:

```<code><meta name="viewport" content="width=980,maximum-scale=1.0" />
</code>```

It works just fine in portrait, then when the ipad goes into landscape mode it works just fine as well. The problem is when I go back to portrait from landscape the page is over stretched, meaning portions of the page go off the screen in portrait mode. I have to double tap the screen to get it back to the normal view.

I then tried:

```<code><meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">
</code>```

But in portrait mode its not wide enough and the icons/text wraps to 2 lines when it should only be one line. It gets all bunched up. Any suggestions?

答:
Have you tried something like this:</p>

```<code><meta name="viewport" content="initial-scale = 1,user-scalable=no,maximum-scale=1.0">
</code>```

Body:
I have a web page that comes up on an ipad. I added this meta for the viewport:

<meta name="viewport" content="width=980,maximum-scale=1.0" />

It works just fine in portrait, then when the ipad goes into landscape mode it works just fine as well. The problem is when I go back to portrait from landscape the page is over stretched, meaning portions of the page go off the screen in portrait mode. I have to double tap the screen to get it back to the normal view.

I then tried:

<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0;">

But in portrait mode its not wide enough and the icons/text wraps to 2 lines when it should only be one line. It gets all bunched up. Any suggestions?

Body:
Have you tried something like this:

<meta name="viewport" content="initial-scale = 1,user-scalable=no,maximum-scale=1.0">


问:
Changing orientation of all children of LinearLayout programatically
I have a LinearLayout (child) inside another (parent) LinearLayout. I want to change the orientation of the parent from horizontal to vertical and vice versa and do the same for all children. How can i propagate this orientation change from parent to its children with adding any additional interface.

Btw, this has nothing to with orientation change of the device. I want the  orientation to change as per event encountered.

I can have multiple LinearLayout as its children and i don't want to set the orientation of all of these in a for loop since i am adding children programmatically

答:
```<code>yourLinearLayout.setLayoutParams(new LayoutParams(LinearLayout.WRAP_CONTENT, LinearLayout.WRAP_CONTENT);
yourLinearLayout.setOrientation(LinearLayout.VERTICAL);
</code>```

Do the same for the children

Body:
yourLinearLayout.setLayoutParams(new LayoutParams(LinearLayout.WRAP_CONTENT, LinearLayout.WRAP_CONTENT);
yourLinearLayout.setOrientation(LinearLayout.VERTICAL);

Do the same for the children


问:
C++ calculator displays and extra 0 in the end
I am having this problem with my calculator I made. See, when I type in a calculation it always adds a 0 to the end. I don't know how to fix this do you have any ideas?

Here's the code:

```<code>#include <iostream>

using namespace std;

void Input(float &x, float &y);

float a = 1.0, b = 1.0, result;
char op;

int main() {

    cout << "Welcome to Foxy's calculator" << endl;
    cout << "----------------------------" << endl;
    cout << "Please input a calculation operation (eg. 1+1): ";
    cin >> a >> op >> b;

    Input(a, b);

    cout << result << endl;
    system("pause");
    return 0;
}

void Input (float &x, float &y) {

    a = x;
    b = y;

    switch (op)
    {
    case '+':
        cout << x + y;
        break;

    case '-':
        cout << x - y;
        break;

    case '*':
        cout << x*y;
        break;

    case '/':
        cout << x / y;
        break;

    default:
        cout << "Error! Operator is not correct" << endl;
        cout << "Please input your calculation with a proper operator: ";
        cin >> a >> op >> b;

    }
}
</code>```

答: Remove cout << result << endl;</p>

Body:
I am having this problem with my calculator I made. See, when I type in a calculation it always adds a 0 to the end. I don't know how to fix this do you have any ideas?

Here's the code:

#include <iostream>

using namespace std;

void Input(float &x, float &y);

float a = 1.0, b = 1.0, result;
char op;

int main() {

    cout << "Welcome to Foxy's calculator" << endl;
    cout << "----------------------------" << endl;
    cout << "Please input a calculation operation (eg. 1+1): ";
    cin >> a >> op >> b;

    Input(a, b);

    cout << result << endl;
    system("pause");
    return 0;
}

void Input (float &x, float &y) {

    a = x;
    b = y;

    switch (op)
    {
    case '+':
        cout << x + y;
        break;

    case '-':
        cout << x - y;
        break;

    case '*':
        cout << x*y;
        break;

    case '/':
        cout << x / y;
        break;

    default:
        cout << "Error! Operator is not correct" << endl;
        cout << "Please input your calculation with a proper operator: ";
        cin >> a >> op >> b;

    }
}

Body: Remove cout << result << endl;


答:
You call cout << result << endl; in the caller. and result is always 0. This is because it is never explicitly set to anything and the C++ compiler kindly zero-initialises it since it's at global scope.

In such instances, your line by line debugger is your best friend. The fact that you've mashed up your 1) input, 2) calculation, and 3) output stages is not helping: ideally they should all be separate parts of your program.

Title: C++ calculator displays and extra 0 in the end


问:
Mysql "is not NULL" is working very slowly
My query is;

```<code> "SELECT firma.id from firma where firma.video IS NOT NULL limit 0,20";
</code>```

It is working after nearly 14 seconds for 576.000 rows at firma table.
 There is only 1 row which is not NULL in video.
 I add index for video varchar(1000).

How can i fasten this query ?

答:
Do you know about the index content limitation of size?
By default, the index key prefix length limit is 767 bytes. See Section 13.1.13, “CREATE INDEX Syntax”.  </p>

Body:
My query is;

 "SELECT firma.id from firma where firma.video IS NOT NULL limit 0,20";

It is working after nearly 14 seconds for 576.000 rows at firma table.
 There is only 1 row which is not NULL in video.
 I add index for video varchar(1000).

How can i fasten this query ?


问:
How to combine multiple plugin files in one folder in WordPress?
I have several plugins that communicate with Apipee.Each plugin contains only from one php file. My task is to put all these plugins in one folder for better usability.

I created a folder and moved the php files in that folder. I removed the headers from the plugins and created loader.php file in the same folder. The content of loader.php:

```<code><?php
/*
Plugin Name: Combined Plugin
Description: Contains plugin a, plugin b and plugin c
*/
 include dirname(__FILE__) . '/plugin-a.php';
 include dirname(__FILE__) . '/plugin-b.php';
 include dirname(__FILE__) . '/plugin-c.php';
 ?>
</code>```

For some reason the plugins does not work at all. The plguin appears and can be activated. But none of the plugins does anything.

答:
Try this format of getting the plugin path.

```<code>require plugin_dir_path( __FILE__ ) . 'plugin-a.php';
</code>```

Using the keyword require will cause a fatal error when the specified file location is invalid so you know if the path is correctly being referenced then.

Body:
I have several plugins that communicate with Apipee.Each plugin contains only from one php file. My task is to put all these plugins in one folder for better usability.

I created a folder and moved the php files in that folder. I removed the headers from the plugins and created loader.php file in the same folder. The content of loader.php:

<?php
/*
Plugin Name: Combined Plugin
Description: Contains plugin a, plugin b and plugin c
*/
 include dirname(__FILE__) . '/plugin-a.php';
 include dirname(__FILE__) . '/plugin-b.php';
 include dirname(__FILE__) . '/plugin-c.php';
 ?>

For some reason the plugins does not work at all. The plguin appears and can be activated. But none of the plugins does anything.

Body:
Try this format of getting the plugin path.

require plugin_dir_path( __FILE__ ) . 'plugin-a.php';

Using the keyword require will cause a fatal error when the specified file location is invalid so you know if the path is correctly being referenced then.


问:
How to use a struct/interface to mock dependency for testing
I'm new to go here... my objective is to unit test that a status is being updated in my ready().  I've been looking at https://engineering.aircto.com/writing-testable-code-in-golang/ and trying to figure out how to adapt what they're doing to my use case, filling in gaps of golang knowledge where I can.

I'm getting the error cannot use fakeSession (type *FakeSession) as type *discordgo.Session in argument to ready but I'm not sure why I'm getting this error.

main.go

```<code>import (
    "fmt"
    "os"
    "os/signal"
    "syscall"

    "github.com/bwmarrin/discordgo"
)

var (
    // bot token used for this bot when connecting
    token    = os.Getenv("DISCORD_BOT_TOKEN")
    status   = os.Getenv("BOT_STATUS")
)

func main() {
    // initiate Discord bot

    // Register ready as a callback for the ready events.
    discordConnection.AddHandler(ready)

    // running the app, waiting to receive a close signal
}

// This function will be called (due to AddHandler above) when the bot receives
// the "ready" event from Discord.
func ready(session *discordgo.Session, event *discordgo.Ready) {

    // Set the playing status.
    session.UpdateStatus(0, status)
}
</code>```

main_test.go

```<code>type FakeSession struct {
    status  string
    idle    int
}

func (f *FakeSession) UpdateStatus(idle int, game string) error {
    f.idle, f.status = idle, game
    return nil
}

func TestStatusIsUpdated(t *testing.T) {
    readyDependency := &discordgo.Ready{}
    fakeSession := &FakeSession{}

    ready(fakeSession, readyDependency)

    // @todo assert that idle/game status were set to correct values
}
</code>```

答:
As @Andrew pointed out discordgo.Session is a go struct (from the docs link you posted type Session struct {)

structs are Concrete types in go and are unable to be substituted.  The only argument go compiler will allow for ready is a pointer to a session.

To break this dependency you can create a custom interface owned and controlled by your project using the methods that you need.  This will allow you to create and call ready with a fake structure for your tests.

Sometimes 3rd party libraries already have interfaces so it's usually worth-while to scan their godoc to see which interfaces are available before creating your own.

But if you have to create your own for testing (and I find myself regularly having to do this), it might look like:

```<code>type StatusUpdater interface {
   UpdateStatus(int, string)
}

// This function will be called (due to AddHandler above) when the bot receives
// the "ready" event from Discord.
func ready(s StatusUpdater, event *discordgo.Ready) {

    // Set the playing status.
    s.UpdateStatus(0, status)
}
</code>```

Now the dependency on discordgo.Session has been broken, and your test code can call ready function with its fake session, and then make assertions on it!

Body:
I'm new to go here... my objective is to unit test that a status is being updated in my ready().  I've been looking at https://engineering.aircto.com/writing-testable-code-in-golang/ and trying to figure out how to adapt what they're doing to my use case, filling in gaps of golang knowledge where I can.

I'm getting the error cannot use fakeSession (type *FakeSession) as type *discordgo.Session in argument to ready but I'm not sure why I'm getting this error.

main.go

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"

    "github.com/bwmarrin/discordgo"
)

var (
    // bot token used for this bot when connecting
    token    = os.Getenv("DISCORD_BOT_TOKEN")
    status   = os.Getenv("BOT_STATUS")
)

func main() {
    // initiate Discord bot

    // Register ready as a callback for the ready events.
    discordConnection.AddHandler(ready)

    // running the app, waiting to receive a close signal
}

// This function will be called (due to AddHandler above) when the bot receives
// the "ready" event from Discord.
func ready(session *discordgo.Session, event *discordgo.Ready) {

    // Set the playing status.
    session.UpdateStatus(0, status)
}

main_test.go

type FakeSession struct {
    status  string
    idle    int
}

func (f *FakeSession) UpdateStatus(idle int, game string) error {
    f.idle, f.status = idle, game
    return nil
}

func TestStatusIsUpdated(t *testing.T) {
    readyDependency := &discordgo.Ready{}
    fakeSession := &FakeSession{}

    ready(fakeSession, readyDependency)

    // @todo assert that idle/game status were set to correct values
}

Body:
As @Andrew pointed out discordgo.Session is a go struct (from the docs link you posted type Session struct {)

structs are Concrete types in go and are unable to be substituted.  The only argument go compiler will allow for ready is a pointer to a session.

To break this dependency you can create a custom interface owned and controlled by your project using the methods that you need.  This will allow you to create and call ready with a fake structure for your tests.

Sometimes 3rd party libraries already have interfaces so it's usually worth-while to scan their godoc to see which interfaces are available before creating your own.

But if you have to create your own for testing (and I find myself regularly having to do this), it might look like:

type StatusUpdater interface {
   UpdateStatus(int, string)
}

// This function will be called (due to AddHandler above) when the bot receives
// the "ready" event from Discord.
func ready(s StatusUpdater, event *discordgo.Ready) {

    // Set the playing status.
    s.UpdateStatus(0, status)
}

Now the dependency on discordgo.Session has been broken, and your test code can call ready function with its fake session, and then make assertions on it!


问:
How do I accept all changes from a remote?
I'm doing a pull origin some_branch and can see there are a lot of changes. Eventually I don't mind if their erase all mine.

How can I accept them all instead or using mergetool and merge files one by one?

答:
Just:

```<code>    git clone $url
</code>```

Seriously! That's the best way.

You could do all sorts of git reset and git branch commands to move the refs, but the only purpose would be to keep your commits somewhere in your local repository for future reference. If that's the goal, just keep the whole repository as is, and re-clone the origin.

To accept all changes on just one branch, foo:

```<code>    git checkout foo
    git fetch origin +refs/heads/foo:refs/remotes/origin/foo
    git reset refs/remotes/origin/foo
</code>```

foo will now point at the same commit as foo on origin. If you want to blow away the files in your working directory, add --hard to git reset. If you want to merge first, replace fetch with pull.

You may have a bunch of dangling commits in your local repo, which git may clean-up someday, but for awhile you can still access them via the reflog.

Body:
Just:

    git clone $url

Seriously! That's the best way.

You could do all sorts of git reset and git branch commands to move the refs, but the only purpose would be to keep your commits somewhere in your local repository for future reference. If that's the goal, just keep the whole repository as is, and re-clone the origin.

To accept all changes on just one branch, foo:

    git checkout foo
    git fetch origin +refs/heads/foo:refs/remotes/origin/foo
    git reset refs/remotes/origin/foo

foo will now point at the same commit as foo on origin. If you want to blow away the files in your working directory, add --hard to git reset. If you want to merge first, replace fetch with pull.

You may have a bunch of dangling commits in your local repo, which git may clean-up someday, but for awhile you can still access them via the reflog.


问:
In docker, how to change shared folder on running state
I run my docker container with command blow.

```<code>docker run -v /host/folder:/docker/container/folder my_image
</code>```

If I want to change shared folder, should I restart?

答:
This has been requested many times, and it is currently not possible. Containers should be ephemeral. You should be able to restart the container again without lose of data.

Check the following issue for more reasons why this is not possible.

Body:
I run my docker container with command blow.

docker run -v /host/folder:/docker/container/folder my_image

If I want to change shared folder, should I restart?


问:
How can I fix Laravel 5.1 - 404 Not Found?
I am trying to use Laravel 5.1 for the first time. I was able to install it and https://sub.example.com/laravel/public/ is displaying what is should. However, views I create are giving me a 404 error Page not found.

Here is what I have done so far:

I created a controller in laravel\app\Http\controllers\Authors.php

Here is the code behind the Authors.php file

```<code><?php

class Authors_Controller extends Base_Controller {

    public $restful = true;

    public function get_index() {
        return View::make('authors.index')
            ->with('title', 'Authors and Books')
            ->with('authors', Author::order_by('name')->get());
    }
}
</code>```

Then I created a view in laravel\resources\views\Authors\index.blade.php

Here is the code behind the index.blade.php file

```<code>@layout('layouts.default')

@section('content')
    Hello, this is a test
@endsection
</code>```

Then I created a layout in laravel\resources\views\layouts\default.blade.php

Here is the code behind the default.blade.php file

```<code><!DOCTYPE html>
<html>
    <head>
        <title>{{ $title }}</title>
    </head>
    <body>

    @if(Session::has('message'))
        <p style="color: green;">{{ Session::get('message') }}</p>
    @endif

    @yield('content')
    Hello - My first test
    </body>
</html>
</code>```

Finally I created a route in laravel\app\Http\routes.php

```<code><?php
Route::get('/', function () {
    return view('welcome');
});

Route::get('authors', array('as'=>'authors', 'uses'=>'authors@index'));
</code>```

But for some reason I keep getting 404 error Page not found.

I enabled the mod_rewrite on my Apache 2.4.9 by uncommenting out the line

```<code>LoadModule rewrite_module modules/mod_rewrite.so
</code>```

Then restarted Apache.

From what I can tell in the php_info() output the mod_rewrite is enabled

```<code>Loaded Modules
core mod_win32 mpm_winnt http_core mod_so mod_php5 mod_access_compat mod_actions mod_alias mod_allowmethods mod_asis mod_auth_basic mod_authn_core mod_authn_file mod_authz_core mod_authz_groupfile mod_authz_host mod_authz_user mod_autoindex mod_cgi mod_dir mod_env mod_include mod_isapi mod_log_config mod_mime mod_negotiation mod_rewrite mod_setenvif mod_socache_shmcb mod_ssl
</code>```

My current .htaccess file looks like this "which is the factory default"

        Options -MultiViews

```<code>RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</code>```

I have also tried to change it to the code below as per the documentation:

```<code>Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</code>```

However, I am still getting the 404 page when I go to

```<code>https://sub.example.com/laravel/public/authors
</code>```

What am I doing wrong?
How can I fix this problem?

答:
If your Laravel routes aren't working, and you're getting "Not Found" errors whenever you try and load a page, your .htaccess file is likely lacking permission to do its duty.

The key is the apache AllowOverride directive.

If you don't have AllowOverride set to All, your Laravel .htaccess file (/public/.htaccess) won't be able to enable mod_rewrite, and your routes won't work.

The first step is to open your apache httpd.conf file. In OS X, it is located at:

```<code>/private/etc/apache2/httpd.conf
</code>```

Option 1) Modify your main  directive

This will change the AllowOverride value for all your websites. In your httpd.conf file, look for the main  directive:

```<code><Directory "/var/www/html">
    ...
    AllowOverride None
    ...
</Directory>
</code>```

Simply change it to this:

```<code><Directory "/var/www/html">
    ...
    AllowOverride All
    ...
</Directory>
</code>```

Option 2) Add a  directive to your site's  directive.

```<code><VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/html/epigroove/public"
    ...
    <Directory "/var/www/html/epigroove/public">
        AllowOverride All
    </Directory>
</VirtualHost>
</code>```

Save the changes to your httpd.conf file, restart or reload apache, and your routes should be up-and-running.

Body:
I am trying to use Laravel 5.1 for the first time. I was able to install it and https://sub.example.com/laravel/public/ is displaying what is should. However, views I create are giving me a 404 error Page not found.

Here is what I have done so far:

I created a controller in laravel\app\Http\controllers\Authors.php

Here is the code behind the Authors.php file

<?php

class Authors_Controller extends Base_Controller {

    public $restful = true;

    public function get_index() {
        return View::make('authors.index')
            ->with('title', 'Authors and Books')
            ->with('authors', Author::order_by('name')->get());
    }
}

Then I created a view in laravel\resources\views\Authors\index.blade.php

Here is the code behind the index.blade.php file

@layout('layouts.default')

@section('content')
    Hello, this is a test
@endsection

Then I created a layout in laravel\resources\views\layouts\default.blade.php

Here is the code behind the default.blade.php file

<!DOCTYPE html>

        <title>{{ $title }}</title>

    @if(Session::has('message'))

{{ Session::get('message') }}

    @endif

    @yield('content')
    Hello - My first test

Finally I created a route in laravel\app\Http\routes.php

<?php
Route::get('/', function () {
    return view('welcome');
});

Route::get('authors', array('as'=>'authors', 'uses'=>'authors@index'));

But for some reason I keep getting 404 error Page not found.

I enabled the mod_rewrite on my Apache 2.4.9 by uncommenting out the line

LoadModule rewrite_module modules/mod_rewrite.so

Then restarted Apache.

From what I can tell in the php_info() output the mod_rewrite is enabled

Loaded Modules
core mod_win32 mpm_winnt http_core mod_so mod_php5 mod_access_compat mod_actions mod_alias mod_allowmethods mod_asis mod_auth_basic mod_authn_core mod_authn_file mod_authz_core mod_authz_groupfile mod_authz_host mod_authz_user mod_autoindex mod_cgi mod_dir mod_env mod_include mod_isapi mod_log_config mod_mime mod_negotiation mod_rewrite mod_setenvif mod_socache_shmcb mod_ssl

My current .htaccess file looks like this "which is the factory default"

        Options -MultiViews

RewriteEngine On

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

I have also tried to change it to the code below as per the documentation:

Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]

However, I am still getting the 404 page when I go to

https://sub.example.com/laravel/public/authors

What am I doing wrong?
How can I fix this problem?

Body:
If your Laravel routes aren't working, and you're getting "Not Found" errors whenever you try and load a page, your .htaccess file is likely lacking permission to do its duty.

The key is the apache AllowOverride directive.

If you don't have AllowOverride set to All, your Laravel .htaccess file (/public/.htaccess) won't be able to enable mod_rewrite, and your routes won't work.

The first step is to open your apache httpd.conf file. In OS X, it is located at:

/private/etc/apache2/httpd.conf

Option 1) Modify your main  directive

This will change the AllowOverride value for all your websites. In your httpd.conf file, look for the main  directive:

<Directory "/var/www/html">
    ...
    AllowOverride None
    ...
</Directory>

Simply change it to this:

<Directory "/var/www/html">
    ...
    AllowOverride All
    ...
</Directory>

Option 2) Add a  directive to your site's  directive.

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/var/www/html/epigroove/public"
    ...
    <Directory "/var/www/html/epigroove/public">
        AllowOverride All
    </Directory>
</VirtualHost>

Save the changes to your httpd.conf file, restart or reload apache, and your routes should be up-and-running.


问:
On page refresh, my select option dropdown value is getting selected to default, how to stop it?
On page refresh, my select option drop-down value is getting selected to default. I want to set it to the previously selected value. On page refresh it should not reset. How i can achieve it in html, java, js.</p>

答:
Your question is quiet tricky and you don't really explain it accurately in your original question.

Since you are using Content Presenter, that means this code resides in WebCenter content and Oracle ADF itself cannot control its behaviour, as it is just loading the content!


问:
Prestashop 1.6 CCC css new file in cache each time
I don't know how prestashop work. I'm a full stack developer and i need to resolve a problem in a prestashop project.

I use a theme "sns_kanta" modified by one other developper.

When i enable the css cache with the CCC options in dashboard, each time a user load a page, a compiled css file is created in cache folder in the theme. 1 page view = 1 new file.

Many time later... this give 28 GB useless data. Time passed to compile it is useless.

Anyone have an idea ?
A start point for see where is the problem ? To debug it.

i try to check the prestashop documentation and try to see why css it's compiled each time  ...

I know it's not easy without an access and all data, but if you have an idea, a file to check, ...

Thx a lot in advance

答:
I have an option in theme option like : -> ADVANCE SETTINGS -> SCSS Compile -> Always compile

I changed this to only if css file is not found.

useless time losed.

Thank's for the help and sorry.


问:
Find out if MPMoviePlayerController is currently playing
I have one small problem regarding MPMoviePlayerController, i have a link that play movie when i click on that movie  button, however when i click on another button the application gets crashed, i need to find how to identify that movie is playing or getting any kind of response</p>

答:
```<code>typedef NS_ENUM(NSInteger, AVPlayerTimeControlStatus) {
    AVPlayerTimeControlStatusPaused,
    AVPlayerTimeControlStatusWaitingToPlayAtSpecifiedRate,
    AVPlayerTimeControlStatusPlaying
} NS_ENUM_AVAILABLE(10_12, 10_0);

if(self.player.timeControlStatus == AVPlayerTimeControlStatusPlaying)
{
  // is Playing
}
</code>```


问:
Changes view in IntelliJ continues to list files where the only difference are LF vs CRLF
I have 2 files that won't go away in the Changes view.  If I look at the diff, it just tells me the committed version has LF line endings and the local version has CRLF line endings.  I'm working on a Mac and I understand linux based systems use LF line endings and Windows use CRLF.  Is there someway I can just convert these 2 files so all the line endings are LF?

Thanks.

答:
Simple and quick solution to is - Shelve & Unshelve the changes.
Works for me every time.

Shelving:

Unshelve:


问:
Angular 5: Subject's .next() is not a function
I'm trying to push a new string to a Subject called period with .next() but the console gives me a this.period.next is not a function error.

option.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
    selector: 'app-option',
    templateUrl: './option.component.html'
})
export class OptionComponent implements OnInit {
    public period: Subject<string> = new Subject<string>();

    constructor() {}

    ngOnInit() {}

    setPeriod(period: string) {
        this.period.next(period);
    }
}
</code>```

option.component.html

```<code><mat-radio-group [(ngModel)]="period" (ngModelChange)="setPeriod($event)">
    <span *ngFor="let option of httpHeader.option"><mat-radio-button [checked]="option.default" [value]="option.param" >{{ option.desc }}</mat-radio-button><br /></span>
</mat-radio-group>
</code>```

I'm running rxjs 5.5.2. The function setPeriod is triggered when a user selects a radio button.

What am I doing wrong? I use the same method in a http service and that works but in this component it doesn't.

答:
In Angular 2/4 usually the import is:

```<code>import { Subject } from 'rxjs/Subject';
</code>```

I think, I hasn't changed in Angular 5

Also you are calling the function with an event as input parameter "setPeriod($event)" but the definition in code is a string setPeriod(period: string)

Body:
I'm trying to push a new string to a Subject called period with .next() but the console gives me a this.period.next is not a function error.

option.component.ts

import { Component, OnInit } from '@angular/core';
import { Subject } from 'rxjs';

@Component({
    selector: 'app-option',
    templateUrl: './option.component.html'
})
export class OptionComponent implements OnInit {
    public period: Subject<string> = new Subject<string>();

    constructor() {}

    ngOnInit() {}

    setPeriod(period: string) {
        this.period.next(period);
    }
}

option.component.html

<mat-radio-group [(ngModel)]="period" (ngModelChange)="setPeriod($event)">
    <mat-radio-button [checked]="option.default" [value]="option.param" >{{ option.desc }}</mat-radio-button>

</mat-radio-group>

I'm running rxjs 5.5.2. The function setPeriod is triggered when a user selects a radio button.

What am I doing wrong? I use the same method in a http service and that works but in this component it doesn't.

Body:
In Angular 2/4 usually the import is:

import { Subject } from 'rxjs/Subject';

I think, I hasn't changed in Angular 5

Also you are calling the function with an event as input parameter "setPeriod($event)" but the definition in code is a string setPeriod(period: string)


问:
Datatables improperly sized in bootstrap tab
I have a page that has three bootstrap tabs and a datatable in each tab. The datatable in the first tab works fine. However, the datatable in the second tab is at half-width and I have no idea why. There's no css applied to it either.

Here's a screenshot of the first tab (works fine)

And the 2nd tab (datatable at half width)

My code:

```<code>$('#companies').DataTable({ //table in tab 1 (works fine)
        responsive: true
});

$('#companies2').DataTable({ //table in tab 2
        responsive: true
});
</code>```

My html:

```<code><!-- tab start -->
<div class="container">
    <div class="row">
        <div class="col-md-12">
            <h1>Tabs</h1>
            <ul class="nav nav-tabs">
                <li class="active"><a href="#tab1" data-toggle="tab">Section 1</a></li>
                <li><a href="#tab2" data-toggle="tab">Section 2</a></li>
                <li><a href="#tab3" data-toggle="tab">Section 3</a></li>
            </ul>

            <!-- tab sections -->
            <div class="tab-content">
                <div class="tab-pane active" id="tab1">
                    <table id="companies" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0">
                        <thead>
                            <tr>
                                <th>Company ID</th>
                                <th>Company Name</th>
                                <th>Status</th>
                                <th></th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            {{#each context}}
                            {{#if setup}}
                            <tr>
                                <td>{{company_id}}</td>
                                <td>{{company_name}}</td>
                                {{#if is_approved}}
                                <td>Approved</td>
                                {{else}}
                                <td>Not Approved</td>
                                {{/if}}
                                <td><a href="/admin/viewclientorders/{{company_id}}">View Orders</a></td>
                                <td><a href="/admin/company/{{company_id}}">View Details</a></td>
                            </tr>
                            {{/if}}
                            {{/each}}
                        </tbody>
                    </table>
                </div>
                <div class="tab-pane" id="tab2">
                    <table id="companies2" class="table table-striped table-bordered dt-responsive nowrap" cellspacing="0">
                        <thead>
                            <tr>
                                <th>Company ID</th>
                                <th>Company Name</th>
                                <th>Create Date</th>
                                <th></th>
                                <th></th>
                            </tr>
                        </thead>
                        <tbody>
                            {{#each context}}
                            {{#unless setup}}
                            <tr>
                                <td>{{company_id}}</td>
                                <td>{{company_name}}</td>
                                <td>{{created_at}}</td>
                                <td><button class="btn btn-primary setup"><a href="/admin/companies/setup_company/{{company_id}}">Setup</a></button></td>
                                <td><button class="btn btn-danger delete">Ignore</button></td>
                            </tr>
                            {{/unless}}
                            {{/each}}
                        </tbody>
                    </table>
                </div>
                <div class="tab-pane" id="tab3">
                    3rd
                </div>

            </div>
</code>```

Can someone help?

答:
When using Responsive add-on for DataTables, you should also call responsive.recalc(), also:

```<code>$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    $.fn.dataTable.tables({ visible: true, api: true })
        .columns.adjust()
        .responsive.recalc()
        .draw();
});
</code>```

It'a na old question, but maybe someone will help this additional information.

Body:
I have a page that has three bootstrap tabs and a datatable in each tab. The datatable in the first tab works fine. However, the datatable in the second tab is at half-width and I have no idea why. There's no css applied to it either.

Here's a screenshot of the first tab (works fine)

And the 2nd tab (datatable at half width)

My code:

$('#companies').DataTable({ //table in tab 1 (works fine)
        responsive: true
});

$('#companies2').DataTable({ //table in tab 2
        responsive: true
});

My html:

Tabs

Section 1

Section 2

Section 3

                                Company ID
                                Company Name
                                Status

                            {{#each context}}
                            {{#if setup}}

                                {{company_id}}
                                {{company_name}}
                                {{#if is_approved}}
                                Approved
                                {{else}}
                                Not Approved
                                {{/if}}
                                View Orders
                                View Details

                            {{/if}}
                            {{/each}}

                                Company ID
                                Company Name
                                Create Date

                            {{#each context}}
                            {{#unless setup}}

                                {{company_id}}
                                {{company_name}}
                                {{created_at}}
                                <button class="btn btn-primary setup">Setup</button>
                                <button class="btn btn-danger delete">Ignore</button>

                            {{/unless}}
                            {{/each}}

                    3rd

Can someone help?

Body:
When using Responsive add-on for DataTables, you should also call responsive.recalc(), also:

$(document).on('shown.bs.tab', 'a[data-toggle="tab"]', function (e) {
    $.fn.dataTable.tables({ visible: true, api: true })
        .columns.adjust()
        .responsive.recalc()
        .draw();
});

It'a na old question, but maybe someone will help this additional information.


问:
Using RabbitMQ stomp adapter to relay message across subscriptions in different servers
I am using Spring to setup Stomp server endpoints (extending AbstractWebSocketMessageBrokerConfigurer)

```<code>@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableStompBrokerRelay("/topic","/queue")
        .setRelayHost(<rmqhost>);
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/myapp/websockets").setAllowedOrigins("*");
}
</code>```

The objective is that I can have multiple servers, and a client will connect to any one of them for a specific topic: /topic/topic-id-1

Any of the server (at a time) can send a message for this topic using Spring's SimpMessagingTemplate

```<code>messagingTemplate.convertAndSend(destination, message);
</code>```

where destination = "/topic/topic-id-1".
For ex: I have 2 server nodes and a client connecting to each one of them, subscribing to the same topic (/topic/topic-id-1). The objective is that if server 1 sends a message for topic-id-1, it should relay via rabbitmq to both clients subscribing to the same topic. I see a queue being created with routing key as "topic-id-1", but only the client connecting to the server sending out the message explicitly receives it. Am I missing something here? Isn't RMQ stomp broker supposed to relay the message send by one server for a subscription, across all the subscriptions for the same topic? Does the server need to do something else to get messages sent by other node?

答:
I'm not sure if this is exactly the same thing but I just solved a very similar problem. I posted my answer here: Sending STOMP messages from other layers of an application

I decided to split the implementation of the relay server into it's own setup and then manually forward messages between the rabbitmq server and the websocket subscribers on each of the servers.

Hopefully this can be of some use for you.

Body:
I am using Spring to setup Stomp server endpoints (extending AbstractWebSocketMessageBrokerConfigurer)

@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
        config.enableStompBrokerRelay("/topic","/queue")
        .setRelayHost(<rmqhost>);
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/myapp/websockets").setAllowedOrigins("*");
}

The objective is that I can have multiple servers, and a client will connect to any one of them for a specific topic: /topic/topic-id-1

Any of the server (at a time) can send a message for this topic using Spring's SimpMessagingTemplate

messagingTemplate.convertAndSend(destination, message);

where destination = "/topic/topic-id-1".
For ex: I have 2 server nodes and a client connecting to each one of them, subscribing to the same topic (/topic/topic-id-1). The objective is that if server 1 sends a message for topic-id-1, it should relay via rabbitmq to both clients subscribing to the same topic. I see a queue being created with routing key as "topic-id-1", but only the client connecting to the server sending out the message explicitly receives it. Am I missing something here? Isn't RMQ stomp broker supposed to relay the message send by one server for a subscription, across all the subscriptions for the same topic? Does the server need to do something else to get messages sent by other node?


答:
result is a global static variable that gets zero - initialized and is never changed. So cout << result << endl; will always print "0". To fix this you should make a, b, result and op local to main (global variables are bad), pass a, b andop to calculating function and store returned calculation result in result. It will look something like this:

```<code>float result = Input(a, b, op);
cout << result << endl;
</code>```

Body:
result is a global static variable that gets zero - initialized and is never changed. So cout << result << endl; will always print "0". To fix this you should make a, b, result and op local to main (global variables are bad), pass a, b andop to calculating function and store returned calculation result in result. It will look something like this:

float result = Input(a, b, op);
cout << result << endl;


问:
mysql NOT IN not show result
```<code>SELECT * FROM device
WHERE (device_id NOT IN (SELECT device_id FROM vehicle)) AND client_id =3
</code>```

this for my query, this query working fine in phpmyadmin. but not working mysql workbench MySql Workbench.

i'm using MySql Workbench version 5.7.20

device table

```<code>device_id  device_name status
 1         OLX          1
 2         AMA          1
</code>```

vehicle table

```<code>id  vehicle_name device_id  status
 1      indica     NULL         1
 2      innov      NULL         2

SELECT * FROM device
WHERE (device_id NOT IN (SELECT device_id FROM vehicle)) AND client_id =3
</code>```

USE THIS QUERY IN PhpMyadmin , i'll get all rows from device table

BUT Same Query Show Give result

```<code>device_id device_name  status
</code>```

答:
I can see that in device table column `` doesn't even exist. Also remove unnecessary parentheses. Following query will do.

```<code>SELECT * FROM device d
WHERE
    d.device_id NOT IN (SELECT device_id FROM vehicle) as sub_query AND
    d.status <> 1
</code>```

Title: mysql NOT IN not show result

Body:
SELECT * FROM device
WHERE (device_id NOT IN (SELECT device_id FROM vehicle)) AND client_id =3

this for my query, this query working fine in phpmyadmin. but not working mysql workbench MySql Workbench.

i'm using MySql Workbench version 5.7.20

device table

device_id  device_name status
 1         OLX          1
 2         AMA          1

vehicle table

id  vehicle_name device_id  status
 1      indica     NULL         1
 2      innov      NULL         2

SELECT * FROM device
WHERE (device_id NOT IN (SELECT device_id FROM vehicle)) AND client_id =3

USE THIS QUERY IN PhpMyadmin , i'll get all rows from device table

BUT Same Query Show Give result

device_id device_name  status

Body:
I can see that in device table column `` doesn't even exist. Also remove unnecessary parentheses. Following query will do.

SELECT * FROM device d
WHERE
    d.device_id NOT IN (SELECT device_id FROM vehicle) as sub_query AND
    d.status <> 1


问:
WebElement getText() doesn't work on Winium-Desktop
I'm trying to execute getText() on a WebElement instance but for some reason it doesn't work: pcresultsList.get(0).getText()

Maybe Winium doesn't support this method?

My code is:

```<code>public void monitorBasic() throws InterruptedException {
    monitorFrame = driver.findElement(By.name("BEAM Monitor"));
    WebElement resultsFrame = monitorFrame.findElement(By.id("ReportListBox"));
    List<WebElement> pcresultsList = resultsFrame.findElements(By.className("TextBlock"));
    System.out.println(pcresultsList.get(0).getText());
}
</code>```

sorry for not posting the error I'm getting - the site tells me that my code is not indent and when i'm trying to present it as code the site tells i have too much code. :)

答: I've found that with Winium, you need to get the Name attribute because getText() does not work correctly.

Body:
I'm trying to execute getText() on a WebElement instance but for some reason it doesn't work: pcresultsList.get(0).getText()

Maybe Winium doesn't support this method?

My code is:

public void monitorBasic() throws InterruptedException {
    monitorFrame = driver.findElement(By.name("BEAM Monitor"));
    WebElement resultsFrame = monitorFrame.findElement(By.id("ReportListBox"));
    List<WebElement> pcresultsList = resultsFrame.findElements(By.className("TextBlock"));
    System.out.println(pcresultsList.get(0).getText());
}

sorry for not posting the error I'm getting - the site tells me that my code is not indent and when i'm trying to present it as code the site tells i have too much code. :)


问:
Javascript properties end up in loops
the following code will add the property 'id' to the object 'obj'. When calling the getter and setter there will be a console.log execution.

let obj = {}

Object.defineProperty(obj, 'id', {
    set: (val) => { console.log('set'); this.id = val; },
    get: () => { console.log('get'); return this.id; }
})

obj.id = 1;
// 'set'
console.log(obj.id);
// 'get'
// 1```
</div>
</div>
</p>

<p>I want to add the same functionality to a constructor function, but it ends up in a loop.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let myObject = function(){
    Object.defineProperty(this, 'id', {
        set: (val) => { console.log('set'); this.id = val; },
        get: () => { console.log('get'); return this.id; }
    })
}

let obj = new myObject();
obj.id = 1;
// 'set'
// 'set'
// 'set'
// ...
// error
console.log(obj.id);</code>```

How can I solve that problem without creating a pseudo-private variable called '_id'?

Btw I have the same problem when using classes.

答:
I guess i found the answer. As long as you refer to _id instead of this._id there will be no value stored in the object itself.

let myObj = function(){
    let _id
    Object.defineProperty(this, 'id', {
        get: () => {console.log('get'); return _id},
        set: (val) => {console.log('set'); _id = val}
    })
}

let obj = new myObj()

obj.id = 1
// -> 'set'

console.log(obj.id)
// -> 'get'
// -> 1

console.log(obj)
// -> {}
// the _id variable will not be part of the object!```

Title: Javascript properties end up in loops

Body:
the following code will add the property 'id' to the object 'obj'. When calling the getter and setter there will be a console.log execution.

let obj = {}

Object.defineProperty(obj, 'id', {
    set: (val) => { console.log('set'); this.id = val; },
    get: () => { console.log('get'); return this.id; }
})

obj.id = 1;
// 'set'
console.log(obj.id);
// 'get'
// 1

I want to add the same functionality to a constructor function, but it ends up in a loop.

let myObject = function(){
    Object.defineProperty(this, 'id', {
        set: (val) => { console.log('set'); this.id = val; },
        get: () => { console.log('get'); return this.id; }
    })
}

let obj = new myObject();
obj.id = 1;
// 'set'
// 'set'
// 'set'
// ...
// error
console.log(obj.id);

How can I solve that problem without creating a pseudo-private variable called '_id'?

Btw I have the same problem when using classes.


问:
change default color for RTE text in craftercms
How can we change the default color of RTE text color option "A".
Please consider attached screen shot for more details.

Screen Shot

答:
To add the text color option "A" in the toolbar of the RTE, all you have to do is add forecolor to the tag toolbarItems1 in the RTE Configuration file, that you can access from Site Config -> Configuration, then select RTE Configuration from the dropdown.

```<code><toolbarItems1>
formatselect,|,bold,italic,underline,strikethrough,|,sub,sup,charmap,|,forecolor,|,outdent,indent,blockquote,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,managedImage,link,unlink,anchor,|,edithtml,|,undo,redo
</toolbarItems1>
</code>```

Body:
To add the text color option "A" in the toolbar of the RTE, all you have to do is add forecolor to the tag toolbarItems1 in the RTE Configuration file, that you can access from Site Config -> Configuration, then select RTE Configuration from the dropdown.

<toolbarItems1>
formatselect,|,bold,italic,underline,strikethrough,|,sub,sup,charmap,|,forecolor,|,outdent,indent,blockquote,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,managedImage,link,unlink,anchor,|,edithtml,|,undo,redo
</toolbarItems1>


问:
Saving Image In UWP Then Loading In WinForms
Good morning StackOverflow,

I come to you today with a scenario that is driving me slowly insane. Im hopeful you can aid me with this, as I’m certain this must be possible but I can’t solve it myself.

My issue is that I’m working on two different applications at present. The first is a UWP application to deliver packages for an internal mail system. The idea here is that upon receipt of the package the person will sign the application using a InkCanvas signature. This should then be saved to the database as a byte array, and then reloaded in either a WinForm or WebForm app (I’m currently doing the WinForm one first) as a regular old image file. However, I’m absolutely stuck on converting between the WriteableBitmap that I get from UWP and the regular Bitmap I need to load in WinForms. Any ideas?

Here’s what I’m doing presently:

Saving the UWP image:

```<code>private byte[] SaveImage()
{
    var canvasStrokes = SignatureCanvas.InkPresenter.StrokeContainer.GetStrokes();

    if (canvasStrokes.Count > 0)
    {
        var width = (int) SignatureCanvas.ActualWidth;
        var height = (int) SignatureCanvas.ActualHeight;
        var device = CanvasDevice.GetSharedDevice();
        var renderTarget = new CanvasRenderTarget(device, width, height, 96);

        using (var drawingSession = renderTarget.CreateDrawingSession())
        {
            drawingSession.Clear(Colors.White);
            drawingSession.DrawInk(SignatureCanvas.InkPresenter.StrokeContainer.GetStrokes());
        }
        return renderTarget.GetPixelBytes();
    }
    return null;
}
</code>```

Then I save the bytes to the database, and pull them from the database in the WinForms app... so am I making some boneheaded mistake here? Am I reading the signature in the wrong format? Or do I need to do something more to convert the formats from one to the other?

I’m stumped, after trying many different results from StackOverflow pages I don’t know what I’m doing wrong.

Any help would be amazing! And sorry if I’ve done something dumb.

答:
You're actually saving raw bitmap data to your database.
I don't remember well how the Winform importer was working but I doubt it can import raw bitmap data.

You should encode your raw data to a PNG or JPEG image first and save the result. You will end with a regular old image file that should be readable from Winform.

```<code>using (IRandomAccessStream stream = /* the stream where you want to save the data */)
{
    byte[] bytes = renderTarget.GetPixelBytes();

    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
    encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                 BitmapAlphaMode.Ignore,
                                 (uint)canvas.Width, (uint)canvas.Height,
                                 96, 96, bytes);

    await encoder.FlushAsync();
}
</code>```

Body:
Good morning StackOverflow,

I come to you today with a scenario that is driving me slowly insane. Im hopeful you can aid me with this, as I’m certain this must be possible but I can’t solve it myself.

My issue is that I’m working on two different applications at present. The first is a UWP application to deliver packages for an internal mail system. The idea here is that upon receipt of the package the person will sign the application using a InkCanvas signature. This should then be saved to the database as a byte array, and then reloaded in either a WinForm or WebForm app (I’m currently doing the WinForm one first) as a regular old image file. However, I’m absolutely stuck on converting between the WriteableBitmap that I get from UWP and the regular Bitmap I need to load in WinForms. Any ideas?

Here’s what I’m doing presently:

Saving the UWP image:

private byte[] SaveImage()
{
    var canvasStrokes = SignatureCanvas.InkPresenter.StrokeContainer.GetStrokes();

    if (canvasStrokes.Count > 0)
    {
        var width = (int) SignatureCanvas.ActualWidth;
        var height = (int) SignatureCanvas.ActualHeight;
        var device = CanvasDevice.GetSharedDevice();
        var renderTarget = new CanvasRenderTarget(device, width, height, 96);

        using (var drawingSession = renderTarget.CreateDrawingSession())
        {
            drawingSession.Clear(Colors.White);
            drawingSession.DrawInk(SignatureCanvas.InkPresenter.StrokeContainer.GetStrokes());
        }
        return renderTarget.GetPixelBytes();
    }
    return null;
}

Then I save the bytes to the database, and pull them from the database in the WinForms app... so am I making some boneheaded mistake here? Am I reading the signature in the wrong format? Or do I need to do something more to convert the formats from one to the other?

I’m stumped, after trying many different results from StackOverflow pages I don’t know what I’m doing wrong.

Any help would be amazing! And sorry if I’ve done something dumb.

Body:
You're actually saving raw bitmap data to your database.
I don't remember well how the Winform importer was working but I doubt it can import raw bitmap data.

You should encode your raw data to a PNG or JPEG image first and save the result. You will end with a regular old image file that should be readable from Winform.

using (IRandomAccessStream stream = /* the stream where you want to save the data */)
{
    byte[] bytes = renderTarget.GetPixelBytes();

    var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
    encoder.SetPixelData(BitmapPixelFormat.Bgra8,
                                 BitmapAlphaMode.Ignore,
                                 (uint)canvas.Width, (uint)canvas.Height,
                                 96, 96, bytes);

    await encoder.FlushAsync();
}


问:
Unmet Peer Dependency Error

npm WARN @schematics/angular@0.0.49 requires a peer of
  @angular-devkit/schematics@0.0.34 but none is installed. You must
  install peer  dependencies yourself.

Earlier I installed angular cli by using npm install -g @angular/cli then i uninstalled and installed npm install -g @angular/cli@latest. Now many earlier packages are not compatible, so I again uninstalled and installed angular cli using command npm install -g @angular/cli@1.4.0. Now when i was trying to download various packages, I am unable to. I tried downloading bootstrap using npm install bootstrap --save, the below warning occurs:

npm WARN @schematics/angular@0.0.49 requires a peer of @angular-devkit/schematics@0.0.34 but none is installed. You must
  install peer  dependencies yourself.

Please help me how I can start fresh and have all packages intact.

答:
I just had this issue, you'll need to install it via NPM.  Not sure why it doesn't get automatically installed.

npm install @angular-devkit/schematics@0.0.34 --save

Title: Unmet Peer Dependency Error


问:
Inspect Parquet from command line
How do I inspect the content of a Parquet file from the command line?

The only option I see now is

```<code>$ hadoop fs -get my-path local-file
$ parquet-tools head local-file | less
</code>```

I would like to

avoid creating the local-file and

view the file content as json rather than the typeless text that parquet-tools prints.

Is there an easy way?

答:
You can use parquet-tools with the command cat and the --json option in order to view the files without a local copy and in the JSON format.

Here is an example:

parquet-tools cat --json  hdfs://localhost/tmp/save/part-r-00000-6a3ccfae-5eb9-4a88-8ce8-b11b2644d5de.gz.parquet

This prints out the data in JSON format:

```<code>{"name":"gil","age":48,"city":"london"}
{"name":"jane","age":30,"city":"new york"}
{"name":"jordan","age":18,"city":"toronto"}
</code>```

Disclaimer: this was tested in Cloudera CDH 5.12.0

Title: Inspect Parquet from command line

Body:
How do I inspect the content of a Parquet file from the command line?

The only option I see now is

$ hadoop fs -get my-path local-file
$ parquet-tools head local-file | less

I would like to

avoid creating the local-file and

view the file content as json rather than the typeless text that parquet-tools prints.

Is there an easy way?

Body:
You can use parquet-tools with the command cat and the --json option in order to view the files without a local copy and in the JSON format.

Here is an example:

parquet-tools cat --json  hdfs://localhost/tmp/save/part-r-00000-6a3ccfae-5eb9-4a88-8ce8-b11b2644d5de.gz.parquet

This prints out the data in JSON format:

{"name":"gil","age":48,"city":"london"}
{"name":"jane","age":30,"city":"new york"}
{"name":"jordan","age":18,"city":"toronto"}

Disclaimer: this was tested in Cloudera CDH 5.12.0


问:
Compression not available on SQL Server Standard? Options?
So as they say, everyday is a school day. Today I learned that my workplace, runs SQL Server Standard edition, where I would have assumed Enterprise was in place. Although in reality shouldn't be surprised!

For some context, we have a very large database that houses our warehouse data. As the database has grown to a large size, it's causing issues with space on the server along with some application performance. So looking at it from my perspective I suggested we archive and purge the PROD database, to house only 18 months data in the PROD environment.

Wrote my scripts and tested them and all fine. I then went to compress the tables I had deleted data from, to find error messages that compression is not available in SQL Server Standard and requires Enterprise edition.

Wondering what my next steps are here? My assumption is that even though I am deleting a lot of data, we won't actually benefit in terms of performance, and space requisition until the tables get compressed.

Shrinking is something I guess I've always shy'd away from, many articles or posts here would advise not to use it.

Wondering, what sort of options do I have here?

Is my assumption correct, in that without compressing, we won't regain space from the trimmed database?

答: Moving this to resolved as opening query in specific DBA portion of the site</p>